#!/usr/bin/env python3 """Manifold — a minimal polyphonic peer-to-peer wiki. Core module (no HTTP here): content-addressed object store, signed commit DAG with coexisting heads per article, pure-python ed25519, sandboxed code runner, peer sync client over multiple network layers, CLI. The HTTP layer (human UI + agent API) lives in manifold_http.py: python3 manifold.py serve """ import argparse import base64 import hashlib import hmac import json import math import os import re import secrets import shutil import signal import sqlite3 import subprocess import sys import tempfile import threading import time import urllib.error import urllib.parse import urllib.request from collections import deque from typing import NamedTuple, Optional __version__ = "0.6.0" PROTOCOL = 1 SOFTWARE = "manifold" USER_AGENT = "Manifold/%s (+p2p wiki node)" % __version__ ARTICLE_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$") ID_RE = re.compile(r"^[0-9a-f]{64}$") # sha256 id / public key SIG_RE = re.compile(r"^[0-9a-f]{128}$") # Ed25519 signature (2 * 64 hex) FP_RE = re.compile(r"^[0-9a-f]{16}([0-9a-f]{48})?$") # fingerprint or pub key REQID_RE = re.compile(r"^[A-Za-z0-9._~-]{1,128}$") TEXT_LIMIT = 64 << 10 # 64 KiB per text object: every commit stores a # full text, and polyphony multiplies it — pages # grow slowly by policy CODE_LIMIT = 64 << 10 # code source cap OBJECT_LIMIT = 256 << 10 # hard cap for any object body NOTE_LIMIT = 1024 # GET /n quick-note branch cap MAX_LINE = 8192 # request-line budget for /n (nginx's default # window is the real ceiling on deployed doors) FETCH_LIMIT = 64 << 20 # max bytes read from one peer response MAX_PARENTS = 16 LANGS = ("python3",) RUN_TIMEOUT = 15.0 RUN_OUTPUT_CAP = 65536 # -- software releases (roadmap #1: manifest + hash-named chunk blobs) ----- RELEASE_CHUNK = 48 << 10 # chunk blob size: safely under TEXT_LIMIT, so # every chunk is an ordinary text object and no # file needs a new object kind or bigger caps RELEASE_SHIP_FILES = ("manifold.py", "manifold_http.py", "README.md", "AGENTS.md", "llms.txt", "LICENSE") RELEASE_PATH_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") RELEASE_VER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.+~-]{0,31}$") RELEASE_FILES_MAX = 64 RELEASE_CHUNKS_MAX = 1024 # per manifest: 48 KiB * 1024 = 48 MiB ceiling RELEASE_FILE_MAX = 64 << 20 ESSENTIAL_FILES = ("manifold.py", "manifold_http.py") # an update must ship these # -- open network (v0.4): signed gossip batches, node discovery ----------- GOSSIP_BATCH_OBJECTS = 64 # objects per push batch ... GOSSIP_BATCH_BYTES = 2 << 20 # ... and the raw-bytes ceiling for one batch GOSSIP_BACKOFF_MIN = 30.0 # a peer that refused/failed a push is retried GOSSIP_BACKOFF_MAX = 600.0 # after a doubling delay capped here KNOWN_NODES_MAX = 256 # learned nodes kept (and at most this many # are republished in the manifest) INBOX_MODES = ("token", "open", "f2f") # -- accounts (v0.5): flatboard-style name + pass on top of key identities -- ACCOUNT_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{1,31}$") ACCOUNT_ROLES = ("user", "admin") FRONTPAGE = "frontpage" # reserved article rendered as / # ----------------------------------------------------------------- ed25519 -- # Pure-python RFC 8032 implementation. Correct and dependency-free, but slow # (~0.5-2 s per scalar multiplication group). If the `cryptography` package # is importable it is used transparently instead; the pure path always exists. try: from cryptography.hazmat.primitives.asymmetric.ed25519 import ( Ed25519PrivateKey, Ed25519PublicKey) from cryptography.hazmat.primitives.serialization import ( Encoding, PublicFormat) _HAVE_CRYPTO = True except Exception: _HAVE_CRYPTO = False _P = 2 ** 255 - 19 # Group order of the base point (RFC 8032), pinned via its canonical hex form. _L = 2 ** 252 + int("14def9dea2f79cd65812631a5cf5d3ed", 16) _D = (-121665 * pow(121666, _P - 2, _P)) % _P _I = pow(2, (_P - 1) // 4, _P) # square root of -1 mod p _IDENTITY = (0, 1, 1, 0) # neutral element, extended coords def _clamp(h32: bytes) -> bytes: b = bytearray(h32) b[0] &= 248 b[31] &= 127 b[31] |= 64 return bytes(b) def _recover_x(y: int, sign: int) -> Optional[int]: if y >= _P: return None xx = (y * y - 1) * pow(y * y * _D + 1, _P - 2, _P) % _P if xx == 0: return None if sign else 0 x = pow(xx, (_P + 3) // 8, _P) if (x * x - xx) % _P != 0: x = x * _I % _P if (x * x - xx) % _P != 0: return None if (x & 1) != sign: x = _P - x return x _BY = (4 * pow(5, _P - 2, _P)) % _P _BX = _recover_x(_BY, 0) _B = (_BX, _BY, 1, _BX * _BY % _P) # base point, extended coords def _add(p, q): X1, Y1, Z1, T1 = p X2, Y2, Z2, T2 = q A = (Y1 - X1) * (Y2 - X2) % _P B = (Y1 + X1) * (Y2 + X2) % _P C = 2 * T1 * T2 * _D % _P D = 2 * Z1 * Z2 % _P E, F, G, H = B - A, D - C, D + C, B + A return (E * F % _P, G * H % _P, F * G % _P, E * H % _P) def _mul(n: int, p): r = _IDENTITY while n > 0: if n & 1: r = _add(r, p) p = _add(p, p) n >>= 1 return r _B_TABLE = None def _base_table(): """Lazy 4-bit comb table for the fixed base point (64 nibble columns x 15 multiples). One-time cost ~ one scalar mult; signing then needs only ~64 point additions.""" global _B_TABLE if _B_TABLE is None: table = [] p = _B for _ in range(64): col = [] acc = _IDENTITY for _ in range(15): acc = _add(acc, p) col.append(acc) table.append(col) for _ in range(4): p = _add(p, p) _B_TABLE = table return _B_TABLE def _mul_base(n: int): table = _base_table() r = _IDENTITY j = 0 while n > 0: nib = n & 15 if nib: r = _add(r, table[j][nib - 1]) n >>= 4 j += 1 return r def _neg(p): X, Y, Z, T = p return ((_P - X) % _P, Y, Z, (_P - T) % _P) def _mul2(k: int, A, s: int, B): """Combined double-and-add: k*A + s*B (saves the extra 255 doublings a pair of independent scalar multiplications would need).""" r = _IDENTITY for i in range(255, -1, -1): r = _add(r, r) if (k >> i) & 1: r = _add(r, A) if (s >> i) & 1: r = _add(r, B) return r def _compress(p) -> bytes: X, Y, Z, _ = p zinv = pow(Z, _P - 2, _P) x = X * zinv % _P y = Y * zinv % _P return int.to_bytes(y | ((x & 1) << 255), 32, "little") def _decompress(b: bytes): if len(b) != 32: return None y = int.from_bytes(b, "little") sign = y >> 255 y &= (1 << 255) - 1 x = _recover_x(y, sign) if x is None: return None return (x, y, 1, x * y % _P) def sign_pure(seed: bytes, msg: bytes) -> bytes: h = hashlib.sha512(seed).digest() a = int.from_bytes(_clamp(h[:32]), "little") prefix = h[32:] pub = _compress(_mul_base(a)) r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % _L R = _compress(_mul_base(r)) k = int.from_bytes(hashlib.sha512(R + pub + msg).digest(), "little") % _L s = (r + k * a) % _L return R + s.to_bytes(32, "little") def verify_pure(pub: bytes, msg: bytes, sig: bytes) -> bool: if len(sig) != 64: return False A = _decompress(pub) R = _decompress(sig[:32]) if A is None or R is None: return False s = int.from_bytes(sig[32:], "little") if s >= _L: return False k = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(), "little") % _L # s*B == R + k*A <=> s*B + k*(-A) == R (projective-normalized compare) left = _mul2(s, _B, k, _neg(A)) return _compress(left) == _compress(R) def pub_from_seed(seed: bytes) -> bytes: if _HAVE_CRYPTO: return (Ed25519PrivateKey.from_private_bytes(seed).public_key() .public_bytes(Encoding.Raw, PublicFormat.Raw)) h = hashlib.sha512(seed).digest() return _compress(_mul_base(int.from_bytes(_clamp(h[:32]), "little"))) def sign_bytes(seed: bytes, msg: bytes) -> bytes: if _HAVE_CRYPTO: return Ed25519PrivateKey.from_private_bytes(seed).sign(msg) return sign_pure(seed, msg) def verify_bytes(pub: bytes, msg: bytes, sig: bytes) -> bool: if _HAVE_CRYPTO: try: Ed25519PublicKey.from_public_bytes(pub).verify(sig, msg) return True except Exception: return False return verify_pure(pub, msg, sig) # ------------------------------------------------------- canonical objects -- def canon(obj) -> bytes: return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") def obj_id(body: bytes) -> str: return hashlib.sha256(body).hexdigest() # ------------------------------------------------------------------- keys -- class Key(NamedTuple): seed: bytes pub: bytes fp: str # short fingerprint (first 16 hex of the public key) name: str @property def pub_hex(self) -> str: return self.pub.hex() def keygen(root: str, name: str = "") -> Key: seed = os.urandom(32) pub = pub_from_seed(seed) key = Key(seed, pub, pub.hex()[:16], name or "anonymous") kdir = os.path.join(root, "data", "keys") os.makedirs(kdir, exist_ok=True) path = os.path.join(kdir, key.fp + ".json") if os.path.exists(path): raise SystemExit("key %s already exists" % key.fp) with open(path, "w", encoding="utf-8") as f: json.dump({"seed": seed.hex(), "pub": pub.hex(), "name": key.name, "created": int(time.time())}, f, indent=1) os.chmod(path, 0o600) return key def load_keys(root: str): kdir = os.path.join(root, "data", "keys") keys = [] if os.path.isdir(kdir): for fn in sorted(os.listdir(kdir)): if not fn.endswith(".json"): continue try: with open(os.path.join(kdir, fn), encoding="utf-8") as f: d = json.load(f) pub = bytes.fromhex(d["pub"]) keys.append(Key(bytes.fromhex(d["seed"]), pub, pub.hex()[:16], d.get("name", "anonymous"))) except Exception: continue return keys def default_key(root: str, cfg) -> Optional[Key]: keys = load_keys(root) if not keys: return None want = (cfg or {}).get("default_key", "") for k in keys: if k.fp == want or k.pub_hex == want: return k return keys[-1] # ------------------------------------------------------------------ config -- DEFAULT_CONFIG = { "name": "manifold node", "bind": "127.0.0.1", "port": 8830, "write_token": "", "default_key": "", # Honor X-Forwarded-For for rate-limit keys (set ONLY behind a trusted # reverse proxy; otherwise the header is trivially spoofable). "trust_proxy": False, # Let requests from loopback to a loopback-bound node write and manage # WITHOUT signing in ("the operator is on the box"). Off by default: # local users have accounts like everyone else, and the write token # still works for scripts. "local_shortcut": False, # Announced addresses, one per network layer the node is reachable on: "endpoints": [], # [{"layer": "tor", "url": "http://...onion:8830/"}] # Who may push objects into this node (v0.4). "token": write token only; # "open": anyone (signatures, author policy and rate limits still apply); # "f2f": pushes signed by a key in inbox.friends (fingerprints, pub[:16]). "inbox": {"mode": "token", "friends": []}, # Publish learned node addresses in /api/manifest (discovery). Turn off # to keep your peer map private. "announce_peers": True, # Auto-peer with learned nodes (open mode only; f2f never auto-peers). # Null = the mode default: 8 in open mode, 0 otherwise. "peers": {"max_auto": None}, # Background network loop of `serve`: push newly held objects to peers # every N seconds, pull from all peers every M seconds (0 = pull only on # demand / from the UI). "gossip": {"interval": 10}, "sync": {"interval": 300}, "network": {"tor_socks": "127.0.0.1:9050", "i2p_http": "127.0.0.1:4444"}, # Commits from authors outside `allow` (if non-empty) or inside `deny` # are refused at accept time. Fingerprints are pub[:16] hex. "author_policy": {"allow": [], "deny": []}, # Node-local karma (never synced). Default: computed and DISPLAYED only. # Set karma.throttle_below to an integer (0-99) and push batches carrying # commits from authors below that score cost extra rate-limiter events. "karma": {"throttle_below": None}, # Software updates: release manifests signed by one of these key # fingerprints (pub[:16]) may be applied by `update`. Empty = only this # node's own default key (self-cut releases bootstrap the trust chain). "update": {"allow_keys": []}, } def config_path(root: str) -> str: return os.path.join(root, "config.json") def load_config(root: str) -> dict: cfg = json.loads(json.dumps(DEFAULT_CONFIG)) # deep copy of defaults try: with open(config_path(root), encoding="utf-8") as f: user = json.load(f) except Exception: user = {} for k, v in user.items(): if isinstance(v, dict) and isinstance(cfg.get(k), dict): cfg[k].update(v) else: cfg[k] = v return cfg def save_config(root: str, cfg: dict) -> None: with open(config_path(root), "w", encoding="utf-8") as f: json.dump(cfg, f, indent=2, ensure_ascii=False) f.write("\n") # ------------------------------------------------------------------- store -- _SCHEMA = """ CREATE TABLE IF NOT EXISTS meta( key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS objects( id TEXT PRIMARY KEY, type TEXT NOT NULL, body BLOB NOT NULL, size INTEGER NOT NULL, first_seen TEXT NOT NULL, origin TEXT NOT NULL); CREATE TABLE IF NOT EXISTS commits( id TEXT PRIMARY KEY, article TEXT NOT NULL, author TEXT NOT NULL, ts INTEGER NOT NULL, comment TEXT NOT NULL, content TEXT NOT NULL, origin TEXT NOT NULL); CREATE INDEX IF NOT EXISTS commits_article ON commits(article, ts); CREATE TABLE IF NOT EXISTS commit_parents( commit_id TEXT NOT NULL, idx INTEGER NOT NULL, parent_id TEXT NOT NULL, PRIMARY KEY(commit_id, idx)); CREATE INDEX IF NOT EXISTS cp_parent ON commit_parents(parent_id); CREATE TABLE IF NOT EXISTS peers( url TEXT PRIMARY KEY, layer TEXT NOT NULL, added TEXT NOT NULL, last_sync TEXT, last_ok INTEGER, last_status TEXT); CREATE TABLE IF NOT EXISTS aliases( fingerprint TEXT PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE IF NOT EXISTS idem( article TEXT NOT NULL, request_id TEXT NOT NULL, commit_id TEXT NOT NULL, digest TEXT NOT NULL, created TEXT NOT NULL, PRIMARY KEY(article, request_id)); CREATE TABLE IF NOT EXISTS peer_has( peer_url TEXT NOT NULL, object_id TEXT NOT NULL, PRIMARY KEY(peer_url, object_id)); CREATE TABLE IF NOT EXISTS known_nodes( instance_id TEXT PRIMARY KEY, name TEXT NOT NULL, endpoints TEXT NOT NULL, first_seen TEXT NOT NULL, last_seen TEXT NOT NULL, source TEXT NOT NULL); """ # Columns added after a table first shipped: (table, column, DDL). Applied at # open so live databases migrate in place. _MIGRATIONS = ( ("peers", "cursor", "INTEGER"), ("peers", "pushed", "INTEGER"), # sent-cursor: rowid of the last # object this peer was given ("peers", "push_status", "TEXT"), ("peers", "token", "TEXT"), # peer's write token, for gossip to # token-mode peers (never published) ("peers", "auto", "INTEGER"), # 1 = added by discovery, not by hand ) class Store: """Content-addressed object store + commit DAG for one node.""" def __init__(self, root: str, cfg: Optional[dict] = None): self.root = os.path.abspath(root) data = os.path.join(self.root, "data") os.makedirs(os.path.join(data, "keys"), exist_ok=True) self.cfg = cfg if cfg is not None else load_config(self.root) self.db = sqlite3.connect(os.path.join(data, "manifold.db"), check_same_thread=False) self.db.row_factory = sqlite3.Row self.db.execute("PRAGMA journal_mode=WAL") self.db.executescript(_SCHEMA) self.db.commit() self._lock = threading.Lock() for table, col, ddl in _MIGRATIONS: cols = {r[1] for r in self.db.execute("PRAGMA table_info(%s)" % table)} if col not in cols: self.db.execute("ALTER TABLE %s ADD COLUMN %s %s" % (table, col, ddl)) self.db.commit() if self.get_meta("instance_id") is None: self.set_meta("instance_id", os.urandom(16).hex()) if self.get_meta("created") is None: self.set_meta("created", str(int(time.time()))) # -- meta ------------------------------------------------------------ def get_meta(self, key, default=None): row = self.db.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone() return row[0] if row else default def set_meta(self, key, value): with self._lock: self.db.execute( "INSERT INTO meta(key,value) VALUES(?,?) " "ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value)) self.db.commit() @property def instance_id(self) -> str: return self.get_meta("instance_id", "?") # -- objects --------------------------------------------------------- def has(self, oid: str) -> bool: return self.db.execute("SELECT 1 FROM objects WHERE id=?", (oid,)).fetchone() is not None def object(self, oid: str): return self.db.execute("SELECT * FROM objects WHERE id=?", (oid,)).fetchone() def object_body(self, oid: str) -> Optional[bytes]: row = self.object(oid) return bytes(row["body"]) if row else None def objects_by_ids(self, ids): out = [] for oid in ids: row = self.object(oid) if row: out.append(row) return out def all_ids(self, since=None): """Object listing ordered by insertion — rowid doubles as the sync cursor (objects are immutable and never deleted). With since=, only rows after that seq.""" if since is None: return self.db.execute( "SELECT id, type, size, rowid AS seq FROM objects ORDER BY rowid" ).fetchall() return self.db.execute( "SELECT id, type, size, rowid AS seq FROM objects WHERE rowid > ? " "ORDER BY rowid", (since,)).fetchall() def count_objects(self) -> int: return self.db.execute("SELECT COUNT(*) FROM objects").fetchone()[0] def put_object(self, body: bytes, kind: str, origin: str = "local") -> str: """Insert WITHOUT locking — the accept pipeline runs entirely under self._lock so verification and storage stay atomic.""" oid = obj_id(body) self.db.execute( "INSERT OR IGNORE INTO objects(id,type,body,size,first_seen,origin) " "VALUES(?,?,?,?,?,?)", (oid, kind, body, len(body), time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), origin)) self.db.commit() return oid # -- accept pipeline (used by local creation, push and pull alike) ---- def accept_object(self, body: bytes, origin: str = "local") -> dict: with self._lock: return self._accept_object_locked(body, origin) def _accept_object_locked(self, body: bytes, origin: str = "local") -> dict: """Verify and store one object. Signature and id checks are mandatory; unknown parents/content are allowed (partial DAGs are expected). Caller must hold self._lock.""" res = {"ok": False, "id": None, "type": "text", "reason": "", "duplicate": False} if not body: res["reason"] = "empty object" return res if len(body) > OBJECT_LIMIT: res["reason"] = "object exceeds %d bytes" % OBJECT_LIMIT return res oid = obj_id(body) res["id"] = oid if self.has(oid): stored = self.object(oid) res.update(ok=True, duplicate=True, type=stored["type"]) return res kind = "text" parsed = None try: parsed = json.loads(body.decode("utf-8")) if isinstance(parsed, dict) and parsed.get("t") in ("commit", "code", "release"): kind = parsed["t"] except Exception: parsed = None res["type"] = kind if kind == "commit": err = self._check_commit(parsed) if err: res["reason"] = err return res elif kind == "code": err = self._check_code(parsed) if err: res["reason"] = err return res elif kind == "release": if len(body) > CODE_LIMIT: res["reason"] = "release manifest exceeds %d bytes" % CODE_LIMIT return res err = self._check_release(parsed) if err: res["reason"] = err return res elif len(body) > TEXT_LIMIT: res["reason"] = "text exceeds %d bytes" % TEXT_LIMIT return res self.put_object(body, kind, origin) if kind == "commit": self.db.execute( "INSERT OR IGNORE INTO commits(id,article,author,ts,comment,content,origin) " "VALUES(?,?,?,?,?,?,?)", (oid, parsed["article"], parsed["author"], parsed["ts"], parsed.get("comment", ""), parsed["content"], origin)) for i, pid in enumerate(parsed["parents"]): self.db.execute( "INSERT OR IGNORE INTO commit_parents(commit_id,idx,parent_id) " "VALUES(?,?,?)", (oid, i, pid)) self.db.commit() res["ok"] = True return res def _check_commit(self, o: dict) -> str: """Return "" when the commit is acceptable, else the reason.""" if o.get("v") != 1: return "unsupported commit version" article = o.get("article") if not isinstance(article, str) or not ARTICLE_RE.match(article): return "bad article name" parents = o.get("parents") if not isinstance(parents, list) or len(parents) > MAX_PARENTS: return "bad parents list" if len(set(parents)) != len(parents): return "duplicate parents" for p in parents: if not isinstance(p, str) or not ID_RE.match(p): return "bad parent id" # Parents must belong to the same article. Unknown parents are fine # (partial DAGs are expected); a parent we DO hold in another article # means the commit is malformed or hostile — reject it. for p in parents: prow = self.commit(p) if prow is not None and prow["article"] != article: return "parent %s belongs to article %s" % (p[:12], prow["article"]) for field in ("content", "author"): v = o.get(field) if not isinstance(v, str) or not ID_RE.match(v): return "bad %s id" % field ts = o.get("ts") if not isinstance(ts, int) or ts < 946684800 or ts > time.time() + 86400: return "bad timestamp" comment = o.get("comment", "") if not isinstance(comment, str) or len(comment) > 300: return "bad comment" return self._signed_author_ok(o) def _signed_author_ok(self, o: dict) -> str: """Shared tail of every self-signed object check (commit, release): signature encoding, author policy, and the signature itself over the canonical body with `sig` blanked. "" when acceptable.""" sig = o.get("sig") if not isinstance(sig, str) or not SIG_RE.match(sig): return "bad signature encoding" fp = o["author"][:16] policy = self.cfg.get("author_policy", {}) or {} if policy.get("deny") and fp in policy["deny"]: return "author is denied by local policy" if policy.get("allow") and fp not in policy["allow"]: return "author is not in the local allow list" unsigned = dict(o) unsigned["sig"] = "" if not verify_bytes(bytes.fromhex(o["author"]), canon(unsigned), bytes.fromhex(sig)): return "bad signature" return "" def _check_code(self, o: dict) -> str: if o.get("v") != 1: return "unsupported code version" if o.get("lang") not in LANGS: return "unsupported language (allowed: %s)" % ", ".join(LANGS) entry = o.get("entry", "main") if not isinstance(entry, str) or len(entry) > 64 or not re.match(r"^[A-Za-z_][A-Za-z0-9_.-]{0,63}$", entry): return "bad entry name" src = o.get("source") if not isinstance(src, str) or len(src.encode("utf-8")) > CODE_LIMIT: return "code source too large" return "" def _check_release(self, o: dict) -> str: """Release manifests follow the commit pattern: self-signed canonical JSON. Storage is open to any correctly-signed release (a manifest is just data); TRUST is applied later, by `update`, against the pinned key list — accept-time checks are validity only, like commits.""" if o.get("v") != 1: return "unsupported release version" name = o.get("name") if not isinstance(name, str) or not ARTICLE_RE.match(name): return "bad release name" ver = o.get("version") if not isinstance(ver, str) or not RELEASE_VER_RE.match(ver): return "bad version string" created = o.get("created") if not isinstance(created, int) or created < 946684800 \ or created > time.time() + 86400: return "bad created timestamp" notes = o.get("notes", "") if not isinstance(notes, str) or len(notes) > 500: return "bad notes" files = o.get("files") if not isinstance(files, list) or not 1 <= len(files) <= RELEASE_FILES_MAX: return "bad files list" seen = set() total_chunks = 0 for f in files: if not isinstance(f, dict): return "bad file entry" path = f.get("path") if not isinstance(path, str) or not RELEASE_PATH_RE.match(path): return "bad file path" if path in seen: return "duplicate file path" seen.add(path) size = f.get("size") if not isinstance(size, int) or not 0 < size <= RELEASE_FILE_MAX: return "bad file size" if not isinstance(f.get("sha256"), str) or not ID_RE.match(f["sha256"]): return "bad file hash" chunks = f.get("chunks") if not isinstance(chunks, list) or not 1 <= len(chunks) <= 256: return "bad chunk list" for c in chunks: if not isinstance(c, str) or not ID_RE.match(c): return "bad chunk id" total_chunks += len(chunks) if total_chunks > RELEASE_CHUNKS_MAX: return "too many chunks" for field in ("author",): v = o.get(field) if not isinstance(v, str) or not ID_RE.match(v): return "bad %s id" % field return self._signed_author_ok(o) # -- releases ------------------------------------------------------------ def list_releases(self, name=None): """[(id, manifest)] for every release object held — all versions coexist in the store; nothing supersedes anything.""" out = [] for row in self.db.execute( "SELECT id, body FROM objects WHERE type='release' ORDER BY rowid"): try: o = json.loads(bytes(row["body"]).decode("utf-8")) except Exception: continue if name and o.get("name") != name: continue out.append((row["id"], o)) return out # -- commits / DAG ----------------------------------------------------- def commit(self, cid: str): return self.db.execute("SELECT * FROM commits WHERE id=?", (cid,)).fetchone() def parents_of(self, cid: str): return [r[0] for r in self.db.execute( "SELECT parent_id FROM commit_parents WHERE commit_id=? ORDER BY idx", (cid,)).fetchall()] def children_of(self, cid: str): return [r[0] for r in self.db.execute( "SELECT commit_id FROM commit_parents WHERE parent_id=?", (cid,)).fetchall()] def commits_for(self, article: str): return self.db.execute( "SELECT * FROM commits WHERE article=? ORDER BY ts, id", (article,)).fetchall() def heads(self, article: str): """Heads = stored commits of this article with no stored CHILD IN THE SAME ARTICLE: the coexisting points of view. A child in a different article (reachable only via partial DAGs) must never demote a head here — otherwise a hostile peer could hide another article's branch by parenting it cross-article. Emerges from the DAG; nothing is announced.""" return self.db.execute( "SELECT c.* FROM commits c WHERE c.article=? " "AND NOT EXISTS (SELECT 1 FROM commit_parents p JOIN commits k " "ON k.id=p.commit_id WHERE p.parent_id=c.id AND k.article=c.article) " "ORDER BY c.ts DESC, c.id", (article,)).fetchall() def resolve_head(self, article: str, q: str): """Accept a full id or a unique prefix among the article's heads.""" q = (q or "").strip().lower() if not q: return None if ID_RE.match(q): row = self.commit(q) if row and row["article"] == article: return q return None matches = [h["id"] for h in self.heads(article) if h["id"].startswith(q)] return matches[0] if len(matches) == 1 else None def missing_ancestors(self, cid: str, limit: int = 2048): """Walk the parent chain; count referenced commits we do not hold. Returns (known_ids, missing_count).""" seen = set() missing = 0 stack = [cid] while stack and len(seen) < limit: x = stack.pop() if x in seen: continue seen.add(x) row = self.commit(x) if row is None: missing += 1 continue stack.extend(self.parents_of(x)) return seen, missing def tree(self, article: str) -> dict: """Whole article DAG as {nodes, edges} for humans and agents.""" rows = self.commits_for(article) head_ids = {h["id"] for h in self.heads(article)} nodes = [] edges = [] for r in rows: parents = self.parents_of(r["id"]) nodes.append({"id": r["id"], "ts": r["ts"], "author": r["author"], "comment": r["comment"], "content": r["content"], "origin": r["origin"], "head": r["id"] in head_ids, "parents": parents}) edges.extend([[r["id"], p] for p in parents]) known = {r["id"] for r in rows} missing = sorted({p for n in nodes for p in n["parents"]} - known) return {"article": article, "nodes": nodes, "edges": edges, "missing_ancestors": missing} def articles(self): return self.db.execute( "SELECT article, COUNT(*) AS commits, MAX(ts) AS updated, " "COUNT(DISTINCT author) AS authors FROM commits GROUP BY article " "ORDER BY updated DESC").fetchall() def article_head_counts(self): out = {} for a in self.articles(): out[a["article"]] = len(self.heads(a["article"])) return out def recent_commits(self, n=10): return self.db.execute( "SELECT * FROM commits ORDER BY ts DESC, id LIMIT ?", (n,)).fetchall() def stats(self) -> dict: c = self.db.execute return { "objects": c("SELECT COUNT(*) FROM objects").fetchone()[0], "commits": c("SELECT COUNT(*) FROM commits").fetchone()[0], "articles": c("SELECT COUNT(DISTINCT article) FROM commits").fetchone()[0], "peers": c("SELECT COUNT(*) FROM peers").fetchone()[0], } def content_body(self, cid: str): """Return (kind, bytes-or-None) for a commit's content object.""" body = self.object_body(cid) if body is None: return "missing", None try: o = json.loads(body.decode("utf-8")) if isinstance(o, dict) and o.get("t") == "code": return "code", body except Exception: pass return "text", body # -- authors ----------------------------------------------------------- def alias(self, fp: str, default=""): row = self.db.execute("SELECT name FROM aliases WHERE fingerprint=?", (fp,)).fetchone() return row[0] if row else default def set_alias(self, fp: str, name: str): with self._lock: self.db.execute( "INSERT INTO aliases(fingerprint,name) VALUES(?,?) " "ON CONFLICT(fingerprint) DO UPDATE SET name=excluded.name", (fp, name)) self.db.commit() def clear_alias(self, fp: str): with self._lock: self.db.execute("DELETE FROM aliases WHERE fingerprint=?", (fp,)) self.db.commit() def all_aliases(self): return self.db.execute( "SELECT fingerprint, name FROM aliases ORDER BY name").fetchall() def author_display(self, pub_hex: str) -> str: fp = pub_hex[:16] return self.alias(fp) or fp # -- search -------------------------------------------------------------- def search(self, q: str, limit: int = 50): """Substring search over held content objects + article names. Matching uses instr() with bound parameters — no LIKE pattern, so a query of '%' or '_' is a literal, not a wildcard. lower() folds ASCII only (honest v1 behavior; non-ASCII search stays case-sensitive).""" q = (q or "").strip() if not q: return [] ql = q.lower() out = {} for r in self.db.execute( "SELECT c.article, c.id, c.author, c.ts, c.comment, " "c.content, o.type FROM commits c " "JOIN objects o ON o.id = c.content " "WHERE o.type IN ('text','code') " "AND instr(lower(CAST(o.body AS TEXT)), ?) > 0 " "ORDER BY c.ts DESC LIMIT ?", (ql, limit)): out[r["id"]] = dict(r) for r in self.db.execute( "SELECT article, id, author, ts, comment, content, NULL AS type " "FROM commits WHERE instr(lower(article), ?) > 0 " "ORDER BY ts DESC LIMIT ?", (ql, limit)): out.setdefault(r["id"], dict(r)) hits = sorted(out.values(), key=lambda r: -r["ts"])[:limit] return hits # -- node-local karma (committed decision 4: visible, never synced) ------ def author_stats(self): """One row per author this node has seen, with every observable the karma score is built from — all local, nothing fetched or synced.""" rows = self.db.execute( "SELECT author, COUNT(*) AS commits, " "COUNT(DISTINCT article) AS articles, MIN(ts) AS first_ts, " "MAX(ts) AS last_ts, " "SUM(CASE WHEN origin IN ('local','api') THEN 1 ELSE 0 END) " "AS local_commits FROM commits GROUP BY author").fetchall() merges = {r[0]: r[1] for r in self.db.execute( "SELECT c.author, COUNT(*) FROM commits c WHERE c.id IN " "(SELECT commit_id FROM commit_parents GROUP BY commit_id " " HAVING COUNT(*) > 1) GROUP BY c.author").fetchall()} built_on = {r[0]: r[1] for r in self.db.execute( "SELECT p.author, COUNT(*) FROM commit_parents cp " "JOIN commits c ON c.id = cp.commit_id " "JOIN commits p ON p.id = cp.parent_id " "WHERE c.author != p.author GROUP BY p.author").fetchall()} out = [] for r in rows: d = dict(r) d["merges"] = merges.get(d["author"], 0) d["built_on"] = built_on.get(d["author"], 0) out.append(d) return out @staticmethod def karma_score(s: dict) -> dict: """Deterministic v1 score (0-100) from locally held observables. breadth: how many distinct articles the author touched (cap 30); volume: commits held (cap 20); trust: commits by OTHER authors that build on this author's work — the local stand-in for head survival (a head that others branch from is a head that survived) (cap 20); synthesis: two-parent commits authored (cap 15); tenure: days since the first commit this node holds (cap 10); locality: commits that arrived through this node's own token-gated door (cap 5).""" b = { "breadth": min(30, 6 * s.get("articles", 0)), "volume": min(20, s.get("commits", 0)), "trust": min(20, 4 * s.get("built_on", 0)), "synthesis": min(15, 5 * s.get("merges", 0)), "tenure": min(10, max(0, (s.get("last_ts", 0) - s.get("first_ts", 0)) // 86400)), "locality": min(5, s.get("local_commits", 0)), } b["score"] = sum(b.values()) return b def author_karma(self, fp: str): """Karma report for one fingerprint (16-hex or full pub key).""" fp = fp[:16] for s in self.author_stats(): if s["author"][:16] == fp: return {"fingerprint": fp, "alias": self.alias(fp, ""), **s, "karma": self.karma_score(s)} return {"fingerprint": fp, "alias": self.alias(fp, ""), "author": fp, "commits": 0, "articles": 0, "first_ts": None, "last_ts": None, "local_commits": 0, "merges": 0, "built_on": 0, "karma": self.karma_score({})} def authors(self): """Author table with karma, newest activity first.""" out = [] for s in self.author_stats(): out.append({"fingerprint": s["author"][:16], "alias": self.alias(s["author"][:16], ""), **s, "karma": self.karma_score(s)}) out.sort(key=lambda a: -(a.get("last_ts") or 0)) return out # -- peers ------------------------------------------------------------- def add_peer(self, url: str, layer: str = None, token: str = "", auto: bool = False): url = url.rstrip("/") layer = layer or detect_layer(url) with self._lock: self.db.execute( "INSERT OR IGNORE INTO peers(url,layer,added,pushed,token,auto) " "VALUES(?,?,?,?,?,?)", (url, layer, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), 0, token or "", 1 if auto else 0)) if token: self.db.execute("UPDATE peers SET token=? WHERE url=?", (token, url)) self.db.commit() def remove_peer(self, url: str) -> bool: with self._lock: cur = self.db.execute("DELETE FROM peers WHERE url=?", (url.rstrip("/"),)) self.db.commit() return cur.rowcount > 0 def list_peers(self): return self.db.execute("SELECT * FROM peers ORDER BY added").fetchall() def get_peer(self, url: str): return self.db.execute("SELECT * FROM peers WHERE url=?", (url.rstrip("/"),)).fetchone() # -- gossip bookkeeping (what this node has already pushed where) -------- def pending_objects(self, peer_url: str): """Objects the peer has not been given yet: everything after the sent-cursor, except what was pulled FROM that peer (it has those), capped to one batch by count and raw size. Returns (rows, last_seq).""" row = self.get_peer(peer_url) since = (row["pushed"] or 0) if row else 0 rows, size = [], 0 q = self.db.execute( "SELECT id, type, body, size, rowid AS seq FROM objects " "WHERE rowid > ? AND origin <> ? AND id NOT IN (" "SELECT object_id FROM peer_has WHERE peer_url=?) " "ORDER BY rowid LIMIT ?", (since, peer_url.rstrip("/"), peer_url.rstrip("/"), GOSSIP_BATCH_OBJECTS)) for r in q: if rows and size + r["size"] > GOSSIP_BATCH_BYTES: break rows.append(r) size += r["size"] return rows, (rows[-1]["seq"] if rows else since) def peer_has(self, peer_url: str, ids) -> None: """Record that the peer already holds these objects (seen in its listing), so gossip never pushes them back.""" peer_url = peer_url.rstrip("/") with self._lock: self.db.executemany( "INSERT OR IGNORE INTO peer_has(peer_url, object_id) VALUES(?,?)", [(peer_url, i) for i in ids]) self.db.commit() def peer_pushed(self, url: str, cursor: int, ok: bool, note: str = ""): """Record a push attempt. A confirmed batch advances the sent-cursor (even when the peer rejected every object: it never will take them); a failed one leaves it, so the batch is retried.""" status = ("%s: %s" % ("ok" if ok else "FAIL", note))[:200] if note else ( "ok" if ok else "FAIL") with self._lock: if ok: self.db.execute("UPDATE peers SET pushed=?, push_status=? WHERE url=?", (cursor, status, url)) else: self.db.execute("UPDATE peers SET push_status=? WHERE url=?", (status, url)) self.db.commit() # -- node discovery -------------------------------------------------- def inbox_mode(self) -> str: mode = (self.cfg.get("inbox") or {}).get("mode", "token") return mode if mode in INBOX_MODES else "token" def is_friend(self, fp: str) -> bool: friends = (self.cfg.get("inbox") or {}).get("friends") or [] return fp[:16] in [str(f)[:16].lower() for f in friends] def know_node(self, manifest: dict, source: str = ""): """Remember a node's self-announced addresses from its manifest.""" iid = str(manifest.get("instance_id") or "") eps = manifest.get("endpoints") if not iid or iid == self.instance_id or not isinstance(eps, list): return eps = [e for e in eps if isinstance(e, dict) and isinstance(e.get("url"), str) and len(e["url"]) < 300][:8] if not eps: return now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) with self._lock: self.db.execute( "INSERT INTO known_nodes(instance_id,name,endpoints,first_seen," "last_seen,source) VALUES(?,?,?,?,?,?) " "ON CONFLICT(instance_id) DO UPDATE SET name=excluded.name, " "endpoints=excluded.endpoints, last_seen=excluded.last_seen", (iid[:64], str(manifest.get("name") or "")[:80], json.dumps(eps), now, now, source.rstrip("/")[:200])) self.db.execute( "DELETE FROM known_nodes WHERE instance_id NOT IN (" "SELECT instance_id FROM known_nodes ORDER BY last_seen DESC " "LIMIT ?)", (KNOWN_NODES_MAX,)) self.db.commit() def know_nodes(self, nodes, source: str = ""): """Ingest the flat `nodes` list of a peer's manifest (addresses that peer learned from others).""" by_instance = {} for n in nodes if isinstance(nodes, list) else []: if not isinstance(n, dict) or not isinstance(n.get("url"), str): continue d = by_instance.setdefault(str(n.get("instance") or n["url"]), { "instance_id": str(n.get("instance") or ""), "name": n.get("name", ""), "endpoints": []}) d["endpoints"].append({"layer": n.get("layer"), "url": n["url"]}) for d in by_instance.values(): if d["instance_id"]: self.know_node(d, source) def list_known_nodes(self): return self.db.execute("SELECT * FROM known_nodes ORDER BY last_seen DESC" ).fetchall() def known_endpoints(self): """Learned addresses (newest first) as flat dicts.""" out = [] for n in self.list_known_nodes(): try: eps = json.loads(n["endpoints"]) except Exception: continue for e in eps: out.append({"instance": n["instance_id"], "name": n["name"], "url": e["url"], "layer": e.get("layer") or detect_layer(e["url"])}) return out def peer_synced(self, url: str, ok: bool, note: str): with self._lock: self.db.execute( "UPDATE peers SET last_sync=?, last_ok=?, last_status=? WHERE url=?", (time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), 1 if ok else 0, note[:200], url)) self.db.commit() # -- accounts --------------------------------------------------------- # One file per account under data/accounts/ (0700): the account's own # Ed25519 key (so commits are signed with the USER's key, not the node's) # and the sha256 of the pass. Never synced, never published. def _accounts_dir(self) -> str: d = os.path.join(self.root, "data", "accounts") os.makedirs(d, mode=0o700, exist_ok=True) return d def _account_path(self, name: str) -> str: return os.path.join(self._accounts_dir(), name + ".json") def account(self, name: str) -> Optional[dict]: if not isinstance(name, str) or not ACCOUNT_NAME_RE.match(name): return None try: with open(self._account_path(name), encoding="utf-8") as f: a = json.load(f) except (OSError, ValueError): return None if not isinstance(a, dict) or "seed" not in a or "pass_hash" not in a: return None return a def accounts(self) -> list: out = [] try: for fn in sorted(os.listdir(self._accounts_dir())): a = self.account(fn[:-5]) if a: out.append(a) except OSError: pass return out def account_create(self, name: str, role: str = "user") -> tuple: """Register an account: new keypair + fresh pass. Returns (Key, pass) — the pass is shown once and stored only as a hash. Raises ValueError on a bad/taken name. The single enforcement point of the name rules, so CLI, /auth and MCP cannot diverge: a name already worn as an account or as an alias of another key is not claimable (committed decision 3).""" name = (name or "").strip().lower() if not ACCOUNT_NAME_RE.match(name): raise ValueError("bad account name (2-32 chars: a-z 0-9 _ -)") if role not in ACCOUNT_ROLES: raise ValueError("bad role") with self._lock: if self.account_name_taken(name): raise ValueError("name taken") seed = os.urandom(32) pub = pub_from_seed(seed) key = Key(seed, pub, pub.hex()[:16], name) pass_ = secrets.token_hex(16) rec = {"seed": seed.hex(), "pub": pub.hex(), "fp": key.fp, "name": name, "role": role, "created": int(time.time()), "pass_hash": hashlib.sha256(pass_.encode()).hexdigest()} path = self._account_path(name) with open(path, "w", encoding="utf-8") as f: json.dump(rec, f, indent=1) os.chmod(path, 0o600) # the account name is this node's alias for the key self.db.execute( "INSERT INTO aliases(fingerprint,name) VALUES(?,?) " "ON CONFLICT(fingerprint) DO UPDATE SET name=excluded.name", (key.fp, name)) self.db.commit() return key, pass_ def account_key(self, name: str) -> Optional[Key]: a = self.account(name) if a is None: return None pub = bytes.fromhex(a["pub"]) return Key(bytes.fromhex(a["seed"]), pub, pub.hex()[:16], a["name"]) def account_auth(self, name: str, pass_: str) -> Optional[dict]: """Constant-time pass check. Returns the account record or None.""" a = self.account(name) if a is None or not isinstance(pass_, str) or not pass_: return None want = a["pass_hash"] got = hashlib.sha256(pass_.encode()).hexdigest() return a if hmac.compare_digest(want, got) else None def account_reissue(self, name: str) -> Optional[str]: """New pass for an account (operator act). Returns it once.""" with self._lock: a = self.account(name) if a is None: return None pass_ = secrets.token_hex(16) a["pass_hash"] = hashlib.sha256(pass_.encode()).hexdigest() with open(self._account_path(name), "w", encoding="utf-8") as f: json.dump(a, f, indent=1) return pass_ def account_remove(self, name: str) -> bool: """Delete an account (operator act). Its commits stay — they are signed with a key that simply has no account behind it any more. The alias is removed by the account's own fingerprint: another key wearing the same name as an operator-curated alias keeps it.""" with self._lock: a = self.account(name) if a is None: return False os.remove(self._account_path(name)) self.db.execute("DELETE FROM aliases WHERE fingerprint=?", (a["fp"],)) self.db.commit() return True def account_set_role(self, name: str, role: str) -> bool: if role not in ACCOUNT_ROLES: raise ValueError("bad role") with self._lock: a = self.account(name) if a is None: return False a["role"] = role with open(self._account_path(name), "w", encoding="utf-8") as f: json.dump(a, f, indent=1) return True def account_name_taken(self, name: str) -> bool: """A name is free iff no account has it and no OTHER key wears it as an alias (an account must not steal an operator-curated name).""" if self.account(name) is not None: return True row = self.db.execute("SELECT fingerprint FROM aliases WHERE name=?", (name,)).fetchone() return bool(row) # -- idempotency ------------------------------------------------------- @staticmethod def idem_digest(article: str, parents, content_id: str, comment: str, kind: str) -> str: """What identifies a logical commit: everything except ts. A client retrying a timed-out write mints a new ts, and without this table that retry would land as a sibling commit — a duplicate head.""" return hashlib.sha256("\x00".join( [article, ",".join(parents), content_id, comment, kind]) .encode("utf-8")).hexdigest() def idem_lookup(self, article: str, request_id: str, digest: str): """Advisory fast-path. Returns (commit_id, replayed) on a hit; (None, False) when unseen; raises on key reuse with other content.""" row = self.db.execute( "SELECT commit_id, digest FROM idem WHERE article=? AND request_id=?", (article, request_id)).fetchone() if row is None: return None, False if row["digest"] != digest: raise ValueError("request_id_conflict") return row["commit_id"], True def peer_set_cursor(self, url: str, cursor: int) -> None: with self._lock: self.db.execute("UPDATE peers SET cursor=? WHERE url=?", (cursor, url)) self.db.commit() def backup_to(self, path: str) -> None: """Crash-consistent snapshot of the live (WAL) database.""" dst = sqlite3.connect(path) try: self.db.backup(dst) finally: dst.close() # -- creation ---------------------------------------------------------- def create_commit(self, key: Key, article: str, content: bytes, parents, comment: str, kind: str = "text", lang: str = "python3", entry: str = "main", request_id=None): """Build, sign and store a commit. Returns (commit_id, content_id, replayed) or raises ValueError with the reason. With request_id set, an identical retry replays the original commit instead of minting a sibling head; the same key with different content is a conflict.""" if not ARTICLE_RE.match(article): raise ValueError("bad article name") rid = None if request_id not in (None, ""): rid = str(request_id) if not REQID_RE.match(rid): raise ValueError("bad request_id (1-128 chars of A-Za-z0-9._~-)") if isinstance(content, str): content = content.encode("utf-8") if kind == "text": if len(content) > TEXT_LIMIT: raise ValueError("text too large") cbody = content elif kind == "code": if len(content) > CODE_LIMIT: raise ValueError("code too large") cbody = canon({"t": "code", "v": 1, "lang": lang, "entry": entry, "source": content.decode("utf-8")}) else: raise ValueError("bad content kind") cres = self.accept_object(cbody, origin="local") if not cres["ok"]: raise ValueError("content rejected: %s" % cres["reason"]) parents = list(parents)[:MAX_PARENTS] comment = comment[:300] digest = self.idem_digest(article, parents, cres["id"], comment, kind) if rid: cid, replayed = self.idem_lookup(article, rid, digest) if replayed: return cid, cres["id"], True commit = {"t": "commit", "v": 1, "article": article, "parents": parents, "content": cres["id"], "author": key.pub_hex, "ts": int(time.time()), "comment": comment, "sig": ""} msg = canon(commit) commit["sig"] = sign_bytes(key.seed, msg).hex() body = canon(commit) if rid: # authoritative check shares the lock with storage, so concurrent # identical retries can never double-post with self._lock: row = self.db.execute( "SELECT commit_id, digest FROM idem WHERE article=? AND request_id=?", (article, rid)).fetchone() if row is not None: if row["digest"] != digest: raise ValueError("request_id_conflict") return row["commit_id"], cres["id"], True res = self._accept_object_locked(body, origin="local") if not res["ok"]: raise ValueError("commit rejected: %s" % res["reason"]) self.db.execute( "INSERT INTO idem(article,request_id,commit_id,digest,created) " "VALUES(?,?,?,?,?)", (article, rid, res["id"], digest, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))) self.db.commit() return res["id"], cres["id"], False res = self.accept_object(body, origin="local") if not res["ok"]: raise ValueError("commit rejected: %s" % res["reason"]) return res["id"], cres["id"], False # ------------------------------------------------------------- rate limiter DEFAULT_RATE_LIMITS = { # kind -> {"ip": [(window_s, max_events), ...]} sliding windows. # Generous on purpose: node-to-node sync bursts must fit inside them. "commit": {"ip": [(60, 10), (3600, 60)], # /api/commit, /edit, /n "user": [(60, 20), (3600, 300)]}, # ... per signed-in account "register": {"ip": [(3600, 10)]}, # /auth new accounts "login": {"ip": [(60, 10), (3600, 50)]}, # failed /auth attempts "push": {"ip": [(60, 30), (3600, 600)]}, # /api/push, /sync/* "read": {"ip": [(60, 300)]}, # every GET } def rate_limits_from(cfg) -> dict: """Defaults deep-merged with config.json's rate_limits key (JSON tuples arrive as arrays; normalized to (int, int) here).""" out = {k: {s: list(rules) for s, rules in scopes.items()} for k, scopes in DEFAULT_RATE_LIMITS.items()} user = (cfg or {}).get("rate_limits") or {} for kind, scopes in user.items(): if isinstance(scopes, dict): slot = out.setdefault(kind, {}) for scope, rules in scopes.items(): slot[scope] = [tuple(r) for r in rules] return out class RateLimiter: """Sliding-window limiter, in memory (wipes on restart — acceptable for a small node). Rejected events are NOT counted, so a 429 backoff is free.""" def __init__(self, clock=time.monotonic): self.clock = clock self._events = {} # key -> deque of timestamps self._lock = threading.Lock() def _recent(self, q, window, now): n = 0 for t in reversed(q): if now - t <= window: n += 1 else: break return n def _violation(self, q, rules, now): worst = None for window, max_events in rules: if max_events <= 0: return window # "none allowed": refuse for a whole window if self._recent(q, window, now) >= max_events: # the (max_events)-th newest event must age out to free a slot retry = q[len(q) - max_events] + window - now worst = retry if worst is None else max(worst, retry) return worst def hit(self, key: str, rules, weight: int = 1): """Record `weight` events (1 for normal use). None if allowed; else retry_after (rejected events are not recorded). Weight > 1 lets one request cost several slots — used by the optional karma throttle so a push batch carrying low-karma authors burns the window faster.""" now = self.clock() max_window = max(w for w, _ in rules) with self._lock: q = self._events.setdefault(key, deque()) while q and now - q[0] > max_window: q.popleft() for _ in range(max(1, weight)): retry = self._violation(q, rules, now) if retry is not None: return retry q.append(now) return None # ------------------------------------------------------- sandboxed runner -- _NET_ISOLATION = None _PRLIMIT_ARGS = None _PRLIMIT_PROBED = False def net_isolation_available() -> bool: """True when `unshare --net` works for the current user (unprivileged user namespaces enabled). Cached once per process.""" global _NET_ISOLATION if _NET_ISOLATION is None: ok = False if shutil.which("unshare"): try: r = subprocess.run(["unshare", "--net", "true"], capture_output=True, timeout=5) ok = r.returncode == 0 except Exception: ok = False _NET_ISOLATION = ok return _NET_ISOLATION def rlimits_available() -> bool: """Probe (once) whether prlimit actually works here. Some hardened or containerized hosts crash children under setrlimit even for /bin/true, so we verify with a trivial command and degrade gracefully instead of shipping a sandbox that segfaults on exec.""" global _PRLIMIT_ARGS, _PRLIMIT_PROBED if not _PRLIMIT_PROBED: _PRLIMIT_PROBED = True _PRLIMIT_ARGS = [] pr = shutil.which("prlimit") if pr: tiers = [ ["--cpu=5", "--as=1G", "--nofile=64"], ["--cpu=5", "--nofile=64"], ] for tier in tiers: try: r = subprocess.run([pr] + tier + ["--", "/bin/true"], capture_output=True, timeout=5) if r.returncode == 0: _PRLIMIT_ARGS = tier break except Exception: pass return bool(_PRLIMIT_ARGS) def _kill_group(pid: int) -> None: """SIGKILL a whole process group. The sandbox child is its own group leader (start_new_session), so this takes down anything it spawned — plain kill() on the direct child leaves grandchildren running.""" try: os.killpg(pid, signal.SIGKILL) except OSError: pass def _descendants(root_pid: int): """All live descendant pids of root_pid, walked via /proc PPID chains. Needed because sandboxed code can setsid() a child out of the process group; parentage is still intact while the direct child lives.""" kids = {} try: names = os.listdir("/proc") except OSError: return [] for name in names: if not name.isdigit(): continue try: with open("/proc/%s/stat" % name, "rb") as f: st = f.read() # comm may contain spaces/parens: parse fields after the last ')' ppid = int(st[st.rindex(b")") + 2:].split()[1]) kids.setdefault(ppid, []).append(int(name)) except (OSError, ValueError, IndexError): continue out = [] stack = [root_pid] while stack: pid = stack.pop() for k in kids.get(pid, []): out.append(k) stack.append(k) return out def _kill_run(p) -> None: """End a sandbox run: kill every descendant first (catches setsid escapers while the parent is still alive to name them), then the whole process group. Limitation: daemons orphaned by a CLEAN exit are already reparented when we look — full containment there needs cgroups, so the trust decision stays with whoever pressed run.""" for pid in _descendants(p.pid): try: os.kill(pid, signal.SIGKILL) except OSError: pass _kill_group(p.pid) def clamp_run_timeout(value, default: float = RUN_TIMEOUT, lo: float = 1.0, hi: float = 300.0) -> float: """Run timeouts arriving over the API are untrusted input: garbage or None -> default, NaN/inf -> default, everything else clamped to [lo, hi].""" try: t = float(value) except (TypeError, ValueError): return default if not math.isfinite(t): return default return max(lo, min(hi, t)) def run_code(store: Store, oid: str, args=None, timeout: float = RUN_TIMEOUT) -> dict: """Run a signed code object in a throwaway sandbox. Opt-in only: nothing here is ever invoked implicitly by sync, render or the API. Isolation layers (net namespace, rlimits) are probed and reported per run; the trust decision stays with whoever pressed run.""" args = [str(a)[:200] for a in (args or [])][:32] rlimits_ok = rlimits_available() out = {"exit_code": None, "stdout": "", "stderr": "", "duration_ms": 0, "timed_out": False, "net_isolated": net_isolation_available(), "rlimits": rlimits_ok, "truncated": False} row = store.object(oid) if row is None or row["type"] != "code": out["stderr"] = "not a code object: %s" % oid[:12] return out try: obj = json.loads(bytes(row["body"]).decode("utf-8")) except Exception: out["stderr"] = "code object does not parse" return out if obj.get("lang") != "python3": out["stderr"] = "unsupported language: %s" % obj.get("lang") return out tmp = tempfile.mkdtemp(prefix="manifold-run-") try: main = os.path.join(tmp, "main.py") with open(main, "w", encoding="utf-8") as f: f.write(obj.get("source", "")) cmd = [] if out["net_isolated"]: cmd += ["unshare", "--net", "--"] if rlimits_ok: prlimit = shutil.which("prlimit") cpu = max(1, int(timeout)) tier = [a if not a.startswith("--cpu=") else "--cpu=%d" % cpu for a in _PRLIMIT_ARGS] cmd += [prlimit] + tier + ["--"] cmd += [sys.executable, "-I", main] + args env = {"PATH": "/usr/bin:/bin", "HOME": tmp, "TMPDIR": tmp, "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "PYTHONDONTWRITEBYTECODE": "1"} t0 = time.monotonic() p = None try: p = subprocess.Popen(cmd, cwd=tmp, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True) stdout, stderr = p.communicate(timeout=timeout) out["exit_code"] = p.returncode except subprocess.TimeoutExpired: out["timed_out"] = True _kill_run(p) try: stdout, stderr = p.communicate(timeout=5) except Exception: stdout, stderr = b"", b"" finally: if p is not None: # normal exit too: reap any group members the code left behind _kill_group(p.pid) out["duration_ms"] = int((time.monotonic() - t0) * 1000) for field, blob in (("stdout", stdout), ("stderr", stderr)): text = (blob or b"").decode("utf-8", errors="replace") if len(text) > RUN_OUTPUT_CAP: text = text[:RUN_OUTPUT_CAP] out["truncated"] = True out[field] = text finally: shutil.rmtree(tmp, ignore_errors=True) return out # ------------------------------------------------------------- networking -- class SyncError(Exception): pass # Never honor ambient proxy variables: fleet machines often export # http_proxy, which would silently hijack loopback and clearnet fetches. _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) def detect_layer(url: str) -> str: host = urllib.parse.urlparse(url).hostname or "" if host.endswith(".onion"): return "tor" if host.endswith(".i2p"): return "i2p" if ":" in host: # bare IPv6 (e.g. a Yggdrasil 200::/7 address) return "yggdrasil" return "clearnet" def _curl(args, timeout, max_bytes=None, input=None, headers=None): cmd = ["curl", "-fsSL", "--max-time", str(timeout)] if max_bytes: cmd += ["--max-filesize", str(max_bytes)] for k, v in (headers or {}).items(): cmd += ["-H", "%s: %s" % (k, v)] if input is not None: cmd += ["-H", "Content-Type: application/json", "--data-binary", "@-"] cmd += args try: r = subprocess.run(cmd, capture_output=True, input=input, timeout=timeout + 10) except subprocess.TimeoutExpired: raise SyncError("curl timeout") if r.returncode == 63: raise SyncError("response exceeds max-filesize") if r.returncode != 0: raise SyncError("curl rc=%d: %s" % (r.returncode, r.stderr.decode(errors="replace")[-200:])) if max_bytes and len(r.stdout) > max_bytes: raise SyncError("response exceeds %d bytes" % max_bytes) return r.stdout def layer_curl_args(layer: str, cfg: dict = None) -> list: """curl arguments routing a request through the right overlay network: tor via the local SOCKS proxy, i2p via the local HTTP proxy, plain HTTP(S) otherwise (Yggdrasil addresses route like any IPv6).""" cfg = cfg or {} if layer == "tor": socks = (cfg.get("network") or {}).get("tor_socks", "127.0.0.1:9050") return ["--socks5-hostname", socks] if layer == "i2p": proxy = (cfg.get("network") or {}).get("i2p_http", "127.0.0.1:4444") return ["-x", "http://" + proxy] return [] def fetch(url: str, layer: str = None, cfg: dict = None, timeout: int = 45, max_bytes: int = FETCH_LIMIT) -> bytes: """Fetch one URL over the right network layer. Tor and I2P peers are reached through the local SOCKS/HTTP proxy; everything else is plain HTTP(S) from this host (Yggdrasil addresses route like any IPv6). Responses are size-capped: a hostile peer must not balloon the syncer's memory.""" layer = layer or detect_layer(url) proxy = layer_curl_args(layer, cfg) if proxy: return _curl(proxy + [url], timeout, max_bytes) req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with _OPENER.open(req, timeout=timeout) as resp: data = resp.read(max_bytes + 1) if max_bytes else resp.read() if max_bytes and len(data) > max_bytes: raise SyncError("response exceeds %d bytes" % max_bytes) return data def fetch_json(url: str, layer: str = None, cfg: dict = None, timeout: int = 45): return json.loads(fetch(url, layer, cfg, timeout).decode("utf-8")) def post_json(url: str, payload: dict, layer: str = None, cfg: dict = None, timeout: int = 45, token: str = "") -> dict: """POST a JSON body over the right network layer and parse the JSON reply. Raises SyncError on any transport/HTTP failure.""" layer = layer or detect_layer(url) body = json.dumps(payload).encode("utf-8") headers = {"X-Manifold-Token": token} if token else {} proxy = layer_curl_args(layer, cfg) if proxy: raw = _curl(proxy + ["-H", "Accept: application/json", url], timeout, input=body, headers=headers) else: hdrs = {"Content-Type": "application/json", "User-Agent": USER_AGENT} hdrs.update(headers) req = urllib.request.Request(url, data=body, headers=hdrs, method="POST") try: with _OPENER.open(req, timeout=timeout) as resp: raw = resp.read(FETCH_LIMIT + 1) except urllib.error.HTTPError as e: raise SyncError("HTTP %d from peer" % e.code) except Exception as e: raise SyncError("post failed: %s" % str(e)[:120]) if len(raw) > FETCH_LIMIT: raise SyncError("response exceeds %d bytes" % FETCH_LIMIT) try: out = json.loads(raw.decode("utf-8")) except Exception: raise SyncError("peer replied non-JSON") if not isinstance(out, dict): raise SyncError("peer reply is not a JSON object") return out # -- gossip: push what we hold to peers (v0.4) ------------------------------ # A batch is signed by the sending NODE's key over its object ids. That is # the whole "friend" mechanism: an f2f node accepts a push iff the key that # signed the batch is in its friends list. Replays are harmless (objects are # content-addressed), so there is no challenge and no timestamp. def push_message(from_pub_hex: str, ids) -> bytes: return ("manifold-push-v1\n%s\n%s" % (from_pub_hex, "\n".join(ids))).encode("utf-8") def sign_push(key: Key, ids) -> dict: """Envelope fields for a push batch: {"from": pub, "sig": hex}.""" ids = [str(i) for i in ids] sig = sign_bytes(key.seed, push_message(key.pub_hex, ids)) return {"from": key.pub_hex, "sig": sig.hex()} def push_sender(store: Store, payload: dict) -> tuple: """Check a push envelope. Returns (ok, fingerprint16, reason). A batch without an envelope is (False, "", "unsigned").""" env_from = str((payload or {}).get("from") or "") sig_hex = str((payload or {}).get("sig") or "") if not env_from and not sig_hex: return False, "", "unsigned push" if not ID_RE.match(env_from) or not SIG_RE.match(sig_hex): return False, "", "malformed push envelope" ids = [] for o in (payload.get("objects") or []): try: oid = str(o.get("id", "")).lower() except Exception: return False, "", "malformed push envelope" ids.append(oid) try: ok = verify_bytes(bytes.fromhex(env_from), push_message(env_from, ids), bytes.fromhex(sig_hex)) except Exception: return False, "", "malformed push envelope" if not ok: return False, env_from[:16], "bad push signature" return True, env_from[:16], "" _PUSH_BACKOFF = {} # peer url -> monotonic time before which pushes wait _PUSH_BACKOFF_DELAY = {} # peer url -> the delay that produced that deadline def gossip_backoff(peer_url: str) -> float: """Doubling per-peer delay: 30 s, 60 s, ... capped at 10 min.""" delay = min(GOSSIP_BACKOFF_MAX, _PUSH_BACKOFF_DELAY.get(peer_url, GOSSIP_BACKOFF_MIN / 2) * 2) _PUSH_BACKOFF_DELAY[peer_url] = delay return delay def gossip_peer(store: Store, peer_url: str, layer: str = None, cfg: dict = None, key: Key = None) -> dict: """Push one pending batch to one peer. Returns a report; never raises. An f2f peer only takes the batch because it is signed by our node key.""" peer_url = peer_url.rstrip("/") layer = layer or detect_layer(peer_url) cfg = cfg or store.cfg report = {"peer": peer_url, "pushed": 0, "status": "", "error": ""} peer = store.get_peer(peer_url) rows, last_seq = store.pending_objects(peer_url) if not rows: report["status"] = "nothing to push" return report try: if key is None: key = default_key(store.root, store.cfg) if key is None: raise SyncError("no signing key — run: manifold.py keygen") objs = [{"id": r["id"], "body": base64.b64encode(bytes(r["body"])).decode()} for r in rows] env = sign_push(key, [r["id"] for r in rows]) reply = post_json(peer_url + "/api/push", {"objects": objs, **env}, layer, cfg, token=(peer["token"] if peer else "") or "") accepted = reply.get("accepted") if not isinstance(accepted, list): raise SyncError("peer did not acknowledge the batch") report["pushed"] = len(accepted) report["status"] = "pushed %d, rejected %d" % ( len(accepted), len(reply.get("rejected") or [])) store.peer_pushed(peer_url, last_seq, True, report["status"]) _PUSH_BACKOFF.pop(peer_url, None) _PUSH_BACKOFF_DELAY.pop(peer_url, None) except Exception as e: # report, never raise report["error"] = str(e)[:200] report["status"] = "error: " + report["error"] _PUSH_BACKOFF[peer_url] = time.monotonic() + gossip_backoff(peer_url) store.peer_pushed(peer_url, 0, False, report["error"]) return report def gossip_all(store: Store, only_url: str = None, ignore_backoff: bool = False) -> list: """One gossip round over all peers (skips peers in backoff unless told otherwise). Only peers with pending objects are contacted.""" reports = [] now = time.monotonic() for p in store.list_peers(): if only_url and only_url not in p["url"]: continue if not ignore_backoff and _PUSH_BACKOFF.get(p["url"], 0) > now: continue reports.append(gossip_peer(store, p["url"], p["layer"], store.cfg)) return reports def layer_available(layer: str, cfg: dict = None) -> bool: """Whether this host can reach a network layer: tor/i2p need their local proxy up; clearnet and yggdrasil are assumed routable.""" if layer not in ("tor", "i2p"): return True cfg = cfg or {} addr = ((cfg.get("network") or {}).get("tor_socks", "127.0.0.1:9050") if layer == "tor" else (cfg.get("network") or {}).get("i2p_http", "127.0.0.1:4444")) try: import socket host, port = addr.rsplit(":", 1) with socket.create_connection((host, int(port)), timeout=1): return True except Exception: return False def auto_peer_limit(store: Store) -> int: """How many peers discovery may add by itself.""" if store.inbox_mode() == "f2f": return 0 # a friend is someone the operator added, never learned v = (store.cfg.get("peers") or {}).get("max_auto") if isinstance(v, int) and not isinstance(v, bool): return max(0, v) return 8 if store.inbox_mode() == "open" else 0 def auto_peer(store: Store) -> list: """Add learned nodes as peers up to the limit. Returns the urls added.""" added = [] limit = auto_peer_limit(store) if limit <= 0: return added have = {p["url"].rstrip("/") for p in store.list_peers()} mine = {str(e.get("url", "")).rstrip("/") for e in store.cfg.get("endpoints") or []} room = limit - len(have) for ep in store.known_endpoints(): if room <= 0: break url = ep["url"].rstrip("/") if url in have or url in mine or not re.match(r"^https?://", url): continue if not layer_available(ep["layer"], store.cfg): continue store.add_peer(url, ep["layer"], auto=True) added.append(url) have.add(url) room -= 1 return added def sync_peer(store: Store, peer_url: str, layer: str = None, cfg: dict = None) -> dict: """Pull objects the peer has that we are missing. Verification is identical to local acceptance: id match, commit signatures, size caps. Heads are never negotiated - each peer derives them from its own DAG. Incremental: when we hold a cursor for this peer, only objects newer than it are listed; peers without cursor support fall back to the full listing transparently.""" cfg = cfg or store.cfg peer_url = peer_url.rstrip("/") layer = layer or detect_layer(peer_url) report = {"peer": peer_url, "layer": layer, "fetched": 0, "accepted": 0, "rejected": 0, "error": ""} try: manifest = fetch_json(peer_url + "/api/manifest", layer, cfg) if manifest.get("protocol") != PROTOCOL: raise SyncError("peer speaks protocol %r, we speak %d" % (manifest.get("protocol"), PROTOCOL)) # discovery: remember its addresses and the nodes it republishes store.know_node(manifest, peer_url) store.know_nodes(manifest.get("nodes"), peer_url) row = store.get_peer(peer_url) since = row["cursor"] if row and row["cursor"] else None url = peer_url + "/api/ids" if since: url += "?since=%d" % since listing = fetch_json(url, layer, cfg) ids = [e["id"] for e in listing.get("ids", []) if ID_RE.match(e.get("id", ""))] missing = [i for i in ids if not store.has(i)] store.peer_has(peer_url, [i for i in ids if i not in set(missing)]) report["fetched"] = len(missing) for i in range(0, len(missing), 64): chunk = missing[i:i + 64] qs = urllib.parse.urlencode({"ids": ",".join(chunk)}) payload = fetch_json("%s/api/objects?%s" % (peer_url, qs), layer, cfg) for entry in payload.get("objects", []): try: body = base64.b64decode(entry.get("body", "")) except Exception: report["rejected"] += 1 continue res = store.accept_object(body, origin=peer_url) if res["ok"] and not res["duplicate"]: report["accepted"] += 1 elif not res["ok"]: report["rejected"] += 1 cursor = listing.get("cursor") if isinstance(cursor, int) and cursor >= 0: store.peer_set_cursor(peer_url, cursor) note = "ok: %d missing, %d accepted, %d rejected" % ( report["fetched"], report["accepted"], report["rejected"]) store.peer_synced(peer_url, True, note) report["status"] = note except Exception as e: # report, never raise report["error"] = str(e)[:200] store.peer_synced(peer_url, False, "error: %s" % report["error"]) return report def sync_all(store: Store, only_url: str = None, discover: bool = True) -> list: """Pull from every peer (or the ones matching a url substring). With discover=, nodes learned from the manifests just synced are added as peers (open mode, up to the limit) and pulled from in the same round.""" reports = [] for p in store.list_peers(): if only_url and only_url not in p["url"]: continue reports.append(sync_peer(store, p["url"], p["layer"], store.cfg)) if discover and not only_url: for url in auto_peer(store): reports.append(sync_peer(store, url, None, store.cfg)) return reports # ------------------------------------------------------ software releases -- # Roadmap #1, per committed direction + operator calls (2026-11-30): # manifest + hash-named blobs, files split into chunks so every blob is an # ordinary text object; signed by the node's existing key; all versions # coexist as immutable objects. Updates are pull-only (sync), applied by an # explicit local act — never at sync or serve time. def _read_version(path: str): """Pull `__version__ = "x.y.z"` out of a source file (None if absent).""" try: with open(path, encoding="utf-8") as f: src = f.read(1 << 20) except OSError: return None m = re.search(r'^__version__\s*=\s*["\']([^"\']+)["\']', src, re.M) return m.group(1) if m else None def cut_release(store: Store, key: Key, src_dir: str, name: str = SOFTWARE, version: str = None, notes: str = "") -> tuple: """Chunk the shipped files into text objects and store a signed release manifest pointing at them. Returns (release_id, manifest).""" files = [] for fn in sorted(os.listdir(src_dir)): if fn not in RELEASE_SHIP_FILES: continue path = os.path.join(src_dir, fn) if not os.path.isfile(path): continue with open(path, "rb") as f: data = f.read() if not data: continue chunks = [] for i in range(0, len(data), RELEASE_CHUNK): res = store.accept_object(data[i:i + RELEASE_CHUNK], origin="local") if not res["ok"]: raise ValueError("chunk rejected (%s): %s" % (fn, res["reason"])) chunks.append(res["id"]) files.append({"path": fn, "size": len(data), "sha256": hashlib.sha256(data).hexdigest(), "chunks": chunks}) if not files: raise ValueError("no release files found in %s" % src_dir) if version is None: version = _read_version(os.path.join(src_dir, "manifold.py")) if not version: raise ValueError("no --version and no __version__ in %s/manifold.py" % src_dir) man = {"t": "release", "v": 1, "name": name, "version": str(version), "created": int(time.time()), "notes": (notes or "")[:500], "files": files, "author": key.pub_hex, "sig": ""} man["sig"] = sign_bytes(key.seed, canon(man)).hex() res = store.accept_object(canon(man), origin="local") if not res["ok"]: raise ValueError("release rejected: %s" % res["reason"]) return res["id"], man def release_sig_ok(man: dict) -> bool: try: unsigned = dict(man) unsigned["sig"] = "" return verify_bytes(bytes.fromhex(man["author"]), canon(unsigned), bytes.fromhex(man["sig"])) except Exception: return False def _version_key(v): """Orderable key for dotted versions: numeric parts numerically, else lexicographically (1.10 > 1.9, 1.0.0-rc1 still sorts after 1.0.0).""" out = [] for p in str(v).split(".")[:8]: out.append((0, int(p), "") if p.isdigit() else (1, 0, p)) return tuple(out) def verify_release_files(store: Store, man: dict) -> tuple: """(ok, lines): every chunk held locally, concatenated bytes hash to the recorded file sha256 and match the recorded size.""" lines, ok = [], True for f in man["files"]: missing = [c for c in f["chunks"] if not store.has(c)] if missing: ok = False lines.append("MISSING %s — %d chunk(s) not on this node " "(sync peers)" % (f["path"], len(missing))) continue blob = b"".join(store.object_body(c) for c in f["chunks"]) if hashlib.sha256(blob).hexdigest() != f["sha256"] \ or len(blob) != f["size"]: ok = False lines.append("CORRUPT %s — hash/size mismatch" % f["path"]) else: lines.append("ok %s (%d B, %d chunk(s))" % (f["path"], f["size"], len(f["chunks"]))) return ok, lines def _state_path(code_dir: str) -> str: return os.path.join(code_dir, ".update-state.json") def _read_state(code_dir: str): try: with open(_state_path(code_dir), encoding="utf-8") as f: return json.load(f) except Exception: return None def _write_state(code_dir: str, state: dict) -> None: with open(_state_path(code_dir), "w", encoding="utf-8") as f: json.dump(state, f, indent=1) def apply_release(store: Store, man: dict, rid: str, code_dir: str, dry_run: bool = False) -> None: """Verify → backup → stage → atomic swap. The running process keeps its in-memory code either way; restart to run the new version.""" if not release_sig_ok(man): raise ValueError("release signature invalid") paths = [f["path"] for f in man["files"]] for req in ESSENTIAL_FILES: if req not in paths: raise ValueError("release does not ship %s — refusing" % req) ok, lines = verify_release_files(store, man) for ln in lines: print(" " + ln) if not ok: raise ValueError("verification failed — nothing staged") if dry_run: print("check ok: release %s %s is fully verifiable on this node" % (man["name"], man["version"])) return staging = os.path.join(code_dir, ".update-staging", rid[:16]) shutil.rmtree(staging, ignore_errors=True) os.makedirs(staging, exist_ok=True) for f in man["files"]: blob = b"".join(store.object_body(c) for c in f["chunks"]) p = os.path.join(staging, f["path"]) with open(p, "wb") as fh: fh.write(blob) fh.flush() os.fsync(fh.fileno()) backup_dir = None prev_state = _read_state(code_dir) if any(os.path.exists(os.path.join(code_dir, f["path"])) for f in man["files"]): backup_dir = os.path.join( code_dir, ".update-backup", time.strftime("%Y%m%d-%H%M%S") + "-" + rid[:8]) os.makedirs(backup_dir, exist_ok=True) for f in man["files"]: src = os.path.join(code_dir, f["path"]) if os.path.exists(src): shutil.copy2(src, os.path.join(backup_dir, f["path"])) with open(os.path.join(backup_dir, ".state.json"), "w", encoding="utf-8") as fh: json.dump(prev_state, fh) for f in man["files"]: os.replace(os.path.join(staging, f["path"]), os.path.join(code_dir, f["path"])) shutil.rmtree(staging, ignore_errors=True) _write_state(code_dir, {"release_id": rid, "name": man["name"], "version": man["version"], "applied": int(time.time()), "backup": backup_dir}) print("applied %s %s (backup: %s)" % (man["name"], man["version"], backup_dir or "none")) print("restart the node to run the new code") def rollback_release(code_dir: str) -> None: root = os.path.join(code_dir, ".update-backup") if not os.path.isdir(root) or not os.listdir(root): raise SystemExit("no backups under %s" % root) bdir = os.path.join(root, sorted(os.listdir(root))[-1]) for fn in os.listdir(bdir): if fn == ".state.json": continue shutil.copy2(os.path.join(bdir, fn), os.path.join(code_dir, fn)) sp = os.path.join(bdir, ".state.json") state = None try: with open(sp, encoding="utf-8") as f: state = json.load(f) except Exception: state = None if state: _write_state(code_dir, state) elif os.path.exists(_state_path(code_dir)): os.remove(_state_path(code_dir)) print("rolled back to %s" % bdir) print("restart the node to run the restored code") # -------------------------------------------------------------------- CLI -- def _fmt_ts(ts) -> str: return time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(ts)) def _cli_store(args) -> Store: return Store(args.dir) def cmd_init(args): root = args.dir os.makedirs(os.path.join(root, "data"), exist_ok=True) cfgp = config_path(root) fresh = not os.path.exists(cfgp) or args.force if not fresh: print("config already exists: %s (use --force to overwrite)" % cfgp) cfg = load_config(root) else: cfg = json.loads(json.dumps(DEFAULT_CONFIG)) if args.name: cfg["name"] = args.name if not cfg.get("write_token"): cfg["write_token"] = secrets.token_hex(16) print("generated write_token (gates every write; agents need it for /api)") save_config(root, cfg) os.chmod(cfgp, 0o600) if fresh: print("wrote %s (0600)" % cfgp) store = Store(root) print("node %s ready (instance %s)" % (cfg.get("name", args.name), store.instance_id)) print("next: python3 manifold.py keygen --name you") def cmd_account(args): store = _cli_store(args) what = args.action if what == "list": accts = store.accounts() if not accts: print("no accounts — anyone can register at /auth, or: " "python3 manifold.py account add NAME --admin") for a in accts: print("%-6s %-24s %s since %s" % ( a["role"], a["name"], a["fp"], _fmt_ts(a.get("created")) if a.get("created") else "?")) return name = args.name if what == "add": try: key, pass_ = store.account_create(name, "admin" if args.admin else "user") except ValueError as e: raise SystemExit(str(e)) print("account %s created (%s) — key %s" % ( name, "admin" if args.admin else "user", key.fp)) print("pass (shown once): %s" % pass_) elif what == "admin": try: ok = store.account_set_role(name, "user" if args.remove else "admin") except ValueError as e: raise SystemExit(str(e)) print("%s %s" % (name, "is no longer an admin" if ok and args.remove else "is now an admin" if ok else "has no account")) elif what == "remove": if not store.account_remove(name): raise SystemExit("no account named %s" % name) print("account %s removed (its commits stay, signed by its old key)" % name) elif what == "token": pass_ = store.account_reissue(name) if pass_ is None: raise SystemExit("no account named %s" % name) print("new pass for %s (shown once): %s" % (name, pass_)) def cmd_token(args): cfg = load_config(args.dir) cfg["write_token"] = secrets.token_hex(16) save_config(args.dir, cfg) os.chmod(config_path(args.dir), 0o600) print("write_token: %s" % cfg["write_token"]) print("(stored in %s, 0600 — restart the node to pick it up)" % config_path(args.dir)) def cmd_backup(args): store = _cli_store(args) store.backup_to(args.path) print("backed up to %s" % args.path) def cmd_keygen(args): key = keygen(args.dir, args.name) print("generated key %s (%s)" % (key.fp, key.name)) keys = load_keys(args.dir) if len(keys) == 1: cfg = load_config(args.dir) cfg["default_key"] = key.fp save_config(args.dir, cfg) print("set as default_key in config.json") def cmd_keys(args): store = _cli_store(args) keys = load_keys(args.dir) if not keys: print("no keys yet: python3 manifold.py keygen --name you") return for k in keys: mark = " (default)" if k.fp == (store.cfg.get("default_key") or "") else "" alias = store.alias(k.fp, "") print("%s %-16s %s%s" % (k.fp, k.name, alias, mark)) def cmd_alias(args): """Operator-curated display names, node-local (committed decision 3). No argument lists; sets; --remove clears; alone shows one.""" store = _cli_store(args) if args.fingerprint: fp = args.fingerprint.strip().lower() if not FP_RE.match(fp): raise SystemExit("fingerprint must be 16 (or 64) hex chars") fp = fp[:16] if args.remove: store.clear_alias(fp) print("alias cleared for %s" % fp) return if args.name: name = args.name.strip() if not name or len(name) > 48: raise SystemExit("alias must be 1-48 chars") store.set_alias(fp, name) print("%s = %s" % (fp, name)) return cur = store.alias(fp, "") print("%s = %s" % (fp, cur if cur else "(no alias)")) return rows = store.all_aliases() if not rows: print("no aliases set — usage: manifold.py alias ") return for r in rows: print("%s %s" % (r["fingerprint"], r["name"])) def cmd_commit(args): store = _cli_store(args) key = default_key(args.dir, store.cfg) if args.key: for k in load_keys(args.dir): if k.fp == args.key: key = k if key is None: raise SystemExit("no keys: python3 manifold.py keygen --name you") if args.file == "-": content = sys.stdin.buffer.read() else: with open(args.file, "rb") as f: content = f.read() heads = store.heads(args.article) if args.parents: parents = args.parents elif args.root or not heads: parents = [] else: parents = [heads[0]["id"]] cid, _, replayed = store.create_commit(key, args.article, content, parents, args.comment, request_id=args.request_id, kind="code" if args.code else "text") print("committed %s -> %s%s (parents: %s)" % ( args.article, cid[:12], " REPLAY" if replayed else "", ", ".join(p[:8] for p in parents) if parents else "root")) def cmd_read(args): store = _cli_store(args) heads = store.heads(args.article) if not heads: raise SystemExit("no commits for %r" % args.article) if args.head: hid = store.resolve_head(args.article, args.head) if not hid: raise SystemExit("head %r not found" % args.head) else: hid = heads[0]["id"] row = store.commit(hid) kind, body = store.content_body(row["content"]) if body is None: raise SystemExit("content object missing locally (sync peers)") if kind == "code": sys.stdout.write(json.dumps(json.loads(body.decode()), indent=1)) else: sys.stdout.flush() sys.stdout.buffer.write(body) sys.stdout.buffer.flush() def cmd_heads(args): store = _cli_store(args) heads = store.heads(args.article) if not heads: print("no commits for %r" % args.article) return print("%d head(s) for %s:" % (len(heads), args.article)) for h in heads: _, missing = store.missing_ancestors(h["id"]) tag = " [missing %d ancestors]" % missing if missing else "" print(" %s %s %s %s%s" % ( h["id"][:12], _fmt_ts(h["ts"]), store.author_display(h["author"]), h["comment"], tag)) def cmd_log(args): store = _cli_store(args) rows = store.commits_for(args.article) for r in reversed(rows): parents = ", ".join(p[:8] for p in store.parents_of(r["id"])) or "root" print("%s %s %s %s <- %s" % ( r["id"][:12], _fmt_ts(r["ts"]), store.author_display(r["author"]), r["comment"], parents)) def cmd_show(args): store = _cli_store(args) body = store.object_body(args.object_id) if body is None: raise SystemExit("unknown object") sys.stdout.flush() sys.stdout.buffer.write(body) sys.stdout.buffer.flush() def cmd_run(args): store = _cli_store(args) prow = store.db.execute( "SELECT article, author, origin FROM commits WHERE content=? " "ORDER BY ts DESC LIMIT 1", (args.object_id,)).fetchone() orow = store.object(args.object_id) if prow: print("code from article %r · author %s (%s…) · first seen via %s" % (prow["article"], store.author_display(prow["author"]), prow["author"][:16], prow["origin"])) elif orow is not None: print("bare object, no commit references it · origin %s" % orow["origin"]) res = run_code(store, args.object_id, args.args) print("exit=%s duration=%sms net_isolated=%s%s" % ( res["exit_code"], res["duration_ms"], res["net_isolated"], " TIMED OUT" if res["timed_out"] else "")) if res["stdout"]: print("--- stdout ---\n" + res["stdout"]) if res["stderr"]: print("--- stderr ---\n" + res["stderr"]) def cmd_peers(args): store = _cli_store(args) peers = store.list_peers() if not peers: print("no peers yet: python3 manifold.py add-peer URL") return for p in peers: state = ("ok" if p["last_ok"] else "FAIL") if p["last_sync"] else "never" print("%-8s %-42s %s%s %s" % ( p["layer"], p["url"], state, " [auto]" if p["auto"] else "", p["last_status"] or "")) print("%-8s %-42s push: %s" % ("", "", p["push_status"] or "not yet")) def cmd_add_peer(args): store = _cli_store(args) store.add_peer(args.url, args.layer, args.token or "") print("peer added: %s (layer %s)" % (args.url, args.layer or detect_layer(args.url))) if not args.no_sync: rep = sync_peer(store, args.url, args.layer, store.cfg) print(rep.get("status") or rep.get("error")) rep = gossip_peer(store, args.url, args.layer) print("gossip: %s" % (rep.get("status") or rep.get("error"))) def cmd_remove_peer(args): store = _cli_store(args) if store.remove_peer(args.url): print("peer removed: %s" % args.url) else: print("no such peer: %s" % args.url) def cmd_gossip(args): store = _cli_store(args) reports = gossip_all(store, args.peer, ignore_backoff=True) if not reports: print("nothing to push" if store.list_peers() else "no peers configured") for r in reports: print("%s %s" % (r["peer"], r.get("status") or r.get("error"))) def cmd_sync(args): store = _cli_store(args) reports = sync_all(store, args.peer, discover=not args.no_discover) for r in gossip_all(store, args.peer, ignore_backoff=True): reports.append(r) if not reports: print("no peers configured") for r in reports: print(r.get("status") or r.get("error")) def cmd_import_dir(args): store = _cli_store(args) key = default_key(args.dir, store.cfg) if key is None: raise SystemExit("no keys: python3 manifold.py keygen --name you") files = sorted(f for f in os.listdir(args.path) if f.endswith(".md")) if not files: raise SystemExit("no .md files in %s" % args.path) for fn in files: article = re.sub(r"[^a-z0-9._-]", "-", fn[:-3].lower()).strip("-") article = ARTICLE_RE.match(article) and article if not article: print("skip %s (name does not normalize)" % fn) continue with open(os.path.join(args.path, fn), "rb") as f: content = f.read() heads = store.heads(article) parents = [heads[0]["id"]] if heads else [] cid, _, _ = store.create_commit(key, article, content, parents, "imported from %s" % fn) print("imported %-40s -> %s" % (article, cid[:12])) def cmd_release(args): """Cut a release from a source dir into this node's store (manifest + chunk blobs, signed with the node's key). Peers receive it via sync.""" store = _cli_store(args) key = default_key(args.dir, store.cfg) if key is None: raise SystemExit("no keys: python3 manifold.py keygen --name you") src = os.path.abspath(args.src or os.path.dirname(os.path.abspath(__file__))) rid, man = cut_release(store, key, src, name=args.name or SOFTWARE, version=args.version, notes=args.notes) total = sum(f["size"] for f in man["files"]) nch = sum(len(f["chunks"]) for f in man["files"]) print("release %s %s -> %s" % (man["name"], man["version"], rid[:16])) print(" %d file(s), %d B, %d chunk object(s) — all versions coexist; " "peers get it via sync" % (len(man["files"]), total, nch)) def _trusted_releases(store, allow_fps, name): """Held releases whose author key is pinned AND whose signature still verifies (accept checked it once; update re-verifies before staging).""" out = [] for rid, man in store.list_releases(name): if str(man.get("author", ""))[:16].lower() not in allow_fps: continue if not release_sig_ok(man): continue out.append((rid, man)) return out def cmd_update(args): """Software update operator act — never runs at sync or serve time.""" store = _cli_store(args) code_dir = os.path.abspath(args.code_dir or os.path.dirname(os.path.abspath(__file__))) allow = [str(a).lower() for a in ((store.cfg.get("update") or {}).get("allow_keys") or [])] if not allow: k = default_key(args.dir, store.cfg) allow = [k.fp] if k else [] name = args.name or SOFTWARE if args.rollback: rollback_release(code_dir) return cands = _trusted_releases(store, allow, name) if args.version: sel = [(rid, m) for rid, m in cands if m.get("version") == args.version] if not sel: raise SystemExit("release %s %s not held/trusted on this node " "(sync peers, or set update.allow_keys)" % (name, args.version)) rid, man = sel[0] apply_release(store, man, rid, code_dir, dry_run=args.check) return if args.latest: if not cands: raise SystemExit("no trusted releases held — sync peers, or cut " "one: manifold.py release") rid, man = max(cands, key=lambda rm: (_version_key(rm[1].get("version", "")), rm[1].get("created", 0))) apply_release(store, man, rid, code_dir, dry_run=args.check) return # no target: status + what is held (every version, side by side) print("code dir : %s" % code_dir) print("running : %s" % __version__) st = _read_state(code_dir) print("applied : %s" % (("release %s (%s)" % (st.get("version"), st.get("release_id", "")[:16])) if st else "none recorded")) print("trusted : %s" % (", ".join(allow) if allow else "NONE — keygen first")) if not cands: print("no trusted releases held — sync peers or cut one " "(manifold.py release); all versions coexist in the store") return print("releases held:") for rid, m in sorted(cands, key=lambda rm: _version_key(rm[1].get("version", ""))): tot = sum(f.get("size", 0) for f in m.get("files", [])) print(" %-14s %s %d file(s) %7d B %s" % ( m.get("version", "?"), rid[:16], len(m.get("files", [])), tot, time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(m.get("created", 0))))) def cmd_serve(args): store = _cli_store(args) from manifold_http import serve serve(store) def main(argv=None): ap = argparse.ArgumentParser( prog="manifold", description="Manifold: minimal polyphonic peer-to-peer wiki. " "Every article is a signed history DAG; conflicting " "points of view coexist as heads. HTML UI + JSON API.") ap.add_argument("--dir", default=os.environ.get("MANIFOLD_DIR") or os.path.dirname(os.path.abspath(__file__)), help="node directory (default: this repo / $MANIFOLD_DIR)") sub = ap.add_subparsers(dest="cmd", required=True) p = sub.add_parser("init", help="create config + database") p.add_argument("--name") p.add_argument("--force", action="store_true") p.set_defaults(fn=cmd_init) p = sub.add_parser("keygen", help="generate an author keypair") p.add_argument("--name", default="anonymous") p.set_defaults(fn=cmd_keygen) p = sub.add_parser("keys", help="list keys") p.set_defaults(fn=cmd_keys) p = sub.add_parser("alias", help="curate node-local display names per " "fingerprint (list / set / --remove)") p.add_argument("fingerprint", nargs="?", help="fp16 or full pub key hex") p.add_argument("name", nargs="?", help="display name (empty = show)") p.add_argument("--remove", action="store_true", help="clear the alias") p.set_defaults(fn=cmd_alias) p = sub.add_parser("commit", help="add a commit (new branch) to an article") p.add_argument("article") p.add_argument("file", help="text file, or - for stdin") p.add_argument("-p", "--parent", action="append", dest="parents", help="parent commit id (repeatable; default: newest head)") p.add_argument("--root", action="store_true", help="ignore heads, no parents") p.add_argument("-m", "--comment", default="") p.add_argument("--code", action="store_true", help="store as a code object (python3)") p.add_argument("--key", help="signing key fingerprint") p.add_argument("-i", "--request-id", dest="request_id", help="idempotency key: identical retries replay, not re-commit") p.set_defaults(fn=cmd_commit) p = sub.add_parser("read", help="print an article head (default: newest)") p.add_argument("article") p.add_argument("--head", help="head id or unique prefix") p.set_defaults(fn=cmd_read) p = sub.add_parser("heads", help="list coexisting heads of an article") p.add_argument("article") p.set_defaults(fn=cmd_heads) p = sub.add_parser("log", help="list all commits of an article") p.add_argument("article") p.set_defaults(fn=cmd_log) p = sub.add_parser("show", help="print a raw object by id") p.add_argument("object_id") p.set_defaults(fn=cmd_show) p = sub.add_parser("run", help="run a signed code object in the sandbox") p.add_argument("object_id") p.add_argument("args", nargs="*") p.set_defaults(fn=cmd_run) p = sub.add_parser("peers", help="list peers") p.set_defaults(fn=cmd_peers) p = sub.add_parser("add-peer", help="register a peer and pull from it") p.add_argument("url") p.add_argument("--layer", help="clearnet|tor|i2p|yggdrasil (default: auto)") p.add_argument("--no-sync", action="store_true") p.add_argument("--token", help="peer's write token, for pushing to a " "token-mode peer (kept in the node DB, never published)") p.set_defaults(fn=cmd_add_peer) p = sub.add_parser("remove-peer", help="forget a peer") p.add_argument("url") p.set_defaults(fn=cmd_remove_peer) p = sub.add_parser("gossip", help="push newly held objects to peers") p.add_argument("--peer", help="url substring filter") p.set_defaults(fn=cmd_gossip) p = sub.add_parser("sync", help="pull from all peers (or one), then push") p.add_argument("--peer", help="url substring filter") p.add_argument("--no-discover", action="store_true", help="do not add learned nodes as peers") p.set_defaults(fn=cmd_sync) p = sub.add_parser("import-dir", help="import *.md files as articles") p.add_argument("path") p.set_defaults(fn=cmd_import_dir) p = sub.add_parser("token", help="(re)generate the write token (config.json, 0600)") p.set_defaults(fn=cmd_token) p = sub.add_parser("account", help="manage accounts (list / add / admin / remove / token)") p.add_argument("action", choices=["list", "add", "admin", "token", "remove"]) p.add_argument("name", nargs="?", help="account name (not needed for `list`)") p.add_argument("--admin", action="store_true", help="add: create as admin") p.add_argument("--remove", action="store_true", help="admin: take the admin role away instead") p.set_defaults(fn=cmd_account) p = sub.add_parser("backup", help="crash-consistent snapshot of the node DB") p.add_argument("path") p.set_defaults(fn=cmd_backup) p = sub.add_parser("release", help="cut a signed release (manifest + " "chunk blobs) from a source dir into the store") p.add_argument("--src", help="source dir (default: this code's dir)") p.add_argument("--name", help="software name (default: manifold)") p.add_argument("--version", help="version tag (default: __version__ in " "src/manifold.py)") p.add_argument("-m", "--notes", default="", help="release notes (<=500 chars)") p.set_defaults(fn=cmd_release) p = sub.add_parser("update", help="apply a held release to the code dir " "(verify -> backup -> stage -> atomic swap; explicit " "operator act, never at sync/serve time)") p.add_argument("--version", help="apply this exact release version") p.add_argument("--latest", action="store_true", help="apply the newest " "trusted release (safe for cron)") p.add_argument("--check", action="store_true", help="verify only, " "stage/swap nothing") p.add_argument("--rollback", action="store_true", help="restore the most " "recent backup") p.add_argument("--name", help="software name (default: manifold)") p.add_argument("--code-dir", dest="code_dir", help="dir to swap files in " "(default: this code's dir)") p.set_defaults(fn=cmd_update) p = sub.add_parser("serve", help="start the HTTP server (UI + API)") p.set_defaults(fn=cmd_serve) args = ap.parse_args(argv) args.fn(args) if __name__ == "__main__": main()