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.

feat(billing): unify plan management and synchronize the Creem catalog

Timothy Yin9adce08b3480
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 70ea3be4..fd1915d6 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -3205,3 +3205,106 @@ a.cf-domain-address:hover {
.cf-pricing-current {
margin-bottom: 24px;
}
+
+/* The account billing view keeps subscription, allowances and plan choices together. */
+.cf-subscription-overview {
+ display: grid;
+ grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1.2fr);
+ align-items: start;
+ gap: 20px;
+ padding: 22px;
+}
+.cf-subscription-overview h2 {
+ font-size: 25px;
+ font-weight: 600;
+ margin: 8px 0 0;
+}
+.cf-subscription-overview p {
+ font-size: 13px;
+ line-height: 1.6;
+ margin: 7px 0 0;
+}
+.cf-plan-management {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 8px;
+ padding-top: 14px;
+ border-top: 1px solid var(--border);
+}
+.cf-plan-page .cf-quota-grid {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+}
+.cf-plan-page .cf-quota-card {
+ padding: 16px 18px;
+}
+.cf-plan-page .cf-quota-card h3 {
+ margin-bottom: 8px;
+}
+.cf-plan-page .cf-quota-card strong {
+ font-size: 21px;
+}
+.cf-plan-page .cf-quota-track {
+ margin-top: 10px;
+}
+.cf-plan-options {
+ scroll-margin-top: 90px;
+ padding-top: 12px;
+}
+.cf-plan-options-heading {
+ margin-bottom: 22px;
+ display: grid;
+ gap: 10px;
+ justify-items: start;
+}
+.cf-plan-options-heading h2 {
+ font-size: 19px;
+ font-weight: 600;
+}
+.cf-plan-options-heading > p {
+ font-size: 13px;
+ color: var(--muted-foreground);
+}
+.cf-plan-options-heading .cf-billing-toggle {
+ margin: 6px 0;
+}
+.cf-plan-options .cf-pricing-card {
+ padding: 20px;
+ gap: 14px;
+}
+.cf-plan-options .cf-plan-price strong {
+ font-size: 30px;
+}
+.cf-plan-options .cf-plan-description {
+ min-height: 0;
+}
+.cf-plan-options .cf-pricing-card.is-current {
+ border-color: var(--primary);
+ box-shadow: 0 0 0 1px var(--primary);
+}
+.cf-plan-options .cf-price-caption {
+ min-height: 16px;
+}
+@media (max-width: 760px) {
+ .cf-subscription-overview {
+ grid-template-columns: 1fr 1fr;
+ gap: 16px;
+ padding: 18px;
+ }
+ .cf-subscription-overview > div:first-child {
+ grid-column: 1 / -1;
+ }
+ .cf-plan-page .cf-quota-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ .cf-plan-management {
+ justify-content: flex-start;
+ }
+}
+@media (max-width: 380px) {
+ .cf-subscription-overview,
+ .cf-plan-page .cf-quota-grid {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
diff --git a/apps/cloud/app/components/CloudPaymentsPanel.vue b/apps/cloud/app/components/CloudPaymentsPanel.vue
deleted file mode 100644
index 18f9f1cc..00000000
--- a/apps/cloud/app/components/CloudPaymentsPanel.vue
+++ /dev/null
@@ -1,116 +0,0 @@
-<script setup lang="ts">
-const props = defineProps<{ workspaceId: number | string }>()
-const { t, locale } = useI18n()
-const state = ref<any>(),
- busy = ref(false),
- error = ref('')
-let generation = 0,
- alive = true
-async function load() {
- const current = ++generation,
- id = Number(props.workspaceId)
- if (!id) return
- try {
- const result = await $fetch('/api/billing/payments', {
- query: { workspaceId: id },
- })
- if (alive && current === generation) {
- state.value = result
- error.value = ''
- }
- } catch {
- if (alive && current === generation)
- error.value = t('cloud.payments.failed')
- }
-}
-watch(
- () => props.workspaceId,
- () => {
- state.value = null
- error.value = ''
- void load()
- },
-)
-onMounted(load)
-onBeforeUnmount(() => {
- alive = false
- generation++
-})
-useIntervalFn(() => {
- if (document.visibilityState === 'visible') void load()
-}, 15000)
-async function portal() {
- if (busy.value) return
- busy.value = true
- error.value = ''
- const workspaceId = Number(props.workspaceId)
- try {
- const result = await $fetch<{ url: string }>('/api/billing/payments', {
- method: 'POST',
- body: { action: 'portal', workspaceId },
- })
- if (alive && workspaceId === Number(props.workspaceId))
- await navigateTo(result.url, { external: true })
- } catch {
- if (alive) error.value = t('cloud.payments.failed')
- } finally {
- busy.value = false
- }
-}
-</script>
-<template>
- <CloudCard
- v-if="
- state && (state.enabled || state.subscriptions.length || state.pending)
- "
- class="cf-current-plan"
- >
- <div>
- <h2>{{ $t('cloud.payments.billing') }}</h2>
- <CloudBadge>{{ $t('cloud.payments.test') }}</CloudBadge>
- <p>{{ $t('cloud.payments.testHelp') }}</p>
- <p
- v-if="state.pending"
- role="status"
- >
- {{ $t('cloud.payments.pending') }}
- </p>
- <p
- v-for="s in state.subscriptions"
- :key="s.id"
- class="cf-field-hint"
- >
- {{ $t('cloud.payments.status.' + s.status) }} ·
- {{ new Date(s.period_end).toLocaleString(locale) }}
- </p>
- <p
- v-if="error"
- class="cf-error-message"
- role="alert"
- >
- {{ error }}
- </p>
- </div>
- <div class="cf-inline-controls">
- <CloudButton
- v-if="state.canManage && state.subscriptions.length"
- :loading="busy"
- @click="portal"
- >{{ $t('cloud.payments.manage') }}</CloudButton
- ><CloudButton
- v-if="state.canManage && state.pending?.url"
- as-child
- variant="secondary"
- ><a :href="state.pending.url">{{
- $t('cloud.payments.resume')
- }}</a></CloudButton
- >
- <p
- v-if="!state.canManage"
- class="cf-field-hint"
- >
- {{ $t('cloud.billing.adminOnly') }}
- </p>
- </div>
- </CloudCard>
-</template>
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vue
index f9c2a88e..f50f3557 100644
--- a/apps/cloud/app/components/CloudPricing.vue
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -5,13 +5,25 @@ import {
price,
conditionText,
} from '../utils/billing-format'
-const props = withDefaults(defineProps<{ portal?: boolean }>(), {
- portal: false,
- }),
- { t, locale } = useI18n(),
+const props = withDefaults(
+ defineProps<{
+ portal?: boolean
+ embedded?: boolean
+ workspaceBilling?: ReturnType<typeof useWorkspaceBilling>
+ paymentController?: ReturnType<typeof useCloudPayments>
+ }>(),
+ { portal: false, embedded: false },
+)
+const { t, locale } = useI18n(),
links = useCloudLinks(),
- interval = ref<1 | 3>(1),
- billing = props.portal ? useWorkspaceBilling() : null
+ interval = ref<1 | 3>(1)
+const billing = props.portal
+ ? (props.workspaceBilling ?? useWorkspaceBilling())
+ : null
+const payments = props.portal
+ ? (props.paymentController ??
+ useCloudPayments(() => billing?.selected.value ?? 0))
+ : null
const { data, error, refresh } = await useFetch<any>('/api/billing/catalog', {
key: 'public-pricing-catalog',
})
@@ -26,37 +38,25 @@ const action = (plan: any) =>
(props.portal && billing?.selected.value
? '?workspaceId=' + billing.selected.value
: '')
-const payment = ref<any>(),
+const payment = computed(() => payments?.data.value),
paying = ref(''),
paymentError = ref('')
-let paymentGeneration = 0,
- mounted = true
-async function loadPayments() {
- const id = billing?.selected.value,
- generation = ++paymentGeneration
- if (!id) return
- try {
- const result = await $fetch('/api/billing/payments', {
- query: { workspaceId: id },
- })
- if (mounted && generation === paymentGeneration) payment.value = result
- } catch {
- if (mounted && generation === paymentGeneration) payment.value = null
- }
-}
-onMounted(() => {
- if (props.portal) void loadPayments()
-})
-if (billing)
- watch(billing.selected, () => {
- payment.value = null
- paymentError.value = ''
- void loadPayments()
- })
+let mounted = true
onBeforeUnmount(() => {
mounted = false
- paymentGeneration++
})
+watch(
+ () => payment.value?.pending?.interval,
+ (n) => {
+ if (n === 1 || n === 3) interval.value = n
+ },
+ { immediate: true },
+)
+const pendingFor = (plan: any) => payment.value?.pending?.planId === plan.id
+async function resume() {
+ if (payment.value?.pending?.url)
+ await navigateTo(payment.value.pending.url, { external: true })
+}
const offer = (plan: any) =>
payment.value?.enabled &&
payment.value?.canManage &&
@@ -90,7 +90,7 @@ async function checkout(plan: any) {
} catch {
if (mounted) {
paymentError.value = t('cloud.payments.failed')
- await loadPayments()
+ await payments?.refresh()
}
} finally {
paying.value = ''
@@ -99,10 +99,24 @@ async function checkout(plan: any) {
</script>
<template>
<div class="cf-pricing">
- <div class="cf-pricing-heading">
- <p class="cf-eyebrow">ChronoFrame Cloud</p>
- <h1>{{ $t('cloud.billing.pricing') }}</h1>
- <p>{{ $t('cloud.billing.pricingHelp') }}</p>
+ <div :class="embedded ? 'cf-plan-options-heading' : 'cf-pricing-heading'">
+ <p
+ v-if="!embedded"
+ class="cf-eyebrow"
+ >
+ ChronoFrame Cloud
+ </p>
+ <h2 v-if="embedded">{{ $t('cloud.billing.choosePlan') }}</h2>
+ <h1 v-else>{{ $t('cloud.billing.pricing') }}</h1>
+ <p>
+ {{
+ $t(
+ embedded
+ ? 'cloud.billing.optionsHelp'
+ : 'cloud.billing.pricingHelp',
+ )
+ }}
+ </p>
<fieldset class="cf-billing-toggle">
<legend class="sr-only">{{ $t('cloud.billing.interval') }}</legend>
<label
@@ -113,6 +127,7 @@ async function checkout(plan: any) {
v-model="interval"
type="radio"
name="billing-interval"
+ :disabled="portal && !!payment?.pending"
:value="n"
/><span>{{
$t('cloud.billing.' + (n === 1 ? 'monthly' : 'quarterly'))
@@ -134,23 +149,7 @@ async function checkout(plan: any) {
{{ paymentError }}
</p>
</div>
- <CloudPaymentsPanel
- v-if="portal && billing?.selected.value"
- :workspace-id="billing.selected.value"
- />
- <template v-if="billing">
- <label class="cf-workspace-picker"
- >{{ $t('cloud.billing.workspace')
- }}<select v-model="billing.selected.value">
- <option
- v-for="workspace in billing.workspaces.value"
- :key="workspace.id"
- :value="workspace.id"
- >
- {{ workspace.name }}
- </option>
- </select></label
- >
+ <template v-if="billing && !embedded">
<p
v-if="billing.error.value"
role="alert"
@@ -183,12 +182,18 @@ async function checkout(plan: any) {
v-for="plan in data.plans"
:key="plan.id"
class="cf-pricing-card"
- :class="{ 'is-featured': plan.featured }"
+ :class="{
+ 'is-featured': plan.featured && !embedded,
+ 'is-current': portal && plan.id === currentPlan,
+ }"
>
<div class="cf-plan-card-heading">
<h2>{{ plan.name }}</h2>
<CloudBadge v-if="portal && plan.id === currentPlan">{{
$t('cloud.billing.current')
+ }}</CloudBadge
+ ><CloudBadge v-else-if="embedded && plan.featured">{{
+ $t('cloud.billing.recommended')
}}</CloudBadge>
</div>
<p class="cf-plan-description">
@@ -215,28 +220,66 @@ async function checkout(plan: any) {
price(amount(plan)! / 3, plan.currency, locale) +
' / ' +
$t('cloud.billing.month')
- : $t('cloud.billing.noCheckout')
+ : $t(
+ portal
+ ? amount(plan) === 0
+ ? 'cloud.billing.noCharge'
+ : 'cloud.billing.monthlyBilling'
+ : 'cloud.billing.noCheckout',
+ )
}}
</p>
<CloudButton
- v-if="portal && offer(plan)"
+ v-if="portal && !payment"
+ disabled
+ variant="secondary"
+ >{{ $t('cloud.billing.loading') }}</CloudButton
+ >
+ <CloudButton
+ v-else-if="portal && pendingFor(plan)"
+ :disabled="!payment.pending.url || !!paying"
+ @click="resume"
+ >
+ {{
+ $t(
+ payment.pending.url
+ ? 'cloud.payments.resume'
+ : 'cloud.payments.waiting',
+ )
+ }}
+ </CloudButton>
+ <CloudButton
+ v-else-if="portal && plan.id === currentPlan"
+ disabled
+ variant="secondary"
+ >{{ $t('cloud.billing.current') }}</CloudButton
+ >
+ <CloudButton
+ v-else-if="portal && subscriptionActive && amount(plan) !== 0"
+ :disabled="
+ !payment.canManage || !!payment.pending || payments?.busy.value
+ "
+ variant="secondary"
+ @click="payments?.portal()"
+ >{{ $t('cloud.payments.manage') }}</CloudButton
+ >
+ <CloudButton
+ v-else-if="portal && offer(plan)"
:loading="paying === plan.id + ':' + interval"
- :disabled="!!paying || !!payment.pending || subscriptionActive"
+ :disabled="!!paying || !!payment.pending"
:variant="plan.featured ? 'default' : 'secondary'"
@click="checkout(plan)"
- >{{
- subscriptionActive
- ? $t('cloud.payments.manageExisting')
- : $t('cloud.payments.subscribe')
- }}</CloudButton
+ >{{ $t('cloud.payments.subscribe') }}</CloudButton
>
<CloudButton
v-else-if="
- portal && billing?.data.value?.workspace.role !== 'admin'
+ portal &&
+ (billing?.data.value?.workspace.role !== 'admin' ||
+ !!payment?.pending)
"
disabled
:title="$t('cloud.billing.adminOnly')"
- :variant="plan.featured ? 'default' : 'secondary'"
+ variant="secondary"
>{{ $t('cloud.billing.redeem') }}</CloudButton
>
<CloudButton
@@ -296,7 +339,7 @@ async function checkout(plan: any) {
{{ $t('cloud.billing.noPlans') }}
</div>
<section
- v-else
+ v-else-if="!embedded"
class="cf-plan-comparison"
>
<h2>{{ $t('cloud.billing.compare') }}</h2>
diff --git a/apps/cloud/app/composables/useCheckoutReturn.ts b/apps/cloud/app/composables/useCheckoutReturn.ts
new file mode 100644
index 00000000..0b0590b2
--- /dev/null
+++ b/apps/cloud/app/composables/useCheckoutReturn.ts
@@ -0,0 +1,73 @@
+import type { MaybeRefOrGetter } from 'vue'
+export function useCheckoutReturn(
+ workspaceId: MaybeRefOrGetter<number>,
+ refresh: () => Promise<void>,
+) {
+ const route = useRoute(),
+ state = ref<
+ 'idle' | 'checking' | 'pending' | 'completed' | 'failed' | 'expired'
+ >(typeof route.query.checkout === 'string' ? 'checking' : 'idle')
+ let generation = 0,
+ alive = true,
+ timer: ReturnType<typeof setTimeout> | undefined
+ async function check() {
+ const checkoutId =
+ typeof route.query.checkout === 'string' ? route.query.checkout : '',
+ id = toValue(workspaceId)
+ const current = ++generation
+ if (timer) clearTimeout(timer)
+ if (!checkoutId || !id) {
+ state.value = 'idle'
+ return
+ }
+ state.value = 'checking'
+ async function poll(attempt: number) {
+ if (!alive || current !== generation) return
+ try {
+ const result = await $fetch<{ state: string }>(
+ '/api/billing/payments',
+ {
+ method: 'POST',
+ body: { action: 'refresh', workspaceId: id, checkoutId },
+ },
+ )
+ if (!alive || current !== generation) return
+ await refresh()
+ if (!alive || current !== generation) return
+ if (result.state === 'completed') {
+ state.value = 'completed'
+ return
+ }
+ if (result.state === 'expired') {
+ state.value = 'expired'
+ return
+ }
+ } catch (e: any) {
+ if (!alive || current !== generation) return
+ if ([400, 401, 403, 404].includes(e?.statusCode ?? e?.status)) {
+ state.value = 'failed'
+ return
+ }
+ }
+ if (attempt >= 7) {
+ state.value = 'pending'
+ return
+ }
+ timer = setTimeout(() => void poll(attempt + 1), 5000)
+ }
+ await poll(0)
+ }
+ onMounted(() => {
+ watch(
+ () => [route.query.checkout, toValue(workspaceId)],
+ () => void check(),
+ { immediate: true },
+ )
+ })
+ onBeforeUnmount(() => {
+ alive = false
+ generation++
+ if (timer) clearTimeout(timer)
+ })
+ return { state, retry: check }
+}
diff --git a/apps/cloud/app/composables/useCloudLinks.ts b/apps/cloud/app/composables/useCloudLinks.ts
index 4a60f246..79fb23a7 100644
--- a/apps/cloud/app/composables/useCloudLinks.ts
+++ b/apps/cloud/app/composables/useCloudLinks.ts
@@ -9,6 +9,6 @@ export function useCloudLinks() {
signin: portal + '/signin',
signup: portal + '/signup',
redeem: portal + '/account/redeem',
- portalPricing: portal ? portal + '/pricing' : '/pricing?portal=1',
+ portalPricing: portal + '/account/plan#plans',
}
}
diff --git a/apps/cloud/app/composables/useCloudPayments.ts b/apps/cloud/app/composables/useCloudPayments.ts
new file mode 100644
index 00000000..b4a5893f
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudPayments.ts
@@ -0,0 +1,63 @@
+import type { MaybeRefOrGetter } from 'vue'
+export function useCloudPayments(
+ workspaceId: MaybeRefOrGetter<number | string>,
+) {
+ const { t } = useI18n(),
+ data = ref<any>(),
+ busy = ref(false),
+ error = ref('')
+ let generation = 0,
+ alive = true
+ async function refresh() {
+ const current = ++generation,
+ id = Number(toValue(workspaceId))
+ if (!id) return
+ try {
+ const result = await $fetch('/api/billing/payments', {
+ query: { workspaceId: id },
+ })
+ if (alive && current === generation) {
+ data.value = result
+ error.value = ''
+ }
+ } catch {
+ if (alive && current === generation)
+ error.value = t('cloud.payments.failed')
+ }
+ }
+ watch(
+ () => toValue(workspaceId),
+ () => {
+ data.value = null
+ error.value = ''
+ void refresh()
+ },
+ )
+ onMounted(refresh)
+ onBeforeUnmount(() => {
+ alive = false
+ generation++
+ })
+ useIntervalFn(() => {
+ if (document.visibilityState === 'visible') void refresh()
+ }, 15000)
+ async function portal() {
+ if (busy.value) return
+ busy.value = true
+ error.value = ''
+ const id = Number(toValue(workspaceId))
+ try {
+ const result = await $fetch<{ url: string }>('/api/billing/payments', {
+ method: 'POST',
+ body: { action: 'portal', workspaceId: id },
+ })
+ if (alive && id === Number(toValue(workspaceId)))
+ await navigateTo(result.url, { external: true })
+ } catch {
+ if (alive) error.value = t('cloud.payments.failed')
+ } finally {
+ busy.value = false
+ }
+ }
+ return { data, busy, error, refresh, portal }
+}
diff --git a/apps/cloud/app/composables/useWorkspaceBilling.ts b/apps/cloud/app/composables/useWorkspaceBilling.ts
index b75a58fb..bd89db77 100644
--- a/apps/cloud/app/composables/useWorkspaceBilling.ts
+++ b/apps/cloud/app/composables/useWorkspaceBilling.ts
@@ -1,47 +1,31 @@
export function useWorkspaceBilling(adminOnly = false) {
- const route = useRoute(),
- user = usePortalIdentity(),
- fetcher = useRequestFetch(),
- requested = Number(route.query.workspaceId) || 0,
- selected = ref(requested)
- type Workspace = { id: number; name: string; role: string }
- // A stable payload key covers both steps: the selected workspace is resolved
- // by the server before hydration, rather than changing the async-data key mid-fetch.
+ const user = usePortalIdentity(),
+ fetcher = useRequestFetch()
+ type Workspace = { id: number; name: string; role: string; owned?: number }
const billing = useAsyncData(
- `workspace-billing-${user.value?.id}-${adminOnly ? 'admin' : 'all'}-${requested}`,
+ `workspace-billing-${user.value?.id}`,
async () => {
const list = await fetcher<{ workspaces: Workspace[] }>(
'/api/billing/workspaces',
)
- const workspaces = list.workspaces.filter(
- (w) => !adminOnly || w.role === 'admin',
- )
- const id = workspaces.some((w) => w.id === selected.value)
- ? selected.value
- : (workspaces[0]?.id ?? 0)
+ const primary = list.workspaces.find((w) => w.owned) ?? list.workspaces[0]
+ const id = primary?.id ?? 0
const plan = id
? await fetcher<any>('/api/billing/plan', {
query: { workspaceId: id },
})
: null
return {
- workspaces,
+ workspaces: primary ? [primary] : [],
membershipCount: list.workspaces.length,
selected: id,
plan,
}
},
)
- watch(
- billing.data,
- (value) => {
- if (value) selected.value = value.selected
- },
- { immediate: true, flush: 'sync' },
+ const permitted = computed(
+ () => !adminOnly || billing.data.value?.plan?.workspace.role === 'admin',
)
- watch(selected, (id) => {
- if (id !== billing.data.value?.selected) void billing.refresh()
- })
onMounted(async () => {
await billing
if (billing.data.value?.membershipCount === 0 && !billing.error.value) {
@@ -54,13 +38,13 @@ export function useWorkspaceBilling(adminOnly = false) {
}
})
return {
- workspaces: computed(() => billing.data.value?.workspaces ?? []),
- selected,
- data: computed(() =>
- billing.data.value?.selected === selected.value
- ? billing.data.value.plan
- : null,
+ workspaces: computed(() =>
+ permitted.value ? (billing.data.value?.workspaces ?? []) : [],
+ ),
+ selected: computed(() =>
+ permitted.value ? (billing.data.value?.selected ?? 0) : 0,
),
+ data: computed(() => (permitted.value ? billing.data.value?.plan : null)),
error: billing.error,
listError: billing.error,
status: billing.status,
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
index 03f72940..ba059d11 100644
--- a/apps/cloud/app/pages/account/plan.vue
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -3,17 +3,26 @@ import { BILLING_LIMITS, allowance } from '../../utils/billing-format'
definePageMeta({ layout: 'portal' })
const { t, locale } = useI18n(),
links = useCloudLinks(),
- {
- workspaces,
- selected,
- data,
- error,
- listError,
- status,
- refresh,
- retry,
- ready,
- } = useWorkspaceBilling()
+ billing = useWorkspaceBilling()
+const { selected, data, error, listError, status, refresh, retry, ready } =
+ billing
+const payments = useCloudPayments(() => selected.value)
+const returned = useCheckoutReturn(
+ () => selected.value,
+ async () => {
+ await Promise.all([refresh(), payments.refresh()])
+ if (error.value || payments.error.value)
+ throw new Error('billing_refresh_failed')
+ },
+)
+const latestSubscription = computed(() => {
+ const rows = payments.data.value?.subscriptions ?? []
+ return (
+ rows.find((s: any) => !['expired', 'canceled'].includes(s.status)) ??
+ rows[0]
+ )
+})
+const quotaKeys = BILLING_LIMITS.filter((key) => key !== 'byos')
await ready
useSeoMeta({
title: t('cloud.billing.plan') + ' — ChronoFrame Cloud',
@@ -41,26 +50,21 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
<h1 class="cf-page-title">{{ $t('cloud.billing.plan') }}</h1>
<p class="cf-page-description">{{ $t('cloud.billing.planHelp') }}</p>
</div>
+ </div>
+ <p
+ v-if="returned.state.value !== 'idle'"
+ class="cf-notice"
+ role="status"
+ >
+ {{ $t('cloud.payments.return_' + returned.state.value) }}
<CloudButton
- as-child
- variant="secondary"
- ><NuxtLink :to="links.portalPricing">{{
- $t('cloud.billing.compare')
- }}</NuxtLink></CloudButton
+ v-if="['pending', 'failed'].includes(returned.state.value)"
+ variant="ghost"
+ @click="returned.retry"
+ >{{ $t('cloud.payments.checkAgain') }}</CloudButton
>
- </div>
- <label class="cf-workspace-picker"
- >{{ $t('cloud.billing.workspace')
- }}<select v-model="selected">
- <option
- v-for="w in workspaces"
- :key="w.id"
- :value="w.id"
- >
- {{ w.name }}
- </option>
- </select></label
- ><CloudCard
+ </p>
+ <CloudCard
v-if="error || listError"
role="alert"
><p>{{ $t('cloud.billing.failed') }}</p>
@@ -68,44 +72,67 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
$t('cloud.billing.retry')
}}</CloudButton></CloudCard
><template v-else-if="data"
- ><CloudCard class="cf-current-plan"
- ><div>
+ ><CloudCard class="cf-subscription-overview">
+ <div>
<span class="cf-eyebrow">{{ $t('cloud.billing.current') }}</span>
<h2>{{ data.plan.name }}</h2>
+ <p v-if="data.subscription.source === 'promotion'">
+ {{ $t('cloud.billing.signupOffer') }}
+ </p>
+ </div>
+ <div>
+ <span class="cf-field-hint">{{
+ $t('cloud.billing.subscriptionStatus')
+ }}</span>
+ <p>
+ {{
+ latestSubscription
+ ? $t('cloud.payments.status.' + latestSubscription.status)
+ : $t(
+ data.subscription.source === 'payment'
+ ? 'cloud.payments.checkingStatus'
+ : 'cloud.billing.includedPlan',
+ )
+ }}
+ </p>
+ </div>
+ <div>
+ <span class="cf-field-hint">{{ $t('cloud.billing.expiry') }}</span>
<p>
{{
data.subscription.expiresAt
- ? $t('cloud.billing.expires', {
- date: date(data.subscription.expiresAt),
- })
+ ? date(data.subscription.expiresAt)
: $t('cloud.billing.noExpiry')
}}
</p>
- <p
+ </div>
+ <div class="cf-plan-management">
+ <CloudButton
v-if="
- data.subscription.source === 'promotion' &&
- data.subscription.expiresAt !== null
+ payments.data.value?.canManage &&
+ payments.data.value.subscriptions.length
"
- class="cf-field-hint"
+ :loading="payments.busy.value"
+ @click="payments.portal"
+ >{{ $t('cloud.payments.manage') }}</CloudButton
>
- {{ $t('cloud.billing.signupOffer') }}
- </p>
- <p
- v-if="data.subscription.source !== 'payment'"
- class="cf-field-hint"
+ <CloudButton
+ v-if="data.workspace.role === 'admin'"
+ as-child
+ variant="secondary"
+ ><NuxtLink :to="links.redeem">{{
+ $t('cloud.billing.redeem')
+ }}</NuxtLink></CloudButton
>
- {{ $t('cloud.billing.noRenewal') }}
- </p>
</div>
- <CloudButton
- v-if="data.workspace.role === 'admin'"
- as-child
- ><NuxtLink :to="links.redeem + '?workspaceId=' + selected">{{
- $t('cloud.billing.redeem')
- }}</NuxtLink></CloudButton
- ></CloudCard
- >
- <CloudPaymentsPanel :workspace-id="selected" />
+ <p
+ v-if="payments.error.value"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ payments.error.value }}
+ </p>
+ </CloudCard>
<section>
<div class="cf-plan-section-heading">
<div>
@@ -128,24 +155,12 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
</div>
<div class="cf-quota-grid">
<article
- v-for="key in BILLING_LIMITS"
+ v-for="key in quotaKeys"
:key="key"
class="cf-quota-card"
>
<h3>{{ $t('cloud.billing.' + key) }}</h3>
- <template v-if="key === 'byos'"
- ><p>
- <strong>{{
- data.plan.limits.byos
- ? $t('cloud.billing.yes')
- : $t('cloud.billing.no')
- }}</strong>
- </p>
- <small>{{
- $t('cloud.billing.connectionCount', { count: data.usage.byos })
- }}</small></template
- >
- <p v-else-if="used(key) === null">
+ <p v-if="used(key) === null">
<strong>{{
allowance(key, data.plan.limits[key], locale)
}}</strong
@@ -192,6 +207,26 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
</div>
<p class="cf-field-hint">{{ $t('cloud.billing.usageHelp') }}</p>
</section>
+ <p class="cf-field-hint">
+ {{ $t('cloud.billing.byos') }}:
+ {{
+ data.plan.limits.byos
+ ? $t('cloud.billing.yes')
+ : $t('cloud.billing.no')
+ }}
+ · {{ $t('cloud.billing.connectionCount', { count: data.usage.byos }) }}
+ </p>
+ <section
+ id="plans"
+ class="cf-plan-options"
+ >
+ <CloudPricing
+ portal
+ embedded
+ :workspace-billing="billing"
+ :payment-controller="payments"
+ />
+ </section>
<details class="cf-billing-details">
<summary>{{ $t('cloud.billing.byosAllowances') }}</summary>
<dl>
@@ -205,8 +240,11 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
>
</dl>
</details>
- <section v-if="data.history.length">
- <h2>{{ $t('cloud.billing.history') }}</h2>
+ <details
+ v-if="data.history.length"
+ class="cf-billing-details"
+ >
+ <summary>{{ $t('cloud.billing.history') }}</summary>
<ol class="cf-subscription-history">
<li
v-for="(event, index) in data.history"
@@ -216,7 +254,7 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
><time>{{ date(event.created_at) }}</time>
</li>
</ol>
- </section></template
+ </details></template
>
<div
v-else
diff --git a/apps/cloud/app/pages/account/redeem.vue b/apps/cloud/app/pages/account/redeem.vue
index 1d48877e..c7194137 100644
--- a/apps/cloud/app/pages/account/redeem.vue
+++ b/apps/cloud/app/pages/account/redeem.vue
@@ -93,20 +93,6 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
@submit.prevent="inspect"
>
<label class="cf-field"
- >{{ $t('cloud.billing.workspace')
- }}<select
- v-model="selected"
- :disabled="busy || !!receipt"
- >
- <option
- v-for="w in workspaces"
- :key="w.id"
- :value="w.id"
- >
- {{ w.name }}
- </option>
- </select></label
- ><label class="cf-field"
>{{ $t('cloud.billing.code')
}}<CloudInput
v-model="code"
@@ -188,7 +174,7 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
: $t('cloud.billing.noExpiry')
}}
</p>
- <NuxtLink :to="'/account/plan?workspaceId=' + selected">{{
+ <NuxtLink :to="'/account/plan'">{{
$t('cloud.billing.viewPlan')
}}</NuxtLink>
</div>
diff --git a/apps/cloud/app/pages/pricing.vue b/apps/cloud/app/pages/pricing.vue
index 7f5fa205..d5148775 100644
--- a/apps/cloud/app/pages/pricing.vue
+++ b/apps/cloud/app/pages/pricing.vue
@@ -5,6 +5,11 @@ const route = useRoute(),
route.query.portal === '1',
{ t } = useI18n()
definePageMeta({ layout: false })
+if (portal)
+ await navigateTo(
+ { path: '/account/plan', hash: '#plans' },
+ { replace: true, redirectCode: 302 },
+ )
useSeoMeta({
title: t('cloud.billing.pricing') + ' — ChronoFrame Cloud',
description: t('cloud.billing.pricingHelp'),
@@ -12,13 +17,8 @@ useSeoMeta({
})
</script>
<template>
- <NuxtLayout
- v-if="portal"
- name="portal"
- ><CloudPricing portal
- /></NuxtLayout>
<div
- v-else
+ v-if="!portal"
class="cf-marketing"
>
<CloudMarketingHeader />
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index 98d51272..1dfff5b0 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -676,7 +676,14 @@
"event_signup_promotion": "Registration promotion activated",
"event_signup_default": "Registration plan assigned",
"signupOffer": "Your registration promotion is active until the expiration shown above.",
- "event_payment": "Subscription billing updated"
+ "event_payment": "Subscription billing updated",
+ "choosePlan": "Choose your plan",
+ "optionsHelp": "Compare current plans. Existing subscriptions keep their billing price.",
+ "subscriptionStatus": "Subscription status",
+ "includedPlan": "Included plan",
+ "recommended": "Recommended",
+ "noCharge": "No payment required",
+ "monthlyBilling": "Monthly billing"
},
"payments": {
"billing": "Subscription billing",
@@ -697,7 +704,15 @@
"paused": "Paused",
"canceled": "Canceled",
"unpaid": "Unpaid"
- }
+ },
+ "waiting": "Waiting for confirmation",
+ "checkingStatus": "Checking subscription…",
+ "return_checking": "Confirming your payment and updating your plan…",
+ "return_pending": "Your payment is still being confirmed. You can check again; do not start another checkout.",
+ "return_completed": "Payment confirmed. Your plan and allowances are up to date.",
+ "return_failed": "We could not verify this checkout. Check your account or try again.",
+ "return_expired": "This checkout has expired. You can start a new one from the plans below.",
+ "checkAgain": "Check payment status"
}
}
}
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 34ca9fc0..2c676df7 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -676,7 +676,14 @@
"event_signup_promotion": "注册活动套餐已开通",
"event_signup_default": "注册默认套餐已分配",
"signupOffer": "注册促销权益已生效,有效期见上方到期时间。",
- "event_payment": "订阅账单已更新"
+ "event_payment": "订阅账单已更新",
+ "choosePlan": "选择适合你的套餐",
+ "optionsHelp": "对比当前套餐权益;已有订阅的价格以账单为准。",
+ "subscriptionStatus": "订阅状态",
+ "includedPlan": "默认套餐",
+ "recommended": "推荐",
+ "noCharge": "无需付款",
+ "monthlyBilling": "按月计费"
},
"payments": {
"billing": "订阅账单",
@@ -697,7 +704,15 @@
"paused": "已暂停",
"canceled": "已取消",
"unpaid": "未付款"
- }
+ },
+ "waiting": "等待确认",
+ "checkingStatus": "正在核对订阅…",
+ "return_checking": "正在确认付款并更新套餐与额度…",
+ "return_pending": "付款仍在确认中,可以稍后再次检查,请勿重复发起付款。",
+ "return_completed": "付款已确认,套餐与额度已更新。",
+ "return_failed": "无法核验这笔付款,请检查登录账号或重试。",
+ "return_expired": "这笔付款已过期,可以在下方选择套餐重新发起。",
+ "checkAgain": "检查付款状态"
}
}
}
diff --git a/apps/cloud/server/api/billing/payments.post.ts b/apps/cloud/server/api/billing/payments.post.ts
index e54434a0..170471ae 100644
--- a/apps/cloud/server/api/billing/payments.post.ts
+++ b/apps/cloud/server/api/billing/payments.post.ts
@@ -1,6 +1,7 @@
import {
createPaymentCheckout,
createPaymentPortal,
+ refreshPaymentCheckout,
} from '../../../../../packages/platform/src/payments'
import {
definePlatformHandler,
@@ -29,6 +30,14 @@ export default definePlatformHandler(async (event) => {
},
config.portalOrigin,
)
+ if (b.action === 'refresh')
+ return refreshPaymentCheckout(
+ db,
+ config.storageSecret,
+ user.userId,
+ Number(b.workspaceId),
+ String(b.checkoutId),
+ )
if (b.action === 'portal')
return createPaymentPortal(
db,
diff --git a/apps/cloud/server/plugins/payments.ts b/apps/cloud/server/plugins/payments.ts
index 48bedf7c..5c4f0455 100644
--- a/apps/cloud/server/plugins/payments.ts
+++ b/apps/cloud/server/plugins/payments.ts
@@ -1,12 +1,20 @@
+import { syncPaymentProducts } from '../../../../packages/platform/src/payment-product-sync'
+import { expirePaymentEventPayloads } from '../../../../packages/platform/src/payment-events'
import { reconcilePayments } from '../../../../packages/platform/src/payments'
import type { PlatformD1 } from '@chronoframe/platform'
export default defineNitroPlugin((app) => {
app.hooks.hook('cloudflare:scheduled', async ({ env }) => {
const db = env.DB as PlatformD1 | undefined
- if (db)
+ if (db) {
+ await syncPaymentProducts(
+ db,
+ String(env.NUXT_PLATFORM_STORAGE_SECRET || ''),
+ ).catch(() => undefined)
+ await expirePaymentEventPayloads(db)
await reconcilePayments(
db,
String(env.NUXT_PLATFORM_STORAGE_SECRET || ''),
)
+ }
})
})
diff --git a/packages/platform/migrations/0023_payment_operations.sql b/packages/platform/migrations/0023_payment_operations.sql
new file mode 100644
index 00000000..42b1644a
--- /dev/null
+++ b/packages/platform/migrations/0023_payment_operations.sql
@@ -0,0 +1,11 @@
+ALTER TABLE platform_payment_settings ADD COLUMN auto_sync INTEGER NOT NULL DEFAULT 1 CHECK(auto_sync IN(0,1));
+ALTER TABLE platform_payment_settings ADD COLUMN catalog_revision INTEGER NOT NULL DEFAULT 1;
+ALTER TABLE platform_payment_settings ADD COLUMN payload_retention_days INTEGER NOT NULL DEFAULT 30 CHECK(payload_retention_days BETWEEN 1 AND 365);
+ALTER TABLE platform_payment_products ADD COLUMN sync_hash TEXT;
+CREATE TABLE platform_payment_event_payloads(event_id TEXT PRIMARY KEY REFERENCES platform_payment_events(id) ON DELETE CASCADE,ciphertext TEXT NOT NULL,received_at INTEGER NOT NULL);
+CREATE INDEX platform_payment_payload_retention ON platform_payment_event_payloads(received_at);
+CREATE TABLE platform_payment_product_sync(plan_id TEXT NOT NULL REFERENCES platform_plans(id) ON DELETE CASCADE,interval INTEGER NOT NULL CHECK(interval IN(1,3)),desired_revision INTEGER NOT NULL,catalog_revision INTEGER NOT NULL DEFAULT 1,state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN('pending','syncing','synced','failed','disabled')),attempts INTEGER NOT NULL DEFAULT 0,available_at INTEGER NOT NULL DEFAULT 0,lease_token TEXT,lease_until INTEGER,product_id TEXT,sync_hash TEXT,error TEXT,updated_at INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(plan_id,interval));
+CREATE INDEX platform_payment_product_sync_due ON platform_payment_product_sync(state,available_at);
+CREATE TABLE platform_payment_product_versions(product_id TEXT PRIMARY KEY,plan_id TEXT NOT NULL REFERENCES platform_plans(id),interval INTEGER NOT NULL,price INTEGER NOT NULL,currency TEXT NOT NULL,snapshot_json TEXT NOT NULL,sync_hash TEXT NOT NULL,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);
+INSERT INTO platform_payment_product_sync(plan_id,interval,desired_revision) SELECT id,1,revision FROM platform_plans;
+INSERT INTO platform_payment_product_sync(plan_id,interval,desired_revision) SELECT id,3,revision FROM platform_plans;
diff --git a/packages/platform/src/account-purge.ts b/packages/platform/src/account-purge.ts
index 50839c15..82009822 100644
--- a/packages/platform/src/account-purge.ts
+++ b/packages/platform/src/account-purge.ts
@@ -197,6 +197,14 @@ export async function purgeAccounts(
)
.bind(id, id),
)
+ // Callback bodies can contain the erased purchaser's personal data even on another owner's workspace.
+ statements.push(
+ db
+ .prepare(
+ 'DELETE FROM platform_payment_event_payloads WHERE event_id IN(SELECT e.id FROM platform_payment_events e WHERE e.reference_id IN(SELECT id FROM platform_payment_checkouts WHERE user_id=?) OR e.object_id IN(SELECT provider_id FROM platform_payment_checkouts WHERE user_id=?) OR e.object_id IN(SELECT s.id FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE c.user_id=?))',
+ )
+ .bind(id, id, id),
+ )
// Payment resources were closed upstream. Retain other owners' ledgers without the erased purchaser identity.
statements.push(
db
diff --git a/packages/platform/src/billing.ts b/packages/platform/src/billing.ts
index 488ddaa7..61f84bf0 100644
--- a/packages/platform/src/billing.ts
+++ b/packages/platform/src/billing.ts
@@ -80,12 +80,17 @@ export async function pricingCatalog(db: PlatformD1) {
}
}
export async function billingWorkspaces(db: PlatformD1, userId: number) {
- return allRows<{ id: number; name: string; role: 'admin' | 'member' }>(
+ return allRows<{
+ id: number
+ name: string
+ role: 'admin' | 'member'
+ owned: number
+ }>(
db
.prepare(
- "SELECT w.id,w.name,m.role FROM platform_workspaces w JOIN platform_memberships m ON m.workspace_id=w.id WHERE m.user_id=? AND m.role IN('admin','member') ORDER BY w.id",
+ "SELECT w.id,w.name,m.role,CASE WHEN w.owner_user_id=? THEN 1 ELSE 0 END AS owned FROM platform_workspaces w JOIN platform_memberships m ON m.workspace_id=w.id WHERE m.user_id=? AND m.role IN('admin','member') ORDER BY owned DESC,w.id",
)
- .bind(userId),
+ .bind(userId, userId),
)
}
export async function workspaceBilling(
diff --git a/packages/platform/src/payment-events.ts b/packages/platform/src/payment-events.ts
new file mode 100644
index 00000000..c01194f5
--- /dev/null
+++ b/packages/platform/src/payment-events.ts
@@ -0,0 +1,135 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows, SubscriptionError } from './subscriptions.ts'
+const enc = new TextEncoder()
+function fail(code: string, status = 400): never {
+ throw new SubscriptionError(status, code)
+}
+function base64(bytes: Uint8Array) {
+ let value = ''
+ for (let i = 0; i < bytes.length; i += 8192)
+ value += String.fromCharCode(...bytes.subarray(i, i + 8192))
+ return btoa(value)
+}
+const bytes = (value: string) =>
+ Uint8Array.from(atob(value), (v) => v.charCodeAt(0))
+async function payloadKey(root: string, eventId: string) {
+ if (root.length < 32) fail('payment_encryption_unavailable', 503)
+ const material = await crypto.subtle.importKey(
+ 'raw',
+ enc.encode(root),
+ 'HKDF',
+ false,
+ ['deriveKey'],
+ )
+ return crypto.subtle.deriveKey(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: enc.encode('chronoframe-payment-payloads-v1'),
+ info: enc.encode(eventId),
+ },
+ material,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ ['encrypt', 'decrypt'],
+ )
+}
+export async function sealPaymentEventPayload(
+ root: string,
+ eventId: string,
+ body: Uint8Array,
+) {
+ if (body.length > 65536) fail('payment_payload_too_large', 413)
+ const nonce = crypto.getRandomValues(new Uint8Array(12))
+ const ciphertext = await crypto.subtle.encrypt(
+ { name: 'AES-GCM', iv: nonce, additionalData: enc.encode(eventId) },
+ await payloadKey(root, eventId),
+ Uint8Array.from(body),
+ )
+ return JSON.stringify([base64(nonce), base64(new Uint8Array(ciphertext))])
+}
+export async function paymentEventPayload(
+ db: PlatformD1,
+ root: string,
+ eventId: string,
+ now = Date.now(),
+) {
+ if (!/^[a-zA-Z0-9_-]{1,512}$/.test(eventId)) fail('payment_event_invalid')
+ const row = await db
+ .prepare(
+ 'SELECT p.ciphertext,p.received_at FROM platform_payment_event_payloads p CROSS JOIN platform_payment_settings s WHERE p.event_id=? AND s.id=1 AND p.received_at>=? - s.payload_retention_days*86400000',
+ )
+ .bind(eventId, now)
+ .first<any>()
+ if (!row) return { available: false, payload: null }
+ try {
+ const [nonce, ciphertext] = JSON.parse(row.ciphertext)
+ const plain = await crypto.subtle.decrypt(
+ {
+ name: 'AES-GCM',
+ iv: bytes(nonce),
+ additionalData: enc.encode(eventId),
+ },
+ await payloadKey(root, eventId),
+ bytes(ciphertext),
+ )
+ return {
+ available: true,
+ receivedAt: row.received_at,
+ payload: JSON.parse(new TextDecoder().decode(plain)),
+ }
+ } catch {
+ return fail('payment_payload_unavailable', 503)
+ }
+}
+export async function paymentEventPage(db: PlatformD1, cursor?: string) {
+ let at = Number.MAX_SAFE_INTEGER,
+ id = '~'
+ if (cursor && cursor.length > 1024) fail('payment_cursor_invalid')
+ if (cursor) {
+ try {
+ const value = JSON.parse(atob(cursor))
+ if (
+ !Number.isSafeInteger(value.at) ||
+ value.at < 1 ||
+ typeof value.id !== 'string' ||
+ !/^[a-zA-Z0-9_-]{1,512}$/.test(value.id)
+ )
+ throw 0
+ at = value.at
+ id = value.id
+ } catch {
+ return fail('payment_cursor_invalid')
+ }
+ }
+ const rows = await allRows<any>(
+ db
+ .prepare(
+ 'SELECT id,type,state,attempts,error,available_at,created_at FROM platform_payment_events WHERE created_at<? OR (created_at=? AND id<?) ORDER BY created_at DESC,id DESC LIMIT 26',
+ )
+ .bind(at, at, id),
+ )
+ const events = rows.slice(0, 25),
+ last = events[events.length - 1]
+ return {
+ events,
+ nextCursor:
+ rows.length > 25
+ ? btoa(JSON.stringify({ at: last.created_at, id: last.id }))
+ : null,
+ }
+}
+export async function expirePaymentEventPayloads(
+ db: PlatformD1,
+ now = Date.now(),
+) {
+ const settings = await db
+ .prepare(
+ 'SELECT payload_retention_days FROM platform_payment_settings WHERE id=1',
+ )
+ .first<any>()
+ await db
+ .prepare('DELETE FROM platform_payment_event_payloads WHERE received_at<?')
+ .bind(now - Number(settings?.payload_retention_days ?? 30) * 86400000)
+ .run()
+}
diff --git a/packages/platform/src/payment-product-sync.ts b/packages/platform/src/payment-product-sync.ts
new file mode 100644
index 00000000..b844f481
--- /dev/null
+++ b/packages/platform/src/payment-product-sync.ts
@@ -0,0 +1,358 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows, SubscriptionError } from './subscriptions.ts'
+import { LIMIT_KEYS, validatePolicy } from './entitlements.ts'
+import {
+ creemRequest,
+ paymentSecrets,
+ paymentSettings,
+ type PaymentFetch,
+} from './payments.ts'
+const enc = new TextEncoder()
+async function hash(value: string) {
+ return Array.from(
+ new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(value))),
+ (b) => b.toString(16).padStart(2, '0'),
+ ).join('')
+}
+const names: Record<string, string> = {
+ byos: 'Custom S3 storage',
+ storageBytes: 'Platform storage',
+ fileBytes: 'Maximum file size',
+ sites: 'Sites',
+ customDomains: 'Custom domains',
+ photos: 'Photographs',
+ monthlyBytes: 'Monthly uploads',
+}
+function allowance(key: string, value: number) {
+ if (key === 'byos') return value ? 'Included' : 'Not included'
+ if (key.endsWith('Bytes')) {
+ if (!value) return '0 B'
+ const i = Math.min(3, Math.floor(Math.log(value) / Math.log(1024)))
+ return `${Number((value / 1024 ** i).toFixed(2))} ${['B', 'KiB', 'MiB', 'GiB'][i]}`
+ }
+ return String(value)
+}
+function condition(c: any): string {
+ if (c.all) return '(' + c.all.map(condition).join(' AND ') + ')'
+ if (c.any) return '(' + c.any.map(condition).join(' OR ') + ')'
+ const fields: Record<string, string> = {
+ storageMode: 'Storage type',
+ workspaceAgeDays: 'Workspace age in days',
+ emailVerified: 'Verified email',
+ }
+ return `${fields[c.field]} ${{ eq: '=', gte: '≥', lte: '≤' }[c.op as 'eq']} ${c.value}`
+}
+export function paymentProductSnapshot(plan: any, interval: number) {
+ const policy = validatePolicy(JSON.parse(plan.policy_json)),
+ price = interval === 1 ? plan.monthly_price : plan.quarterly_price
+ const description = [
+ plan.description || plan.name,
+ '',
+ ...LIMIT_KEYS.map((k) => `${names[k]}: ${allowance(k, policy.limits[k])}`),
+ ...policy.rules.map(
+ (r) =>
+ `When ${condition(r.when)}: ${Object.entries(r.limits)
+ .map(([k, v]) => `${names[k]} ${allowance(k, Number(v))}`)
+ .join('; ')}`,
+ ),
+ ].join('\n')
+ return {
+ planId: plan.id,
+ interval,
+ policy,
+ product: {
+ name: `${plan.name} · ${interval === 1 ? 'Monthly' : 'Quarterly'}`,
+ description,
+ price,
+ currency: plan.currency,
+ billing_type: 'recurring',
+ billing_period: interval === 1 ? 'every-month' : 'every-three-months',
+ tax_mode: 'inclusive',
+ tax_category: 'saas',
+ },
+ }
+}
+/** Source revisions are scanned durably, so a process crash after a plan save cannot lose synchronization. */
+export async function queuePaymentProductSync(db: PlatformD1) {
+ await db
+ .prepare(
+ "INSERT INTO platform_payment_product_sync(plan_id,interval,desired_revision,catalog_revision) SELECT p.id,i.period,p.revision,s.catalog_revision FROM platform_plans p CROSS JOIN (SELECT 1 AS period UNION ALL SELECT 3) i CROSS JOIN platform_payment_settings s WHERE s.id=1 ON CONFLICT(plan_id,interval) DO UPDATE SET desired_revision=excluded.desired_revision,catalog_revision=excluded.catalog_revision,state='pending',attempts=0,available_at=0,error=NULL WHERE desired_revision<>excluded.desired_revision OR catalog_revision<>excluded.catalog_revision",
+ )
+ .run()
+}
+export async function paymentProductSyncStatus(db: PlatformD1) {
+ return allRows<any>(
+ db.prepare(
+ "SELECT p.id AS plan_id,p.name,i.period AS interval,CASE WHEN j.desired_revision IS NOT p.revision OR j.catalog_revision IS NOT s.catalog_revision THEN 'pending' ELSE COALESCE(j.state,'pending') END AS state,j.error,j.product_id,j.attempts,j.updated_at FROM platform_plans p CROSS JOIN (SELECT 1 AS period UNION ALL SELECT 3) i CROSS JOIN platform_payment_settings s LEFT JOIN platform_payment_product_sync j ON j.plan_id=p.id AND j.interval=i.period WHERE s.id=1 ORDER BY p.sort_order,p.id,i.period",
+ ),
+ )
+}
+/** The lease and both source revisions fence publication; existing subscription prices are never mutated. */
+export async function syncPaymentProducts(
+ db: PlatformD1,
+ root: string,
+ transport: PaymentFetch = fetch,
+ now = Date.now(),
+ limit = 2,
+) {
+ const settings = await paymentSettings(db)
+ if (!settings.configured || !settings.autoSync) return { processed: 0 }
+ const credentials = await paymentSecrets(db, root),
+ credentialHash = await hash(credentials.apiKey)
+ await queuePaymentProductSync(db)
+ // Non-purchasable plans need no network calls and must not consume the paid-job budget.
+ const inactive =
+ 'EXISTS(SELECT 1 FROM platform_plans p WHERE p.id=plan_id AND (p.active=0 OR p.listed=0 OR CASE WHEN interval=1 THEN p.monthly_price ELSE p.quarterly_price END IS NULL OR CASE WHEN interval=1 THEN p.monthly_price ELSE p.quarterly_price END=0))'
+ await db.batch([
+ db.prepare(
+ `UPDATE platform_payment_products SET enabled=0,revision=revision+1 WHERE enabled<>0 AND ${inactive}`,
+ ),
+ db
+ .prepare(
+ `UPDATE platform_payment_product_sync SET state='disabled',error=NULL,updated_at=? WHERE state<>'disabled' AND (lease_until IS NULL OR lease_until<?) AND ${inactive}`,
+ )
+ .bind(now, now),
+ ])
+ await db
+ .prepare(
+ "UPDATE platform_payment_product_sync SET state='failed',error='payment_product_sync_exhausted',lease_token=NULL,lease_until=NULL WHERE state='syncing' AND attempts>=8 AND (lease_until IS NULL OR lease_until<?)",
+ )
+ .bind(now)
+ .run()
+ const jobs = await allRows<any>(
+ db
+ .prepare(
+ "SELECT * FROM platform_payment_product_sync WHERE state IN('pending','syncing') AND attempts<8 AND available_at<=? AND (lease_until IS NULL OR lease_until<?) ORDER BY available_at,plan_id,interval LIMIT ?",
+ )
+ .bind(now, now, Math.max(1, Math.min(20, limit))),
+ )
+ let processed = 0
+ const wallStart = Date.now(),
+ clock = () => now + Date.now() - wallStart
+ for (const job of jobs) {
+ const token = crypto.randomUUID(),
+ started = clock()
+ const claim = await db
+ .prepare(
+ "UPDATE platform_payment_product_sync SET state='syncing',lease_token=?,lease_until=?,attempts=attempts+1 WHERE plan_id=? AND interval=? AND desired_revision=? AND catalog_revision=? AND state IN('pending','syncing') AND attempts<8 AND available_at<=? AND (lease_until IS NULL OR lease_until<?) RETURNING attempts",
+ )
+ .bind(
+ token,
+ started + 60000,
+ job.plan_id,
+ job.interval,
+ job.desired_revision,
+ job.catalog_revision,
+ started,
+ started,
+ )
+ .first<any>()
+ if (!claim) continue
+ const fence =
+ "EXISTS(SELECT 1 FROM platform_payment_product_sync j JOIN platform_plans p ON p.id=j.plan_id CROSS JOIN platform_payment_settings s WHERE j.plan_id=? AND j.interval=? AND j.lease_token=? AND j.lease_until>? AND j.state='syncing' AND j.desired_revision=p.revision AND j.catalog_revision=s.catalog_revision AND s.id=1 AND s.auto_sync=1 AND j.desired_revision=? AND j.catalog_revision=?)"
+ const fenced = () => [
+ job.plan_id,
+ job.interval,
+ token,
+ clock(),
+ job.desired_revision,
+ job.catalog_revision,
+ ]
+ try {
+ const plan = await db
+ .prepare('SELECT * FROM platform_plans WHERE id=?')
+ .bind(job.plan_id)
+ .first<any>()
+ if (!plan || plan.revision !== job.desired_revision) continue
+ const snapshot = paymentProductSnapshot(plan, job.interval),
+ body = snapshot.product
+ if (
+ !plan.active ||
+ !plan.listed ||
+ body.price === null ||
+ body.price === 0
+ ) {
+ await db.batch([
+ db
+ .prepare(
+ `UPDATE platform_payment_products SET enabled=0,revision=revision+1 WHERE plan_id=? AND interval=? AND ${fence}`,
+ )
+ .bind(plan.id, job.interval, ...fenced()),
+ db
+ .prepare(
+ `UPDATE platform_payment_product_sync SET state='disabled',error=NULL,updated_at=? WHERE plan_id=? AND interval=? AND ${fence}`,
+ )
+ .bind(clock(), plan.id, job.interval, ...fenced()),
+ ])
+ processed++
+ continue
+ }
+ if (!Number.isSafeInteger(body.price) || body.price < 100)
+ throw new SubscriptionError(400, 'payment_product_minimum_price')
+ const snapshotJSON = JSON.stringify(snapshot),
+ businessHash = await hash(snapshotJSON),
+ syncHash = await hash(snapshotJSON + credentialHash)
+ const mapping = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_products WHERE plan_id=? AND interval=?',
+ )
+ .bind(plan.id, job.interval)
+ .first<any>()
+ let productId: string | undefined = mapping?.product_id
+ const samePrice =
+ mapping?.price === body.price && mapping?.currency === body.currency
+ if (mapping?.sync_hash !== syncHash) {
+ let existing: any
+ if (samePrice && productId) {
+ try {
+ existing = await creemRequest(
+ credentials,
+ '/v1/products?product_id=' + encodeURIComponent(productId),
+ undefined,
+ transport,
+ )
+ } catch (e) {
+ if (
+ Number((e as { providerStatus?: number }).providerStatus) !== 404
+ )
+ throw e
+ }
+ }
+ if (
+ existing?.mode === 'test' &&
+ existing.id === productId &&
+ existing.price === body.price &&
+ existing.currency === body.currency &&
+ existing.billing_type === 'recurring' &&
+ existing.billing_period === body.billing_period &&
+ !Number(existing.trial_period_days ?? 0) &&
+ !existing.usage_prices?.length &&
+ (!existing.status || existing.status === 'active')
+ ) {
+ await creemRequest(
+ credentials,
+ '/v1/products/' + encodeURIComponent(productId!),
+ { name: body.name, description: body.description },
+ transport,
+ { method: 'PATCH' },
+ )
+ } else {
+ const created = await creemRequest(
+ credentials,
+ '/v1/products',
+ body,
+ transport,
+ { idempotencyKey: 'cfp_' + businessHash },
+ )
+ if (
+ typeof created?.id !== 'string' ||
+ !/^prod_[a-zA-Z0-9_-]{1,150}$/.test(created.id)
+ )
+ throw new SubscriptionError(502, 'payment_product_response_invalid')
+ productId = created.id
+ }
+ const actual = await creemRequest(
+ credentials,
+ '/v1/products?product_id=' + encodeURIComponent(productId!),
+ undefined,
+ transport,
+ )
+ if (
+ actual.id !== productId ||
+ actual.mode !== 'test' ||
+ actual.price !== body.price ||
+ actual.currency !== body.currency ||
+ actual.billing_type !== 'recurring' ||
+ actual.billing_period !== body.billing_period ||
+ (actual.status && actual.status !== 'active') ||
+ Number(actual.trial_period_days ?? 0) > 0 ||
+ actual.usage_prices?.length
+ )
+ throw new SubscriptionError(422, 'payment_product_mismatch')
+ }
+ if (!productId)
+ throw new SubscriptionError(502, 'payment_product_response_invalid')
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO platform_payment_product_versions(product_id,plan_id,interval,price,currency,snapshot_json,sync_hash,created_at,updated_at) SELECT ?,?,?,?,?,?,?,?,? WHERE ${fence} ON CONFLICT(product_id) DO UPDATE SET snapshot_json=excluded.snapshot_json,sync_hash=excluded.sync_hash,updated_at=excluded.updated_at`,
+ )
+ .bind(
+ productId,
+ plan.id,
+ job.interval,
+ body.price,
+ body.currency,
+ snapshotJSON,
+ syncHash,
+ clock(),
+ clock(),
+ ...fenced(),
+ ),
+ db
+ .prepare(
+ `INSERT INTO platform_payment_products(plan_id,interval,product_id,price,currency,enabled,sync_hash) SELECT ?,?,?,?,?,1,? WHERE ${fence} ON CONFLICT(plan_id,interval) DO UPDATE SET product_id=excluded.product_id,price=excluded.price,currency=excluded.currency,enabled=1,sync_hash=excluded.sync_hash,revision=platform_payment_products.revision+1`,
+ )
+ .bind(
+ plan.id,
+ job.interval,
+ productId,
+ body.price,
+ body.currency,
+ syncHash,
+ ...fenced(),
+ ),
+ db
+ .prepare(
+ `UPDATE platform_payment_product_sync SET state='synced',product_id=?,sync_hash=?,error=NULL,updated_at=? WHERE plan_id=? AND interval=? AND ${fence}`,
+ )
+ .bind(
+ productId,
+ syncHash,
+ clock(),
+ plan.id,
+ job.interval,
+ ...fenced(),
+ ),
+ ])
+ processed++
+ } catch (e) {
+ const code =
+ e instanceof SubscriptionError ? e.code : 'payment_product_sync_failed'
+ const providerStatus = Number(
+ (e as { providerStatus?: number })?.providerStatus,
+ )
+ const diagnostic =
+ code +
+ (Number.isInteger(providerStatus) &&
+ providerStatus >= 100 &&
+ providerStatus <= 599
+ ? ':' + providerStatus
+ : '')
+ await db
+ .prepare(
+ "UPDATE platform_payment_product_sync SET state=?,error=?,available_at=?,updated_at=? WHERE plan_id=? AND interval=? AND lease_token=? AND state='syncing' AND desired_revision=? AND catalog_revision=?",
+ )
+ .bind(
+ claim.attempts >= 8 ? 'failed' : 'pending',
+ diagnostic,
+ clock() + Math.min(3600000, 60000 * 2 ** (claim.attempts - 1)),
+ clock(),
+ job.plan_id,
+ job.interval,
+ token,
+ job.desired_revision,
+ job.catalog_revision,
+ )
+ .run()
+ } finally {
+ await db
+ .prepare(
+ 'UPDATE platform_payment_product_sync SET lease_token=NULL,lease_until=NULL WHERE plan_id=? AND interval=? AND lease_token=?',
+ )
+ .bind(job.plan_id, job.interval, token)
+ .run()
+ }
+ }
+ return { processed }
+}
diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.ts
index bb542657..94a303f1 100644
--- a/packages/platform/src/payments.ts
+++ b/packages/platform/src/payments.ts
@@ -1,3 +1,4 @@
+import { sealPaymentEventPayload } from './payment-events.ts'
import type { PlatformD1 } from './index.ts'
import {
allRows,
@@ -99,11 +100,14 @@ export async function paymentSecrets(
export async function paymentSettings(db: PlatformD1) {
const row = await db
.prepare(
- 'SELECT enabled,environment,workspace_ids_json,revision,credentials_ciphertext IS NOT NULL AS configured FROM platform_payment_settings WHERE id=1',
+ 'SELECT enabled,environment,workspace_ids_json,revision,catalog_revision,auto_sync,payload_retention_days,credentials_ciphertext IS NOT NULL AS configured FROM platform_payment_settings WHERE id=1',
)
.first<any>()
return {
enabled: !!row.enabled,
+ autoSync: !!row.auto_sync,
+ catalogRevision: Number(row.catalog_revision),
+ payloadRetentionDays: Number(row.payload_retention_days),
environment: 'test' as const,
workspaceIds: JSON.parse(row.workspace_ids_json) as number[],
revision: Number(row.revision),
@@ -115,16 +119,20 @@ export async function creemRequest(
path: string,
body?: unknown,
transport: PaymentFetch = fetch,
+ options: { method?: 'PATCH'; idempotencyKey?: string } = {},
) {
if (!credentials.apiKey.startsWith('creem_test_') || !path.startsWith('/v1/'))
fail(400, 'payment_test_mode_required')
let response: Response
try {
response = await transport(CREEM_TEST_API + path, {
- method: body === undefined ? 'GET' : 'POST',
+ method: options.method ?? (body === undefined ? 'GET' : 'POST'),
headers: {
'x-api-key': credentials.apiKey,
'content-type': 'application/json',
+ ...(options.idempotencyKey
+ ? { 'Idempotency-Key': options.idempotencyKey }
+ : {}),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
redirect: 'manual',
@@ -266,7 +274,7 @@ export async function paymentStatus(
settings.workspaceIds.includes(workspaceId)
? await allRows<any>(
db.prepare(
- 'SELECT m.plan_id,m.interval FROM platform_payment_products m JOIN platform_plans p ON p.id=m.plan_id WHERE m.enabled=1 AND p.active=1 AND p.listed=1 AND p.currency=m.currency AND m.price=CASE WHEN m.interval=1 THEN p.monthly_price ELSE p.quarterly_price END',
+ "SELECT m.plan_id,m.interval FROM platform_payment_products m JOIN platform_plans p ON p.id=m.plan_id WHERE m.enabled=1 AND p.active=1 AND p.listed=1 AND p.currency=m.currency AND m.price=CASE WHEN m.interval=1 THEN p.monthly_price ELSE p.quarterly_price END AND ((SELECT auto_sync FROM platform_payment_settings WHERE id=1)=0 OR EXISTS(SELECT 1 FROM platform_payment_product_sync j WHERE j.plan_id=p.id AND j.interval=m.interval AND j.state='synced' AND j.desired_revision=p.revision AND j.product_id=m.product_id AND j.catalog_revision=(SELECT catalog_revision FROM platform_payment_settings WHERE id=1)))",
),
)
: []
@@ -407,6 +415,16 @@ export async function createPaymentCheckout(
.bind(input.planId, input.interval)
.first<any>()
if (!mapping) fail(400, 'payment_product_unavailable')
+ if (
+ settings.autoSync &&
+ !(await db
+ .prepare(
+ "SELECT 1 FROM platform_payment_product_sync j JOIN platform_plans p ON p.id=j.plan_id WHERE j.plan_id=? AND j.interval=? AND j.state='synced' AND j.desired_revision=p.revision AND j.product_id=? AND j.catalog_revision=(SELECT catalog_revision FROM platform_payment_settings WHERE id=1)",
+ )
+ .bind(input.planId, input.interval, mapping.product_id)
+ .first())
+ )
+ fail(409, 'payment_product_sync_pending')
await paymentRequestBudget(db, userId, now)
const credentials = await paymentSecrets(db, rootKey)
const product = await validatePaymentProduct(
@@ -650,20 +668,27 @@ export async function receivePaymentEvent(
)
const ref =
event.object.request_id || event.object.metadata?.chronoframe_checkout_id
- await db
- .prepare(
- 'INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,reference_id,created_at,state,available_at) VALUES(?,?,?,?,?,?,?)',
- )
- .bind(
- event.id,
- type,
- event.object.id,
- identifier(ref) ? ref : null,
- event.created_at,
- supported ? 'pending' : 'ignored',
- now,
- )
- .run()
+ const payload = await sealPaymentEventPayload(rootKey, event.id, body)
+ await db.batch([
+ db
+ .prepare(
+ 'INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,reference_id,created_at,state,available_at) VALUES(?,?,?,?,?,?,?)',
+ )
+ .bind(
+ event.id,
+ type,
+ event.object.id,
+ identifier(ref) ? ref : null,
+ event.created_at,
+ supported ? 'pending' : 'ignored',
+ now,
+ ),
+ db
+ .prepare(
+ 'INSERT OR IGNORE INTO platform_payment_event_payloads(event_id,ciphertext,received_at) VALUES(?,?,?)',
+ )
+ .bind(event.id, payload, now),
+ ])
return { received: true }
}
@@ -1011,6 +1036,7 @@ export async function processPaymentEvents(
transport: PaymentFetch = fetch,
now = Date.now(),
limit = 5,
+ onlyId?: string,
) {
await db
.prepare(
@@ -1021,9 +1047,9 @@ export async function processPaymentEvents(
const rows = await allRows<any>(
db
.prepare(
- "SELECT * FROM platform_payment_events WHERE state='pending' AND attempts<8 AND available_at<=? AND (lease_until IS NULL OR lease_until<?) ORDER BY available_at,id LIMIT ?",
+ "SELECT * FROM platform_payment_events WHERE state='pending' AND attempts<8 AND available_at<=? AND (lease_until IS NULL OR lease_until<?) AND (? IS NULL OR id=?) ORDER BY available_at,id LIMIT ?",
)
- .bind(now, now, limit),
+ .bind(now, now, onlyId ?? null, onlyId ?? null, limit),
)
let processed = 0
for (const row of rows) {
@@ -1314,3 +1340,54 @@ export async function closeAccountPayments(
}
return true
}
+
+/** A return only requests authoritative reconciliation; query parameters never grant access. */
+export async function refreshPaymentCheckout(
+ db: PlatformD1,
+ rootKey: string,
+ userId: number,
+ workspaceId: number,
+ checkoutId: string,
+ transport: PaymentFetch = fetch,
+ now = Date.now(),
+) {
+ await paymentMember(db, userId, workspaceId, true)
+ if (!identifier(checkoutId)) fail(400, 'payment_checkout_invalid')
+ await paymentRequestBudget(db, userId, now)
+ const row = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_checkouts WHERE id=? AND workspace_id=? AND user_id=?',
+ )
+ .bind(checkoutId, workspaceId, userId)
+ .first<any>()
+ if (!row) fail(404, 'payment_checkout_unavailable')
+ if (['completed', 'expired'].includes(row.state)) return { state: row.state }
+ if (!row.provider_id) return { state: 'pending' }
+ const checkout = await creemRequest(
+ await paymentSecrets(db, rootKey),
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(row.provider_id),
+ undefined,
+ transport,
+ )
+ if (
+ checkout.id !== row.provider_id ||
+ checkout.mode !== 'test' ||
+ !checkoutBound(checkout, row.id) ||
+ objectId(checkout.product) !== row.product_id
+ )
+ fail(422, 'payment_binding_invalid')
+ if (checkout.status !== 'completed') return { state: 'pending' }
+ const eventId = 'return_' + row.id
+ await db
+ .prepare(
+ "INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,reference_id,created_at,available_at) VALUES(?,'checkout.completed',?,?,?,?)",
+ )
+ .bind(eventId, row.provider_id, row.id, now, now)
+ .run()
+ await processPaymentEvents(db, rootKey, transport, now, 1, eventId)
+ const current = await db
+ .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')
+ .bind(row.id)
+ .first<any>()
+ return { state: current?.state === 'completed' ? 'completed' : 'pending' }
+}
diff --git a/tests/platform-payments.test.ts b/tests/platform-payments.test.ts
index d6bdebe5..4d5d572e 100644
--- a/tests/platform-payments.test.ts
+++ b/tests/platform-payments.test.ts
@@ -1,3 +1,12 @@
+import {
+ paymentEventPage,
+ paymentEventPayload,
+ expirePaymentEventPayloads,
+} from '../packages/platform/src/payment-events.ts'
+import {
+ syncPaymentProducts,
+ paymentProductSyncStatus,
+} from '../packages/platform/src/payment-product-sync.ts'
import {
activationHash,
redeemActivation,
@@ -26,6 +35,7 @@ import {
closeAccountPayments,
validatePaymentProduct,
reconcilePayments,
+ refreshPaymentCheckout,
} from '../packages/platform/src/payments.ts'
import {
resolveSubscription,
@@ -63,8 +73,7 @@ async function fixture() {
)
)
.replace(/^--.*$/gm, '')
- .split(';')
- .filter((s) => s.trim()))
+ .match(/\s*CREATE TRIGGER[\s\S]+?END;|[^;]+;/g) ?? [])
await db.prepare(sql).run()
}
await db
@@ -97,7 +106,7 @@ async function fixture() {
.run()
await db
.prepare(
- "UPDATE platform_payment_settings SET enabled=1,workspace_ids_json='[1]',credentials_ciphertext=?",
+ "UPDATE platform_payment_settings SET auto_sync=0,enabled=1,workspace_ids_json='[1]',credentials_ciphertext=?",
)
.bind(await sealPaymentSecrets(root, credentials))
.run()
@@ -1281,3 +1290,414 @@ test('Abandoned sandbox attempts cannot grant access through late callbacks or b
await f.mf.dispose()
}
})
+
+test('Checkout return reconciliation verifies provider truth and ownership without trusting the browser return', async () => {
+ const f = await fixture()
+ try {
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ assert.deepEqual(
+ await refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.checkoutId,
+ f.transport,
+ f.now + 1,
+ ),
+ { state: 'pending' },
+ )
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 1)).id, 'free')
+ await assert.rejects(
+ refreshPaymentCheckout(
+ f.db,
+ root,
+ 2,
+ 2,
+ checkout.checkoutId,
+ f.transport,
+ f.now + 1,
+ ),
+ { statusCode: 404 },
+ )
+ await assert.rejects(
+ refreshPaymentCheckout(
+ f.db,
+ root,
+ 3,
+ 1,
+ checkout.checkoutId,
+ f.transport,
+ f.now + 1,
+ ),
+ { statusCode: 403 },
+ )
+ await f.complete()
+ assert.deepEqual(
+ await refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.checkoutId,
+ f.transport,
+ f.now + 2,
+ ),
+ { state: 'completed' },
+ )
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 2)).id, 'pro')
+ const revision = (await resolveSubscription(f.db, 1, f.now + 2))
+ .assignment_revision
+ const calls = f.calls.length
+ await refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.checkoutId,
+ f.transport,
+ f.now + 3,
+ )
+ assert.equal(f.calls.length, calls)
+ assert.equal(
+ (await resolveSubscription(f.db, 1, f.now + 3)).assignment_revision,
+ revision,
+ )
+ await (
+ await f.event(
+ 'evt_delayed_return',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ f.now + 4,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 4)
+ assert.equal(
+ (await resolveSubscription(f.db, 1, f.now + 4)).assignment_revision,
+ revision,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Signed webhook payloads are encrypted, bound to their event, paginated and expired without losing the inbox', async () => {
+ const f = await fixture()
+ try {
+ for (let i = 0; i < 56; i++)
+ await (
+ await f.event(
+ 'evt_page_' + String(i).padStart(3, '0'),
+ 'refund.created',
+ {
+ id: 'refund_' + i,
+ mode: 'test',
+ customer: { email: '[email protected]' },
+ note: i === 0 ? 'x'.repeat(50000) : 'original',
+ },
+ )
+ ).receive()
+ const first = await paymentEventPage(f.db),
+ second = await paymentEventPage(f.db, first.nextCursor!),
+ third = await paymentEventPage(f.db, second.nextCursor!)
+ assert.equal(first.events.length, 25)
+ assert.equal(second.events.length, 25)
+ assert.equal(third.events.length, 6)
+ assert.equal(third.nextCursor, null)
+ assert.equal(
+ new Set(
+ [...first.events, ...second.events, ...third.events].map((r) => r.id),
+ ).size,
+ 56,
+ )
+ await assert.rejects(paymentEventPage(f.db, 'invalid-cursor'), {
+ statusCode: 400,
+ })
+ const payload = await paymentEventPayload(f.db, root, 'evt_page_000', f.now)
+ assert.equal(
+ payload.payload.object.customer.email,
+ )
+ assert.equal(payload.payload.object.note.length, 50000)
+ const cipher = await f.db
+ .prepare(
+ "SELECT ciphertext FROM platform_payment_event_payloads WHERE event_id='evt_page_000'",
+ )
+ .first<any>()
+ assert.ok(!cipher.ciphertext.includes('private-customer'))
+ await assert.rejects(
+ paymentEventPayload(
+ f.db,
+ 'different-root-'.repeat(4),
+ 'evt_page_000',
+ f.now,
+ ),
+ { statusCode: 503 },
+ )
+ await (
+ await f.event('evt_page_000', 'refund.created', {
+ id: 'refund_0',
+ mode: 'test',
+ note: 'duplicate',
+ })
+ ).receive()
+ assert.equal(
+ (await paymentEventPayload(f.db, root, 'evt_page_000', f.now)).payload
+ .object.note.length,
+ 50000,
+ )
+ assert.equal(
+ (
+ await paymentEventPayload(
+ f.db,
+ root,
+ 'evt_page_000',
+ f.now + 31 * 86400000,
+ )
+ ).available,
+ false,
+ )
+ await expirePaymentEventPayloads(f.db, f.now + 31 * 86400000)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) n FROM platform_payment_event_payloads')
+ .first<any>()
+ ).n,
+ 0,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) n FROM platform_payment_events')
+ .first<any>()
+ ).n,
+ 56,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+function productTransport(f: any) {
+ const products = new Map<string, any>(),
+ keys = new Map<string, string>(),
+ calls: string[] = []
+ let loseOnce = false,
+ changeDuringCreate = false
+ const transport = async (url: any, init: any = {}) => {
+ const u = new URL(String(url)),
+ method = init.method ?? 'GET'
+ if (!u.pathname.startsWith('/v1/products')) return f.transport(url, init)
+ calls.push(method + ' ' + u.pathname)
+ if (method === 'POST') {
+ const b = JSON.parse(init.body),
+ key = init.headers['Idempotency-Key']
+ assert.match(key, /^cfp_[a-f0-9]{64}$/)
+ let id = keys.get(key)
+ if (!id) {
+ id = 'prod_auto_' + (products.size + 1)
+ keys.set(key, id)
+ products.set(id, { ...b, id, mode: 'test', status: 'active' })
+ }
+ if (changeDuringCreate) {
+ changeDuringCreate = false
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_price=1900,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ }
+ if (loseOnce) {
+ loseOnce = false
+ throw new DOMException('Response lost after creation', 'TimeoutError')
+ }
+ return Response.json(products.get(id))
+ }
+ const id = u.searchParams.get('product_id') ?? u.pathname.split('/').at(-1)!
+ if (method === 'PATCH') {
+ assert.ok(!('price' in JSON.parse(init.body)))
+ products.set(id, { ...products.get(id), ...JSON.parse(init.body) })
+ return Response.json(products.get(id))
+ }
+ return products.has(id)
+ ? Response.json(products.get(id))
+ : Response.json({}, { status: 404 })
+ }
+ return {
+ transport,
+ products,
+ calls,
+ loseNext() {
+ loseOnce = true
+ },
+ changeNext() {
+ changeDuringCreate = true
+ },
+ }
+}
+
+test('Automatic catalog sync publishes month/quarter products, updates rights and preserves existing billed prices', async () => {
+ const f = await fixture(),
+ p = productTransport(f)
+ try {
+ await f.db.prepare('DELETE FROM platform_payment_products').run()
+ await f.db
+ .prepare(
+ 'UPDATE platform_payment_settings SET auto_sync=1,revision=revision+1',
+ )
+ .run()
+ assert.equal((await paymentStatus(f.db, 1, 1)).offers.length, 0)
+ await syncPaymentProducts(f.db, root, p.transport, f.now, 20)
+ assert.equal(p.products.size, 2)
+ assert.equal((await paymentStatus(f.db, 1, 1)).offers.length, 2)
+ const mapping = await f.db
+ .prepare(
+ "SELECT product_id FROM platform_payment_products WHERE plan_id='pro' AND interval=1",
+ )
+ .first<any>()
+ const original = p.products.get(mapping.product_id)
+ assert.ok(original.description.includes('Platform storage'))
+ assert.equal(original.billing_period, 'every-month')
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ p.transport,
+ f.now,
+ )
+ const subscription = await f.complete()
+ await (
+ await f.event(
+ 'evt_auto_paid',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, p.transport, f.now)
+ const policy = JSON.parse(
+ (
+ await f.db
+ .prepare("SELECT policy_json FROM platform_plans WHERE id='pro'")
+ .first<any>()
+ ).policy_json,
+ )
+ policy.limits.storageBytes = 2 * 1024 ** 3
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET name='Updated Pro',policy_json=?,revision=revision+1 WHERE id='pro'",
+ )
+ .bind(JSON.stringify(policy))
+ .run()
+ assert.equal((await paymentStatus(f.db, 1, 1)).offers.length, 0)
+ await syncPaymentProducts(f.db, root, p.transport, f.now + 1, 20)
+ assert.equal(p.products.size, 2)
+ assert.ok(p.products.get(mapping.product_id).description.includes('2 GiB'))
+ assert.ok(p.calls.some((c) => c.startsWith('PATCH')))
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_price=1500,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ await syncPaymentProducts(f.db, root, p.transport, f.now + 2, 20)
+ assert.equal(p.products.size, 3)
+ assert.equal(p.products.get(mapping.product_id).price, 1200)
+ assert.notEqual(
+ (
+ await f.db
+ .prepare(
+ "SELECT product_id FROM platform_payment_products WHERE plan_id='pro' AND interval=1",
+ )
+ .first<any>()
+ ).product_id,
+ mapping.product_id,
+ )
+ subscription.updated_at = new Date(f.now + 3).toISOString()
+ subscription.current_period_end_date = new Date(
+ f.now + 60 * 86400000,
+ ).toISOString()
+ await (
+ await f.event(
+ 'evt_old_price_renewal',
+ 'subscription.paid',
+ subscription,
+ f.now + 3,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, p.transport, f.now + 3)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 3)).id, 'pro')
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT price FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.checkoutId)
+ .first<any>()
+ ).price,
+ 1200,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT product_id FROM platform_payment_subscriptions')
+ .first<any>()
+ ).product_id,
+ mapping.product_id,
+ )
+ const calls = p.calls.length
+ await syncPaymentProducts(f.db, root, p.transport, f.now + 4, 20)
+ assert.equal(p.calls.length, calls)
+ assert.ok(
+ (await paymentProductSyncStatus(f.db))
+ .filter((r) => r.plan_id === 'free')
+ .every((r) => r.state === 'disabled'),
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Product creation retries are idempotent and a concurrent plan edit cannot publish an outdated product', async () => {
+ for (const kind of ['timeout', 'edit']) {
+ const f = await fixture(),
+ p = productTransport(f)
+ try {
+ await f.db.prepare('DELETE FROM platform_payment_products').run()
+ await f.db
+ .prepare(
+ 'UPDATE platform_payment_settings SET auto_sync=1,revision=revision+1',
+ )
+ .run()
+ if (kind === 'timeout') p.loseNext()
+ else p.changeNext()
+ await syncPaymentProducts(f.db, root, p.transport, f.now, 20)
+ const month = await f.db
+ .prepare(
+ "SELECT * FROM platform_payment_products WHERE plan_id='pro' AND interval=1",
+ )
+ .first<any>()
+ assert.equal(month, null)
+ await syncPaymentProducts(f.db, root, p.transport, f.now + 120000, 20)
+ const current = await f.db
+ .prepare(
+ "SELECT * FROM platform_payment_products WHERE plan_id='pro' AND interval=1",
+ )
+ .first<any>()
+ assert.ok(current)
+ assert.equal(current.price, kind === 'edit' ? 1900 : 1200)
+ if (kind === 'timeout') assert.equal(p.products.size, 2)
+ assert.equal((await paymentStatus(f.db, 1, 1)).offers.length, 2)
+ } finally {
+ await f.mf.dispose()
+ }
+ }
+})