Skip to content

Commit 7ea4cae

Browse files
authored
fix(payments): do not downgrade a pubkey whose dearer plan is still running (#1092)
## Description Anyone can pay an invoice for any pubkey (`POST /invoices` takes the pubkey and a plan, and a Lightning payment carries no proof of who paid). `applyPayment` switched the pubkey to the paid plan at once, so someone could buy the cheapest plan for another pubkey and take away the dearer plan the pubkey had paid for: its rate limits and retention would change immediately, and the purge would then delete events its own plan keeps. While a period of a dearer plan is running, a payment for a cheaper plan now leaves the plan alone and credits the money to it: the running period is extended by the share of one of its periods the payment covers (a payment of a fifth of the price adds a fifth of the interval), with the grace of the plan the pubkey has. Nothing the pubkey has paid for is shortened or taken away. Unchanged: paying for the plan the pubkey has, paying for a dearer plan (it takes effect as before), and paying after the running period has ended or when the pubkey has no running paid plan. `confirmInvoice` passes the plan the pubkey has and the amount paid (converted to msats), so the credit follows what was paid. ## Related Issue Closes #1017 ## Motivation and Context #1017 is an automated finding, not a confirmed exploit, but the path it describes is real: the pubkey and plan are public inputs and `confirmInvoice` replaced the plan. I read it as a payment changing a plan the payer has no right to change, and fixed it without a schema change by making a payment unable to lower an existing running plan, rather than requiring the beneficiary to authenticate (the other fix the issue suggests), which would need an auth step in the invoice flow. Known limits, left out on purpose: a pubkey admitted before plans existed (the never-ending `grandfathered` plan) is still moved onto a paid plan by a payment, and someone who really wants a cheaper plan has to wait until the running period ends, instead of having the change queued for then (that would need a stored next plan). ## How Has This Been Tested? - New unit tests for `applyPayment` (the plan is kept; the credit is a share of a period, grows with the amount paid, adds the grace of the plan the pubkey has, never shortens; a pending renewal is kept too; the plan still switches after the period ended, with no running plan, or when the plan was removed from the settings; moving up to a dearer plan and extending the same plan are unchanged) and for `confirmInvoice` (a cheaper plan is not applied and the money is credited, the credit follows the amount paid in sats, moving up still works). - Flipping the comparison, or dropping the amount paid or the plan the pubkey has from the call, each fails tests. - `pnpm lint`, `pnpm check:deps`, `pnpm run build:check`, `pnpm run build`, `pnpm run verify:cli:build`, `pnpm run test:unit` (3006 passing), `pnpm run test:cli` (113 passing). ## Screenshots (if appropriate): ## Types of changes - [ ] Non-functional change (docs, style, minor refactor) - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) ## Checklist: - [x] My code follows the code style of this project. - [x] My change requires a change to the documentation. - [x] I have updated the documentation accordingly. - [x] I have read the **CONTRIBUTING** document. - [x] I have added tests to cover my code changes. - [x] I added a changeset, or this is docs-only and I added an empty changeset. - [x] All new and existing tests passed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Paying for a cheaper plan while a more expensive subscription is active now credits the payment toward extending the current plan instead of switching plans. The extension reflects the amount paid, while the current plan, its limits, status, and grace period remain in effect. * Payments for more expensive plans continue to switch the subscription to the new plan. Payments made when no subscription is active or after its current period ends take effect as before. * **Documentation** * Clarified how payments for cheaper, same-price, or more expensive plans take effect, including payments made after the current subscription period ends. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents d80b3b2 + 3598b5f commit 7ea4cae

8 files changed

Lines changed: 404 additions & 2 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"nostream": patch
3+
---
4+
5+
fix(payments): a payment for a cheaper plan no longer downgrades a pubkey whose dearer plan is still running

‎CONFIGURATION.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta
256256
| payments.feeSchedules.admission[].whitelists.event_kinds | List of event kinds to waive admission fee. Use `[min, max]` for ranges. |
257257
| payments.feeSchedules.admission[].whitelists.pubkeys | List of pubkeys to waive admission fee. |
258258
| payments.processor | Either `zebedee`, `lnbits`, `lnurl`. |
259-
| 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. |
259+
| 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. |
260260
| 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. |
261261
| 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. |
262262
| payments.subscriptionPlans[].intervalSeconds | Length of one paid period, in seconds. |

‎src/services/payments-service.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,10 @@ export class PaymentsService implements IPaymentsService {
219219
const date = new Date()
220220
const existing = await this.userSubscriptionRepository.findByPubkey(invoice.pubkey, transaction.transaction)
221221
await this.userSubscriptionRepository.upsert(
222-
applyPayment(invoice.pubkey, existing, plan, date),
222+
applyPayment(invoice.pubkey, existing, plan, date, {
223+
existingPlan: findSubscriptionPlan(currentSettings, existing?.planId),
224+
paidMsat: amountPaidMsat,
225+
}),
223226
transaction.transaction,
224227
)
225228
await this.userRepository.admitUser(invoice.pubkey, date, transaction.transaction)

‎src/utils/subscription.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,18 @@ export const hasSubscriptionAccess = (subscription: UserSubscription | undefined
5252
* The subscription after a payment for `plan`. A payment made while access is still running
5353
* extends it from the current period end, so paying early costs nothing. After access has
5454
* lapsed, or on the never-ending grandfathered plan, the new period starts now.
55+
*
56+
* Anyone can pay an invoice for any pubkey, so a payment must not take away what the pubkey already has paid for. While
57+
* a period of a dearer plan is running, a payment for a cheaper plan therefore does not switch the plan (its lower limits
58+
* and shorter retention would take effect at once, and the purge would delete events the dearer plan keeps). The money
59+
* is credited to the plan the pubkey has, as the share of one of its periods it pays for.
5560
*/
5661
export const applyPayment = (
5762
pubkey: Pubkey,
5863
existing: UserSubscription | undefined,
5964
plan: SubscriptionPlan,
6065
now: Date,
66+
context: { existingPlan?: SubscriptionPlan; paidMsat?: bigint } = {},
6167
): Omit<UserSubscription, 'createdAt' | 'updatedAt'> => {
6268
const stillRunning =
6369
existing &&
@@ -66,6 +72,32 @@ export const applyPayment = (
6672
(existing.status === SubscriptionStatus.ACTIVE || existing.status === SubscriptionStatus.RENEWAL_PENDING) &&
6773
existing.currentPeriodEnd.getTime() > now.getTime()
6874

75+
const { existingPlan } = context
76+
if (
77+
stillRunning &&
78+
existingPlan &&
79+
existingPlan.id === existing.planId &&
80+
BigInt(plan.amount) < BigInt(existingPlan.amount)
81+
) {
82+
// The share of a period of the plan the pubkey has that the payment covers, in milliseconds.
83+
const paidMsat = context.paidMsat ?? BigInt(plan.amount)
84+
const creditMs = Number((BigInt(existingPlan.intervalSeconds) * 1000n * paidMsat) / BigInt(existingPlan.amount))
85+
const periodEnd = new Date((existing.currentPeriodEnd as Date).getTime() + creditMs)
86+
87+
return {
88+
pubkey,
89+
planId: existing.planId,
90+
// Not paid for the renewal that may be waiting: a pending renewal invoice is still payable, and moving the
91+
// subscription back to active would let the next sweep issue a second one if the credit leaves the end near.
92+
status: existing.status,
93+
currentPeriodStart: existing.currentPeriodStart,
94+
currentPeriodEnd: periodEnd,
95+
graceEndsAt:
96+
existingPlan.graceSeconds > 0 ? new Date(periodEnd.getTime() + existingPlan.graceSeconds * 1000) : null,
97+
cancelAtPeriodEnd: false,
98+
}
99+
}
100+
69101
const periodStart = stillRunning ? (existing.currentPeriodEnd as Date) : now
70102
const periodEnd = new Date(periodStart.getTime() + plan.intervalSeconds * 1000)
71103

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
@opennode-callback @subscription-plan-change
2+
Feature: Paying for another plan while a subscription is running
3+
Anyone can pay an invoice for any pubkey, so a payment for a cheaper plan must not take away
4+
what the pubkey has already paid for. The plan limits "basic" (21000 sats) and "pro" (100000 sats)
5+
are each one period of 30 days.
6+
7+
Scenario: a cheaper plan paid for a running dearer plan is credited to the dearer plan
8+
Given OpenNode callback processing is enabled
9+
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
10+
And a subscriber has a running "pro" plan that ends in 10 days
11+
And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists
12+
When I post a signed OpenNode callback with status "paid"
13+
Then the OpenNode callback response status is 200
14+
And the subscriber is still on the plan "pro"
15+
And the subscriber's plan ends 6.3 days later than before
16+
And the subscriber has been admitted to the relay
17+
18+
Scenario: a repeated callback does not credit the payment twice
19+
Given OpenNode callback processing is enabled
20+
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
21+
And a subscriber has a running "pro" plan that ends in 10 days
22+
And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists
23+
When I post a signed OpenNode callback with status "paid"
24+
And I post a signed OpenNode callback with status "paid"
25+
Then the subscriber is still on the plan "pro"
26+
And the subscriber's plan ends 6.3 days later than before
27+
28+
Scenario: a dearer plan paid for a running cheaper plan switches the plan
29+
Given OpenNode callback processing is enabled
30+
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
31+
And a subscriber has a running "basic" plan that ends in 10 days
32+
And a pending OpenNode invoice for the subscriber for 100000 sats on the plan "pro" exists
33+
When I post a signed OpenNode callback with status "paid"
34+
Then the OpenNode callback response status is 200
35+
And the subscriber is on the plan "pro"
36+
And the subscriber's plan ends 30 days later than before
37+
38+
Scenario: a cheaper plan paid by a pubkey with no subscription starts that plan
39+
Given OpenNode callback processing is enabled
40+
And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats
41+
And a subscriber without a subscription
42+
And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists
43+
When I post a signed OpenNode callback with status "paid"
44+
Then the OpenNode callback response status is 200
45+
And the subscriber is on the plan "basic"
46+
And the subscriber has been admitted to the relay
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import { After, Given, Then } from '@cucumber/cucumber'
2+
import { expect } from 'chai'
3+
import { randomBytes, randomUUID } from 'crypto'
4+
5+
import { getMasterDbClient } from '../../../../src/database/client'
6+
import { SettingsStatic } from '../../../../src/utils/settings'
7+
8+
const DAY_MS = 24 * 60 * 60 * 1000
9+
const PLAN_INTERVAL_SECONDS = 30 * 24 * 60 * 60
10+
11+
const readSubscription = async (pubkey: Buffer) => {
12+
const row = await getMasterDbClient()('user_subscriptions')
13+
.where('pubkey', pubkey)
14+
.first('plan_id', 'status', 'current_period_start', 'current_period_end')
15+
16+
expect(row, 'the subscriber has no subscription').to.exist
17+
18+
return row
19+
}
20+
21+
Given(
22+
'the relay sells the plans {string} at {int} sats and {string} at {int} sats',
23+
function (firstId: string, firstSats: number, secondId: string, secondSats: number) {
24+
const settings = SettingsStatic._settings as any
25+
const plan = (id: string, sats: number) => ({
26+
id,
27+
amount: BigInt(sats) * 1000n,
28+
intervalSeconds: PLAN_INTERVAL_SECONDS,
29+
graceSeconds: DAY_MS / 1000,
30+
})
31+
32+
// The OpenNode callback steps restore the settings they replaced once the scenario ends.
33+
SettingsStatic._settings = {
34+
...settings,
35+
payments: {
36+
...settings.payments,
37+
subscriptionPlans: [plan(firstId, firstSats), plan(secondId, secondSats)],
38+
},
39+
}
40+
},
41+
)
42+
43+
const createSubscriber = async (world: any, subscription?: { planId: string; endsInDays: number }) => {
44+
const dbClient = getMasterDbClient()
45+
const pubkey = randomBytes(32)
46+
47+
await dbClient('users').insert({ pubkey, is_admitted: false })
48+
world.parameters.subscriberPubkey = pubkey
49+
world.parameters.subscriberPubkeys = [...(world.parameters.subscriberPubkeys ?? []), pubkey]
50+
51+
if (!subscription) {
52+
return
53+
}
54+
55+
const now = Date.now()
56+
const periodEnd = new Date(now + subscription.endsInDays * DAY_MS)
57+
await dbClient('user_subscriptions').insert({
58+
pubkey,
59+
plan_id: subscription.planId,
60+
status: 'active',
61+
current_period_start: new Date(now - (30 - subscription.endsInDays) * DAY_MS),
62+
current_period_end: periodEnd,
63+
grace_ends_at: new Date(periodEnd.getTime() + DAY_MS),
64+
})
65+
await dbClient('users').where('pubkey', pubkey).update({ is_admitted: true })
66+
67+
world.parameters.subscriptionEndBefore = (await readSubscription(pubkey)).current_period_end as Date
68+
}
69+
70+
Given(
71+
'a subscriber has a running {string} plan that ends in {int} days',
72+
async function (planId: string, days: number) {
73+
await createSubscriber(this, { planId, endsInDays: days })
74+
},
75+
)
76+
77+
Given('a subscriber without a subscription', async function () {
78+
await createSubscriber(this)
79+
})
80+
81+
Given(
82+
'a pending OpenNode invoice for the subscriber for {int} sats on the plan {string} exists',
83+
async function (sats: number, planId: string) {
84+
const invoiceId = `integration-subscription-${randomUUID()}`
85+
86+
await getMasterDbClient()('invoices').insert({
87+
id: invoiceId,
88+
pubkey: this.parameters.subscriberPubkey,
89+
bolt11: 'lnbc210n1integration',
90+
amount_requested: String(sats),
91+
unit: 'sats',
92+
status: 'pending',
93+
description: 'subscription plan change integration test',
94+
plan_id: planId,
95+
expires_at: new Date(Date.now() + 15 * 60 * 1000),
96+
updated_at: new Date(),
97+
created_at: new Date(),
98+
})
99+
100+
// The OpenNode callback steps post for, and clean up, this invoice.
101+
this.parameters.openNodeInvoiceId = invoiceId
102+
this.parameters.openNodeInvoiceIds = [...(this.parameters.openNodeInvoiceIds ?? []), invoiceId]
103+
},
104+
)
105+
106+
Then('the subscriber is still on the plan {string}', async function (planId: string) {
107+
const subscription = await readSubscription(this.parameters.subscriberPubkey)
108+
109+
expect(subscription.plan_id).to.equal(planId)
110+
// The payment was credited to the running plan, so the subscription is neither restarted nor ended.
111+
expect(subscription.status).to.equal('active')
112+
})
113+
114+
Then('the subscriber is on the plan {string}', async function (planId: string) {
115+
const subscription = await readSubscription(this.parameters.subscriberPubkey)
116+
117+
expect(subscription.plan_id).to.equal(planId)
118+
expect(subscription.status).to.equal('active')
119+
})
120+
121+
Then("the subscriber's plan ends {float} days later than before", async function (days: number) {
122+
const subscription = await readSubscription(this.parameters.subscriberPubkey)
123+
const before = this.parameters.subscriptionEndBefore as Date
124+
125+
expect(subscription.current_period_end.getTime() - before.getTime()).to.equal(Math.round(days * DAY_MS))
126+
})
127+
128+
Then('the subscriber has been admitted to the relay', async function () {
129+
const user = await getMasterDbClient()('users').where('pubkey', this.parameters.subscriberPubkey).first('is_admitted')
130+
131+
expect(user.is_admitted).to.equal(true)
132+
})
133+
134+
After({ tags: '@subscription-plan-change' }, async function () {
135+
const pubkeys = this.parameters.subscriberPubkeys ?? []
136+
if (pubkeys.length > 0) {
137+
// The subscription goes with the user, whose row it references.
138+
await getMasterDbClient()('users').whereIn('pubkey', pubkeys).delete()
139+
}
140+
141+
this.parameters.subscriberPubkey = undefined
142+
this.parameters.subscriberPubkeys = []
143+
this.parameters.subscriptionEndBefore = undefined
144+
})

‎test/unit/services/payments-service.spec.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,68 @@ describe('PaymentsService', () => {
567567
expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 30 * DAY))
568568
})
569569

570+
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 () => {
571+
const premium = { id: 'premium', amount: 25_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 }
572+
settings.returns(plansSettings([plan, premium]))
573+
const periodEnd = new Date(Date.now() + 5 * DAY)
574+
userSubscriptionRepository.findByPubkey.resolves({
575+
pubkey: 'pubkey1234',
576+
planId: 'premium',
577+
status: 'active',
578+
currentPeriodStart: new Date(Date.now() - 25 * DAY),
579+
currentPeriodEnd: periodEnd,
580+
graceEndsAt: null,
581+
cancelAtPeriodEnd: false,
582+
})
583+
584+
await service.confirmInvoice(makeCompletedInvoice({ amountPaid: 5_000_000n }))
585+
586+
const [subscription] = userSubscriptionRepository.upsert.firstCall.args
587+
expect(subscription.planId).to.equal('premium')
588+
// the cheaper plan costs a fifth of premium, so it buys a fifth of a premium period: six days
589+
expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 6 * DAY))
590+
expect(userSubscriptionRepository.upsert).to.have.been.calledOnce
591+
})
592+
593+
it('credits what was actually paid, converted to msats, not the price of the plan', async () => {
594+
const premium = { id: 'premium', amount: 25_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 }
595+
settings.returns(plansSettings([plan, premium]))
596+
const periodEnd = new Date(Date.now() + 5 * DAY)
597+
userSubscriptionRepository.findByPubkey.resolves({
598+
pubkey: 'pubkey1234',
599+
planId: 'premium',
600+
status: 'active',
601+
currentPeriodStart: new Date(Date.now() - 25 * DAY),
602+
currentPeriodEnd: periodEnd,
603+
graceEndsAt: null,
604+
cancelAtPeriodEnd: false,
605+
})
606+
607+
// 10,000 sats = 10,000,000 msats, twice the price of the cheaper plan
608+
await service.confirmInvoice(makeCompletedInvoice({ unit: InvoiceUnit.SATS, amountPaid: 10_000n }))
609+
610+
const [subscription] = userSubscriptionRepository.upsert.firstCall.args
611+
expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 12 * DAY))
612+
})
613+
614+
it('moves a pubkey up to a dearer plan that somebody paid for it', async () => {
615+
const lite = { id: 'lite', amount: 1_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 }
616+
settings.returns(plansSettings([lite, plan]))
617+
userSubscriptionRepository.findByPubkey.resolves({
618+
pubkey: 'pubkey1234',
619+
planId: 'lite',
620+
status: 'active',
621+
currentPeriodStart: new Date(Date.now() - 25 * DAY),
622+
currentPeriodEnd: new Date(Date.now() + 5 * DAY),
623+
graceEndsAt: null,
624+
cancelAtPeriodEnd: false,
625+
})
626+
627+
await service.confirmInvoice(makeCompletedInvoice({ amountPaid: 5_000_000n }))
628+
629+
expect(userSubscriptionRepository.upsert.firstCall.args[0].planId).to.equal('basic')
630+
})
631+
570632
it('does not extend the subscription again for a repeated callback of an invoice that was already confirmed', async () => {
571633
invoiceRepository.findById.resolves(stubInvoice({ planId: 'basic', confirmedAt: new Date() }))
572634

0 commit comments

Comments
 (0)