"""Blossom authorization and the mirror exchange (profile `blossom-mirror`).
BUD-01 names the kind 24242 authorization event: tags `t` (the verb), `x`
(the blob sha256), `expiration`; the content is free text. It travels as
`Authorization: Nostr <base64(JSON event)>`.
BUD-04 is `PUT /mirror` with body `{"url": <source>}`; the server fetches,
hashes and refuses with 401 unless the hash is the one the `x` tag committed
to. This node's profile narrows it for replication: the verb is `mirror`
when a node asks a partner to copy, the source is the owner's public Blossom
URL `<base>/<sha256>`, and the 200 body is the standard blob descriptor
`{url, sha256, size, type, uploaded}` plus `cid`.
Verification (`check_auth`) is pure and takes `now` so a second node and a
vector can both hold the same event to the same verdict.
"""
from __future__ import annotations
import base64
import json
from typing import Optional, TypedDict
from . import store
from ..conformance.errors import FleetmeshError
from ..wire.interfaces import EventLike, NostrEvent
KIND: int = 24242
VERBS: tuple[str, ...] = ('get', 'upload', 'mirror', 'list', 'delete')
DEFAULT_EXPIRATION: int = 300
[docs]class AuthError(FleetmeshError, ValueError):
pass
[docs]class MirrorRequest(TypedDict):
url: str
[docs]class BlobDescriptor(TypedDict, total=False):
url: str
sha256: str
size: int
type: str
uploaded: int
cid: str
[docs]def auth_event(signer_sk: str, verb: str, sha256_hex: str, now: int,
expiration_seconds: int = DEFAULT_EXPIRATION, content: str = '') -> NostrEvent:
"""A signed kind 24242 for one verb over one blob."""
if verb not in VERBS:
raise AuthError('unknown verb %r' % verb)
tags = [['t', verb], ['x', sha256_hex.lower()], ['expiration', str(now + expiration_seconds)]]
return store.make_signed_event(signer_sk, now, KIND, tags, content or '%s %s' % (verb.capitalize(), sha256_hex))
[docs]def check_auth(ev: EventLike, verb: str, now: int, sha256_hex: Optional[str] = None) -> str:
"""The signer's pubkey, or AuthError naming the first rule the event breaks:
signature, kind, verb, hash, expiry - in that order."""
if not store.verify_event(ev):
raise AuthError('invalid event signature')
if ev.get('kind') != KIND:
raise AuthError('authorization event must be kind %d' % KIND)
raw_tags = ev.get('tags', [])
tags = {str(t[0]): str(t[1]) for t in (raw_tags if isinstance(raw_tags, list) else []) if isinstance(t, list) and len(t) >= 2}
if tags.get('t') != verb:
raise AuthError("authorization action mismatch: expected '%s', got '%s'" % (verb, tags.get('t')))
if sha256_hex is not None and tags.get('x', '').lower() != sha256_hex.lower():
raise AuthError('authorization hash mismatch')
exp = tags.get('expiration', '')
if not exp:
raise AuthError('authorization event has expired')
exp_ts = store.ascii_int(exp)
if exp_ts is None or exp_ts < now:
raise AuthError('authorization event has expired')
pk = ev.get('pubkey')
if not isinstance(pk, str):
raise AuthError('no pubkey')
return pk
[docs]def x_tag(ev: EventLike) -> Optional[str]:
"""The lowercase sha256 the event commits to, if any."""
raw_tags = ev.get('tags', [])
for t in raw_tags if isinstance(raw_tags, list) else []:
if isinstance(t, list) and len(t) >= 2 and t[0] == 'x' and isinstance(t[1], str) and t[1]:
return t[1].lower()
return None
[docs]def mirror_request(source_base: str, sha256_hex: str) -> MirrorRequest:
"""The body a replicating node PUTs to a partner's /mirror."""
return {'url': '%s/%s' % (source_base.rstrip('/'), sha256_hex.lower())}
[docs]def mirror_response(sha256_hex: str, size: int, content_type: str, uploaded: int, cid: str) -> BlobDescriptor:
"""The 200 body: the blob descriptor, url relative to the serving base."""
return {'url': '/' + sha256_hex.lower(), 'sha256': sha256_hex.lower(), 'size': size,
'type': content_type, 'uploaded': uploaded, 'cid': cid}