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(dodo): support legacy discounts and expose safe sync diagnostics

Timothy Yin24d6d22dec48
diff --git a/packages/platform/src/dodo-client.ts b/packages/platform/src/dodo-client.ts
index 5b9a0b6e..eb675d46 100644
--- a/packages/platform/src/dodo-client.ts
+++ b/packages/platform/src/dodo-client.ts
@@ -76,7 +76,68 @@ export async function dodoClient(
}),
}
}
-/** Provider bodies and SDK errors can contain credentials or customer data. */
+const productFields = new Set([
+ 'name',
+ 'description',
+ 'tax_category',
+ 'price',
+ 'price.currency',
+ 'price.price',
+ 'price.discount',
+ 'price.discount_bps',
+ 'price.payment_frequency_count',
+ 'price.payment_frequency_interval',
+ 'price.subscription_period_count',
+ 'price.subscription_period_interval',
+ 'price.tax_inclusive',
+ 'price.trial_period_days',
+ 'metadata',
+])
+function validationField(body: unknown): string | undefined {
+ if (!body || typeof body !== 'object') return
+ const value = body as Record<string, unknown>
+ const entries = Array.isArray(value.detail)
+ ? value.detail
+ : Array.isArray(value.errors)
+ ? value.errors
+ : [value]
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue
+ const field = entry as Record<string, unknown>
+ const path = Array.isArray(field.loc)
+ ? field.loc
+ .filter((part) => typeof part === 'string' && part !== 'body')
+ .join('.')
+ : (field.field ?? field.param ?? field.path)
+ if (typeof path === 'string' && productFields.has(path)) return path
+ }
+ // Retain only a known schema field from older API validation messages, never the message or values.
+ const missing =
+ typeof value.message === 'string'
+ ? /missing field [`'"]([a-z_]+)[`'"]/.exec(value.message)?.[1]
+ : undefined
+ if (missing && productFields.has('price.' + missing))
+ return 'price.' + missing
+}
+export class DodoProviderError extends SubscriptionError {
+ providerStatus?: number
+ providerField?: string
+ constructor(code: string, providerStatus?: number, providerField?: string) {
+ super(502, code)
+ this.providerStatus = providerStatus
+ this.providerField = providerField
+ }
+ diagnostic() {
+ return [
+ this.code,
+ this.providerStatus ? 'http_' + this.providerStatus : null,
+ this.providerField,
+ ]
+ .filter(Boolean)
+ .join(':')
+ }
+}
+/** Persist only typed HTTP status and allowlisted field names, never SDK bodies, headers or messages. */
export async function dodoRequest<T>(
operation: () => PromiseLike<T>,
): Promise<T> {
@@ -84,6 +145,34 @@ export async function dodoRequest<T>(
return await operation()
} catch (error) {
if (error instanceof SubscriptionError) throw error
- throw new SubscriptionError(502, 'payment_provider_request_failed')
+ if (error instanceof DodoPayments.APIConnectionTimeoutError)
+ throw new DodoProviderError('payment_provider_timeout')
+ if (error instanceof DodoPayments.APIError && error.status) {
+ const status = error.status
+ const code =
+ status === 401
+ ? 'payment_provider_authentication_failed'
+ : status === 403
+ ? 'payment_provider_permission_denied'
+ : status === 400 || status === 422
+ ? 'payment_provider_validation_failed'
+ : status === 429
+ ? 'payment_provider_rate_limited'
+ : status >= 500
+ ? 'payment_provider_unavailable'
+ : 'payment_provider_request_failed'
+ throw new DodoProviderError(
+ code,
+ status,
+ status === 400 || status === 422
+ ? validationField(error.error)
+ : undefined,
+ )
+ }
+ throw new DodoProviderError(
+ error instanceof DodoPayments.APIConnectionError
+ ? 'payment_provider_connection_failed'
+ : 'payment_provider_request_failed',
+ )
}
}
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 74cfb90a..440f6dfd 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -10,6 +10,7 @@ import {
import { paymentMember, paymentSettings } from './payments.ts'
import {
dodoClient,
+ DodoProviderError,
dodoRequest,
dodoId,
rawDodoId,
@@ -45,6 +46,7 @@ export async function syncDodoProducts(
transport: typeof fetch = fetch,
now = Date.now(),
limit = 2,
+ force = false,
) {
const settings = await paymentSettings(db)
if (!settings.enabled || !settings.providerAvailable || !settings.configured)
@@ -66,16 +68,17 @@ export async function syncDodoProducts(
)
.bind(key, syncToken, now + 240000, now)
.first<any>()
- if (syncLock?.token !== syncToken) return { processed: 0 }
+ if (syncLock?.token !== syncToken) return { processed: 0, busy: true }
try {
const plans = await allRows<any>(
db
.prepare(
- 'SELECT p.*,i.period,COALESCE(f.attempts,0) AS sync_attempts FROM platform_plans p CROSS JOIN (SELECT 1 AS period UNION ALL SELECT 3) i LEFT JOIN platform_dodo_products d ON d.provider_key=? AND d.plan_id=p.id AND d.interval=i.period LEFT JOIN platform_dodo_sync_failures f ON f.provider_key=? AND f.plan_id=p.id AND f.interval=i.period AND f.plan_revision=p.revision AND f.credential_revision=? WHERE (f.next_attempt_at IS NULL OR f.next_attempt_at<=?) AND p.active=1 AND p.listed=1 AND CASE WHEN i.period=1 THEN p.monthly_price ELSE p.quarterly_price END>0 AND (d.product_id IS NULL OR d.plan_revision<>p.revision OR d.credential_revision<>?) ORDER BY p.sort_order,p.id,i.period LIMIT ?',
+ 'SELECT p.*,i.period,COALESCE(f.attempts,0) AS sync_attempts FROM platform_plans p CROSS JOIN (SELECT 1 AS period UNION ALL SELECT 3) i LEFT JOIN platform_dodo_products d ON d.provider_key=? AND d.plan_id=p.id AND d.interval=i.period LEFT JOIN platform_dodo_sync_failures f ON f.provider_key=? AND f.plan_id=p.id AND f.interval=i.period AND f.plan_revision=p.revision AND f.credential_revision=? WHERE (?=1 OR f.next_attempt_at IS NULL OR f.next_attempt_at<=?) AND p.active=1 AND p.listed=1 AND CASE WHEN i.period=1 THEN p.monthly_price ELSE p.quarterly_price END>0 AND (d.product_id IS NULL OR d.plan_revision<>p.revision OR d.credential_revision<>?) ORDER BY p.sort_order,p.id,i.period LIMIT ?',
)
- .bind(key, key, revision, now, revision, limit),
+ .bind(key, key, revision, force ? 1 : 0, now, revision, limit),
)
- let processed = 0
+ let processed = 0,
+ failed = 0
for (const plan of plans) {
try {
const price = Number(
@@ -103,6 +106,8 @@ export async function syncDodoProducts(
subscription_period_interval: 'Year' as const,
tax_inclusive: true,
trial_period_days: 0,
+ // Older Dodo API deployments still require the integer-percent field. New APIs prefer discount_bps.
+ discount: Math.floor(discountBps / 100),
discount_bps: discountBps,
purchasing_power_parity: false,
},
@@ -123,6 +128,20 @@ export async function syncDodoProducts(
)
if (!identifier(product.product_id))
fail('payment_product_invalid', 502)
+ const returnedPrice = product.price
+ if (
+ returnedPrice?.type !== 'recurring_price' ||
+ returnedPrice.price !== price ||
+ returnedPrice.currency !== plan.currency ||
+ returnedPrice.payment_frequency_count !== plan.period ||
+ returnedPrice.payment_frequency_interval !== 'Month'
+ )
+ fail('payment_product_mismatch', 502)
+ if (
+ (returnedPrice.discount_bps ??
+ (returnedPrice.discount ?? 0) * 100) !== discountBps
+ )
+ fail('payment_discount_precision_unsupported', 422)
const published = await db
.prepare(
`INSERT INTO platform_dodo_products(provider_key,plan_id,interval,product_id,price,currency,discount_bps,effective_price,plan_revision,credential_revision,updated_at) SELECT ?,?,?,?,?,?,?,?,?,?,? WHERE ${activeFence} AND EXISTS(SELECT 1 FROM platform_dodo_sync_locks WHERE provider_key=? AND token=? AND expires_at>?) AND EXISTS(SELECT 1 FROM platform_plans WHERE id=? AND revision=?) ON CONFLICT(provider_key,plan_id,interval) DO UPDATE SET product_id=excluded.product_id,price=excluded.price,currency=excluded.currency,discount_bps=excluded.discount_bps,effective_price=excluded.effective_price,plan_revision=excluded.plan_revision,credential_revision=excluded.credential_revision,updated_at=excluded.updated_at`,
@@ -158,15 +177,20 @@ export async function syncDodoProducts(
processed++
}
} catch (error) {
+ failed++
const code =
- error instanceof SubscriptionError &&
- [
- 'payment_price_invalid',
- 'payment_product_invalid',
- 'payment_provider_request_failed',
- ].includes(error.code)
- ? error.code
- : 'payment_product_sync_failed'
+ error instanceof DodoProviderError
+ ? error.diagnostic()
+ : error instanceof SubscriptionError &&
+ [
+ 'payment_price_invalid',
+ 'payment_product_invalid',
+ 'payment_product_mismatch',
+ 'payment_discount_precision_unsupported',
+ 'payment_provider_request_failed',
+ ].includes(error.code)
+ ? error.code
+ : 'payment_product_sync_failed'
const attempts = Number(plan.sync_attempts) + 1
const nextAttempt =
now + Math.min(3600000, 30000 * 2 ** Math.min(attempts - 1, 7))
@@ -192,7 +216,7 @@ export async function syncDodoProducts(
.run()
}
}
- return { processed }
+ return { processed, failed }
} finally {
await db
.prepare(
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 72cdd2b4..1c4d5d63 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -937,7 +937,7 @@ test('product failures persist redacted backoff without starving later plans and
.first<any>()
assert.equal(failure.attempts, 1)
assert.equal(failure.next_attempt_at, f.now + 30000)
- assert.equal(failure.error, 'payment_provider_request_failed')
+ assert.equal(failure.error, 'payment_provider_validation_failed:http_422')
assert.ok(!JSON.stringify(failure).includes('private-provider'))
assert.equal(
(await syncDodoProducts(f.db, root, transport, f.now + 1)).processed,
@@ -1132,3 +1132,146 @@ test('stale Dodo attempts release slots only in the active profile and remain re
await f.mf.dispose()
}
})
+
+test('product synchronization supports legacy required discounts without silently changing fractional discounts', async () => {
+ const f = await fixture()
+ try {
+ const legacy: typeof fetch = async (input, init) => {
+ const url = new URL(
+ typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : input.url,
+ )
+ if (url.pathname === '/products' && init?.method === 'POST') {
+ const body = JSON.parse(String(init.body))
+ if (!Number.isInteger(body.price.discount))
+ return Response.json(
+ { message: 'missing field `discount`' },
+ { status: 422 },
+ )
+ const response = await f.transport(input, init),
+ product = (await response.json()) as any
+ delete product.price.discount_bps
+ f.products.set(product.product_id, product)
+ return Response.json(product)
+ }
+ return f.transport(input, init)
+ }
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_discount_bps=2000,quarterly_discount_bps=2000,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ assert.deepEqual(await syncDodoProducts(f.db, root, legacy), {
+ processed: 2,
+ failed: 0,
+ })
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ legacy,
+ )
+ assert.ok(checkout.url)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT price FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<any>()
+ ).price,
+ 960,
+ )
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_discount_bps=1250,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ const result = await syncDodoProducts(f.db, root, legacy)
+ assert.equal(result.failed, 1)
+ const failure = await f.db
+ .prepare(
+ "SELECT error FROM platform_dodo_sync_failures WHERE provider_key='dodo_test' AND interval=1",
+ )
+ .first<any>()
+ assert.equal(failure.error, 'payment_discount_precision_unsupported')
+ assert.equal(
+ (await paymentStatus(f.db, 1, 1)).offers.filter((o) => o.interval === 1)
+ .length,
+ 0,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('manual synchronization retries immediately and reports only safe HTTP and schema diagnostics', async () => {
+ const f = await fixture()
+ try {
+ let attempts = 0,
+ status = 401
+ const rejected: typeof fetch = async () => {
+ attempts++
+ return Response.json(
+ {
+ message: 'missing field `discount`',
+ private_key: 'secret-do-not-store',
+ detail: [
+ { loc: ['body', 'price', 'discount'], input: 'secret-input' },
+ ],
+ },
+ { status },
+ )
+ }
+ assert.deepEqual(await syncDodoProducts(f.db, root, rejected, f.now), {
+ processed: 0,
+ failed: 2,
+ })
+ let row = await f.db
+ .prepare(
+ "SELECT * FROM platform_dodo_sync_failures WHERE provider_key='dodo_test' AND interval=1",
+ )
+ .first<any>()
+ assert.equal(row.error, 'payment_provider_authentication_failed:http_401')
+ await syncDodoProducts(f.db, root, rejected, f.now + 1)
+ assert.equal(attempts, 2)
+ status = 422
+ await syncDodoProducts(f.db, root, rejected, f.now + 2, 20, true)
+ assert.equal(attempts, 4)
+ row = await f.db
+ .prepare(
+ "SELECT * FROM platform_dodo_sync_failures WHERE provider_key='dodo_test' AND interval=1",
+ )
+ .first<any>()
+ assert.equal(
+ row.error,
+ 'payment_provider_validation_failed:http_422:price.discount',
+ )
+ assert.ok(!JSON.stringify(row).includes('secret'))
+ status = 403
+ await syncDodoProducts(f.db, root, rejected, f.now + 3, 20, true)
+ row = await f.db
+ .prepare(
+ "SELECT * FROM platform_dodo_sync_failures WHERE provider_key='dodo_test' AND interval=1",
+ )
+ .first<any>()
+ assert.equal(row.error, 'payment_provider_permission_denied:http_403')
+ assert.deepEqual(
+ await syncDodoProducts(f.db, root, f.transport, f.now + 4, 20, true),
+ { processed: 2, failed: 0 },
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_dodo_sync_failures')
+ .first<any>()
+ ).n,
+ 0,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})