1. Executive Summary
Buzz is a self-hosted team communication platform built on the Nostr protocol (NIP-01 wire format), where AI agents and humans are first-class equals. Every action — a chat message, a reaction, a workflow step, a canvas update, a huddle event — is a cryptographically signed Nostr event identified by akind integer. Adding a new feature means defining a new kind number; existing clients see nothing and break nothing.
The relay is the single source of truth. All reads and writes flow through it. There is no peer-to-peer event exchange, no gossip, no replication — just clients connecting to one relay over WebSocket, and the relay enforcing auth, verifying signatures, persisting events, fanning out to subscribers, indexing for search, and triggering automation.
A Buzz community is the tenant-visible workspace selected by the request host.
The self-hosted default remains one host, one relay process, one implicit
community. Multi-community deployments move that semantic boundary one level up:
req.community = resolve_host(connection.host) is established before AUTH,
EVENT, REQ, REST, media, git, search, workflow, or pub/sub handling. Unknown
hosts fail closed, and NIP-98/API-token stamps must agree with the host-derived
community rather than overriding it.
Buzz is a Rust monorepo, licensed Apache 2.0 under Block, Inc.
System Architecture
Crate Dependency Hierarchy
buzz-relay orchestrates all subsystems by calling them directly — it imports buzz-db, buzz-auth, buzz-pubsub, buzz-search, buzz-audit, and buzz-workflow. However, those subsystems are isolated from each other: buzz-workflow never calls buzz-pubsub, buzz-search never calls buzz-db, etc. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of TenantContext; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags.
2. The Protocol
Buzz uses Nostr NIP-01 on the wire. Every action is a JSON event with six fields:kind integer is the only dispatch switch. The relay routes, stores, and fans out events based on kind. Clients filter subscriptions by kind. New feature = new kind number = zero breaking changes to existing clients.
Kind Ranges
Buzz Custom Kinds (selected)
buzz-core defines all 81 kinds as pub const KIND_*: u32 and exports ALL_KINDS: &[u32]. Kinds are u32 (NIP-01 specifies unsigned integer; u32 covers the full range). Buzz uses both standard Nostr kinds (e.g., kind 7 for reactions) and custom ranges (40000+).
Note: KIND_AUTH (22242) is pub const KIND_AUTH: u32 in buzz-core/src/kind.rs and imported by buzz-relay/src/handlers/event.rs. KIND_CANVAS (40100) is likewise pub const KIND_CANVAS: u32 in buzz-core/src/kind.rs.
Wire Protocol (NIP-01 messages)
Max frame size: 65,536 bytes. Max subscriptions per connection: 1024. Max historical results per filter: 500.
3. Connection Lifecycle
Every WebSocket connection follows this exact sequence:Step 0: Community Binding
The server resolvesTenantContext from the request host before any handler can
observe tenant data. The URL/domain is authoritative for the community, matching
today’s “the relay URL is the workspace” behavior. In single-community mode the
configured host maps to the default community. In multi-community mode, an
unknown or unmapped host rejects generically and never falls through to a default
tenant. Client-supplied #h tags are still channel identifiers; they must resolve
to a channel inside the host-derived community.
Step 1: Semaphore Acquire
state.conn_semaphore.try_acquire_owned() — if the relay is at connection capacity, the connection is rejected immediately before any data is read. The permit is held for the entire connection lifetime and dropped on cleanup.
Step 2: NIP-42 Challenge
The relay immediately sends["AUTH", "<challenge>"]. The challenge is a random string. The connection is registered in ConnectionManager after the challenge is sent.
Step 3: Authentication
The client must respond with["AUTH", <signed-event>] before submitting events or subscriptions. Authentication paths:
On success,
ConnectionState.auth_state transitions from Pending → Authenticated(AuthContext). On failure → Failed. Unauthenticated EVENT/REQ messages are rejected with ["CLOSED", ...] or ["OK", ..., false, "auth-required: ..."].
Step 4: Active Loops
Three concurrent tasks run for the lifetime of the connection:- recv_loop (inline): reads frames, parses
ClientMessage, dispatches to handlers - send_loop (spawned): drains the mpsc channel, writes frames to the WebSocket
- heartbeat_loop (spawned): sends WebSocket ping every 30 seconds; 3 missed pongs → disconnect
CancellationToken coordinates shutdown across all three loops.
Slow clients: ConnectionState::send() uses try_send — if the send buffer is full, a grace counter increments. After SLOW_CLIENT_GRACE_LIMIT (3) consecutive full-buffer events, the connection is cancelled. A successful send resets the counter.
Step 5: Cleanup
On disconnect (any cause):cancel.cancel()— signals all loops- Await send_loop and heartbeat_loop tasks
sub_registry.remove_connection(conn_id)— removes all subscriptions from the DashMap indexesconn_manager.deregister(conn_id)— removes from the send-channel mapdrop(permit)— releases the connection semaphore slot
4. Event Pipeline
When the relay receives["EVENT", <event>], the handler in handlers/event.rs runs this pipeline in order:
search_index_tx, capacity 1000); audit and workflow triggers are spawned as independent async tasks. A failure in any of these does not fail the event submission. The client receives ["OK", <id>, true, ""] at the end of the pipeline, not immediately after DB insert.
Step 9 (fan-out) explicitly excludes global subscriptions (no channel_id constraint) from channel-scoped events — global subscriptions do NOT receive events from private channels, regardless of filter match. This is a deliberate security boundary: only subscriptions scoped to an accessible channel_id receive those events.
Workflow loop prevention: workflow execution kinds (46001–46012), relay-signed messages with buzz:workflow tag, and KIND_GIFT_WRAP are excluded from triggering workflows. All other stored events (including kind 9 stream messages) trigger workflow evaluation.
Ephemeral Sub-Pipeline (kinds 20000–29999)
Ephemeral events bypass DB storage, audit, and search. Two sub-paths: Presence events (kind 20001):Handler Semaphore
Beyond the per-connection semaphore, ahandler_semaphore (capacity 1024) limits concurrent EVENT and REQ processing across all connections. CLOSE is not rate-limited.
5. Subscription System
SubscriptionRegistry
The subscription registry is a DashMap-backed structure insubscription.rs:
Three-Tier Fan-Out
When an event arrives,fan_out consults three indexes in order:
Global subs (tier 3) are checked for non-channel-scoped events only. Channel-scoped events are delivered exclusively to subscriptions that carry a matching
channel_id — global subscriptions are explicitly excluded from channel fan-out as a security boundary.
NIP-01 Edge Cases
kinds: [](explicit empty array) means “match nothing” — NOT a wildcard. Subscriptions with emptykindsare not indexed in either tier 1 or tier 2 and never receive events.kindsabsent (no field) means “match all kinds” — indexed in tier 2 (channel wildcard) or tier 3 (global).
REQ Handler Access Control
The REQ handler checks channel access before registering the subscription:Historical Query (EOSE)
After registering, the REQ handler queries Postgres for stored events matching the filters (up to 500 per filter, hard cap). These are sent as["EVENT", sub_id, event] frames before ["EOSE", sub_id]. New events arriving after EOSE are delivered via the fan-out path.
6. Crate Reference
buzz-core — Shared Types and Verification
Zero I/O. The foundation every other crate builds on. Explicitly prohibits tokio, sqlx, redis, and axum in itsCargo.toml.
Key types:
Does NOT: store events, make network calls, spawn tasks, or depend on any async runtime.
buzz-auth — Authentication and Authorization
Handles authentication paths, scope enforcement, and token operations. Auth paths:
Key types:
- NIP-98 auth: Schnorr-signed
kind:27235events with URL + method tags. - NIP-42 timestamp tolerance: ±60 seconds.
- Dev-only key derivation:
SHA-256("buzz-test-key:{username}")— gated behind#[cfg(any(test, feature = "dev"))]. Thedevfeature must not be enabled in production relay deployments.
RateLimiter beyond a test stub (AlwaysAllowRateLimiter, gated behind #[cfg(any(test, feature = "test-utils"))]). No Redis-backed rate limiter exists anywhere in the codebase — rate limiting is not currently enforced. RateLimitConfig defines 4 tiers (human, agent-standard, agent-elevated, agent-platform) as a design target.
buzz-db — Postgres Event Store
All database access. Usessqlx::query() (runtime, not compile-time macros) — no .sqlx/ offline cache required.
Key operations:
Channel types:
Stream, Forum, Dm, WorkflowMember roles:
Owner, Admin, Member, Guest, BotWorkflow statuses:
Active, Disabled, ArchivedRun statuses:
Pending, Running, WaitingApproval, Completed, Failed, Cancelled
Key behaviors:
ON CONFLICT DO NOTHINGfor event dedup — returns(StoredEvent, was_inserted: bool).- Rejects
KIND_AUTH(22242) and ephemeral (20000–29999) with distinct error variants. - Transactional role enforcement in
add_member/remove_member/create_channel— TOCTOU-safe. - Soft-delete for channel members:
remove_membersetsremoved_at; re-adding reverses it. - Feed hard cap:
FEED_MAX_LIMIT = 100rows regardless of caller-requested limit. query_mentionsusesINNER JOIN event_mentions— normalized table with composite index on(pubkey_hex, created_at).- Approval tokens:
create_approvalreceives the raw token and hashes it internally with SHA-256. - DDL injection protection in partition manager: allowlist of table names + strict suffix/date validators.
buzz-pubsub — Redis Pub/Sub, Presence, Typing
Manages Redis pub/sub fan-out, presence tracking, and typing indicators. In multi-community mode all tenant-visible keys are prefixed or otherwise partitioned by community (buzz:{community}:...) so channel fan-out, presence, typing, and cache invalidation cannot cross hosts.
Architecture:
redis::aio::PubSub connection — not from the pool. This is intentional: pool connections cannot hold PSUBSCRIBE state.
Current state: The subscriber loop is spawned in buzz-relay/src/main.rs and populates the broadcast channel. A consumer task subscribes via pubsub.subscribe_local(), calls sub_registry.fan_out() on each received event, and delivers matches to local WebSocket connections via conn_manager.send_to(). Multi-node fan-out is now wired end-to-end. Local-echo deduplication is implemented via AppState.local_event_ids — events published by the local relay instance are tracked and skipped when received via the Redis round-trip.
Reconnection: exponential backoff 1s → 30s (backoff_secs * 2). Backoff resets to 1s only after a clean stream end, not on each reconnect attempt.
Presence: SET buzz:presence:{pubkey_hex} {status} EX 180 — 180-second TTL (3× the 60-second heartbeat interval). Single missed heartbeat does not cause presence flap.
Typing indicators:
PubSubManager is not Clone — callers use Arc<PubSubManager>.
buzz-search — Postgres FTS Integration
Full-text search via Postgres FTS. Events are searchable through theevents.search_tsv generated tsvector column (populated on insert, indexed
by a GIN index) — there is no separate search service or out-of-band indexer.
Privacy-sensitive kinds are excluded at the storage level (the search_tsv
CASE WHEN kind IN (...) yields NULL, which never matches @@). In
multi-community mode every query filter includes community_id, so the shared
events table is infrastructure, not a cross-community result space; the relay
re-authorizes every candidate hit before returning it.
Key behaviors:
SearchService::new(pool)wraps aPgPool;search(&SearchQuery)runs a parameterized FTS query against theevents.search_tsvGIN index and returnsSearchResult(candidateSearchHits).ChannelScopemakes the channel constraint explicit (Any/ChannelLessOnly/Channels/ChannelsOrChannelLess), closing the ambiguity the oldOption<Vec<Uuid>> + boolmatrix could not express.- Every query carries
community_id; the FTS predicate is BitmapAnd-ed with the community-leading btree filters so a query never crosses tenants. - Permission filtering is caller’s responsibility —
buzz-searchreturns candidate hits; the relay re-authorizes each one (channel membership,#p, owner gates) before delivering it.
search_tsv generated column on the events insert).
buzz-audit — Hash-Chain Audit Log
Tamper-evident append-only log with SHA-256 hash chaining. Hash chain: each entry storesprev_hash (hash of the previous entry). In multi-community mode audit heads/chains are per-community; operator metrics may aggregate, but tenant-readable audit verification walks one community chain. verify_chain() walks entries and recomputes hashes to detect tampering. Genesis entry uses GENESIS_HASH (64 zeros).
Hash covers: seq (big-endian bytes), timestamp (RFC3339), event_id, event_kind (big-endian), actor_pubkey, action string, channel_id (16 bytes or 16 zero bytes if None), canonical metadata JSON (BTreeMap for deterministic key ordering), prev_hash.
Single-writer guarantee: pg_advisory_lock before each transaction. Lock released in all branches including panic (catch_unwind).
10 audit actions: EventCreated, EventDeleted, ChannelCreated, ChannelUpdated, ChannelDeleted, MemberAdded, MemberRemoved, AuthSuccess, AuthFailure, RateLimitExceeded.
Does NOT: log KIND_AUTH (22242) events — returns AuditError::AuthEventForbidden immediately. Does NOT log ephemeral events (they never reach the audit pipeline).
buzz-workflow — YAML-as-Code Automation Engine
Parses, validates, and executes channel-scoped workflow definitions. In multi-community mode workflow definitions, runs, approvals, webhook routes, and schedules inherit the host-derived community and evaluate triggers only against events in that community. Workflow definition structure:TriggerDef and ActionDef use serde internally-tagged enums. Triggers use on: as the tag field; actions use action: as the tag field. Fields are flattened into the parent struct, not nested.
4 trigger types: message_posted, reaction_added, schedule, webhook
7 action types:
Template variables:
{{trigger.text}}, {{trigger.author}}, {{steps.ID.output.FIELD}}. Single-pass resolution (not recursive). Unknown variables left as literal text.
Condition evaluation: evalexpr with HashMapContext. Dot notation converted to underscores (trigger.text → trigger_text). Custom functions registered: str_contains, str_starts_with, str_ends_with, str_len. 100ms timeout prevents adversarial expressions from blocking.
Concurrency: Arc<Semaphore> with 100 permits. try_acquire() — returns CapacityExceeded immediately rather than queuing.
Approval gates: request_approval action returns StepResult::Suspended with a generated UUID token, but the engine does not yet persist the token or resume execution — runs that hit an approval gate are marked as failed (🚧 WF-08). execute_from_step() exists for future resumption support.
Cron scheduler: loop ticks every 60 seconds, evaluates cron expressions with window-based matching, and creates workflow runs for matched triggers. Fully implemented.
Does NOT: recursively resolve templates (single-pass only). Does NOT queue workflow runs when at capacity — returns CapacityExceeded immediately.
Huddle Audio — WebSocket Opus Relay
Real-time voice lives insidebuzz-relay (src/audio/), not a separate crate. A WebSocket endpoint (wss://.../huddle/{channel_id}/audio) authenticates each participant with a NIP-42 challenge, checks channel membership, admits them to an in-memory room, and forwards opaque Opus frames between peers. No external SFU.
Frame protocol (v2): 8-byte big-endian header (sequence u16, 48 kHz timestamp u32, level dBov i8, flags u8) followed by an opaque Opus payload. Invalid level_dbov values are clamped rather than dropped — losing a metric beats losing audio.
Room state: an admission guard synchronizes joins against the room’s ended flag; soft cap 25 peers (hard cap 255 via u8 peer index). Per-peer audio uses a bounded channel (drop-on-full); the control channel is separate and never drops join/leave.
Lifecycle events: the relay emits Nostr events for participant joined / left and huddle ended; the desktop client emits huddle started and guidelines. When the last peer leaves, the room ends and the channel archives atomically.
Not yet built: recording and per-track publishing (the corresponding kinds are reserved, no producer exists).
buzz-relay — The Server
Axum WebSocket server. Ties all other crates together. The only crate that imports and orchestrates all subsystems.AppState (Arc-wrapped, shared across all connections — key fields shown, not exhaustive):
ConnectionState (per-connection):
Constants:
Does NOT: implement business logic — delegates to the appropriate crate for every operation.
buzz-acp — Agent Communication Protocol Harness
Standalone binary that bridges Buzz relay events to AI agents via the Agent Communication Protocol (ACP). Architecture:buzz-acp spawns AI agent subprocesses (1–32, default 1), connects to the relay via WebSocket with NIP-42 auth, discovers channels via REST API, and queues @mention events per channel. At most one prompt is in-flight per channel. Queued events are batched into a single prompt sent via session/prompt over ACP.
Key modules:
Key behaviors:
- Pool of 1–32 agent subprocesses with claim/return lifecycle.
- Per-channel queuing: at most one prompt in-flight per channel; subsequent @mentions queue until the agent responds.
- Crash recovery: agent subprocess crashes are detected and the agent is respawned.
- Depends on
buzz-core(kind constants) andbuzz-sdk(relay/REST utilities).
buzz-admin — Operator CLI
Subcommands:
The
buzz-admin binary is shipped in the relay Docker image (/usr/local/bin/buzz-admin) and is the recommended way to manage relay membership in production. Use ./run.sh add-member, ./run.sh remove-member, and ./run.sh list-members in Docker Compose deployments.
buzz-test-client — Integration Test Harness
BuzzTestClient wraps a WebSocket connection with a VecDeque<RelayMessage> buffer for message interleaving. Methods: connect, connect_unauthenticated, authenticate, send_event, send_text_message, subscribe, close_subscription, recv_event, collect_until_eose, disconnect.
Test coverage:
All e2e tests are
#[ignore] — require a running relay. Total: 134 e2e tests.
src/main.rs is a manual testing CLI (buzz-test-cli) with --send, --subscribe, --channel, --url, --kind flags.
Defines parse_relay_message, OkResponse, RelayMessage directly in src/lib.rs.
7. Security Model
Every security-sensitive operation uses an explicit, verified pattern. No implicit trust.Authentication
Input Validation
SSRF Protection
is_private_ip() in buzz-core covers:
- IPv4: unspecified (0.0.0.0/8), loopback (127.0.0.0/8), private (10/8, 172.16/12, 192.168/16), link-local (169.254/16), CGNAT (100.64/10), benchmarking (198.18/15), broadcast (255.255.255.255)
- IPv6: loopback (::1), ULA (fc00::/7), link-local (fe80::/10), multicast (ff00::/8), documentation (2001:db8::/32)
- IPv4-mapped IPv6 (::ffff:0:0/96) — recursively checks the embedded IPv4 address
buzz-workflow (CallWebhook action), buzz-core (shared utility).
Audit Integrity
- Hash chain: each entry’s SHA-256 covers all fields including
prev_hash— tampering any entry breaks all subsequent hashes - Canonical JSON:
BTreeMapfor deterministic key ordering — hash is reproducible - Single-writer lock:
pg_advisory_lock— prevents concurrent writes from breaking the chain - Panic-safe:
catch_unwindensures lock release even on panic
Access Control
- Channel membership is the only gate — enforced by the relay at every operation
- REQ handler checks access before subscription registration — no race window for private channel leaks
- TOCTOU-safe membership operations: all check-then-modify sequences run inside Postgres transactions
- Approval tokens: UUID (CSPRNG), stored as SHA-256 hash, single-use enforced with
AND status = 'pending'in UPDATE
Webhook Security
- Workflow webhooks: constant-time XOR comparison of stored UUID secret (not HMAC — compares the secret directly, not a body MAC)
- Outbound webhooks (CallWebhook): SSRF protection + redirects disabled + 1 MiB response cap
8. Infrastructure
Docker Compose provides the full local development stack. All services include health checks and resource limits.Services
Postgres Schema (key tables)
Redis Key Patterns
Full-Text Search (Postgres FTS)
Search runs over theevents.search_tsv generated tsvector column on the
events table (no separate collection or service). The column is populated on
insert — to_tsvector('simple', content) — and excludes privacy-sensitive
kinds via CASE WHEN kind IN (1059, 30300, 30622) THEN NULL, so those rows are
storage-level unsearchable (a NULL tsvector never matches @@). A GIN index
(idx_events_search_tsv) backs the @@ probe; in multi-community mode the
community-leading btree filters BitmapAnd with the GIN probe so every query is
fenced to its community_id.