"""Bluesky access through the OAuth sidecar — every read and write made as a person, by DID. The sidecar (auth/oauth, Node) is the only process that holds a credential: atproto OAuth binds every access token to a key with DPoP, so whoever holds the key must make the call. Python asks it to call as a DID; it calls. There is no bearer token anywhere in Python. Unlike the agent product, aligned.click has **no allowlist**: any atproto handle can log in and create topics. This module therefore has no session- owner indirection — a call is made as the DID the caller passes (or ACTING_DID / ADMIN_DID for admin operations), and that is all. from auth import bsky posts = bsky.get("app.bsky.feed.searchPosts", {"q": "repair cafe"}, did) """ import json import os import urllib.error import urllib.parse import urllib.request from pathlib import Path SIDECAR = os.environ.get("OAUTH_SIDECAR", "http://127.0.0.1:4098").rstrip("/") TIMEOUT = 30 ENV_FILE = Path(__file__).parent.parent / ".env" class BskyError(RuntimeError): """A failed Bluesky call. Its message is safe to print — it names a method and a reason, never a credential, because there is no credential in this process to name.""" def admin_did() -> str: """The account that owns the authorising domain (aligned.click), which publishes schemas and the feed generator records under the domain's name. Read from .env: the ADMIN_DID account has logged into the sidecar like anyone else — there are no app passwords in the write path. """ did = os.environ.get("ADMIN_DID", "").strip() if not did and ENV_FILE.exists(): for line in ENV_FILE.read_text().splitlines(): if line.startswith("ADMIN_DID="): did = line.split("=", 1)[1].strip().strip('"').strip("'") break if not did: raise BskyError( "ADMIN_DID is not set. Writing under the domain's own name needs " "the account that owns it, and this refuses to guess which that " "is. Put `ADMIN_DID=did:plc:…` in .env, and make sure that account " "has logged into the sidecar.") return _checked(did) def _checked(did: str) -> str: if not did.startswith("did:"): raise BskyError(f"{did!r} is a handle, not a DID — a handle can move " "between accounts and a DID cannot.") return did def get(method: str, params: dict, did: str | None = None) -> dict: """A read through the sidecar, as `did` (or ACTING_DID). Failures are loud and never fall back to another identity.""" qs = urllib.parse.urlencode({**params, "did": did}, doseq=True) url = f"{SIDECAR}/xrpc/{method}?{qs}" try: with urllib.request.urlopen(url, timeout=TIMEOUT) as response: body = response.read() except urllib.error.HTTPError as e: detail = e.read().decode("utf-8", "replace") try: detail = json.loads(detail).get("message") or detail except json.JSONDecodeError: pass raise BskyError(f"{method}: {detail}") from None except OSError as e: raise BskyError( f"{method}: cannot reach the OAuth sidecar at {SIDECAR} ({e}). " "Start it with `node auth/oauth/server.mjs`." ) from None try: return json.loads(body) except json.JSONDecodeError: raise BskyError(f"{method}: unparseable response") from None def _call(method: str, body: dict, did: str) -> dict: """POST an XRPC procedure through the sidecar, as `did`.""" request = urllib.request.Request( f"{SIDECAR}/xrpc/{method}?did={urllib.parse.quote(did)}", data=json.dumps(body).encode(), headers={"content-type": "application/json"}, method="POST", ) try: with urllib.request.urlopen(request, timeout=TIMEOUT) as response: return json.loads(response.read()) except urllib.error.HTTPError as e: detail = e.read().decode("utf-8", "replace") try: detail = json.loads(detail).get("message") or detail except json.JSONDecodeError: pass raise BskyError(f"{method}: {detail}") from None except OSError as e: raise BskyError( f"{method}: cannot reach the OAuth sidecar at {SIDECAR} ({e}). " "Start it with `node auth/oauth/server.mjs`." ) from None