Skip to content

fix(payments): do not downgrade a pubkey whose dearer plan is still running - #1092

Merged
cameri merged 3 commits into
cameri:mainfrom
Priyanshubhartistm:fix/subscription-third-party-plan-change
Nov 12, 2026
Merged

cameri merged 3 commits into
cameri:mainfrom
Priyanshubhartistm:fix/subscription-third-party-plan-change

Conversation

@Priyanshubhartistm

@Priyanshubhartistm Priyanshubhartistm commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

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)
  • 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:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my code changes.
  • I added a changeset, or this is docs-only and I added an empty changeset.
  • All new and existing tests passed.

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.

…unning

Signed-off-by: Priyanshubhartistm <bhartipriyanshustm@gmail.com>
@changeset-bot

changeset-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 3598b5f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
nostream Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

When a user pays for a cheaper plan while a more expensive plan is active, the payment can extend the existing plan by a duration proportional to the amount paid. Payment confirmation passes the existing plan and paid amount to applyPayment. Other cases retain the prior plan-start behavior.

Changes: Subscription payment handling

Layer / File(s) Summary
Payment context and plan credit
src/utils/subscription.ts, src/services/payments-service.ts, test/unit/utils/subscription.spec.ts, test/unit/services/payments-service.spec.ts
applyPayment accepts optional existing-plan and paid-amount context. Payment confirmation supplies both values. When a cheaper plan is paid for during a running, more expensive plan, the paid amount determines the proportional period credit and the existing plan is retained. Unit tests cover this behavior and cases where plans switch.
Plan-change scenarios and documentation
test/integration/features/subscriptions/subscription-plan-change.feature, test/integration/features/subscriptions/subscription-plan-change.feature.ts, CONFIGURATION.md, .changeset/subscription-third-party-plan-change.md
Integration scenarios cover cheaper and dearer plan payments, duplicate paid callbacks, and subscribers without a subscription. Configuration documentation and the changeset describe the payment behavior.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Merge Risk: Minimal · up to 3598b

No material issue remains identified for this change. Normal checks are appropriate before merging.

Security architecture risk: Low · up to 3598b

The change reduces the ability of a third-party payment to downgrade another subscriber’s running plan. Existing transaction and duplicate-confirmation controls remain in place. Protection still depends on resolving the current plan, and recovery under concurrent failures was not demonstrated end to end.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A requester can select another pubkey as an invoice beneficiary without possessing its private key. The relevant attackable scope is therefore other subscribers on the relay, one targeted beneficiary per invoice. The changed control acts on subscription entitlements rather than granting infrastructure or secret-management authority.

Security Findings and Attack Paths

  • inferred — The base allowed a paid cheaper-plan invoice to replace another pubkey’s running plan. The new branch blocks that transition when the current plan resolves and its price exceeds the purchased plan’s price. This is a bounded mitigation, not a general beneficiary-authorization mechanism; no introduced or worsened attack path was established in the inspected transition.

Trust Boundaries and Controls

  • observed — The inspected OpenNode callback requires a configured API key and a timing-safe HMAC check over the invoice ID. It obtains the beneficiary and requested amount from the stored invoice before confirmation. These controls authenticate the callback path but do not establish that the payer controls the beneficiary pubkey.

Resilience and Maintainability Implications

  • observed — The credit branch preserves renewal-pending status instead of resetting it to active, retaining the existing renewal lifecycle while extending entitlement. The added scenarios exercise plan preservation, proportional extension, admission and repeated callbacks; they do not demonstrate injected serialization failure or post-commit callback recovery.

Hardening Proposals

  • proposed — If entitlement preservation must survive plan removal or repricing, consider persisting paid-period plan terms or requiring beneficiary authorization for entitlement-reducing plan changes. This would strengthen the existing configuration-dependent contract beyond this PR’s bounded mitigation.
Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main behavior change: a payment for a cheaper plan no longer replaces a still-running, more expensive plan. The changeset adds that guard in applyPayment and passes the existing pl…
Linked Issues check Passed [#1017] The issue states the harm. A payment replaces the running plan at once. A cheaper plan can shorten retention, and the purge then deletes events that the previous paid plan protects. The issue …
Out of Scope Changes check Passed Changed files, from the whole-PR diff and summary: src/utils/subscription.ts (applyPayment gains an optional context parameter that defaults to an empty object, and a credit branch), src/services/paym…
Docstring Coverage Passed No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Title check

Explanation

The title names the main behavior change: a payment for a cheaper plan no longer replaces a still-running, more expensive plan. The changeset adds that guard in applyPayment and passes the existing plan and paid amount through confirmInvoice. The fix prefix matches a patch-level bug fix. The title is specific and short, and it matches the changeset objectives in PR #1092.

Full details: Linked Issues check

Explanation

[#1017] The issue states the harm. A payment replaces the running plan at once. A cheaper plan can shorten retention, and the purge then deletes events that the previous paid plan protects. The issue suggests two fixes: (a) require beneficiary authorization before a plan change that reduces benefits, and (b) store a subsequent plan separately and keep the current plan's retention until its paid period ends.

Source at reviewed head 3598b5f, src/utils/subscription.ts, applyPayment: when the subscription is still running, existingPlan.id equals existing.planId, and plan.amount is below existingPlan.amount, the function keeps planId, status, and currentPeriodStart. It extends currentPeriodEnd by intervalSeconds * 1000 * paidMsat / existingPlan.amount and sets graceEndsAt from existingPlan.graceSeconds. Paid retention therefore holds until the paid period ends. This meets the retention intent of part (b) for running periods.

src/services/payments-service.ts, confirmInvoice: passes existingPlan from findSubscriptionPlan(currentSettings, existing?.planId) and paidMsat set to amountPaidMsat. The method already compares amountPaidMsat with plan.amount, so the units match. Dearer plans, the same plan, no running period, and a removed plan keep the prior switch behaviour.

Not implemented: part (a), beneficiary authorization, and the stored subsequent plan. The issue labels its finding unconfirmed and presents these as a suggested fix. The PR states its choice and its reason (no schema change, no auth step in the invoice flow). This is a design choice, not a missed requirement, because the stated harm is removed for running paid periods.

Residual gaps, acknowledged in the PR: a grandfathered pubkey with no paid plan still moves to a paid plan on payment, and a cheaper plan still takes effect after the running period ends. The stated harm names a previous paid plan, so these fall outside it.

The unit and integration tests cited in the PR were not run. This verdict relies on the source diff at the reviewed head.

Full details: Out of Scope Changes check

Explanation

Changed files, from the whole-PR diff and summary: src/utils/subscription.ts (applyPayment gains an optional context parameter that defaults to an empty object, and a credit branch), src/services/payments-service.ts (confirmInvoice passes existingPlan and paidMsat), unit tests in test/unit/services/payments-service.spec.ts and test/unit/utils/subscription.spec.ts, integration feature and step files under test/integration/features/subscriptions/ (cheaper-plan, dearer-plan, duplicate-callback, and no-subscription scenarios), CONFIGURATION.md (documents the cheaper-plan credit rule and the unchanged cases), and a patch changeset.

Each source change supports the fix for #1017. The default context keeps existing callers that omit it on the prior behaviour. The tests, documentation, and changeset describe the same change. The integration files support the same behaviour and answer the reviewer request for an integration test. No unrelated behaviour change is visible in the source diffs.

Full details: Docstring Coverage

Explanation

No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 5 files. (1 skipped: 1 unsupported.)

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

A rabbit checks the plans at dawn
A cheaper payment adds time on
The current plan stays in place
Paid millis guide the period’s pace
Then hops away across the lawn

Recent review info

Automatic approval policy

Commit: 3598b5fe3607.

Setting Effective value Source
Automatic approvals Enabled Global configuration
Merge risk Minimal Global configuration
Security risk Not set Global configuration

Not set means no limit was configured after inheritance. Use @coderabbitai configuration to inspect the resolved settings and their sources.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2e1c33fe-261c-4825-96ff-3c3bfdcb8024
Commits

Reviewing files that changed from the base of the PR and between 6b4fd79 and 3598b5f.

Files selected for processing: 2

  • test/integration/features/subscriptions/subscription-plan-change.feature
  • test/integration/features/subscriptions/subscription-plan-change.feature.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@greptile-apps

greptile-apps Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new actionable issues were found.

Summary

Cheaper-plan payments extend a running dearer plan instead of replacing it.

  • Cheaper payments extend a running dearer plan instead of replacing it.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Confirmed plan payment] --> B{Cheaper than the running plan?}
  B -- Yes --> C[Keep current plan and status]
  C --> D[Extend by the share paid for]
  B -- No --> E[Apply the paid plan as before]
Loading

Reviews (3) · Last reviewed commit: "test(payments): cover paying for another..." · Reviewed by Greptile

Comment thread src/utils/subscription.ts Resolved
@coveralls

coveralls commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 42645801845

Coverage decreased (-0.05%) to 77.63%

Details

  • Coverage decreased (-0.05%) from the base build.
  • Patch coverage: 6 of 6 lines across 1 file are fully covered (100%).
  • 5 coverage regressions across 2 files.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

5 previously-covered lines in 2 files lost coverage.

File Lines Losing Coverage Coverage
src/utils/relay-probe/ws-protocol-probe.ts 4 58.99%
src/adapters/web-socket-adapter.ts 1 93.5%

Coverage Stats

Coverage Status
Relevant Lines: 13158
Covered Lines: 10681
Line Coverage: 81.17%
Relevant Branches: 6918
Covered Branches: 4904
Branch Coverage: 70.89%
Branches in Coverage %: Yes
Coverage Strength: 708.22 hits per line

💛 - Coveralls

…credited

Signed-off-by: Priyanshubhartistm <bhartipriyanshustm@gmail.com>
greptile-apps[bot]
greptile-apps Bot previously approved these changes Nov 9, 2026
coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 9, 2026
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.

@cameri

cameri commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@Priyanshubhartistm could you please add an integration test?

Signed-off-by: Priyanshubhartistm <bhartipriyanshustm@gmail.com>
@cameri
cameri merged commit 7ea4cae into cameri:main Nov 12, 2026
17 of 18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Security: idor in src/services/payments-service.ts

3 participants