From 9bfe34ef614d2f2788da00dc9384e6fb08d43978 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:23:40 -0400 Subject: [PATCH 01/14] remoteauth: verify the edge's signed identity for remote MCP Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- pyproject.toml | 5 +- src/brain/remoteauth.py | 177 ++++++++++++++++++++++++++++++++++++++ tests/remote_helpers.py | 47 ++++++++++ tests/test_packaging.py | 6 ++ tests/test_remoteauth.py | 124 +++++++++++++++++++++++++++ uv.lock | 179 ++++++++++++++++++++++++++++++++++++++- 6 files changed, 536 insertions(+), 2 deletions(-) create mode 100644 src/brain/remoteauth.py create mode 100644 tests/remote_helpers.py create mode 100644 tests/test_remoteauth.py diff --git a/pyproject.toml b/pyproject.toml index 830bae25..d957e092 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,10 @@ Issues = "https://github.com/joedanz/brainkit/issues" Source = "https://github.com/joedanz/brainkit" [project.optional-dependencies] -dev = ["pytest>=8.0", "pytest-aiohttp>=1.0"] +dev = ["pytest>=8.0", "pytest-aiohttp>=1.0", "pyjwt[crypto]>=2.10"] +# Remote MCP (`brain mcp --http`, `brain mcp-router`): verifies the signed +# identity assertion an edge such as Cloudflare Access adds to each request. +remote = ["pyjwt[crypto]>=2.10"] [project.scripts] brain = "brain.cli:main" diff --git a/src/brain/remoteauth.py b/src/brain/remoteauth.py new file mode 100644 index 00000000..a19b685a --- /dev/null +++ b/src/brain/remoteauth.py @@ -0,0 +1,177 @@ +"""Verify the signed identity an edge adds to each remote-MCP request. + +brainkit is not an OAuth server. The edge (Cloudflare Access with Managed +OAuth) runs sign-in and stamps every request it lets through with a short-lived +RS256 JWT naming the person — ``Cf-Access-Jwt-Assertion``. This module checks +that JWT against the edge's published keys and returns the email in it. It +issues nothing and stores nothing. + +Needs the optional extra: ``pip install 'brainkit[remote]'``. +""" + +from __future__ import annotations + +import json +import math +import os +import threading +import time +import urllib.request +from collections.abc import Callable, Mapping +from dataclasses import dataclass + +from brain.errors import BrainError +from brain.version import __version__ + +DEFAULT_HEADER = "Cf-Access-Jwt-Assertion" +LEEWAY_S = 60 +REFETCH_MIN_INTERVAL_S = 60.0 +REFRESH_EVERY_S = 12 * 3600.0 +_ENV = {"issuer": "BRAIN_MCP_ISSUER", "jwks_url": "BRAIN_MCP_JWKS_URL", + "audience": "BRAIN_MCP_AUDIENCE", "header": "BRAIN_MCP_HEADER"} + + +class RemoteAuthError(BrainError, ValueError): + """Misconfiguration found at startup — the server refuses to start.""" + + +class AuthRejected(BrainError): + """A request the server must refuse: ``status`` is the HTTP status, + ``code`` the stable error code in the JSON body.""" + + def __init__(self, status: int, code: str, message: str): + super().__init__(message) + self.status, self.code, self.message = status, code, message + + +@dataclass(frozen=True) +class AuthConfig: + issuer: str + jwks_url: str + audience: str + header: str = DEFAULT_HEADER + + +@dataclass(frozen=True) +class Identity: + email: str + + +def normalize_email(value: str) -> str: + """The comparison Org.person_by_email uses: case- and whitespace-insensitive.""" + return value.strip().lower() + + +def auth_config(*, issuer: str | None = None, jwks_url: str | None = None, + audience: str | None = None, header: str | None = None, + environ: Mapping[str, str] | None = None) -> AuthConfig: + """Flags win; each unset flag falls back to its BRAIN_MCP_* variable.""" + env = os.environ if environ is None else environ + vals = {"issuer": issuer, "jwks_url": jwks_url, "audience": audience, "header": header} + for key, var in _ENV.items(): + if not vals[key]: + vals[key] = env.get(var, "") + missing = [f"--auth-{k.replace('_', '-')} / {_ENV[k]}" + for k in ("issuer", "jwks_url", "audience") if not vals[k]] + if missing: + raise RemoteAuthError("remote MCP needs its identity settings; missing: " + + ", ".join(missing)) + for key in ("issuer", "jwks_url"): + if not vals[key].startswith("https://"): + raise RemoteAuthError(f"{_ENV[key]} must be an https:// URL, got {vals[key]!r}") + return AuthConfig(vals["issuer"].rstrip("/"), vals["jwks_url"], vals["audience"], + vals["header"] or DEFAULT_HEADER) + + +def _require_jwt(): + try: + import jwt + from jwt.algorithms import RSAAlgorithm # absent without the [crypto] extra + except ImportError as e: + raise RemoteAuthError( + "remote MCP needs the optional extra — install 'brainkit[remote]'") from e + return jwt, RSAAlgorithm + + +def _fetch_json(url: str) -> dict: + # A named User-Agent: some zones refuse library defaults (Cloudflare 1010). + req = urllib.request.Request(url, headers={"User-Agent": f"brainkit/{__version__}", + "Accept": "application/json"}) + with urllib.request.urlopen(req, timeout=10) as r: + return json.load(r) + + +class Verifier: + def __init__(self, config: AuthConfig, *, fetch: Callable[[str], dict] = _fetch_json, + clock: Callable[[], float] = time.monotonic): + self._jwt, self._rsa = _require_jwt() + self.config = config + self._fetch = fetch + self._clock = clock + self._keys: dict[str, object] = {} + self._loaded_at = -math.inf + self._attempted_at = -math.inf + self._lock = threading.Lock() + + def load(self) -> None: + """Startup: fetch the signing keys, or refuse to start.""" + try: + keys = self._parse(self._fetch(self.config.jwks_url)) + except Exception as e: + raise RemoteAuthError( + f"cannot load signing keys from {self.config.jwks_url}: {e}") from e + if not keys: + raise RemoteAuthError(f"no RSA signing keys at {self.config.jwks_url}") + self._keys = keys + self._loaded_at = self._attempted_at = self._clock() + + def _parse(self, doc) -> dict[str, object]: + keys: dict[str, object] = {} + for k in (doc or {}).get("keys", []): + if isinstance(k, dict) and k.get("kty") == "RSA" and k.get("kid"): + keys[k["kid"]] = self._rsa.from_jwk(json.dumps(k)) + return keys + + def _refresh(self) -> None: + """Best effort, at most once per REFETCH_MIN_INTERVAL_S. A failed or + empty fetch keeps the keys already held.""" + with self._lock: + now = self._clock() + if now - self._attempted_at < REFETCH_MIN_INTERVAL_S: + return + self._attempted_at = now + try: + keys = self._parse(self._fetch(self.config.jwks_url)) + except Exception: + return + if keys: + self._keys, self._loaded_at = keys, now + + def verify(self, headers: Mapping[str, str]) -> Identity: + jwt = self._jwt + token = headers.get(self.config.header, "") + if not token: + raise AuthRejected(401, "unauthenticated", "missing identity assertion") + if self._clock() - self._loaded_at > REFRESH_EVERY_S: + self._refresh() + try: + kid = jwt.get_unverified_header(token).get("kid") + except jwt.PyJWTError: + raise AuthRejected(401, "unauthenticated", "malformed identity assertion") from None + key = self._keys.get(kid) + if key is None: + self._refresh() + key = self._keys.get(kid) + if key is None: + raise AuthRejected(401, "unauthenticated", "assertion signed by an unknown key") + try: + claims = jwt.decode(token, key, algorithms=["RS256"], + audience=self.config.audience, issuer=self.config.issuer, + leeway=LEEWAY_S, options={"require": ["exp", "iss", "aud"]}) + except jwt.PyJWTError as e: + raise AuthRejected(401, "unauthenticated", + f"invalid identity assertion ({type(e).__name__})") from None + email = claims.get("email") + if not isinstance(email, str) or not email.strip(): + raise AuthRejected(403, "no_identity", "the assertion names no person") + return Identity(normalize_email(email)) diff --git a/tests/remote_helpers.py b/tests/remote_helpers.py new file mode 100644 index 00000000..f18ab20b --- /dev/null +++ b/tests/remote_helpers.py @@ -0,0 +1,47 @@ +"""Signing keys and tokens for remote-MCP tests: a local stand-in for the +edge (Cloudflare Access) that signs identity assertions.""" + +from __future__ import annotations + +import json +import time + +import jwt +from cryptography.hazmat.primitives.asymmetric import rsa +from jwt.algorithms import RSAAlgorithm + +ISSUER = "https://team.example.cloudflareaccess.com" +AUD = "aud-tag-1" +JWKS_URL = ISSUER + "/cdn-cgi/access/certs" + + +class Signer: + def __init__(self, kid: str = "k1"): + self.kid = kid + self.key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + def jwk(self) -> dict: + d = json.loads(RSAAlgorithm.to_jwk(self.key.public_key())) + d["kid"] = self.kid + return d + + def token(self, email: str | None = "bob@acme.com", **overrides) -> str: + now = int(time.time()) + claims = {"iss": ISSUER, "aud": [AUD], "email": email, "iat": now, + "nbf": now, "exp": now + 600, "type": "app"} + claims.update(overrides) + claims = {k: v for k, v in claims.items() if v is not None} + return jwt.encode(claims, self.key, algorithm="RS256", headers={"kid": self.kid}) + + +SIGNER = Signer() + + +def make_verifier(*signers: Signer, fetch=None, clock=None): + from brain.remoteauth import AuthConfig, Verifier + + doc = {"keys": [s.jwk() for s in (signers or (SIGNER,))]} + kwargs = {"clock": clock} if clock is not None else {} + v = Verifier(AuthConfig(ISSUER, JWKS_URL, AUD), fetch=fetch or (lambda url: doc), **kwargs) + v.load() + return v diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 52c7e777..f4f6606b 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -161,3 +161,9 @@ def test_mcp_does_not_leak_the_revision_into_serverinfo(): A "(rev …)" suffix there would be a wire-format change, not a nicety. """ assert "rev" not in SERVER_INFO["version"] + + +def test_remote_extra_is_optional_and_carries_pyjwt(project): + extras = project["optional-dependencies"] + assert any(d.startswith("pyjwt[crypto]") for d in extras["remote"]) + assert not any(d.startswith("pyjwt") for d in project["dependencies"]) diff --git a/tests/test_remoteauth.py b/tests/test_remoteauth.py new file mode 100644 index 00000000..7432e0e5 --- /dev/null +++ b/tests/test_remoteauth.py @@ -0,0 +1,124 @@ +import time + +import jwt +import pytest + +from brain.remoteauth import ( + AuthConfig, + AuthRejected, + Identity, + RemoteAuthError, + Verifier, + auth_config, +) +from tests.remote_helpers import AUD, ISSUER, JWKS_URL, SIGNER, Signer, make_verifier + + +def _h(token): + return {"Cf-Access-Jwt-Assertion": token} + + +def test_valid_assertion_yields_normalized_email(): + v = make_verifier() + assert v.verify(_h(SIGNER.token(email=" Bob@Acme.com "))) == Identity("bob@acme.com") + + +def test_missing_assertion_is_401(): + with pytest.raises(AuthRejected) as e: + make_verifier().verify({}) + assert (e.value.status, e.value.code) == (401, "unauthenticated") + + +@pytest.mark.parametrize("override", [ + {"iss": "https://evil.example"}, + {"aud": ["someone-else"]}, + {"exp": int(time.time()) - 120}, +]) +def test_wrong_issuer_audience_or_expired_is_401(override): + with pytest.raises(AuthRejected) as e: + make_verifier().verify(_h(SIGNER.token(**override))) + assert e.value.status == 401 + + +def test_expiry_within_leeway_still_passes(): + assert make_verifier().verify(_h(SIGNER.token(exp=int(time.time()) - 30))) + + +def test_assertion_without_email_is_403_no_identity(): + with pytest.raises(AuthRejected) as e: + make_verifier().verify(_h(SIGNER.token(email=None))) + assert (e.value.status, e.value.code) == (403, "no_identity") + + +def test_hs256_token_is_refused(): + forged = jwt.encode({"iss": ISSUER, "aud": [AUD], "email": "bob@acme.com", + "exp": int(time.time()) + 600}, "secret", algorithm="HS256", + headers={"kid": "k1"}) + with pytest.raises(AuthRejected) as e: + make_verifier().verify(_h(forged)) + assert e.value.status == 401 + + +def test_unknown_kid_triggers_one_refetch_then_rate_limits(): + rotated = Signer(kid="k2") + docs = {"keys": [SIGNER.jwk()]} + calls = [] + + def fetch(url): + calls.append(url) + return docs + + now = [1000.0] + v = make_verifier(fetch=fetch, clock=lambda: now[0]) + assert len(calls) == 1 + docs["keys"] = [SIGNER.jwk(), rotated.jwk()] + now[0] += 61 + assert v.verify(_h(rotated.token())).email == "bob@acme.com" # refetched + assert len(calls) == 2 + stranger = Signer(kid="k3") + with pytest.raises(AuthRejected): + v.verify(_h(stranger.token())) # within 60 s of the last fetch: no refetch + assert len(calls) == 2 + + +def test_jwks_down_at_runtime_keeps_cached_keys(): + now = [1000.0] + state = {"down": False} + + def fetch(url): + if state["down"]: + raise OSError("unreachable") + return {"keys": [SIGNER.jwk()]} + + v = make_verifier(fetch=fetch, clock=lambda: now[0]) + state["down"] = True + now[0] += 13 * 3600 # past the 12 h forced refresh + assert v.verify(_h(SIGNER.token())).email == "bob@acme.com" + with pytest.raises(AuthRejected) as e: + v.verify(_h(Signer(kid="kx").token())) + assert e.value.status == 401 + + +def test_load_refuses_when_keys_unreachable_or_empty(): + cfg = AuthConfig(ISSUER, JWKS_URL, AUD) + with pytest.raises(RemoteAuthError): + Verifier(cfg, fetch=lambda url: (_ for _ in ()).throw(OSError("down"))).load() + with pytest.raises(RemoteAuthError): + Verifier(cfg, fetch=lambda url: {"keys": []}).load() + + +def test_auth_config_reads_env_and_names_what_is_missing(): + cfg = auth_config(environ={"BRAIN_MCP_ISSUER": ISSUER + "/", + "BRAIN_MCP_JWKS_URL": JWKS_URL, + "BRAIN_MCP_AUDIENCE": AUD}) + assert cfg == AuthConfig(ISSUER, JWKS_URL, AUD, "Cf-Access-Jwt-Assertion") + with pytest.raises(RemoteAuthError, match="BRAIN_MCP_AUDIENCE"): + auth_config(environ={"BRAIN_MCP_ISSUER": ISSUER, "BRAIN_MCP_JWKS_URL": JWKS_URL}) + with pytest.raises(RemoteAuthError, match="https"): + auth_config(issuer="http://x", jwks_url=JWKS_URL, audience=AUD, environ={}) + + +def test_flags_override_env(): + cfg = auth_config(audience="flag-aud", environ={"BRAIN_MCP_ISSUER": ISSUER, + "BRAIN_MCP_JWKS_URL": JWKS_URL, "BRAIN_MCP_AUDIENCE": "env-aud"}) + assert cfg.audience == "flag-aud" diff --git a/uv.lock b/uv.lock index ef8df874..60b83f4c 100644 --- a/uv.lock +++ b/uv.lock @@ -145,19 +145,110 @@ dependencies = [ [package.optional-dependencies] dev = [ + { name = "pyjwt", extra = ["crypto"] }, { name = "pytest" }, { name = "pytest-aiohttp" }, ] +remote = [ + { name = "pyjwt", extra = ["crypto"] }, +] [package.metadata] requires-dist = [ { name = "aiohttp", specifier = ">=3.14.3" }, + { name = "pyjwt", extras = ["crypto"], marker = "extra == 'dev'", specifier = ">=2.10" }, + { name = "pyjwt", extras = ["crypto"], marker = "extra == 'remote'", specifier = ">=2.10" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, { name = "pytest-aiohttp", marker = "extra == 'dev'", specifier = ">=1.0" }, { name = "pyyaml", specifier = ">=6.0" }, { name = "sqlite-vec", specifier = ">=0.1.9" }, ] -provides-extras = ["dev"] +provides-extras = ["dev", "remote"] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, +] [[package]] name = "colorama" @@ -168,6 +259,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" }, + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" }, + { url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" }, + { url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" }, +] + [[package]] name = "frozenlist" version = "1.8.0" @@ -486,6 +640,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3a/ed/1cdcab6ba3d6ab7feca11fc14f0eeea80755bb53ef4e892079f31b10a25f/propcache-0.5.2-py3-none-any.whl", hash = "sha256:be1ddfcbb376e3de5d2e2db1d58d6d67463e6b4f9f040c000de8e300295465fe", size = 14036, upload-time = "2026-05-08T21:02:10.673Z" }, ] +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + [[package]] name = "pygments" version = "2.20.0" @@ -495,6 +658,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, ] +[[package]] +name = "pyjwt" +version = "2.15.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, +] + +[package.optional-dependencies] +crypto = [ + { name = "cryptography" }, +] + [[package]] name = "pytest" version = "9.1.1" From a65c621f4ce38f2a51bd33126cf7068908de20c1 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:38:48 -0400 Subject: [PATCH 02/14] remoteauth: non-string kid is a 401; prove the failing-fetch path Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/remoteauth.py | 2 ++ tests/test_remoteauth.py | 22 +++++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/brain/remoteauth.py b/src/brain/remoteauth.py index a19b685a..3f774ea0 100644 --- a/src/brain/remoteauth.py +++ b/src/brain/remoteauth.py @@ -158,6 +158,8 @@ def verify(self, headers: Mapping[str, str]) -> Identity: kid = jwt.get_unverified_header(token).get("kid") except jwt.PyJWTError: raise AuthRejected(401, "unauthenticated", "malformed identity assertion") from None + if not isinstance(kid, str): + raise AuthRejected(401, "unauthenticated", "malformed identity assertion") key = self._keys.get(kid) if key is None: self._refresh() diff --git a/tests/test_remoteauth.py b/tests/test_remoteauth.py index 7432e0e5..e8413203 100644 --- a/tests/test_remoteauth.py +++ b/tests/test_remoteauth.py @@ -1,3 +1,5 @@ +import base64 +import json import time import jwt @@ -83,10 +85,12 @@ def fetch(url): def test_jwks_down_at_runtime_keeps_cached_keys(): now = [1000.0] - state = {"down": False} + state = {"down": False, "attempts": 0, "raised": 0} def fetch(url): + state["attempts"] += 1 if state["down"]: + state["raised"] += 1 raise OSError("unreachable") return {"keys": [SIGNER.jwk()]} @@ -94,9 +98,25 @@ def fetch(url): state["down"] = True now[0] += 13 * 3600 # past the 12 h forced refresh assert v.verify(_h(SIGNER.token())).email == "bob@acme.com" + assert state["raised"] == 1 # the forced refresh was attempted and failed + now[0] += 61 # clear the refetch rate limit so the next fetch really runs + before = state["attempts"] with pytest.raises(AuthRejected) as e: v.verify(_h(Signer(kid="kx").token())) assert e.value.status == 401 + assert state["attempts"] == before + 1 and state["raised"] == 2 + + +@pytest.mark.parametrize("kid", [[], {}, ["k1"], 5]) +def test_non_string_kid_is_401_not_500(kid): + def b64(d): + return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode() + + token = (b64({"alg": "RS256", "typ": "JWT", "kid": kid}) + "." + + b64({"iss": ISSUER, "aud": [AUD], "email": "bob@acme.com"}) + ".") + with pytest.raises(AuthRejected) as e: + make_verifier().verify(_h(token)) + assert (e.value.status, e.value.code) == (401, "unauthenticated") def test_load_refuses_when_keys_unreachable_or_empty(): From db1841891a1b4678c1e82c2271cf6ac7ba219808 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:39:29 -0400 Subject: [PATCH 03/14] spool: queue remote captures as atomic JSON envelopes Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/spool.py | 63 +++++++++++++++++++++++++++++++++++++++++++++ tests/test_spool.py | 45 ++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 src/brain/spool.py create mode 100644 tests/test_spool.py diff --git a/src/brain/spool.py b/src/brain/spool.py new file mode 100644 index 00000000..f050e771 --- /dev/null +++ b/src/brain/spool.py @@ -0,0 +1,63 @@ +"""Notes captured over remote MCP, waiting for the cycle to file them. + +The per-person MCP process must not write into the compiled vault: a raw write +dirties its git tree (the person's agent pushes bounce until the next cycle), +and a capture landing between the cycle's final write-back and the compile's +directory swap would be lost. So it drops a small JSON envelope here instead, +and ``brain cycle --spool-root`` files each one into master through +``ingest_note`` — the same path, write check and single-file commit the webhook +uses. Only the cycle ever touches master. +""" + +from __future__ import annotations + +import json +import os +import secrets +from datetime import datetime +from pathlib import Path + +from brain.errors import BrainError + +ENVELOPE_VERSION = 1 +MAX_TEXT = 20_000 +MAX_TITLE = 120 +MAX_PENDING = 200 +REJECTED_DIR = ".rejected" +_TMP_DIR = ".tmp" + + +class SpoolError(BrainError, ValueError): + """A capture the spool refuses; the message is shown to the person.""" + + +def pending_count(spool: Path) -> int: + return sum(1 for p in spool.glob("*.json") if p.is_file()) + + +def write_envelope(spool: Path, person: str, *, text: str, title: str, + now: datetime) -> str: + """Queue one capture atomically; return its file name. ``now`` is UTC.""" + if not isinstance(text, str) or not text.strip(): + raise SpoolError("nothing to capture — the text is empty") + if len(text) > MAX_TEXT: + raise SpoolError(f"the text is {len(text)} characters; the limit is {MAX_TEXT}") + title = (title or "").strip() + if "\n" in title or "\r" in title: + raise SpoolError("the title must be a single line") + if len(title) > MAX_TITLE: + raise SpoolError(f"the title is longer than {MAX_TITLE} characters") + if pending_count(spool) >= MAX_PENDING: + raise SpoolError("capture queue full — try again after the next sync") + + name = f"{now:%Y%m%dT%H%M%S}Z-{secrets.token_hex(4)}.json" + envelope = {"version": ENVELOPE_VERSION, "person": person, "title": title, + "body": text, "source": "mcp", "created": now.date().isoformat()} + tmp_dir = spool / _TMP_DIR + tmp_dir.mkdir(mode=0o700, exist_ok=True) + tmp = tmp_dir / name + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(envelope, f) + os.replace(tmp, spool / name) # a reader never sees half a file + return name diff --git a/tests/test_spool.py b/tests/test_spool.py new file mode 100644 index 00000000..f501ea88 --- /dev/null +++ b/tests/test_spool.py @@ -0,0 +1,45 @@ +import json +from datetime import UTC, datetime + +import pytest + +from brain import spool as sp +from brain.spool import SpoolError, pending_count, write_envelope + +NOW = datetime(2026, 10, 6, 14, 30, 5, tzinfo=UTC) + + +def test_write_envelope_is_one_complete_json_file(tmp_path): + name = write_envelope(tmp_path, "bob", text="Met Ana re: Lisbon", title="Lisbon", now=NOW) + assert name.startswith("20261006T143005Z-") and name.endswith(".json") + env = json.loads((tmp_path / name).read_text()) + assert env == {"version": 1, "person": "bob", "title": "Lisbon", + "body": "Met Ana re: Lisbon", "source": "mcp", "created": "2026-10-06"} + assert list((tmp_path / ".tmp").iterdir()) == [] # temp file renamed away + assert pending_count(tmp_path) == 1 + + +@pytest.mark.parametrize("text,title,match", [ + (" ", "", "empty"), + ("x" * (sp.MAX_TEXT + 1), "", "limit"), + ("ok", "two\nlines", "single line"), + ("ok", "t" * (sp.MAX_TITLE + 1), "longer"), +]) +def test_bad_input_writes_nothing(tmp_path, text, title, match): + with pytest.raises(SpoolError, match=match): + write_envelope(tmp_path, "bob", text=text, title=title, now=NOW) + assert pending_count(tmp_path) == 0 + + +def test_full_queue_refuses(tmp_path, monkeypatch): + monkeypatch.setattr(sp, "MAX_PENDING", 2) + write_envelope(tmp_path, "bob", text="a", title="", now=NOW) + write_envelope(tmp_path, "bob", text="b", title="", now=NOW) + with pytest.raises(SpoolError, match="queue full"): + write_envelope(tmp_path, "bob", text="c", title="", now=NOW) + + +def test_rejected_envelopes_do_not_count_as_pending(tmp_path): + (tmp_path / ".rejected").mkdir() + (tmp_path / ".rejected" / "old.json").write_text("{}") + assert pending_count(tmp_path) == 0 From 269ed39a7797c75ca2d145a587c2e2c8fad04020 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:41:27 -0400 Subject: [PATCH 04/14] mcp: serve one person's vault over HTTP behind the edge's identity Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/mcphttp.py | 245 ++++++++++++++++++++++++++++++++++++++++++ tests/test_mcphttp.py | 201 ++++++++++++++++++++++++++++++++++ 2 files changed, 446 insertions(+) create mode 100644 src/brain/mcphttp.py create mode 100644 tests/test_mcphttp.py diff --git a/src/brain/mcphttp.py b/src/brain/mcphttp.py new file mode 100644 index 00000000..86e0baed --- /dev/null +++ b/src/brain/mcphttp.py @@ -0,0 +1,245 @@ +"""Remote MCP over HTTP for ONE person's compiled vault (`brain mcp --http`). + +One process per person, bound to loopback, behind ``brain mcp-router`` and the +edge (Cloudflare Access). Every request must carry the edge's signed identity +and that identity must be this vault's owner — the router already checked, and +this re-check means a routing mistake is refused, never served. The MCP +methods themselves are ``brain.mcp._handle`` unchanged; this module is only +transport, identity and the ``brain_capture`` tool. + +The vault directory is replaced on every compile, so nothing here holds a path +handle between requests. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import math +import os +import threading +import time +from collections import deque +from collections.abc import Callable +from datetime import UTC, datetime +from pathlib import Path + +from aiohttp import web + +from brain.mcp import _TOOLS, _error, _handle, _result, _text_result +from brain.remoteauth import ( + AuthConfig, + AuthRejected, + RemoteAuthError, + Verifier, + normalize_email, +) + +log = logging.getLogger("brain.mcphttp") + +MAX_BODY = 1024 * 1024 +RATE_PER_S = 20.0 +BURST = 40.0 +CAPTURES_PER_HOUR = 60 +LOOPBACK = frozenset({"127.0.0.1", "::1", "localhost"}) + +CAPTURE_TOOL = { + "name": "brain_capture", + "description": "Save a note into your brain's Inbox — something worth keeping from this " + "conversation. It appears in your brain after the next sync (usually a few " + "minutes); your assistant files it from the Inbox.", + "inputSchema": { + "type": "object", + "properties": { + "text": {"type": "string", "description": "the note, in markdown"}, + "title": {"type": "string", "description": "optional one-line title"}, + }, + "required": ["text"], + }, +} + + +def http_error(status: int, code: str, message: str, *, + headers: dict | None = None) -> web.Response: + return web.json_response({"error": code, "message": message}, status=status, + headers=headers) + + +def check_vault_owner(vault: Path, person: str) -> None: + """The manifest is a tracked file an agent can push, so it is trusted + only together with the folder name (compiled vaults live at /) — + the same rule as server._corrections_person.""" + from brain.writeback import ManifestError, _load_manifest + + try: + pid = _load_manifest(vault).get("person", "") + except (ManifestError, OSError) as e: + raise RemoteAuthError(f"{vault} is not a compiled vault: {e}") from e + if pid != person: + raise RemoteAuthError(f"this vault belongs to {pid!r}, not {person!r}") + if vault.resolve().name != person: + raise RemoteAuthError(f"the vault folder must be named after its person ({person})") + + +def check_spool(spool: Path) -> None: + if spool.is_symlink() or not spool.is_dir(): + raise RemoteAuthError(f"spool {spool} is not a directory") + if spool.stat().st_uid != os.getuid(): + raise RemoteAuthError(f"spool {spool} is not owned by this user") + + +def _take(bucket: dict, now: float) -> int: + """Token bucket; 0 admits, else whole seconds until the next slot.""" + tokens = min(BURST, bucket["tokens"] + (now - bucket["at"]) * RATE_PER_S) + bucket["at"] = now + if tokens >= 1.0: + bucket["tokens"] = tokens - 1.0 + return 0 + bucket["tokens"] = tokens + return max(1, math.ceil((1.0 - tokens) / RATE_PER_S)) + + +def _capture(app: web.Application, args: dict) -> tuple[str, bool]: + from brain.spool import SpoolError, write_envelope + + with app["capture_lock"]: + now = app["clock"]() + recent: deque = app["captures"] + while recent and now - recent[0] > 3600: + recent.popleft() + if len(recent) >= CAPTURES_PER_HOUR: + return (f"capture limit reached ({CAPTURES_PER_HOUR} per hour) — try again later", + True) + try: + write_envelope(app["spool"], app["person"], text=args.get("text"), + title=args.get("title") or "", now=app["now"]()) + except SpoolError as e: + return str(e), True + recent.append(now) + saved = ("Saved. It will appear in your Inbox after the next sync " + "(usually within a few minutes).") + return saved, False + + +def _dispatch(app: web.Application, msg) -> dict | None: + if not isinstance(msg, dict): + return _error(None, -32600, "invalid request") + method, mid = msg.get("method"), msg.get("id") + params = msg.get("params") or {} + if app["spool"] is not None: + if method == "tools/list": + return _result(mid, {"tools": [*_TOOLS, CAPTURE_TOOL]}) + if method == "tools/call" and params.get("name") == "brain_capture": + args = params.get("arguments") or {} + if not isinstance(args.get("text"), str): + return _error(mid, -32602, "brain_capture: missing required argument(s): text") + text, is_err = _capture(app, args) + return _text_result(mid, text, is_err) + from brain.writeback import vault_shared + + vault: Path = app["vault"] + return _handle(vault, app["provider"], msg, vault_shared(vault)) + + +def _describe(msgs: list) -> str: + parts = [] + for m in msgs: + if not isinstance(m, dict): + parts.append("?") + elif m.get("method") == "tools/call": + parts.append(f"tools/call:{(m.get('params') or {}).get('name')}") + else: + parts.append(str(m.get("method"))) + return ",".join(parts) + + +async def handle_mcp(request: web.Request) -> web.StreamResponse: + app = request.app + if request.method != "POST": + return http_error(405, "method_not_allowed", "use POST", headers={"Allow": "POST"}) + if request.headers.get("Content-Encoding"): + return http_error(415, "unsupported_encoding", "compressed bodies are not accepted") + try: + ident = await asyncio.to_thread(app["verifier"].verify, request.headers) + except AuthRejected as e: + log.info("refused %s: %s", e.code, e.message) + return http_error(e.status, e.code, e.message) + if ident.email != app["email"]: + log.warning("routing error: %s reached %s's brain", ident.email, app["person"]) + return http_error(403, "wrong_person", "this brain belongs to someone else") + wait = _take(app["bucket"], app["clock"]()) + if wait: + return http_error(429, "rate_limited", "too many requests", + headers={"Retry-After": str(wait)}) + try: + raw = await request.read() + except web.HTTPRequestEntityTooLarge: + return http_error(413, "too_large", "request body too large") + try: + payload = json.loads(raw) + except (UnicodeDecodeError, json.JSONDecodeError): + return web.json_response(_error(None, -32700, "parse error"), status=400) + batch = isinstance(payload, list) + msgs = payload if batch else [payload] + if batch and not msgs: + return web.json_response(_error(None, -32600, "empty batch"), status=400) + started = time.perf_counter() + out = [] + for m in msgs: + r = await asyncio.to_thread(_dispatch, app, m) + if r is not None: + out.append(r) + log.info("%s %s %dms", ident.email, _describe(msgs), + (time.perf_counter() - started) * 1000) + if not out: + return web.Response(status=202) + return web.json_response(out if batch else out[0]) + + +async def handle_health(request: web.Request) -> web.Response: + return web.json_response({"ok": True}) + + +def create_vault_app(vault: Path, *, person: str, email: str, verifier: Verifier, + spool: Path | None = None, provider=None, + clock: Callable[[], float] = time.monotonic, + now: Callable[[], datetime] = lambda: datetime.now(UTC) + ) -> web.Application: + from brain.webhook import _security_headers + + app = web.Application(client_max_size=MAX_BODY, middlewares=[_security_headers]) + app["vault"] = Path(vault) + app["person"] = person + app["email"] = normalize_email(email) + app["verifier"] = verifier + app["spool"] = spool + app["provider"] = provider + app["clock"] = clock + app["now"] = now + app["bucket"] = {"tokens": BURST, "at": clock()} + app["captures"] = deque() + app["capture_lock"] = threading.Lock() + app.router.add_route("*", "/mcp", handle_mcp) + app.router.add_get("/healthz", handle_health) + return app + + +def run_vault_server(vault: Path, *, person: str, email: str, auth: AuthConfig, port: int, + host: str = "127.0.0.1", spool: Path | None = None) -> int: + if host not in LOOPBACK: + raise RemoteAuthError("brain mcp --http binds loopback only — the edge " + "(cloudflared) and brain mcp-router sit in front") + vault = Path(vault) + check_vault_owner(vault, person) + if spool is not None: + check_spool(spool) + verifier = Verifier(auth) + verifier.load() + from brain.embeddings import provider_from_config + + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s") + app = create_vault_app(vault, person=person, email=email, verifier=verifier, + spool=spool, provider=provider_from_config()) + web.run_app(app, host=host, port=port, print=None, access_log=None) + return 0 diff --git a/tests/test_mcphttp.py b/tests/test_mcphttp.py new file mode 100644 index 00000000..1bc93cc8 --- /dev/null +++ b/tests/test_mcphttp.py @@ -0,0 +1,201 @@ +import json +import os +from datetime import UTC, datetime +from pathlib import Path + +import pytest + +from brain import mcphttp +from brain.cli import main +from brain.mcphttp import check_vault_owner, create_vault_app, run_vault_server +from brain.remoteauth import AuthConfig, RemoteAuthError +from tests.remote_helpers import AUD, ISSUER, JWKS_URL, SIGNER, make_verifier +from tests.test_cli import seed_meta + +NOW = datetime(2026, 10, 6, 14, 30, tzinfo=UTC) + + +@pytest.fixture +def vault(master, tmp_path) -> Path: + seed_meta(master) + out = tmp_path / "compiled" + main(["compile", "--master", str(master), "--out", str(out)]) + return out / "bob" + + +def _hdr(email="bob@acme.com", header="Cf-Access-Jwt-Assertion"): + return {header: SIGNER.token(email=email), "Content-Type": "application/json"} + + +def _rpc(method, mid=1, **params): + msg = {"jsonrpc": "2.0", "method": method} + if mid is not None: + msg["id"] = mid + if params: + msg["params"] = params + return msg + + +@pytest.fixture +def make_client(aiohttp_client, vault): + async def _make(spool=None, **kw): + app = create_vault_app(vault, person="bob", email="Bob@Acme.com ", verifier=make_verifier(), + spool=spool, now=lambda: NOW, **kw) + return await aiohttp_client(app) + return _make + + +async def test_healthz_needs_no_identity(make_client): + c = await make_client() + r = await c.get("/healthz") + assert r.status == 200 and await r.json() == {"ok": True} + + +async def test_no_assertion_is_401_json(make_client): + c = await make_client() + r = await c.post("/mcp", json=_rpc("initialize")) + assert r.status == 401 and (await r.json())["error"] == "unauthenticated" + + +async def test_someone_elses_identity_is_403(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("tools/list")), headers=_hdr("alice@acme.com")) + assert r.status == 403 and (await r.json())["error"] == "wrong_person" + + +async def test_lowercase_header_name_is_accepted(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("initialize")), + headers=_hdr(header="cf-access-jwt-assertion")) + assert r.status == 200 + + +async def test_initialize_and_tools_list(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("initialize", protocolVersion="2025-06-18")), + headers=_hdr()) + assert (await r.json())["result"]["protocolVersion"] == "2025-06-18" + r = await c.post("/mcp", data=json.dumps(_rpc("tools/list", 2)), headers=_hdr()) + names = [t["name"] for t in (await r.json())["result"]["tools"]] + assert "brain_search" in names and "brain_capture" not in names + + +async def test_notification_only_is_202(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("notifications/initialized", mid=None)), + headers=_hdr()) + assert r.status == 202 + + +async def test_server_discover_gets_method_not_found_so_clients_fall_back(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("server/discover")), headers=_hdr()) + assert (await r.json())["error"]["code"] == -32601 + + +async def test_batch_returns_a_list(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps([_rpc("ping", 1), _rpc("tools/list", 2)]), + headers=_hdr()) + body = await r.json() + assert isinstance(body, list) and [m["id"] for m in body] == [1, 2] + + +@pytest.mark.parametrize("method,status,code", [("GET", 405, "method_not_allowed"), + ("DELETE", 405, "method_not_allowed")]) +async def test_non_post_is_405(make_client, method, status, code): + c = await make_client() + r = await c.request(method, "/mcp", headers=_hdr()) + assert r.status == status and (await r.json())["error"] == code + + +async def test_compressed_body_is_415(make_client): + c = await make_client() + r = await c.post("/mcp", data=b"x", headers={**_hdr(), "Content-Encoding": "gzip"}) + assert r.status == 415 + + +async def test_oversized_body_is_413(make_client): + c = await make_client() + r = await c.post("/mcp", data=b"x" * (mcphttp.MAX_BODY + 1), headers=_hdr()) + assert r.status == 413 and (await r.json())["error"] == "too_large" + + +async def test_bad_json_is_parse_error(make_client): + c = await make_client() + r = await c.post("/mcp", data=b"{nope", headers=_hdr()) + assert r.status == 400 and (await r.json())["error"]["code"] == -32700 + + +async def test_rate_limit_is_429_with_retry_after(make_client): + c = await make_client(clock=lambda: 5.0) + c.server.app["bucket"]["tokens"] = 0.0 + r = await c.post("/mcp", data=json.dumps(_rpc("ping")), headers=_hdr()) + assert r.status == 429 and int(r.headers["Retry-After"]) >= 1 + + +async def test_tool_call_reads_the_vault(make_client): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_read", + arguments={"rel_path": "People/bob/Memory.md"})), headers=_hdr()) + assert "Bob private memory" in (await r.json())["result"]["content"][0]["text"] + + +async def test_vault_swapped_between_requests_still_serves(make_client, vault, master): + c = await make_client() + main(["compile", "--master", str(master), "--out", str(vault.parent)]) # renames the dir + r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_read", + arguments={"rel_path": "People/bob/Memory.md"})), headers=_hdr()) + assert "Bob private memory" in (await r.json())["result"]["content"][0]["text"] + + +async def test_capture_is_listed_and_queues_one_envelope(make_client, tmp_path): + spool = tmp_path / "spool" + spool.mkdir() + c = await make_client(spool=spool) + r = await c.post("/mcp", data=json.dumps(_rpc("tools/list")), headers=_hdr()) + assert "brain_capture" in [t["name"] for t in (await r.json())["result"]["tools"]] + r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_capture", + arguments={"text": "Ana prefers aisle seats", "title": "Ana"})), headers=_hdr()) + result = (await r.json())["result"] + assert result["isError"] is False and "Saved" in result["content"][0]["text"] + [env] = [json.loads(p.read_text()) for p in spool.glob("*.json")] + assert env["person"] == "bob" and env["body"] == "Ana prefers aisle seats" + + +async def test_bad_capture_is_a_tool_error_and_writes_nothing(make_client, tmp_path): + spool = tmp_path / "spool" + spool.mkdir() + c = await make_client(spool=spool) + r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_capture", + arguments={"text": "x", "title": "a\nb"})), headers=_hdr()) + assert (await r.json())["result"]["isError"] is True + assert list(spool.glob("*.json")) == [] + + +async def test_capture_hourly_limit(make_client, tmp_path, monkeypatch): + monkeypatch.setattr(mcphttp, "CAPTURES_PER_HOUR", 1) + spool = tmp_path / "spool" + spool.mkdir() + c = await make_client(spool=spool, clock=lambda: 100.0) + call = json.dumps(_rpc("tools/call", name="brain_capture", arguments={"text": "x"})) + assert (await (await c.post("/mcp", data=call, headers=_hdr())).json())["result"]["isError"] is False + second = await (await c.post("/mcp", data=call, headers=_hdr())).json() + assert second["result"]["isError"] is True and "limit" in second["result"]["content"][0]["text"] + + +def test_vault_owner_must_match_manifest_and_folder(vault, tmp_path): + check_vault_owner(vault, "bob") + with pytest.raises(RemoteAuthError, match="belongs to"): + check_vault_owner(vault, "alice") + other = tmp_path / "alice" + os.rename(vault, other) + with pytest.raises(RemoteAuthError, match="named after"): + check_vault_owner(other, "bob") + + +def test_run_refuses_a_public_bind(vault): + cfg = AuthConfig(ISSUER, JWKS_URL, AUD) + with pytest.raises(RemoteAuthError, match="loopback"): + run_vault_server(vault, person="bob", email="bob@acme.com", auth=cfg, port=8901, + host="0.0.0.0") From c6d04dcc5a65eaf4c66ccea54800d4bc78d84960 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:45:49 -0400 Subject: [PATCH 05/14] cycle: file remote captures from the spool (--spool-root) Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/cli.py | 10 +++++- src/brain/cycle.py | 19 ++++++++++- src/brain/spool.py | 78 ++++++++++++++++++++++++++++++++++++++++++++- tests/test_cycle.py | 32 +++++++++++++++++++ tests/test_spool.py | 69 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 205 insertions(+), 3 deletions(-) diff --git a/src/brain/cli.py b/src/brain/cli.py index d9bd3036..9f51806c 100644 --- a/src/brain/cli.py +++ b/src/brain/cli.py @@ -413,7 +413,8 @@ def cmd_webhook(args) -> int: def cmd_cycle(args) -> int: report = run_cycle(Path(args.master), Path(args.out), - today=date.today().isoformat(), index=args.index) + today=date.today().isoformat(), index=args.index, + spool_root=Path(args.spool_root) if args.spool_root else None) if args.json: payload = asdict(report) payload["ok"] = report.ok @@ -433,6 +434,10 @@ def cmd_cycle(args) -> int: print(f"swept {report.swept} draft(s); " f"compiled {report.compiled} vault(s); " f"{report.pending} promotion(s) pending") + if report.spool_ingested or report.spool_rejected: + print(f"spool: {report.spool_ingested} filed, {report.spool_rejected} rejected") + for w in report.spool_warnings: + print(f" {w}", file=sys.stderr) for f in report.compile_failures: print(f" compile failed: {f}", file=sys.stderr) if report.promotion_decisions_applied or report.promotion_decisions_refused: @@ -878,6 +883,9 @@ def build_parser() -> argparse.ArgumentParser: y.add_argument("--json", action="store_true") y.add_argument("--index", action="store_true", help="also refresh each vault's search index after compile") + y.add_argument("--spool-root", default=None, metavar="DIR", + help="file remote-MCP captures queued under DIR// " + "(brain mcp --http --spool) into each person's Inbox") y.set_defaults(func=cmd_cycle) ix = sub.add_parser("index", help="build/refresh the search index for a compiled vault") diff --git a/src/brain/cycle.py b/src/brain/cycle.py index 708c3094..69a9d163 100644 --- a/src/brain/cycle.py +++ b/src/brain/cycle.py @@ -83,6 +83,10 @@ class CycleReport: # Grandfathering could not record this box's existing corrections; they # stay pending until a later cycle records them. Never fails the cycle. corrections_warnings: list[str] = field(default_factory=list) + # Remote captures filed from the spool this cycle (brain cycle --spool-root). + spool_ingested: int = 0 + spool_rejected: int = 0 + spool_warnings: list[str] = field(default_factory=list) # Wall time for the whole cycle, in milliseconds. # # A cycle that outgrows its own cron interval is the failure mode this @@ -247,7 +251,8 @@ def _writeback_one(master: Path, vault: Path, person, rules, *, now: str, applied=applied, held=held, error=error) -def run_cycle(master: Path, out_root: Path, today: str, *, index: bool = False) -> CycleReport: +def run_cycle(master: Path, out_root: Path, today: str, *, index: bool = False, + spool_root: Path | None = None) -> CycleReport: # First statement, so the measurement covers the whole run rather than # whatever part of it someone remembers to include. _started = time.monotonic() @@ -275,6 +280,15 @@ def lap(stage: str) -> None: f"existing corrections not recorded ({describe(e)}); they stay " "pending until the next cycle records them") lap("corrections") + # Before write-back and the compile, so a capture filed now is in the + # person's vault this same cycle. Only when asked: the stage's timing key + # is how an operator (Fleet) confirms the drain is wired. + spool_report = None + if spool_root is not None: + from brain.spool import drain_spools + + spool_report = drain_spools(spool_root, master, org, rules, shared=config.shared) + lap("spool") wb: dict[str, PersonWriteback] = {} already: dict[str, dict[str, str | None]] = {} @@ -448,6 +462,9 @@ def final_writeback(person) -> None: return CycleReport( duration_ms=duration_ms, timings_ms=timings, + spool_ingested=spool_report.ingested if spool_report else 0, + spool_rejected=spool_report.rejected if spool_report else 0, + spool_warnings=spool_report.warnings if spool_report else [], writebacks=writebacks, swept=swept, compiled=compiled, compile_failures=compile_failures, pending=pending, clients_created=sum(1 for p in provisioned if p.status == "created"), diff --git a/src/brain/spool.py b/src/brain/spool.py index f050e771..93e2a812 100644 --- a/src/brain/spool.py +++ b/src/brain/spool.py @@ -14,7 +14,8 @@ import json import os import secrets -from datetime import datetime +from dataclasses import dataclass, field +from datetime import date, datetime from pathlib import Path from brain.errors import BrainError @@ -61,3 +62,78 @@ def write_envelope(spool: Path, person: str, *, text: str, title: str, json.dump(envelope, f) os.replace(tmp, spool / name) # a reader never sees half a file return name + + +@dataclass +class DrainReport: + ingested: int = 0 + rejected: int = 0 + warnings: list[str] = field(default_factory=list) + + +def _reject(path: Path, report: DrainReport, why: str) -> None: + dest = path.parent / REJECTED_DIR + dest.mkdir(mode=0o700, exist_ok=True) + os.replace(path, dest / path.name) + report.rejected += 1 + report.warnings.append(f"spool: rejected {path.parent.name}/{path.name}: {why}") + + +def _envelope_problem(env, pid: str) -> str | None: + if not isinstance(env, dict) or env.get("version") != ENVELOPE_VERSION: + return "unknown envelope version" + if env.get("person") != pid: + return "envelope names a different person" + if not all(isinstance(env.get(k), str) for k in ("body", "title", "created")): + return "malformed envelope" + try: + # `created` becomes part of a file name in build_inbox_note — only a + # real ISO date may pass. + date.fromisoformat(env["created"]) + except ValueError: + return "bad created date" + return None + + +def drain_spools(spool_root: Path, master: Path, org, rules, *, shared: str) -> DrainReport: + """File every queued capture into master. Runs inside the cycle lock. + + A failure is moved to .rejected/ and reported, never retried: ingest_note + uses one error class for bad metadata and a failed commit, and retrying a + half-done ingest could file the note twice.""" + from brain.ingest import IngestError, ingest_note + + report = DrainReport() + if not spool_root.is_dir(): + report.warnings.append(f"spool: {spool_root} is not a directory — nothing drained") + return report + folders = sorted(p for p in spool_root.iterdir() + if p.is_dir() and not p.is_symlink() and not p.name.startswith(".")) + for folder in folders: + person = org.people.get(folder.name) + envelopes = sorted(p for p in folder.glob("*.json") + if p.is_file() and not p.is_symlink()) + for path in envelopes: + if person is None: + _reject(path, report, "not a person in org.yaml") + continue + try: + env = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e: + _reject(path, report, f"unreadable ({type(e).__name__})") + continue + problem = _envelope_problem(env, folder.name) + if problem: + _reject(path, report, problem) + continue + try: + ingest_note(master, person, rules, env["body"], + title=env["title"] or "Captured from Claude", source="mcp", + sender=person.email or person.id, created=env["created"], + shared=shared) + except IngestError as e: + _reject(path, report, str(e)) + continue + path.unlink() + report.ingested += 1 + return report diff --git a/tests/test_cycle.py b/tests/test_cycle.py index beefdf33..ab2fd896 100644 --- a/tests/test_cycle.py +++ b/tests/test_cycle.py @@ -1571,3 +1571,35 @@ def spy(master_path, *, today): out = _first_compile(master, tmp_path) run_cycle(master, out, today="2020-01-01") assert seen["today"] == datetime.now(UTC).date().isoformat() +def test_cycle_drains_the_spool_and_times_it(master, tmp_path): + seed_meta(master) + out = _first_compile(master, tmp_path) + root = tmp_path / "spool" + (root / "bob").mkdir(parents=True) + (root / "bob" / "20261006T143005Z-abcd1234.json").write_text(json.dumps( + {"version": 1, "person": "bob", "title": "Ana", "body": "aisle seats", + "source": "mcp", "created": "2026-10-06"})) + + report = run_cycle(master, out, today="2026-10-06", spool_root=root) + + assert report.spool_ingested == 1 and report.spool_rejected == 0 + assert list(report.timings_ms)[:2] == ["corrections", "spool"] + # filed into master before the compile, so bob's fresh vault already has it + assert list((out / "bob/People/bob/Inbox").glob("2026-10-06-ana*.md")) + + +def test_cycle_without_spool_root_has_no_spool_timing(master, tmp_path): + seed_meta(master) + out = _first_compile(master, tmp_path) + report = run_cycle(master, out, today="2026-10-06") + assert "spool" not in report.timings_ms and report.spool_ingested == 0 + + +def test_cli_cycle_accepts_spool_root(master, tmp_path, capsys): + seed_meta(master) + out = _first_compile(master, tmp_path) + (tmp_path / "spool").mkdir() + assert main(["cycle", "--master", str(master), "--out", str(out), + "--spool-root", str(tmp_path / "spool"), "--json"]) == 0 + payload = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert "spool" in payload["timings_ms"] diff --git a/tests/test_spool.py b/tests/test_spool.py index f501ea88..f9812c5f 100644 --- a/tests/test_spool.py +++ b/tests/test_spool.py @@ -43,3 +43,72 @@ def test_rejected_envelopes_do_not_count_as_pending(tmp_path): (tmp_path / ".rejected").mkdir() (tmp_path / ".rejected" / "old.json").write_text("{}") assert pending_count(tmp_path) == 0 +import subprocess + +from brain.schemas import load_org, load_spaces +from brain.spool import drain_spools +from tests.test_cli import seed_meta + + +def _drain(master, root): + org = load_org(master / "_meta/org.yaml") + rules = load_spaces(master / "_meta/spaces.yaml") + return drain_spools(root, master, org, rules, shared="Company") + + +def _queue(root, pid, **env): + d = root / pid + d.mkdir(parents=True, exist_ok=True) + base = {"version": 1, "person": pid, "title": "Ana", "body": "aisle seats", + "source": "mcp", "created": "2026-10-06"} + base.update(env) + p = d / "20261006T143005Z-abcd1234.json" + p.write_text(json.dumps(base)) + return p + + +def test_drain_files_a_capture_into_master_inbox_and_commits(master, tmp_path): + seed_meta(master) + root = tmp_path / "spool" + env = _queue(root, "bob") + report = _drain(master, root) + assert (report.ingested, report.rejected) == (1, 0) + assert not env.exists() + [note] = (master / "People/bob/Inbox").glob("2026-10-06-ana*.md") + text = note.read_text() + assert "source: mcp" in text and "from: bob@acme.com" in text and text.endswith("aisle seats") + log = subprocess.run(["git", "-C", str(master), "log", "-1", "--format=%an"], + capture_output=True, text=True).stdout.strip() + assert log == "Brain Ingest" + + +@pytest.mark.parametrize("pid,env,why", [ + ("mallory", {}, "not a person"), + ("bob", {"person": "alice"}, "different person"), + ("bob", {"version": 9}, "version"), + ("bob", {"body": 5}, "malformed"), + ("bob", {"created": "../../x"}, "created"), +]) +def test_drain_rejects_and_keeps_bad_envelopes(master, tmp_path, pid, env, why): + seed_meta(master) + root = tmp_path / "spool" + path = _queue(root, pid, **env) + report = _drain(master, root) + assert (report.ingested, report.rejected) == (0, 1) + assert (path.parent / ".rejected" / path.name).exists() + assert why in report.warnings[0] + assert not list(master.rglob("x.md")) + + +def test_drain_ignores_tmp_and_rejected_folders(master, tmp_path): + seed_meta(master) + root = tmp_path / "spool" + (root / "bob" / ".tmp").mkdir(parents=True) + (root / "bob" / ".tmp" / "half.json").write_text("{") + assert _drain(master, root).ingested == 0 + + +def test_drain_of_missing_root_warns(master, tmp_path): + seed_meta(master) + report = _drain(master, tmp_path / "nope") + assert report.ingested == 0 and "not a directory" in report.warnings[0] From 8ce69a51418d676608433d6fac72b1c566d01273 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:46:13 -0400 Subject: [PATCH 06/14] mcp-router: route each verified person to their own brain process Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/mcprouter.py | 175 ++++++++++++++++++++++++++++++++++++++++ tests/test_mcprouter.py | 106 ++++++++++++++++++++++++ 2 files changed, 281 insertions(+) create mode 100644 src/brain/mcprouter.py create mode 100644 tests/test_mcprouter.py diff --git a/src/brain/mcprouter.py b/src/brain/mcprouter.py new file mode 100644 index 00000000..0eb6cf86 --- /dev/null +++ b/src/brain/mcprouter.py @@ -0,0 +1,175 @@ +"""Route remote-MCP requests to the right person's brain (`brain mcp-router`). + +One per company, behind the edge. It verifies the edge's signed identity, +looks the email up in a route table the operator writes (Fleet), and forwards +to that person's ``brain mcp --http`` on loopback. It never opens a vault and +reads nothing under /srv/brain; the vault process re-verifies the identity, so +a wrong route is refused there rather than served. +""" + +from __future__ import annotations + +import asyncio +import logging +import time +from collections.abc import Callable +from pathlib import Path + +import aiohttp +import yaml +from aiohttp import web + +from brain.errors import BrainError +from brain.mcphttp import LOOPBACK, MAX_BODY, http_error +from brain.remoteauth import AuthConfig, AuthRejected, RemoteAuthError, Verifier, normalize_email + +log = logging.getLogger("brain.mcprouter") + +ROUTES_VERSION = 1 +RELOAD_CHECK_S = 1.0 +FORWARD_HEADERS = ("Content-Type", "Accept", "User-Agent", "Mcp-Method", "Mcp-Name", + "MCP-Protocol-Version", "Mcp-Session-Id") +RETURN_HEADERS = ("Content-Type", "Mcp-Session-Id", "Retry-After") + + +class RouteTableError(BrainError, ValueError): + """A route table the router cannot use.""" + + +def load_routes(path: Path) -> dict[str, int]: + try: + doc = yaml.safe_load(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, yaml.YAMLError) as e: + raise RouteTableError(f"{path}: {e}") from e + if not isinstance(doc, dict) or doc.get("version") != ROUTES_VERSION: + raise RouteTableError(f"{path}: expected `version: {ROUTES_VERSION}`") + routes = doc.get("routes") or {} + if not isinstance(routes, dict): + raise RouteTableError(f"{path}: `routes` must map email: port") + out: dict[str, int] = {} + for email, port in routes.items(): + if not isinstance(email, str) or "@" not in email: + raise RouteTableError(f"{path}: bad email {email!r}") + if isinstance(port, bool) or not isinstance(port, int) or not 1024 <= port <= 65535: + raise RouteTableError(f"{path}: {email}: port must be an integer 1024-65535") + key = normalize_email(email) + if key in out: + raise RouteTableError(f"{path}: {email} is listed twice") + out[key] = port + return out + + +class RouteTable: + """The route table, reloaded when the file changes (checked at most once a + second). A bad new file is logged and the last good table kept.""" + + def __init__(self, path: Path, *, clock: Callable[[], float] = time.monotonic): + self.path = Path(path) + self._clock = clock + self._routes = load_routes(self.path) + self._mtime = self.path.stat().st_mtime_ns + self._checked = clock() + + @property + def count(self) -> int: + return len(self._routes) + + def _maybe_reload(self) -> None: + now = self._clock() + if now - self._checked < RELOAD_CHECK_S: + return + self._checked = now + try: + mtime = self.path.stat().st_mtime_ns + except OSError as e: + log.error("route table unreadable, keeping the last good one: %s", e) + return + if mtime == self._mtime: + return + self._mtime = mtime + try: + self._routes = load_routes(self.path) + log.info("route table reloaded: %d route(s)", len(self._routes)) + except RouteTableError as e: + log.error("route table rejected, keeping the last good one: %s", e) + + def get(self, email: str) -> int | None: + self._maybe_reload() + return self._routes.get(normalize_email(email)) + + +async def handle_route(request: web.Request) -> web.StreamResponse: + app = request.app + if request.method != "POST": + return http_error(405, "method_not_allowed", "use POST", headers={"Allow": "POST"}) + if request.headers.get("Content-Encoding"): + return http_error(415, "unsupported_encoding", "compressed bodies are not accepted") + verifier: Verifier = app["verifier"] + try: + ident = await asyncio.to_thread(verifier.verify, request.headers) + except AuthRejected as e: + return http_error(e.status, e.code, e.message) + port = app["routes"].get(ident.email) + if port is None: + log.info("no route for %s", ident.email) + return http_error(403, "no_route", + f"No brain is set up for {ident.email}. Ask your admin.") + try: + body = await request.read() + except web.HTTPRequestEntityTooLarge: + return http_error(413, "too_large", "request body too large") + names = (*FORWARD_HEADERS, verifier.config.header) + headers = {h: request.headers[h] for h in names if h in request.headers} + try: + async with app["session"].post(f"http://127.0.0.1:{port}/mcp", data=body, + headers=headers) as up: + payload = await up.read() + back = {h: up.headers[h] for h in RETURN_HEADERS if h in up.headers} + return web.Response(status=up.status, body=payload, headers=back) + except (TimeoutError, aiohttp.ClientError) as e: + log.warning("upstream %d for %s unavailable: %s", port, ident.email, type(e).__name__) + return http_error(503, "upstream_unavailable", + "this brain is restarting — try again shortly", + headers={"Retry-After": "5"}) + + +async def handle_health(request: web.Request) -> web.Response: + return web.json_response({"ok": True, "routes": request.app["routes"].count}) + + +def create_router_app(routes: RouteTable, *, verifier: Verifier, + upstream_timeout: float = 30.0) -> web.Application: + from brain.webhook import _security_headers + + app = web.Application(client_max_size=MAX_BODY, middlewares=[_security_headers]) + app["routes"] = routes + app["verifier"] = verifier + + async def _open(app): + app["session"] = aiohttp.ClientSession( + timeout=aiohttp.ClientTimeout(total=upstream_timeout), auto_decompress=False) + + async def _close(app): + await app["session"].close() + + app.on_startup.append(_open) + app.on_cleanup.append(_close) + app.router.add_route("*", "/mcp", handle_route) + app.router.add_get("/healthz", handle_health) + return app + + +def run_router(routes_path: Path, *, auth: AuthConfig, port: int = 8900, + host: str = "127.0.0.1") -> int: + if host not in LOOPBACK: + raise RemoteAuthError("brain mcp-router binds loopback only — the edge " + "(cloudflared) sits in front") + # Verifier first: a missing [remote] extra must be the error a person + # sees, not a complaint about the routes file. + verifier = Verifier(auth) + table = RouteTable(Path(routes_path)) + verifier.load() + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s") + web.run_app(create_router_app(table, verifier=verifier), host=host, port=port, + print=None, access_log=None) + return 0 diff --git a/tests/test_mcprouter.py b/tests/test_mcprouter.py new file mode 100644 index 00000000..25343359 --- /dev/null +++ b/tests/test_mcprouter.py @@ -0,0 +1,106 @@ +import json +import os + +import pytest +from aiohttp import web + +from brain.mcprouter import RouteTable, RouteTableError, create_router_app, load_routes +from tests.remote_helpers import SIGNER, make_verifier + +H = "Cf-Access-Jwt-Assertion" + + +def _routes(tmp_path, routes, version=1): + p = tmp_path / "mcp-routes.yaml" + p.write_text(json.dumps({"version": version, "routes": routes})) # JSON is valid YAML + return p + + +@pytest.fixture +async def upstream(aiohttp_server): + seen = [] + + async def handler(request): + seen.append({"headers": dict(request.headers), "body": await request.read()}) + return web.json_response({"jsonrpc": "2.0", "id": 1, "result": {}}, + headers={"Mcp-Session-Id": "s1"}) + + app = web.Application() + app.router.add_post("/mcp", handler) + server = await aiohttp_server(app) + server.seen = seen + return server + + +async def _client(aiohttp_client, path): + return await aiohttp_client(create_router_app(RouteTable(path), verifier=make_verifier())) + + +async def test_routes_by_verified_email_and_passes_headers(aiohttp_client, upstream, tmp_path): + c = await _client(aiohttp_client, _routes(tmp_path, {"Bob@Acme.com ": upstream.port})) + r = await c.post("/mcp", data=b'{"jsonrpc":"2.0","id":1,"method":"ping"}', + headers={"cf-access-jwt-assertion": SIGNER.token(email="bob@acme.com"), + "Content-Type": "application/json", "Mcp-Method": "ping", + "User-Agent": "Claude-User", "Cookie": "secret=1"}) + assert r.status == 200 and r.headers["Mcp-Session-Id"] == "s1" + fwd = upstream.seen[0]["headers"] + assert fwd[H] and fwd["Mcp-Method"] == "ping" and fwd["User-Agent"] == "Claude-User" + assert "Cookie" not in fwd + + +async def test_unknown_email_is_403_no_route(aiohttp_client, upstream, tmp_path): + c = await _client(aiohttp_client, _routes(tmp_path, {"bob@acme.com": upstream.port})) + r = await c.post("/mcp", data=b"{}", headers={H: SIGNER.token(email="eve@acme.com")}) + body = await r.json() + assert r.status == 403 and body["error"] == "no_route" and "eve@acme.com" in body["message"] + assert upstream.seen == [] + + +async def test_identity_without_email_is_403_no_identity(aiohttp_client, upstream, tmp_path): + c = await _client(aiohttp_client, _routes(tmp_path, {"bob@acme.com": upstream.port})) + r = await c.post("/mcp", data=b"{}", headers={H: SIGNER.token(email=None)}) + assert r.status == 403 and (await r.json())["error"] == "no_identity" + + +async def test_no_assertion_is_401(aiohttp_client, tmp_path): + c = await _client(aiohttp_client, _routes(tmp_path, {})) + r = await c.post("/mcp", data=b"{}") + assert r.status == 401 + + +async def test_dead_upstream_is_503_with_retry_after(aiohttp_client, unused_tcp_port, tmp_path): + c = await _client(aiohttp_client, _routes(tmp_path, {"bob@acme.com": unused_tcp_port})) + r = await c.post("/mcp", data=b"{}", headers={H: SIGNER.token()}) + assert r.status == 503 and r.headers["Retry-After"] == "5" + assert (await r.json())["error"] == "upstream_unavailable" + + +async def test_healthz_counts_routes_without_naming_anyone(aiohttp_client, tmp_path): + c = await _client(aiohttp_client, _routes(tmp_path, {"bob@acme.com": 8901})) + assert await (await c.get("/healthz")).json() == {"ok": True, "routes": 1} + + +@pytest.mark.parametrize("routes,version,match", [ + ({"bob@acme.com": 80}, 1, "1024"), + ({"bob@acme.com": "8901"}, 1, "1024"), + ({"not-an-email": 8901}, 1, "email"), + ({"bob@acme.com": 8901, "BOB@acme.com": 8902}, 1, "twice"), + ({}, 2, "version"), +]) +def test_load_routes_rejects_bad_tables(tmp_path, routes, version, match): + with pytest.raises(RouteTableError, match=match): + load_routes(_routes(tmp_path, routes, version)) + + +def test_route_table_reloads_and_keeps_last_good_on_a_bad_file(tmp_path): + path = _routes(tmp_path, {"bob@acme.com": 8901}) + now = [0.0] + table = RouteTable(path, clock=lambda: now[0]) + path.write_text(json.dumps({"version": 1, "routes": {"bob@acme.com": 8902}})) + os.utime(path, ns=(10**18, 10**18)) + now[0] = 2.0 + assert table.get("bob@acme.com") == 8902 + path.write_text("version: [") + os.utime(path, ns=(2 * 10**18, 2 * 10**18)) + now[0] = 4.0 + assert table.get("bob@acme.com") == 8902 # last good kept From ba3ab1247c44dd7723b59eab3b109255800fc5f2 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:46:53 -0400 Subject: [PATCH 07/14] cli: brain mcp --http and brain mcp-router Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/cli.py | 72 +++++++++++++++++++++++++++++++++--- tests/test_cli_remote_mcp.py | 60 ++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 tests/test_cli_remote_mcp.py diff --git a/src/brain/cli.py b/src/brain/cli.py index 9f51806c..2fc6c86d 100644 --- a/src/brain/cli.py +++ b/src/brain/cli.py @@ -627,11 +627,45 @@ def cmd_facts(args) -> int: return 0 if not any(w.startswith(stale) for w in warnings) else 1 +def _remote_auth(args): + from brain.remoteauth import auth_config + + return auth_config(issuer=args.auth_issuer, jwks_url=args.auth_jwks_url, + audience=args.auth_audience, header=args.auth_header) + + def cmd_mcp(args) -> int: - from brain.mcp import serve + if not args.http: + from brain.mcp import serve - serve(Path(args.vault)) - return 0 + serve(Path(args.vault)) + return 0 + from brain import mcphttp + from brain.remoteauth import RemoteAuthError + + if not (args.person and args.person_email and args.port): + print("brain mcp --http needs --person, --person-email and --port", file=sys.stderr) + return 2 + try: + return mcphttp.run_vault_server( + Path(args.vault), person=args.person, email=args.person_email, + auth=_remote_auth(args), port=args.port, host=args.host, + spool=Path(args.spool) if args.spool else None) + except RemoteAuthError as e: + print(f"cannot start remote MCP: {e}", file=sys.stderr) + return 2 + + +def cmd_mcp_router(args) -> int: + from brain import mcprouter + from brain.remoteauth import RemoteAuthError + + try: + return mcprouter.run_router(Path(args.routes), auth=_remote_auth(args), + port=args.port, host=args.host) + except (RemoteAuthError, mcprouter.RouteTableError) as e: + print(f"cannot start remote MCP: {e}", file=sys.stderr) + return 2 def cmd_status(args) -> int: @@ -747,6 +781,14 @@ def _dashboard_serve(args) -> int: if args.corrections_master else None)) +def _add_remote_auth_args(p) -> None: + g = p.add_argument_group("identity (or BRAIN_MCP_* environment variables)") + g.add_argument("--auth-issuer", help="assertion issuer, e.g. https://.cloudflareaccess.com") + g.add_argument("--auth-jwks-url", help="signing keys URL, e.g. /cdn-cgi/access/certs") + g.add_argument("--auth-audience", help="the Access application's AUD tag") + g.add_argument("--auth-header", help="assertion header (default: Cf-Access-Jwt-Assertion)") + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="brain") # Answers "what is this box running?" over ssh or `docker exec`, which @@ -930,11 +972,31 @@ def build_parser() -> argparse.ArgumentParser: mc = sub.add_parser( "mcp", - help="run a stdio MCP server over a vault " - "(register: claude mcp add brain -- brain mcp --vault ~/brain)") + help="run an MCP server over a vault: stdio by default " + "(claude mcp add brain -- brain mcp --vault ~/brain), or --http for remote clients") mc.add_argument("--vault", required=True) + mc.add_argument("--http", action="store_true", + help="serve Streamable HTTP on loopback behind brain mcp-router and an " + "identity-asserting edge (needs brainkit[remote])") + mc.add_argument("--person", help="--http: the vault's owner (person id)") + mc.add_argument("--person-email", help="--http: the only identity this process serves") + mc.add_argument("--host", default="127.0.0.1", help="--http: loopback address") + mc.add_argument("--port", type=int, help="--http: port") + mc.add_argument("--spool", help="--http: enable brain_capture, queueing notes in this " + "directory for brain cycle --spool-root") + _add_remote_auth_args(mc) mc.set_defaults(func=cmd_mcp) + mr = sub.add_parser("mcp-router", + help="route remote-MCP requests to each person's brain mcp --http " + "(needs brainkit[remote])") + mr.add_argument("--routes", required=True, + help="route table: version: 1, routes: {email: port}") + mr.add_argument("--host", default="127.0.0.1") + mr.add_argument("--port", type=int, default=8900) + _add_remote_auth_args(mr) + mr.set_defaults(func=cmd_mcp_router) + st = sub.add_parser("status", help="counts, freshness and health for a vault or the whole company") lens = st.add_mutually_exclusive_group(required=True) diff --git a/tests/test_cli_remote_mcp.py b/tests/test_cli_remote_mcp.py new file mode 100644 index 00000000..d6d834f2 --- /dev/null +++ b/tests/test_cli_remote_mcp.py @@ -0,0 +1,60 @@ +import pytest + +from brain import mcphttp, mcprouter, remoteauth +from brain.cli import main + +ENV = {"BRAIN_MCP_ISSUER": "https://team.example.cloudflareaccess.com", + "BRAIN_MCP_JWKS_URL": "https://team.example.cloudflareaccess.com/cdn-cgi/access/certs", + "BRAIN_MCP_AUDIENCE": "aud-tag-1"} + + +@pytest.fixture +def env(monkeypatch): + for k, v in ENV.items(): + monkeypatch.setenv(k, v) + + +def test_http_mode_passes_env_auth_and_flags(env, monkeypatch, tmp_path): + seen = {} + monkeypatch.setattr(mcphttp, "run_vault_server", lambda vault, **kw: seen.update(kw, vault=vault) or 0) + rc = main(["mcp", "--http", "--vault", str(tmp_path / "bob"), "--person", "bob", + "--person-email", "bob@acme.com", "--port", "8901", "--spool", str(tmp_path)]) + assert rc == 0 + assert seen["person"] == "bob" and seen["port"] == 8901 and seen["spool"] == tmp_path + assert seen["auth"].audience == "aud-tag-1" + + +def test_http_mode_needs_person_email_and_port(env, capsys, tmp_path): + assert main(["mcp", "--http", "--vault", str(tmp_path)]) == 2 + assert "--person" in capsys.readouterr().err + + +def test_http_mode_without_identity_settings_refuses(monkeypatch, capsys, tmp_path): + for k in ENV: + monkeypatch.delenv(k, raising=False) + assert main(["mcp", "--http", "--vault", str(tmp_path), "--person", "bob", + "--person-email", "b@x.com", "--port", "8901"]) == 2 + assert "BRAIN_MCP_ISSUER" in capsys.readouterr().err + + +def test_missing_extra_is_named(env, monkeypatch, capsys, tmp_path): + def boom(): + raise remoteauth.RemoteAuthError("remote MCP needs the optional extra — install 'brainkit[remote]'") + monkeypatch.setattr(remoteauth, "_require_jwt", boom) + assert main(["mcp-router", "--routes", str(tmp_path / "r.yaml")]) == 2 + assert "brainkit[remote]" in capsys.readouterr().err + + +def test_router_passes_routes_and_port(env, monkeypatch, tmp_path): + seen = {} + monkeypatch.setattr(mcprouter, "run_router", lambda path, **kw: seen.update(kw, path=path) or 0) + assert main(["mcp-router", "--routes", str(tmp_path / "r.yaml")]) == 0 + assert seen["port"] == 8900 and seen["path"] == tmp_path / "r.yaml" + + +def test_stdio_mode_is_unchanged(monkeypatch, tmp_path): + called = {} + import brain.mcp as stdio + monkeypatch.setattr(stdio, "serve", lambda vault: called.setdefault("vault", vault)) + assert main(["mcp", "--vault", str(tmp_path)]) == 0 + assert called["vault"] == tmp_path From 95a878c719c16b101a0b99f3d2cc2f5db875435a Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:48:04 -0400 Subject: [PATCH 08/14] deploy: ship remote-MCP units; liveness checks template instances Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- deploy/brain-box/brain-liveness.sh | 8 ++- deploy/brain-box/brain-mcp-router.service | 34 ++++++++++++ deploy/brain-box/brain-mcp@.service | 43 +++++++++++++++ tests/test_deploy_brain_box.py | 64 +++++++++++++++++++++++ 4 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 deploy/brain-box/brain-mcp-router.service create mode 100644 deploy/brain-box/brain-mcp@.service create mode 100644 tests/test_deploy_brain_box.py diff --git a/deploy/brain-box/brain-liveness.sh b/deploy/brain-box/brain-liveness.sh index 1fcff6f8..63d1266b 100755 --- a/deploy/brain-box/brain-liveness.sh +++ b/deploy/brain-box/brain-liveness.sh @@ -16,9 +16,13 @@ # /usr/local/sbin/brain-liveness.sh >> /var/log/brain-liveness.log 2>&1 set -eu -: "${HEALTHCHECK_URL:?set HEALTHCHECK_URL (hc-ping.com check for this box's services)}" +: "${HEALTHCHECK_URL:?set HEALTHCHECK_URL (hc-ping.com check for this box services)}" -units="$(systemctl list-unit-files 'brain-*.service' --state=enabled --no-legend | awk '{print $1}')" +# Unit files list templates (brain-mcp@.service), which are never "active"; +# check the running instances of a template instead. +files="$(systemctl list-unit-files 'brain-*.service' --state=enabled --no-legend)" +live="$(systemctl list-units 'brain-*@*.service' --all --no-legend --plain)" +units="$(printf '%s\n%s\n' "$files" "$live" | awk '$1 != "" && $1 !~ /@[.]service$/ {print $1}')" down="" for u in $units ${EXTRA_UNITS:-}; do diff --git a/deploy/brain-box/brain-mcp-router.service b/deploy/brain-box/brain-mcp-router.service new file mode 100644 index 00000000..71a95eb4 --- /dev/null +++ b/deploy/brain-box/brain-mcp-router.service @@ -0,0 +1,34 @@ +# systemd unit: the company's remote-MCP router (`brain mcp-router`). +# Verifies the edge's identity and forwards each person to their own +# brain-mcp@. It holds no vault and can see nothing under /srv/brain. +# +# Needs brainkit[remote], /etc/brain/mcp.env (as brain-mcp@.service) and +# /etc/brain/mcp-routes.yaml: +# version: 1 +# routes: +# alice@acme.com: 8901 +# The router reloads the routes file when it changes; no restart needed. +# Point the edge tunnel (cloudflared) at http://127.0.0.1:8900. + +[Unit] +Description=brainkit remote MCP router +Documentation=https://github.com/joedanz/brainkit +After=network-online.target +Wants=network-online.target + +[Service] +User=brain +EnvironmentFile=/etc/brain/mcp.env +ExecStart=/usr/local/bin/brain mcp-router --routes /etc/brain/mcp-routes.yaml --port 8900 +Restart=on-failure +RestartSec=5 + +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=read-only +InaccessiblePaths=/srv/brain +PrivateTmp=true +MemoryMax=256M + +[Install] +WantedBy=multi-user.target diff --git a/deploy/brain-box/brain-mcp@.service b/deploy/brain-box/brain-mcp@.service new file mode 100644 index 00000000..0bbbb6f4 --- /dev/null +++ b/deploy/brain-box/brain-mcp@.service @@ -0,0 +1,43 @@ +# systemd template: one person's remote MCP server (`brain mcp --http`). +# Instance = person id: brain-mcp@alice serves /srv/brain/compiled/alice. +# +# Needs: +# - brainkit installed with the remote extra: uv tool install 'brainkit[remote] @ ...' +# - /etc/brain/mcp.env BRAIN_MCP_ISSUER, BRAIN_MCP_JWKS_URL, BRAIN_MCP_AUDIENCE +# - /etc/brain/mcp.d/.env BRAIN_MCP_PORT, BRAIN_MCP_EMAIL (the person's sign-in email) +# - /srv/brain/spool// a directory owned by User= (captures queue here; +# run the cycle with --spool-root /srv/brain/spool) +# - brain-mcp-router in front, and an identity-asserting edge (Cloudflare +# Access) in front of that. See docs/guides/remote-access. +# Adjust User= (and add the embedding EnvironmentFile) for your install, e.g. +# with a drop-in, then: systemctl enable --now brain-mcp@alice +# +# Why ReadWritePaths covers all of /srv/brain/compiled: each compile swaps the +# vault directory (a bind on the old one goes stale) and SQLite writes the WAL +# -shm file even for read-only opens. This is the same reach the per-person +# dashboard units have; the process itself serves only its one --vault. + +[Unit] +Description=brainkit remote MCP for %i +Documentation=https://github.com/joedanz/brainkit +After=network-online.target +Wants=network-online.target + +[Service] +User=brain +EnvironmentFile=/etc/brain/mcp.env +EnvironmentFile=/etc/brain/mcp.d/%i.env +ExecStart=/usr/local/bin/brain mcp --http --vault /srv/brain/compiled/%i --person %i --person-email ${BRAIN_MCP_EMAIL} --port ${BRAIN_MCP_PORT} --spool /srv/brain/spool/%i +Restart=on-failure +RestartSec=5 + +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths=/srv/brain/compiled /srv/brain/spool/%i +InaccessiblePaths=-/srv/brain/master +PrivateTmp=true +MemoryMax=512M + +[Install] +WantedBy=multi-user.target diff --git a/tests/test_deploy_brain_box.py b/tests/test_deploy_brain_box.py new file mode 100644 index 00000000..ace60f02 --- /dev/null +++ b/tests/test_deploy_brain_box.py @@ -0,0 +1,64 @@ +import os +import shlex +import stat +import subprocess +from pathlib import Path + +from brain.cli import build_parser + +BOX = Path(__file__).resolve().parents[1] / "deploy" / "brain-box" + + +def _execstart(unit: str) -> list[str]: + line = next(ln for ln in (BOX / unit).read_text().splitlines() if ln.startswith("ExecStart=")) + argv = shlex.split(line.removeprefix("ExecStart=")) + return [a.replace("%i", "alice").replace("${BRAIN_MCP_EMAIL}", "alice@acme.com") + .replace("${BRAIN_MCP_PORT}", "8901") for a in argv] + + +def test_person_unit_parses_against_the_real_cli(): + argv = _execstart("brain-mcp@.service") + assert argv[0] == "/usr/local/bin/brain" + args = build_parser().parse_args(argv[1:]) + assert args.http and args.person == "alice" and args.port == 8901 + assert args.vault == "/srv/brain/compiled/alice" and args.spool == "/srv/brain/spool/alice" + + +def test_router_unit_parses_and_cannot_see_brains(): + args = build_parser().parse_args(_execstart("brain-mcp-router.service")[1:]) + assert args.routes == "/etc/brain/mcp-routes.yaml" and args.port == 8900 + text = (BOX / "brain-mcp-router.service").read_text() + assert "InaccessiblePaths=/srv/brain" in text and "ReadWritePaths" not in text + + +def test_person_unit_reads_shared_and_per_person_env(): + text = (BOX / "brain-mcp@.service").read_text() + assert "EnvironmentFile=/etc/brain/mcp.env" in text + assert "EnvironmentFile=/etc/brain/mcp.d/%i.env" in text + assert "InaccessiblePaths=-/srv/brain/master" in text + + +def _fake(bin_dir: Path, name: str, script: str) -> None: + p = bin_dir / name + p.write_text("#!/bin/sh\n" + script) + p.chmod(p.stat().st_mode | stat.S_IEXEC) + + +def test_liveness_checks_instances_not_templates(tmp_path): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + log = tmp_path / "checked" + _fake(bin_dir, "systemctl", f""" +case "$1" in + list-unit-files) printf 'brain-admin.service enabled\\nbrain-mcp@.service enabled\\n' ;; + list-units) printf 'brain-mcp@alice.service loaded active running x\\n' ;; + is-active) echo "$3" >> {log}; exit 0 ;; +esac +""") + _fake(bin_dir, "curl", "exit 0\n") + env = {**os.environ, "PATH": f"{bin_dir}:{os.environ['PATH']}", + "HEALTHCHECK_URL": "https://hc.example/x"} + subprocess.run(["sh", str(BOX / "brain-liveness.sh")], env=env, check=True) + checked = log.read_text().split() + assert "brain-mcp@alice.service" in checked and "brain-admin.service" in checked + assert "brain-mcp@.service" not in checked From ca8c65da3fe86400223e874cd50268f7141505d4 Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:49:03 -0400 Subject: [PATCH 09/14] =?UTF-8?q?docs:=20remote=20access=20=E2=80=94=20con?= =?UTF-8?q?nect=20your=20brain=20in=20Claude?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- CHANGELOG.md | 17 +++ docs/docs.json | 1 + docs/guides/deployment.mdx | 6 ++ docs/guides/remote-access.mdx | 171 +++++++++++++++++++++++++++++++ docs/reference/cli.mdx | 33 +++++- docs/reference/configuration.mdx | 12 +++ 6 files changed, 238 insertions(+), 2 deletions(-) create mode 100644 docs/guides/remote-access.mdx diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b8c8690..629f1cc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,23 @@ explicitly under **Changed**, with what to do about it. ## [Unreleased] +### Added + +- **Connect your brain in Claude on the web and on your phone.** `brain mcp --http` + serves one person's brain over HTTPS, `brain mcp-router` gives a company one address + and sends each person to their own brain, and a new `brain_capture` tool saves a note + into the person's Inbox. Sign-in is handled by an identity edge in front (Cloudflare + Access is documented); brainkit only checks the signed identity it attaches. Saved + notes wait in a per-person spool, and `brain cycle --spool-root DIR` files them into + the Inbox. It needs the optional extra `brainkit[remote]`; nothing changes for a + deployment that doesn't use it. See [Remote Access](https://brainkit-docs.vercel.app/guides/remote-access). + +### Fixed + +- `brain-liveness.sh` no longer reports systemd template units (such as + `brain-mcp@.service`) as down, and now checks their running instances. Its + `HEALTHCHECK_URL` error message no longer breaks the script under macOS's `sh`. + ## [0.8.0] - 2026-10-05 ### Added diff --git a/docs/docs.json b/docs/docs.json index e302d839..9495427b 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -35,6 +35,7 @@ "getting-started", "guides/onboarding", "guides/per-employee-setup", + "guides/remote-access", "guides/graph-view", "guides/pages", "guides/getting-things-in", diff --git a/docs/guides/deployment.mdx b/docs/guides/deployment.mdx index e07a5026..659228f6 100644 --- a/docs/guides/deployment.mdx +++ b/docs/guides/deployment.mdx @@ -37,6 +37,12 @@ The tenant wall in this system is *physical*: it holds only where a personal age The compiler guarantees that a person's *vault* contains only what they may see. That guarantee is about what gets written to disk. It says nothing about what a process running as your OS user can `open()` elsewhere on that disk. Keeping agents to one-vault-per-host (device or container mount) is what preserves the boundary at runtime. + + [Remote access](/guides/remote-access) does not change this rule. `brain mcp-router` is not + a personal agent and holds no vault; each `brain mcp --http` process serves exactly one + person's compiled vault and answers only to that person. + + ## Server-side jobs are different The **server assistant** agent is *supposed* to have full master access — it ingests transcripts, routes knowledge, and maintains dashboards across all spaces. Run it with master access, on cron and on Inbox drops. The deployment rule above is about *personal* agents, which must never see more than their one slice. diff --git a/docs/guides/remote-access.mdx b/docs/guides/remote-access.mdx new file mode 100644 index 00000000..258407bf --- /dev/null +++ b/docs/guides/remote-access.mdx @@ -0,0 +1,171 @@ +--- +title: Remote Access +description: Connect each person's brain to Claude on the web and on their phone. +icon: plug +--- + +`brain mcp` over stdio only works for tools that can start a program on your own computer, like Claude Code. Claude on the web and in the phone app can only reach a server over HTTPS. Remote access gives each person a private address that Claude can reach, so they can search, read and save notes in their own brain from anywhere. + +One connector, one address per company. Everyone clicks **Connect** and signs in with their work email. + +## How it fits together + +``` +Claude (web, phone, Code) + │ HTTPS, signed in through your identity edge + ▼ +Cloudflare Access runs the sign-in (OAuth) and signs each request with who it came from + │ + ▼ +brain mcp-router checks the signature, finds that person's port (holds no vault) + │ + ├─▶ brain mcp --http (alice) reads only compiled/alice, saves only to spool/alice + └─▶ brain mcp --http (bob) reads only compiled/bob, saves only to spool/bob +``` + +brainkit does not run the sign-in. An identity edge in front of it does, and brainkit only checks the signed note the edge attaches to each request. Cloudflare Access is what this guide describes; the check is generic, so another edge that signs requests the same way works with a settings change. + + + **The tenant wall still holds.** Each `brain mcp --http` process is given exactly one + compiled vault and answers only to that person's email. The router never opens a vault. + Three separate checks stand between a request and a vault: the edge's list of allowed + emails, the router's route table, and the vault process's own pinned email. A wrong route + is refused, never served. See the [deployment rule](/guides/deployment). + + +## Connect in Claude + + + + On a Claude Team or Enterprise plan, an owner goes to **Settings → Connectors → Add + custom connector** and pastes the company address your admin gave you + (for example `https://mcp-acme.example.com/mcp`). Everyone in the organization then + sees it. On other plans, each person adds the same address themselves. + + + + Claude opens a sign-in page. Sign in with your work email. The first time, you'll be + asked to allow Claude to use your brain. + + + + Try "what changed in my brain this week?" or "save a note: Ana prefers aisle seats." + Notes you save appear in your Inbox after the next sync, usually within a few + minutes. + + + + + If the sign-in page says **Invalid nonce**, it just waited too long. Click **Connect** + again. + + +## What Claude can do + +The same six read tools as `brain mcp` (`brain_search`, `brain_read`, `brain_links`, +`brain_graph`, `brain_recent`, `brain_facts`), plus **`brain_capture`**, which saves a note +into your Inbox. Claude cannot edit or delete existing notes this way. + +## Set it up by hand + +If you run brainkit without Fleet, here is every piece. You need a Cloudflare account with +Zero Trust, and `brainkit[remote]` installed on the brain box: + +```bash +uv tool install 'brainkit[remote] @ git+https://github.com/joedanz/brainkit@' +``` + + + + 1. A tunnel that sends one hostname (say `mcp-acme.example.com`) to + `http://127.0.0.1:8900`. + 2. A **self-hosted Access application** on that hostname with **Managed OAuth** turned + on: dynamic client registration enabled, allowed redirect addresses + `https://claude.ai/api/mcp/auth_callback` and + `https://claude.com/api/mcp/auth_callback`, and localhost and loopback allowed (for + Claude Code). + 3. An **allow** policy listing your staff's work emails. + 4. Note the application's **AUD tag** and your team's address + (`https://.cloudflareaccess.com`). + + + + `/etc/brain/mcp.env` (no secrets in it): + + ```bash + BRAIN_MCP_ISSUER=https://.cloudflareaccess.com + BRAIN_MCP_JWKS_URL=https://.cloudflareaccess.com/cdn-cgi/access/certs + BRAIN_MCP_AUDIENCE= + ``` + + + + For each person (`alice` here), a settings file `/etc/brain/mcp.d/alice.env`: + + ```bash + BRAIN_MCP_PORT=8901 + BRAIN_MCP_EMAIL=alice@acme.com + ``` + + a spool folder for saved notes, owned by the user the service runs as: + + ```bash + install -d -o brain -m 0700 /srv/brain/spool/alice + ``` + + and the service: + + ```bash + install -m 644 deploy/brain-box/brain-mcp@.service /etc/systemd/system/ + systemctl enable --now brain-mcp@alice + ``` + + + + `/etc/brain/mcp-routes.yaml` maps each email to that person's port: + + ```yaml + version: 1 + routes: + alice@acme.com: 8901 + bob@acme.com: 8902 + ``` + + ```bash + install -m 644 deploy/brain-box/brain-mcp-router.service /etc/systemd/system/ + systemctl enable --now brain-mcp-router + ``` + + The router reloads this file when it changes. A broken edit is ignored and the last + good table stays in force. + + + + Add `--spool-root /srv/brain/spool` to the [`brain cycle`](/reference/cli#brain-cycle) + line in your cron. Saved notes are filed into each person's Inbox on the next cycle. + + + +Adjust `User=` in both unit files for your install, and add an `EnvironmentFile` for your +[embedding settings](/reference/configuration#embeddings) to the per-person unit if you +want semantic search. + +## Troubleshooting + +Each failed request returns a small JSON body: `{"error": "", "message": "..."}`. + +| Code | Status | What it means | +|---|---|---| +| `unauthenticated` | 401 | No signed identity, or it is expired or from the wrong place. Check `BRAIN_MCP_ISSUER` and `BRAIN_MCP_AUDIENCE`. | +| `no_identity` | 403 | The request was signed but names no person (for example a service token). | +| `no_route` | 403 | The email is not in the route table. Add it to `mcp-routes.yaml`. | +| `wrong_person` | 403 | The router sent a request to someone else's process. Check the ports in the route table. | +| `rate_limited` | 429 | Too many requests; retry after the `Retry-After` seconds. | +| `too_large` | 413 | The request was over 1 MB. | +| `unsupported_encoding` | 415 | Compressed request bodies are not accepted. | +| `method_not_allowed` | 405 | Use `POST`. | +| `upstream_unavailable` | 503 | That person's process is down or restarting. | + +If a person's brain does not answer, check `journalctl -u brain-mcp@` and +`curl http://127.0.0.1:/healthz`. If saved notes never appear, check that the cycle +runs with `--spool-root` and look in `/srv/brain/spool//.rejected/`. diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index a40f327e..4f2622cf 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -288,7 +288,7 @@ This command manages the *queue and direct revokes*; it doesn't create requests. Run the whole server-side loop once: write back every person's edits, provision any self-service [client requests](/concepts/spaces-and-permissions#self-service-client-spaces), route pending/auto-applied [share requests](/concepts/spaces-and-permissions#sharing-a-space) and apply any delegated decisions on them, sweep agent drafts into the promotions pending queue, then recompile all vaults. ```bash -brain cycle --master --out [--json] [--index] +brain cycle --master --out [--json] [--index] [--spool-root ] ``` | Flag | Required | Meaning | @@ -297,6 +297,7 @@ brain cycle --master --out [--json] [--index] | `--out` | yes | Compiled-vault root — the same `--out` you pass to `compile`. | | `--json` | no | Emit a single JSON summary object on stdout instead of human lines. | | `--index` | no | After recompiling, refresh each vault's search index (see [`brain index`](#brain-index)). Index failures warn but never fail the cycle. | +| `--spool-root` | no | File notes saved over [remote access](/guides/remote-access) (queued under `//` by `brain mcp --http --spool`) into each person's Inbox, before write-back and the compile. A saved note that cannot be filed moves to `//.rejected/` with a warning. Without this flag the stage is skipped. | ### The `--json` summary @@ -455,7 +456,35 @@ Register it once with a client — for Claude Code: claude mcp add brain -- brain mcp --vault ~/brain ``` -It exposes six read-only tools: `brain_search` (hybrid search, with an optional `center` note for graph-aware ranking), `brain_read` (read one file by relative path, refusing symlinks, `..` escapes, and anything outside a readable space), `brain_links` (a note's backlinks and outgoing wikilinks), `brain_graph` (a note's typed relations, each edge labeled with why it exists), `brain_recent` (recently changed notes, from the vault's git history), and `brain_facts` (time-stamped fact lines, current, as-of, or believed-on a date). It runs on the employee's device against their own vault clone, so it inherits the compiler's boundary. No HTTP, no OAuth — stdio only. +It exposes six read-only tools: `brain_search` (hybrid search, with an optional `center` note for graph-aware ranking), `brain_read` (read one file by relative path, refusing symlinks, `..` escapes, and anything outside a readable space), `brain_links` (a note's backlinks and outgoing wikilinks), `brain_graph` (a note's typed relations, each edge labeled with why it exists), `brain_recent` (recently changed notes, from the vault's git history), and `brain_facts` (time-stamped fact lines, current, as-of, or believed-on a date). It runs on the employee's device against their own vault clone, so it inherits the compiler's boundary. Plain `brain mcp` is stdio only — no HTTP, no OAuth. + +### Remote mode: `--http` + +For clients that can only reach a server over HTTPS (Claude on the web and on phones), `brain mcp --http` serves one person's compiled vault over HTTP on loopback. It needs the optional extra (`pip install 'brainkit[remote]'`) and sits behind [`brain mcp-router`](#brain-mcp-router) and an edge that signs each request with who it came from. See [Remote Access](/guides/remote-access). + +```bash +brain mcp --http --vault --person --person-email --port [--spool ] +``` + +| Flag | Meaning | +|---|---| +| `--http` | Serve Streamable HTTP instead of stdio. | +| `--person`, `--person-email` | The vault's owner. The process answers only to a request signed for this email, and refuses to start if the vault's manifest or folder name names someone else. | +| `--port` | Port to listen on (loopback only; `--host` accepts only loopback addresses). | +| `--spool` | Turn on the `brain_capture` tool, which queues saved notes in this folder for `brain cycle --spool-root`. | +| `--auth-issuer`, `--auth-jwks-url`, `--auth-audience`, `--auth-header` | The edge's identity settings. Each falls back to `BRAIN_MCP_ISSUER`, `BRAIN_MCP_JWKS_URL`, `BRAIN_MCP_AUDIENCE`, `BRAIN_MCP_HEADER` ([configuration](/reference/configuration#remote-access)). | + +It refuses to start, with exit code 2 and a one-line reason, when the identity settings are missing, the extra is not installed, or the bind address is not loopback. + +## `brain mcp-router` + +Route remote requests to each person's `brain mcp --http`. One per company. It checks the edge's signed identity, looks the email up in a route table, and forwards to that person's loopback port. It never opens a vault. + +```bash +brain mcp-router --routes /etc/brain/mcp-routes.yaml [--port 8900] +``` + +The routes file is `version: 1` plus `routes:` mapping each email to a port (1024–65535). The router reloads it when it changes and keeps the last good table if a new one is broken. It takes the same `--auth-*` settings as `brain mcp --http`. Unknown emails get a 403 `no_route`; a person whose process is down gets a 503 with `Retry-After`. ## `brain doctor` diff --git a/docs/reference/configuration.mdx b/docs/reference/configuration.mdx index 0c5cbd46..f54ceaba 100644 --- a/docs/reference/configuration.mdx +++ b/docs/reference/configuration.mdx @@ -276,6 +276,18 @@ at all the glob matches nothing and zsh will say so — there is nothing to delete in that state.) It leaves `retrieval-stats.json` and `retrieval-log.on` alone; neither is query text. +## Remote access + +Read by `brain mcp --http` and `brain mcp-router` (flags win over variables). Needs the optional extra: `pip install 'brainkit[remote]'`. See [Remote Access](/guides/remote-access). + +| Variable | Meaning | +|---|---| +| `BRAIN_MCP_ISSUER` | The edge's address, e.g. `https://.cloudflareaccess.com`. Must be `https://`. Signed requests must name this issuer. | +| `BRAIN_MCP_JWKS_URL` | Where the edge publishes its signing keys, e.g. `/cdn-cgi/access/certs`. Must be `https://`. Fetched at startup (the process refuses to start without them) and refreshed every 12 hours or when an unknown key appears. | +| `BRAIN_MCP_AUDIENCE` | The Access application's AUD tag. Signed requests must name it. | +| `BRAIN_MCP_HEADER` | Header carrying the signed identity. Default `Cf-Access-Jwt-Assertion`. | +| `BRAIN_MCP_PORT`, `BRAIN_MCP_EMAIL` | Used by the shipped `brain-mcp@.service` template: one person's port and sign-in email. | + ## Embeddings Retrieval's semantic leg needs an embedding provider. Without one, `brain index` and `brain search` still work in **keyword-only** mode — configure a provider to add the vector leg. Any OpenAI-compatible `/embeddings` endpoint works (OpenAI, Together, a company proxy, a local `llama-server`). From 3f8c8368a5ed18885e5a0896e36a3d2cac2477ad Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:49:58 -0400 Subject: [PATCH 10/14] mcp: name a missing [remote] extra first; add end-to-end remote test Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/mcphttp.py | 4 +- tests/test_mcphttp.py | 14 +++++++ tests/test_remote_e2e.py | 86 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 tests/test_remote_e2e.py diff --git a/src/brain/mcphttp.py b/src/brain/mcphttp.py index 86e0baed..4f8f1b88 100644 --- a/src/brain/mcphttp.py +++ b/src/brain/mcphttp.py @@ -231,10 +231,12 @@ def run_vault_server(vault: Path, *, person: str, email: str, auth: AuthConfig, raise RemoteAuthError("brain mcp --http binds loopback only — the edge " "(cloudflared) and brain mcp-router sit in front") vault = Path(vault) + # Verifier first: a box without the [remote] extra should be told to + # install it, not sent chasing vault problems it would hit next anyway. + verifier = Verifier(auth) check_vault_owner(vault, person) if spool is not None: check_spool(spool) - verifier = Verifier(auth) verifier.load() from brain.embeddings import provider_from_config diff --git a/tests/test_mcphttp.py b/tests/test_mcphttp.py index 1bc93cc8..2d5eb18a 100644 --- a/tests/test_mcphttp.py +++ b/tests/test_mcphttp.py @@ -199,3 +199,17 @@ def test_run_refuses_a_public_bind(vault): with pytest.raises(RemoteAuthError, match="loopback"): run_vault_server(vault, person="bob", email="bob@acme.com", auth=cfg, port=8901, host="0.0.0.0") + + +def test_run_names_the_missing_extra_before_vault_problems(monkeypatch, tmp_path): + """A box without brainkit[remote] should be told to install it, not sent + chasing a vault complaint it would hit next anyway.""" + from brain import remoteauth + + def no_jwt(): + raise RemoteAuthError("remote MCP needs the optional extra — install 'brainkit[remote]'") + + monkeypatch.setattr(remoteauth, "_require_jwt", no_jwt) + cfg = AuthConfig(ISSUER, JWKS_URL, AUD) + with pytest.raises(RemoteAuthError, match=r"brainkit\[remote\]"): + run_vault_server(tmp_path, person="bob", email="bob@acme.com", auth=cfg, port=8901) diff --git a/tests/test_remote_e2e.py b/tests/test_remote_e2e.py new file mode 100644 index 00000000..e2f47004 --- /dev/null +++ b/tests/test_remote_e2e.py @@ -0,0 +1,86 @@ +"""The whole remote path in one process: edge-signed request -> router -> +one person's vault server -> brain_capture -> spool -> cycle -> master Inbox.""" + +import json +from datetime import UTC, datetime + +import pytest + +from brain.cli import main +from brain.cycle import run_cycle +from brain.mcphttp import create_vault_app +from brain.mcprouter import RouteTable, create_router_app +from tests.remote_helpers import SIGNER, make_verifier +from tests.test_cli import seed_meta + +H = "Cf-Access-Jwt-Assertion" +NOW = datetime(2026, 10, 6, 14, 30, tzinfo=UTC) + + +def _rpc(method, mid=1, **params): + msg = {"jsonrpc": "2.0", "id": mid, "method": method} + if params: + msg["params"] = params + return json.dumps(msg) + + +@pytest.fixture +async def company(master, tmp_path, aiohttp_server, aiohttp_client): + seed_meta(master) + out = tmp_path / "compiled" + main(["compile", "--master", str(master), "--out", str(out)]) + spool_root = tmp_path / "spool" + ports = {} + for pid, email in (("alice", "alice@acme.com"), ("bob", "bob@acme.com")): + (spool_root / pid).mkdir(parents=True) + app = create_vault_app(out / pid, person=pid, email=email, verifier=make_verifier(), + spool=spool_root / pid, now=lambda: NOW) + ports[email] = (await aiohttp_server(app)).port + routes = tmp_path / "mcp-routes.yaml" + routes.write_text(json.dumps({"version": 1, "routes": ports})) + router = await aiohttp_client( + create_router_app(RouteTable(routes), verifier=make_verifier())) + return {"router": router, "master": master, "out": out, "spool": spool_root, + "routes": routes, "ports": ports} + + +async def _call(router, email, body): + return await router.post("/mcp", data=body, headers={H: SIGNER.token(email=email), + "Content-Type": "application/json"}) + + +async def test_each_person_reaches_only_their_own_brain(company): + r = await _call(company["router"], "bob@acme.com", _rpc( + "tools/call", name="brain_read", arguments={"rel_path": "People/bob/Memory.md"})) + assert "Bob private memory" in (await r.json())["result"]["content"][0]["text"] + + r = await _call(company["router"], "bob@acme.com", _rpc( + "tools/call", name="brain_read", arguments={"rel_path": "People/alice/Memory.md"})) + assert (await r.json())["result"]["isError"] is True # not in bob's vault + + +async def test_a_wrong_route_is_refused_by_the_vault_process(company): + """Route table mistake: alice's email points at bob's process.""" + routes = {"version": 1, "routes": {"alice@acme.com": company["ports"]["bob@acme.com"]}} + company["routes"].write_text(json.dumps(routes)) + company["router"].server.app["routes"]._checked = -10.0 # skip the 1 s reload throttle + r = await _call(company["router"], "alice@acme.com", _rpc("tools/list")) + assert r.status == 403 and (await r.json())["error"] == "wrong_person" + + +async def test_a_capture_reaches_the_master_inbox_through_the_cycle(company): + r = await _call(company["router"], "bob@acme.com", _rpc( + "tools/call", name="brain_capture", + arguments={"text": "Ana prefers aisle seats", "title": "Ana"})) + assert (await r.json())["result"]["isError"] is False + assert len(list((company["spool"] / "bob").glob("*.json"))) == 1 + + report = run_cycle(company["master"], company["out"], today="2026-10-06", + spool_root=company["spool"]) + + assert report.spool_ingested == 1 and report.spool_rejected == 0 + assert list((company["spool"] / "bob").glob("*.json")) == [] + [note] = (company["master"] / "People/bob/Inbox").glob("*ana*.md") + assert "source: mcp" in note.read_text() + assert list((company["out"] / "bob/People/bob/Inbox").glob("*ana*.md")) + assert not list((company["master"] / "People/alice/Inbox").glob("*ana*.md")) From 72220ebc56def11cc94e46f8710ed93248e666cb Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 11:59:06 -0400 Subject: [PATCH 11/14] spool: a bad capture can no longer stop the company cycle Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- docs/guides/remote-access.mdx | 6 ++++ docs/reference/cli.mdx | 2 +- pyproject.toml | 4 +-- src/brain/cycle.py | 8 ++++- src/brain/spool.py | 28 +++++++++++++++-- tests/test_cycle.py | 20 ++++++++++++ tests/test_packaging.py | 9 ++++++ tests/test_spool.py | 58 +++++++++++++++++++++++++++++++++++ uv.lock | 4 +-- 9 files changed, 131 insertions(+), 8 deletions(-) diff --git a/docs/guides/remote-access.mdx b/docs/guides/remote-access.mdx index 258407bf..ad2b35cd 100644 --- a/docs/guides/remote-access.mdx +++ b/docs/guides/remote-access.mdx @@ -113,6 +113,12 @@ uv tool install 'brainkit[remote] @ git+https://github.com/joedanz/brainkit@ + `brain cycle` must run as the same user that owns the spool (the unit's `User=`). + A spool the cycle can't read can't be emptied; the cycle prints a warning naming the + folder, and saved notes pile up until Claude says the queue is full. + + and the service: ```bash diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index 4f2622cf..97e19f28 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -297,7 +297,7 @@ brain cycle --master --out [--json] [--index] [--spool-root | `--out` | yes | Compiled-vault root — the same `--out` you pass to `compile`. | | `--json` | no | Emit a single JSON summary object on stdout instead of human lines. | | `--index` | no | After recompiling, refresh each vault's search index (see [`brain index`](#brain-index)). Index failures warn but never fail the cycle. | -| `--spool-root` | no | File notes saved over [remote access](/guides/remote-access) (queued under `//` by `brain mcp --http --spool`) into each person's Inbox, before write-back and the compile. A saved note that cannot be filed moves to `//.rejected/` with a warning. Without this flag the stage is skipped. | +| `--spool-root` | no | File notes saved over [remote access](/guides/remote-access) (queued under `//` by `brain mcp --http --spool`) into each person's Inbox, before write-back and the compile. A saved note that cannot be filed moves to `//.rejected/` with a warning. Run the cycle as the user that owns the spool, or the folder is skipped with a warning. A broken spool never stops the rest of the cycle. Without this flag the stage is skipped. | ### The `--json` summary diff --git a/pyproject.toml b/pyproject.toml index d957e092..3ecb9372 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,10 +50,10 @@ Issues = "https://github.com/joedanz/brainkit/issues" Source = "https://github.com/joedanz/brainkit" [project.optional-dependencies] -dev = ["pytest>=8.0", "pytest-aiohttp>=1.0", "pyjwt[crypto]>=2.10"] +dev = ["pytest>=8.0", "pytest-aiohttp>=1.0", "pyjwt[crypto]>=2.10.1"] # Remote MCP (`brain mcp --http`, `brain mcp-router`): verifies the signed # identity assertion an edge such as Cloudflare Access adds to each request. -remote = ["pyjwt[crypto]>=2.10"] +remote = ["pyjwt[crypto]>=2.10.1"] [project.scripts] brain = "brain.cli:main" diff --git a/src/brain/cycle.py b/src/brain/cycle.py index 69a9d163..426cdb97 100644 --- a/src/brain/cycle.py +++ b/src/brain/cycle.py @@ -287,7 +287,13 @@ def lap(stage: str) -> None: if spool_root is not None: from brain.spool import drain_spools - spool_report = drain_spools(spool_root, master, org, rules, shared=config.shared) + try: + spool_report = drain_spools(spool_root, master, org, rules, shared=config.shared) + except Exception as e: # a broken spool must never stop write-back and + # compile for everyone — same posture as triage and digest below + from brain.spool import DrainReport + + spool_report = DrainReport(warnings=[f"spool: drain failed ({type(e).__name__}: {e})"]) lap("spool") wb: dict[str, PersonWriteback] = {} diff --git a/src/brain/spool.py b/src/brain/spool.py index 93e2a812..e9e40eaa 100644 --- a/src/brain/spool.py +++ b/src/brain/spool.py @@ -48,6 +48,13 @@ def write_envelope(spool: Path, person: str, *, text: str, title: str, raise SpoolError("the title must be a single line") if len(title) > MAX_TITLE: raise SpoolError(f"the title is longer than {MAX_TITLE} characters") + # JSON allows a lone surrogate ("\\ud800"); no note can hold one, and the + # cycle must never meet it. + for value in (text, title): + try: + value.encode("utf-8") + except UnicodeEncodeError: + raise SpoolError("the text is not valid UTF-8 — remove unusual characters") from None if pending_count(spool) >= MAX_PENDING: raise SpoolError("capture queue full — try again after the next sync") @@ -86,6 +93,11 @@ def _envelope_problem(env, pid: str) -> str | None: return "envelope names a different person" if not all(isinstance(env.get(k), str) for k in ("body", "title", "created")): return "malformed envelope" + for key in ("body", "title"): + try: + env[key].encode("utf-8") + except UnicodeEncodeError: + return "text is not valid UTF-8" try: # `created` becomes part of a file name in build_inbox_note — only a # real ISO date may pass. @@ -111,6 +123,13 @@ def drain_spools(spool_root: Path, master: Path, org, rules, *, shared: str) -> if p.is_dir() and not p.is_symlink() and not p.name.startswith(".")) for folder in folders: person = org.people.get(folder.name) + if not os.access(folder, os.R_OK | os.W_OK | os.X_OK): + # glob() on an unreadable directory returns [] without a word, so + # say it here: the cycle must run as the user that owns the spool. + report.warnings.append( + f"spool: cannot read {folder} — captures for {folder.name} are not " + "being filed (the cycle must run as the user that owns the spool)") + continue envelopes = sorted(p for p in folder.glob("*.json") if p.is_file() and not p.is_symlink()) for path in envelopes: @@ -131,9 +150,14 @@ def drain_spools(spool_root: Path, master: Path, org, rules, *, shared: str) -> title=env["title"] or "Captured from Claude", source="mcp", sender=person.email or person.id, created=env["created"], shared=shared) - except IngestError as e: - _reject(path, report, str(e)) + except (IngestError, OSError, ValueError) as e: + # Not only IngestError: a write failure must cost one capture, + # never the company's cycle. Nothing retries a half-done ingest + # (it could file the note twice). + _reject(path, report, f"{type(e).__name__}: {e}") continue + # A crash between the ingest commit and this unlink files the note + # again next cycle; the window is a few microseconds. path.unlink() report.ingested += 1 return report diff --git a/tests/test_cycle.py b/tests/test_cycle.py index ab2fd896..b0c25f89 100644 --- a/tests/test_cycle.py +++ b/tests/test_cycle.py @@ -1603,3 +1603,23 @@ def test_cli_cycle_accepts_spool_root(master, tmp_path, capsys): "--spool-root", str(tmp_path / "spool"), "--json"]) == 0 payload = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) assert "spool" in payload["timings_ms"] + + +def test_a_broken_spool_never_stops_the_company_cycle(master, tmp_path, monkeypatch): + import brain.spool + + def boom(*a, **kw): + raise OSError("spool volume went away") + + monkeypatch.setattr(brain.spool, "drain_spools", boom) + seed_meta(master) + out = _first_compile(master, tmp_path) + (out / "bob/People/bob/Memory.md").write_text("Bob learned a thing.\n") + + report = run_cycle(master, out, today="2026-10-06", spool_root=tmp_path / "spool") + + assert report.compiled == 2 # write-back and compile still ran + assert (master / "People/bob/Memory.md").read_text() == "Bob learned a thing.\n" + assert report.spool_ingested == 0 + assert "spool volume went away" in report.spool_warnings[0] + assert "spool" in report.timings_ms diff --git a/tests/test_packaging.py b/tests/test_packaging.py index f4f6606b..36086607 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -167,3 +167,12 @@ def test_remote_extra_is_optional_and_carries_pyjwt(project): extras = project["optional-dependencies"] assert any(d.startswith("pyjwt[crypto]") for d in extras["remote"]) assert not any(d.startswith("pyjwt") for d in project["dependencies"]) + + +def test_pyjwt_floor_excludes_the_issuer_substring_bug(project): + """pyjwt 2.10.0 matched `iss` by substring (CVE-2024-53861) — the check this + feature relies on. uv tool install ignores the lock, so the floor must hold.""" + for deps in (project["optional-dependencies"]["remote"], + project["optional-dependencies"]["dev"]): + [dep] = [d for d in deps if d.startswith("pyjwt")] + assert ">=2.10.1" in dep diff --git a/tests/test_spool.py b/tests/test_spool.py index f9812c5f..8f2a47f8 100644 --- a/tests/test_spool.py +++ b/tests/test_spool.py @@ -112,3 +112,61 @@ def test_drain_of_missing_root_warns(master, tmp_path): seed_meta(master) report = _drain(master, tmp_path / "nope") assert report.ingested == 0 and "not a directory" in report.warnings[0] + + +def test_write_envelope_refuses_text_that_cannot_be_stored_as_utf8(tmp_path): + """JSON allows a lone surrogate ("\\ud800"); it cannot be written to a note.""" + with pytest.raises(SpoolError, match="UTF-8"): + write_envelope(tmp_path, "bob", text="hi \ud800", title="", now=NOW) + with pytest.raises(SpoolError, match="UTF-8"): + write_envelope(tmp_path, "bob", text="ok", title="t\ud800", now=NOW) + assert pending_count(tmp_path) == 0 + + +def test_drain_rejects_an_unencodable_envelope_and_leaves_no_stray_note(master, tmp_path): + seed_meta(master) + root = tmp_path / "spool" + path = _queue(root, "bob") + # hand-written escape: json.loads yields a lone surrogate + path.write_text('{"version":1,"person":"bob","title":"Ana","body":"hi \\ud800",' + '"source":"mcp","created":"2026-10-06"}') + report = _drain(master, root) + assert (report.ingested, report.rejected) == (0, 1) + assert (path.parent / ".rejected" / path.name).exists() + assert not list((master / "People/bob/Inbox").glob("*")) # no empty leftover file + + +def test_drain_survives_an_os_error_from_one_envelope(master, tmp_path, monkeypatch): + seed_meta(master) + root = tmp_path / "spool" + bad = _queue(root, "bob") + good = root / "bob" / "99999999T000000Z-zzzzzzzz.json" + good.write_text(bad.read_text()) + import brain.ingest as ingest + real = ingest.ingest_note + calls = [] + + def flaky(*a, **kw): + calls.append(1) + if len(calls) == 1: + raise OSError("disk full") + return real(*a, **kw) + + monkeypatch.setattr(ingest, "ingest_note", flaky) + report = _drain(master, root) + assert (report.ingested, report.rejected) == (1, 1) + assert "OSError" in report.warnings[0] + + +def test_drain_warns_when_a_person_folder_is_unreadable(master, tmp_path): + import os + seed_meta(master) + root = tmp_path / "spool" + _queue(root, "bob") + os.chmod(root / "bob", 0) + try: + report = _drain(master, root) + finally: + os.chmod(root / "bob", 0o700) + assert report.ingested == 0 + assert "bob" in report.warnings[0] and "cannot read" in report.warnings[0] diff --git a/uv.lock b/uv.lock index 60b83f4c..324ab03f 100644 --- a/uv.lock +++ b/uv.lock @@ -156,8 +156,8 @@ remote = [ [package.metadata] requires-dist = [ { name = "aiohttp", specifier = ">=3.14.3" }, - { name = "pyjwt", extras = ["crypto"], marker = "extra == 'dev'", specifier = ">=2.10" }, - { name = "pyjwt", extras = ["crypto"], marker = "extra == 'remote'", specifier = ">=2.10" }, + { name = "pyjwt", extras = ["crypto"], marker = "extra == 'dev'", specifier = ">=2.10.1" }, + { name = "pyjwt", extras = ["crypto"], marker = "extra == 'remote'", specifier = ">=2.10.1" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, { name = "pytest-aiohttp", marker = "extra == 'dev'", specifier = ">=1.0" }, { name = "pyyaml", specifier = ">=6.0" }, From 6f75423cfee485d0d77ccae6a7a828b88bc6f26f Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 12:11:37 -0400 Subject: [PATCH 12/14] remote MCP: harden bad-input, key-refresh, date and timeout edges; docs gaps Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- docs/guides/remote-access.mdx | 2 ++ docs/reference/cli.mdx | 2 +- src/brain/mcphttp.py | 12 ++++++++++-- src/brain/mcprouter.py | 2 +- src/brain/remoteauth.py | 9 ++++++++- src/brain/spool.py | 4 +++- tests/test_mcphttp.py | 32 ++++++++++++++++++++++++++++++++ tests/test_mcprouter.py | 25 +++++++++++++++++++++++++ tests/test_remoteauth.py | 24 ++++++++++++++++++++++++ tests/test_spool.py | 2 ++ 10 files changed, 108 insertions(+), 6 deletions(-) diff --git a/docs/guides/remote-access.mdx b/docs/guides/remote-access.mdx index ad2b35cd..e2be5279 100644 --- a/docs/guides/remote-access.mdx +++ b/docs/guides/remote-access.mdx @@ -75,6 +75,8 @@ Zero Trust, and `brainkit[remote]` installed on the brain box: uv tool install 'brainkit[remote] @ git+https://github.com/joedanz/brainkit@' ``` +The shipped units run `/usr/local/bin/brain`. `uv tool install` puts the program in the installing user's own folder, so link it once (`ln -s ~/.local/bin/brain /usr/local/bin/brain`), or change `ExecStart=` in both unit files to the real path (`which brain`). + 1. A tunnel that sends one hostname (say `mcp-acme.example.com`) to diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index 97e19f28..5eea94f0 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -474,7 +474,7 @@ brain mcp --http --vault --person --person-email | `--spool` | Turn on the `brain_capture` tool, which queues saved notes in this folder for `brain cycle --spool-root`. | | `--auth-issuer`, `--auth-jwks-url`, `--auth-audience`, `--auth-header` | The edge's identity settings. Each falls back to `BRAIN_MCP_ISSUER`, `BRAIN_MCP_JWKS_URL`, `BRAIN_MCP_AUDIENCE`, `BRAIN_MCP_HEADER` ([configuration](/reference/configuration#remote-access)). | -It refuses to start, with exit code 2 and a one-line reason, when the identity settings are missing, the extra is not installed, or the bind address is not loopback. +It refuses to start, with exit code 2 and a one-line reason, when the identity settings are missing, the extra is not installed, the signing keys can't be fetched from `--auth-jwks-url`, the bind address is not loopback, the vault is not a compiled vault or its manifest or folder name names someone other than `--person`, or the `--spool` folder is not a directory owned by the user running the process. ## `brain mcp-router` diff --git a/src/brain/mcphttp.py b/src/brain/mcphttp.py index 4f8f1b88..3816cf42 100644 --- a/src/brain/mcphttp.py +++ b/src/brain/mcphttp.py @@ -127,6 +127,10 @@ def _dispatch(app: web.Application, msg) -> dict | None: return _error(None, -32600, "invalid request") method, mid = msg.get("method"), msg.get("id") params = msg.get("params") or {} + if method == "tools/call": + arguments = params.get("arguments") if isinstance(params, dict) else None + if not isinstance(params, dict) or not (arguments is None or isinstance(arguments, dict)): + return _error(mid, -32602, "invalid params: expected an object") if app["spool"] is not None: if method == "tools/list": return _result(mid, {"tools": [*_TOOLS, CAPTURE_TOOL]}) @@ -134,6 +138,8 @@ def _dispatch(app: web.Application, msg) -> dict | None: args = params.get("arguments") or {} if not isinstance(args.get("text"), str): return _error(mid, -32602, "brain_capture: missing required argument(s): text") + if not isinstance(args.get("title") or "", str): + return _error(mid, -32602, "brain_capture: title must be a string") text, is_err = _capture(app, args) return _text_result(mid, text, is_err) from brain.writeback import vault_shared @@ -148,7 +154,9 @@ def _describe(msgs: list) -> str: if not isinstance(m, dict): parts.append("?") elif m.get("method") == "tools/call": - parts.append(f"tools/call:{(m.get('params') or {}).get('name')}") + params = m.get("params") + name = params.get("name") if isinstance(params, dict) else None + parts.append(f"tools/call:{name}") else: parts.append(str(m.get("method"))) return ",".join(parts) @@ -178,7 +186,7 @@ async def handle_mcp(request: web.Request) -> web.StreamResponse: return http_error(413, "too_large", "request body too large") try: payload = json.loads(raw) - except (UnicodeDecodeError, json.JSONDecodeError): + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError): return web.json_response(_error(None, -32700, "parse error"), status=400) batch = isinstance(payload, list) msgs = payload if batch else [payload] diff --git a/src/brain/mcprouter.py b/src/brain/mcprouter.py index 0eb6cf86..1dfbc488 100644 --- a/src/brain/mcprouter.py +++ b/src/brain/mcprouter.py @@ -138,7 +138,7 @@ async def handle_health(request: web.Request) -> web.Response: def create_router_app(routes: RouteTable, *, verifier: Verifier, - upstream_timeout: float = 30.0) -> web.Application: + upstream_timeout: float = 60.0) -> web.Application: from brain.webhook import _security_headers app = web.Application(client_max_size=MAX_BODY, middlewares=[_security_headers]) diff --git a/src/brain/remoteauth.py b/src/brain/remoteauth.py index 3f774ea0..4c70da9a 100644 --- a/src/brain/remoteauth.py +++ b/src/brain/remoteauth.py @@ -135,7 +135,12 @@ def _parse(self, doc) -> dict[str, object]: def _refresh(self) -> None: """Best effort, at most once per REFETCH_MIN_INTERVAL_S. A failed or empty fetch keeps the keys already held.""" - with self._lock: + # Non-blocking: if another request is already fetching (possibly against + # a hung endpoint), carry on with the keys we hold instead of queueing + # behind it and starving the server's thread pool. + if not self._lock.acquire(blocking=False): + return + try: now = self._clock() if now - self._attempted_at < REFETCH_MIN_INTERVAL_S: return @@ -146,6 +151,8 @@ def _refresh(self) -> None: return if keys: self._keys, self._loaded_at = keys, now + finally: + self._lock.release() def verify(self, headers: Mapping[str, str]) -> Identity: jwt = self._jwt diff --git a/src/brain/spool.py b/src/brain/spool.py index e9e40eaa..938b7812 100644 --- a/src/brain/spool.py +++ b/src/brain/spool.py @@ -101,7 +101,9 @@ def _envelope_problem(env, pid: str) -> str | None: try: # `created` becomes part of a file name in build_inbox_note — only a # real ISO date may pass. - date.fromisoformat(env["created"]) + # Round-trip: fromisoformat also accepts "20261006" and "2026-W41-1". + if date.fromisoformat(env["created"]).isoformat() != env["created"]: + return "bad created date" except ValueError: return "bad created date" return None diff --git a/tests/test_mcphttp.py b/tests/test_mcphttp.py index 2d5eb18a..b0ec9797 100644 --- a/tests/test_mcphttp.py +++ b/tests/test_mcphttp.py @@ -213,3 +213,35 @@ def no_jwt(): cfg = AuthConfig(ISSUER, JWKS_URL, AUD) with pytest.raises(RemoteAuthError, match=r"brainkit\[remote\]"): run_vault_server(tmp_path, person="bob", email="bob@acme.com", auth=cfg, port=8901) + + +@pytest.mark.parametrize("params", [5, "x", ["a"]]) +async def test_non_object_params_is_invalid_params_not_500(make_client, params): + c = await make_client() + msg = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params} + r = await c.post("/mcp", data=json.dumps(msg), headers=_hdr()) + assert r.status == 200 and (await r.json())["error"]["code"] == -32602 + + +@pytest.mark.parametrize("arguments", ["x", 5, ["a"]]) +async def test_non_object_arguments_is_invalid_params_not_500(make_client, arguments): + c = await make_client() + r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_search", + arguments=arguments)), headers=_hdr()) + assert r.status == 200 and (await r.json())["error"]["code"] == -32602 + + +async def test_non_string_capture_title_is_invalid_params_not_500(make_client, tmp_path): + spool = tmp_path / "spool" + spool.mkdir() + c = await make_client(spool=spool) + r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_capture", + arguments={"text": "ok", "title": 5})), headers=_hdr()) + assert r.status == 200 and (await r.json())["error"]["code"] == -32602 + assert list(spool.glob("*.json")) == [] + + +async def test_deeply_nested_json_is_a_parse_error_not_500(make_client): + c = await make_client() + r = await c.post("/mcp", data=b"[" * 200_000, headers=_hdr()) + assert r.status == 400 and (await r.json())["error"]["code"] == -32700 diff --git a/tests/test_mcprouter.py b/tests/test_mcprouter.py index 25343359..87e3a800 100644 --- a/tests/test_mcprouter.py +++ b/tests/test_mcprouter.py @@ -104,3 +104,28 @@ def test_route_table_reloads_and_keeps_last_good_on_a_bad_file(tmp_path): os.utime(path, ns=(2 * 10**18, 2 * 10**18)) now[0] = 4.0 assert table.get("bob@acme.com") == 8902 # last good kept + + +def test_upstream_timeout_covers_a_cold_first_search(): + """The first brain_search after a restart loads the index and embedding + provider lazily; Fleet allows that 60 s, so the router must not give up first.""" + import inspect + + assert inspect.signature(create_router_app).parameters["upstream_timeout"].default == 60.0 + + +async def test_slow_upstream_is_503_not_a_hang(aiohttp_client, aiohttp_server, tmp_path): + import asyncio + + async def slow(request): + await asyncio.sleep(1) + return web.json_response({}) + + app = web.Application() + app.router.add_post("/mcp", slow) + up = await aiohttp_server(app) + routes = RouteTable(_routes(tmp_path, {"bob@acme.com": up.port})) + c = await aiohttp_client(create_router_app(routes, verifier=make_verifier(), + upstream_timeout=0.2)) + r = await c.post("/mcp", data=b"{}", headers={H: SIGNER.token()}) + assert r.status == 503 and r.headers["Retry-After"] == "5" diff --git a/tests/test_remoteauth.py b/tests/test_remoteauth.py index e8413203..abcca250 100644 --- a/tests/test_remoteauth.py +++ b/tests/test_remoteauth.py @@ -142,3 +142,27 @@ def test_flags_override_env(): cfg = auth_config(audience="flag-aud", environ={"BRAIN_MCP_ISSUER": ISSUER, "BRAIN_MCP_JWKS_URL": JWKS_URL, "BRAIN_MCP_AUDIENCE": "env-aud"}) assert cfg.audience == "flag-aud" + + +def test_a_slow_key_fetch_never_blocks_other_requests(): + """While one request is mid-fetch (lock held), others must carry on with + the cached keys instead of queueing behind a hung endpoint.""" + import threading + + now = [1000.0] + v = make_verifier(clock=lambda: now[0]) + now[0] += 61 # a refresh is allowed + result = {} + + def call(): + try: + v.verify(_h(Signer(kid="unknown").token())) + except AuthRejected as e: + result["status"] = e.status + + with v._lock: # another request is "mid-fetch" + t = threading.Thread(target=call, daemon=True) + t.start() + t.join(2) + assert not t.is_alive(), "verify blocked behind an in-flight key fetch" + assert result["status"] == 401 diff --git a/tests/test_spool.py b/tests/test_spool.py index 8f2a47f8..f35305d1 100644 --- a/tests/test_spool.py +++ b/tests/test_spool.py @@ -88,6 +88,8 @@ def test_drain_files_a_capture_into_master_inbox_and_commits(master, tmp_path): ("bob", {"version": 9}, "version"), ("bob", {"body": 5}, "malformed"), ("bob", {"created": "../../x"}, "created"), + ("bob", {"created": "20261006"}, "created"), + ("bob", {"created": "2026-W41-1"}, "created"), ]) def test_drain_rejects_and_keeps_bad_envelopes(master, tmp_path, pid, env, why): seed_meta(master) From ad4d9ad91ae194532b8129f688df92d4f8c8682c Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 12:22:08 -0400 Subject: [PATCH 13/14] simplify: share the request preamble, email normalizer and test helpers One authenticate_post for the router and the vault server, one normalize_email (schemas), a default DrainReport in the cycle, a single shared RSA key for the tests, one JSON-RPC builder, and no HMAC warning. Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- src/brain/cycle.py | 14 ++++---- src/brain/mcphttp.py | 34 ++++++++++++++------ src/brain/mcprouter.py | 16 +++------- src/brain/remoteauth.py | 6 +--- src/brain/schemas.py | 7 +++- src/brain/spool.py | 6 ++-- tests/remote_helpers.py | 21 +++++++++++- tests/test_mcphttp.py | 69 +++++++++++++++------------------------- tests/test_mcprouter.py | 3 +- tests/test_remote_e2e.py | 12 ++----- tests/test_remoteauth.py | 2 +- 11 files changed, 96 insertions(+), 94 deletions(-) diff --git a/src/brain/cycle.py b/src/brain/cycle.py index 426cdb97..22dbd55a 100644 --- a/src/brain/cycle.py +++ b/src/brain/cycle.py @@ -283,16 +283,14 @@ def lap(stage: str) -> None: # Before write-back and the compile, so a capture filed now is in the # person's vault this same cycle. Only when asked: the stage's timing key # is how an operator (Fleet) confirms the drain is wired. - spool_report = None - if spool_root is not None: - from brain.spool import drain_spools + from brain.spool import DrainReport, drain_spools + spool_report = DrainReport() + if spool_root is not None: try: spool_report = drain_spools(spool_root, master, org, rules, shared=config.shared) except Exception as e: # a broken spool must never stop write-back and # compile for everyone — same posture as triage and digest below - from brain.spool import DrainReport - spool_report = DrainReport(warnings=[f"spool: drain failed ({type(e).__name__}: {e})"]) lap("spool") @@ -468,9 +466,9 @@ def final_writeback(person) -> None: return CycleReport( duration_ms=duration_ms, timings_ms=timings, - spool_ingested=spool_report.ingested if spool_report else 0, - spool_rejected=spool_report.rejected if spool_report else 0, - spool_warnings=spool_report.warnings if spool_report else [], + spool_ingested=spool_report.ingested, + spool_rejected=spool_report.rejected, + spool_warnings=spool_report.warnings, writebacks=writebacks, swept=swept, compiled=compiled, compile_failures=compile_failures, pending=pending, clients_created=sum(1 for p in provisioned if p.status == "created"), diff --git a/src/brain/mcphttp.py b/src/brain/mcphttp.py index 3816cf42..cdf96bdc 100644 --- a/src/brain/mcphttp.py +++ b/src/brain/mcphttp.py @@ -31,6 +31,7 @@ from brain.remoteauth import ( AuthConfig, AuthRejected, + Identity, RemoteAuthError, Verifier, normalize_email, @@ -117,9 +118,8 @@ def _capture(app: web.Application, args: dict) -> tuple[str, bool]: except SpoolError as e: return str(e), True recent.append(now) - saved = ("Saved. It will appear in your Inbox after the next sync " - "(usually within a few minutes).") - return saved, False + return ("Saved. It will appear in your Inbox after the next sync " + "(usually within a few minutes)."), False def _dispatch(app: web.Application, msg) -> dict | None: @@ -127,15 +127,16 @@ def _dispatch(app: web.Application, msg) -> dict | None: return _error(None, -32600, "invalid request") method, mid = msg.get("method"), msg.get("id") params = msg.get("params") or {} + args: dict = {} if method == "tools/call": arguments = params.get("arguments") if isinstance(params, dict) else None if not isinstance(params, dict) or not (arguments is None or isinstance(arguments, dict)): return _error(mid, -32602, "invalid params: expected an object") + args = arguments or {} if app["spool"] is not None: if method == "tools/list": return _result(mid, {"tools": [*_TOOLS, CAPTURE_TOOL]}) if method == "tools/call" and params.get("name") == "brain_capture": - args = params.get("arguments") or {} if not isinstance(args.get("text"), str): return _error(mid, -32602, "brain_capture: missing required argument(s): text") if not isinstance(args.get("title") or "", str): @@ -162,17 +163,30 @@ def _describe(msgs: list) -> str: return ",".join(parts) -async def handle_mcp(request: web.Request) -> web.StreamResponse: - app = request.app +async def authenticate_post(request: web.Request, verifier: Verifier + ) -> tuple[Identity | None, web.Response | None]: + """What both servers check before anything else: POST only, no compressed + body, and a valid signed identity. Returns (identity, None) or (None, the + refusal to send). Verification runs in a thread because a key refresh can + do blocking network I/O.""" if request.method != "POST": - return http_error(405, "method_not_allowed", "use POST", headers={"Allow": "POST"}) + return None, http_error(405, "method_not_allowed", "use POST", + headers={"Allow": "POST"}) if request.headers.get("Content-Encoding"): - return http_error(415, "unsupported_encoding", "compressed bodies are not accepted") + return None, http_error(415, "unsupported_encoding", + "compressed bodies are not accepted") try: - ident = await asyncio.to_thread(app["verifier"].verify, request.headers) + return await asyncio.to_thread(verifier.verify, request.headers), None except AuthRejected as e: log.info("refused %s: %s", e.code, e.message) - return http_error(e.status, e.code, e.message) + return None, http_error(e.status, e.code, e.message) + + +async def handle_mcp(request: web.Request) -> web.StreamResponse: + app = request.app + ident, refusal = await authenticate_post(request, app["verifier"]) + if refusal is not None: + return refusal if ident.email != app["email"]: log.warning("routing error: %s reached %s's brain", ident.email, app["person"]) return http_error(403, "wrong_person", "this brain belongs to someone else") diff --git a/src/brain/mcprouter.py b/src/brain/mcprouter.py index 1dfbc488..3f3f767a 100644 --- a/src/brain/mcprouter.py +++ b/src/brain/mcprouter.py @@ -9,7 +9,6 @@ from __future__ import annotations -import asyncio import logging import time from collections.abc import Callable @@ -20,8 +19,8 @@ from aiohttp import web from brain.errors import BrainError -from brain.mcphttp import LOOPBACK, MAX_BODY, http_error -from brain.remoteauth import AuthConfig, AuthRejected, RemoteAuthError, Verifier, normalize_email +from brain.mcphttp import LOOPBACK, MAX_BODY, authenticate_post, http_error +from brain.remoteauth import AuthConfig, RemoteAuthError, Verifier, normalize_email log = logging.getLogger("brain.mcprouter") @@ -100,15 +99,10 @@ def get(self, email: str) -> int | None: async def handle_route(request: web.Request) -> web.StreamResponse: app = request.app - if request.method != "POST": - return http_error(405, "method_not_allowed", "use POST", headers={"Allow": "POST"}) - if request.headers.get("Content-Encoding"): - return http_error(415, "unsupported_encoding", "compressed bodies are not accepted") verifier: Verifier = app["verifier"] - try: - ident = await asyncio.to_thread(verifier.verify, request.headers) - except AuthRejected as e: - return http_error(e.status, e.code, e.message) + ident, refusal = await authenticate_post(request, verifier) + if refusal is not None: + return refusal port = app["routes"].get(ident.email) if port is None: log.info("no route for %s", ident.email) diff --git a/src/brain/remoteauth.py b/src/brain/remoteauth.py index 4c70da9a..65216edd 100644 --- a/src/brain/remoteauth.py +++ b/src/brain/remoteauth.py @@ -21,6 +21,7 @@ from dataclasses import dataclass from brain.errors import BrainError +from brain.schemas import normalize_email from brain.version import __version__ DEFAULT_HEADER = "Cf-Access-Jwt-Assertion" @@ -57,11 +58,6 @@ class Identity: email: str -def normalize_email(value: str) -> str: - """The comparison Org.person_by_email uses: case- and whitespace-insensitive.""" - return value.strip().lower() - - def auth_config(*, issuer: str | None = None, jwks_url: str | None = None, audience: str | None = None, header: str | None = None, environ: Mapping[str, str] | None = None) -> AuthConfig: diff --git a/src/brain/schemas.py b/src/brain/schemas.py index cc49a325..4e0f4d25 100644 --- a/src/brain/schemas.py +++ b/src/brain/schemas.py @@ -187,6 +187,11 @@ def is_admin(self) -> bool: return "admin" in self.roles +def normalize_email(value: str) -> str: + """The one way emails are compared: case- and whitespace-insensitive.""" + return value.strip().lower() + + @dataclass(frozen=True) class Org: people: dict[str, Person] @@ -196,7 +201,7 @@ def person_by_email(self, email: str) -> Person | None: An empty needle never matches (people without an email have ""). """ - needle = email.strip().lower() + needle = normalize_email(email) if not needle: return None for p in self.people.values(): diff --git a/src/brain/spool.py b/src/brain/spool.py index 938b7812..1d94cbab 100644 --- a/src/brain/spool.py +++ b/src/brain/spool.py @@ -99,9 +99,9 @@ def _envelope_problem(env, pid: str) -> str | None: except UnicodeEncodeError: return "text is not valid UTF-8" try: - # `created` becomes part of a file name in build_inbox_note — only a - # real ISO date may pass. - # Round-trip: fromisoformat also accepts "20261006" and "2026-W41-1". + # `created` becomes part of a file name in build_inbox_note, so only a + # canonical YYYY-MM-DD may pass (fromisoformat alone also accepts + # "20261006" and "2026-W41-1"). if date.fromisoformat(env["created"]).isoformat() != env["created"]: return "bad created date" except ValueError: diff --git a/tests/remote_helpers.py b/tests/remote_helpers.py index f18ab20b..01e2ee04 100644 --- a/tests/remote_helpers.py +++ b/tests/remote_helpers.py @@ -5,6 +5,7 @@ import json import time +from datetime import UTC, datetime import jwt from cryptography.hazmat.primitives.asymmetric import rsa @@ -15,10 +16,28 @@ JWKS_URL = ISSUER + "/cdn-cgi/access/certs" +HEADER = "Cf-Access-Jwt-Assertion" +NOW = datetime(2026, 10, 6, 14, 30, tzinfo=UTC) + +# 2048-bit key generation dominates these tests' runtime, so every Signer +# shares one key; tests that need "a different signer" differ by kid. +_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +def rpc(method: str, mid: int | None = 1, **params) -> dict: + """One JSON-RPC request; mid=None makes it a notification.""" + msg = {"jsonrpc": "2.0", "method": method} + if mid is not None: + msg["id"] = mid + if params: + msg["params"] = params + return msg + + class Signer: def __init__(self, kid: str = "k1"): self.kid = kid - self.key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + self.key = _KEY def jwk(self) -> dict: d = json.loads(RSAAlgorithm.to_jwk(self.key.public_key())) diff --git a/tests/test_mcphttp.py b/tests/test_mcphttp.py index b0ec9797..1cef1480 100644 --- a/tests/test_mcphttp.py +++ b/tests/test_mcphttp.py @@ -1,6 +1,5 @@ import json import os -from datetime import UTC, datetime from pathlib import Path import pytest @@ -9,11 +8,9 @@ from brain.cli import main from brain.mcphttp import check_vault_owner, create_vault_app, run_vault_server from brain.remoteauth import AuthConfig, RemoteAuthError -from tests.remote_helpers import AUD, ISSUER, JWKS_URL, SIGNER, make_verifier +from tests.remote_helpers import AUD, ISSUER, JWKS_URL, NOW, SIGNER, make_verifier, rpc from tests.test_cli import seed_meta -NOW = datetime(2026, 10, 6, 14, 30, tzinfo=UTC) - @pytest.fixture def vault(master, tmp_path) -> Path: @@ -27,15 +24,6 @@ def _hdr(email="bob@acme.com", header="Cf-Access-Jwt-Assertion"): return {header: SIGNER.token(email=email), "Content-Type": "application/json"} -def _rpc(method, mid=1, **params): - msg = {"jsonrpc": "2.0", "method": method} - if mid is not None: - msg["id"] = mid - if params: - msg["params"] = params - return msg - - @pytest.fixture def make_client(aiohttp_client, vault): async def _make(spool=None, **kw): @@ -53,60 +41,59 @@ async def test_healthz_needs_no_identity(make_client): async def test_no_assertion_is_401_json(make_client): c = await make_client() - r = await c.post("/mcp", json=_rpc("initialize")) + r = await c.post("/mcp", json=rpc("initialize")) assert r.status == 401 and (await r.json())["error"] == "unauthenticated" async def test_someone_elses_identity_is_403(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("tools/list")), headers=_hdr("alice@acme.com")) + r = await c.post("/mcp", data=json.dumps(rpc("tools/list")), headers=_hdr("alice@acme.com")) assert r.status == 403 and (await r.json())["error"] == "wrong_person" async def test_lowercase_header_name_is_accepted(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("initialize")), + r = await c.post("/mcp", data=json.dumps(rpc("initialize")), headers=_hdr(header="cf-access-jwt-assertion")) assert r.status == 200 async def test_initialize_and_tools_list(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("initialize", protocolVersion="2025-06-18")), + r = await c.post("/mcp", data=json.dumps(rpc("initialize", protocolVersion="2025-06-18")), headers=_hdr()) assert (await r.json())["result"]["protocolVersion"] == "2025-06-18" - r = await c.post("/mcp", data=json.dumps(_rpc("tools/list", 2)), headers=_hdr()) + r = await c.post("/mcp", data=json.dumps(rpc("tools/list", 2)), headers=_hdr()) names = [t["name"] for t in (await r.json())["result"]["tools"]] assert "brain_search" in names and "brain_capture" not in names async def test_notification_only_is_202(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("notifications/initialized", mid=None)), + r = await c.post("/mcp", data=json.dumps(rpc("notifications/initialized", mid=None)), headers=_hdr()) assert r.status == 202 async def test_server_discover_gets_method_not_found_so_clients_fall_back(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("server/discover")), headers=_hdr()) + r = await c.post("/mcp", data=json.dumps(rpc("server/discover")), headers=_hdr()) assert (await r.json())["error"]["code"] == -32601 async def test_batch_returns_a_list(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps([_rpc("ping", 1), _rpc("tools/list", 2)]), + r = await c.post("/mcp", data=json.dumps([rpc("ping", 1), rpc("tools/list", 2)]), headers=_hdr()) body = await r.json() assert isinstance(body, list) and [m["id"] for m in body] == [1, 2] -@pytest.mark.parametrize("method,status,code", [("GET", 405, "method_not_allowed"), - ("DELETE", 405, "method_not_allowed")]) -async def test_non_post_is_405(make_client, method, status, code): +@pytest.mark.parametrize("method", ["GET", "DELETE"]) +async def test_non_post_is_405(make_client, method): c = await make_client() r = await c.request(method, "/mcp", headers=_hdr()) - assert r.status == status and (await r.json())["error"] == code + assert r.status == 405 and (await r.json())["error"] == "method_not_allowed" async def test_compressed_body_is_415(make_client): @@ -130,13 +117,13 @@ async def test_bad_json_is_parse_error(make_client): async def test_rate_limit_is_429_with_retry_after(make_client): c = await make_client(clock=lambda: 5.0) c.server.app["bucket"]["tokens"] = 0.0 - r = await c.post("/mcp", data=json.dumps(_rpc("ping")), headers=_hdr()) + r = await c.post("/mcp", data=json.dumps(rpc("ping")), headers=_hdr()) assert r.status == 429 and int(r.headers["Retry-After"]) >= 1 async def test_tool_call_reads_the_vault(make_client): c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_read", + r = await c.post("/mcp", data=json.dumps(rpc("tools/call", name="brain_read", arguments={"rel_path": "People/bob/Memory.md"})), headers=_hdr()) assert "Bob private memory" in (await r.json())["result"]["content"][0]["text"] @@ -144,7 +131,7 @@ async def test_tool_call_reads_the_vault(make_client): async def test_vault_swapped_between_requests_still_serves(make_client, vault, master): c = await make_client() main(["compile", "--master", str(master), "--out", str(vault.parent)]) # renames the dir - r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_read", + r = await c.post("/mcp", data=json.dumps(rpc("tools/call", name="brain_read", arguments={"rel_path": "People/bob/Memory.md"})), headers=_hdr()) assert "Bob private memory" in (await r.json())["result"]["content"][0]["text"] @@ -153,9 +140,9 @@ async def test_capture_is_listed_and_queues_one_envelope(make_client, tmp_path): spool = tmp_path / "spool" spool.mkdir() c = await make_client(spool=spool) - r = await c.post("/mcp", data=json.dumps(_rpc("tools/list")), headers=_hdr()) + r = await c.post("/mcp", data=json.dumps(rpc("tools/list")), headers=_hdr()) assert "brain_capture" in [t["name"] for t in (await r.json())["result"]["tools"]] - r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_capture", + r = await c.post("/mcp", data=json.dumps(rpc("tools/call", name="brain_capture", arguments={"text": "Ana prefers aisle seats", "title": "Ana"})), headers=_hdr()) result = (await r.json())["result"] assert result["isError"] is False and "Saved" in result["content"][0]["text"] @@ -167,7 +154,7 @@ async def test_bad_capture_is_a_tool_error_and_writes_nothing(make_client, tmp_p spool = tmp_path / "spool" spool.mkdir() c = await make_client(spool=spool) - r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_capture", + r = await c.post("/mcp", data=json.dumps(rpc("tools/call", name="brain_capture", arguments={"text": "x", "title": "a\nb"})), headers=_hdr()) assert (await r.json())["result"]["isError"] is True assert list(spool.glob("*.json")) == [] @@ -178,7 +165,7 @@ async def test_capture_hourly_limit(make_client, tmp_path, monkeypatch): spool = tmp_path / "spool" spool.mkdir() c = await make_client(spool=spool, clock=lambda: 100.0) - call = json.dumps(_rpc("tools/call", name="brain_capture", arguments={"text": "x"})) + call = json.dumps(rpc("tools/call", name="brain_capture", arguments={"text": "x"})) assert (await (await c.post("/mcp", data=call, headers=_hdr())).json())["result"]["isError"] is False second = await (await c.post("/mcp", data=call, headers=_hdr())).json() assert second["result"]["isError"] is True and "limit" in second["result"]["content"][0]["text"] @@ -215,27 +202,23 @@ def no_jwt(): run_vault_server(tmp_path, person="bob", email="bob@acme.com", auth=cfg, port=8901) -@pytest.mark.parametrize("params", [5, "x", ["a"]]) -async def test_non_object_params_is_invalid_params_not_500(make_client, params): +@pytest.mark.parametrize("params", [ + 5, "x", ["a"], # params not an object + {"name": "brain_search", "arguments": "x"}, # arguments not an object + {"name": "brain_search", "arguments": ["a"]}, +]) +async def test_malformed_tool_call_is_invalid_params_not_500(make_client, params): c = await make_client() msg = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params} r = await c.post("/mcp", data=json.dumps(msg), headers=_hdr()) assert r.status == 200 and (await r.json())["error"]["code"] == -32602 -@pytest.mark.parametrize("arguments", ["x", 5, ["a"]]) -async def test_non_object_arguments_is_invalid_params_not_500(make_client, arguments): - c = await make_client() - r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_search", - arguments=arguments)), headers=_hdr()) - assert r.status == 200 and (await r.json())["error"]["code"] == -32602 - - async def test_non_string_capture_title_is_invalid_params_not_500(make_client, tmp_path): spool = tmp_path / "spool" spool.mkdir() c = await make_client(spool=spool) - r = await c.post("/mcp", data=json.dumps(_rpc("tools/call", name="brain_capture", + r = await c.post("/mcp", data=json.dumps(rpc("tools/call", name="brain_capture", arguments={"text": "ok", "title": 5})), headers=_hdr()) assert r.status == 200 and (await r.json())["error"]["code"] == -32602 assert list(spool.glob("*.json")) == [] diff --git a/tests/test_mcprouter.py b/tests/test_mcprouter.py index 87e3a800..fbefe61e 100644 --- a/tests/test_mcprouter.py +++ b/tests/test_mcprouter.py @@ -5,10 +5,9 @@ from aiohttp import web from brain.mcprouter import RouteTable, RouteTableError, create_router_app, load_routes +from tests.remote_helpers import HEADER as H from tests.remote_helpers import SIGNER, make_verifier -H = "Cf-Access-Jwt-Assertion" - def _routes(tmp_path, routes, version=1): p = tmp_path / "mcp-routes.yaml" diff --git a/tests/test_remote_e2e.py b/tests/test_remote_e2e.py index e2f47004..aa527c7b 100644 --- a/tests/test_remote_e2e.py +++ b/tests/test_remote_e2e.py @@ -2,7 +2,6 @@ one person's vault server -> brain_capture -> spool -> cycle -> master Inbox.""" import json -from datetime import UTC, datetime import pytest @@ -10,18 +9,13 @@ from brain.cycle import run_cycle from brain.mcphttp import create_vault_app from brain.mcprouter import RouteTable, create_router_app -from tests.remote_helpers import SIGNER, make_verifier +from tests.remote_helpers import HEADER as H +from tests.remote_helpers import NOW, SIGNER, make_verifier, rpc from tests.test_cli import seed_meta -H = "Cf-Access-Jwt-Assertion" -NOW = datetime(2026, 10, 6, 14, 30, tzinfo=UTC) - def _rpc(method, mid=1, **params): - msg = {"jsonrpc": "2.0", "id": mid, "method": method} - if params: - msg["params"] = params - return json.dumps(msg) + return json.dumps(rpc(method, mid, **params)) @pytest.fixture diff --git a/tests/test_remoteauth.py b/tests/test_remoteauth.py index abcca250..279fbd87 100644 --- a/tests/test_remoteauth.py +++ b/tests/test_remoteauth.py @@ -54,7 +54,7 @@ def test_assertion_without_email_is_403_no_identity(): def test_hs256_token_is_refused(): forged = jwt.encode({"iss": ISSUER, "aud": [AUD], "email": "bob@acme.com", - "exp": int(time.time()) + 600}, "secret", algorithm="HS256", + "exp": int(time.time()) + 600}, "s" * 32, algorithm="HS256", headers={"kid": "k1"}) with pytest.raises(AuthRejected) as e: make_verifier().verify(_h(forged)) From eb6893992df81e8d3daf25140b07fd4b25c5d1bc Mon Sep 17 00:00:00 2001 From: Joe Danziger Date: Tue, 6 Oct 2026 12:39:20 -0400 Subject: [PATCH 14/14] docs: shorter architecture diagram; tell people to reconnect for brain_capture Claude-Session: https://claude.ai/code/session_0145uCzuUjLpe6rbH4WTf43Z --- docs/guides/remote-access.mdx | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/guides/remote-access.mdx b/docs/guides/remote-access.mdx index e2be5279..1e5d61c3 100644 --- a/docs/guides/remote-access.mdx +++ b/docs/guides/remote-access.mdx @@ -14,13 +14,15 @@ One connector, one address per company. Everyone clicks **Connect** and signs in Claude (web, phone, Code) │ HTTPS, signed in through your identity edge ▼ -Cloudflare Access runs the sign-in (OAuth) and signs each request with who it came from +Cloudflare Access runs the sign-in (OAuth) and signs each request │ ▼ -brain mcp-router checks the signature, finds that person's port (holds no vault) - │ - ├─▶ brain mcp --http (alice) reads only compiled/alice, saves only to spool/alice - └─▶ brain mcp --http (bob) reads only compiled/bob, saves only to spool/bob +brain mcp-router checks the signature, finds that person's port + │ (holds no vault) + ├─▶ brain mcp --http (alice) reads compiled/alice only + │ saves to spool/alice only + └─▶ brain mcp --http (bob) reads compiled/bob only + saves to spool/bob only ``` brainkit does not run the sign-in. An identity edge in front of it does, and brainkit only checks the signed note the edge attaches to each request. Cloudflare Access is what this guide describes; the check is generic, so another edge that signs requests the same way works with a settings change. @@ -60,6 +62,12 @@ brainkit does not run the sign-in. An identity edge in front of it does, and bra again. + + Claude remembers a connector's tool list from when it was first connected. If you + connected before saving notes was available, **Disconnect** and **Connect** the connector + once and `brain_capture` will appear. + + ## What Claude can do The same six read tools as `brain mcp` (`brain_search`, `brain_read`, `brain_links`,