Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions NOSTR.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \
| **Membership notifications** | ✅ | kind:44100 (added) / kind:44101 (removed); relay-signed, community-global scope (`channel_id=None` inside the connected community) |
| **Presence (kind:20001)** | ✅ | Ephemeral; arbitrary status string (truncated to 128 chars); writes to Redis (`set_presence`/`clear_presence` on `"offline"`), then fan-out to local subscribers. In multi-community mode presence is scoped to the connected community. |
| **Agent presence (kind:20003)** | ✅ | Ephemeral; an owner's presence for the agents it owns, named by `p` tags (at most 256); `online`/`away` set and `offline` clears each agent's presence as its own kind:20001 would. Not fanned out. |
| **Channel access changed (kind:20004)** | ✅ | Ephemeral, relay-signed and relay-only: tells a channel's live subscribers to ask again what they may do there (see [Channel access](#channel-access)). A client may not send it. |
| **Viewer access changed (kind:20005)** | ✅ | Ephemeral, relay-signed, relay-only and `#p`-gated: tells one pubkey, when its community timeout or ban changes, to ask again what it may do in every channel (see [Channel access](#channel-access)). A client may not send it. |
| **Typing indicators (kind:20002)** | ✅ | Ephemeral, not stored; published via Redis pub/sub (multi-node capable unlike presence fan-out) |
| **NIP-42 authentication** | ✅ | Proactive challenge; optional pubkey allowlist |
| **NIP-11 relay info** | ✅ | `GET /` with `Accept: application/nostr+json` |
Expand Down Expand Up @@ -311,6 +313,72 @@ for its comments. It belongs to the artifact, not to anyone who posts in it.
in NIP-11 `supported_extensions`. They also include artifacts in
auto-archiving channels in incremental artifact sync.

### Channel access

A client asks what its signer may do in named channels, and is told when
to ask again. Conversations, channels read through parents and open
channels the signer has not joined all get the same answer.

- **Asking.** `POST /query` with exactly
`[{"access":"channels","ids":[<channel id>, ...]}]`: 1 to 100 distinct
lowercase channel IDs. The NIP-98 proof must carry a `payload` tag. Any
other shape is refused with 400.
- **Listing.** Without `ids`, `[{"access":"channels"}]` lists the
channels the signer can reach, ordered by channel ID: the channels they
joined, listed open channels, and the children and grandchildren of
both that the parents' grants reach. These are the channels a read that
names no channel covers, so conversations and unlisted channels stay
out. It is paged: optional `"limit"` (1 to 100, default 100) and
`"after":<channel id>`, and no other keys. The answer is
`{"channels":[<entry>, ...],"next":<channel id or null>}`. A page looks
at up to `limit` candidates after `after` and leaves out the ones the
signer cannot read, so it can hold fewer than `limit` and still have a
`next`. To read the next page, send `next` as `after`; `null` means
there are no more. Walking every page lists each channel once.
- **Answer.** For `ids`, a JSON array with one entry per readable channel,
in request order:
`{"id":<channel id>,"read":true,"post":<bool>,"joined":<bool>,"role":<role>,"archived":<bool>}`.
`joined` is whether the signer has a member row. `role` is the one they
act with: their row's (`owner`, `admin`, `member` or `guest`; a bot acts
as `member`), else an open channel's `join_role`, else what the parents
give, capped at `member`. `archived` is whether the channel itself is
archived. `post` is whether a kind:9 from them would be accepted now:
false for a `guest` role, an archived channel, a conversation whose home
is archived, and a community timeout of the signer or of the agent's
owner, by the same check the post itself meets. While the signer is
timed out, every entry also carries `"timed_out_until":<unix seconds>`;
ask again then. A banned signer, or an agent whose owner is banned, is
refused with 403 and the reason, as every request from them is. A channel left out cannot be read:
it is private to them, deleted or missing. If any channel cannot be
answered, the whole request fails with 503 and is retried; a channel is
only ever left out of a complete answer. The answer is a snapshot, and
every post is still checked when it arrives.
- **Ask again.** After a committed change to who may read or post in a
channel, the relay sends an ephemeral kind:20004, signed by the relay,
with empty content and only `["h", <channel id>]`, to that channel and to
every private channel under it, conversations included. A subscription
receives it like any event, so include kind 20004 in the channel's
filter. It goes only to subscribers who can still read the channel;
those who cannot have their subscriptions closed. It is sent for a
member added, removed, leaving, joining or changing role; a change to
visibility, `join_role`, archiving, `parent` or `parent_access`; and an
artifact's move, delete or restore; a channel's deletion; and a
huddle's auto-archive or auto-join. It carries no answer: ask again. It
is best effort, so a client also asks again when it reconnects and when
a post is refused.
- **Ask again everywhere.** When a pubkey's community restriction changes
(a timeout or ban starts or is lifted, by any route: a moderation
command, the admin API or a resolved report), or an agent's owner is
recorded, the relay sends an ephemeral kind:20005, signed by the relay,
with empty content and only `["p", <pubkey>]`, to that pubkey and to each
agent it owns. Subscribe with `{"kinds":[20005],"#p":[<own pubkey>]}`;
the kind is `#p`-gated, so it reaches no one else. It carries no answer:
ask again about every channel. A timeout that runs out sends nothing;
`timed_out_until` says when to ask.
- Relays that support this advertise `buzz-channel-access` in NIP-11
`supported_extensions`. Without it, a client cannot learn whether it may
post in a channel it has not joined.

### Default channels

A community's owners and admins can mark a channel as a **default channel**:
Expand Down
26 changes: 26 additions & 0 deletions crates/buzz-core/src/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ pub const RESULT_GATED_KINDS: &[u32] = &[
KIND_AGENT_TURN_METRIC,
KIND_MEMBER_ADDED_NOTIFICATION,
KIND_MEMBER_REMOVED_NOTIFICATION,
KIND_VIEWER_ACCESS_CHANGED,
];

/// Kinds whose stored events have `#p`-bound read access — readable only by
Expand Down Expand Up @@ -218,6 +219,7 @@ pub const P_GATED_KINDS: &[u32] = &[
// readable by any unauthenticated or non-owner party, including via `ids`
// filters — see NIP-AM §Relay Behavior.
KIND_AGENT_TURN_METRIC,
KIND_VIEWER_ACCESS_CHANGED,
];

/// NIP-AP: Agent Persona (parameterized replaceable, owner-authored).
Expand Down Expand Up @@ -528,6 +530,14 @@ pub const KIND_TYPING_INDICATOR: u32 = 20002;
/// Ephemeral: an owner's presence for its agents. Content is the status, each
/// `p` tag names one agent the signer owns. Never the signer's own presence.
pub const KIND_AGENT_PRESENCE: u32 = 20003;
/// Ephemeral, relay-signed: "ask again what you may do in this channel"
/// (NOSTR.md, Channel access). Empty content; only `["h", <channel id>]`.
pub const KIND_CHANNEL_ACCESS_CHANGED: u32 = 20004;
/// Ephemeral, relay-signed: "ask again what you may do in every channel",
/// sent when the named person's community restriction changes
/// (NOSTR.md, Channel access). Empty content; only `["p", <pubkey>]`, and
/// delivered only to that pubkey.
pub const KIND_VIEWER_ACCESS_CHANGED: u32 = 20005;
/// Ephemeral: owner-scoped encrypted agent observer telemetry and control frame.
pub const KIND_AGENT_OBSERVER_FRAME: u32 = 24200;
/// Ephemeral: huddle emoji reaction burst. Channel-scoped to the ephemeral
Expand Down Expand Up @@ -768,6 +778,8 @@ pub const ALL_KINDS: &[u32] = &[
KIND_PRESENCE_UPDATE,
KIND_TYPING_INDICATOR,
KIND_AGENT_PRESENCE,
KIND_CHANNEL_ACCESS_CHANGED,
KIND_VIEWER_ACCESS_CHANGED,
KIND_HUDDLE_REACTION,
KIND_BLOSSOM_AUTH,
KIND_OPERATOR_LISTENER_REGISTRATION,
Expand Down Expand Up @@ -934,6 +946,8 @@ pub const fn is_relay_only_kind(kind: u32) -> bool {
| KIND_THREAD_WINDOW_BOUNDS
| KIND_MEMBERSHIP_SNAPSHOT
| KIND_MEMBERSHIP_PUBLIC
| KIND_CHANNEL_ACCESS_CHANGED
| KIND_VIEWER_ACCESS_CHANGED
)
}

Expand Down Expand Up @@ -1024,6 +1038,18 @@ mod tests {
assert!(!is_relay_only_kind(KIND_NIP43_LEAVE_REQUEST));
}

#[test]
fn channel_access_changed_is_relay_only_and_ephemeral() {
assert_eq!(KIND_CHANNEL_ACCESS_CHANGED, 20004);
assert!(is_relay_only_kind(KIND_CHANNEL_ACCESS_CHANGED));
assert!(is_ephemeral(KIND_CHANNEL_ACCESS_CHANGED));
assert_eq!(KIND_VIEWER_ACCESS_CHANGED, 20005);
assert!(is_relay_only_kind(KIND_VIEWER_ACCESS_CHANGED));
assert!(is_ephemeral(KIND_VIEWER_ACCESS_CHANGED));
assert!(RESULT_GATED_KINDS.contains(&KIND_VIEWER_ACCESS_CHANGED));
assert!(P_GATED_KINDS.contains(&KIND_VIEWER_ACCESS_CHANGED));
}

#[test]
fn thread_window_bounds_is_relay_only() {
assert_eq!(KIND_THREAD_WINDOW_BOUNDS, 39007);
Expand Down
93 changes: 90 additions & 3 deletions crates/buzz-relay/src/api/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1305,7 +1305,7 @@ async fn unban_member(
if !lifted {
return Err(ApiError::conflict("no active ban for this member"));
}
state.invalidate_restrictions(&tenant);
state.restrictions_changed(&tenant, Some(&target_bytes));

Ok(axum::http::StatusCode::NO_CONTENT)
}
Expand Down Expand Up @@ -1348,7 +1348,7 @@ async fn untimeout_member(
if !lifted {
return Err(ApiError::conflict("no active timeout for this member"));
}
state.invalidate_restrictions(&tenant);
state.restrictions_changed(&tenant, Some(&target_bytes));

Ok(axum::http::StatusCode::NO_CONTENT)
}
Expand Down Expand Up @@ -2283,10 +2283,19 @@ mod postgres_tests {
/// routes that hit the DB can commit and read back results.
pub(super) async fn nip98_state_with_real_pool(
pool: sqlx::PgPool,
) -> Arc<crate::state::AppState> {
nip98_state_with_real_pool_and_redis(pool, "redis://127.0.0.1:1").await
}

/// [`nip98_state_with_real_pool`] on the Redis at `redis_url`, for
/// tests that watch what a route publishes.
async fn nip98_state_with_real_pool_and_redis(
pool: sqlx::PgPool,
redis_url: &str,
) -> Arc<crate::state::AppState> {
let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE]
config.require_relay_membership = false;
config.redis_url = "redis://127.0.0.1:1".to_string();
config.redis_url = redis_url.to_string();
config.relay_operator_pubkeys = vec![test_operator_keys().public_key().to_hex()];
config.relay_operator_api_origin = Some("https://admin.example".to_string());
config.admin = Some(crate::config::AdminConfig {
Expand Down Expand Up @@ -12679,6 +12688,84 @@ mod postgres_tests {
);
}

/// A timeout or ban set from the dashboard is pushed to the person and
/// their agent, so their clients ask again whether they may post, and to
/// no one else. The route reaches the push only through the one step
/// every restriction change takes.
/// Mutation: drop the push from `AppState::restrictions_changed` → RED.
#[tokio::test]
#[ignore = "requires Postgres and Redis"]
async fn direct_timeout_and_ban_are_pushed_to_that_person_only() {
use crate::handlers::channel_access_postgres_tests::{subscribe_viewer, viewer_pushes};
let (pool, community, host, _) = direct_fixture().await;
let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL names a live Redis");
let state = nip98_state_with_real_pool_and_redis(pool, &redis_url).await;
tokio::spawn(state.pubsub.clone().run_subscriber());
crate::handlers::multinode_fanout::spawn(state.clone(), state.pubsub.subscribe_local());
let tenant = buzz_core::TenantContext::resolved(community, &host);
let (member, agent, bystander) = (
nostr::Keys::generate(),
nostr::Keys::generate(),
nostr::Keys::generate(),
);
for keys in [&member, &agent] {
state
.db
.ensure_user(community, keys.public_key().as_bytes())
.await
.expect("user");
}
state
.db
.set_agent_owner(
community,
agent.public_key().as_bytes(),
member.public_key().as_bytes(),
)
.await
.expect("agent owner");
let mut member_rx = subscribe_viewer(&state, &tenant, &member, true);
let mut agent_rx = subscribe_viewer(&state, &tenant, &agent, true);
let mut bystander_rx = subscribe_viewer(&state, &tenant, &bystander, false);
state
.pubsub
.retain_topic(&tenant, buzz_pubsub::EventTopic::Global)
.await;
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let target = member.public_key().to_hex();
let wait = std::time::Duration::from_secs(2);

for (path, body) in [
(
format!("/members/{target}/timeout?communityHost={host}"),
serde_json::json!({ "requestId": Uuid::new_v4(), "expirationSecs": 600 }),
),
(
format!("/members/{target}/ban?communityHost={host}"),
serde_json::json!({ "requestId": Uuid::new_v4() }),
),
] {
let (status, answer) = direct_post(&state, &path, body).await;
assert_eq!(status, StatusCode::OK, "{path}: {answer}");
assert_eq!(
viewer_pushes(&state, &mut member_rx, wait).await,
vec![target.clone()],
"{path}"
);
assert_eq!(
viewer_pushes(&state, &mut agent_rx, wait).await,
vec![agent.public_key().to_hex()],
"{path}"
);
}
assert!(
viewer_pushes(&state, &mut bystander_rx, wait)
.await
.is_empty(),
"a bystander is told nothing"
);
}

/// A ban whose mutation committed before a crash still disconnects the
/// target when recovery resumes past the ban step.
#[tokio::test]
Expand Down
13 changes: 9 additions & 4 deletions crates/buzz-relay/src/api/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! These endpoints provide HTTP access to the relay's Nostr protocol,
//! authenticated via NIP-98 signed events.

mod channel_access;
mod effective_edit;
mod membership_snapshot;
mod read_state_snapshot;
Expand Down Expand Up @@ -1640,8 +1641,9 @@ pub async fn query_events(

// This authority surface always needs payload-bound NIP-98, including dev.
// Detect before admission, and before Filter can drop the extension key.
let compact_membership = serde_json::from_slice::<Vec<Value>>(&body)
.is_ok_and(|filters| membership_snapshot::requested(&filters));
let payload_bound = serde_json::from_slice::<Vec<Value>>(&body).is_ok_and(|filters| {
membership_snapshot::requested(&filters) || channel_access::requested(&filters)
});

// NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM]
let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge");
Expand All @@ -1657,8 +1659,8 @@ pub async fn query_events(
"POST",
&url,
Some(&body),
state.config.require_auth_token || nip_fi_active || compact_membership,
nip_fi_enforce || compact_membership,
state.config.require_auth_token || nip_fi_active || payload_bound,
nip_fi_enforce || payload_bound,
))
.map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at)))
.map_err(|e| e.into_response())
Expand Down Expand Up @@ -1748,6 +1750,9 @@ async fn query_member_events(
)
.await;
}
if channel_access::requested(&raw_filters) {
return channel_access::query(state, tenant, &pubkey, &raw_filters).await;
}
let routed = || caller.read_artifact(&raw_filters);
if let Some(result) =
super::artifact::query(state, tenant, &pubkey, &raw_filters, false, routed).await
Expand Down
Loading
Loading