feat(relay): let group-state filters opt in to system channels

A filter on kinds 39000-39003 with #t:["system"] or any #P now also
returns the system channels the reader can read (member, or open), and
then matches as usual. kind:39000 to 39003 already carry
["t", <channel_type>] and ["P", <creator>], so this needs no new filter
key. Existing clients send neither on these kinds, so they still never see
a system channel.

This makes the lookups a consumer needs work in one SQL-backed filter:

- {kinds:[39002], #p:[me], #t:["system"]} lists my system channels;
- {kinds:[39000], #t:["system"]} lists the open ones;
- {kinds:[39000], #P:[creator], #t:[label]} finds one creator's labeled
  channel, system or not.

The opt-in applies per filter, on REQ, COUNT and the HTTP bridge. NOSTR.md
documents the system channel query rules.

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
This commit is contained in:
Logan Johnson
2026-10-08 14:27:01 -04:00
parent 0d06eaf8ba
commit 2fd35289a2
3 changed files with 216 additions and 5 deletions

View File

@@ -134,6 +134,24 @@ label set with more than 8 labels, a label that is not 1-64 characters
from `a-z`, `0-9`, `.`, `:` and `-`, or a label equal to a channel type
name (`stream`, `forum`, `dm`, `workflow`, `system`).
**System channels.** A channel with `channel_type` `system` exists only for
access control, for example to hold config that only an agent and its owner
can read. It is an ordinary channel in every other way, but queries leave it
out unless they ask for it:
- A filter that does not name it, for example a REQ with no `#h`, a COUNT,
a NIP-50 search, or kind:39002 `#p:[me]`, does not return it.
- A filter that names it with `#h`, or with `#d` on kinds 39000–39003, reads
it under the ordinary rules: the reader is a member, or it is open.
- A filter on kinds 39000–39003 with `#t:["system"]` or any `#P` also
returns the system channels the reader can read, then matches as usual.
For example, `{kinds:[39000], #P:[<creator>], #t:[<label>]}` finds one
creator's labeled channel, system or not. Values in one tag filter
combine with OR, so `#t:["system", <label>]` does not mean "a system
channel with this label".
Push and kind:44100/44101 membership notifications skip system channels.
Events are stored **channel-scoped** so access control applies — private channel member lists are
only visible to members. Discover groups via historical REQ:

View File

@@ -391,3 +391,123 @@ async fn system_channels_send_no_membership_notifications() {
}
assert_eq!(sorted(notified), vec![ordinary.to_string()]);
}
/// A group-state filter with `#t:["system"]` or any `#P` finds the system
/// channels the reader can read, and still matches as usual: a creator plus
/// a label finds that creator's one labeled channel.
/// Mutation: make `filter_opts_in` return false → RED (discovery finds
/// nothing). Drop the readability check from the opt-in → RED (an outsider
/// finds the private channel).
#[tokio::test]
#[ignore = "requires Postgres and Redis"]
async fn system_channels_are_found_by_type_or_creator() {
let f = fixture().await;
let owner = Keys::generate();
let outsider = Keys::generate();
let owner_hex = owner.public_key().to_hex();
let label = "agent-attention";
let private = create_channel(
&f.state,
&f.tenant,
&owner,
&[&["channel_type", "system"], &["t", label]],
)
.await;
let open = create_channel(&f.state, &f.tenant, &owner, &[&["channel_type", "system"]]).await;
edit_channel(
&f.state,
&f.tenant,
&owner,
open,
&[&["visibility", "open"]],
)
.await
.expect("open the system channel");
let ordinary = create_channel(&f.state, &f.tenant, &owner, &[]).await;
// Another creator's channel with the same label: #P must exclude it.
let lookalike = create_channel(&f.state, &f.tenant, &outsider, &[&["t", label]]).await;
let meta = |channel| group_state_id(&f, channel, 39000);
let (private_meta, open_meta, ordinary_meta, lookalike_meta) = (
meta(private).await,
meta(open).await,
meta(ordinary).await,
meta(lookalike).await,
);
// #t:["system"]: members find both; outsiders find only the open one.
assert_eq!(
sorted(req(&f, &owner, json!({"kinds": [39000], "#t": ["system"]})).await),
sorted(vec![private_meta.clone(), open_meta.clone()]),
"member #t:system"
);
assert_eq!(
req(&f, &outsider, json!({"kinds": [39000], "#t": ["system"]})).await,
vec![open_meta.clone()],
"outsider #t:system"
);
// A member lists its own system channels from kind:39002.
assert_eq!(
sorted(
req(
&f,
&owner,
json!({"kinds": [39002], "#p": [owner_hex], "#t": ["system"]})
)
.await
),
sorted(vec![
group_state_id(&f, private, 39002).await,
group_state_id(&f, open, 39002).await,
]),
"member 39002 #p:[me] #t:system"
);
// #P opts in, so a creator's channels include its system channels.
assert_eq!(
sorted(req(&f, &owner, json!({"kinds": [39000], "#P": [owner_hex]})).await),
sorted(vec![private_meta.clone(), open_meta.clone(), ordinary_meta]),
"member #P"
);
// Creator plus label finds exactly the one channel, in SQL.
let lookup = json!({"kinds": [39000], "#P": [owner_hex], "#t": [label], "limit": 1});
assert_eq!(
req(&f, &owner, lookup.clone()).await,
vec![private_meta.clone()],
"creator + label"
);
assert!(
req(&f, &outsider, lookup.clone()).await.is_empty(),
"an outsider cannot find a private system channel"
);
// A label alone is not an opt-in.
assert_eq!(
req(&f, &owner, json!({"kinds": [39000], "#t": [label]})).await,
vec![lookalike_meta],
"label alone"
);
// The same opt-in on COUNT and the HTTP bridge.
assert_eq!(
count(&f, &owner, json!({"kinds": [39000], "#t": ["system"]})).await,
2,
"COUNT #t:system"
);
assert_eq!(
bridge_ids(bridge(&f, &owner, "/query", json!([lookup])).await),
vec![private_meta],
"bridge creator + label"
);
assert_eq!(
bridge_count(
bridge(
&f,
&outsider,
"/count",
json!([{"kinds": [39000], "#t": ["system"]}])
)
.await
),
1,
"bridge /count outsider #t:system"
);
}

View File

@@ -9,6 +9,12 @@
//! - `#h` lists the channel, on any kinds;
//! - `#d` lists the channel, on a filter whose kinds are all 39000–39003.
//!
//! A filter whose kinds are all 39000–39003 also opts in to every readable
//! system channel when it has `#t:["system"]` (the channel type tag) or any
//! `#P` (the creator tag). The filter then matches as usual, so
//! `{kinds:[39000], #P:[creator], #t:[label]}` finds one creator's labeled
//! channel, system or not. Existing clients send neither on these kinds.
//!
//! The addition is per filter. Another filter in the same request keeps the
//! implicit set, so naming one system channel cannot widen a sibling filter.
@@ -52,13 +58,34 @@ fn named_channels(filter: &Filter) -> impl Iterator<Item = Uuid> + '_ {
.filter_map(|value| value.parse::<Uuid>().ok())
}
/// Whether `filter` opts in to every readable system channel: its kinds are
/// all group-state kinds, and it has `#t:["system"]` or any `#P`.
fn filter_opts_in(filter: &Filter) -> bool {
if !filter_is_group_state_only(filter) {
return false;
}
let system_type = filter
.generic_tags
.get(&SingleLetterTag::lowercase(Alphabet::T))
.is_some_and(|values| {
values
.iter()
.any(|value| value == buzz_core::channel::ChannelType::System.as_str())
});
let creator = filter
.generic_tags
.get(&SingleLetterTag::uppercase(Alphabet::P))
.is_some_and(|values| !values.is_empty());
system_type || creator
}
/// Whether `filter` could need a system channel added to its scope.
fn filter_needs_system_channels(filter: &Filter, implicit: &[Uuid]) -> bool {
named_channels(filter).any(|id| !implicit.contains(&id))
filter_opts_in(filter) || named_channels(filter).any(|id| !implicit.contains(&id))
}
/// The channels `filter` may read: the implicit set, plus the readable
/// system channels the filter names.
/// system channels the filter names, or all of them when it opts in.
pub(crate) fn filter_channel_scope<'a>(
filter: &Filter,
implicit: &'a [Uuid],
@@ -67,8 +94,14 @@ pub(crate) fn filter_channel_scope<'a>(
if readable_system.is_empty() {
return Cow::Borrowed(implicit);
}
let opted_in = filter_opts_in(filter);
let mut extra: Vec<Uuid> = Vec::new();
for id in named_channels(filter) {
let candidates: Vec<Uuid> = if opted_in {
readable_system.to_vec()
} else {
named_channels(filter).collect()
};
for id in candidates {
if readable_system.contains(&id) && !implicit.contains(&id) && !extra.contains(&id) {
extra.push(id);
}
@@ -83,8 +116,8 @@ pub(crate) fn filter_channel_scope<'a>(
/// Load the system channels the reader can read, narrowed to the token's
/// channel scope, when at least one filter could use them. Returns an empty
/// set, without a database read, when no filter names a channel outside the
/// implicit set.
/// set, without a database read, when no filter opts in or names a channel
/// outside the implicit set.
pub(crate) async fn readable_system_channels_for_filters(
state: &AppState,
community: CommunityId,
@@ -112,6 +145,7 @@ pub(crate) async fn readable_system_channels_for_filters(
#[cfg(test)]
mod tests {
use super::*;
use nostr::Keys;
fn filter(json: serde_json::Value) -> Filter {
serde_json::from_value(json).expect("filter")
@@ -160,6 +194,45 @@ mod tests {
);
}
#[test]
fn system_type_or_creator_on_group_state_kinds_opts_in() {
let open = Uuid::new_v4();
let system = vec![Uuid::new_v4(), Uuid::new_v4()];
let implicit = vec![open];
let all = [vec![open], system.clone()].concat();
let creator = Keys::generate().public_key().to_hex();
for opt_in in [
serde_json::json!({"kinds": [39000], "#t": ["system"]}),
serde_json::json!({"kinds": [39002], "#p": [creator], "#t": ["system", "x"]}),
serde_json::json!({"kinds": [39000, 39003], "#P": [creator]}),
serde_json::json!({"kinds": [39000], "#P": [creator], "#t": ["agent-attention"]}),
] {
let f = filter(opt_in.clone());
assert!(filter_needs_system_channels(&f, &implicit), "{opt_in}");
assert_eq!(
filter_channel_scope(&f, &implicit, &system).as_ref(),
all.as_slice(),
"{opt_in}"
);
}
for no_opt_in in [
// Labels alone, or other kinds, do not opt in.
serde_json::json!({"kinds": [39000], "#t": ["agent-attention"]}),
serde_json::json!({"kinds": [39000, 9], "#t": ["system"]}),
serde_json::json!({"kinds": [9], "#P": [creator]}),
serde_json::json!({"#t": ["system"]}),
] {
let f = filter(no_opt_in.clone());
assert!(!filter_needs_system_channels(&f, &implicit), "{no_opt_in}");
assert_eq!(
filter_channel_scope(&f, &implicit, &system).as_ref(),
&[open],
"{no_opt_in}"
);
}
}
#[test]
fn lookup_runs_only_when_a_filter_names_a_channel_outside_the_implicit_set() {
let open = Uuid::new_v4();