buzzkit 0.2.0__tar.gz → 0.3.0__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 (36) hide show
  1. {buzzkit-0.2.0 → buzzkit-0.3.0}/Cargo.lock +1 -1
  2. {buzzkit-0.2.0 → buzzkit-0.3.0}/Cargo.toml +1 -1
  3. {buzzkit-0.2.0 → buzzkit-0.3.0}/PKG-INFO +17 -1
  4. {buzzkit-0.2.0 → buzzkit-0.3.0}/README.md +16 -0
  5. {buzzkit-0.2.0 → buzzkit-0.3.0}/pyproject.toml +1 -1
  6. {buzzkit-0.2.0 → buzzkit-0.3.0}/python/buzzkit/__init__.py +3 -1
  7. {buzzkit-0.2.0 → buzzkit-0.3.0}/python/buzzkit/agents.py +35 -0
  8. {buzzkit-0.2.0 → buzzkit-0.3.0}/python/buzzkit/client.py +56 -13
  9. {buzzkit-0.2.0 → buzzkit-0.3.0}/src/lib.rs +4 -2
  10. {buzzkit-0.2.0 → buzzkit-0.3.0}/tests/test_agents.py +56 -0
  11. buzzkit-0.3.0/tests/test_client.py +27 -0
  12. {buzzkit-0.2.0 → buzzkit-0.3.0}/.cargo/config.toml +0 -0
  13. {buzzkit-0.2.0 → buzzkit-0.3.0}/.github/workflows/CI.yml +0 -0
  14. {buzzkit-0.2.0 → buzzkit-0.3.0}/.github/workflows/release.yml +0 -0
  15. {buzzkit-0.2.0 → buzzkit-0.3.0}/.gitignore +0 -0
  16. {buzzkit-0.2.0 → buzzkit-0.3.0}/LICENSE +0 -0
  17. {buzzkit-0.2.0 → buzzkit-0.3.0}/LICENSE-APACHE +0 -0
  18. {buzzkit-0.2.0 → buzzkit-0.3.0}/NOTICE +0 -0
  19. {buzzkit-0.2.0 → buzzkit-0.3.0}/build-support/vendored-libopus.cmake +0 -0
  20. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/_shared.py +0 -0
  21. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/analyze_audio_tap.py +0 -0
  22. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/claim_invite.py +0 -0
  23. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/huddle_echo.py +0 -0
  24. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/huddle_wire_recorder.py +0 -0
  25. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/list_channels.py +0 -0
  26. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/offline_sign.py +0 -0
  27. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/send_message.py +0 -0
  28. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/set_profile.py +0 -0
  29. {buzzkit-0.2.0 → buzzkit-0.3.0}/examples/subscribe.py +0 -0
  30. {buzzkit-0.2.0 → buzzkit-0.3.0}/python/buzzkit/_native.pyi +0 -0
  31. {buzzkit-0.2.0 → buzzkit-0.3.0}/python/buzzkit/huddle.py +0 -0
  32. {buzzkit-0.2.0 → buzzkit-0.3.0}/python/buzzkit/py.typed +0 -0
  33. {buzzkit-0.2.0 → buzzkit-0.3.0}/src/huddle.rs +0 -0
  34. {buzzkit-0.2.0 → buzzkit-0.3.0}/tests/test_huddle.py +0 -0
  35. {buzzkit-0.2.0 → buzzkit-0.3.0}/tests/test_live_relay.py +0 -0
  36. {buzzkit-0.2.0 → buzzkit-0.3.0}/tests/test_signing.py +0 -0
@@ -180,7 +180,7 @@ dependencies = [
180
180
 
181
181
  [[package]]
182
182
  name = "buzzkit"
183
- version = "0.2.0"
183
+ version = "0.3.0"
184
184
  dependencies = [
185
185
  "base64",
186
186
  "buzz-core",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "buzzkit"
3
- version = "0.2.0"
3
+ version = "0.3.0"
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)"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: buzzkit
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -140,6 +140,21 @@ agents = await bz.resolve_agent("Honey", owner_pubkey_hex)
140
140
  verified = [a for a in agents if a["verification"] == "verified"]
141
141
  ```
142
142
 
143
+ The owner controls a running agent over the relay with `!shutdown` /
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:
147
+
148
+ ```python
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:
151
+ ... # proven owner intent — exit gracefully (publish_presence("offline"), close())
152
+ ```
153
+
154
+ `verified_owner_hex` is the auth tag's attester, Schnorr-verified against the
155
+ client's own pubkey at construction (`None` when absent or invalid); the
156
+ unverified `owner_pubkey_hex` must never gate privileged actions.
157
+
143
158
  ## Joining a community (relay onboarding)
144
159
 
145
160
  Hosted Buzz communities are **closed relays**: an identity must be a relay member
@@ -165,6 +180,7 @@ claiming. After joining, `set_profile(...)` gives the agent a display name.
165
180
  | `pubkey_from_secret(secret)` | derive `(npub, hex)` |
166
181
  | `build_*_event` (message/reply, reaction, edit, delete, profile, user status, channel, presence…) | build + sign events |
167
182
  | `compute_auth_tag` / `verify_auth_tag` / `verify_agent_profile` | NIP-OA owner attestation |
183
+ | `parse_owner_command` / `BuzzClient.verified_owner_hex` / `OWNER_COMMANDS` | owner control commands (`!shutdown`…) |
168
184
  | `sign_nip98(secret, method, url, body)` | HTTP bridge auth header |
169
185
  | `verify_event(json)` | check id + Schnorr signature |
170
186
  | `BuzzClient.send_message / react / remove_reaction / edit_message / set_profile / set_status / resolve_agent / query / list_channels / claim_invite` | HTTP bridge |
@@ -106,6 +106,21 @@ agents = await bz.resolve_agent("Honey", owner_pubkey_hex)
106
106
  verified = [a for a in agents if a["verification"] == "verified"]
107
107
  ```
108
108
 
109
+ The owner controls a running agent over the relay with `!shutdown` /
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:
113
+
114
+ ```python
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:
117
+ ... # proven owner intent — exit gracefully (publish_presence("offline"), close())
118
+ ```
119
+
120
+ `verified_owner_hex` is the auth tag's attester, Schnorr-verified against the
121
+ client's own pubkey at construction (`None` when absent or invalid); the
122
+ unverified `owner_pubkey_hex` must never gate privileged actions.
123
+
109
124
  ## Joining a community (relay onboarding)
110
125
 
111
126
  Hosted Buzz communities are **closed relays**: an identity must be a relay member
@@ -131,6 +146,7 @@ claiming. After joining, `set_profile(...)` gives the agent a display name.
131
146
  | `pubkey_from_secret(secret)` | derive `(npub, hex)` |
132
147
  | `build_*_event` (message/reply, reaction, edit, delete, profile, user status, channel, presence…) | build + sign events |
133
148
  | `compute_auth_tag` / `verify_auth_tag` / `verify_agent_profile` | NIP-OA owner attestation |
149
+ | `parse_owner_command` / `BuzzClient.verified_owner_hex` / `OWNER_COMMANDS` | owner control commands (`!shutdown`…) |
134
150
  | `sign_nip98(secret, method, url, body)` | HTTP bridge auth header |
135
151
  | `verify_event(json)` | check id + Schnorr signature |
136
152
  | `BuzzClient.send_message / react / remove_reaction / edit_message / set_profile / set_status / resolve_agent / query / list_channels / claim_invite` | HTTP bridge |
@@ -4,7 +4,7 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "buzzkit"
7
- version = "0.2.0"
7
+ version = "0.3.0"
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"
@@ -57,7 +57,7 @@ from ._native import (
57
57
  verify_auth_tag,
58
58
  verify_event,
59
59
  )
60
- from .agents import verify_agent_profile
60
+ from .agents import OWNER_COMMANDS, parse_owner_command, verify_agent_profile
61
61
  from .client import BuzzClient
62
62
  from .huddle import (
63
63
  HuddleAudio,
@@ -93,6 +93,7 @@ __all__ = [
93
93
  "KIND_STREAM_MESSAGE",
94
94
  "KIND_STREAM_MESSAGE_V2",
95
95
  "KIND_USER_STATUS",
96
+ "OWNER_COMMANDS",
96
97
  "BuzzClient",
97
98
  "HuddleAudio",
98
99
  "HuddleClient",
@@ -120,6 +121,7 @@ __all__ = [
120
121
  "generate_keypair",
121
122
  "pubkey_from_secret",
122
123
  "sign_nip98",
124
+ "parse_owner_command",
123
125
  "verify_agent_profile",
124
126
  "verify_auth_tag",
125
127
  "verify_event",
@@ -89,3 +89,38 @@ def verify_agent_profile(profile_event: dict[str, Any], owner_pubkey_hex: str) -
89
89
  if not _conditions_apply(tag[2], profile_event):
90
90
  return "condition_mismatch"
91
91
  return "verified"
92
+
93
+
94
+ #: Owner control commands the Buzz platform defines. The message content,
95
+ #: trimmed, must equal ``!<command>`` exactly — ``!shutdown please`` is a
96
+ #: regular message, not a command (mirrors upstream ``buzz-acp``).
97
+ OWNER_COMMANDS = ("shutdown", "cancel", "rotate")
98
+
99
+
100
+ def parse_owner_command(event: dict[str, Any], agent_pubkey_hex: str) -> str | None:
101
+ """Match a Buzz owner control command addressed to ``agent_pubkey_hex``.
102
+
103
+ Mirrors upstream ``buzz-acp``'s ``is_owner_control_command``: a control
104
+ command is a chat message (kind 9) whose trimmed content is exactly one
105
+ of :data:`OWNER_COMMANDS` prefixed with ``!``, and which mentions the
106
+ agent through a ``["p", <agent_pubkey>]`` tag. Returns the bare command
107
+ name (``"shutdown"``, ``"cancel"``, ``"rotate"``) or ``None``.
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.
113
+ """
114
+ if event.get("kind") != _native.KIND_STREAM_MESSAGE:
115
+ return None
116
+ content = str(event.get("content", "") or "").strip()
117
+ if not content.startswith("!") or content[1:] not in OWNER_COMMANDS:
118
+ return None
119
+ tags = event.get("tags")
120
+ if not isinstance(tags, list):
121
+ return None
122
+ mentioned = any(
123
+ isinstance(t, list) and len(t) >= 2 and t[0] == "p" and t[1] == agent_pubkey_hex
124
+ for t in tags
125
+ )
126
+ return content[1:] if mentioned else None
@@ -37,6 +37,17 @@ _OK_TIMEOUT = 20.0
37
37
  _MAX_FRAME = 1 << 20 # 1 MiB — matches the relay's max frame size
38
38
 
39
39
 
40
+ def _checked(r: httpx.Response) -> httpx.Response:
41
+ """Raise a readable error carrying the relay's response body on 4xx/5xx.
42
+
43
+ The bridge explains rejections in the body (e.g. ``{"error": "invalid:
44
+ edit target event not found"}``); a bare ``raise_for_status`` hides it.
45
+ """
46
+ if r.status_code >= 400:
47
+ raise RuntimeError(f"HTTP bridge error {r.status_code} on {r.url.path}: {r.text}")
48
+ return r
49
+
50
+
40
51
  def _to_http(relay_url: str) -> str:
41
52
  u = relay_url.rstrip("/")
42
53
  if u.startswith("wss://"):
@@ -65,6 +76,7 @@ class BuzzClient:
65
76
  self._secret = secret
66
77
  self._auth_tag = auth_tag # NIP-OA owner attestation (AUTH + profile)
67
78
  self.npub, self.pubkey_hex = _native.pubkey_from_secret(secret)
79
+ self._verified_owner = self._verify_owner() # attestations are immutable
68
80
  #: WebSocket close code from the last disconnect (``None`` while
69
81
  #: connected or never connected). 1012 means the relay is restarting
70
82
  #: (graceful drain): reconnect with backoff and dedupe replayed
@@ -83,7 +95,12 @@ class BuzzClient:
83
95
  return _native.sign_nip98(self._secret, method, url, body)
84
96
 
85
97
  async def post_event(self, event_json: str) -> dict:
86
- """POST a signed event to the HTTP bridge (non-ephemeral kinds only)."""
98
+ """POST a signed event to the HTTP bridge (non-ephemeral kinds only).
99
+
100
+ The bridge acknowledges before the event is fully indexed: a revision
101
+ (edit/delete/reaction) sent immediately after its target can be
102
+ rejected with "target event not found". Retrying is the caller's call.
103
+ """
87
104
  url = f"{self._http}/events"
88
105
  body = event_json.encode("utf-8")
89
106
  headers = {
@@ -91,9 +108,7 @@ class BuzzClient:
91
108
  "Content-Type": "application/json",
92
109
  }
93
110
  async with httpx.AsyncClient(timeout=20.0) as c:
94
- r = await c.post(url, content=body, headers=headers)
95
- r.raise_for_status()
96
- return r.json()
111
+ return _checked(await c.post(url, content=body, headers=headers)).json()
97
112
 
98
113
  async def send_message(
99
114
  self,
@@ -133,7 +148,12 @@ class BuzzClient:
133
148
  self, channel_id: str, target_event_id: str, *, reason: str | None = None
134
149
  ) -> dict:
135
150
  """Delete a message (kind 9005 tombstone). Management kind — needs
136
- :meth:`connect` first; ``reason`` is shown room-facing."""
151
+ :meth:`connect` first.
152
+
153
+ ``reason`` (the room-facing ``public_reason``) marks the tombstone as
154
+ a MODERATION action: the relay then requires channel owner/admin
155
+ rights, and rejects it even for the message's own author. Omit it to
156
+ delete your own message."""
137
157
  ev = _native.build_delete_message_event(self._secret, channel_id, target_event_id, reason)
138
158
  return await self.publish(ev)
139
159
 
@@ -234,9 +254,7 @@ class BuzzClient:
234
254
  "Content-Type": "application/json",
235
255
  }
236
256
  async with httpx.AsyncClient(timeout=20.0) as c:
237
- r = await c.post(url, content=body, headers=headers)
238
- r.raise_for_status()
239
- data = r.json()
257
+ data = _checked(await c.post(url, content=body, headers=headers)).json()
240
258
  return data if isinstance(data, list) else []
241
259
 
242
260
  async def list_channels(self) -> list[dict]:
@@ -300,11 +318,38 @@ class BuzzClient:
300
318
 
301
319
  @property
302
320
  def owner_pubkey_hex(self) -> str:
303
- """This identity's effective owner: its auth-tag attester, else itself."""
321
+ """This identity's effective owner: its auth-tag attester, else itself.
322
+
323
+ Declared, not proven — this reads the tag's owner field without
324
+ verifying its signature. Anything that grants the owner privileges
325
+ (e.g. honoring ``!shutdown``) must use :attr:`verified_owner_hex`.
326
+ """
304
327
  if self._auth_tag is not None:
305
328
  return json.loads(self._auth_tag)[1]
306
329
  return self.pubkey_hex
307
330
 
331
+ def _verify_owner(self) -> str | None:
332
+ if self._auth_tag is None:
333
+ return None
334
+ try:
335
+ return _native.verify_auth_tag(self._auth_tag, self.pubkey_hex)
336
+ except ValueError as e:
337
+ logger.warning("auth tag does not verify for this identity: %s", e)
338
+ return None
339
+
340
+ @property
341
+ def verified_owner_hex(self) -> str | None:
342
+ """The owner pubkey hex *proven* by this client's NIP-OA auth tag.
343
+
344
+ The tag's Schnorr signature was verified against this client's own
345
+ pubkey (:func:`verify_auth_tag`) at construction. ``None`` when the
346
+ client has no auth tag or the tag does not verify — callers gating
347
+ privileged actions (e.g. honoring ``!shutdown``) must treat ``None``
348
+ as "no owner", never fall back to the unverified
349
+ :attr:`owner_pubkey_hex`.
350
+ """
351
+ return self._verified_owner
352
+
308
353
  async def claim_invite(self, code_or_url: str) -> dict:
309
354
  """Redeem a relay invite: accept the join-policy (if any), then claim.
310
355
 
@@ -323,8 +368,7 @@ class BuzzClient:
323
368
  "age_confirmed": True,
324
369
  },
325
370
  )
326
- rp.raise_for_status()
327
- receipt = rp.json()["receipt"]
371
+ receipt = _checked(rp).json()["receipt"]
328
372
  payload: dict = {"code": code}
329
373
  if receipt:
330
374
  payload["policy_receipt"] = receipt
@@ -335,8 +379,7 @@ class BuzzClient:
335
379
  "Content-Type": "application/json",
336
380
  }
337
381
  rc = await c.post(url, content=body, headers=headers)
338
- rc.raise_for_status()
339
- return rc.json()
382
+ return _checked(rc).json()
340
383
 
341
384
  # ------------------------------------------------------------- WebSocket
342
385
 
@@ -136,8 +136,10 @@ fn build_edit_event(
136
136
  }
137
137
 
138
138
  /// Build and sign a message delete tombstone (kind 9005). `reason`, when
139
- /// given, becomes the room-facing `public_reason` tag. Management kind —
140
- /// publish over the WebSocket.
139
+ /// given, becomes the room-facing `public_reason` tag — which marks the
140
+ /// tombstone as a moderation action the relay only accepts from a channel
141
+ /// owner/admin (authors deleting their own message must omit it).
142
+ /// Management kind — publish over the WebSocket.
141
143
  #[pyfunction]
142
144
  #[pyo3(signature = (secret, channel_id, target_event_id, reason=None))]
143
145
  fn build_delete_message_event(
@@ -96,3 +96,59 @@ async def test_resolve_agent_scopes_to_owner_records(monkeypatch):
96
96
  assert by_pk[agent_pk]["profile"]["display_name"] == "Honey"
97
97
  assert by_pk[missing_pk]["verification"] == "missing_profile"
98
98
  assert "owner_pubkey" not in by_pk[missing_pk]
99
+
100
+
101
+ # ── owner control commands ───────────────────────────────────────────────────
102
+
103
+
104
+ def _command_event(content: str, agent_pk: str, *, kind: int = 9) -> dict:
105
+ return {
106
+ "kind": kind,
107
+ "pubkey": "f" * 64,
108
+ "content": content,
109
+ "tags": [["h", "chan-uuid"], ["p", agent_pk]],
110
+ }
111
+
112
+
113
+ def test_parse_owner_command_matches_the_wire_shape():
114
+ agent = "a" * 64
115
+ for command in buzzkit.OWNER_COMMANDS:
116
+ assert buzzkit.parse_owner_command(_command_event(f"!{command}", agent), agent) == command
117
+ # upstream trims: " !rotate " is a command (buzz-acp has this exact case)
118
+ assert buzzkit.parse_owner_command(_command_event(" !rotate ", agent), agent) == "rotate"
119
+
120
+
121
+ def test_parse_owner_command_rejects_non_commands():
122
+ agent = "a" * 64
123
+ cases = [
124
+ _command_event("!shutdown please", agent), # exact match only
125
+ _command_event("shutdown", agent), # no bang
126
+ _command_event("!reboot", agent), # unknown command
127
+ _command_event("", agent), # empty
128
+ _command_event("!shutdown", agent, kind=40002), # wrong kind (V2 is not matched)
129
+ _command_event("!shutdown", "b" * 64), # mentions another agent
130
+ ]
131
+ for event in cases:
132
+ assert buzzkit.parse_owner_command(event, agent) is None
133
+ unmentioned = _command_event("!shutdown", agent)
134
+ unmentioned["tags"] = [["h", "chan-uuid"]]
135
+ assert buzzkit.parse_owner_command(unmentioned, agent) is None
136
+ malformed = _command_event("!shutdown", agent)
137
+ malformed["tags"] = "not-a-list"
138
+ assert buzzkit.parse_owner_command(malformed, agent) is None
139
+
140
+
141
+ def test_verified_owner_hex_proves_the_attestation():
142
+ owner_sk, owner_pk = _keys()
143
+ agent_sk, agent_pk = _keys()
144
+ tag = buzzkit.compute_auth_tag(owner_sk, agent_pk)
145
+ assert BuzzClient("wss://r", agent_sk, auth_tag=tag).verified_owner_hex == owner_pk
146
+ # no tag → no owner
147
+ assert BuzzClient("wss://r", agent_sk).verified_owner_hex is None
148
+ # a tag attesting a DIFFERENT agent does not verify for this client...
149
+ other_sk, other_pk = _keys()
150
+ stolen = buzzkit.compute_auth_tag(owner_sk, other_pk)
151
+ client = BuzzClient("wss://r", agent_sk, auth_tag=stolen)
152
+ assert client.verified_owner_hex is None
153
+ # ...even though the unverified reading still names the claimed owner
154
+ assert client.owner_pubkey_hex == owner_pk
@@ -0,0 +1,27 @@
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
File without changes
File without changes