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
7 changes: 7 additions & 0 deletions .changeset/nip43-membership-list.md
Original file line number Diff line number Diff line change
@@ -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, 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.
2 changes: 1 addition & 1 deletion CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
1 change: 1 addition & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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('<your_language>', event_content));` — otherwise the planner cannot use the index and queries fall back to sequential scans. |
Expand Down
5 changes: 5 additions & 0 deletions resources/default-settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions src/@types/adapters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EventEmitter } from 'node:stream'
import { Event } from './event'
import { INegentropySessions } from './negentropy'
import { SubscriptionFilter } from './subscription'

Expand Down Expand Up @@ -34,6 +35,11 @@ export type IWebSocketAdapter = EventEmitter & {
* while the client is slow.
*/
waitForWritable(): Promise<void>
/**
* 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
Expand Down
1 change: 1 addition & 0 deletions src/@types/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ export interface IUserRepository {
setVanished(pubkey: Pubkey, vanished: boolean, client?: DatabaseClient): Promise<number>
admitUser(pubkey: Pubkey, admittedAt: Date, client?: DatabaseClient): Promise<void>
revokeAdmission(pubkey: Pubkey, client?: DatabaseClient): Promise<number>
findAdmittedPubkeys(limit: number, client?: DatabaseClient): Promise<Pubkey[]>
}

export interface Nip05VerificationAdminListQuery {
Expand Down
5 changes: 5 additions & 0 deletions src/@types/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 22 additions & 3 deletions src/factories/event-strategy-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -54,7 +55,12 @@ export const eventStrategyFactory =
): Factory<IEventStrategy<Event, Promise<void>>, [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)) {
Expand Down Expand Up @@ -87,9 +93,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
Expand Down
9 changes: 9 additions & 0 deletions src/handlers/event-strategies/join-request-event-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -21,6 +22,7 @@ export class JoinRequestEventStrategy implements IEventStrategy<Event, Promise<v
private readonly userRepository: IUserRepository,
private readonly cache: ICacheAdapter,
private readonly settings: () => Settings,
private readonly membershipList?: MembershipListPublisher,
) {}

public async execute(event: Event): Promise<void> {
Expand Down Expand Up @@ -78,6 +80,13 @@ export class JoinRequestEventStrategy implements IEventStrategy<Event, Promise<v
logger('unable to invalidate admission cache for %s: %o', event.pubkey, error)
}

// The member is admitted whether or not the list could be refreshed, so a failure here must not fail the join.
try {
await this.membershipList?.refresh()
Comment thread
Priyanshubhartistm marked this conversation as resolved.
Resolved
} catch (error) {
logger('unable to refresh the membership list after admitting %s: %o', event.pubkey, error)
}

const relayUrl = currentSettings.info?.relay_url ?? 'this relay'
logger('admitted %s via invite code', event.pubkey)
this.sendResult(event.id, true, `info: welcome to ${relayUrl}!`)
Expand Down
9 changes: 9 additions & 0 deletions src/handlers/event-strategies/leave-request-event-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { IEventStrategy } from '../../@types/message-handlers'
import { isNip43RequestTimestampValid } from '../../utils/nip43'
import { isProtectedEvent } from '../../utils/event'
import { IUserRepository } from '../../@types/repositories'
import { MembershipListPublisher } from '../../utils/nip43-membership'
import { Settings } from '../../@types/settings'
import { WebSocketAdapterEvent } from '../../constants/adapter'

Expand All @@ -18,6 +19,7 @@ export class LeaveRequestEventStrategy implements IEventStrategy<Event, Promise<
private readonly userRepository: IUserRepository,
private readonly cache: ICacheAdapter,
private readonly settings: () => Settings,
private readonly membershipList?: MembershipListPublisher,
) {}

public async execute(event: Event): Promise<void> {
Expand Down Expand Up @@ -66,6 +68,13 @@ export class LeaveRequestEventStrategy implements IEventStrategy<Event, Promise<
logger('unable to invalidate admission cache for %s: %o', event.pubkey, error)
}

// The admission is revoked whether or not the list could be refreshed, so a failure here must not fail the leave.
try {
await this.membershipList?.refresh()
} catch (error) {
logger('unable to refresh the membership list after %s left: %o', event.pubkey, error)
}

logger('revoked admission for %s', event.pubkey)
this.sendResult(event.id, true, '')
}
Expand Down
10 changes: 10 additions & 0 deletions src/handlers/event-strategies/vanish-event-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -14,6 +15,7 @@ export class VanishEventStrategy implements IEventStrategy<Event, Promise<void>>
private readonly webSocket: IWebSocketAdapter,
private readonly eventRepository: IEventRepository,
private readonly userRepository: IUserRepository,
private readonly membershipList?: MembershipListPublisher,
) {}

public async execute(event: Event): Promise<void> {
Expand All @@ -25,6 +27,14 @@ export class VanishEventStrategy implements IEventStrategy<Event, Promise<void>>

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:'))
}
}
19 changes: 18 additions & 1 deletion src/repositories/user-repository.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { always, applySpec, defaultTo, omit, pipe, prop } from 'ramda'
import { DatabaseClient, Pubkey } from '../@types/base'
import { DBUser, User } from '../@types/user'
import { fromDBUser, toBuffer } from '../utils/transform'
import { fromBuffer, fromDBUser, toBuffer } from '../utils/transform'
import { IEventRepository, IUserRepository } from '../@types/repositories'
import { createLogger } from '../factories/logger-factory'

Expand Down Expand Up @@ -113,6 +113,23 @@ export class UserRepository implements IUserRepository {
return BigInt(user.balance)
}

/**
* Pubkeys of the admitted members, in a stable order, at most `limit`. Users who asked to vanish are left
* out: they cannot publish, and they asked not to be shown.
*/
public async findAdmittedPubkeys(limit: number, client: DatabaseClient = this.dbClient): Promise<Pubkey[]> {
logger('find admitted pubkeys (limit %d)', limit)

const rows = await client<DBUser>('users')
.select('pubkey')
.where('is_admitted', true)
.andWhere('is_vanished', false)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
.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<number> {
Expand Down
Loading
Loading