"""Cross-site federated web authentication over BIP-340 Schnorr keys, NIP-98
HTTP Auth (Kind 27235), NIP-42 Relay Auth (Kind 22242), and Portable Identity
Tickets.
Standardizes the three cryptographic web login and request-signing flows across
Fleetmesh HTTP services (MeshNode web faces, NSite, DVM gateways, application front ends):
1. Portable Cross-Site Identity Pass (`fmpass_...`):
A self-contained base64url bundle carrying a user-signed NIP-98 `Kind 27235`
proof event (bound to target origin + expiration + single-use nonce) and
an optional signed identity projection event (e.g. `Kind 30880`).
2. Challenge-Response Login:
Single-use challenge issued by the visited node, answered either with a
signed NIP-98/NIP-42 event carrying a `['challenge', ...]` tag or a direct
BIP-340 Schnorr signature over `SHA-256("<scheme>:<challenge>:<origin>")`.
Challenges are minted with AUTH_SCHEME, which is the only scheme a
signature over the challenge may name.
3. Stateless Per-Request NIP-98 HTTP Auth (`Authorization: Nostr <base64>`):
Verifies `Kind 27235` signature, timestamp skew, `['method', ...]` tag,
`['u', ...]` path/origin tag, and single-use `event_id` replay protection.
Every refusal is an `AuthRefused` carrying a stable snake_case `code` (the
wire `error` field, see ERRORS) and a `detail` sentence. The clock and every
random value (challenge, ticket nonce) are injectable so a vector file can pin
whole exchanges byte for byte (vectors/web-auth.json).
Standard library only.
"""
from __future__ import annotations
import base64
import contextlib
import dataclasses
import hashlib
import json
import secrets
import sqlite3
import threading
import time
import urllib.parse
from typing import Any, Callable, Iterator, Mapping, Optional, TypedDict
from ..conformance.errors import FleetmeshError
from ..crypto import crypto
from ..storage import store
from ..wire.interfaces import NostrEvent
__all__ = [
'NIP98_HTTP_AUTH_KIND',
'NIP42_AUTH_KIND',
'DEFAULT_CHALLENGE_TTL_SEC',
'TICKET_PREFIX',
'ACCEPTED_TICKET_PREFIXES',
'TICKET_CONTENT_PREFIX',
'TICKET_TTL_MIN_SEC',
'TICKET_TTL_MAX_SEC',
'TICKET_FUTURE_SKEW_SEC',
'AUTH_SCHEME',
'ACCEPTED_SCHEMES',
'ERRORS',
'AuthRefused',
'TokenSource',
'SecretsTokenSource',
'AuthChallengeReply',
'PortableTicketBundle',
'PortableTicketReply',
'VerifiedAuthResult',
'challenge_message',
'challenge_digests',
'encode_portable_ticket',
'decode_portable_ticket',
'FederatedWebAuth',
]
NIP98_HTTP_AUTH_KIND: int = 27235
NIP42_AUTH_KIND: int = 22242
DEFAULT_CHALLENGE_TTL_SEC: int = 300
# The pass prefix. A ticket is the bundle below, base64url-encoded after it.
TICKET_PREFIX: str = 'fmpass_'
ACCEPTED_TICKET_PREFIXES: tuple[str, ...] = (TICKET_PREFIX,)
TICKET_CONTENT_PREFIX: str = 'fleetmesh-cross-site-login'
TICKET_TTL_MIN_SEC: int = 30
TICKET_TTL_MAX_SEC: int = 3600
TICKET_FUTURE_SKEW_SEC: int = 120
# The challenge scheme. It is the only one a signature may name.
AUTH_SCHEME: str = 'fleetmesh-auth-v1'
ACCEPTED_SCHEMES: tuple[str, ...] = (AUTH_SCHEME,)
# Every refusal code the auth wire can carry in `error`, with its default
# `detail`. Codes are the contract; sentences may be reworded. The codes
# below the rule are raised by the engine and providers around this module,
# and are listed here so one table names the whole vocabulary.
ERRORS: dict[str, str] = {
'challenge_invalid_or_expired': 'Invalid or expired auth challenge',
'credentials_malformed': 'pubkey, challenge, and 64-byte signature (or portable_ticket) are required',
'signature_invalid': 'BIP-340 Schnorr signature verification failed',
'ticket_malformed': 'Malformed portable login ticket',
'ticket_signature_invalid': 'Invalid BIP-340 signature on portable ticket auth_event',
'ticket_wrong_kind': 'Portable ticket auth_event must be kind 27235',
'ticket_expired': 'Portable login ticket has expired',
'ticket_future_timestamp': 'Portable login ticket timestamp is in the future',
'ticket_host_mismatch': 'Portable ticket is bound to another origin',
'ticket_replayed': 'Portable login ticket has already been used (replay refused)',
'ticket_identity_mismatch': 'identity_event signature or pubkey mismatch',
'identity_event_malformed': 'identity_event must be a JSON object',
'identity_event_wrong_kind': 'identity_event is not of the expected kind',
'auth_event_signature_invalid': 'Invalid BIP-340 signature on auth_event',
'auth_event_wrong_kind': 'Unsupported auth_event kind',
'auth_event_timestamp_skew': 'auth_event timestamp is outside allowed window',
'auth_event_expired': 'auth_event has expired',
'auth_event_challenge_mismatch': 'auth_event must carry a signed challenge tag',
'auth_event_replayed': 'auth_event has already been used',
# ---- raised around this module (fleetmesh_auth engine and providers)
'bunker_uri_malformed': 'The bunker:// or nostrconnect:// URI could not be parsed',
'identity_malformed': 'The pubkey or DID could not be parsed',
'auth_event_malformed': 'auth_event is not a signed Nostr event',
'challenge_verifier_unavailable': 'This node has no challenge verifier',
'portable_ticket_unavailable': 'This node does not accept portable tickets',
'operator_token_not_configured': 'No operator token is configured on this node',
'missing_operator_token': 'No operator token was presented',
'invalid_operator_credentials': 'The operator token does not match',
'unknown_provider': 'The named provider is not registered on this node',
'provider_error': 'The provider failed while handling the login',
'bunker_requires_challenge_signature': 'A bunker URI only names a key; sign the challenge to sign in',
'private_key_not_accepted': 'A private key is never accepted on the wire; sign the challenge in the client',
'provider_not_enabled': 'The provider is not enabled on this node',
'method_not_enabled': 'The login method is not enabled on this node',
'insufficient_role': 'The principal lacks the required role',
'no_provider_for_this_login': 'No provider accepts this login',
'authentication_failed': 'Authentication failed',
'missing_session_token': 'No session token was presented',
'expired_session_token': 'The session token has expired',
'invalid_session_token': 'The session token is not known',
# ---- sovereign-key provider: a login that names no usable credential
'missing_sovereign_key_credentials': 'No key, DID, ticket, auth_event or passkey assertion in the login',
'did_requires_challenge_signature_or_secret_key': 'A DID only names a key; sign the challenge to sign in',
# ---- passkey (WebAuthn) assertions
'missing_passkey_assertion': 'credential_id, challenge_id and client_data_json are required',
'invalid_passkey_client_data': 'client_data_json is not base64url JSON',
'invalid_webauthn_type': 'client_data_json.type is not webauthn.get or webauthn.create',
'invalid_passkey_challenge_encoding': 'client_data_json.challenge is not base64url',
'passkey_challenge_mismatch': 'client_data_json.challenge is not the challenge issued',
'missing_authenticator_data': 'authenticator_data is required',
'invalid_authenticator_data': 'authenticator_data is not base64url',
'authenticator_data_too_short': 'authenticator_data is shorter than 37 bytes',
'passkey_user_not_present': 'authenticator_data has no user-presence flag',
'missing_passkey_signature': 'No passkey signature in the login',
# ---- transport (the reference HTTP server and the route table)
'unknown_fauth_endpoint': 'No such /api/fauth/ route',
'not_found': 'No such route',
'invalid_json': 'The request body is not a JSON object',
'invalid_content_length': 'Content-Length is missing or not a number',
'payload_too_large': 'The request body exceeds the size limit',
}
[docs]class AuthRefused(FleetmeshError, PermissionError):
"""A login refused for a protocol reason. `code` is the wire `error`
(a key of ERRORS); `detail` is the sentence, ERRORS[code] by default.
str() is the detail, as it always was for the PermissionError callers
caught."""
[docs] def __init__(self, code: str, detail: Optional[str] = None) -> None:
self.code = code
self.detail = detail if detail is not None else ERRORS.get(code, code)
super().__init__(self.detail)
[docs] def to_dict(self) -> dict[str, Any]:
return {'ok': False, 'error': self.code, 'detail': self.detail}
class TokenSource:
"""Where the random values come from. The default draws from `secrets`;
a test hands in one that returns fixed values so a whole exchange is
reproducible. Session tokens are the engine's, listed here so one
object covers every random the wire shows."""
def challenge_hex(self) -> str:
raise NotImplementedError
def nonce_hex(self) -> str:
raise NotImplementedError
def session_token(self) -> str:
raise NotImplementedError
class SecretsTokenSource(TokenSource):
def challenge_hex(self) -> str:
return secrets.token_hex(24)
def nonce_hex(self) -> str:
return secrets.token_hex(12)
def session_token(self) -> str:
return 'fmauth_' + secrets.token_urlsafe(24)
DEFAULT_TOKEN_SOURCE = SecretsTokenSource()
class PortableTicketBundle(TypedDict):
version: int
home_instance_url: str
home_node_did: str
target_url: str
expires_at: int
identity_event: Optional[Mapping[str, Any]]
auth_event: Mapping[str, Any]
class PortableTicketReply(TypedDict):
portable_ticket: str
bundle: PortableTicketBundle
expires_at: int
target_url: str
pubkey: str
did: str
class AuthChallengeReply(TypedDict):
challenge: str
auth_message: str
auth_message_sha256: str
instance_url: str
node_did: str
expires_at: int
@dataclasses.dataclass(frozen=True)
class VerifiedAuthResult:
"""Verified cross-site authentication outcome."""
pubkey: str
did: str
method: str
home_instance_url: str = ''
home_node_did: str = ''
identity_event: Optional[Mapping[str, Any]] = None
auth_event_id: str = ''
scheme: str = ''
def to_dict(self) -> dict[str, Any]:
return {
'pubkey': self.pubkey,
'did': self.did,
'method': self.method,
'home_instance_url': self.home_instance_url,
'home_node_did': self.home_node_did,
'identity_event': dict(self.identity_event) if self.identity_event is not None else None,
'auth_event_id': self.auth_event_id,
'scheme': self.scheme,
}
def challenge_message(
challenge: str,
origin_url: str,
*,
scheme: str = AUTH_SCHEME,
) -> str:
"""Canonical challenge string signed in direct BIP-340 challenge-response."""
return f'{scheme}:{challenge}:{origin_url.rstrip("/")}'
def challenge_digests(
challenge: str,
origin_url: str,
*,
schemes: tuple[str, ...] = ACCEPTED_SCHEMES,
) -> dict[str, str]:
"""`{scheme: sha256 hex of its message}` for every accepted scheme: the
32-byte messages a challenge signature may be over."""
return {
sc: hashlib.sha256(challenge_message(challenge, origin_url, scheme=sc).encode('utf-8')).hexdigest()
for sc in schemes
}
def encode_portable_ticket(
sk_hex: str,
*,
home_instance_url: str = '',
home_node_did: str = '',
target_url: str = '*',
ttl_sec: int = DEFAULT_CHALLENGE_TTL_SEC,
identity_event: Optional[Mapping[str, Any]] = None,
now: Optional[int] = None,
prefix: str = TICKET_PREFIX,
nonce_hex: Optional[str] = None,
) -> PortableTicketReply:
"""Mint a signed cross-site login ticket bundling a NIP-98 `Kind 27235`
proof event and an optional signed identity event. `nonce_hex` fixes the
single-use nonce (default: 12 random bytes)."""
clean_sk = (sk_hex or '').strip().lower()
if not store.is_hex64(clean_sk):
raise ValueError('sk_hex must be a 64-character lowercase hex secret key')
pk = crypto.pubkey(clean_sk)
now_ts = int(now if now is not None else time.time())
clean_ttl = max(TICKET_TTL_MIN_SEC, min(int(ttl_sec or DEFAULT_CHALLENGE_TTL_SEC), TICKET_TTL_MAX_SEC))
exp = now_ts + clean_ttl
clean_home = (home_instance_url or '').strip().rstrip('/')
clean_target = (target_url or '').strip().rstrip('/') or '*'
tags: list[list[str]] = [
['u', clean_target],
['method', 'POST'],
['expiration', str(exp)],
['home', clean_home],
['nonce', nonce_hex if nonce_hex is not None else DEFAULT_TOKEN_SOURCE.nonce_hex()],
]
auth_ev: NostrEvent = store.make_signed_event(
clean_sk,
now_ts,
NIP98_HTTP_AUTH_KIND,
tags,
f'{TICKET_CONTENT_PREFIX}:{pk}:{exp}',
)
bundle: PortableTicketBundle = {
'version': 1,
'home_instance_url': clean_home,
'home_node_did': (home_node_did or '').strip(),
'target_url': clean_target,
'expires_at': exp,
'identity_event': dict(identity_event) if isinstance(identity_event, Mapping) else None,
'auth_event': dict(auth_ev),
}
raw_b64 = base64.urlsafe_b64encode(
json.dumps(bundle, separators=(',', ':')).encode('utf-8')
).decode('ascii').rstrip('=')
return {
'portable_ticket': prefix + raw_b64,
'bundle': bundle,
'expires_at': exp,
'target_url': clean_target,
'pubkey': pk,
'did': f'did:nostr:{pk}',
}
def decode_portable_ticket(
raw_ticket: str | Mapping[str, Any],
*,
prefixes: tuple[str, ...] = ACCEPTED_TICKET_PREFIXES,
) -> Mapping[str, Any]:
"""Decode a portable ticket string (any accepted prefix) or mapping into
its bundle dictionary. Refuses `ticket_malformed`."""
if isinstance(raw_ticket, Mapping):
return dict(raw_ticket)
if not isinstance(raw_ticket, str) or not raw_ticket.strip():
raise AuthRefused('ticket_malformed')
s = raw_ticket.strip()
for prefix in prefixes:
if prefix and s.startswith(prefix):
s = s[len(prefix):]
break
pad = '=' * ((4 - len(s) % 4) % 4)
try:
decoded = json.loads(base64.urlsafe_b64decode(s + pad).decode('utf-8'))
except Exception:
raise AuthRefused('ticket_malformed') from None
if not isinstance(decoded, Mapping):
raise AuthRefused('ticket_malformed')
return dict(decoded)
class FederatedWebAuth:
"""Reusable challenge-response, portable ticket, and NIP-98 HTTP Auth
verifier backed by SQLite (either a caller-supplied connection or an
internal in-memory connection)."""
SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS auth_challenges (
challenge TEXT PRIMARY KEY,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS used_auth_events (
event_id TEXT PRIMARY KEY,
pubkey TEXT NOT NULL,
used_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
"""
def __init__(
self,
conn: Optional[sqlite3.Connection] = None,
*,
origin_url: str = '',
node_did: str = '',
scheme: str = AUTH_SCHEME,
accepted_schemes: Optional[tuple[str, ...]] = None,
challenge_ttl_sec: int = DEFAULT_CHALLENGE_TTL_SEC,
lock: Optional[threading.RLock] = None,
clock: Optional[Callable[[], int]] = None,
token_source: Optional[TokenSource] = None,
) -> None:
self._conn = conn if conn is not None else sqlite3.connect(':memory:', check_same_thread=False)
self._lock = lock if lock is not None else threading.RLock()
self.origin_url = (origin_url or '').rstrip('/')
self.node_did = node_did
# `scheme` is minted; a signature over the same challenge under any
# accepted scheme verifies, the minted one always among them.
self.scheme = scheme
accepted = tuple(accepted_schemes) if accepted_schemes is not None else ACCEPTED_SCHEMES
self.accepted_schemes: tuple[str, ...] = (scheme,) + tuple(sc for sc in accepted if sc != scheme)
self.challenge_ttl_sec = int(challenge_ttl_sec)
self.clock: Callable[[], int] = clock or (lambda: int(time.time()))
self.token_source: TokenSource = token_source if token_source is not None else DEFAULT_TOKEN_SOURCE
self._tables_ready = False
self.ensure_tables()
@contextlib.contextmanager
def _tx(self) -> Iterator[sqlite3.Connection]:
with self._lock:
with self._conn:
yield self._conn
def ensure_tables(self) -> None:
if self._tables_ready:
return
with self._tx() as conn:
conn.executescript(self.SCHEMA_SQL)
self._tables_ready = True
def reset(self) -> None:
"""Forget every outstanding challenge and used event id (tests)."""
self.ensure_tables()
with self._tx() as conn:
conn.execute('DELETE FROM auth_challenges')
conn.execute('DELETE FROM used_auth_events')
clear = reset
def issue_challenge(self, *, now: Optional[int] = None, challenge: Optional[str] = None) -> AuthChallengeReply:
"""Issue and persist a single-use cryptographic login challenge.
`challenge` fixes the id (default: the token source's 24 random bytes)."""
self.ensure_tables()
now_ts = int(now if now is not None else self.clock())
challenge = challenge if challenge is not None else self.token_source.challenge_hex()
expires_at = now_ts + self.challenge_ttl_sec
with self._tx() as conn:
conn.execute('DELETE FROM auth_challenges WHERE expires_at <= ?', (now_ts,))
conn.execute(
'INSERT OR REPLACE INTO auth_challenges (challenge, created_at, expires_at) VALUES (?, ?, ?)',
(challenge, now_ts, expires_at),
)
auth_msg = challenge_message(challenge, self.origin_url, scheme=self.scheme)
return {
'challenge': challenge,
'auth_message': auth_msg,
'auth_message_sha256': hashlib.sha256(auth_msg.encode('utf-8')).hexdigest(),
'instance_url': self.origin_url,
'node_did': self.node_did,
'expires_at': expires_at,
}
def consume_challenge(self, challenge: str, *, now: Optional[int] = None) -> bool:
"""Consume `challenge` once; return False if missing or expired."""
if not challenge:
return False
self.ensure_tables()
now_ts = int(now if now is not None else self.clock())
with self._tx() as conn:
conn.execute('DELETE FROM auth_challenges WHERE expires_at <= ?', (now_ts,))
row = conn.execute(
'SELECT expires_at FROM auth_challenges WHERE challenge = ?',
(challenge,),
).fetchone()
if row is None or int(row[0]) <= now_ts:
return False
conn.execute('DELETE FROM auth_challenges WHERE challenge = ?', (challenge,))
return True
def consume_auth_event_id(
self,
event_id: str,
pubkey: str,
expires_at: int,
*,
now: Optional[int] = None,
) -> bool:
"""Record `event_id` in `used_auth_events`; return False on replay."""
if not event_id:
return False
self.ensure_tables()
now_ts = int(now if now is not None else self.clock())
with self._tx() as conn:
conn.execute('DELETE FROM used_auth_events WHERE expires_at <= ?', (now_ts,))
existing = conn.execute(
'SELECT 1 FROM used_auth_events WHERE event_id = ?',
(event_id,),
).fetchone()
if existing is not None:
return False
conn.execute(
'INSERT INTO used_auth_events (event_id, pubkey, used_at, expires_at) VALUES (?, ?, ?, ?)',
(event_id, pubkey, now_ts, max(int(expires_at), now_ts + 600)),
)
return True
def create_portable_ticket(
self,
sk_hex: str,
*,
identity_event: Optional[Mapping[str, Any]] = None,
target_url: str = '*',
ttl_sec: int = DEFAULT_CHALLENGE_TTL_SEC,
now: Optional[int] = None,
nonce_hex: Optional[str] = None,
) -> PortableTicketReply:
"""Mint a portable ticket bound to this instance's origin and DID."""
return encode_portable_ticket(
sk_hex,
home_instance_url=self.origin_url,
home_node_did=self.node_did,
target_url=target_url,
ttl_sec=ttl_sec,
identity_event=identity_event,
now=now if now is not None else self.clock(),
nonce_hex=nonce_hex if nonce_hex is not None else self.token_source.nonce_hex(),
)
@staticmethod
def _validate_identity_event(
id_ev: Optional[Mapping[str, Any]],
verified_pk: str,
expected_identity_kind: Optional[int],
) -> Optional[Mapping[str, Any]]:
if id_ev is None:
return None
if not isinstance(id_ev, Mapping):
raise AuthRefused('identity_event_malformed')
if str(id_ev.get('pubkey') or '').lower() != verified_pk or not store.verify_event(id_ev):
raise AuthRefused('ticket_identity_mismatch')
if expected_identity_kind is not None and id_ev.get('kind') != expected_identity_kind:
raise AuthRefused('identity_event_wrong_kind', f'identity_event must be kind {expected_identity_kind}')
return id_ev
def verify_login_payload(
self,
body: Mapping[str, Any],
*,
expected_identity_kind: Optional[int] = None,
now: Optional[int] = None,
) -> VerifiedAuthResult:
"""Verify a cross-site login request payload (`portable_ticket`,
`auth_event`, or `(pubkey, challenge, signature)`) and return a
`VerifiedAuthResult`, or raise `AuthRefused` with the code."""
self.ensure_tables()
now_ts = int(now if now is not None else self.clock())
raw_body_id_ev = body.get('identity_event')
if raw_body_id_ev is not None and not isinstance(raw_body_id_ev, Mapping):
raise AuthRefused('identity_event_malformed')
identity_ev: Optional[Mapping[str, Any]] = raw_body_id_ev
home_url = str(body.get('home_instance_url') or '').strip()
home_did = str(body.get('home_node_did') or '').strip()
# Path 1: Portable Cross-Site Ticket (`fmpass_...` or bundle dict)
raw_ticket = body.get('portable_ticket')
if raw_ticket:
bundle = decode_portable_ticket(raw_ticket)
auth_ev = bundle.get('auth_event')
id_ev = bundle.get('identity_event')
if not isinstance(auth_ev, Mapping) or not store.verify_event(auth_ev):
raise AuthRefused('ticket_signature_invalid')
if auth_ev.get('kind') != NIP98_HTTP_AUTH_KIND:
raise AuthRefused('ticket_wrong_kind')
exp = store.expiration(auth_ev)
if exp is None or exp <= now_ts:
raise AuthRefused('ticket_expired')
if int(auth_ev.get('created_at', 0)) > now_ts + TICKET_FUTURE_SKEW_SEC:
raise AuthRefused('ticket_future_timestamp')
u_tag = store.first_tag(auth_ev, 'u')
target = (u_tag[1] if u_tag and len(u_tag) > 1 else '*').rstrip('/')
if target not in ('', '*') and self.origin_url and target != self.origin_url:
raise AuthRefused('ticket_host_mismatch', f'Portable ticket is bound to {target}, not {self.origin_url}')
verified_pk = str(auth_ev['pubkey']).lower()
cand_id_ev = id_ev if id_ev is not None else identity_ev
verified_id_ev = self._validate_identity_event(cand_id_ev, verified_pk, expected_identity_kind)
if not self.consume_auth_event_id(str(auth_ev['id']), verified_pk, exp, now=now_ts):
raise AuthRefused('ticket_replayed')
return VerifiedAuthResult(
pubkey=verified_pk,
did=f'did:nostr:{verified_pk}',
method='portable_ticket',
home_instance_url=str(bundle.get('home_instance_url') or home_url),
home_node_did=str(bundle.get('home_node_did') or home_did),
identity_event=verified_id_ev,
auth_event_id=str(auth_ev['id']),
)
# Path 2: Signed NIP-98 / NIP-42 `auth_event` + single-use challenge
if isinstance(body.get('auth_event'), Mapping):
auth_ev = body['auth_event']
if not store.verify_event(auth_ev):
raise AuthRefused('auth_event_signature_invalid')
if auth_ev.get('kind') not in (NIP98_HTTP_AUTH_KIND, NIP42_AUTH_KIND):
raise AuthRefused('auth_event_wrong_kind')
created_at = int(auth_ev.get('created_at', 0))
if abs(now_ts - created_at) > max(self.challenge_ttl_sec, 120):
raise AuthRefused('auth_event_timestamp_skew')
exp = store.expiration(auth_ev)
if exp is not None and exp <= now_ts:
raise AuthRefused('auth_event_expired')
ch_tag = store.first_tag(auth_ev, 'challenge')
if not (ch_tag and len(ch_tag) > 1 and ch_tag[1]):
raise AuthRefused('auth_event_challenge_mismatch')
challenge = ch_tag[1]
verified_pk = str(auth_ev['pubkey']).lower()
verified_id_ev = self._validate_identity_event(identity_ev, verified_pk, expected_identity_kind)
if not self.consume_challenge(challenge, now=now_ts):
raise AuthRefused('challenge_invalid_or_expired')
if not self.consume_auth_event_id(str(auth_ev['id']), verified_pk, now_ts + 600, now=now_ts):
raise AuthRefused('auth_event_replayed')
return VerifiedAuthResult(
pubkey=verified_pk,
did=f'did:nostr:{verified_pk}',
method='auth_event',
home_instance_url=home_url,
home_node_did=home_did,
identity_event=verified_id_ev,
auth_event_id=str(auth_ev['id']),
)
# Path 3: Direct `(pubkey, challenge, signature)` BIP-340 challenge-response
pk = str(body.get('pubkey') or '').strip().lower()
challenge = str(body.get('challenge') or '').strip()
sig_hex = str(body.get('signature') or '').strip().lower()
if not store.is_hex64(pk) or not challenge or len(sig_hex) != 128:
raise AuthRefused('credentials_malformed')
verified_id_ev = self._validate_identity_event(identity_ev, pk, expected_identity_kind)
if not self.consume_challenge(challenge, now=now_ts):
raise AuthRefused('challenge_invalid_or_expired')
# The signature may be over this challenge's message under any
# accepted scheme; the minted scheme is tried first.
signed_scheme = ''
for sc, digest_hex in challenge_digests(challenge, self.origin_url, schemes=self.accepted_schemes).items():
if crypto.schnorr_verify(bytes.fromhex(digest_hex), pk, sig_hex):
signed_scheme = sc
break
if not signed_scheme:
raise AuthRefused('signature_invalid')
return VerifiedAuthResult(
pubkey=pk,
did=f'did:nostr:{pk}',
method='challenge_signature',
home_instance_url=home_url,
home_node_did=home_did,
identity_event=verified_id_ev,
scheme=signed_scheme,
)
def verify_nip98_http_header(
self,
raw_token: str,
*,
method: str,
route: str,
max_skew_sec: int = 120,
now: Optional[int] = None,
) -> Optional[str]:
"""Verify an `Authorization: Nostr <base64-kind-27235>` token and return
the authenticated lowercase 64-hex `pubkey`, or `None` if invalid/replayed."""
self.ensure_tables()
s = (raw_token or '').strip()
if not s:
return None
pad = '=' * ((4 - len(s) % 4) % 4)
try:
ev = json.loads(base64.b64decode(s + pad).decode('utf-8'))
except Exception:
try:
ev = json.loads(base64.urlsafe_b64decode(s + pad).decode('utf-8'))
except Exception:
return None
if not isinstance(ev, Mapping) or ev.get('kind') != NIP98_HTTP_AUTH_KIND:
return None
if not store.verify_event(ev):
return None
now_ts = int(now if now is not None else self.clock())
created_at = int(ev.get('created_at', 0))
if abs(now_ts - created_at) > max_skew_sec:
return None
exp = store.expiration(ev)
if exp is not None and exp <= now_ts:
return None
m_tag = store.first_tag(ev, 'method')
if not m_tag or len(m_tag) < 2 or m_tag[1].upper() != method.upper():
return None
u_tag = store.first_tag(ev, 'u')
if not u_tag or len(u_tag) < 2:
return None
parsed_u = urllib.parse.urlparse(u_tag[1])
u_path = (parsed_u.path or '/').rstrip('/') or '/'
want_path = (route or '/').rstrip('/') or '/'
if u_path != want_path:
return None
if self.origin_url:
if not parsed_u.scheme or not parsed_u.netloc:
return None
u_base = f'{parsed_u.scheme}://{parsed_u.netloc}'.rstrip('/')
if u_base != self.origin_url:
return None
pk = str(ev['pubkey']).lower()
if not self.consume_auth_event_id(str(ev['id']), pk, now_ts + 300, now=now_ts):
return None
return pk