Skip to content
Merged
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
11 changes: 11 additions & 0 deletions .changeset/nip43-membership-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
---

nip43: publish the relay-signed kind-13534 membership list (#1366)

The rewrite now has v3's membership list: `nip43.publishMembershipList` gates a
relay-signed kind-13534 replaceable event listing every admitted, not-vanished member,
republished after every successful join, leave or vanish. The list carries the NIP-70 `-`
tag and one `member` tag per pubkey in ascending order, is capped at 10,000 entries, and is
stored and broadcast only when the upsert wrote a row. Default off, because publishing it
makes every member's pubkey public.
2 changes: 1 addition & 1 deletion CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ docker compose exec nostream node src/cli/index.js invite create

`--uses` defaults to `nip43.defaultMaxUses` (1). `--expires-in` defaults to `nip43.inviteCodeExpirySeconds` (600 = 10 minutes). `--expires-in` must be a positive integer; never-expiring codes are a yaml policy (`nip43.inviteCodeExpirySeconds: 0`), not a CLI flag. The printed code is the first line of human output so scripts can capture it. If `info.self` is a hex pubkey or `npub1…`, it is stored as `created_by`.

The relay also answers `REQ`s for kind 28935 by minting a code on the fly and returning it as a relay-signed ephemeral event, so users can obtain a claim string without an operator handing one out. It is off by default and requires `nip43.enabled`, `nip43.allowInviteRequests` and a NIP-42 authenticated client — see [CONFIGURATION.md](CONFIGURATION.md). Membership list events (kind 13534) are not published yet.
The relay also answers `REQ`s for kind 28935 by minting a code on the fly and returning it as a relay-signed ephemeral event, so users can obtain a claim string without an operator handing one out. It is off by default and requires `nip43.enabled`, `nip43.allowInviteRequests` and a NIP-42 authenticated client — see [CONFIGURATION.md](CONFIGURATION.md). With `nip43.publishMembershipList` on, the relay publishes a relay-signed kind-13534 membership list after every successful join, leave or vanish.

Invites minted over `REQ` record the requesting pubkey as `created_by`; `nostream invite create` records `info.self`.

Expand Down
1 change: 1 addition & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip43.defaultMaxUses | How many times a newly minted invite code can be claimed. Defaults to 1. |
| nip43.allowInviteRequests | Answer REQs for kind 28935 by minting an invite code on the fly and returning it as a relay-signed ephemeral event on that subscription. NIP-43 requires relays to opt in to this explicitly. Requesters must be authenticated via NIP-42, and `info.self` must match the relay's signing pubkey. Defaults to false. |
| nip43.inviteRequestWhitelist | Public keys allowed to request kind 28935 invite codes. Empty (the default) means any authenticated pubkey may request one; a non-empty list restricts minting to those pubkeys. |
| nip43.publishMembershipList | Publish the relay-signed kind-13534 membership list after every successful join, leave or vanish. Defaults to false because it makes every member's pubkey public. The event is signed by the relay, and its size can exceed `network.maxPayloadSize`, which bounds inbound frames only. |
| nip45.enabled | Enable or disable NIP-45 COUNT handling. Defaults to true. |
| nip50.enabled | Enable or disable NIP-50 full-text search. Defaults to false. When enabled, clients can include a `search` field in REQ filters to perform text queries against event content. Requires the GIN full-text index migration. |
| nip50.language | PostgreSQL text-search configuration name. Defaults to `simple` (language-agnostic tokenization). Set to `english`, `spanish`, etc. for stemming support. See [PostgreSQL text search configurations](https://www.postgresql.org/docs/current/textsearch-configuration.html). **Note:** The GIN index migration is built with the `simple` configuration. If you change this value, you must manually rebuild the index: `DROP INDEX CONCURRENTLY events_content_fts_idx; CREATE INDEX CONCURRENTLY events_content_fts_idx ON events USING gin (to_tsvector('<your_language>', event_content));` — otherwise the planner cannot use the index and queries fall back to sequential scans. |
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions crates/nostream-admin/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,17 @@ impl EventRepository for SlowEventRepository {
Box::pin(async { Err(not_implemented()) })
}

fn find_stored_replaceable<'a>(
&'a self,
_pubkey: &'a nostream_core::Pubkey,
_kind: nostream_core::Kind,
) -> nostream_storage::repositories::StorageFuture<
'a,
Option<nostream_storage::repositories::ReconciliationItem>,
> {
Box::pin(async { Err(not_implemented()) })
}

fn delete_by_pubkey_and_ids<'a>(
&'a self,
_pubkey: &'a nostream_core::Pubkey,
Expand Down
4 changes: 4 additions & 0 deletions crates/nostream-config/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,10 @@ pub struct Nip43Settings {
pub allow_invite_requests: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub invite_request_whitelist: Option<Vec<SettingsPubkey>>,
/// Publish the relay-signed kind-13534 membership list after every membership change.
/// Off by default because the list makes every member's pubkey public.
#[serde(skip_serializing_if = "Option::is_none")]
pub publish_membership_list: Option<bool>,
}

/// `nip77` (`src/@types/settings.ts` `Nip77Settings`).
Expand Down
1 change: 1 addition & 0 deletions crates/nostream-config/tests/defaults_parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ fn nip43_defaults_are_the_capture_mint_defaults() {
"nip43.inviteRequestWhitelist",
Value::Sequence(vec![]),
);
assert_value(&defaults, "nip43.publishMembershipList", boolean(false));
}

#[test]
Expand Down
24 changes: 24 additions & 0 deletions crates/nostream-config/tests/defaults_roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,30 @@ fn defaults() -> Value {
serde_yaml::from_str(&raw).expect("the shipped defaults are valid YAML")
}

/// The membership-list gate is shipped off, and the typed field round-trips it.
#[test]
fn the_typed_schema_carries_publish_membership_list() {
let defaults = defaults();
let settings: Settings =
serde_yaml::from_value(defaults.clone()).expect("the defaults fit the typed schema");

assert_eq!(
settings
.nip43
.as_ref()
.and_then(|nip43| nip43.publish_membership_list),
Some(false),
"the shipped default publishes no membership list"
);

let again = serde_yaml::to_value(&settings).expect("the typed settings serialize");
assert_eq!(
again["nip43"]["publishMembershipList"],
Value::Bool(false),
"the typed field serializes under its camelCase name"
);
}

#[test]
fn the_shipped_defaults_validate_with_no_issues() {
let defaults = defaults();
Expand Down
32 changes: 32 additions & 0 deletions crates/nostream-core/src/nip19.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ pub fn decode_npub_hex(value: &str) -> Result<String, CoreError> {
Ok(hex::encode(decode_npub(value)?))
}

/// Encodes one lowercase hex pubkey as its `npub1…` form, the inverse of [`decode_npub_hex`].
pub fn encode_npub(pubkey_hex: &str) -> Result<String, CoreError> {
let bytes: [u8; 32] = hex::decode(pubkey_hex)
.map_err(|error| {
CoreError::InvalidMessage(format!("nip19: `{pubkey_hex}` is not hexadecimal: {error}"))
})?
.try_into()
.map_err(|bytes: Vec<u8>| {
CoreError::InvalidMessage(format!(
"nip19: `{pubkey_hex}` decoded to {} bytes, not 32",
bytes.len()
))
})?;
let hrp = bech32::Hrp::parse("npub")
.map_err(|error| CoreError::InvalidMessage(format!("nip19: npub prefix: {error}")))?;

bech32::encode::<bech32::Bech32>(hrp, &bytes)
.map_err(|error| CoreError::InvalidMessage(format!("nip19: npub encode: {error}")))
}

#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
Expand All @@ -62,6 +82,18 @@ mod tests {
assert_eq!(encoded, NPUB);
}

#[test]
fn an_npub_encodes_and_decodes() {
let npub = encode_npub(HEX).expect("the fixture encodes");
assert_eq!(npub, NPUB);
assert_eq!(
decode_npub_hex(&npub).expect("the npub decodes"),
HEX,
"the encoded form decodes back to the original hex"
);
assert!(encode_npub("not-hex").is_err());
}

#[test]
fn a_malformed_npub_is_refused() {
assert!(decode_npub("npub1invalid").is_err());
Expand Down
89 changes: 87 additions & 2 deletions crates/nostream-core/src/nip43.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
//! `src/utils/nip43-invites.ts`.
//!
//! The pure half is implemented: the invite code's entropy, the limits the settings
//! resolve, and the relay-signed kind-28935 event that answers a REQ. Persisting the code is
//! the REQ handler's call into `InviteCodeRepository`; [`InviteCode`] is the row shape.
//! resolve, the relay-signed kind-28935 event that answers a REQ, and the relay-signed
//! kind-13534 membership list. Persisting the code is the REQ handler's call into
//! `InviteCodeRepository`; [`InviteCode`] is the row shape.

use crate::error::CoreError;
use crate::event::{Event, Kind, Pubkey};
Expand All @@ -25,6 +26,10 @@ pub const DEFAULT_INVITE_MAX_USES: u32 = 1;
/// `src/utils/nip43-invites.ts:11`).
pub const DEFAULT_INVITE_CODE_EXPIRY_SECONDS: u64 = 600;

/// The most members one published kind-13534 membership list carries
/// (`MAX_MEMBERSHIP_LIST_ENTRIES`, `src/utils/nip43-membership.ts:17`).
pub const MAX_MEMBERSHIP_LIST_ENTRIES: usize = 10_000;

/// The limits one minted code carries (`resolveInviteCodeLimits`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InviteCodeLimits {
Expand Down Expand Up @@ -106,6 +111,38 @@ pub fn build_invite_code_event(
Ok(event)
}

/// Builds the relay-signed kind-13534 membership list (`buildMembershipListEvent`,
/// `src/utils/nip43-membership.ts:23-44`).
///
/// The NIP-70 `-` tag comes first, then one `member` tag per pubkey in the order given: the
/// query's ascending order, never sorted here. A list with no members is exactly `[["-"]]`.
pub fn build_membership_list_event(
secret_key: &[u8; 32],
members: &[Pubkey],
created_at: i64,
) -> Result<Event, CoreError> {
let mut tags = vec![vec!["-".to_owned()]];
tags.extend(
members
.iter()
.map(|member| vec!["member".to_owned(), member.to_string()]),
);

let mut event = Event {
id: crate::event::EventId::from_byte_array([0; 32]),
pubkey: crate::event::Pubkey::from_byte_array([0; 32]),
created_at,
kind: Kind(13_534),
tags,
content: String::new(),
sig: crate::event::Signature::from_byte_array([0; 64]),
};

crate::crypto::sign_event(secret_key, &mut event)?;

Ok(event)
}

/// Whether a kind is the membership join request (`src/utils/nip43.ts`).
pub fn is_join_request(kind: Kind) -> bool {
kind == Kind(28_934)
Expand Down Expand Up @@ -174,4 +211,52 @@ mod tests {
assert!(!is_request_timestamp_valid(now - 601, now));
assert!(!is_request_timestamp_valid(now + 3600, now));
}

fn member(byte: u8) -> Pubkey {
Pubkey::from_byte_array([byte; 32])
}

#[test]
fn membership_list_event_has_the_captures_kind_tags_and_signature() {
let secret = [1u8; 32];
let first = member(0xaa);
let second = member(0xbb);

let event = build_membership_list_event(&secret, &[first, second], 1_700_000_000).unwrap();

assert_eq!(event.kind, Kind(13_534));
assert_eq!(event.pubkey, crate::crypto::public_key(&secret).unwrap());
assert_eq!(event.created_at, 1_700_000_000);
assert_eq!(event.content, "");
assert_eq!(
event.tags,
vec![
vec!["-".to_owned()],
vec!["member".to_owned(), first.to_string()],
vec!["member".to_owned(), second.to_string()],
]
);
assert!(event.is_protected());
crate::crypto::verify_event_signature(&event).expect("the relay-signed event verifies");
}

#[test]
fn an_empty_membership_list_has_only_the_protected_tag() {
let event = build_membership_list_event(&[1u8; 32], &[], 1_700_000_000).unwrap();

assert_eq!(event.tags, vec![vec!["-".to_owned()]]);
assert!(event.is_protected());
}

#[test]
fn the_membership_list_builder_keeps_the_member_order_it_is_given() {
let first = member(0xaa);
let second = member(0xbb);

let event =
build_membership_list_event(&[1u8; 32], &[second, first], 1_700_000_000).unwrap();

assert_eq!(event.tags[1][1], second.to_string());
assert_eq!(event.tags[2][1], first.to_string());
}
}
20 changes: 20 additions & 0 deletions crates/nostream-mcp/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,14 @@ impl EventRepository for VanishingRepository {
EventRepository::find_stored(&*self.inner, id)
}

fn find_stored_replaceable<'a>(
&'a self,
pubkey: &'a Pubkey,
kind: Kind,
) -> StorageFuture<'a, Option<nostream_storage::repositories::ReconciliationItem>> {
self.inner.find_stored_replaceable(pubkey, kind)
}

fn delete_by_pubkey_and_ids<'a>(
&'a self,
pubkey: &'a Pubkey,
Expand Down Expand Up @@ -772,6 +780,14 @@ impl EventRepository for ZeroCountDeleter {
EventRepository::find_stored(&*self.inner, id)
}

fn find_stored_replaceable<'a>(
&'a self,
pubkey: &'a Pubkey,
kind: Kind,
) -> StorageFuture<'a, Option<nostream_storage::repositories::ReconciliationItem>> {
self.inner.find_stored_replaceable(pubkey, kind)
}

/// The real soft delete, and a count that says nothing happened.
fn delete_by_pubkey_and_ids<'a>(
&'a self,
Expand Down Expand Up @@ -905,4 +921,8 @@ impl nostream_storage::repositories::UserRepository for NoBalanceRead {
fn revoke_admission<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, u64> {
nostream_storage::repositories::UserRepository::revoke_admission(&*self.inner, pubkey)
}

fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec<Pubkey>> {
nostream_storage::repositories::UserRepository::find_admitted_pubkeys(&*self.inner, limit)
}
}
1 change: 1 addition & 0 deletions crates/nostream-relay/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ tracing.workspace = true

[dev-dependencies]
base64.workspace = true
tempfile.workspace = true
serde_yaml.workspace = true

[lints]
Expand Down
2 changes: 2 additions & 0 deletions crates/nostream-relay/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//! - `src/controllers/admission/get-admission-check-controller.ts`,
//! `src/routes/admissions/index.ts`
//! - `src/utils/{sliding-window-rate-limiter,ewma-rate-limiter,hidden-content-cache}.ts`
//! - `src/utils/nip43-membership.ts` (the relay-signed membership list)
//! - `src/@types/{message-handlers,subscription,clients}.ts`
//! - `src/factories/{event-strategy-factory,message-handler-factory,
//! websocket-adapter-factory,rate-limiter-factory}.ts`
Expand Down Expand Up @@ -54,6 +55,7 @@ pub mod hidden_content;
pub mod limits;
pub mod metrics;
pub mod nip11;
pub mod nip43_membership;
pub mod relay;
pub mod relay_key;
pub mod sink;
Expand Down
Loading
Loading