"""AT Protocol (atproto) identity, handle resolution, and K-256 cryptography.
Standard library only. Implements:
- did:plc directory resolution (https://plc.example.org/{did})
- did:web resolution (https://{domain}/.well-known/did.json)
- Handle resolution via DNS TXT (_atproto.{handle}) and HTTPS (/.well-known/atproto-did)
- Bidirectional handle verification (handle -> DID and DID doc alsoKnownAs -> handle)
- K-256 (secp256k1) deterministic ECDSA (RFC 6979) signing and verification
- Conversion between Fleetmesh secp256k1 keys and ATProto did:key:zQ3sh...
- AtprotoIdentityAdapter conforming to ProtocolIdentityAdapter
"""
from __future__ import annotations
import hashlib
import hmac
import json
import re
import time
import urllib.parse
from typing import Any, Callable, Mapping, Optional
from ..conformance.errors import FleetmeshError
from ..crypto import crypto
from ..netfetch import FetchError, fetch as _guarded_fetch
from .did import b58decode, node_did_key
__all__ = [
'AtprotoError',
'DIDResolutionError',
'HandleResolutionError',
'AtprotoResolver',
'AtprotoIdentityAdapter',
'is_valid_did',
'is_valid_handle',
'parse_at_uri',
'node_pk_to_did_key',
'did_key_to_public_key_bytes',
'ecdsa_sign',
'ecdsa_verify',
]
_DID_PLC_RE = re.compile(r'^did:plc:[a-z2-7]{24}$')
_DID_WEB_RE = re.compile(r'^did:web:[a-zA-Z0-9_.:%-]+$')
_DID_KEY_RE = re.compile(r'^did:key:z[1-9A-HJ-NP-Za-km-z]+$')
_HANDLE_RE = re.compile(r'^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$')
# secp256k1 multicodec prefix in did:key is 0xe7 0x01
_SECP256K1_CODEC = bytes([0xe7, 0x01])
# A DID document is a small JSON object (keys, services, alsoKnownAs). 1 MiB
# is generous by three orders of magnitude and bounds what a hostile did:web
# host can make us hold in memory.
MAX_DID_DOC_BYTES = 1 * 1024 * 1024
[docs]class AtprotoError(FleetmeshError):
"""Base error for ATProto identity operations."""
[docs]class DIDResolutionError(AtprotoError):
"""Raised when a DID cannot be resolved or document is invalid."""
[docs]class HandleResolutionError(AtprotoError):
"""Raised when a handle cannot be resolved or is invalid."""
[docs]def is_valid_did(did: Any) -> bool:
"""True if string is a valid ATProto did:plc, did:web, or did:key."""
if not isinstance(did, str):
return False
return bool(_DID_PLC_RE.match(did) or _DID_WEB_RE.match(did) or _DID_KEY_RE.match(did))
[docs]def is_valid_handle(handle: Any) -> bool:
"""True if string conforms to ATProto handle domain name syntax."""
if not isinstance(handle, str) or len(handle) > 253:
return False
return bool(_HANDLE_RE.match(handle.lower()))
[docs]def parse_at_uri(uri: str) -> tuple[str, str, str]:
"""Parse an at:// URI into (did_or_handle, collection, rkey).
Example: at://alice.bsky.social/app.bsky.feed.post/3k23v5w6 ->
('alice.bsky.social', 'app.bsky.feed.post', '3k23v5w6')
"""
if not uri.startswith('at://'):
raise AtprotoError(f"not an at:// URI: {uri}")
parts = uri[5:].split('/')
repo = parts[0]
collection = parts[1] if len(parts) > 1 else ''
rkey = parts[2] if len(parts) > 2 else ''
return repo, collection, rkey
[docs]def node_pk_to_did_key(x_only_hex_or_bytes: str | bytes) -> str:
"""Map a 32-byte secp256k1 public key to ATProto did:key:zQ3sh... string."""
if isinstance(x_only_hex_or_bytes, bytes):
pk_hex = x_only_hex_or_bytes.hex()
else:
pk_hex = x_only_hex_or_bytes.strip()
return node_did_key(pk_hex)
[docs]def did_key_to_public_key_bytes(did_key_str: str) -> bytes:
"""Extract compressed 33-byte public key from did:key:zQ3sh..."""
if not did_key_str.startswith('did:key:z'):
raise AtprotoError(f"not a base58btc did:key: {did_key_str}")
raw = b58decode(did_key_str[9:])
if not raw.startswith(_SECP256K1_CODEC):
raise AtprotoError(f"unsupported did:key codec: {raw[:2].hex()}")
key_bytes = raw[len(_SECP256K1_CODEC):]
if len(key_bytes) != 33:
raise AtprotoError(f"invalid compressed secp256k1 length: {len(key_bytes)}")
return key_bytes
def _rfc6979_nonce(d: int, z: bytes) -> int:
"""Deterministic nonce generator per RFC 6979 for secp256k1."""
v = b'\x01' * 32
k = b'\x00' * 32
d_bytes = d.to_bytes(32, 'big')
k = hmac.new(k, v + b'\x00' + d_bytes + z, hashlib.sha256).digest()
v = hmac.new(k, v, hashlib.sha256).digest()
k = hmac.new(k, v + b'\x01' + d_bytes + z, hashlib.sha256).digest()
v = hmac.new(k, v, hashlib.sha256).digest()
while True:
v = hmac.new(k, v, hashlib.sha256).digest()
candidate = int.from_bytes(v, 'big')
if 1 <= candidate < crypto.N:
return candidate
k = hmac.new(k, v + b'\x00', hashlib.sha256).digest()
v = hmac.new(k, v, hashlib.sha256).digest()
[docs]def ecdsa_sign(msg_bytes: bytes, sk_hex: str, normalize_even_y: bool = True) -> bytes:
"""Sign msg_bytes with secp256k1 private key using deterministic RFC 6979 ECDSA.
Returns raw 64-byte r || s signature with low-S normalization per BIP-62 / ATProto.
If normalize_even_y is True, normalizes scalar to even-y matching compressed_node_key.
"""
d0 = crypto._scalar(sk_hex)
if normalize_even_y:
pt_pub = crypto.point_mul(d0, crypto.G)
assert pt_pub is not None
d = d0 if pt_pub[1] % 2 == 0 else crypto.N - d0
else:
d = d0
z = hashlib.sha256(msg_bytes).digest()
z_int = int.from_bytes(z, 'big')
nonce = _rfc6979_nonce(d, z)
pt = crypto.point_mul(nonce, crypto.G)
assert pt is not None
r = pt[0] % crypto.N
if r == 0:
raise AtprotoError("r is zero")
s = (pow(nonce, -1, crypto.N) * (z_int + r * d)) % crypto.N
if s == 0:
raise AtprotoError("s is zero")
# Low-S normalization
if s > crypto.N // 2:
s = crypto.N - s
return r.to_bytes(32, 'big') + s.to_bytes(32, 'big')
[docs]def ecdsa_verify(msg_bytes: bytes, pk_compressed: bytes, sig_bytes: bytes) -> bool:
"""Verify raw 64-byte r || s signature against 33-byte compressed secp256k1 public key."""
if len(sig_bytes) != 64:
return False
if len(pk_compressed) != 33 or pk_compressed[0] not in (0x02, 0x03):
return False
r = int.from_bytes(sig_bytes[:32], 'big')
s = int.from_bytes(sig_bytes[32:], 'big')
if not (1 <= r < crypto.N and 1 <= s <= crypto.N // 2):
return False
# Decompress public key point
x = int.from_bytes(pk_compressed[1:], 'big')
even_pt = crypto.lift_x(x)
if even_pt is None:
return False
y = even_pt[1] if pk_compressed[0] == 0x02 else crypto.P - even_pt[1]
pk_point = (x, y)
z = hashlib.sha256(msg_bytes).digest()
z_int = int.from_bytes(z, 'big')
w = pow(s, -1, crypto.N)
u1 = (z_int * w) % crypto.N
u2 = (r * w) % crypto.N
p1 = crypto.point_mul(u1, crypto.G)
p2 = crypto.point_mul(u2, pk_point)
res = crypto.point_add(p1, p2)
if res is None:
return False
return (res[0] % crypto.N) == r
[docs]class AtprotoResolver:
"""Resolves and caches ATProto DIDs (did:plc, did:web) and handles."""
[docs] def __init__(
self,
plc_directory: str = "https://plc.example.org",
cache_ttl: float = 300.0,
fetcher: Optional[Callable[[str], bytes]] = None,
dns_resolver: Optional[Callable[[str], list[str]]] = None,
dns_txt: Optional[Callable[[str], list[str]]] = None,
):
self.plc_directory = plc_directory.rstrip('/')
self.cache_ttl = cache_ttl
self._fetcher = fetcher or self._default_fetcher
self._dns_resolver = dns_resolver or dns_txt
self._did_cache: dict[str, tuple[float, Mapping[str, Any]]] = {}
self._handle_cache: dict[str, tuple[float, str]] = {}
@staticmethod
def _default_fetcher(url: str) -> bytes:
"""Fetch a DID document through core's guarded fetcher.
Two kinds of URL arrive here. The PLC directory URL is operator
config; a did:web URL is built from a DID somebody handed us, so the
remote side effectively chooses the host. Because the two share this
one fetcher, it always runs the full policy: http/https only, no
loopback/private/link-local/metadata address (redirects re-checked),
and a 1 MiB cap -- the largest DID document seen in the wild is a few
kilobytes.
An operator who really runs a PLC directory on a private address
passes ``fetcher=`` to AtprotoResolver with its own policy; that stays
an explicit, local decision rather than a flag that a did:web host
could also benefit from.
"""
try:
body, _ = _guarded_fetch(
url,
max_bytes=MAX_DID_DOC_BYTES,
timeout=5.0,
headers={'User-Agent': 'fleetmesh-core/1.0', 'Accept': 'application/json, text/plain'},
)
except FetchError as e:
# Callers wrap this into DIDResolutionError/HandleResolutionError
# with the URL they were resolving; keep the policy reason intact.
raise DIDResolutionError(str(e)) from e
return body
[docs] def resolve_did_plc(self, did: str) -> Mapping[str, Any]:
"""Resolve did:plc using PLC directory."""
if not _DID_PLC_RE.match(did):
raise DIDResolutionError(f"invalid did:plc identifier: {did}")
now = time.time()
if did in self._did_cache:
ts, doc = self._did_cache[did]
if now - ts < self.cache_ttl:
return doc
url = f"{self.plc_directory}/{did}"
try:
raw = self._fetcher(url)
doc = json.loads(raw.decode('utf-8'))
except Exception as e:
raise DIDResolutionError(f"failed to fetch did:plc document from {url}: {e}") from e
if not isinstance(doc, dict) or doc.get('id') != did:
raise DIDResolutionError(f"invalid DID document returned for {did}")
self._did_cache[did] = (now, doc)
return doc
[docs] def resolve_did_web(self, did: str) -> Mapping[str, Any]:
"""Resolve did:web per W3C did:web specification."""
if not is_valid_did(did) or not did.startswith('did:web:'):
raise DIDResolutionError(f"invalid did:web identifier: {did}")
now = time.time()
if did in self._did_cache:
ts, doc = self._did_cache[did]
if now - ts < self.cache_ttl:
return doc
parts = did[len('did:web:'):].split(':')
host = urllib.parse.unquote(parts[0])
if not host or '..' in host or any(c in host for c in ('@', '/', '?', '#', '\\', ' ')):
raise DIDResolutionError(f"invalid did:web host: {host}")
if len(parts) == 1:
url = f"https://{host}/.well-known/did.json"
else:
segments: list[str] = []
for p in parts[1:]:
seg = urllib.parse.unquote(p)
if not seg or seg in ('.', '..') or '..' in seg or any(c in seg for c in ('/', '\\', '?', '#')):
raise DIDResolutionError(f"invalid did:web path segment: {seg}")
segments.append(seg)
path = '/'.join(segments)
url = f"https://{host}/{path}/did.json"
try:
raw = self._fetcher(url)
doc = json.loads(raw.decode('utf-8'))
except Exception as e:
raise DIDResolutionError(f"failed to fetch did:web document from {url}: {e}") from e
if not isinstance(doc, dict) or doc.get('id') != did:
raise DIDResolutionError(f"invalid DID document returned for {did}")
self._did_cache[did] = (now, doc)
return doc
[docs] def resolve_did(self, did: str) -> Mapping[str, Any]:
"""Resolve any ATProto DID (did:plc, did:web)."""
if did.startswith('did:plc:'):
return self.resolve_did_plc(did)
if did.startswith('did:web:'):
return self.resolve_did_web(did)
if did.startswith('did:key:'):
# Synthesize minimal self-certifying DID Document for did:key
return {
'@context': ['https://www.w3.org/ns/did/v1'],
'id': did,
'verificationMethod': [{
'id': f"{did}#key-1",
'type': 'Multikey',
'controller': did,
'publicKeyMultibase': did[len('did:key:'):],
}],
'authentication': [f"{did}#key-1"],
}
raise DIDResolutionError(f"unsupported DID method in: {did}")
[docs] def resolve_handle_dns(self, handle: str) -> Optional[str]:
"""Resolve handle via DNS TXT record at _atproto.<handle>."""
if not is_valid_handle(handle):
return None
target = f"_atproto.{handle.lower()}"
records: list[str] = []
if self._dns_resolver is not None:
try:
records = self._dns_resolver(target)
except Exception:
return None
else:
return None
for rec in records:
rec = rec.strip()
if rec.startswith('did='):
val = rec[4:].strip()
if is_valid_did(val):
return val
return None
[docs] def resolve_handle_http(self, handle: str) -> Optional[str]:
"""Resolve handle via HTTPS GET https://<handle>/.well-known/atproto-did."""
if not is_valid_handle(handle):
return None
url = f"https://{handle.lower()}/.well-known/atproto-did"
try:
raw = self._fetcher(url)
val = raw.decode('utf-8').strip()
if is_valid_did(val):
return val
except Exception:
return None
return None
[docs] def resolve_handle(self, handle: str) -> str:
"""Resolve handle to DID trying DNS TXT first, then HTTPS well-known fallback."""
handle_clean = handle.lower().strip()
if not is_valid_handle(handle_clean):
raise HandleResolutionError(f"invalid handle syntax: {handle}")
now = time.time()
if handle_clean in self._handle_cache:
ts, cached_did = self._handle_cache[handle_clean]
if now - ts < self.cache_ttl:
return cached_did
found_did = self.resolve_handle_dns(handle_clean)
if not found_did:
found_did = self.resolve_handle_http(handle_clean)
if not found_did:
raise HandleResolutionError(f"could not resolve handle: {handle}")
self._handle_cache[handle_clean] = (now, found_did)
return found_did
[docs] def verify_handle(self, handle: str, did: str) -> bool:
"""Bidirectionally verify that handle resolves to DID and DID doc claims handle."""
try:
resolved_did = self.resolve_handle(handle)
if resolved_did != did:
return False
doc = self.resolve_did(did)
handles = self.get_handles(doc)
return handle.lower().strip() in [h.lower() for h in handles]
except Exception:
return False
[docs] @staticmethod
def get_signing_key(doc: Mapping[str, Any]) -> str:
"""Extract public key multibase string (or did:key) from DID document."""
vms = doc.get('verificationMethod', [])
for vm in vms:
vm_id = vm.get('id', '')
if vm_id.endswith('#atproto') or vm_id.endswith('#key-1'):
mb = vm.get('publicKeyMultibase')
if mb:
return f"did:key:{mb}"
# Fallback to first verificationMethod
if vms and 'publicKeyMultibase' in vms[0]:
return f"did:key:{vms[0]['publicKeyMultibase']}"
raise DIDResolutionError(f"no verificationMethod found in DID document for {doc.get('id')}")
[docs] @staticmethod
def get_pds_endpoint(doc: Mapping[str, Any]) -> Optional[str]:
"""Extract AtprotoPersonalDataServer endpoint URI from DID document."""
services = doc.get('service', [])
for svc in services:
if svc.get('type') == 'AtprotoPersonalDataServer':
return svc.get('serviceEndpoint')
return None
[docs] @staticmethod
def get_handles(doc: Mapping[str, Any]) -> list[str]:
"""Extract all claimed handles from alsoKnownAs list in DID document."""
akas = doc.get('alsoKnownAs', [])
handles: list[str] = []
for aka in akas:
if aka.startswith('at://'):
handles.append(aka[5:].strip())
return handles
[docs] @staticmethod
def build_did_document(
did: str,
handle: str,
pds_endpoint: str,
signing_key_did_key: str,
) -> Mapping[str, Any]:
"""Construct a self-describing ATProto DID document (e.g. for did:web)."""
pubkey_mb = signing_key_did_key.removeprefix('did:key:')
return {
'@context': [
'https://www.w3.org/ns/did/v1',
'https://w3id.org/security/multikey/v1',
],
'id': did,
'alsoKnownAs': [f"at://{handle.lower()}"],
'verificationMethod': [
{
'id': f"{did}#atproto",
'type': 'Multikey',
'controller': did,
'publicKeyMultibase': pubkey_mb,
}
],
'service': [
{
'id': '#atproto_pds',
'type': 'AtprotoPersonalDataServer',
'serviceEndpoint': pds_endpoint,
}
],
}
[docs]class AtprotoIdentityAdapter:
"""Translates between Fleetmesh keys and ATProto DIDs / handles."""
protocol_name: str = 'atproto'
[docs] def __init__(
self,
keystore: Any = None,
resolver: Optional[AtprotoResolver] = None,
handle: Optional[str] = None,
did: Optional[str] = None,
):
self.keystore = keystore
self.resolver = resolver or AtprotoResolver()
self.handle = handle
self.did = did
[docs] def resolve_id(self, uri: str) -> Optional[str]:
"""Resolve handle or at:// URI to canonical DID."""
if not uri:
return None
uri_str = uri.strip()
if uri_str.startswith('at://'):
repo, _, _ = parse_at_uri(uri_str)
uri_str = repo
if uri_str.startswith('did:'):
return uri_str
try:
return self.resolver.resolve_handle(uri_str)
except Exception:
return None
[docs] def sign_assertion(self, payload: bytes) -> bytes:
"""Sign payload using node's secp256k1 secret key with RFC 6979 ECDSA."""
if self.keystore is None:
raise AtprotoError("no keystore configured for signing")
# Extract secret key hex from keystore (e.g. node_sk or key._d)
sk_hex = getattr(self.keystore, 'node_sk_hex', None) or getattr(self.keystore, 'node_sk', None)
if sk_hex is None and hasattr(self.keystore, 'get_secret_key'):
sk_hex = self.keystore.get_secret_key('node')
if sk_hex is None and hasattr(self.keystore, 'key') and hasattr(self.keystore.key, '_d'):
sk_hex = f"{self.keystore.key._d:064x}"
if sk_hex is None:
raise AtprotoError("unable to extract secp256k1 signing key from keystore")
return ecdsa_sign(payload, sk_hex)
[docs] def verify_assertion(self, payload: bytes, signature: bytes, pubkey: str) -> bool:
"""Verify RFC 6979 ECDSA signature against pubkey (did:key or compressed hex)."""
try:
if pubkey.startswith('did:key:'):
pk_bytes = did_key_to_public_key_bytes(pubkey)
else:
pk_bytes = bytes.fromhex(pubkey)
if len(pk_bytes) == 32:
pk_bytes = b"\x02" + pk_bytes
return ecdsa_verify(payload, pk_bytes, signature)
except Exception:
return False