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
5 changes: 5 additions & 0 deletions .changeset/subscription-third-party-plan-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"nostream": patch
---

fix(payments): a payment for a cheaper plan no longer downgrades a pubkey whose dearer plan is still running
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| payments.feeSchedules.admission[].whitelists.event_kinds | List of event kinds to waive admission fee. Use `[min, max]` for ranges. |
| payments.feeSchedules.admission[].whitelists.pubkeys | List of pubkeys to waive admission fee. |
| payments.processor | Either `zebedee`, `lnbits`, `lnurl`. |
| payments.subscriptionPlans | Recurring membership plans. Leave empty to keep the one-time admission fee. With plans and `payments.enabled`, `POST /invoices` takes a `planId` instead of a fee schedule, a payment of at least the plan price starts or extends a period (from the period end while access is still running, otherwise from now), and writes need an active subscription or grace period. Admitted users with no subscription keep access. About three days before a period ends the relay creates a renewal invoice and sends it to the subscriber in a kind 402 event, replacing it if it expires unpaid; it moves the subscription through grace to expired once the period and grace pass without payment. Users still have to pay renewal invoices themselves, since Lightning cannot be charged automatically. The invoice page lets users pick a plan. Clients see the plans in the NIP-11 document under `fees.subscription` (`id`, `amount` in msats, `unit`, `period` in seconds, and `description` when set), and with plans `limitation.restricted_writes` is true. `GET /subscriptions/status?pubkey=<hex or npub>` returns a pubkey's `planId`, `status`, `active`, `currentPeriodEnd` and `accessEndsAt` (without a subscription `active` is false and the other fields are null), counted against `limits.invoice.rateLimits`; it answers 404 while plans are off. |
| payments.subscriptionPlans | Recurring membership plans. Leave empty to keep the one-time admission fee. With plans and `payments.enabled`, `POST /invoices` takes a `planId` instead of a fee schedule, a payment of at least the plan price starts or extends a period (from the period end while access is still running, otherwise from now), and writes need an active subscription or grace period. Admitted users with no subscription keep access. About three days before a period ends the relay creates a renewal invoice and sends it to the subscriber in a kind 402 event, replacing it if it expires unpaid; it moves the subscription through grace to expired once the period and grace pass without payment. Users still have to pay renewal invoices themselves, since Lightning cannot be charged automatically. The invoice page lets users pick a plan. Anyone can pay an invoice for any pubkey, so while a period of a dearer plan is running, a payment for a cheaper plan for that pubkey does not switch its plan: the money is credited to the plan it has, as the share of one of its periods it pays for. Paying for the same or a dearer plan, or after the running period has ended, takes effect as before. Clients see the plans in the NIP-11 document under `fees.subscription` (`id`, `amount` in msats, `unit`, `period` in seconds, and `description` when set), and with plans `limitation.restricted_writes` is true. `GET /subscriptions/status?pubkey=<hex or npub>` returns a pubkey's `planId`, `status`, `active`, `currentPeriodEnd` and `accessEndsAt` (without a subscription `active` is false and the other fields are null), counted against `limits.invoice.rateLimits`; it answers 404 while plans are off. |
| payments.subscriptionPlans[].id | Unique plan name, for example `basic`. `grandfathered` is reserved: users admitted before plans existed are moved onto it and keep access without a paid period. |
| payments.subscriptionPlans[].amount | Price of one period in msats. Must be unique across plans. A payment below it does not start or extend a period. |
| payments.subscriptionPlans[].intervalSeconds | Length of one paid period, in seconds. |
Expand Down
5 changes: 4 additions & 1 deletion src/services/payments-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ export class PaymentsService implements IPaymentsService {
const date = new Date()
const existing = await this.userSubscriptionRepository.findByPubkey(invoice.pubkey, transaction.transaction)
await this.userSubscriptionRepository.upsert(
applyPayment(invoice.pubkey, existing, plan, date),
applyPayment(invoice.pubkey, existing, plan, date, {
existingPlan: findSubscriptionPlan(currentSettings, existing?.planId),

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@greptile Is findSubscriptionPlan within the same transaction?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not as a database operation. confirmInvoice has already begun the transaction, and existing is fetched with that transaction; then findSubscriptionPlan(currentSettings, existing?.planId) synchronously looks up the plan in the in-memory settings snapshot captured earlier in the method. The subsequent subscription upsert uses the same transaction.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

paidMsat: amountPaidMsat,
}),
transaction.transaction,
)
await this.userRepository.admitUser(invoice.pubkey, date, transaction.transaction)
Expand Down
32 changes: 32 additions & 0 deletions src/utils/subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,18 @@ export const hasSubscriptionAccess = (subscription: UserSubscription | undefined
* The subscription after a payment for `plan`. A payment made while access is still running
* extends it from the current period end, so paying early costs nothing. After access has
* lapsed, or on the never-ending grandfathered plan, the new period starts now.
*
* Anyone can pay an invoice for any pubkey, so a payment must not take away what the pubkey already has paid for. While
* a period of a dearer plan is running, a payment for a cheaper plan therefore does not switch the plan (its lower limits
* and shorter retention would take effect at once, and the purge would delete events the dearer plan keeps). The money
* is credited to the plan the pubkey has, as the share of one of its periods it pays for.
*/
export const applyPayment = (
pubkey: Pubkey,
existing: UserSubscription | undefined,
plan: SubscriptionPlan,
now: Date,
context: { existingPlan?: SubscriptionPlan; paidMsat?: bigint } = {},
): Omit<UserSubscription, 'createdAt' | 'updatedAt'> => {
const stillRunning =
existing &&
Expand All @@ -66,6 +72,32 @@ export const applyPayment = (
(existing.status === SubscriptionStatus.ACTIVE || existing.status === SubscriptionStatus.RENEWAL_PENDING) &&
existing.currentPeriodEnd.getTime() > now.getTime()

const { existingPlan } = context
if (
stillRunning &&
existingPlan &&
existingPlan.id === existing.planId &&
BigInt(plan.amount) < BigInt(existingPlan.amount)
) {
// The share of a period of the plan the pubkey has that the payment covers, in milliseconds.
const paidMsat = context.paidMsat ?? BigInt(plan.amount)
const creditMs = Number((BigInt(existingPlan.intervalSeconds) * 1000n * paidMsat) / BigInt(existingPlan.amount))
const periodEnd = new Date((existing.currentPeriodEnd as Date).getTime() + creditMs)

return {
pubkey,
planId: existing.planId,
// Not paid for the renewal that may be waiting: a pending renewal invoice is still payable, and moving the
// subscription back to active would let the next sweep issue a second one if the credit leaves the end near.
status: existing.status,
currentPeriodStart: existing.currentPeriodStart,
currentPeriodEnd: periodEnd,
graceEndsAt:
existingPlan.graceSeconds > 0 ? new Date(periodEnd.getTime() + existingPlan.graceSeconds * 1000) : null,
cancelAtPeriodEnd: false,
}
}

const periodStart = stillRunning ? (existing.currentPeriodEnd as Date) : now
const periodEnd = new Date(periodStart.getTime() + plan.intervalSeconds * 1000)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
@opennode-callback @subscription-plan-change
Feature: Paying for another plan while a subscription is running
Anyone can pay an invoice for any pubkey, so a payment for a cheaper plan must not take away
what the pubkey has already paid for. The plan limits "basic" (21000 sats) and "pro" (100000 sats)
are each one period of 30 days.

Scenario: a cheaper plan paid for a running dearer plan is credited to the dearer plan
Given OpenNode callback processing is enabled
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
And a subscriber has a running "pro" plan that ends in 10 days
And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists
When I post a signed OpenNode callback with status "paid"
Then the OpenNode callback response status is 200
And the subscriber is still on the plan "pro"
And the subscriber's plan ends 6.3 days later than before
And the subscriber has been admitted to the relay

Scenario: a repeated callback does not credit the payment twice
Given OpenNode callback processing is enabled
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
And a subscriber has a running "pro" plan that ends in 10 days
And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists
When I post a signed OpenNode callback with status "paid"
And I post a signed OpenNode callback with status "paid"
Then the subscriber is still on the plan "pro"
And the subscriber's plan ends 6.3 days later than before

Scenario: a dearer plan paid for a running cheaper plan switches the plan
Given OpenNode callback processing is enabled
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
And a subscriber has a running "basic" plan that ends in 10 days
And a pending OpenNode invoice for the subscriber for 100000 sats on the plan "pro" exists
When I post a signed OpenNode callback with status "paid"
Then the OpenNode callback response status is 200
And the subscriber is on the plan "pro"
And the subscriber's plan ends 30 days later than before

Scenario: a cheaper plan paid by a pubkey with no subscription starts that plan
Given OpenNode callback processing is enabled
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
And a subscriber without a subscription
And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists
When I post a signed OpenNode callback with status "paid"
Then the OpenNode callback response status is 200
And the subscriber is on the plan "basic"
And the subscriber has been admitted to the relay
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { After, Given, Then } from '@cucumber/cucumber'
import { expect } from 'chai'
import { randomBytes, randomUUID } from 'crypto'

import { getMasterDbClient } from '../../../../src/database/client'
import { SettingsStatic } from '../../../../src/utils/settings'

const DAY_MS = 24 * 60 * 60 * 1000
const PLAN_INTERVAL_SECONDS = 30 * 24 * 60 * 60

const readSubscription = async (pubkey: Buffer) => {
const row = await getMasterDbClient()('user_subscriptions')
.where('pubkey', pubkey)
.first('plan_id', 'status', 'current_period_start', 'current_period_end')

expect(row, 'the subscriber has no subscription').to.exist

return row
}

Given(
'the relay sells the plans {string} at {int} sats and {string} at {int} sats',
function (firstId: string, firstSats: number, secondId: string, secondSats: number) {
const settings = SettingsStatic._settings as any
const plan = (id: string, sats: number) => ({
id,
amount: BigInt(sats) * 1000n,
intervalSeconds: PLAN_INTERVAL_SECONDS,
graceSeconds: DAY_MS / 1000,
})

// The OpenNode callback steps restore the settings they replaced once the scenario ends.
SettingsStatic._settings = {
...settings,
payments: {
...settings.payments,
subscriptionPlans: [plan(firstId, firstSats), plan(secondId, secondSats)],
},
}
},
)

const createSubscriber = async (world: any, subscription?: { planId: string; endsInDays: number }) => {
const dbClient = getMasterDbClient()
const pubkey = randomBytes(32)

await dbClient('users').insert({ pubkey, is_admitted: false })
world.parameters.subscriberPubkey = pubkey
world.parameters.subscriberPubkeys = [...(world.parameters.subscriberPubkeys ?? []), pubkey]

if (!subscription) {
return
}

const now = Date.now()
const periodEnd = new Date(now + subscription.endsInDays * DAY_MS)
await dbClient('user_subscriptions').insert({
pubkey,
plan_id: subscription.planId,
status: 'active',
current_period_start: new Date(now - (30 - subscription.endsInDays) * DAY_MS),
current_period_end: periodEnd,
grace_ends_at: new Date(periodEnd.getTime() + DAY_MS),
})
await dbClient('users').where('pubkey', pubkey).update({ is_admitted: true })

world.parameters.subscriptionEndBefore = (await readSubscription(pubkey)).current_period_end as Date
}

Given(
'a subscriber has a running {string} plan that ends in {int} days',
async function (planId: string, days: number) {
await createSubscriber(this, { planId, endsInDays: days })
},
)

Given('a subscriber without a subscription', async function () {
await createSubscriber(this)
})

Given(
'a pending OpenNode invoice for the subscriber for {int} sats on the plan {string} exists',
async function (sats: number, planId: string) {
const invoiceId = `integration-subscription-${randomUUID()}`

await getMasterDbClient()('invoices').insert({
id: invoiceId,
pubkey: this.parameters.subscriberPubkey,
bolt11: 'lnbc210n1integration',
amount_requested: String(sats),
unit: 'sats',
status: 'pending',
description: 'subscription plan change integration test',
plan_id: planId,
expires_at: new Date(Date.now() + 15 * 60 * 1000),
updated_at: new Date(),
created_at: new Date(),
})

// The OpenNode callback steps post for, and clean up, this invoice.
this.parameters.openNodeInvoiceId = invoiceId
this.parameters.openNodeInvoiceIds = [...(this.parameters.openNodeInvoiceIds ?? []), invoiceId]
},
)

Then('the subscriber is still on the plan {string}', async function (planId: string) {
const subscription = await readSubscription(this.parameters.subscriberPubkey)

expect(subscription.plan_id).to.equal(planId)
// The payment was credited to the running plan, so the subscription is neither restarted nor ended.
expect(subscription.status).to.equal('active')
})

Then('the subscriber is on the plan {string}', async function (planId: string) {
const subscription = await readSubscription(this.parameters.subscriberPubkey)

expect(subscription.plan_id).to.equal(planId)
expect(subscription.status).to.equal('active')
})

Then("the subscriber's plan ends {float} days later than before", async function (days: number) {
const subscription = await readSubscription(this.parameters.subscriberPubkey)
const before = this.parameters.subscriptionEndBefore as Date

expect(subscription.current_period_end.getTime() - before.getTime()).to.equal(Math.round(days * DAY_MS))
})

Then('the subscriber has been admitted to the relay', async function () {
const user = await getMasterDbClient()('users').where('pubkey', this.parameters.subscriberPubkey).first('is_admitted')

expect(user.is_admitted).to.equal(true)
})

After({ tags: '@subscription-plan-change' }, async function () {
const pubkeys = this.parameters.subscriberPubkeys ?? []
if (pubkeys.length > 0) {
// The subscription goes with the user, whose row it references.
await getMasterDbClient()('users').whereIn('pubkey', pubkeys).delete()
}

this.parameters.subscriberPubkey = undefined
this.parameters.subscriberPubkeys = []
this.parameters.subscriptionEndBefore = undefined
})
62 changes: 62 additions & 0 deletions test/unit/services/payments-service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,68 @@ describe('PaymentsService', () => {
expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 30 * DAY))
})

it('does not switch a pubkey from a dearer plan to a cheaper one that somebody paid for it, and credits the money to the plan it has', async () => {
const premium = { id: 'premium', amount: 25_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 }
settings.returns(plansSettings([plan, premium]))
const periodEnd = new Date(Date.now() + 5 * DAY)
userSubscriptionRepository.findByPubkey.resolves({
pubkey: 'pubkey1234',
planId: 'premium',
status: 'active',
currentPeriodStart: new Date(Date.now() - 25 * DAY),
currentPeriodEnd: periodEnd,
graceEndsAt: null,
cancelAtPeriodEnd: false,
})

await service.confirmInvoice(makeCompletedInvoice({ amountPaid: 5_000_000n }))

const [subscription] = userSubscriptionRepository.upsert.firstCall.args
expect(subscription.planId).to.equal('premium')
// the cheaper plan costs a fifth of premium, so it buys a fifth of a premium period: six days
expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 6 * DAY))
expect(userSubscriptionRepository.upsert).to.have.been.calledOnce
})

it('credits what was actually paid, converted to msats, not the price of the plan', async () => {
const premium = { id: 'premium', amount: 25_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 }
settings.returns(plansSettings([plan, premium]))
const periodEnd = new Date(Date.now() + 5 * DAY)
userSubscriptionRepository.findByPubkey.resolves({
pubkey: 'pubkey1234',
planId: 'premium',
status: 'active',
currentPeriodStart: new Date(Date.now() - 25 * DAY),
currentPeriodEnd: periodEnd,
graceEndsAt: null,
cancelAtPeriodEnd: false,
})

// 10,000 sats = 10,000,000 msats, twice the price of the cheaper plan
await service.confirmInvoice(makeCompletedInvoice({ unit: InvoiceUnit.SATS, amountPaid: 10_000n }))

const [subscription] = userSubscriptionRepository.upsert.firstCall.args
expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 12 * DAY))
})

it('moves a pubkey up to a dearer plan that somebody paid for it', async () => {
const lite = { id: 'lite', amount: 1_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 }
settings.returns(plansSettings([lite, plan]))
userSubscriptionRepository.findByPubkey.resolves({
pubkey: 'pubkey1234',
planId: 'lite',
status: 'active',
currentPeriodStart: new Date(Date.now() - 25 * DAY),
currentPeriodEnd: new Date(Date.now() + 5 * DAY),
graceEndsAt: null,
cancelAtPeriodEnd: false,
})

await service.confirmInvoice(makeCompletedInvoice({ amountPaid: 5_000_000n }))

expect(userSubscriptionRepository.upsert.firstCall.args[0].planId).to.equal('basic')
})

it('does not extend the subscription again for a repeated callback of an invoice that was already confirmed', async () => {
invoiceRepository.findById.resolves(stubInvoice({ planId: 'basic', confirmedAt: new Date() }))

Expand Down
Loading
Loading