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(cloud): harden subscription recovery and quota transitions

Timothy Yinf7969277cdfa
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 3e7af691..7bd9b8d5 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -3087,6 +3087,14 @@ a.cf-domain-address:hover {
font-size: 11px;
color: var(--muted-foreground);
}
+.cf-portal .cf-quota-card small.cf-error-message {
+ display: block;
+ padding: 0;
+ margin: 0;
+ border: 0;
+ background: transparent;
+ color: var(--destructive);
+}
.cf-quota-track {
height: 4px;
border-radius: 4px;
diff --git a/apps/cloud/app/composables/useCloudLinks.ts b/apps/cloud/app/composables/useCloudLinks.ts
index e9aa5f61..4a60f246 100644
--- a/apps/cloud/app/composables/useCloudLinks.ts
+++ b/apps/cloud/app/composables/useCloudLinks.ts
@@ -1,6 +1,6 @@
/** Production actions cross to the portal; preview/local auth stays on its own isolated origin. */
export function useCloudLinks() {
- const hostname = useRequestURL().hostname
+ const hostname = useCloudRequestURL().hostname
const portal = ['chronoframe.art', 'app.chronoframe.art'].includes(hostname)
? 'https://app.chronoframe.art'
: ''
diff --git a/apps/cloud/app/composables/useCloudRequestURL.ts b/apps/cloud/app/composables/useCloudRequestURL.ts
new file mode 100644
index 00000000..3bd4a072
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudRequestURL.ts
@@ -0,0 +1,7 @@
+/** Keep SSR host decisions consistent with the original Worker request. */
+export function useCloudRequestURL() {
+ const request = import.meta.server
+ ? (useRequestEvent()?.context.cloudflare?.request as Request | undefined)
+ : undefined
+ return request ? new URL(request.url) : useRequestURL()
+}
diff --git a/apps/cloud/app/composables/useWorkspaceBilling.ts b/apps/cloud/app/composables/useWorkspaceBilling.ts
index b8900fb4..e0660c19 100644
--- a/apps/cloud/app/composables/useWorkspaceBilling.ts
+++ b/apps/cloud/app/composables/useWorkspaceBilling.ts
@@ -1,40 +1,63 @@
-export async function useWorkspaceBilling(adminOnly = false) {
+export function useWorkspaceBilling(adminOnly = false) {
const route = useRoute(),
user = usePortalIdentity(),
- fetcher = useRequestFetch()
- const { data: list, error: listError } = await useFetch<{
- workspaces: { id: number; name: string; role: string }[]
- }>('/api/billing/workspaces', { key: 'billing-workspaces-' + user.value?.id })
+ fetcher = useRequestFetch(),
+ listing = useFetch<{
+ workspaces: { id: number; name: string; role: string }[]
+ }>('/api/billing/workspaces', {
+ key: 'billing-workspaces-' + user.value?.id,
+ })
+ const { data: list, error: listError } = listing
const workspaces = computed(() =>
(list.value?.workspaces ?? []).filter(
(w) => !adminOnly || w.role === 'admin',
),
)
- const selected = ref(
- workspaces.value.some((w) => w.id === Number(route.query.workspaceId))
- ? Number(route.query.workspaceId)
- : (workspaces.value[0]?.id ?? 0),
+ const selected = ref(Number(route.query.workspaceId) || 0)
+ watch(
+ workspaces,
+ (available) => {
+ if (!list.value) return
+ if (!available.some((w) => w.id === selected.value))
+ selected.value = available[0]?.id ?? 0
+ },
+ { immediate: true, flush: 'sync' },
)
- const { data, error, status, refresh } = await useAsyncData(
+ // Register every composable synchronously while the page owns the Vue scope.
+ // Waiting for the workspace list inside the handler also covers SSR cold loads.
+ const billing = useAsyncData(
computed(
() => 'workspace-billing-' + user.value?.id + '-' + selected.value,
),
- () =>
- selected.value
+ async () => {
+ await listing
+ return selected.value
? fetcher<any>('/api/billing/plan', {
query: { workspaceId: selected.value },
})
- : Promise.resolve(null),
+ : null
+ },
)
onMounted(async () => {
+ await listing
if (!workspaces.value.length && !listError.value) {
try {
list.value = await $fetch('/api/billing/workspaces', { method: 'POST' })
- selected.value = workspaces.value[0]?.id ?? 0
} catch {
/* Do not restore revoked memberships. */
}
}
})
- return { workspaces, selected, data, error, listError, status, refresh }
+ return {
+ workspaces,
+ selected,
+ ...billing,
+ listError,
+ retry: async () => {
+ await listing.refresh()
+ await nextTick()
+ if (!listError.value) await billing.refresh()
+ },
+ ready: Promise.all([listing, billing]),
+ }
}
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index 0522f8d0..b43718c9 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -9,7 +9,7 @@ export default defineNuxtRouteMiddleware(async (to) => {
'platform-site-catalog',
() => null,
)
- if (path === '/' && useRequestURL().hostname === 'app.chronoframe.art')
+ if (path === '/' && useCloudRequestURL().hostname === 'app.chronoframe.art')
return navigateTo('/sites', { redirectCode: 302 })
if (path === '/dashboard' || path.startsWith('/dashboard/'))
return navigateTo('/sites', { redirectCode: 302 })
@@ -22,7 +22,7 @@ export default defineNuxtRouteMiddleware(async (to) => {
}
if (
(path === '/pricing' &&
- (useRequestURL().hostname === 'app.chronoframe.art' ||
+ (useCloudRequestURL().hostname === 'app.chronoframe.art' ||
to.query.portal === '1')) ||
path === '/account' ||
path.startsWith('/account/') ||
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
index 6383bcb5..0cf03e73 100644
--- a/apps/cloud/app/pages/account/plan.vue
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -3,8 +3,18 @@ import { BILLING_LIMITS, allowance } from '../../utils/billing-format'
definePageMeta({ layout: 'portal' })
const { t, locale } = useI18n(),
links = useCloudLinks(),
- { workspaces, selected, data, error, listError, status, refresh } =
- await useWorkspaceBilling()
+ {
+ workspaces,
+ selected,
+ data,
+ error,
+ listError,
+ status,
+ refresh,
+ retry,
+ ready,
+ } = useWorkspaceBilling()
+await ready
useSeoMeta({
title: t('cloud.billing.plan') + ' — ChronoFrame Cloud',
robots: 'noindex',
@@ -54,7 +64,7 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
v-if="error || listError"
role="alert"
><p>{{ $t('cloud.billing.failed') }}</p>
- <CloudButton @click="refresh">{{
+ <CloudButton @click="retry">{{
$t('cloud.billing.retry')
}}</CloudButton></CloudCard
><template v-else-if="data"
diff --git a/apps/cloud/app/pages/account/redeem.vue b/apps/cloud/app/pages/account/redeem.vue
index 7c2616d3..a260a970 100644
--- a/apps/cloud/app/pages/account/redeem.vue
+++ b/apps/cloud/app/pages/account/redeem.vue
@@ -2,14 +2,15 @@
import { billingError } from '../../utils/billing-format'
definePageMeta({ layout: 'portal' })
const { t, locale } = useI18n(),
- { workspaces, selected, error, listError, refresh } =
- await useWorkspaceBilling(true),
+ { workspaces, selected, error, listError, refresh, ready } =
+ useWorkspaceBilling(true),
code = ref(''),
preview = ref<any>(null),
busy = ref(false),
failure = ref(''),
receipt = ref<any>(null),
requestId = ref('')
+await ready
useSeoMeta({
title: t('cloud.billing.redeem') + ' — ChronoFrame Cloud',
robots: 'noindex',
@@ -59,7 +60,13 @@ async function redeem() {
} catch (error: any) {
failure.value = billingError(error, t)
const code = error?.data?.data?.code ?? error?.data?.code
- if (['subscription_changed', 'redemption_changed'].includes(code)) {
+ if (
+ [
+ 'subscription_changed',
+ 'redemption_changed',
+ 'invalid_activation_code',
+ ].includes(code)
+ ) {
preview.value = null
requestId.value = ''
}
diff --git a/apps/cloud/app/pages/pricing.vue b/apps/cloud/app/pages/pricing.vue
index bd04e858..7f5fa205 100644
--- a/apps/cloud/app/pages/pricing.vue
+++ b/apps/cloud/app/pages/pricing.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
const route = useRoute(),
portal =
- useRequestURL().hostname === 'app.chronoframe.art' ||
+ useCloudRequestURL().hostname === 'app.chronoframe.art' ||
route.query.portal === '1',
{ t } = useI18n()
definePageMeta({ layout: false })
diff --git a/packages/platform/src/activation.ts b/packages/platform/src/activation.ts
index 4edc0b13..61fee027 100644
--- a/packages/platform/src/activation.ts
+++ b/packages/platform/src/activation.ts
@@ -278,6 +278,12 @@ export async function redeemActivation(
)
.bind(userId, input.requestId as string)
.first<{ workspace_id: number; receipt_json: string }>()
- if (!result || result.workspace_id !== workspaceId) invalid()
+ if (!result) {
+ const latest = await resolveSubscription(db, workspaceId, now)
+ if (latest.assignment_revision !== Number(input.revision))
+ throw new SubscriptionError(409, 'subscription_changed')
+ invalid()
+ }
+ if (result.workspace_id !== workspaceId) invalid()
return JSON.parse(result.receipt_json)
}
diff --git a/packages/platform/src/subscriptions.ts b/packages/platform/src/subscriptions.ts
index 1f49775e..12b20a28 100644
--- a/packages/platform/src/subscriptions.ts
+++ b/packages/platform/src/subscriptions.ts
@@ -108,12 +108,12 @@ export async function resolveSubscription(
const row = await db
.prepare(`SELECT p.id,p.name,p.revision,p.policy_json,p.currency,p.monthly_price,p.quarterly_price,w.created_at,w.owner_user_id,COALESCE(u.email_verified,0) AS email_verified,
COALESCE(wp.revision,0) AS assignment_revision,CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.source ELSE 'default' END AS source,
- CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.starts_at ELSE COALESCE(wp.expires_at,wp.starts_at,w.created_at) END AS starts_at,
+ CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.starts_at WHEN wp.expires_at<=? THEN wp.expires_at ELSE COALESCE(wp.starts_at,w.created_at) END AS starts_at,
CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.expires_at ELSE NULL END AS expires_at,wp.billing_interval,
CASE WHEN wp.expires_at<=? OR assigned.active=0 OR wp.source='expired_default' THEN 1 ELSE 0 END AS expired
FROM platform_workspaces w LEFT JOIN platform_users u ON u.id=w.owner_user_id LEFT JOIN platform_workspace_plans wp ON wp.workspace_id=w.id LEFT JOIN platform_plans assigned ON assigned.id=wp.plan_id
JOIN platform_plans p ON p.id=CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN assigned.id ELSE ${EXPIRY_PLAN_SQL} END WHERE w.id=?`)
- .bind(now, now, now, now, now, workspaceId)
+ .bind(now, now, now, now, now, now, workspaceId)
.first<{
id: string
name: string
@@ -180,7 +180,7 @@ export async function reconcileSubscriptions(
}>(
db
.prepare(
- 'SELECT wp.* FROM platform_workspace_plans wp JOIN platform_plans p ON p.id=wp.plan_id WHERE wp.expires_at<=? OR p.active=0 ORDER BY COALESCE(wp.expires_at,0),wp.workspace_id LIMIT ?',
+ `SELECT wp.* FROM platform_workspace_plans wp JOIN platform_plans p ON p.id=wp.plan_id WHERE (wp.expires_at<=? OR p.active=0) AND NOT (wp.source='expired_default' AND wp.expires_at IS NULL AND wp.plan_id=${EXPIRY_PLAN_SQL}) ORDER BY COALESCE(wp.expires_at,0),wp.workspace_id LIMIT ?`,
)
.bind(now, limit),
)
@@ -193,7 +193,7 @@ export async function reconcileSubscriptions(
const results = await db.batch([
db
.prepare(
- "INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,'expired',?,?,? WHERE EXISTS(SELECT 1 FROM platform_workspace_plans wp JOIN platform_plans p ON p.id=wp.plan_id WHERE wp.workspace_id=? AND wp.revision=? AND (wp.expires_at<=? OR p.active=0))",
+ `INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,'expired',?,?,? WHERE EXISTS(SELECT 1 FROM platform_workspace_plans wp JOIN platform_plans p ON p.id=wp.plan_id WHERE wp.workspace_id=? AND wp.revision=? AND (wp.expires_at<=? OR p.active=0) AND NOT (wp.source='expired_default' AND wp.expires_at IS NULL AND wp.plan_id=${EXPIRY_PLAN_SQL}))`,
)
.bind(
id,
@@ -207,9 +207,9 @@ export async function reconcileSubscriptions(
),
db
.prepare(
- `UPDATE platform_workspace_plans SET plan_id=${EXPIRY_PLAN_SQL},starts_at=COALESCE(expires_at,starts_at),expires_at=NULL,source='expired_default',billing_interval=NULL,revision=revision+1 WHERE workspace_id=? AND revision=? AND EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)`,
+ `UPDATE platform_workspace_plans SET plan_id=${EXPIRY_PLAN_SQL},starts_at=CASE WHEN expires_at<=? THEN expires_at ELSE starts_at END,expires_at=NULL,source='expired_default',billing_interval=NULL,revision=revision+1 WHERE workspace_id=? AND revision=? AND EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)`,
)
- .bind(row.workspace_id, row.revision, id),
+ .bind(now, row.workspace_id, row.revision, id),
...subscriptionInvalidation(db, row.workspace_id, id),
])
changed += results[0]?.meta.changes ?? 0
diff --git a/tests/platform-subscriptions.test.ts b/tests/platform-subscriptions.test.ts
index 83e26c3a..d7c876c1 100644
--- a/tests/platform-subscriptions.test.ts
+++ b/tests/platform-subscriptions.test.ts
@@ -209,7 +209,7 @@ test('Real D1 defaults, live expiry, activation races/idempotency and workspace
},
now,
)
- assert.equal(result.grant.expiresAt, addMonths(addMonths(now, 1), 1))
+ assert.equal(result.grant.expiresAt, addMonths(now, 2))
assert.equal(result.grant.startsAt, now)
const shared = await code(1)
const a = await previewActivation(db, 2, two.id, shared.code, now),
@@ -467,6 +467,99 @@ test('Real D1 defaults, live expiry, activation races/idempotency and workspace
assert.equal(route, false)
const quota = (await resolveSubscription(db, one.id, now)).quotaPeriod
assert.equal(quota.start, now - 1)
+ // A plan disabled before its paid expiry must retain a current quota anchor.
+ await db
+ .prepare(
+ "UPDATE platform_billing_settings SET expiry_plan_id='free' WHERE id=1",
+ )
+ .run()
+ await db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='pro',starts_at=?,expires_at=?,source='activation',revision=revision+1 WHERE workspace_id=?",
+ )
+ .bind(now, addMonths(now, 3), one.id)
+ .run()
+ await db.prepare("UPDATE platform_plans SET active=0 WHERE id='pro'").run()
+ const disabled = await resolveSubscription(db, one.id, now)
+ assert.equal(disabled.id, 'free')
+ assert.equal(disabled.quotaPeriod.start, now)
+ assert.equal(
+ (await workspaceBilling(db, 1, one.id, now)).usage.monthlyBytes,
+ 123,
+ )
+ await reconcileSubscriptions(db, now)
+ assert.equal(
+ (await resolveSubscription(db, one.id, now)).quotaPeriod.start,
+ now,
+ )
+ assert.equal(
+ (await workspaceBilling(db, 1, one.id, now)).usage.monthlyBytes,
+ 123,
+ )
+ // Even a manually corrupted inactive fallback cannot monopolize the bounded queue.
+ await db.prepare("UPDATE platform_plans SET active=0 WHERE id='free'").run()
+ await reconcileSubscriptions(db, now)
+ assert.equal((await reconcileSubscriptions(db, now)).changed, 0)
+ await db
+ .prepare("UPDATE platform_plans SET active=1 WHERE id='starter'")
+ .run()
+ const genuine = await db
+ .prepare(
+ "INSERT INTO platform_workspaces(name) VALUES('Genuinely expired') RETURNING id",
+ )
+ .first<{ id: number }>()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspace_plans(workspace_id,plan_id,starts_at,expires_at,source) VALUES(?,'starter',?,?,'manual')",
+ )
+ .bind(genuine!.id, now - 1000, now - 1)
+ .run()
+ assert.equal((await reconcileSubscriptions(db, now, 1)).changed, 1)
+ assert.equal(
+ (await resolveSubscription(db, genuine!.id, now)).subscription.source,
+ 'default',
+ )
+ await db.prepare("UPDATE platform_plans SET active=1 WHERE id='free'").run()
+ // Change the assignment after preflight but before the atomic claim statement.
+ await db.prepare("UPDATE platform_plans SET active=1 WHERE id='pro'").run()
+ const racedCode = await code(null),
+ stale = await resolveSubscription(db, one.id, now)
+ const racingDb = {
+ prepare: db.prepare.bind(db),
+ batch: async (statements: any[]) => {
+ await db
+ .prepare(
+ 'UPDATE platform_workspace_plans SET revision=revision+1 WHERE workspace_id=?',
+ )
+ .bind(one.id)
+ .run()
+ return db.batch(statements)
+ },
+ }
+ await assert.rejects(
+ () =>
+ redeemActivation(
+ racingDb,
+ 1,
+ one.id,
+ {
+ code: racedCode.code,
+ revision: stale.assignment_revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ ),
+ { code: 'subscription_changed' },
+ )
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT uses FROM platform_activation_codes WHERE id=?')
+ .bind(racedCode.id)
+ .first()
+ ).uses,
+ 0,
+ )
const rateWindow = now + 9000000
for (let i = 0; i < 20; i++)
await assert.rejects(