Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix(billing): enforce elapsed deadlines and verify fenced checkout closure
Timothy Yind8f64134fac1
diff --git a/apps/cloud/app/composables/useDodoCheckoutReturn.ts b/apps/cloud/app/composables/useDodoCheckoutReturn.tsindex f50043d4..b8906aab 100644--- a/apps/cloud/app/composables/useDodoCheckoutReturn.ts+++ b/apps/cloud/app/composables/useDodoCheckoutReturn.ts@@ -33,16 +33,27 @@ export function useDodoCheckoutReturn(return}state.value = 'checking'- // Bound the whole return flow, including slow refreshes and transient workspace resets.- deadlineTimer = setTimeout(() => {- if (!alive || current !== generation) return+ function expire() {generation++deadline = 0if (timer) clearTimeout(timer)+ if (deadlineTimer) clearTimeout(deadlineTimer)state.value = 'pending'+ }+ function isCurrent() {+ if (!alive || current !== generation) return false+ if (Date.now() >= deadline) {+ expire()+ return false+ }+ return true+ }+ // Timers may be throttled in background tabs, so also check time after awaits.+ deadlineTimer = setTimeout(() => {+ if (alive && current === generation) expire()}, deadline - Date.now())async function poll(attempt: number): Promise<void> {- if (!alive || current !== generation) return+ if (!isCurrent()) returntry {const result = await $fetch<{ state: string }>('/api/billing/payments',@@ -52,9 +63,9 @@ export function useDodoCheckoutReturn(body: { action: 'refresh', workspaceId: id, checkoutId: checkout },},)- if (!alive || current !== generation) return+ if (!isCurrent()) returnawait refresh()- if (!alive || current !== generation) return+ if (!isCurrent()) returnif (['completed', 'scheduled', 'expired', 'inactive'].includes(result.state,@@ -65,7 +76,7 @@ export function useDodoCheckoutReturn(return}} catch (error: any) {- if (!alive || current !== generation) return+ if (!isCurrent()) returnif ([400, 401, 403, 404, 410, 422, 503].includes(error?.statusCode ?? error?.status,diff --git a/packages/platform/src/unpaid-checkout.ts b/packages/platform/src/unpaid-checkout.tsindex 9ef1ed6a..143083b1 100644--- a/packages/platform/src/unpaid-checkout.ts+++ b/packages/platform/src/unpaid-checkout.ts@@ -39,11 +39,13 @@ export async function closeFailedInitialCheckout()) as anyif (actual.status !== 'cancelled')throw new SubscriptionError(409, 'payment_confirmation_pending')- await db+ const result = await db.prepare(`UPDATE platform_payment_checkouts SET state='expired',error='payment_not_completed',updated_at=? WHERE id=? AND state IN('creating','open','uncertain') AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id) AND ${fence}`,).bind(now, checkout.id, ...fenceValues).run()+ if (!result.meta.changes)+ throw new SubscriptionError(409, 'payment_entitlement_changed')return true}diff --git a/scripts/smoke-edge-entry.mjs b/scripts/smoke-edge-entry.mjsindex 66a47c6a..6e27df32 100644--- a/scripts/smoke-edge-entry.mjs+++ b/scripts/smoke-edge-entry.mjs@@ -46,11 +46,13 @@ try {let ready = falsefor (let attempt = 0; attempt < 120; attempt++) {if (worker.exitCode !== null) throw new Error(`Worker exited: ${output}`)- const response = await fetch(base + '/api/health', {+ const health = await fetch(base + '/api/health', {signal: AbortSignal.timeout(1000),- }).catch(() => null)- if (response?.ok) {- assert.deepEqual(await response.json(), {+ })+ .then(async (response) => (response.ok ? await response.json() : null))+ .catch(() => null)+ if (health) {+ assert.deepEqual(health, {service: `chronoframe-${entry}`,status: 'bootstrap',})diff --git a/tests/dodo-checkout-return.test.ts b/tests/dodo-checkout-return.test.tsindex 749ab562..85e9de75 100644--- a/tests/dodo-checkout-return.test.ts+++ b/tests/dodo-checkout-return.test.ts@@ -8,7 +8,11 @@ import { ref, toValue, watch, nextTick, effectScope } from 'vue'function fixture(fetch: (...args: any[]) => Promise<any>,refresh = async () => {},- sources: { workspaceId?: () => number; enabled?: () => boolean } = {},+ sources: {+ workspaceId?: () => number+ enabled?: () => boolean+ now?: () => number+ } = {},) {const exports: Record<string, any> = {}const timers: (() => void)[] = []@@ -29,6 +33,7 @@ function fixture().outputText,{exports,+ Date: { now: sources.now ?? Date.now },ref,toValue,watch,@@ -317,3 +322,38 @@ test('the overall return deadline also covers a hung entitlement refresh', asyncf.dispose()}})++for (const stage of ['fetch', 'refresh', 'error'])+ test(`elapsed return deadline wins when a delayed timer has not run during ${stage}`, async () => {+ let now = 1000,+ release!: () => void,+ refreshes = 0+ const wait = new Promise<void>((r) => {+ release = r+ })+ const f = fixture(+ async () => {+ if (stage !== 'refresh') await wait+ if (stage === 'error') throw { statusCode: 422 }+ return { state: 'completed' }+ },+ async () => {+ refreshes+++ if (stage === 'refresh') await wait+ },+ { now: () => now },+ )+ try {+ await flush()+ assert.equal(f.watchdogs.length, 1)+ now += 60001+ release()+ await flush()+ assert.equal(f.returned.state.value, 'pending')+ assert.equal(refreshes, stage === 'refresh' ? 1 : 0)+ assert.equal(f.watchdogs.length, 0)+ assert.equal(f.timers.length, 0)+ } finally {+ f.dispose()+ }+ })diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.tsindex 6599f0e2..74d2aacb 100644--- a/tests/dodo-payments.test.ts+++ b/tests/dodo-payments.test.ts@@ -3063,3 +3063,85 @@ test('unconfirmed provider cancellation and mismatched failed payments never relawait f.mf.dispose()}})++test('lost checkout update fences reject closure and a later reconciliation can converge', async () => {+ const f = await fixture()+ try {+ await syncDodoProducts(f.db, root, f.transport)+ const checkout = await createPaymentCheckout(+ f.db,+ root,+ 1,+ input(),+ origin,+ f.transport,+ f.now,+ )+ const { payment, sub } = await f.paid(checkout)+ payment.status = 'failed'+ sub.status = 'pending'+ const row = await f.db+ .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')+ .bind(checkout.id)+ .first<any>()+ const client = {+ subscriptions: {+ update: async () => {+ sub.status = 'cancelled'+ },+ retrieve: async () => sub,+ },+ }+ const { closeFailedInitialCheckout } =+ await import('../packages/platform/src/unpaid-checkout.ts')+ await assert.rejects(+ closeFailedInitialCheckout(+ f.db,+ client,+ row,+ sub,+ payment,+ null,+ f.now,+ '0=1',+ [],+ ),+ { code: 'payment_entitlement_changed' },+ )+ assert.equal(sub.status, 'cancelled')+ assert.equal(+ (+ await f.db+ .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')+ .bind(checkout.id)+ .first<any>()+ ).state,+ 'open',+ )+ assert.equal(+ (+ await refreshDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 1000,+ )+ ).state,+ 'inactive',+ )+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)+ assert.equal(+ (+ await f.db+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')+ .first<any>()+ ).n,+ 0,+ )+ } finally {+ await f.mf.dispose()+ }+})