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/keep-user-admission-and-vanish-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': patch
---

fix(storage): stop invoices and vanish checks from overwriting a user's admission and vanish state

Creating an admission or subscription invoice upserted its pubkey with `is_admitted` and `is_vanished` set to false, so it cleared both for an existing user. A renewal invoice, including the ones the relay creates itself, took a paying subscriber's admission away, so their events were refused once the admission cache expired, and an invoice anyone could request for a vanished pubkey lifted its request to vanish. An existing row now keeps the admission, vanish and terms fields the caller did not supply, and a new row created without a vanish state starts vanished when a request to vanish for the pubkey is stored. The vanish check for a pubkey without a row no longer overwrites a row another writer created in the meantime and returns that row's state. Both look for the stored request on the primary instead of a replica that may not have it yet. A deliberate limit: any undeleted stored request to vanish counts, as it already did when a user's first event created the row, so one that names only another relay also starts a new row vanished.
10 changes: 9 additions & 1 deletion src/@types/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export interface IEventRepository {
findStoredReplaceable(pubkey: Pubkey, kind: number): IQueryResult<ReconciliationItem[]>
deleteByPubkeyAndIds(pubkey: Pubkey, ids: EventId[]): Promise<number>
deleteByPubkeyExceptKinds(pubkey: Pubkey, excludedKinds: number[]): Promise<number>
hasActiveRequestToVanish(pubkey: Pubkey): Promise<boolean>
hasActiveRequestToVanish(pubkey: Pubkey, client?: DatabaseClient): Promise<boolean>
deleteExpiredAndRetained(options?: EventRetentionOptions): Promise<EventPurgeCounts>
}

Expand Down Expand Up @@ -232,6 +232,14 @@ export interface IUserSubscriptionRepository {

export interface IUserRepository {
findByPubkey(pubkey: Pubkey, client?: DatabaseClient): Promise<User | undefined>
/**
* Writes only the fields `user` supplies. An existing row keeps everything else — admission,
* vanish state and the ToS timestamp are never reset by omission — and a missing row is
* created with `false` for the flags, except that its vanish state comes from the stored
* request-to-vanish events when the caller does not give one.
*
* Resolves with the number of rows written, so `0` means the row already existed.
*/
upsert(user: Partial<User>, client?: DatabaseClient): Promise<number>
getBalanceByPubkey(pubkey: Pubkey, client?: DatabaseClient): Promise<bigint>
isVanished(pubkey: Pubkey, client?: DatabaseClient): Promise<boolean>
Expand Down
8 changes: 6 additions & 2 deletions src/repositories/event-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,8 +550,12 @@ export class EventRepository implements IEventRepository {
})
}

public async hasActiveRequestToVanish(pubkey: string): Promise<boolean> {
const result = await this.readReplicaDbClient('events')
// The answer becomes the user's stored vanish state, so it is never read from a replica that may lag.
public async hasActiveRequestToVanish(
pubkey: string,
client: DatabaseClient = this.masterDbClient,
): Promise<boolean> {
const result = await client('events')
.select('event_id')
.where('event_pubkey', toBuffer(pubkey))
.where('event_kind', EventKinds.REQUEST_TO_VANISH)
Expand Down
58 changes: 32 additions & 26 deletions src/repositories/user-repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { always, applySpec, defaultTo, omit, pipe, prop } from 'ramda'
import { isEmpty, pickBy, prop } from 'ramda'
import { DatabaseClient, Pubkey } from '../@types/base'
import { DBUser, User } from '../@types/user'
import { fromBuffer, fromDBUser, toBuffer } from '../utils/transform'
Expand Down Expand Up @@ -29,43 +29,49 @@ export class UserRepository implements IUserRepository {

const date = new Date()

const row = applySpec<DBUser>({
pubkey: pipe(prop('pubkey'), toBuffer),
is_admitted: pipe(prop('isAdmitted'), defaultTo(false)),
is_vanished: pipe(prop('isVanished'), defaultTo(false)),
tos_accepted_at: prop('tosAcceptedAt'),
updated_at: always(date),
created_at: always(date),
})(user)
// A new row starts from the stored events, so creating it cannot lift a request to vanish.
const isVanished = user.isVanished ?? (await this.eventRepository.hasActiveRequestToVanish(user.pubkey, client))

const query = client<DBUser>('users')
.insert(row)
.onConflict('pubkey')
.merge(omit(['pubkey', 'balance', 'created_at'])(row))
const row = {
pubkey: toBuffer(user.pubkey),
is_admitted: user.isAdmitted ?? false,
is_vanished: isVanished,
tos_accepted_at: user.tosAcceptedAt,
updated_at: date,
created_at: date,
}

return {
then: <T1, T2>(
onfulfilled: (value: number) => T1 | PromiseLike<T1>,
onrejected: (reason: any) => T2 | PromiseLike<T2>,
) => query.then(prop('rowCount') as () => number).then(onfulfilled, onrejected),
catch: <T>(onrejected: (reason: any) => T | PromiseLike<T>) => query.catch(onrejected),
toString: (): string => query.toString(),
} as Promise<number>
// An existing row takes only the fields the caller supplied.
const changes: Record<string, unknown> = pickBy((value) => value !== undefined, {
is_admitted: user.isAdmitted,
is_vanished: user.isVanished,
tos_accepted_at: user.tosAcceptedAt,
})

const insert = client<DBUser>('users').insert(row).onConflict('pubkey')
const query = isEmpty(changes) ? insert.ignore() : insert.merge({ ...changes, updated_at: date })

return query.then(prop('rowCount') as () => number)
}

/**
* Returns vanish state from users.is_vanished, or lazily hydrates a user row from events once
* when no users row exists (single upsert; no duplicate inserts).
* Returns vanish state from users.is_vanished. A missing row is created from the stored events,
* and a row another writer created first is left as it is.
*/
public async isVanished(pubkey: Pubkey, client: DatabaseClient = this.dbClient): Promise<boolean> {
const existing = await this.findByPubkey(pubkey, client)
if (existing) {
return existing.isVanished
}

const vanishedFromEvents = await this.eventRepository.hasActiveRequestToVanish(pubkey)
await this.upsertVanishState(pubkey, vanishedFromEvents, client)
return vanishedFromEvents
await this.upsert({ pubkey }, client)

const created = await this.findByPubkey(pubkey, client)
if (!created) {
throw new Error(`users row for ${pubkey} is missing after it was created`)
}

return created.isVanished
}

public setVanished(pubkey: Pubkey, vanished: boolean, client: DatabaseClient = this.dbClient): Promise<number> {
Expand Down
2 changes: 1 addition & 1 deletion src/scripts/benchmark-queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ function buildCases(): BenchmarkCase[] {
{
name: 'hasActiveRequestToVanish (pubkey + kind=62 + not deleted)',
description:
'Exact query run on every inbound event via UserRepository.isVanished; latency here is a per-message tax. This is the only hot path that filters on deleted_at.',
'Exact query `UserRepository.isVanished` runs when a pubkey has no users row, on the master so a lagging replica cannot decide what is stored; it is not on the per-message path. This is the only query in the set that reads `deleted_at IS NULL`; the retention sweep reads the same column with `IS NOT NULL`.',
skipIf: (ctx) => (ctx.samplePubkey ? undefined : 'no events rows found'),
build: (ctx) =>
ctx.db('events')
Expand Down
24 changes: 24 additions & 0 deletions test/integration/features/invoices/nwc-invoice.feature
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,27 @@ Feature: NWC invoice integration
When I request an admission invoice for pubkey "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
Then the invoice request response status is 200
And an NWC invoice is stored as pending for pubkey "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"

# The subscription fixture's own teardown removes the subscriber it creates.
@subscription-plan-change
Scenario: a renewal invoice leaves the subscriber admitted and vanished
Given NWC payments are enabled with URI scheme "nostr+walletconnect"
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
And NWC wallet service make_invoice responds with a pending invoice
And a subscriber has a running "basic" plan that ends in 10 days
And the subscriber has requested to vanish
When I request a "basic" plan invoice for the subscriber
Then the invoice request response status is 200
And the subscriber is still admitted and vanished

Scenario: an invoice for a pubkey without a users row keeps its stored request to vanish
Given someone called Alice
And Alice sends a request_to_vanish event
And the relay has no users row for Alice
And NWC payments are enabled with URI scheme "nostr+walletconnect"
And NWC wallet service make_invoice responds with a pending invoice
When I request an admission invoice for Alice
Then the invoice request response status is 200
And the relay has a users row for Alice that is vanished
And Alice drafts a text_note event with content "still gone"
Then Alice sends their last draft event unsuccessfully because "blocked: request to vanish active for pubkey"
69 changes: 65 additions & 4 deletions test/integration/features/invoices/nwc-invoice.feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,12 @@ Given('NWC wallet service make_invoice never responds', async function (this: Wo
},
})
})
When('I request an admission invoice for pubkey {string}', async function (this: World<Record<string, any>>, pubkey: string) {
const requestInvoice = async (world: World<Record<string, any>>, pubkey: string, fields: Record<string, string>) => {
const response: AxiosResponse = await axios.post(
INVOICES_URL,
new URLSearchParams({
tosAccepted: 'yes',
feeSchedule: 'admission',
...fields,
pubkey,
}).toString(),
{
Expand All @@ -213,12 +213,73 @@ When('I request an admission invoice for pubkey {string}', async function (this:
},
)

this.parameters.nwcInvoiceHttpResponse = response
this.parameters.nwcTestPubkeys = [...(this.parameters.nwcTestPubkeys ?? []), pubkey]
world.parameters.nwcInvoiceHttpResponse = response
world.parameters.nwcTestPubkeys = [...(world.parameters.nwcTestPubkeys ?? []), pubkey]

if (response.status === 400) {
throw new Error(`Unexpected 400 response body: ${String(response.data)}`)
}
}

When(
'I request an admission invoice for pubkey {string}',
async function (this: World<Record<string, any>>, pubkey: string) {
await requestInvoice(this, pubkey, { feeSchedule: 'admission' })
},
)

const recordInvoicesFor = async (world: World<Record<string, any>>, pubkey: string) => {
const rows = await getMasterDbClient()('invoices').where('pubkey', Buffer.from(pubkey, 'hex')).select('id')

world.parameters.nwcInsertedInvoiceIds = [
...(world.parameters.nwcInsertedInvoiceIds ?? []),
...rows.map((row: { id: string }) => row.id),
]
}

When('I request an admission invoice for {word}', async function (this: World<Record<string, any>>, name: string) {
const { pubkey } = this.parameters.identities[name]

await requestInvoice(this, pubkey, { feeSchedule: 'admission' })
await recordInvoicesFor(this, pubkey)
})

When(
'I request a {string} plan invoice for the subscriber',
async function (this: World<Record<string, any>>, planId: string) {
const pubkey = (this.parameters.subscriberPubkey as Buffer).toString('hex')

await requestInvoice(this, pubkey, { planId })
await recordInvoicesFor(this, pubkey)
},
)

Given('the relay has no users row for {word}', async function (this: World<Record<string, any>>, name: string) {
const { pubkey } = this.parameters.identities[name]

await getMasterDbClient()('users').where('pubkey', Buffer.from(pubkey, 'hex')).delete()
})

Then(
'the relay has a users row for {word} that is vanished',
async function (this: World<Record<string, any>>, name: string) {
const { pubkey } = this.parameters.identities[name]
const user = await getMasterDbClient()('users').where('pubkey', Buffer.from(pubkey, 'hex')).first('is_vanished')

expect(user).to.deep.equal({ is_vanished: true })
},
)

Given('the subscriber has requested to vanish', async function (this: World<Record<string, any>>) {
await getMasterDbClient()('users').where('pubkey', this.parameters.subscriberPubkey).update({ is_vanished: true })
})

Then('the subscriber is still admitted and vanished', async function (this: World<Record<string, any>>) {
const user = await getMasterDbClient()('users')
.where('pubkey', this.parameters.subscriberPubkey)
.first('is_admitted', 'is_vanished')

expect(user).to.deep.equal({ is_admitted: true, is_vanished: true })
})

Then('the invoice request response status is {int}', function (this: World<Record<string, any>>, statusCode: number) {
Expand Down
37 changes: 36 additions & 1 deletion test/unit/repositories/event-repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ chai.use(sinonChai)

const { expect } = chai

import { ContextMetadataKey, EventDeduplicationMetadataKey, EventTags } from '../../../src/constants/base'
import { ContextMetadataKey, EventDeduplicationMetadataKey, EventKinds, EventTags } from '../../../src/constants/base'
import { DatabaseClient } from '../../../src/@types/base'
import { EventRepository } from '../../../src/repositories/event-repository'
import { MAX_IMPORTED_DELETION_TARGETS } from '../../../src/services/event-import-service'
import { createRecordingKnex } from './recording-knex'

describe('EventRepository', () => {
let repository: IEventRepository
Expand Down Expand Up @@ -1110,6 +1111,40 @@ describe('EventRepository', () => {
})
})

describe('hasActiveRequestToVanish', () => {
const pubkey = '22'.repeat(32)

it('reads the primary, not the replica', async () => {
const primary = createRecordingKnex()
const replica = createRecordingKnex()
primary.respondWith([{ event_id: Buffer.alloc(32) }])

const result = await new EventRepository(primary.db, replica.db).hasActiveRequestToVanish(pubkey)

expect(result).to.equal(true)
expect(primary.queries).to.have.length(1)
expect(replica.queries).to.be.empty
})

it('runs one bounded query on the client it is given', async () => {
const primary = createRecordingKnex()
const replica = createRecordingKnex()
const transaction = createRecordingKnex()

const result = await new EventRepository(primary.db, replica.db).hasActiveRequestToVanish(pubkey, transaction.db)

expect(result).to.equal(false)
expect(transaction.queries).to.deep.equal([
{
sql: 'select "event_id" from "events" where "event_pubkey" = $1 and "event_kind" = $2 and "deleted_at" is null limit $3',
bindings: [Buffer.from(pubkey, 'hex'), EventKinds.REQUEST_TO_VANISH, 1],
},
])
expect(primary.queries).to.be.empty
expect(replica.queries).to.be.empty
})
})

describe('deleteExpiredAndRetained', () => {
it('returns zero counts when retention is disabled', async () => {
const result = await repository.deleteExpiredAndRetained({ maxDays: 0 })
Expand Down
Loading
Loading