From cce55b6a06f83555f7fe287cecd041943be3bad6 Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Fri, 20 Nov 2026 23:57:15 +0530 Subject: [PATCH 1/2] feat(nip43): publish the kind 13534 membership list Signed-off-by: Priyanshubhartistm --- .changeset/nip43-membership-list.md | 7 + CLI.md | 2 +- CONFIGURATION.md | 1 + resources/default-settings.yaml | 5 + src/@types/repositories.ts | 1 + src/@types/settings.ts | 5 + src/factories/event-strategy-factory.ts | 18 +- .../join-request-event-strategy.ts | 9 + .../leave-request-event-strategy.ts | 9 + src/repositories/user-repository.ts | 19 +- src/utils/nip43-membership.ts | 115 +++++++++ .../join-request-event-strategy.spec.ts | 67 ++++++ .../leave-request-event-strategy.spec.ts | 58 +++++ .../unit/repositories/user-repository.spec.ts | 43 ++++ test/unit/utils/nip43-membership.spec.ts | 227 ++++++++++++++++++ test/unit/utils/settings.spec.ts | 6 + 16 files changed, 588 insertions(+), 4 deletions(-) create mode 100644 .changeset/nip43-membership-list.md create mode 100644 src/utils/nip43-membership.ts create mode 100644 test/unit/utils/nip43-membership.spec.ts diff --git a/.changeset/nip43-membership-list.md b/.changeset/nip43-membership-list.md new file mode 100644 index 000000000..d9f0ffaff --- /dev/null +++ b/.changeset/nip43-membership-list.md @@ -0,0 +1,7 @@ +--- +'nostream': minor +--- + +feat(nip43): publish the kind 13534 membership list + +With the new `nip43.publishMembershipList` setting (off by default) the relay publishes a replaceable kind 13534 event, signed by its own key, with the NIP-70 `-` tag and one `member` tag per admitted pubkey, and refreshes it after every successful join or leave. Joins and leaves that are rejected or change nothing do not refresh it. Nothing is published when `info.self` does not match the relay's signing pubkey, since NIP-43 requires that signer. The list makes every member's pubkey public to anyone who can read the relay, which is why the setting defaults to off. It is a convenience for clients, not the source of truth for who may publish, and it holds at most the first 10,000 members. Users who asked to vanish are left out. Admissions made another way, for example a paid admission, do not refresh it. diff --git a/CLI.md b/CLI.md index 80d80bc21..d7358a6b0 100644 --- a/CLI.md +++ b/CLI.md @@ -46,7 +46,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). A kind 13534 membership list can be published too, after each successful join or leave, with `nip43.publishMembershipList`; it is off by default because it makes the members' pubkeys public — see [CONFIGURATION.md](CONFIGURATION.md). Invites minted over `REQ` record the requesting pubkey as `created_by`; `nostream invite create` records `info.self`. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 5a2e6b372..f7837b3bd 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -222,6 +222,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 a kind 13534 membership list (a replaceable event with a NIP-70 `-` tag and one `member` tag per admitted pubkey) signed by the relay's own key, and refresh it after each successful join or leave. **It makes every member's pubkey public to anyone who can read the relay.** `info.self` must match the relay's signing pubkey, or nothing is published. Joins and leaves that are rejected or change nothing do not refresh it, and neither does an admission made another way (for example a paid admission). The list is a convenience for clients, not the source of truth for who may publish. Defaults to false. | | 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('', event_content));` — otherwise the planner cannot use the index and queries fall back to sequential scans. | diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index f40b2a677..439a0457b 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -109,6 +109,11 @@ nip43: # Pubkeys allowed to request invite codes. Empty means any authenticated pubkey # may request one; non-empty restricts minting to the listed pubkeys. inviteRequestWhitelist: [] + # Publish a kind 13534 membership list, signed by the relay's own key, and refresh it + # after every successful join or leave. This makes every member's pubkey public to + # anyone who can read the relay, so it is off by default. The list is a convenience + # for clients, not the source of truth for who may publish. + publishMembershipList: false nip45: enabled: true nip50: diff --git a/src/@types/repositories.ts b/src/@types/repositories.ts index a9b8a9e90..b62c1ea03 100644 --- a/src/@types/repositories.ts +++ b/src/@types/repositories.ts @@ -193,6 +193,7 @@ export interface IUserRepository { setVanished(pubkey: Pubkey, vanished: boolean, client?: DatabaseClient): Promise admitUser(pubkey: Pubkey, admittedAt: Date, client?: DatabaseClient): Promise revokeAdmission(pubkey: Pubkey, client?: DatabaseClient): Promise + findAdmittedPubkeys(limit: number, client?: DatabaseClient): Promise } export interface Nip05VerificationAdminListQuery { diff --git a/src/@types/settings.ts b/src/@types/settings.ts index 203cf83d1..682ebe237 100644 --- a/src/@types/settings.ts +++ b/src/@types/settings.ts @@ -512,6 +512,11 @@ export interface Nip43Settings { defaultMaxUses?: number allowInviteRequests?: boolean inviteRequestWhitelist?: Pubkey[] + /** + * Publish a kind 13534 membership list (a replaceable event signed by the relay's own key) and refresh it + * after each successful join or leave. It makes every member's pubkey public, so it defaults to false. + */ + publishMembershipList?: boolean } export interface Nip56Settings { diff --git a/src/factories/event-strategy-factory.ts b/src/factories/event-strategy-factory.ts index e1d99a000..882b855e4 100644 --- a/src/factories/event-strategy-factory.ts +++ b/src/factories/event-strategy-factory.ts @@ -34,6 +34,7 @@ import { IEventStrategy } from '../@types/message-handlers' import { InviteRequestEventStrategy } from '../handlers/event-strategies/invite-request-event-strategy' import { JoinRequestEventStrategy } from '../handlers/event-strategies/join-request-event-strategy' import { LeaveRequestEventStrategy } from '../handlers/event-strategies/leave-request-event-strategy' +import { MembershipListPublisher } from '../utils/nip43-membership' import { ParameterizedReplaceableEventStrategy } from '../handlers/event-strategies/parameterized-replaceable-event-strategy' import { ReplaceableEventStrategy } from '../handlers/event-strategies/replaceable-event-strategy' import { ReportEventStrategy } from '../handlers/event-strategies/report-event-strategy' @@ -87,9 +88,22 @@ export const eventStrategyFactory = // ephemeral handler, because kinds 28934/28935/28936 fall in the ephemeral // range (20000-29999) and would otherwise be broadcast to every subscriber. } else if (isNip43JoinRequest(event)) { - return new JoinRequestEventStrategy(adapter, inviteCodeRepository, userRepository, cache, settings) + return new JoinRequestEventStrategy( + adapter, + inviteCodeRepository, + userRepository, + cache, + settings, + new MembershipListPublisher(settings, userRepository, eventRepository, adapter), + ) } else if (isNip43LeaveRequest(event)) { - return new LeaveRequestEventStrategy(adapter, userRepository, cache, settings) + return new LeaveRequestEventStrategy( + adapter, + userRepository, + cache, + settings, + new MembershipListPublisher(settings, userRepository, eventRepository, adapter), + ) } else if (isNip43InviteRequest(event)) { return new InviteRequestEventStrategy(adapter) // NIP-90: DVM job requests (kind 5000-5999) checked early, same reasoning diff --git a/src/handlers/event-strategies/join-request-event-strategy.ts b/src/handlers/event-strategies/join-request-event-strategy.ts index 9a16d9710..b1e03ac27 100644 --- a/src/handlers/event-strategies/join-request-event-strategy.ts +++ b/src/handlers/event-strategies/join-request-event-strategy.ts @@ -6,6 +6,7 @@ import { createEventCommandResult } from '../../telemetry/event-metrics' import { createLogger } from '../../factories/logger-factory' import { Event } from '../../@types/event' import { IEventStrategy } from '../../@types/message-handlers' +import { MembershipListPublisher } from '../../utils/nip43-membership' import { Settings } from '../../@types/settings' import { WebSocketAdapterEvent } from '../../constants/adapter' @@ -21,6 +22,7 @@ export class JoinRequestEventStrategy implements IEventStrategy Settings, + private readonly membershipList?: MembershipListPublisher, ) {} public async execute(event: Event): Promise { @@ -78,6 +80,13 @@ export class JoinRequestEventStrategy implements IEventStrategy Settings, + private readonly membershipList?: MembershipListPublisher, ) {} public async execute(event: Event): Promise { @@ -66,6 +68,13 @@ export class LeaveRequestEventStrategy implements IEventStrategy { + logger('find admitted pubkeys (limit %d)', limit) + + const rows = await client('users') + .select('pubkey') + .where('is_admitted', true) + .andWhere('is_vanished', false) + .orderBy('pubkey', 'asc') + .limit(limit) + + return rows.map((row) => fromBuffer(row.pubkey)) + } + // Targeted update instead of upsert so admission revocation cannot clobber // unrelated columns (is_vanished, tos_accepted_at) on the existing row. public async revokeAdmission(pubkey: Pubkey, client: DatabaseClient = this.dbClient): Promise { diff --git a/src/utils/nip43-membership.ts b/src/utils/nip43-membership.ts new file mode 100644 index 000000000..0d617086b --- /dev/null +++ b/src/utils/nip43-membership.ts @@ -0,0 +1,115 @@ +import { andThen, pipe } from 'ramda' + +import { Event, UnidentifiedEvent } from '../@types/event' +import { EventKinds, EventTags } from '../constants/base' +import { getPublicKey, getRelayPrivateKey, identifyEvent, signEvent } from './event' +import { IEventRepository, IUserRepository } from '../@types/repositories' +import { IWebSocketAdapter } from '../@types/adapters' +import { isRelaySelfConsistent } from './nip43' +import { Pubkey, Tag } from '../@types/base' +import { createLogger } from '../factories/logger-factory' +import { Settings } from '../@types/settings' +import { WebSocketAdapterEvent } from '../constants/adapter' + +const logger = createLogger('nip43-membership') + +// A list this long is already a very large event to deliver to every subscriber, so a relay with more members +// than this publishes the first ones. NIP-43 says clients must not treat the list as complete anyway. +export const MAX_MEMBERSHIP_LIST_ENTRIES = 10_000 + +/** + * The NIP-43 membership list (kind 13534): a replaceable event signed by the relay's own key, with the NIP-70 + * `-` tag and one `member` tag per admitted pubkey. + */ +export const buildMembershipListEvent = async ( + relayPrivkey: string, + relayPubkey: string, + members: Pubkey[], + createdAt: number = Math.floor(Date.now() / 1000), +): Promise => { + const tags: Tag[] = [ + // NIP-70: the tag carries no value, which Tag (which requires an index 1) cannot express. + [EventTags.Protected] as unknown as Tag, + ...members.map((member): Tag => [EventTags.Member, member]), + ] + + const unidentifiedEvent: UnidentifiedEvent = { + pubkey: relayPubkey, + kind: EventKinds.NIP43_MEMBERSHIP_LIST, + created_at: createdAt, + content: '', + tags, + } + + return pipe(identifyEvent, andThen(signEvent(relayPrivkey)))(unidentifiedEvent) +} + +// Refreshes are queued so that two joins handled at the same moment do not publish out of order. The queue is +// per process: a second worker can still publish at the same time, which the list's "not authoritative" +// status allows, and the next join or leave corrects it. +let queue: Promise = Promise.resolve() + +export class MembershipListPublisher { + public constructor( + private readonly settings: () => Settings, + private readonly userRepository: IUserRepository, + private readonly eventRepository: IEventRepository, + private readonly webSocket: IWebSocketAdapter, + ) {} + + /** Publishes the current membership list when `nip43.publishMembershipList` is on, and does nothing otherwise. */ + public refresh(): Promise { + const run = queue.then(() => this.publish()) + queue = run.catch(() => undefined) + + return run + } + + private async publish(): Promise { + const settings = this.settings() + + if (settings.nip43?.enabled !== true || settings.nip43.publishMembershipList !== true) { + return + } + + // NIP-43 requires the list to be signed by the pubkey advertised as `self`; the relay signs with a key derived + // from SECRET, so a hand-edited `info.self` that differs would make the list unverifiable. + let selfConsistent: boolean | undefined + try { + selfConsistent = isRelaySelfConsistent(settings) + } catch (error) { + logger('info.self is not a valid pubkey, not publishing the membership list: %o', error) + return + } + + if (selfConsistent === false) { + logger('info.self does not match the relay signing pubkey, not publishing the membership list') + return + } + + const relayPrivkey = getRelayPrivateKey(settings.info?.relay_url) + const relayPubkey = getPublicKey(relayPrivkey) + + // One more than the cap tells us whether the list had to be cut. + const members = await this.userRepository.findAdmittedPubkeys(MAX_MEMBERSHIP_LIST_ENTRIES + 1) + if (members.length > MAX_MEMBERSHIP_LIST_ENTRIES) { + logger('more than %d members, the membership list is cut to the first ones', MAX_MEMBERSHIP_LIST_ENTRIES) + members.length = MAX_MEMBERSHIP_LIST_ENTRIES + } + + // A replaceable event is only replaced by a later created_at (or an equal one with a lower id), so a refresh in + // the same second as the last one would otherwise keep either list at random. + const [stored] = await this.eventRepository.findStoredReplaceable(relayPubkey, EventKinds.NIP43_MEMBERSHIP_LIST) + const now = Math.floor(Date.now() / 1000) + const createdAt = stored ? Math.max(now, stored.event_created_at + 1) : now + + const event = await buildMembershipListEvent(relayPrivkey, relayPubkey, members, createdAt) + + const count = await this.eventRepository.upsert(event) + if (count) { + this.webSocket.emit(WebSocketAdapterEvent.Broadcast, event) + } + + logger('published a membership list with %d members', members.length) + } +} diff --git a/test/unit/handlers/event-strategies/join-request-event-strategy.spec.ts b/test/unit/handlers/event-strategies/join-request-event-strategy.spec.ts index d22605958..db4587a04 100644 --- a/test/unit/handlers/event-strategies/join-request-event-strategy.spec.ts +++ b/test/unit/handlers/event-strategies/join-request-event-strategy.spec.ts @@ -160,4 +160,71 @@ describe('JoinRequestEventStrategy', () => { expect(result[2]).to.be.true expect(result[3]).to.contain('welcome to') }) + + describe('membership list', () => { + let refresh: sinon.SinonStub + + beforeEach(() => { + refresh = sinon.stub().resolves() + strategy = new JoinRequestEventStrategy(adapter, inviteCodeRepository, userRepository, cache, settings, { + refresh, + } as any) + ;(userRepository.findByPubkey as sinon.SinonStub).resolves(undefined) + ;(inviteCodeRepository.claimCode as sinon.SinonStub).resolves(true) + ;(userRepository.admitUser as sinon.SinonStub).resolves() + }) + + it('refreshes the list after a user is admitted', async () => { + await strategy.execute(event) + + expect(refresh).to.have.been.calledOnce + expect(refresh).to.have.been.calledAfter(userRepository.admitUser as sinon.SinonStub) + }) + + it('still admits and welcomes the user when the refresh fails', async () => { + refresh.rejects(new Error('db down')) + + await strategy.execute(event) + + expect((userRepository.admitUser as sinon.SinonStub).calledOnce).to.be.true + const result = emitStub.firstCall.args[1] + expect(result[2]).to.be.true + expect(result[3]).to.contain('welcome to') + }) + + it('does not refresh when the request is rejected', async () => { + settings = () => ({ info: { relay_url: 'wss://test.relay' }, nip43: { enabled: false } }) as any + strategy = new JoinRequestEventStrategy(adapter, inviteCodeRepository, userRepository, cache, settings, { + refresh, + } as any) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + + it('does not refresh when the invite code is not valid', async () => { + ;(inviteCodeRepository.claimCode as sinon.SinonStub).resolves(false) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + + it('does not refresh when the user is already a member', async () => { + ;(userRepository.findByPubkey as sinon.SinonStub).resolves({ isAdmitted: true }) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + + it('does not refresh when the user is not authenticated', async () => { + ;(adapter.getAuthenticatedPubkeys as sinon.SinonStub).returns(new Set()) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + }) }) diff --git a/test/unit/handlers/event-strategies/leave-request-event-strategy.spec.ts b/test/unit/handlers/event-strategies/leave-request-event-strategy.spec.ts index 37354b899..52f127ac4 100644 --- a/test/unit/handlers/event-strategies/leave-request-event-strategy.spec.ts +++ b/test/unit/handlers/event-strategies/leave-request-event-strategy.spec.ts @@ -144,4 +144,62 @@ describe('LeaveRequestEventStrategy', () => { const result = emitStub.firstCall.args[1] expect(result[2]).to.be.true }) + + describe('membership list', () => { + let refresh: sinon.SinonStub + + beforeEach(() => { + refresh = sinon.stub().resolves() + strategy = new LeaveRequestEventStrategy(adapter, userRepository, cache, settings, { refresh } as any) + }) + + it('refreshes the list after admission is revoked', async () => { + await strategy.execute(event) + + expect(refresh).to.have.been.calledOnce + expect(refresh).to.have.been.calledAfter(userRepository.revokeAdmission as sinon.SinonStub) + }) + + it('still revokes and answers OK when the refresh fails', async () => { + refresh.rejects(new Error('db down')) + + await strategy.execute(event) + + expect((userRepository.revokeAdmission as sinon.SinonStub).calledOnce).to.be.true + const result = emitStub.firstCall.args[1] + expect(result[2]).to.be.true + }) + + it('does not refresh for a leave that changes nothing, because the user is not admitted', async () => { + ;(userRepository.findByPubkey as sinon.SinonStub).resolves({ isAdmitted: false }) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + + it('does not refresh for a user that does not exist', async () => { + ;(userRepository.findByPubkey as sinon.SinonStub).resolves(undefined) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + + it('does not refresh when the request is rejected', async () => { + event.tags = [] + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + + it('does not refresh when the user is not authenticated', async () => { + ;(adapter.getAuthenticatedPubkeys as sinon.SinonStub).returns(new Set()) + + await strategy.execute(event) + + expect(refresh).not.to.have.been.called + }) + }) }) diff --git a/test/unit/repositories/user-repository.spec.ts b/test/unit/repositories/user-repository.spec.ts index 06354dba6..855e8faa6 100644 --- a/test/unit/repositories/user-repository.spec.ts +++ b/test/unit/repositories/user-repository.spec.ts @@ -104,6 +104,49 @@ describe('UserRepository', () => { }) }) + describe('.findAdmittedPubkeys', () => { + const otherHex = 'a'.repeat(64) + + const clientReturning = (rows: unknown[]) => { + const limitStub = sandbox.stub().resolves(rows) + const orderByStub = sandbox.stub().returns({ limit: limitStub }) + const andWhereStub = sandbox.stub().returns({ orderBy: orderByStub }) + const whereStub = sandbox.stub().returns({ andWhere: andWhereStub }) + const selectStub = sandbox.stub().returns({ where: whereStub }) + const client = sandbox.stub().returns({ select: selectStub }) as unknown as DatabaseClient + + return { client, selectStub, whereStub, andWhereStub, orderByStub, limitStub } + } + + it('returns the admitted pubkeys as hex', async () => { + const { client } = clientReturning([ + { pubkey: Buffer.from(pubkeyHex, 'hex') }, + { pubkey: Buffer.from(otherHex, 'hex') }, + ]) + + expect(await repository.findAdmittedPubkeys(10, client)).to.deep.equal([pubkeyHex, otherHex]) + }) + + it('returns an empty list when nobody is admitted', async () => { + const { client } = clientReturning([]) + + expect(await repository.findAdmittedPubkeys(10, client)).to.deep.equal([]) + }) + + it('asks for admitted users who have not vanished, in a stable order, up to the limit', async () => { + const { client, selectStub, whereStub, andWhereStub, orderByStub, limitStub } = clientReturning([]) + + await repository.findAdmittedPubkeys(25, client) + + expect(client).to.have.been.calledWith('users') + expect(selectStub).to.have.been.calledOnceWithExactly('pubkey') + expect(whereStub).to.have.been.calledOnceWithExactly('is_admitted', true) + expect(andWhereStub).to.have.been.calledOnceWithExactly('is_vanished', false) + expect(orderByStub).to.have.been.calledOnceWithExactly('pubkey', 'asc') + expect(limitStub).to.have.been.calledOnceWithExactly(25) + }) + }) + describe('.upsert', () => { function makeFakeQueryBuilder(rowCount = 1) { const fakeQB = { diff --git a/test/unit/utils/nip43-membership.spec.ts b/test/unit/utils/nip43-membership.spec.ts new file mode 100644 index 000000000..850905ed1 --- /dev/null +++ b/test/unit/utils/nip43-membership.spec.ts @@ -0,0 +1,227 @@ +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import * as eventUtils from '../../../src/utils/event' +import { buildMembershipListEvent, MAX_MEMBERSHIP_LIST_ENTRIES, MembershipListPublisher } from '../../../src/utils/nip43-membership' +import { EventKinds } from '../../../src/constants/base' +import { Settings } from '../../../src/@types/settings' +import { WebSocketAdapterEvent } from '../../../src/constants/adapter' + +chai.use(sinonChai) +chai.use(chaiAsPromised) +const { expect } = chai + +const relayPrivkey = '1'.repeat(64) +const relayPubkey = eventUtils.getPublicKey(relayPrivkey) +const memberA = 'a'.repeat(64) +const memberB = 'b'.repeat(64) + +describe('NIP-43 membership list', () => { + let sandbox: Sinon.SinonSandbox + + beforeEach(() => { + sandbox = Sinon.createSandbox() + }) + + afterEach(() => { + sandbox.restore() + }) + + describe('buildMembershipListEvent', () => { + it('builds a kind 13534 event signed by the relay key with a protected tag and one member tag per pubkey', async () => { + const event = await buildMembershipListEvent(relayPrivkey, relayPubkey, [memberA, memberB], 1_700_000_000) + + expect(event.kind).to.equal(EventKinds.NIP43_MEMBERSHIP_LIST) + expect(event.kind).to.equal(13534) + expect(event.pubkey).to.equal(relayPubkey) + expect(event.created_at).to.equal(1_700_000_000) + expect(event.content).to.equal('') + expect(event.tags).to.deep.equal([['-'], ['member', memberA], ['member', memberB]]) + }) + + it('produces an event with a valid id and signature', async () => { + const event = await buildMembershipListEvent(relayPrivkey, relayPubkey, [memberA], 1_700_000_000) + + expect(await eventUtils.isEventIdValid(event)).to.equal(true) + expect(await eventUtils.isEventSignatureValid(event)).to.equal(true) + }) + + it('builds an empty list when there are no members', async () => { + const event = await buildMembershipListEvent(relayPrivkey, relayPubkey, [], 1_700_000_000) + + expect(event.tags).to.deep.equal([['-']]) + }) + }) + + describe('MembershipListPublisher', () => { + let settings: Settings + let findAdmittedPubkeys: Sinon.SinonStub + let findStoredReplaceable: Sinon.SinonStub + let upsert: Sinon.SinonStub + let emit: Sinon.SinonStub + let publisher: MembershipListPublisher + const NOW = 1_800_000_000 + + beforeEach(() => { + sandbox.useFakeTimers({ now: NOW * 1000, toFake: ['Date'] }) + sandbox.stub(eventUtils, 'getRelayPrivateKey').returns(relayPrivkey) + settings = { + info: { relay_url: 'wss://relay.example.com' }, + nip43: { enabled: true, publishMembershipList: true }, + } as any + findAdmittedPubkeys = sandbox.stub().resolves([memberA, memberB]) + findStoredReplaceable = sandbox.stub().resolves([]) + upsert = sandbox.stub().resolves(1) + emit = sandbox.stub() + publisher = new MembershipListPublisher( + () => settings, + { findAdmittedPubkeys } as any, + { findStoredReplaceable, upsert } as any, + { emit } as any, + ) + }) + + it('publishes the list of admitted members and broadcasts it', async () => { + await publisher.refresh() + + expect(upsert).to.have.been.calledOnce + const event = upsert.firstCall.args[0] + expect(event.kind).to.equal(13534) + expect(event.pubkey).to.equal(relayPubkey) + expect(event.tags).to.deep.equal([['-'], ['member', memberA], ['member', memberB]]) + expect(event.created_at).to.equal(NOW) + expect(emit).to.have.been.calledOnceWithExactly(WebSocketAdapterEvent.Broadcast, event) + }) + + it('does nothing by default, when publishMembershipList is not set', async () => { + settings.nip43!.publishMembershipList = undefined + + await publisher.refresh() + + expect(findAdmittedPubkeys).not.to.have.been.called + expect(upsert).not.to.have.been.called + }) + + it('does nothing when it is switched off', async () => { + settings.nip43!.publishMembershipList = false + + await publisher.refresh() + + expect(upsert).not.to.have.been.called + }) + + it('does nothing when NIP-43 is disabled', async () => { + settings.nip43!.enabled = false + + await publisher.refresh() + + expect(upsert).not.to.have.been.called + }) + + it('does not publish when info.self is not the relay signing pubkey', async () => { + settings.info!.self = 'c'.repeat(64) + + await publisher.refresh() + + expect(upsert).not.to.have.been.called + }) + + it('publishes when info.self is the relay signing pubkey', async () => { + settings.info!.self = relayPubkey + + await publisher.refresh() + + expect(upsert).to.have.been.calledOnce + }) + + it('does not publish when info.self is a malformed npub', async () => { + settings.info!.self = 'npub1notvalid' + + await publisher.refresh() + + expect(upsert).not.to.have.been.called + }) + + it('uses a created_at later than the stored list, so a refresh in the same second still replaces it', async () => { + findStoredReplaceable.resolves([{ event_created_at: NOW, event_id: Buffer.alloc(32) }]) + + await publisher.refresh() + + expect(findStoredReplaceable).to.have.been.calledOnceWithExactly(relayPubkey, 13534) + expect(upsert.firstCall.args[0].created_at).to.equal(NOW + 1) + }) + + it('uses the current time when the stored list is older', async () => { + findStoredReplaceable.resolves([{ event_created_at: NOW - 500, event_id: Buffer.alloc(32) }]) + + await publisher.refresh() + + expect(upsert.firstCall.args[0].created_at).to.equal(NOW) + }) + + it('does not broadcast when the list was not stored', async () => { + upsert.resolves(0) + + await publisher.refresh() + + expect(emit).not.to.have.been.called + }) + + it('cuts the list at the maximum number of entries', async () => { + findAdmittedPubkeys.resolves( + Array.from({ length: MAX_MEMBERSHIP_LIST_ENTRIES + 1 }, (_, i) => i.toString(16).padStart(64, '0')), + ) + + await publisher.refresh() + + expect(findAdmittedPubkeys).to.have.been.calledOnceWithExactly(MAX_MEMBERSHIP_LIST_ENTRIES + 1) + expect(upsert.firstCall.args[0].tags).to.have.length(MAX_MEMBERSHIP_LIST_ENTRIES + 1) + }) + + it('rejects when the list cannot be stored, so the caller can log it', async () => { + upsert.rejects(new Error('db down')) + + await expect(publisher.refresh()).to.be.rejectedWith('db down') + }) + + it('keeps working after a failed refresh', async () => { + upsert.onFirstCall().rejects(new Error('db down')) + + await publisher.refresh().catch(() => undefined) + await publisher.refresh() + + expect(upsert).to.have.been.calledTwice + }) + + it('publishes refreshes one after the other, in the order they were asked for', async () => { + const order: string[] = [] + let releaseFirst!: () => void + const gate = new Promise((resolve) => { + releaseFirst = resolve + }) + findAdmittedPubkeys.onFirstCall().callsFake(async () => { + order.push('first-start') + await gate + order.push('first-end') + return [memberA] + }) + findAdmittedPubkeys.onSecondCall().callsFake(async () => { + order.push('second-start') + return [memberA, memberB] + }) + + const first = publisher.refresh() + const second = publisher.refresh() + await new Promise((resolve) => setImmediate(resolve)) + expect(order).to.deep.equal(['first-start']) + releaseFirst() + await Promise.all([first, second]) + + expect(order).to.deep.equal(['first-start', 'first-end', 'second-start']) + expect(upsert.firstCall.args[0].tags).to.have.length(2) + expect(upsert.secondCall.args[0].tags).to.have.length(3) + }) + }) +}) diff --git a/test/unit/utils/settings.spec.ts b/test/unit/utils/settings.spec.ts index a606c710d..d786d5c04 100644 --- a/test/unit/utils/settings.spec.ts +++ b/test/unit/utils/settings.spec.ts @@ -305,6 +305,12 @@ describe('SettingsStatic', () => { expect(defaults).to.have.nested.property('nip43.inviteRequestWhitelist').that.deep.equals([]) }) + it('default-settings.yaml does not publish the membership list, as it makes the members public', () => { + const defaults = SettingsStatic.loadAndParseYamlFile(SettingsStatic.getDefaultSettingsFilePath()) + + expect(defaults).to.have.nested.property('nip43.publishMembershipList', false) + }) + it('default-settings.yaml rate limits kind 28935 invite requests per pubkey', () => { const defaults = SettingsStatic.loadAndParseYamlFile(SettingsStatic.getDefaultSettingsFilePath()) From 14b7c200bfe680d50cbf8db35470e19f37ec46db Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Sat, 21 Nov 2026 00:18:12 +0530 Subject: [PATCH 2/2] fix(nip43): refresh the list on vanish and broadcast past a closed socket Signed-off-by: Priyanshubhartistm --- .changeset/nip43-membership-list.md | 2 +- CONFIGURATION.md | 2 +- src/@types/adapters.ts | 6 +++ src/factories/event-strategy-factory.ts | 7 +++- .../event-strategies/vanish-event-strategy.ts | 10 +++++ src/utils/nip43-membership.ts | 5 ++- .../vanish-event-strategy.spec.ts | 41 +++++++++++++++++++ test/unit/utils/nip43-membership.spec.ts | 15 +++++-- 8 files changed, 79 insertions(+), 9 deletions(-) diff --git a/.changeset/nip43-membership-list.md b/.changeset/nip43-membership-list.md index d9f0ffaff..870c535e9 100644 --- a/.changeset/nip43-membership-list.md +++ b/.changeset/nip43-membership-list.md @@ -4,4 +4,4 @@ feat(nip43): publish the kind 13534 membership list -With the new `nip43.publishMembershipList` setting (off by default) the relay publishes a replaceable kind 13534 event, signed by its own key, with the NIP-70 `-` tag and one `member` tag per admitted pubkey, and refreshes it after every successful join or leave. Joins and leaves that are rejected or change nothing do not refresh it. Nothing is published when `info.self` does not match the relay's signing pubkey, since NIP-43 requires that signer. The list makes every member's pubkey public to anyone who can read the relay, which is why the setting defaults to off. It is a convenience for clients, not the source of truth for who may publish, and it holds at most the first 10,000 members. Users who asked to vanish are left out. Admissions made another way, for example a paid admission, do not refresh it. +With the new `nip43.publishMembershipList` setting (off by default) the relay publishes a replaceable kind 13534 event, signed by its own key, with the NIP-70 `-` tag and one `member` tag per admitted pubkey, and refreshes it after every successful join or leave, and when a member's request to vanish is accepted, so that pubkey is taken out of it. Joins and leaves that are rejected or change nothing do not refresh it. Nothing is published when `info.self` does not match the relay's signing pubkey, since NIP-43 requires that signer. The list makes every member's pubkey public to anyone who can read the relay, which is why the setting defaults to off. It is a convenience for clients, not the source of truth for who may publish, and it holds at most the first 10,000 members. Users who asked to vanish are left out. Admissions made another way, for example a paid admission, do not refresh it. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index f7837b3bd..a59a0d448 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -222,7 +222,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 a kind 13534 membership list (a replaceable event with a NIP-70 `-` tag and one `member` tag per admitted pubkey) signed by the relay's own key, and refresh it after each successful join or leave. **It makes every member's pubkey public to anyone who can read the relay.** `info.self` must match the relay's signing pubkey, or nothing is published. Joins and leaves that are rejected or change nothing do not refresh it, and neither does an admission made another way (for example a paid admission). The list is a convenience for clients, not the source of truth for who may publish. Defaults to false. | +| nip43.publishMembershipList | Publish a kind 13534 membership list (a replaceable event with a NIP-70 `-` tag and one `member` tag per admitted pubkey) signed by the relay's own key, and refresh it after each successful join or leave. **It makes every member's pubkey public to anyone who can read the relay.** `info.self` must match the relay's signing pubkey, or nothing is published. It is also refreshed when a member's request to vanish is accepted, which takes that pubkey out of it. Joins and leaves that are rejected or change nothing do not refresh it, and neither does an admission made another way (for example a paid admission). The list is a convenience for clients, not the source of truth for who may publish. Defaults to false. | | 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('', event_content));` — otherwise the planner cannot use the index and queries fall back to sequential scans. | diff --git a/src/@types/adapters.ts b/src/@types/adapters.ts index 465f999b4..e8dc537cc 100644 --- a/src/@types/adapters.ts +++ b/src/@types/adapters.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'node:stream' +import { Event } from './event' import { INegentropySessions } from './negentropy' import { SubscriptionFilter } from './subscription' @@ -34,6 +35,11 @@ export type IWebSocketAdapter = EventEmitter & { * while the client is slow. */ waitForWritable(): Promise + /** + * Hands an event to every subscriber of this relay (the server adapter and, in a worker, the primary), without + * going through this socket's own listeners, which are gone once the client has disconnected. + */ + onBroadcast(event: Event): void drainAndClose(reason?: string): void /** NIP-77 sessions of this connection. */ getNegentropySessions(): INegentropySessions diff --git a/src/factories/event-strategy-factory.ts b/src/factories/event-strategy-factory.ts index 882b855e4..8db6d2e75 100644 --- a/src/factories/event-strategy-factory.ts +++ b/src/factories/event-strategy-factory.ts @@ -55,7 +55,12 @@ export const eventStrategyFactory = ): Factory>, [Event, IWebSocketAdapter]> => ([event, adapter]: [Event, IWebSocketAdapter]) => { if (isRequestToVanishEvent(event)) { - return new VanishEventStrategy(adapter, eventRepository, userRepository) + return new VanishEventStrategy( + adapter, + eventRepository, + userRepository, + new MembershipListPublisher(settings, userRepository, eventRepository, adapter), + ) } else if (isGiftWrapEvent(event)) { return new GiftWrapEventStrategy(adapter, eventRepository) } else if (isMarmotGroupEvent(event)) { diff --git a/src/handlers/event-strategies/vanish-event-strategy.ts b/src/handlers/event-strategies/vanish-event-strategy.ts index 35d269cd7..8f85a3401 100644 --- a/src/handlers/event-strategies/vanish-event-strategy.ts +++ b/src/handlers/event-strategies/vanish-event-strategy.ts @@ -5,6 +5,7 @@ import { Event } from '../../@types/event' import { EventKinds } from '../../constants/base' import { IEventStrategy } from '../../@types/message-handlers' import { IWebSocketAdapter } from '../../@types/adapters' +import { MembershipListPublisher } from '../../utils/nip43-membership' import { WebSocketAdapterEvent } from '../../constants/adapter' const logger = createLogger('vanish-event-strategy') @@ -14,6 +15,7 @@ export class VanishEventStrategy implements IEventStrategy> private readonly webSocket: IWebSocketAdapter, private readonly eventRepository: IEventRepository, private readonly userRepository: IUserRepository, + private readonly membershipList?: MembershipListPublisher, ) {} public async execute(event: Event): Promise { @@ -25,6 +27,14 @@ export class VanishEventStrategy implements IEventStrategy> await this.userRepository.setVanished(event.pubkey, true) + // A member who vanishes is left out of the published membership list, which only changes when it is refreshed. + // The vanish itself is done whether or not the list could be refreshed. + try { + await this.membershipList?.refresh() + } catch (error) { + logger('unable to refresh the membership list after %s vanished: %o', event.pubkey, error) + } + this.webSocket.emit(WebSocketAdapterEvent.Message, createEventCommandResult(event.id, true, count ? '' : 'duplicate:')) } } diff --git a/src/utils/nip43-membership.ts b/src/utils/nip43-membership.ts index 0d617086b..abdef58da 100644 --- a/src/utils/nip43-membership.ts +++ b/src/utils/nip43-membership.ts @@ -9,7 +9,6 @@ import { isRelaySelfConsistent } from './nip43' import { Pubkey, Tag } from '../@types/base' import { createLogger } from '../factories/logger-factory' import { Settings } from '../@types/settings' -import { WebSocketAdapterEvent } from '../constants/adapter' const logger = createLogger('nip43-membership') @@ -107,7 +106,9 @@ export class MembershipListPublisher { const count = await this.eventRepository.upsert(event) if (count) { - this.webSocket.emit(WebSocketAdapterEvent.Broadcast, event) + // Not webSocket.emit(Broadcast): a queued refresh can run after the client that asked for it has + // disconnected, and its adapter no longer listens for that event. + this.webSocket.onBroadcast(event) } logger('published a membership list with %d members', members.length) diff --git a/test/unit/handlers/event-strategies/vanish-event-strategy.spec.ts b/test/unit/handlers/event-strategies/vanish-event-strategy.spec.ts index 3a4a8d994..a3a7db5d8 100644 --- a/test/unit/handlers/event-strategies/vanish-event-strategy.spec.ts +++ b/test/unit/handlers/event-strategies/vanish-event-strategy.spec.ts @@ -83,4 +83,45 @@ describe('VanishEventStrategy', () => { 'duplicate:', ]) }) + + describe('membership list', () => { + let refresh: Sinon.SinonStub + + beforeEach(() => { + refresh = sandbox.stub().resolves() + strategy = new VanishEventStrategy(webSocket, eventRepository, userRepository, { refresh } as any) + }) + + it('refreshes the membership list once the user is marked as vanished', async () => { + await strategy.execute(event) + + expect(refresh).to.have.been.calledOnce + expect(refresh).to.have.been.calledAfter(userRepository.setVanished) + }) + + it('still completes the vanish and answers OK when the refresh fails', async () => { + refresh.rejects(new Error('db down')) + + await strategy.execute(event) + + expect(userRepository.setVanished).to.have.been.calledOnceWithExactly(event.pubkey, true) + expect(webSocketEmitStub).to.have.been.calledOnce + }) + + it('does not refresh when the vanish could not be completed', async () => { + userRepository.setVanished.rejects(new Error('db down')) + + await expect(strategy.execute(event)).to.be.rejectedWith('db down') + + expect(refresh).not.to.have.been.called + }) + + it('works without a membership list publisher', async () => { + strategy = new VanishEventStrategy(webSocket, eventRepository, userRepository) + + await strategy.execute(event) + + expect(webSocketEmitStub).to.have.been.calledOnce + }) + }) }) diff --git a/test/unit/utils/nip43-membership.spec.ts b/test/unit/utils/nip43-membership.spec.ts index 850905ed1..c371d1a1c 100644 --- a/test/unit/utils/nip43-membership.spec.ts +++ b/test/unit/utils/nip43-membership.spec.ts @@ -7,7 +7,6 @@ import * as eventUtils from '../../../src/utils/event' import { buildMembershipListEvent, MAX_MEMBERSHIP_LIST_ENTRIES, MembershipListPublisher } from '../../../src/utils/nip43-membership' import { EventKinds } from '../../../src/constants/base' import { Settings } from '../../../src/@types/settings' -import { WebSocketAdapterEvent } from '../../../src/constants/adapter' chai.use(sinonChai) chai.use(chaiAsPromised) @@ -61,6 +60,7 @@ describe('NIP-43 membership list', () => { let findStoredReplaceable: Sinon.SinonStub let upsert: Sinon.SinonStub let emit: Sinon.SinonStub + let onBroadcast: Sinon.SinonStub let publisher: MembershipListPublisher const NOW = 1_800_000_000 @@ -75,11 +75,12 @@ describe('NIP-43 membership list', () => { findStoredReplaceable = sandbox.stub().resolves([]) upsert = sandbox.stub().resolves(1) emit = sandbox.stub() + onBroadcast = sandbox.stub() publisher = new MembershipListPublisher( () => settings, { findAdmittedPubkeys } as any, { findStoredReplaceable, upsert } as any, - { emit } as any, + { emit, onBroadcast } as any, ) }) @@ -92,7 +93,13 @@ describe('NIP-43 membership list', () => { expect(event.pubkey).to.equal(relayPubkey) expect(event.tags).to.deep.equal([['-'], ['member', memberA], ['member', memberB]]) expect(event.created_at).to.equal(NOW) - expect(emit).to.have.been.calledOnceWithExactly(WebSocketAdapterEvent.Broadcast, event) + expect(onBroadcast).to.have.been.calledOnceWithExactly(event) + }) + + it('broadcasts through the adapter, not through its listeners, which are gone once the client disconnected', async () => { + await publisher.refresh() + + expect(emit).not.to.have.been.called }) it('does nothing by default, when publishMembershipList is not set', async () => { @@ -166,7 +173,7 @@ describe('NIP-43 membership list', () => { await publisher.refresh() - expect(emit).not.to.have.been.called + expect(onBroadcast).not.to.have.been.called }) it('cuts the list at the maximum number of entries', async () => {