"""NIP-46 Nostr Bunker (`bunker://`), Bech32 (`nsec1`/`npub1`), and DID (`did:nostr`/`did:key`) helpers."""
from __future__ import annotations
import dataclasses
import hashlib
import urllib.parse
from typing import Any, Optional
from fleetmesh_core.crypto import crypto
from fleetmesh_core.identity.web_auth import ACCEPTED_SCHEMES, AUTH_SCHEME
from fleetmesh_core.crypto.bech32 import bech32_decode
from fleetmesh_core.storage import store
[docs]def is_hex64(value: str) -> bool:
return bool(store.is_hex64((value or '').strip().lower()))
[docs]def decode_bech32_hex(bech: str, expected_hrp: Optional[str] = None) -> str:
"""Decode `nsec1...` or `npub1...` Bech32 string into a 64-char lowercase hex string."""
s = (bech or '').strip().lower()
pos = s.rfind('1')
if pos < 1 or pos + 7 > len(s):
raise ValueError('Invalid Bech32 key format')
hrp = s[:pos]
if expected_hrp and hrp != expected_hrp:
raise ValueError(f'Expected {expected_hrp}1... key, got {hrp}1...')
raw = bech32_decode(hrp, s)
if raw is None or len(raw) != 32:
raise ValueError('Invalid 32-byte Bech32 payload')
return raw.hex()
[docs]def normalize_secret_key(raw_key: str) -> str:
"""Accept 64-char hex or `nsec1...` Bech32 secret key and return 64-char lowercase hex."""
s = (raw_key or '').strip()
if s.lower().startswith('nsec1'):
return decode_bech32_hex(s, expected_hrp='nsec')
if s.lower().startswith('0x'):
s = s[2:]
clean = s.lower()
if not is_hex64(clean):
raise ValueError('Private key must be a 64-character hex string or nsec1... Bech32 key')
return clean
[docs]def normalize_pubkey_or_did(raw_value: str) -> dict[str, str]:
"""Normalize `did:nostr:<hex>`, `did:key:...`, `npub1...`, or 64-char hex into `{'pubkey_hex': pk, 'did': did}`."""
s = (raw_value or '').strip()
if not s:
raise ValueError('Empty pubkey or DID')
low = s.lower()
if low.startswith('did:nostr:'):
pk = low[len('did:nostr:'):].strip()
if pk.startswith('npub1'):
pk = decode_bech32_hex(pk, expected_hrp='npub')
if not is_hex64(pk):
raise ValueError('did:nostr subject must be a 64-character hex pubkey')
return {'pubkey_hex': pk, 'did': f'did:nostr:{pk}'}
if low.startswith('npub1'):
pk = decode_bech32_hex(low, expected_hrp='npub')
return {'pubkey_hex': pk, 'did': f'did:nostr:{pk}'}
if low.startswith('did:key:') or low.startswith('did:plc:') or low.startswith('did:web:'):
tail = s.split(':', 2)[-1]
if is_hex64(tail):
return {'pubkey_hex': tail.lower(), 'did': s}
digest = hashlib.sha256(s.encode('utf-8')).hexdigest()
return {'pubkey_hex': digest, 'did': s}
if is_hex64(low):
return {'pubkey_hex': low, 'did': f'did:nostr:{low}'}
raise ValueError('Must be a 64-char hex pubkey, npub1..., did:nostr:..., or did:key:...')
[docs]@dataclasses.dataclass(frozen=True)
class BunkerDescriptor:
"""Parsed NIP-46 `bunker://` or `nostrconnect://` remote signer connection URI."""
scheme: str
remote_pubkey: str
did: str
relays: list[str]
secret: str = ''
raw_uri: str = ''
@property
def remote_pubkey_hex(self) -> str:
return self.remote_pubkey
[docs] def to_dict(self) -> dict[str, Any]:
return {
'scheme': self.scheme,
'remote_pubkey': self.remote_pubkey,
'remote_pubkey_hex': self.remote_pubkey,
'did': self.did,
'relays': list(self.relays),
'has_secret': bool(self.secret),
}
[docs]def parse_bunker_uri(bunker_uri: str) -> BunkerDescriptor:
"""Parse and validate a NIP-46 `bunker://<pubkey>?relay=wss://...&secret=...` URI."""
raw = (bunker_uri or '').strip()
if not raw:
raise ValueError('Missing bunker:// URI')
parsed = urllib.parse.urlparse(raw)
scheme = (parsed.scheme or '').lower()
if scheme not in ('bunker', 'nostrconnect'):
raise ValueError('Bunker URI must start with bunker:// or nostrconnect://')
host_part = (parsed.netloc or parsed.path or '').strip().lstrip('/')
if not host_part:
raise ValueError('Bunker URI is missing remote signer pubkey')
norm = normalize_pubkey_or_did(host_part)
pk = norm['pubkey_hex']
did = norm['did']
qs = urllib.parse.parse_qs(parsed.query, keep_blank_values=False)
relays: list[str] = []
for r in qs.get('relay', []) + qs.get('relays', []):
clean_r = r.strip()
if clean_r and (clean_r.startswith('wss://') or clean_r.startswith('ws://')):
relays.append(clean_r)
if not relays:
relays = ['wss://relay.fleetmesh.org']
secret = (qs.get('secret', [''])[0] or '').strip()
return BunkerDescriptor(
scheme=scheme,
remote_pubkey=pk,
did=did,
relays=relays,
secret=secret,
raw_uri=raw,
)
[docs]def sign_challenge_with_secret_key(
sk_input: str,
challenge: str,
origin_url: str = '',
*,
scheme: str = AUTH_SCHEME,
) -> dict[str, str]:
"""Sign a FleetMesh challenge message with a 64-char hex or `nsec1...` secret key."""
sk_hex = normalize_secret_key(sk_input)
pk_hex = crypto.pubkey(sk_hex)
# A full challenge_text (`<scheme>:<challenge>:<origin>`, any accepted
# scheme) is signed as given; a bare challenge gets the scheme's message.
if challenge.startswith(tuple(f'{sc}:' for sc in set(ACCEPTED_SCHEMES) | {scheme})):
msg = challenge
parts = challenge.split(':', 2)
raw_challenge = parts[1] if len(parts) > 1 else challenge
else:
raw_challenge = challenge
msg = f'{scheme}:{challenge}:{origin_url.rstrip("/")}'
msg_hash = hashlib.sha256(msg.encode('utf-8')).digest()
raw_sig = crypto.schnorr_sign(msg_hash, sk_hex)
sig_hex = raw_sig.hex() if isinstance(raw_sig, (bytes, bytearray)) else str(raw_sig)
return {
'pubkey': pk_hex,
'pubkey_hex': pk_hex,
'did': f'did:nostr:{pk_hex}',
'signature': sig_hex,
'signature_hex': sig_hex,
'challenge': raw_challenge,
'auth_message': msg,
}