nostr_auth.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """Dependency-free Nostr signing (secp256k1 / BIP-340) for Buzz WebSocket authentication."""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. import secrets
  6. import time
  7. from typing import Any, Optional
  8. FIELD_ORDER = 2**256 - 2**32 - 977
  9. CURVE_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
  10. GENERATOR = (
  11. 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
  12. 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
  13. )
  14. BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
  15. _BECH32_GENERATORS = (0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3)
  16. Point = Optional[tuple[int, int]]
  17. def _bech32_polymod(values: list[int]) -> int:
  18. checksum = 1
  19. for value in values:
  20. top = checksum >> 25
  21. checksum = ((checksum & 0x1FFFFFF) << 5) ^ value
  22. for index, generator in enumerate(_BECH32_GENERATORS):
  23. if (top >> index) & 1:
  24. checksum ^= generator
  25. return checksum
  26. def _bech32_hrp_expand(hrp: str) -> list[int]:
  27. return [ord(char) >> 5 for char in hrp] + [0] + [ord(char) & 31 for char in hrp]
  28. def _decode_nsec(value: str) -> bytes:
  29. if value.lower() != value and value.upper() != value:
  30. raise ValueError("nsec cannot mix upper- and lowercase")
  31. normalized = value.lower()
  32. separator = normalized.rfind("1")
  33. if separator < 1 or separator + 7 > len(normalized):
  34. raise ValueError("invalid nsec encoding")
  35. hrp = normalized[:separator]
  36. if hrp != "nsec":
  37. raise ValueError("private key must use the nsec prefix")
  38. try:
  39. data = [BECH32_CHARSET.index(char) for char in normalized[separator + 1 :]]
  40. except ValueError as exc:
  41. raise ValueError("invalid character in nsec") from exc
  42. if _bech32_polymod(_bech32_hrp_expand(hrp) + data) != 1:
  43. raise ValueError("invalid nsec checksum")
  44. accumulator = bits = 0
  45. decoded = bytearray()
  46. for value5 in data[:-6]:
  47. accumulator = (accumulator << 5) | value5
  48. bits += 5
  49. while bits >= 8:
  50. bits -= 8
  51. decoded.append((accumulator >> bits) & 0xFF)
  52. if bits and (accumulator & ((1 << bits) - 1)):
  53. raise ValueError("non-zero nsec padding")
  54. if len(decoded) != 32:
  55. raise ValueError("nsec must encode exactly 32 bytes")
  56. return bytes(decoded)
  57. def decode_private_key(value: str) -> int:
  58. raw = value.strip()
  59. if raw.lower().startswith("nsec1"):
  60. key_bytes = _decode_nsec(raw)
  61. else:
  62. try:
  63. key_bytes = bytes.fromhex(raw)
  64. except ValueError as exc:
  65. raise ValueError("private key must be 64 hex characters or nsec") from exc
  66. if len(key_bytes) != 32:
  67. raise ValueError("private key must be 32 bytes")
  68. key = int.from_bytes(key_bytes, "big")
  69. if not 1 <= key < CURVE_ORDER:
  70. raise ValueError("private key is outside the secp256k1 range")
  71. return key
  72. def _point_add(left: Point, right: Point) -> Point:
  73. if left is None or right is None:
  74. return right if left is None else left
  75. x1, y1 = left
  76. x2, y2 = right
  77. if x1 == x2:
  78. if (y1 + y2) % FIELD_ORDER == 0:
  79. return None
  80. slope = (3 * x1 * x1) * pow(2 * y1, FIELD_ORDER - 2, FIELD_ORDER)
  81. else:
  82. slope = (y2 - y1) * pow(x2 - x1, FIELD_ORDER - 2, FIELD_ORDER)
  83. slope %= FIELD_ORDER
  84. x3 = (slope * slope - x1 - x2) % FIELD_ORDER
  85. return x3, (slope * (x1 - x3) - y1) % FIELD_ORDER
  86. def _point_multiply(scalar: int, point: Point = GENERATOR) -> Point:
  87. result: Point = None
  88. addend = point
  89. while scalar:
  90. if scalar & 1:
  91. result = _point_add(result, addend)
  92. addend = _point_add(addend, addend)
  93. scalar >>= 1
  94. return result
  95. def _tagged_hash(tag: str, payload: bytes) -> bytes:
  96. tag_hash = hashlib.sha256(tag.encode()).digest()
  97. return hashlib.sha256(tag_hash + tag_hash + payload).digest()
  98. def public_key_hex(private_key: str) -> str:
  99. point = _point_multiply(decode_private_key(private_key))
  100. if point is None: # pragma: no cover - range validation makes this unreachable
  101. raise ValueError("invalid private key")
  102. return point[0].to_bytes(32, "big").hex()
  103. def schnorr_sign(message: bytes, private_key: str, *, auxiliary_randomness: Optional[bytes] = None) -> bytes:
  104. if len(message) != 32:
  105. raise ValueError("BIP-340 signs a 32-byte message")
  106. secret = decode_private_key(private_key)
  107. public_point = _point_multiply(secret)
  108. if public_point is None: # pragma: no cover
  109. raise ValueError("invalid private key")
  110. public_x = public_point[0].to_bytes(32, "big")
  111. adjusted_secret = secret if public_point[1] % 2 == 0 else CURVE_ORDER - secret
  112. aux = auxiliary_randomness if auxiliary_randomness is not None else secrets.token_bytes(32)
  113. if len(aux) != 32:
  114. raise ValueError("auxiliary randomness must be 32 bytes")
  115. masked = (adjusted_secret ^ int.from_bytes(_tagged_hash("BIP0340/aux", aux), "big")).to_bytes(32, "big")
  116. nonce = int.from_bytes(_tagged_hash("BIP0340/nonce", masked + public_x + message), "big") % CURVE_ORDER
  117. if nonce == 0:
  118. raise RuntimeError("BIP-340 produced a zero nonce")
  119. nonce_point = _point_multiply(nonce)
  120. if nonce_point is None: # pragma: no cover
  121. raise RuntimeError("BIP-340 produced an invalid nonce point")
  122. nonce_x = nonce_point[0].to_bytes(32, "big")
  123. adjusted_nonce = nonce if nonce_point[1] % 2 == 0 else CURVE_ORDER - nonce
  124. challenge = int.from_bytes(_tagged_hash("BIP0340/challenge", nonce_x + public_x + message), "big") % CURVE_ORDER
  125. return nonce_x + ((adjusted_nonce + challenge * adjusted_secret) % CURVE_ORDER).to_bytes(32, "big")
  126. def parse_auth_tag(raw: Any, label: str) -> list[str]:
  127. """Validate a NIP-OA owner-attestation tag (JSON text or list) -> ``["auth", a, b, c]``."""
  128. if isinstance(raw, str):
  129. try:
  130. raw = json.loads(raw)
  131. except json.JSONDecodeError as exc:
  132. raise ValueError(f"{label} is not valid JSON") from exc
  133. if not isinstance(raw, list) or len(raw) != 4 or raw[0] != "auth" or not all(isinstance(p, str) for p in raw):
  134. raise ValueError(f"{label} must be a four-string auth tag")
  135. return raw
  136. def build_auth_event(
  137. *, private_key: str, challenge: str, relay_url: str, auth_tag_json: str = "",
  138. created_at: Optional[int] = None, auxiliary_randomness: Optional[bytes] = None,
  139. ) -> dict[str, Any]:
  140. tags: list[list[str]] = [["relay", relay_url], ["challenge", challenge]]
  141. if auth_tag_json.strip():
  142. tags.append(parse_auth_tag(auth_tag_json, "BUZZ_AUTH_TAG"))
  143. pubkey = public_key_hex(private_key)
  144. timestamp = int(time.time()) if created_at is None else int(created_at)
  145. serialized = json.dumps([0, pubkey, timestamp, 22242, tags, ""], separators=(",", ":"), ensure_ascii=False).encode()
  146. event_id = hashlib.sha256(serialized).digest()
  147. return {
  148. "id": event_id.hex(), "pubkey": pubkey, "created_at": timestamp, "kind": 22242, "tags": tags, "content": "",
  149. "sig": schnorr_sign(event_id, private_key, auxiliary_randomness=auxiliary_randomness).hex(),
  150. }