buzzkit 0.3.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. buzzkit-0.3.1/CHANGELOG.md +195 -0
  2. {buzzkit-0.3.0 → buzzkit-0.3.1}/Cargo.lock +8 -8
  3. {buzzkit-0.3.0 → buzzkit-0.3.1}/Cargo.toml +3 -3
  4. {buzzkit-0.3.0 → buzzkit-0.3.1}/PKG-INFO +14 -7
  5. {buzzkit-0.3.0 → buzzkit-0.3.1}/README.md +13 -6
  6. {buzzkit-0.3.0 → buzzkit-0.3.1}/pyproject.toml +1 -1
  7. {buzzkit-0.3.0 → buzzkit-0.3.1}/python/buzzkit/agents.py +6 -4
  8. {buzzkit-0.3.0 → buzzkit-0.3.1}/python/buzzkit/client.py +52 -11
  9. {buzzkit-0.3.0 → buzzkit-0.3.1}/src/huddle.rs +4 -2
  10. {buzzkit-0.3.0 → buzzkit-0.3.1}/src/lib.rs +10 -3
  11. {buzzkit-0.3.0 → buzzkit-0.3.1}/tests/test_agents.py +28 -0
  12. buzzkit-0.3.1/tests/test_client.py +119 -0
  13. {buzzkit-0.3.0 → buzzkit-0.3.1}/tests/test_signing.py +19 -0
  14. buzzkit-0.3.0/tests/test_client.py +0 -27
  15. {buzzkit-0.3.0 → buzzkit-0.3.1}/.cargo/config.toml +0 -0
  16. {buzzkit-0.3.0 → buzzkit-0.3.1}/.github/workflows/CI.yml +0 -0
  17. {buzzkit-0.3.0 → buzzkit-0.3.1}/.github/workflows/release.yml +0 -0
  18. {buzzkit-0.3.0 → buzzkit-0.3.1}/.gitignore +0 -0
  19. {buzzkit-0.3.0 → buzzkit-0.3.1}/LICENSE +0 -0
  20. {buzzkit-0.3.0 → buzzkit-0.3.1}/LICENSE-APACHE +0 -0
  21. {buzzkit-0.3.0 → buzzkit-0.3.1}/NOTICE +0 -0
  22. {buzzkit-0.3.0 → buzzkit-0.3.1}/build-support/vendored-libopus.cmake +0 -0
  23. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/_shared.py +0 -0
  24. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/analyze_audio_tap.py +0 -0
  25. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/claim_invite.py +0 -0
  26. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/huddle_echo.py +0 -0
  27. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/huddle_wire_recorder.py +0 -0
  28. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/list_channels.py +0 -0
  29. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/offline_sign.py +0 -0
  30. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/send_message.py +0 -0
  31. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/set_profile.py +0 -0
  32. {buzzkit-0.3.0 → buzzkit-0.3.1}/examples/subscribe.py +0 -0
  33. {buzzkit-0.3.0 → buzzkit-0.3.1}/python/buzzkit/__init__.py +0 -0
  34. {buzzkit-0.3.0 → buzzkit-0.3.1}/python/buzzkit/_native.pyi +0 -0
  35. {buzzkit-0.3.0 → buzzkit-0.3.1}/python/buzzkit/huddle.py +0 -0
  36. {buzzkit-0.3.0 → buzzkit-0.3.1}/python/buzzkit/py.typed +0 -0
  37. {buzzkit-0.3.0 → buzzkit-0.3.1}/tests/test_huddle.py +0 -0
  38. {buzzkit-0.3.0 → buzzkit-0.3.1}/tests/test_live_relay.py +0 -0
@@ -0,0 +1,195 @@
1
+ # Changelog
2
+
3
+ All notable changes to buzzkit are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.3.1] — 2026-10-01
11
+
12
+ ### Security
13
+
14
+ - `nostr` 0.44.6 → 0.44.7, fixing RUSTSEC-2026-0225 through -0230 — among
15
+ them resource exhaustion in NIP-98 authorization parsing and in NIP-44 v2
16
+ decryption, both features buzzkit enables. `chacha20` 0.10.1 (yanked) →
17
+ 0.10.2.
18
+
19
+ ### Changed
20
+
21
+ - Upstream `buzz-core`/`buzz-sdk` pin moves from `209536ade` (post-v0.5.3) to
22
+ `5fdb2e536` (post-v0.5.26). Two visible effects:
23
+ - `build_message_event` keeps a `p` tag mentioning the signer itself
24
+ (block/buzz#4975); it was silently dropped before.
25
+ - `verify_auth_tag` rejects uppercase-hex owner keys and signatures, as
26
+ relays do.
27
+ - `start_huddle(ttl=...)` is deprecated and ignored (`DeprecationWarning` for
28
+ any value but 3600). Relays now reject a huddle announcement unless its
29
+ backing channel carries the relay's huddle TTL (block/buzz#6056) — 3600 s,
30
+ or an operator override that replaces the client's value — so any other
31
+ `ttl` failed after creating the channel.
32
+
33
+ ### Fixed
34
+
35
+ - `connect()` raises `RuntimeError` as soon as the relay rejects the NIP-42
36
+ auth (e.g. `restricted: not a relay member`) or closes the socket before
37
+ accepting it, and closes the connection. It used to log the rejection and
38
+ wait out the 20 s timeout. A relay that never answers still raises
39
+ `TimeoutError`.
40
+
41
+ ### Documented
42
+
43
+ - Owner commands: the README's check now verifies the event itself
44
+ (`verify_event`) before trusting its content and author, as upstream
45
+ `buzz-acp` does for every inbound event (block/buzz#7010).
46
+ - Close code **1008** means the community was deleted: do not reconnect
47
+ (block/buzz#4425). 1012 still means a graceful restart.
48
+ - The 1 MiB WebSocket frame cap is buzzkit's receive limit; the relay's own
49
+ inbound limit is 512 KiB by default.
50
+
51
+ ## [0.3.0] — 2026-08-02
52
+
53
+ ### Added
54
+
55
+ - **Owner control commands**: `parse_owner_command(event, agent_pubkey_hex)`
56
+ matches the platform's owner commands (`!shutdown` / `!cancel` / `!rotate`)
57
+ on the wire — kind 9, exact trimmed content, `p`-tag mention of the agent —
58
+ mirroring upstream `buzz-acp`'s `is_owner_control_command` (`!shutdown
59
+ please` is a regular message, ` !rotate ` is a command). Pure function, no
60
+ I/O. `OWNER_COMMANDS` exported.
61
+ - **`BuzzClient.verified_owner_hex`**: the NIP-OA auth tag's attester,
62
+ Schnorr-verified against the client's own pubkey at construction; `None`
63
+ when the tag is absent or does not verify. This is the value that must gate
64
+ privileged actions (e.g. honoring `!shutdown`).
65
+
66
+ ### Documented
67
+
68
+ - `owner_pubkey_hex` is **declared, not proven** — it reads the tag's owner
69
+ field without verifying the signature and must never gate privileged
70
+ actions. The README's NIP-OA section shows both halves of the
71
+ owner-command check.
72
+
73
+ ## [0.2.1] — 2026-07-31
74
+
75
+ ### Fixed
76
+
77
+ - **HTTP bridge errors are now readable**: a rejected bridge call previously
78
+ raised a bare `400 Bad Request`; the relay's actual reason (e.g.
79
+ `invalid: edit target event not found`) sat unread in the response body.
80
+ `post_event`, `query`, and `claim_invite` now raise a `RuntimeError`
81
+ carrying the status and body.
82
+
83
+ ### Documented (relay contracts, verified live)
84
+
85
+ - `delete_message(reason=...)` is **moderation-only**: a kind-9005 tombstone
86
+ carrying `public_reason` requires channel owner/admin rights and is
87
+ rejected even for the message's own author. Omit `reason` to delete your
88
+ own message.
89
+ - **The bridge acks before indexing**: an edit/delete sent immediately after
90
+ its target can transiently fail with `target event not found`; retrying is
91
+ the caller's call.
92
+
93
+ ## [0.2.0] — 2026-07-31
94
+
95
+ ### Added
96
+
97
+ - **Message lifecycle**: threaded replies
98
+ (`send_message(..., reply_to=, reply_root=)`), `react` / `remove_reaction`
99
+ (kinds 7/5), `edit_message` (kind 40003), `delete_message` (kind 9005
100
+ tombstone, optional room-facing reason), `set_topic` (kind 9002),
101
+ `leave_channel` (kind 9022).
102
+ - **Agent ownership (NIP-OA)**: `verify_auth_tag`, `verify_agent_profile`,
103
+ and `BuzzClient.resolve_agent(name, owner)` — agent-by-name lookup scoped
104
+ to the owner's kind-30177 managed-agent records, verified
105
+ cryptographically (mirrors block/buzz#3178).
106
+ - **NIP-38 user status**: `build_user_status_event` / `BuzzClient.set_status`
107
+ (kind 30315; blank text clears it).
108
+ - **Reconnect signals**: `BuzzClient.close_code` exposes the WebSocket close
109
+ code; 1012 means the relay is restarting gracefully — back off gently and
110
+ dedupe replayed events by id.
111
+
112
+ ### Changed
113
+
114
+ - Upstream `buzz-core`/`buzz-sdk` pin moves from v0.4.23 to post-v0.5.3
115
+ (`209536ade`); crate API delta is purely additive and picks up the IPv6
116
+ SSRF hardening (block/buzz#2801) and kinds 30177/30178.
117
+ - `__version__` derives from package metadata instead of a hardcoded string.
118
+ - Behavior notes when upgrading: channel names are canonicalized upstream
119
+ (leading `#` stripped; a name canonicalizing to empty raises `ValueError`);
120
+ presence contract on buzz v0.5.x relays is a 60 s heartbeat against a
121
+ 180 s TTL (30 s stays safe on both relay generations); relay REQ pages cap
122
+ at 1000 events and the advertised limit is now honest.
123
+
124
+ ### Security
125
+
126
+ - `nostr` 0.44.4 → 0.44.6, fixing RUSTSEC-2026-0216 (remote DoS via a
127
+ malformed NIP-44 payload; buzzkit enables `nip44`).
128
+
129
+ ## [0.1.4] — 2026-07-23
130
+
131
+ ### Changed
132
+
133
+ - **Huddle audio robustness**: all WebSocket I/O runs on a dedicated thread
134
+ (caller event-loop stalls can no longer distort pacing); the paced sender
135
+ never bursts (late frames are dropped and the clock realigned); silence is
136
+ streamed between utterances so receiver jitter buffers see a continuous
137
+ real-time timeline (Opus DTX keeps those packets tiny); Opus encode/decode
138
+ release the GIL.
139
+
140
+ ### Added
141
+
142
+ - `paced=False` mode: an external pacer (e.g. RoomKit's
143
+ `OutboundAudioPacer`) owns the clock and the client just relays frames.
144
+ - Diagnostics examples: `huddle_wire_recorder.py` (join as a silent peer and
145
+ record exactly what receivers get) and `analyze_audio_tap.py` (stage-by-
146
+ stage timing analysis). These traced choppy huddle audio to a Buzz desktop
147
+ playout bug (block/buzz#2652).
148
+ - CI enforces `ruff format` and `ty` type checking.
149
+
150
+ ## [0.1.3] — 2026-07-23
151
+
152
+ ### Added
153
+
154
+ - **Huddle voice**: `HuddleClient` (challenge → NIP-42 auth → joined
155
+ handshake, real-time paced Opus send, roster tracking, barge-in), Rust
156
+ `HuddleEncoder`/`HuddleDecoder` for the huddle v2 wire protocol (Opus
157
+ 48 kHz mono + 8-byte header), `BuzzClient.start_huddle()`, kind 9007/48100
158
+ builders, and `set_profile(auth_tag=)` defaulting to the client's NIP-OA
159
+ attestation.
160
+ - Self-contained wheels (static libopus) for Linux x86_64/aarch64
161
+ (manylinux_2_28), macOS x86_64/arm64, and Windows x64.
162
+
163
+ ## [0.1.2] — 2026-07-22
164
+
165
+ ### Added
166
+
167
+ - **NIP-OA owner attestation**: `compute_auth_tag(owner_secret,
168
+ agent_pubkey_hex, conditions)` (the owner attests the agent;
169
+ self-attestation rejected), `build_auth_event(..., auth_tag=)`, and
170
+ `BuzzClient(auth_tag=)` injecting the tag into AUTH and the profile.
171
+ - **Presence**: `build_presence_event` / `BuzzClient.publish_presence`
172
+ (kind 20001, ephemeral, WebSocket-published).
173
+
174
+ ## [0.1.1] — 2026-07-22
175
+
176
+ ### Added
177
+
178
+ - **Channel self-join**: `join_channel` / `build_join_channel_event`
179
+ (NIP-29 kind 9000, role `bot`). Builders allow self-tagging — `nostr`'s
180
+ `EventBuilder` otherwise strips a `p` tag naming the event author, which
181
+ made relays reject the self-join for a missing `p` tag.
182
+
183
+ ## [0.1.0] — 2026-07-22
184
+
185
+ ### Added
186
+
187
+ - Initial release. PyO3 bindings over Block's zero-I/O `buzz-core` /
188
+ `buzz-sdk` crates: keypair generation, event building/signing/verification,
189
+ NIP-42 auth events, NIP-98 HTTP auth — all synchronous, no tokio.
190
+ - Async `BuzzClient` (all I/O in Python): HTTP bridge (`query`,
191
+ `list_channels`, `send_message`, `set_profile`, `claim_invite`,
192
+ `post_event`) and authenticated WebSocket (`connect`, `subscribe`,
193
+ `subscribe_channel`, `publish`, `close`).
194
+ - One abi3 (CPython ≥ 3.12) mixed wheel; MIT-licensed with Apache-2.0
195
+ attribution (NOTICE) for the statically linked buzz crates.
@@ -146,7 +146,7 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
146
146
  [[package]]
147
147
  name = "buzz-core"
148
148
  version = "0.1.0"
149
- source = "git+https://github.com/block/buzz?rev=209536ade6c5ebf7fa82671d7ca0b74f599a40cc#209536ade6c5ebf7fa82671d7ca0b74f599a40cc"
149
+ source = "git+https://github.com/block/buzz?rev=5fdb2e53659ee29002545f1022c138fe0b8282f9#5fdb2e53659ee29002545f1022c138fe0b8282f9"
150
150
  dependencies = [
151
151
  "base64",
152
152
  "chrono",
@@ -168,7 +168,7 @@ dependencies = [
168
168
  [[package]]
169
169
  name = "buzz-sdk"
170
170
  version = "0.1.0"
171
- source = "git+https://github.com/block/buzz?rev=209536ade6c5ebf7fa82671d7ca0b74f599a40cc#209536ade6c5ebf7fa82671d7ca0b74f599a40cc"
171
+ source = "git+https://github.com/block/buzz?rev=5fdb2e53659ee29002545f1022c138fe0b8282f9#5fdb2e53659ee29002545f1022c138fe0b8282f9"
172
172
  dependencies = [
173
173
  "buzz-core",
174
174
  "nostr",
@@ -180,7 +180,7 @@ dependencies = [
180
180
 
181
181
  [[package]]
182
182
  name = "buzzkit"
183
- version = "0.3.0"
183
+ version = "0.3.1"
184
184
  dependencies = [
185
185
  "base64",
186
186
  "buzz-core",
@@ -231,9 +231,9 @@ dependencies = [
231
231
 
232
232
  [[package]]
233
233
  name = "chacha20"
234
- version = "0.10.1"
234
+ version = "0.10.2"
235
235
  source = "registry+https://github.com/rust-lang/crates.io-index"
236
- checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
236
+ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
237
237
  dependencies = [
238
238
  "cfg-if",
239
239
  "cpufeatures 0.3.0",
@@ -727,9 +727,9 @@ dependencies = [
727
727
 
728
728
  [[package]]
729
729
  name = "nostr"
730
- version = "0.44.6"
730
+ version = "0.44.7"
731
731
  source = "registry+https://github.com/rust-lang/crates.io-index"
732
- checksum = "e826dd648489de2c5b293920e20b92932ef820302007c1987c758d4d06eeb2cf"
732
+ checksum = "c7d3d987ea7078dc36947cde532637c472a229426702e4331dd7667325378bd9"
733
733
  dependencies = [
734
734
  "base64",
735
735
  "bech32",
@@ -957,7 +957,7 @@ version = "0.10.2"
957
957
  source = "registry+https://github.com/rust-lang/crates.io-index"
958
958
  checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
959
959
  dependencies = [
960
- "chacha20 0.10.1",
960
+ "chacha20 0.10.2",
961
961
  "getrandom 0.4.3",
962
962
  "rand_core 0.10.1",
963
963
  ]
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "buzzkit"
3
- version = "0.3.0"
3
+ version = "0.3.1"
4
4
  edition = "2021"
5
5
  publish = false
6
6
  description = "PyO3 bindings over Block's Buzz zero-I/O crates (buzz-core / buzz-sdk)"
@@ -20,8 +20,8 @@ pyo3 = { version = "0.24", features = ["abi3-py312"] }
20
20
  # Event/Keys/EventBuilder types unify across crate boundaries.
21
21
  nostr = { version = "0.44", features = ["nip44", "nip98"] }
22
22
  # Pinned to a specific Buzz commit; bump deliberately to track their kind churn.
23
- buzz-core = { git = "https://github.com/block/buzz", rev = "209536ade6c5ebf7fa82671d7ca0b74f599a40cc", package = "buzz-core" }
24
- buzz-sdk = { git = "https://github.com/block/buzz", rev = "209536ade6c5ebf7fa82671d7ca0b74f599a40cc", package = "buzz-sdk" }
23
+ buzz-core = { git = "https://github.com/block/buzz", rev = "5fdb2e53659ee29002545f1022c138fe0b8282f9", package = "buzz-core" }
24
+ buzz-sdk = { git = "https://github.com/block/buzz", rev = "5fdb2e53659ee29002545f1022c138fe0b8282f9", package = "buzz-sdk" }
25
25
  uuid = { version = "1", features = ["v4"] }
26
26
  sha2 = "0.10"
27
27
  hex = "0.4"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: buzzkit
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -142,12 +142,16 @@ verified = [a for a in agents if a["verification"] == "verified"]
142
142
 
143
143
  The owner controls a running agent over the relay with `!shutdown` /
144
144
  `!cancel` / `!rotate` (a kind-9 message mentioning the agent — the same wire
145
- shape Buzz's own agent harness obeys). buzzkit gives you both halves of the
146
- check:
145
+ shape Buzz's own agent harness obeys). buzzkit gives you every part of the
146
+ check — the command, the event's signature, and its author:
147
147
 
148
148
  ```python
149
149
  cmd = buzzkit.parse_owner_command(event, bz.pubkey_hex) # "shutdown" | "cancel" | "rotate" | None
150
- if cmd == "shutdown" and event["pubkey"] == bz.verified_owner_hex:
150
+ if (
151
+ cmd == "shutdown"
152
+ and buzzkit.verify_event(json.dumps(event)) # authentic: id + signature
153
+ and event["pubkey"] == bz.verified_owner_hex # sent by the proven owner
154
+ ):
151
155
  ... # proven owner intent — exit gracefully (publish_presence("offline"), close())
152
156
  ```
153
157
 
@@ -189,9 +193,12 @@ claiming. After joining, `set_profile(...)` gives the agent a display name.
189
193
  | `HuddleEncoder` / `HuddleDecoder` | raw huddle wire frames ↔ PCM |
190
194
 
191
195
  Threaded replies: `send_message(..., reply_to=<event-id>)` (add
192
- `reply_root=` for nested replies). Reconnect note: the relay closes with
193
- code **1012** on graceful restart, so check `BuzzClient.close_code` in your
194
- reconnect loop and dedupe replayed events by id.
196
+ `reply_root=` for nested replies). Reconnect note: check
197
+ `BuzzClient.close_code` in your reconnect loop. The relay closes with code
198
+ **1012** on graceful restart (back off, then dedupe replayed events by id) and
199
+ **1008** when the community was deleted (stop: there is nothing to come back
200
+ to). `connect()` raises `RuntimeError` at once when the relay rejects the
201
+ NIP-42 auth (e.g. `restricted: not a relay member`).
195
202
 
196
203
  ## Build from source
197
204
 
@@ -108,12 +108,16 @@ verified = [a for a in agents if a["verification"] == "verified"]
108
108
 
109
109
  The owner controls a running agent over the relay with `!shutdown` /
110
110
  `!cancel` / `!rotate` (a kind-9 message mentioning the agent — the same wire
111
- shape Buzz's own agent harness obeys). buzzkit gives you both halves of the
112
- check:
111
+ shape Buzz's own agent harness obeys). buzzkit gives you every part of the
112
+ check — the command, the event's signature, and its author:
113
113
 
114
114
  ```python
115
115
  cmd = buzzkit.parse_owner_command(event, bz.pubkey_hex) # "shutdown" | "cancel" | "rotate" | None
116
- if cmd == "shutdown" and event["pubkey"] == bz.verified_owner_hex:
116
+ if (
117
+ cmd == "shutdown"
118
+ and buzzkit.verify_event(json.dumps(event)) # authentic: id + signature
119
+ and event["pubkey"] == bz.verified_owner_hex # sent by the proven owner
120
+ ):
117
121
  ... # proven owner intent — exit gracefully (publish_presence("offline"), close())
118
122
  ```
119
123
 
@@ -155,9 +159,12 @@ claiming. After joining, `set_profile(...)` gives the agent a display name.
155
159
  | `HuddleEncoder` / `HuddleDecoder` | raw huddle wire frames ↔ PCM |
156
160
 
157
161
  Threaded replies: `send_message(..., reply_to=<event-id>)` (add
158
- `reply_root=` for nested replies). Reconnect note: the relay closes with
159
- code **1012** on graceful restart, so check `BuzzClient.close_code` in your
160
- reconnect loop and dedupe replayed events by id.
162
+ `reply_root=` for nested replies). Reconnect note: check
163
+ `BuzzClient.close_code` in your reconnect loop. The relay closes with code
164
+ **1012** on graceful restart (back off, then dedupe replayed events by id) and
165
+ **1008** when the community was deleted (stop: there is nothing to come back
166
+ to). `connect()` raises `RuntimeError` at once when the relay rejects the
167
+ NIP-42 auth (e.g. `restricted: not a relay member`).
161
168
 
162
169
  ## Build from source
163
170
 
@@ -4,7 +4,7 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "buzzkit"
7
- version = "0.3.0"
7
+ version = "0.3.1"
8
8
  description = "Python bindings + async client for Block's Buzz (Nostr) protocol, backed by Rust buzz-core/buzz-sdk"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -106,10 +106,12 @@ def parse_owner_command(event: dict[str, Any], agent_pubkey_hex: str) -> str | N
106
106
  agent through a ``["p", <agent_pubkey>]`` tag. Returns the bare command
107
107
  name (``"shutdown"``, ``"cancel"``, ``"rotate"``) or ``None``.
108
108
 
109
- Wire matching only — verifying that the event's *author* is the agent's
110
- owner is the caller's job (see :attr:`BuzzClient.verified_owner_hex`):
111
- upstream treats a non-owner ``!shutdown`` as a regular message, and so
112
- must callers.
109
+ Wire matching only. Before acting, the caller must also check that the
110
+ event is authentic (:func:`verify_event` on its JSON — upstream verifies
111
+ every inbound event's id and signature, so a relay cannot forge one) and
112
+ that its *author* is the agent's owner (see
113
+ :attr:`BuzzClient.verified_owner_hex`): upstream treats a non-owner
114
+ ``!shutdown`` as a regular message, and so must callers.
113
115
  """
114
116
  if event.get("kind") != _native.KIND_STREAM_MESSAGE:
115
117
  return None
@@ -21,6 +21,7 @@ import contextlib
21
21
  import json
22
22
  import logging
23
23
  import uuid
24
+ import warnings
24
25
  from collections.abc import AsyncIterator
25
26
  from typing import Any
26
27
 
@@ -34,7 +35,13 @@ logger = logging.getLogger("buzzkit.client")
34
35
 
35
36
  _AUTH_TIMEOUT = 20.0
36
37
  _OK_TIMEOUT = 20.0
37
- _MAX_FRAME = 1 << 20 # 1 MiB — matches the relay's max frame size
38
+ # Inbound cap for frames *from* the relay. The relay's own inbound limit is
39
+ # 512 KiB by default (BUZZ_MAX_FRAME_BYTES); 1 MiB is its HTTP body limit.
40
+ _MAX_FRAME = 1 << 20
41
+ # Relays reject a huddle announcement unless its backing channel carries the
42
+ # relay's huddle TTL: 3600 s, or BUZZ_EPHEMERAL_TTL_OVERRIDE, which replaces
43
+ # whatever the client sends (block/buzz#6056).
44
+ _HUDDLE_TTL = 3600
38
45
 
39
46
 
40
47
  def _checked(r: httpx.Response) -> httpx.Response:
@@ -80,11 +87,12 @@ class BuzzClient:
80
87
  #: WebSocket close code from the last disconnect (``None`` while
81
88
  #: connected or never connected). 1012 means the relay is restarting
82
89
  #: (graceful drain): reconnect with backoff and dedupe replayed
83
- #: events by id after resubscribing.
90
+ #: events by id after resubscribing. 1008 means the community was
91
+ #: deleted: do not reconnect.
84
92
  self.close_code: int | None = None
85
93
  self._ws: Any = None
86
94
  self._reader: asyncio.Task | None = None
87
- self._authed = asyncio.Event()
95
+ self._auth_result: asyncio.Future | None = None
88
96
  self._auth_event_id: str | None = None
89
97
  self._subs: dict[str, asyncio.Queue] = {}
90
98
  self._pending_ok: dict[str, asyncio.Future] = {}
@@ -203,7 +211,7 @@ class BuzzClient:
203
211
  return await self.publish(ev)
204
212
 
205
213
  async def start_huddle(
206
- self, parent_channel_id: str, *, name: str | None = None, ttl: int = 3600
214
+ self, parent_channel_id: str, *, name: str | None = None, ttl: int | None = None
207
215
  ) -> str:
208
216
  """Start a huddle in a channel; returns the ephemeral huddle channel id.
209
217
 
@@ -211,7 +219,19 @@ class BuzzClient:
211
219
  :meth:`connect` first) and posts the kind-48100 announcement to the
212
220
  parent channel. Join the audio with
213
221
  ``HuddleClient(..., huddle_id, parent_channel_id=parent_channel_id)``.
222
+
223
+ ``ttl`` is deprecated and ignored: relays only accept a huddle whose
224
+ backing channel carries their huddle TTL (3600 s, or an operator
225
+ override that replaces the client's value), so buzzkit always sends
226
+ 3600.
214
227
  """
228
+ if ttl is not None and ttl != _HUDDLE_TTL:
229
+ warnings.warn(
230
+ f"start_huddle(ttl={ttl}) is ignored: relays require a {_HUDDLE_TTL} s "
231
+ "huddle channel; the parameter will be removed",
232
+ DeprecationWarning,
233
+ stacklevel=2,
234
+ )
215
235
  huddle_id = str(uuid.uuid4())
216
236
  create_ev = _native.build_create_channel_event(
217
237
  self._secret,
@@ -219,7 +239,7 @@ class BuzzClient:
219
239
  name or f"huddle-{huddle_id[:8]}",
220
240
  visibility="private",
221
241
  channel_type="stream",
222
- ttl=ttl,
242
+ ttl=_HUDDLE_TTL,
223
243
  )
224
244
  result = await self.publish(create_ev)
225
245
  if not result["accepted"]:
@@ -391,12 +411,31 @@ class BuzzClient:
391
411
  await self.close()
392
412
 
393
413
  async def connect(self) -> None:
394
- """Open the WebSocket and complete the NIP-42 auth handshake."""
395
- self._authed.clear()
414
+ """Open the WebSocket and complete the NIP-42 auth handshake.
415
+
416
+ Raises ``RuntimeError`` as soon as the relay rejects the AUTH (e.g.
417
+ ``restricted: not a relay member``) or closes the socket before
418
+ accepting it, and ``TimeoutError`` when it never answers.
419
+ """
396
420
  self.close_code = None
421
+ self._auth_result = asyncio.get_running_loop().create_future()
397
422
  self._ws = await websockets.connect(self._ws_url, max_size=_MAX_FRAME)
398
423
  self._reader = asyncio.create_task(self._read_loop())
399
- await asyncio.wait_for(self._authed.wait(), timeout=_AUTH_TIMEOUT)
424
+ try:
425
+ await asyncio.wait_for(self._auth_result, timeout=_AUTH_TIMEOUT)
426
+ except BaseException:
427
+ await self.close()
428
+ raise
429
+
430
+ def _settle_auth(self, error: str | None) -> None:
431
+ """Resolve the pending :meth:`connect` (no-op once settled)."""
432
+ fut = self._auth_result
433
+ if fut is None or fut.done():
434
+ return
435
+ if error is None:
436
+ fut.set_result(None)
437
+ else:
438
+ fut.set_exception(RuntimeError(error))
400
439
 
401
440
  async def _read_loop(self) -> None:
402
441
  try:
@@ -431,6 +470,9 @@ class BuzzClient:
431
470
  self.close_code = close.code if close else None
432
471
  logger.info("buzz websocket closed (code %s)", self.close_code)
433
472
  finally:
473
+ self._settle_auth(
474
+ f"connection closed before NIP-42 auth completed (code {self.close_code})"
475
+ )
434
476
  for q in self._subs.values():
435
477
  q.put_nowait(("closed", "connection lost"))
436
478
 
@@ -446,10 +488,9 @@ class BuzzClient:
446
488
  accepted = bool(msg[2]) if len(msg) > 2 else False
447
489
  message = msg[3] if len(msg) > 3 else ""
448
490
  if event_id == self._auth_event_id:
449
- if accepted:
450
- self._authed.set()
451
- else:
491
+ if not accepted:
452
492
  logger.error("NIP-42 auth rejected: %s", message)
493
+ self._settle_auth(None if accepted else f"NIP-42 auth rejected: {message}")
453
494
  return
454
495
  fut = self._pending_ok.pop(event_id, None)
455
496
  if fut is not None and not fut.done():
@@ -130,8 +130,10 @@ fn pcm_bytes_to_i16(pcm: &[u8]) -> Result<Vec<i16>, String> {
130
130
  ));
131
131
  }
132
132
  Ok(pcm
133
- .chunks_exact(2)
134
- .map(|b| i16::from_le_bytes([b[0], b[1]]))
133
+ .as_chunks::<2>()
134
+ .0
135
+ .iter()
136
+ .map(|&b| i16::from_le_bytes(b))
135
137
  .collect())
136
138
  }
137
139
 
@@ -91,9 +91,16 @@ fn build_message_event(
91
91
  parent_event_id: event_id(parent, "reply_to")?,
92
92
  }),
93
93
  };
94
- let builder =
95
- buzz_sdk::build_message(cid, content, thread_ref.as_ref(), &mention_refs, false, &[])
96
- .map_err(|e| PyValueError::new_err(format!("build_message: {e}")))?;
94
+ let builder = buzz_sdk::build_message(
95
+ cid,
96
+ content,
97
+ thread_ref.as_ref(),
98
+ &mention_refs,
99
+ false,
100
+ &[],
101
+ &[],
102
+ )
103
+ .map_err(|e| PyValueError::new_err(format!("build_message: {e}")))?;
97
104
  sign(builder, &keys)
98
105
  }
99
106
 
@@ -138,6 +138,34 @@ def test_parse_owner_command_rejects_non_commands():
138
138
  assert buzzkit.parse_owner_command(malformed, agent) is None
139
139
 
140
140
 
141
+ def test_owner_command_check_rejects_forged_events():
142
+ owner_sk, owner_pk = _keys()
143
+ agent_sk, agent_pk = _keys()
144
+ bz = BuzzClient("wss://r", agent_sk, auth_tag=buzzkit.compute_auth_tag(owner_sk, agent_pk))
145
+ channel = "6b1f4b1e-1b8a-4a3e-9c51-0d7f5f2c9a10"
146
+
147
+ def message(secret: str, content: str) -> dict:
148
+ return json.loads(buzzkit.build_message_event(secret, channel, content, [agent_pk]))
149
+
150
+ def is_owner_shutdown(event: dict) -> bool: # the README's documented check
151
+ return (
152
+ buzzkit.parse_owner_command(event, bz.pubkey_hex) == "shutdown"
153
+ and buzzkit.verify_event(json.dumps(event))
154
+ and event["pubkey"] == bz.verified_owner_hex
155
+ )
156
+
157
+ assert is_owner_shutdown(message(owner_sk, "!shutdown"))
158
+ # A relay rewriting an owner's message into a command matches the wire
159
+ # shape, but no longer verifies.
160
+ forged = {**message(owner_sk, "hi"), "content": "!shutdown"}
161
+ assert buzzkit.parse_owner_command(forged, bz.pubkey_hex) == "shutdown"
162
+ assert not is_owner_shutdown(forged)
163
+ # Nor does a stranger's command relabelled with the owner's pubkey.
164
+ stranger_sk, _ = _keys()
165
+ spoofed = {**message(stranger_sk, "!shutdown"), "pubkey": owner_pk}
166
+ assert not is_owner_shutdown(spoofed)
167
+
168
+
141
169
  def test_verified_owner_hex_proves_the_attestation():
142
170
  owner_sk, owner_pk = _keys()
143
171
  agent_sk, agent_pk = _keys()
@@ -0,0 +1,119 @@
1
+ """Offline tests for BuzzClient: HTTP bridge errors, auth handshake, huddle start."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ import uuid
9
+ import warnings
10
+
11
+ import buzzkit
12
+ import httpx
13
+ import pytest
14
+ import websockets
15
+ from buzzkit.client import BuzzClient
16
+
17
+
18
+ async def test_post_event_surfaces_relay_error_body(monkeypatch):
19
+ def handler(request: httpx.Request) -> httpx.Response:
20
+ return httpx.Response(400, json={"error": "invalid: edit target event not found"})
21
+
22
+ real = httpx.AsyncClient
23
+ monkeypatch.setattr(
24
+ httpx,
25
+ "AsyncClient",
26
+ lambda **kw: real(transport=httpx.MockTransport(handler), timeout=1),
27
+ )
28
+ nsec, _, _ = buzzkit.generate_keypair()
29
+ bz = BuzzClient("wss://relay.example", nsec)
30
+ ev = buzzkit.build_message_event(nsec, str(uuid.uuid4()), "x")
31
+ with pytest.raises(RuntimeError, match="edit target event not found"):
32
+ await bz.post_event(ev)
33
+
34
+
35
+ # ── WebSocket auth handshake (fake relay) ────────────────────────────────────
36
+
37
+
38
+ @contextlib.asynccontextmanager
39
+ async def serve(handler):
40
+ server = await websockets.serve(handler, "127.0.0.1", 0)
41
+ port = server.sockets[0].getsockname()[1]
42
+ try:
43
+ yield f"ws://127.0.0.1:{port}"
44
+ finally:
45
+ server.close()
46
+ await server.wait_closed()
47
+
48
+
49
+ async def _challenge_and_read_auth(ws) -> dict:
50
+ await ws.send(json.dumps(["AUTH", "challenge-1"]))
51
+ return json.loads(await ws.recv())[1]
52
+
53
+
54
+ async def test_connect_completes_on_accepted_auth():
55
+ async def handler(ws):
56
+ auth = await _challenge_and_read_auth(ws)
57
+ await ws.send(json.dumps(["OK", auth["id"], True, ""]))
58
+ await ws.wait_closed()
59
+
60
+ nsec, _, _ = buzzkit.generate_keypair()
61
+ async with serve(handler) as url:
62
+ bz = BuzzClient(url, nsec)
63
+ await asyncio.wait_for(bz.connect(), 2)
64
+ await bz.close()
65
+
66
+
67
+ async def test_connect_fails_fast_on_rejected_auth():
68
+ async def handler(ws):
69
+ auth = await _challenge_and_read_auth(ws)
70
+ await ws.send(json.dumps(["OK", auth["id"], False, "restricted: not a relay member"]))
71
+ await ws.wait_closed()
72
+
73
+ nsec, _, _ = buzzkit.generate_keypair()
74
+ async with serve(handler) as url:
75
+ bz = BuzzClient(url, nsec)
76
+ # Well under the 20 s auth timeout: the rejection itself ends connect().
77
+ with pytest.raises(RuntimeError, match="not a relay member"):
78
+ await asyncio.wait_for(bz.connect(), 2)
79
+ assert bz._ws is None
80
+
81
+
82
+ async def test_connect_fails_fast_when_closed_before_auth():
83
+ async def handler(ws):
84
+ await _challenge_and_read_auth(ws)
85
+ await ws.close(code=1008, reason="community deleted")
86
+
87
+ nsec, _, _ = buzzkit.generate_keypair()
88
+ async with serve(handler) as url:
89
+ bz = BuzzClient(url, nsec)
90
+ with pytest.raises(RuntimeError, match="closed before NIP-42 auth"):
91
+ await asyncio.wait_for(bz.connect(), 2)
92
+ assert bz.close_code == 1008
93
+
94
+
95
+ # ── start_huddle ─────────────────────────────────────────────────────────────
96
+
97
+
98
+ async def test_start_huddle_always_sends_the_relay_huddle_ttl(monkeypatch):
99
+ nsec, _, _ = buzzkit.generate_keypair()
100
+ bz = BuzzClient("wss://relay.example", nsec)
101
+ published: list[dict] = []
102
+
103
+ async def fake_publish(event_json: str) -> dict:
104
+ published.append(json.loads(event_json))
105
+ return {"accepted": True, "event_id": published[-1]["id"], "message": ""}
106
+
107
+ monkeypatch.setattr(bz, "publish", fake_publish)
108
+ parent = str(uuid.uuid4())
109
+ with pytest.warns(DeprecationWarning, match="ttl=7200"):
110
+ await bz.start_huddle(parent, ttl=7200)
111
+ with warnings.catch_warnings():
112
+ warnings.simplefilter("error") # the default and an explicit 3600 stay silent
113
+ await bz.start_huddle(parent)
114
+ await bz.start_huddle(parent, ttl=3600)
115
+
116
+ created = [ev for ev in published if ev["kind"] == buzzkit.KIND_CREATE_CHANNEL]
117
+ assert len(created) == 3
118
+ for ev in created:
119
+ assert ["ttl", "3600"] in ev["tags"]
@@ -145,6 +145,13 @@ def test_join_channel_event_keeps_self_p_tag():
145
145
  assert any(t[0] == "h" for t in event["tags"])
146
146
 
147
147
 
148
+ def test_message_event_keeps_self_mention():
149
+ nsec, _, pk_hex = buzzkit.generate_keypair()
150
+ event = json.loads(buzzkit.build_message_event(nsec, str(uuid.uuid4()), "note", [pk_hex]))
151
+ # Self-mentions survive nostr's self-tag stripping (upstream block/buzz#4975).
152
+ assert ["p", pk_hex] in event["tags"]
153
+
154
+
148
155
  def test_compute_auth_tag():
149
156
  owner_nsec, _, owner_pk = buzzkit.generate_keypair()
150
157
  _, _, agent_pk = buzzkit.generate_keypair()
@@ -222,6 +229,18 @@ def test_verify_auth_tag_roundtrip():
222
229
  buzzkit.verify_auth_tag("not json", agent_pk)
223
230
 
224
231
 
232
+ def test_verify_auth_tag_rejects_noncanonical_hex():
233
+ owner_nsec, _, _ = buzzkit.generate_keypair()
234
+ _, _, agent_pk = buzzkit.generate_keypair()
235
+ tag = json.loads(buzzkit.compute_auth_tag(owner_nsec, agent_pk))
236
+ # Relays reject uppercase hex; verification must not accept what they refuse.
237
+ for i in (1, 3):
238
+ upper = list(tag)
239
+ upper[i] = upper[i].upper()
240
+ with pytest.raises(ValueError):
241
+ buzzkit.verify_auth_tag(json.dumps(upper), agent_pk)
242
+
243
+
225
244
  def test_huddle_started_event():
226
245
  nsec, _, _ = buzzkit.generate_keypair()
227
246
  parent, ephemeral = str(uuid.uuid4()), str(uuid.uuid4())
@@ -1,27 +0,0 @@
1
- """Offline tests for BuzzClient's HTTP bridge error surfacing."""
2
-
3
- from __future__ import annotations
4
-
5
- import uuid
6
-
7
- import buzzkit
8
- import httpx
9
- import pytest
10
- from buzzkit.client import BuzzClient
11
-
12
-
13
- async def test_post_event_surfaces_relay_error_body(monkeypatch):
14
- def handler(request: httpx.Request) -> httpx.Response:
15
- return httpx.Response(400, json={"error": "invalid: edit target event not found"})
16
-
17
- real = httpx.AsyncClient
18
- monkeypatch.setattr(
19
- httpx,
20
- "AsyncClient",
21
- lambda **kw: real(transport=httpx.MockTransport(handler), timeout=1),
22
- )
23
- nsec, _, _ = buzzkit.generate_keypair()
24
- bz = BuzzClient("wss://relay.example", nsec)
25
- ev = buzzkit.build_message_event(nsec, str(uuid.uuid4()), "x")
26
- with pytest.raises(RuntimeError, match="edit target event not found"):
27
- await bz.post_event(ev)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes