Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(billing): cancel rejected deferred authorizations

Timothy Yinf9f0da388889
diff --git a/packages/platform/src/deferred-payments.ts b/packages/platform/src/deferred-payments.ts
index 095139af..2a0d7562 100644
--- a/packages/platform/src/deferred-payments.ts
+++ b/packages/platform/src/deferred-payments.ts
@@ -24,10 +24,31 @@ export async function reconcileDeferredAuthorization(
if (known && known.customer_id !== subscription.customer.customer_id)
fail('payment_customer_mismatch')
const snapshot = JSON.parse(checkout.handover_json)
+ // The caller has verified provider metadata and product ownership. Do not leave
+ // a new, rejected trial running without a local reservation to manage it.
+ async function rejectNewAuthorization(code: string): Promise<never> {
+ if (!known && subscription.status === 'active') {
+ await dodoRequest(() =>
+ client.subscriptions.update(
+ subscription.subscription_id,
+ { status: 'cancelled' },
+ {
+ headers: { 'Idempotency-Key': `cf-cancel-handover-${checkout.id}` },
+ },
+ ),
+ )
+ const actual = (await dodoRequest(() =>
+ client.subscriptions.retrieve(subscription.subscription_id),
+ )) as any
+ if (actual.status !== 'cancelled') fail('payment_confirmation_pending')
+ }
+ return fail(code)
+ }
if (subscription.trial_period_days !== snapshot.trialDays)
fail('payment_subscription_mismatch')
if (!known) {
- if (!checkout.provider_id) fail('payment_checkout_mismatch')
+ if (!checkout.provider_id)
+ await rejectNewAuthorization('payment_checkout_mismatch')
const session = (await dodoRequest(() =>
client.checkoutSessions.retrieve(checkout.provider_id.split(':').pop()),
)) as any
@@ -36,7 +57,7 @@ export async function reconcileDeferredAuthorization(
(session.customer_email &&
session.customer_email.toLowerCase() !== snapshot.email.toLowerCase())
)
- fail('payment_checkout_mismatch')
+ await rejectNewAuthorization('payment_checkout_mismatch')
paymentId ??= session.payment_id ?? undefined
}
let payment = paymentId
@@ -108,7 +129,7 @@ export async function reconcileDeferredAuthorization(
(at > checkout.created_at + (snapshot.trialDays + 1) * DAY ||
time(subscription.previous_billing_date) > checkout.created_at + DAY))
)
- fail('payment_handover_date_invalid')
+ await rejectNewAuthorization('payment_handover_date_invalid')
const prior = await db
.prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=?')
.bind(checkout.workspace_id)
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index c6921945..22f8c666 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -2577,3 +2577,108 @@ test('an authorization without a payment ID converges and blocks redemption unti
await f.mf.dispose()
}
})
+
+for (const invalid of ['checkout', 'date'])
+ test(`new deferred authorization with invalid ${invalid} is canceled before rejection without granting rights`, async () => {
+ const f = await handoverFixture()
+ try {
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...input('invalid_handover'), startMode: 'after_entitlement' },
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { sub, payment, session } = await f.paid(checkout)
+ sub.trial_period_days = session.trial_period_days
+ sub.previous_billing_date = new Date(f.now).toISOString()
+ sub.next_billing_date = new Date(f.now + 4 * 86400000).toISOString()
+ payment.total_amount = 0
+ payment.service_periods = []
+ if (invalid === 'checkout')
+ session.customer_email = '[email protected]'
+ else sub.next_billing_date = new Date(f.originalEnd - 1000).toISOString()
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ ),
+ {
+ code:
+ invalid === 'checkout'
+ ? 'payment_checkout_mismatch'
+ : 'payment_handover_date_invalid',
+ },
+ )
+ assert.equal(sub.status, 'cancelled')
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT COUNT(*) AS count FROM platform_payment_subscriptions',
+ )
+ .first<any>()
+ ).count,
+ 0,
+ )
+ const grant = await f.db
+ .prepare(
+ 'SELECT source,expires_at FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ assert.equal(grant.source, 'activation')
+ assert.equal(grant.expires_at, f.originalEnd)
+ } finally {
+ await f.mf.dispose()
+ }
+ })
+
+test('missing checkout linkage requires verified cancellation before rejecting a new authorization', async () => {
+ const { reconcileDeferredAuthorization } =
+ await import('../packages/platform/src/deferred-payments.ts')
+ for (const confirmed of [false, true]) {
+ let canceled = false
+ const client = {
+ subscriptions: {
+ update: async () => {
+ canceled = true
+ },
+ retrieve: async () => ({ status: confirmed ? 'cancelled' : 'active' }),
+ },
+ }
+ await assert.rejects(
+ reconcileDeferredAuthorization(
+ null as any,
+ client,
+ {
+ id: 'checkout_missing_link',
+ handover_json: JSON.stringify({ trialDays: 4 }),
+ },
+ {
+ subscription_id: 'sub_missing_link',
+ status: 'active',
+ trial_period_days: 4,
+ },
+ null,
+ undefined,
+ Date.now(),
+ '1=1',
+ [],
+ 'local_sub',
+ ),
+ {
+ code: confirmed
+ ? 'payment_checkout_mismatch'
+ : 'payment_confirmation_pending',
+ },
+ )
+ assert.equal(canceled, true)
+ }
+})