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(saas): resolve terminal checkout erasure and defer cross-page hashes

Timothy Yine53d34ae13bc
diff --git a/apps/site/app/router.options.ts b/apps/site/app/router.options.ts
index 52a2329a..e120d9a5 100644
--- a/apps/site/app/router.options.ts
+++ b/apps/site/app/router.options.ts
@@ -1,4 +1,5 @@
import type { RouterConfig } from 'nuxt/schema'
+import { useNuxtApp, useRouter } from '#app'
export default <RouterConfig>{
scrollBehavior(to, from, savedPosition) {
@@ -30,7 +31,23 @@ export default <RouterConfig>{
return false
}
- if (to.hash) return { el: to.hash }
+ if (to.hash) {
+ if (to.path === from.path || !from.matched?.length) return { el: to.hash }
+ const app = useNuxtApp(),
+ router = useRouter()
+ return new Promise((resolve) => {
+ app.hooks.hookOnce('page:loading:end', async () => {
+ await app['~transitionPromise']
+ requestAnimationFrame(() =>
+ resolve(
+ router.currentRoute.value.fullPath === to.fullPath
+ ? { el: to.hash }
+ : false,
+ ),
+ )
+ })
+ })
+ }
return { top: 0 }
},
}
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 8eb4b986..8fb748c5 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -1528,16 +1528,17 @@ export async function closeDodoAccountPayments(
.run()
}
// Locally abandoned sessions can still be paid through an old browser tab.
- // Only release their erasure fence after expiry AND a fresh no-payment response.
+ // Release only after expiry and a fresh no-payment or verified terminal-failure result.
const abandoned = await allRows<{
id: string
provider_id: string
provider_key: string
environment: DodoEnvironment
+ product_id: string
}>(
db
.prepare(
- "SELECT c.id,c.provider_id,c.provider_key,c.environment FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE c.provider='dodo' AND (w.owner_user_id=? OR c.user_id=?) AND c.state='expired' AND c.error='payment_checkout_abandoned' AND c.created_at<? ORDER BY c.created_at LIMIT 10",
+ "SELECT c.id,c.provider_id,c.provider_key,c.environment,c.product_id FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE c.provider='dodo' AND (w.owner_user_id=? OR c.user_id=?) AND c.state='expired' AND c.error='payment_checkout_abandoned' AND c.created_at<? ORDER BY c.created_at LIMIT 3",
)
.bind(userId, userId, now - 86400000),
)
@@ -1553,19 +1554,68 @@ export async function closeDodoAccountPayments(
const session = await dodoRequest(() =>
client.checkoutSessions.retrieve(rawDodoId(checkout.provider_id)),
)
- if (
- session.id !== rawDodoId(checkout.provider_id) ||
- session.payment_id ||
- session.payment_status
- )
- continue
+ if (session.id !== rawDodoId(checkout.provider_id)) continue
+ let resolution = 'payment_checkout_expired'
+ if (session.payment_id) {
+ const payment = await dodoRequest(() =>
+ client.payments.retrieve(session.payment_id!),
+ )
+ if (
+ payment.payment_id !== session.payment_id ||
+ (payment.checkout_session_id &&
+ payment.checkout_session_id !== session.id) ||
+ !['failed', 'cancelled'].includes(payment.status ?? '') ||
+ payment.refunds?.length ||
+ payment.disputes?.length ||
+ payment.is_multi_subscription
+ )
+ continue
+ if (payment.subscription_id) {
+ const subscription = await dodoRequest(() =>
+ client.subscriptions.retrieve(payment.subscription_id!),
+ )
+ if (
+ subscription.subscription_id !== payment.subscription_id ||
+ subscription.metadata?.chronoframe_checkout_id !== checkout.id ||
+ subscription.metadata?.chronoframe_profile_id !==
+ checkout.provider_key ||
+ subscription.metadata?.chronoframe_environment !==
+ checkout.environment ||
+ subscription.product_id !== checkout.product_id
+ )
+ continue
+ if (subscription.status === 'pending') {
+ await dodoRequest(() =>
+ client.subscriptions.update(payment.subscription_id!, {
+ status: 'cancelled',
+ }),
+ )
+ const actual = await dodoRequest(() =>
+ client.subscriptions.retrieve(payment.subscription_id!),
+ )
+ if (actual.status !== 'cancelled') continue
+ } else if (
+ !['cancelled', 'expired', 'failed'].includes(subscription.status)
+ )
+ continue
+ } else if (payment.subscription_ids?.length) continue
+ resolution = 'payment_not_completed'
+ } else if (session.payment_status) continue
await db
.prepare(
- `UPDATE platform_payment_checkouts SET error='payment_checkout_expired',updated_at=? WHERE id=? AND state='expired' AND error='payment_checkout_abandoned' AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id) AND NOT EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=platform_payment_checkouts.workspace_id AND expires_at>?) AND ${activeFence}`,
+ `UPDATE platform_payment_checkouts SET error=?,updated_at=? WHERE id=? AND state='expired' AND error='payment_checkout_abandoned' AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id) AND NOT EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=platform_payment_checkouts.workspace_id AND expires_at>?) AND ${activeFence}`,
)
- .bind(now, checkout.id, now, checkout.provider_key, revision)
+ .bind(resolution, now, checkout.id, now, checkout.provider_key, revision)
.run()
}
+ // A provider-less creation timeout is not proof that no billing exists. Release
+ // it only when authenticated reconciliation has established a terminal ledger.
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET error='payment_not_completed',updated_at=? WHERE provider='dodo' AND state='expired' AND error='payment_confirmation_unresolved' AND (user_id=? OR workspace_id IN(SELECT id FROM platform_workspaces WHERE owner_user_id=?)) AND EXISTS(SELECT 1 FROM platform_payment_subscriptions s WHERE s.checkout_id=platform_payment_checkouts.id AND s.provider_key IS platform_payment_checkouts.provider_key AND s.status IN('canceled','expired','failed'))",
+ )
+ .bind(now, userId, userId)
+ .run()
return !(await db
.prepare(
"SELECT c.id FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE c.provider='dodo' AND (w.owner_user_id=? OR c.user_id=?) AND (c.state IN('creating','open','uncertain') OR (c.state='expired' AND c.error IN('payment_confirmation_unresolved','payment_checkout_abandoned'))) LIMIT 1",
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 10c405bc..a711242c 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -4166,6 +4166,10 @@ test('account erasure retains payable abandoned sessions until expiry is verifie
const session = f.sessions.get(checkout.url.split('/').pop()!)!
const expiredAt = f.now + 86400000 + 2000
session.payment_id = 'pay_late_unresolved'
+ f.payments.set(session.payment_id, {
+ payment_id: session.payment_id,
+ status: 'processing',
+ })
assert.equal(
await closeDodoAccountPayments(f.db, root, 1, f.transport, expiredAt),
false,
@@ -4198,3 +4202,171 @@ test('account erasure retains payable abandoned sessions until expiry is verifie
await f.mf.dispose()
}
})
+
+test('late failed abandoned payments cancel only their pending subscription before releasing erasure', 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 { cancelDodoCheckout, closeDodoAccountPayments } =
+ await import('../packages/platform/src/dodo-payments.ts')
+ await cancelDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ const { sub, payment } = await f.paid(checkout)
+ const expiredAt = f.now + 86400000 + 1000
+ sub.status = 'pending'
+ payment.status = 'processing'
+ assert.equal(
+ await closeDodoAccountPayments(f.db, root, 1, f.transport, expiredAt),
+ false,
+ )
+ payment.status = 'succeeded'
+ assert.equal(
+ await closeDodoAccountPayments(f.db, root, 1, f.transport, expiredAt),
+ false,
+ )
+ payment.status = 'failed'
+ const unconfirmed: typeof fetch = async (url, init) =>
+ init?.method === 'PATCH' ? Response.json(sub) : f.transport(url, init)
+ assert.equal(
+ await closeDodoAccountPayments(f.db, root, 1, unconfirmed, expiredAt),
+ false,
+ )
+ assert.equal(
+ await closeDodoAccountPayments(f.db, root, 1, f.transport, expiredAt),
+ true,
+ )
+ assert.equal(sub.status, 'cancelled')
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT error FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<{ error: string }>()
+ ).error,
+ 'payment_not_completed',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('provider-less timeouts release erasure only after a verified terminal subscription ledger', 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 { sub } = await f.paid(checkout)
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ await f.db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='expired',provider_id=NULL,error='payment_confirmation_unresolved' WHERE id=?",
+ )
+ .bind(checkout.id)
+ .run()
+ const { closeDodoAccountPayments } =
+ await import('../packages/platform/src/dodo-payments.ts')
+ assert.equal(
+ await closeDodoAccountPayments(f.db, root, 1, f.transport, f.now + 2000),
+ true,
+ )
+ assert.equal(sub.status, 'cancelled')
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT error FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<{ error: string }>()
+ ).error,
+ 'payment_not_completed',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('a cancelled late payment without a subscription safely releases abandoned erasure', 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 { cancelDodoCheckout, closeDodoAccountPayments } =
+ await import('../packages/platform/src/dodo-payments.ts')
+ await cancelDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ const session = f.sessions.get(checkout.url.split('/').pop()!)!
+ session.payment_id = 'pay_cancelled_without_subscription'
+ f.payments.set(session.payment_id, {
+ payment_id: session.payment_id,
+ checkout_session_id: session.id,
+ status: 'cancelled',
+ })
+ assert.equal(
+ await closeDodoAccountPayments(
+ f.db,
+ root,
+ 1,
+ f.transport,
+ f.now + 86400000 + 1000,
+ ),
+ true,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT error FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<{ error: string }>()
+ ).error,
+ 'payment_not_completed',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
diff --git a/tests/site-viewer-navigation.test.ts b/tests/site-viewer-navigation.test.ts
index 2b16ac61..8b271a70 100644
--- a/tests/site-viewer-navigation.test.ts
+++ b/tests/site-viewer-navigation.test.ts
@@ -17,7 +17,14 @@ function compile(source: string, context: Record<string, unknown>) {
test('Site viewer route keeps scroll on open/close and preserves normal navigation', () => {
const router = compile(
readFileSync('apps/site/app/router.options.ts', 'utf8'),
- {},
+ {
+ require: () => ({
+ useNuxtApp: () => {
+ throw Error('unexpected page wait')
+ },
+ useRouter: () => ({}),
+ }),
+ },
).default as {
scrollBehavior(
to: {
@@ -162,3 +169,75 @@ test('photo route owns exactly one reactive title across repeated viewer open/cl
scope.stop()
}
})
+
+test('cross-page hashes wait for destination rendering and transitions, while same-page hashes are immediate', async () => {
+ let loaded: (() => Promise<void>) | undefined
+ let transitionEnd: (() => void) | undefined
+ const app = {
+ hooks: {
+ hookOnce: (name: string, callback: () => Promise<void>) => {
+ assert.equal(name, 'page:loading:end')
+ loaded = callback
+ },
+ },
+ '~transitionPromise': new Promise<void>((resolve) => {
+ transitionEnd = resolve
+ }),
+ }
+ const current = { value: { fullPath: '/albums/summer#photo' } }
+ const router = compile(
+ readFileSync('apps/site/app/router.options.ts', 'utf8'),
+ {
+ require: () => ({
+ useNuxtApp: () => app,
+ useRouter: () => ({ currentRoute: current }),
+ }),
+ requestAnimationFrame: (fn: () => void) => fn(),
+ },
+ ).default as {
+ scrollBehavior(to: unknown, from: unknown, saved: unknown): unknown
+ }
+ const destination = {
+ path: '/albums/summer',
+ hash: '#photo',
+ fullPath: current.value.fullPath,
+ }
+ const result = router.scrollBehavior(
+ destination,
+ { path: '/albums', matched: [{}] },
+ null,
+ ) as Promise<unknown>
+ let scrolled = false
+ result.then(() => {
+ scrolled = true
+ })
+ await Promise.resolve()
+ assert.equal(scrolled, false)
+ assert.ok(loaded)
+ const rendering = loaded()
+ await Promise.resolve()
+ assert.equal(scrolled, false)
+ transitionEnd!()
+ await rendering
+ assert.deepEqual(JSON.parse(JSON.stringify(await result)), { el: '#photo' })
+ assert.deepEqual(
+ JSON.parse(
+ JSON.stringify(
+ router.scrollBehavior(
+ destination,
+ { path: destination.path, matched: [{}] },
+ null,
+ ),
+ ),
+ ),
+ { el: '#photo' },
+ )
+ const superseded = router.scrollBehavior(
+ destination,
+ { path: '/albums', matched: [{}] },
+ null,
+ ) as Promise<unknown>
+ current.value.fullPath = '/photos'
+ await loaded!()
+ assert.equal(await superseded, false)
+})