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(cloud): integrate Creem sandbox subscriptions

Timothy Yin7f2b1b34697a
diff --git a/apps/cloud/app/components/CloudPaymentsPanel.vue b/apps/cloud/app/components/CloudPaymentsPanel.vue
new file mode 100644
index 00000000..2daeed54
--- /dev/null
+++ b/apps/cloud/app/components/CloudPaymentsPanel.vue
@@ -0,0 +1,113 @@
+<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
+ } 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 3ef9d18c..f9c2a88e 100644
--- a/apps/cloud/app/components/CloudPricing.vue
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -26,6 +26,76 @@ const action = (plan: any) =>
(props.portal && billing?.selected.value
? '?workspaceId=' + billing.selected.value
: '')
+const payment = ref<any>(),
+ 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()
+ })
+onBeforeUnmount(() => {
+ mounted = false
+ paymentGeneration++
+})
+const offer = (plan: any) =>
+ payment.value?.enabled &&
+ payment.value?.canManage &&
+ payment.value.offers.some(
+ (v: any) => v.plan_id === plan.id && v.interval === interval.value,
+ )
+const subscriptionActive = computed(() =>
+ payment.value?.subscriptions.some(
+ (v: any) => !['expired', 'canceled'].includes(v.status),
+ ),
+)
+async function checkout(plan: any) {
+ if (paying.value || !billing?.selected.value) return
+ const workspaceId = billing.selected.value,
+ key = plan.id + ':' + interval.value
+ paying.value = key
+ paymentError.value = ''
+ try {
+ const result = await $fetch<{ url: string }>('/api/billing/payments', {
+ method: 'POST',
+ body: {
+ action: 'checkout',
+ workspaceId,
+ planId: plan.id,
+ interval: interval.value,
+ requestId: crypto.randomUUID(),
+ },
+ })
+ if (mounted && workspaceId === billing.selected.value)
+ await navigateTo(result.url, { external: true })
+ } catch {
+ if (mounted) {
+ paymentError.value = t('cloud.payments.failed')
+ await loadPayments()
+ }
+ } finally {
+ paying.value = ''
+ }
+}
</script>
<template>
<div class="cf-pricing">
@@ -49,8 +119,25 @@ const action = (plan: any) =>
}}</span></label
>
</fieldset>
- <p class="cf-field-hint">{{ $t('cloud.billing.paymentsPlanned') }}</p>
+ <p class="cf-field-hint">
+ {{
+ payment?.enabled
+ ? $t('cloud.payments.testHelp')
+ : $t('cloud.billing.paymentsPlanned')
+ }}
+ </p>
+ <p
+ v-if="paymentError"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ 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')
@@ -132,7 +219,21 @@ const action = (plan: any) =>
}}
</p>
<CloudButton
- v-if="portal && billing?.data.value?.workspace.role !== 'admin'"
+ v-if="portal && offer(plan)"
+ :loading="paying === plan.id + ':' + interval"
+ :disabled="!!paying || !!payment.pending || subscriptionActive"
+ :variant="plan.featured ? 'default' : 'secondary'"
+ @click="checkout(plan)"
+ >{{
+ subscriptionActive
+ ? $t('cloud.payments.manageExisting')
+ : $t('cloud.payments.subscribe')
+ }}</CloudButton
+ >
+ <CloudButton
+ v-else-if="
+ portal && billing?.data.value?.workspace.role !== 'admin'
+ "
disabled
:title="$t('cloud.billing.adminOnly')"
:variant="plan.featured ? 'default' : 'secondary'"
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
index 77536e91..03f72940 100644
--- a/apps/cloud/app/pages/account/plan.vue
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -90,7 +90,12 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
>
{{ $t('cloud.billing.signupOffer') }}
</p>
- <p class="cf-field-hint">{{ $t('cloud.billing.noRenewal') }}</p>
+ <p
+ v-if="data.subscription.source !== 'payment'"
+ class="cf-field-hint"
+ >
+ {{ $t('cloud.billing.noRenewal') }}
+ </p>
</div>
<CloudButton
v-if="data.workspace.role === 'admin'"
@@ -100,6 +105,7 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
}}</NuxtLink></CloudButton
></CloudCard
>
+ <CloudPaymentsPanel :workspace-id="selected" />
<section>
<div class="cf-plan-section-heading">
<div>
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index e9133d96..45718092 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -676,6 +676,27 @@
"event_signup_promotion": "Registration promotion activated",
"event_signup_default": "Registration plan assigned",
"signupOffer": "Your registration promotion is active until the expiration shown above."
+ },
+ "payments": {
+ "billing": "Subscription billing",
+ "test": "Test mode",
+ "testHelp": "Creem sandbox checkout. No real charges.",
+ "failed": "The billing action could not be completed. Refresh billing status before retrying.",
+ "pending": "Waiting for provider confirmation. Do not start another subscription.",
+ "manage": "Manage billing and subscription",
+ "resume": "Resume checkout",
+ "subscribe": "Subscribe in test mode",
+ "manageExisting": "Manage your existing subscription",
+ "status": {
+ "active": "Active",
+ "trialing": "Trialing",
+ "scheduled_cancel": "Cancels at period end",
+ "past_due": "Past due",
+ "expired": "Expired",
+ "paused": "Paused",
+ "canceled": "Canceled",
+ "unpaid": "Unpaid"
+ }
}
}
}
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index c65c9f4c..20bd4350 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -676,6 +676,27 @@
"event_signup_promotion": "注册活动套餐已开通",
"event_signup_default": "注册默认套餐已分配",
"signupOffer": "注册促销权益已生效,有效期见上方到期时间。"
+ },
+ "payments": {
+ "billing": "订阅账单",
+ "test": "测试环境",
+ "testHelp": "使用 Creem 测试付款,不产生真实扣费。",
+ "failed": "暂时无法完成支付操作,请刷新账单状态后重试。",
+ "pending": "正在等待渠道确认付款,请勿重复订阅。",
+ "manage": "管理账单与订阅",
+ "resume": "继续付款",
+ "subscribe": "测试订阅",
+ "manageExisting": "已有订阅,请前往账单管理",
+ "status": {
+ "active": "有效",
+ "trialing": "试用中",
+ "scheduled_cancel": "周期结束后取消",
+ "past_due": "付款逾期",
+ "expired": "已到期",
+ "paused": "已暂停",
+ "canceled": "已取消",
+ "unpaid": "未付款"
+ }
}
}
}
diff --git a/apps/cloud/server/api/billing/payments.get.ts b/apps/cloud/server/api/billing/payments.get.ts
new file mode 100644
index 00000000..c863790f
--- /dev/null
+++ b/apps/cloud/server/api/billing/payments.get.ts
@@ -0,0 +1,19 @@
+import { paymentStatus } from '../../../../../packages/platform/src/payments'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { getQuery, setResponseHeader } from 'h3'
+export default definePlatformHandler(async (event) => {
+ const user = await requirePlatformSession(
+ event,
+ useRuntimeConfig(event).platform,
+ )
+ setResponseHeader(event, 'Cache-Control', 'no-store')
+ return paymentStatus(
+ platformDatabase(event),
+ user.userId,
+ Number(getQuery(event).workspaceId),
+ )
+})
diff --git a/apps/cloud/server/api/billing/payments.post.ts b/apps/cloud/server/api/billing/payments.post.ts
new file mode 100644
index 00000000..e54434a0
--- /dev/null
+++ b/apps/cloud/server/api/billing/payments.post.ts
@@ -0,0 +1,40 @@
+import {
+ createPaymentCheckout,
+ createPaymentPortal,
+} from '../../../../../packages/platform/src/payments'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { siteManagementBody } from '../../utils/site-management'
+import { createError } from 'h3'
+export default definePlatformHandler(async (event) => {
+ const config = useRuntimeConfig(event).platform
+ const user = await requirePlatformSession(event, config)
+ platformPortalOrigin(event, config.portalOrigin, true)
+ const b = await siteManagementBody(event, 4096),
+ db = platformDatabase(event)
+ if (b.action === 'checkout')
+ return createPaymentCheckout(
+ db,
+ config.storageSecret,
+ user.userId,
+ {
+ workspaceId: Number(b.workspaceId),
+ planId: String(b.planId),
+ interval: Number(b.interval),
+ requestId: String(b.requestId),
+ },
+ config.portalOrigin,
+ )
+ if (b.action === 'portal')
+ return createPaymentPortal(
+ db,
+ config.storageSecret,
+ user.userId,
+ Number(b.workspaceId),
+ )
+ throw createError({ statusCode: 400 })
+})
diff --git a/apps/cloud/server/api/webhooks/creem.post.ts b/apps/cloud/server/api/webhooks/creem.post.ts
new file mode 100644
index 00000000..d62fe50f
--- /dev/null
+++ b/apps/cloud/server/api/webhooks/creem.post.ts
@@ -0,0 +1,49 @@
+import {
+ receivePaymentEvent,
+ processPaymentEvents,
+} from '../../../../../packages/platform/src/payments'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../shared/platform/runtime'
+import { getHeader, getRequestWebStream, createError } from 'h3'
+export default definePlatformHandler(async (event) => {
+ const stream = getRequestWebStream(event)
+ if (!stream) throw createError({ statusCode: 400 })
+ const reader = stream.getReader(),
+ chunks: Uint8Array[] = []
+ let length = 0
+ try {
+ while (true) {
+ const { value, done } = await reader.read()
+ if (done) break
+ length += value.byteLength
+ if (length > 65536) {
+ await reader.cancel()
+ throw createError({ statusCode: 413 })
+ }
+ chunks.push(value)
+ }
+ } finally {
+ reader.releaseLock()
+ }
+ const body = new Uint8Array(length)
+ let offset = 0
+ for (const chunk of chunks) {
+ body.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ const db = platformDatabase(event),
+ key = useRuntimeConfig(event).platform.storageSecret
+ const result = await receivePaymentEvent(
+ db,
+ key,
+ body,
+ getHeader(event, 'creem-signature') || '',
+ )
+ // Durable acceptance precedes processing; failures remain in the scheduled retry inbox.
+ await processPaymentEvents(db, key, fetch, Date.now(), 1).catch(
+ () => undefined,
+ )
+ return result
+})
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index 89f7ef9e..05025c50 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -22,6 +22,8 @@ export default defineEventHandler((event) => {
'/api/billing/workspaces',
'/api/billing/plan',
'/api/billing/redeem',
+ '/api/billing/payments',
+ '/api/webhooks/creem',
'/api/workspaces/default',
].includes(path) ||
/^\/api\/sites\/[1-9][0-9]*\/(?:context|events|settings|domains)$/.test(
diff --git a/apps/cloud/server/plugins/account-lifecycle.ts b/apps/cloud/server/plugins/account-lifecycle.ts
index c0e8af52..e459941f 100644
--- a/apps/cloud/server/plugins/account-lifecycle.ts
+++ b/apps/cloud/server/plugins/account-lifecycle.ts
@@ -1,3 +1,4 @@
+import { closeAccountPayments } from '../../../../packages/platform/src/payments'
import {
scanAccounts,
lifecycleStages,
@@ -49,6 +50,12 @@ export default defineNitroPlugin((app) => {
await purgeAccounts(
db,
{
+ billing: (userId) =>
+ closeAccountPayments(
+ db,
+ String(env.NUXT_PLATFORM_STORAGE_SECRET || ''),
+ userId,
+ ),
async domains(siteId) {
await db
.prepare(
diff --git a/apps/cloud/server/plugins/payments.ts b/apps/cloud/server/plugins/payments.ts
new file mode 100644
index 00000000..48bedf7c
--- /dev/null
+++ b/apps/cloud/server/plugins/payments.ts
@@ -0,0 +1,12 @@
+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)
+ await reconcilePayments(
+ db,
+ String(env.NUXT_PLATFORM_STORAGE_SECRET || ''),
+ )
+ })
+})
diff --git a/packages/platform/migrations/0022_creem_payments.sql b/packages/platform/migrations/0022_creem_payments.sql
new file mode 100644
index 00000000..9a376b6d
--- /dev/null
+++ b/packages/platform/migrations/0022_creem_payments.sql
@@ -0,0 +1,17 @@
+CREATE TABLE platform_payment_settings(id INTEGER PRIMARY KEY CHECK(id=1),enabled INTEGER NOT NULL DEFAULT 0 CHECK(enabled IN(0,1)),environment TEXT NOT NULL DEFAULT 'test' CHECK(environment='test'),workspace_ids_json TEXT NOT NULL DEFAULT '[]',credentials_ciphertext TEXT,revision INTEGER NOT NULL DEFAULT 1,updated_at INTEGER NOT NULL DEFAULT 0);
+INSERT INTO platform_payment_settings(id) VALUES(1);
+CREATE TABLE platform_payment_products(plan_id TEXT NOT NULL REFERENCES platform_plans(id),interval INTEGER NOT NULL CHECK(interval IN(1,3)),product_id TEXT NOT NULL UNIQUE,price INTEGER NOT NULL,currency TEXT NOT NULL,enabled INTEGER NOT NULL DEFAULT 1 CHECK(enabled IN(0,1)),revision INTEGER NOT NULL DEFAULT 1,PRIMARY KEY(plan_id,interval));
+CREATE TABLE platform_payment_checkouts(id TEXT PRIMARY KEY,workspace_id INTEGER NOT NULL REFERENCES platform_workspaces(id),user_id INTEGER REFERENCES platform_users(id) ON DELETE SET NULL,request_id TEXT NOT NULL,plan_id TEXT NOT NULL REFERENCES platform_plans(id),interval INTEGER NOT NULL CHECK(interval IN(1,3)),product_id TEXT NOT NULL,price INTEGER NOT NULL,currency TEXT NOT NULL,assignment_revision INTEGER NOT NULL,provider_id TEXT UNIQUE,checkout_url TEXT,state TEXT NOT NULL CHECK(state IN('creating','open','completed','expired','uncertain')),created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,error TEXT,UNIQUE(user_id,request_id));
+CREATE UNIQUE INDEX platform_payment_checkout_pending ON platform_payment_checkouts(workspace_id) WHERE state IN('creating','open','uncertain');
+CREATE TABLE platform_payment_subscriptions(id TEXT PRIMARY KEY,workspace_id INTEGER NOT NULL REFERENCES platform_workspaces(id),checkout_id TEXT NOT NULL UNIQUE REFERENCES platform_payment_checkouts(id),customer_id TEXT NOT NULL,product_id TEXT NOT NULL,plan_id TEXT NOT NULL REFERENCES platform_plans(id),interval INTEGER NOT NULL,quota_anchor INTEGER NOT NULL,status TEXT NOT NULL,period_start INTEGER NOT NULL,period_end INTEGER NOT NULL,provider_updated_at INTEGER NOT NULL,checked_at INTEGER NOT NULL,next_check_at INTEGER NOT NULL DEFAULT 0,error TEXT,revision INTEGER NOT NULL DEFAULT 1);
+CREATE INDEX platform_payment_subscription_due ON platform_payment_subscriptions(next_check_at);
+CREATE TABLE platform_payment_events(id TEXT PRIMARY KEY,type TEXT NOT NULL,object_id TEXT NOT NULL,reference_id TEXT,created_at INTEGER NOT NULL,state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN('pending','done','ignored','failed')),attempts INTEGER NOT NULL DEFAULT 0,available_at INTEGER NOT NULL,error TEXT,lease_token TEXT,lease_until INTEGER);
+CREATE INDEX platform_payment_events_due ON platform_payment_events(state,available_at);
+CREATE TABLE platform_payment_locks(workspace_id INTEGER PRIMARY KEY REFERENCES platform_workspaces(id),token TEXT NOT NULL,expires_at INTEGER NOT NULL);
+ALTER TABLE platform_workspace_plans ADD COLUMN payment_subscription_id TEXT;
+CREATE TABLE platform_payment_requests(user_id INTEGER NOT NULL REFERENCES platform_users(id) ON DELETE CASCADE,window_start INTEGER NOT NULL,attempts INTEGER NOT NULL,PRIMARY KEY(user_id,window_start));
+
+CREATE INDEX platform_payment_event_object ON platform_payment_events(object_id);
+CREATE INDEX platform_payment_event_reference ON platform_payment_events(reference_id);
+CREATE INDEX platform_payment_subscription_workspace ON platform_payment_subscriptions(workspace_id,checked_at);
+CREATE INDEX platform_payment_subscription_customer ON platform_payment_subscriptions(customer_id);
diff --git a/packages/platform/src/account-purge.ts b/packages/platform/src/account-purge.ts
index 63980478..50839c15 100644
--- a/packages/platform/src/account-purge.ts
+++ b/packages/platform/src/account-purge.ts
@@ -1,6 +1,7 @@
import type { PlatformD1 } from './index.ts'
import { allRows } from './subscriptions.ts'
export interface AccountCleanup {
+ billing?(userId: number): Promise<boolean>
domains(siteId: number): Promise<boolean>
storage(
siteId: number,
@@ -31,6 +32,14 @@ export async function purgeAccounts(
if (!lock) return
const id = row.user_id
try {
+ const billing = await db
+ .prepare(
+ "SELECT s.id FROM platform_payment_subscriptions s JOIN platform_workspaces w ON w.id=s.workspace_id JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE (w.owner_user_id=? OR c.user_id=?) AND s.status NOT IN('canceled','expired') UNION ALL SELECT c.id FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE (w.owner_user_id=? OR c.user_id=?) AND c.state IN('creating','open','uncertain') LIMIT 1",
+ )
+ .bind(id, id, id, id)
+ .first()
+ if (billing && (!cleanup.billing || !(await cleanup.billing(id))))
+ throw new Error('Payment cancellation required')
// A purging account cannot be restored; all existing leases are fenced before external cleanup.
await db
.prepare(
@@ -188,6 +197,34 @@ export async function purgeAccounts(
)
.bind(id, id),
)
+ // Payment resources were closed upstream. Retain other owners' ledgers without the erased purchaser identity.
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM platform_payment_events WHERE reference_id IN(SELECT id FROM platform_payment_checkouts WHERE workspace_id IN(${workspaces})) OR object_id IN(SELECT provider_id FROM platform_payment_checkouts WHERE workspace_id IN(${workspaces})) OR object_id IN(SELECT id FROM platform_payment_subscriptions WHERE workspace_id IN(${workspaces}))`,
+ )
+ .bind(id, id, id),
+ db
+ .prepare(
+ `DELETE FROM platform_payment_subscriptions WHERE workspace_id IN(${workspaces})`,
+ )
+ .bind(id),
+ db
+ .prepare(
+ `DELETE FROM platform_payment_checkouts WHERE workspace_id IN(${workspaces})`,
+ )
+ .bind(id),
+ db
+ .prepare(
+ 'UPDATE platform_payment_checkouts SET user_id=NULL WHERE user_id=?',
+ )
+ .bind(id),
+ db
+ .prepare(
+ `DELETE FROM platform_payment_locks WHERE workspace_id IN(${workspaces})`,
+ )
+ .bind(id),
+ )
statements.push(
db
.prepare('DELETE FROM platform_workspaces WHERE owner_user_id=?')
@@ -201,6 +238,7 @@ export async function purgeAccounts(
'platform_two_factors',
'platform_auth_sessions',
'platform_activation_attempts',
+ 'platform_payment_requests',
'platform_account_controls',
'platform_mail_outbox',
'platform_purge_storage_done',
diff --git a/packages/platform/src/activation.ts b/packages/platform/src/activation.ts
index eec72f40..597cadf8 100644
--- a/packages/platform/src/activation.ts
+++ b/packages/platform/src/activation.ts
@@ -232,13 +232,31 @@ export async function redeemActivation(
throw new SubscriptionError(409, 'redemption_changed')
return JSON.parse(previous.receipt_json)
}
+ async function completedReceipt() {
+ const row = await db
+ .prepare(
+ 'SELECT workspace_id,receipt_json FROM platform_activation_redemptions WHERE user_id=? AND request_id=?',
+ )
+ .bind(userId, input.requestId as string)
+ .first<{ workspace_id: number; receipt_json: string }>()
+ if (row && row.workspace_id !== workspaceId)
+ throw new SubscriptionError(409, 'redemption_changed')
+ return row ? JSON.parse(row.receipt_json) : null
+ }
await attempt(db, userId, now)
const hash = await activationHash(input.code),
code = await available(db, hash, userId, now)
- if (!code) invalid()
+ if (!code) {
+ const receipt = await completedReceipt()
+ if (receipt) return receipt
+ invalid()
+ }
const current = await resolveSubscription(db, workspaceId, now)
- if (current.assignment_revision !== input.revision)
+ if (current.assignment_revision !== input.revision) {
+ const receipt = await completedReceipt()
+ if (receipt) return receipt
throw new SubscriptionError(409, 'subscription_changed')
+ }
const grant = effect(code, current, now),
eventId = crypto.randomUUID(),
receipt = {
@@ -277,7 +295,7 @@ export async function redeemActivation(
.bind(code.id, eventId),
db
.prepare(
- `INSERT INTO platform_workspace_plans(workspace_id,plan_id,starts_at,expires_at,source,billing_interval) SELECT ?,?,?,?,'activation',NULL WHERE EXISTS(SELECT 1 FROM platform_activation_redemptions WHERE claim_id=?) ON CONFLICT(workspace_id) DO UPDATE SET plan_id=excluded.plan_id,starts_at=excluded.starts_at,expires_at=excluded.expires_at,source='activation',billing_interval=NULL,revision=platform_workspace_plans.revision+1`,
+ `INSERT INTO platform_workspace_plans(workspace_id,plan_id,starts_at,expires_at,source,billing_interval) SELECT ?,?,?,?,'activation',NULL WHERE EXISTS(SELECT 1 FROM platform_activation_redemptions WHERE claim_id=?) ON CONFLICT(workspace_id) DO UPDATE SET plan_id=excluded.plan_id,starts_at=excluded.starts_at,expires_at=excluded.expires_at,source='activation',billing_interval=NULL,payment_subscription_id=NULL,revision=platform_workspace_plans.revision+1`,
)
.bind(
workspaceId,
diff --git a/packages/platform/src/lifecycle-exemptions.ts b/packages/platform/src/lifecycle-exemptions.ts
index 4efacc0e..2a834583 100644
--- a/packages/platform/src/lifecycle-exemptions.ts
+++ b/packages/platform/src/lifecycle-exemptions.ts
@@ -66,7 +66,7 @@ export function validateExemptions(value: unknown): LifecycleExemptions {
})),
}
}
-/** Grants belong to owned workspaces. Merely joining another subscriber's workspace cannot exempt an account. */
+/** Owned grants and personally purchased recurring subscriptions qualify; borrowed membership alone never does. */
export async function accountExemption(
db: PlatformD1,
userId: number,
@@ -81,6 +81,15 @@ export async function accountExemption(
)
.bind(userId),
)
+ current.push(
+ ...(await allRows<any>(
+ db
+ .prepare(
+ "SELECT s.plan_id,'payment' AS source,s.period_start AS starts_at,s.period_end AS expires_at,CASE WHEN p.active=1 AND s.status IN('active','trialing','scheduled_cancel','past_due') THEN 1 ELSE 0 END AS active FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id JOIN platform_plans p ON p.id=s.plan_id WHERE c.user_id=?",
+ )
+ .bind(userId),
+ )),
+ )
const events = config.rules.some((r) => r.kind === 'ever-subscribed')
? await allRows<any>(
db
diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.ts
new file mode 100644
index 00000000..e137ff33
--- /dev/null
+++ b/packages/platform/src/payments.ts
@@ -0,0 +1,1202 @@
+import type { PlatformD1 } from './index.ts'
+import {
+ allRows,
+ SubscriptionError,
+ subscriptionInvalidation,
+ EXPIRY_PLAN_SQL,
+} from './subscriptions.ts'
+
+export const CREEM_TEST_API = 'https://test-api.creem.io'
+const enc = new TextEncoder()
+const fail = (status: number, code: string): never => {
+ throw new SubscriptionError(status, code)
+}
+const identifier = (v: unknown) =>
+ typeof v === 'string' && /^[a-zA-Z0-9_-]{1,160}$/.test(v)
+const objectId = (v: any): string => (typeof v === 'string' ? v : v?.id)
+const time = (v: unknown) =>
+ typeof v === 'string' && Number.isFinite(Date.parse(v)) ? Date.parse(v) : 0
+export type PaymentFetch = typeof fetch
+export type PaymentSecrets = { apiKey: string; webhookSecret: string }
+
+/** A distinct HKDF context protects online payment credentials using the existing platform root key. */
+async function credentialKey(secret: string) {
+ if (secret.length < 32) fail(503, 'payment_encryption_unavailable')
+ const material = await crypto.subtle.importKey(
+ 'raw',
+ enc.encode(secret),
+ 'HKDF',
+ false,
+ ['deriveKey'],
+ )
+ return crypto.subtle.deriveKey(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: enc.encode('chronoframe-payments-v1'),
+ info: enc.encode('creem-test-credentials'),
+ },
+ material,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ ['encrypt', 'decrypt'],
+ )
+}
+export async function sealPaymentSecrets(
+ secret: string,
+ value: PaymentSecrets,
+) {
+ const nonce = crypto.getRandomValues(new Uint8Array(12)),
+ key = await credentialKey(secret)
+ const ciphertext = new Uint8Array(
+ await crypto.subtle.encrypt(
+ { name: 'AES-GCM', iv: nonce, additionalData: enc.encode('creem:test') },
+ key,
+ enc.encode(JSON.stringify(value)),
+ ),
+ )
+ return JSON.stringify([
+ btoa(String.fromCharCode(...nonce)),
+ btoa(String.fromCharCode(...ciphertext)),
+ ])
+}
+export async function paymentSecrets(
+ db: PlatformD1,
+ secret: string,
+): Promise<PaymentSecrets> {
+ const row = await db
+ .prepare(
+ 'SELECT credentials_ciphertext FROM platform_payment_settings WHERE id=1',
+ )
+ .first<any>()
+ if (!row?.credentials_ciphertext) fail(503, 'payment_not_configured')
+ try {
+ const [nonce, body] = JSON.parse(row.credentials_ciphertext)
+ const value = await crypto.subtle.decrypt(
+ {
+ name: 'AES-GCM',
+ iv: Uint8Array.from(atob(nonce), (c) => c.charCodeAt(0)),
+ additionalData: enc.encode('creem:test'),
+ },
+ await credentialKey(secret),
+ Uint8Array.from(atob(body), (c) => c.charCodeAt(0)),
+ )
+ return JSON.parse(new TextDecoder().decode(value))
+ } catch {
+ return fail(503, 'payment_credentials_unavailable')
+ }
+}
+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',
+ )
+ .first<any>()
+ return {
+ enabled: !!row.enabled,
+ environment: 'test' as const,
+ workspaceIds: JSON.parse(row.workspace_ids_json) as number[],
+ revision: Number(row.revision),
+ configured: !!row.configured,
+ }
+}
+export async function creemRequest(
+ credentials: PaymentSecrets,
+ path: string,
+ body?: unknown,
+ transport: PaymentFetch = fetch,
+) {
+ 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',
+ headers: {
+ 'x-api-key': credentials.apiKey,
+ 'content-type': 'application/json',
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ redirect: 'manual',
+ signal: AbortSignal.timeout(10000),
+ })
+ } catch {
+ return fail(502, 'payment_provider_unavailable')
+ }
+ if (!response.ok)
+ throw Object.assign(
+ new SubscriptionError(
+ response.status >= 400 && response.status < 500 ? 422 : 502,
+ 'payment_provider_request_failed',
+ ),
+ { providerStatus: response.status },
+ )
+ const text = await response.text()
+ if (text.length > 524288) fail(502, 'payment_provider_response_invalid')
+ try {
+ return JSON.parse(text)
+ } catch {
+ return fail(502, 'payment_provider_response_invalid')
+ }
+}
+export function paymentURL(value: unknown) {
+ try {
+ const u = new URL(String(value))
+ if (
+ u.protocol !== 'https:' ||
+ u.username ||
+ u.password ||
+ u.port ||
+ !['creem.io', 'www.creem.io', 'checkout.creem.io'].includes(u.hostname)
+ )
+ throw 0
+ return u.href
+ } catch {
+ return fail(502, 'payment_redirect_invalid')
+ }
+}
+export async function validatePaymentProduct(
+ db: PlatformD1,
+ credentials: PaymentSecrets,
+ planId: string,
+ interval: number,
+ productId: string,
+ transport: PaymentFetch = fetch,
+) {
+ if (
+ !identifier(planId) ||
+ !identifier(productId) ||
+ ![1, 3].includes(interval)
+ )
+ fail(400, 'payment_product_invalid')
+ const plan = await db
+ .prepare(
+ 'SELECT id,active,listed,currency,monthly_price,quarterly_price FROM platform_plans WHERE id=?',
+ )
+ .bind(planId)
+ .first<any>()
+ if (!plan?.active || !plan.listed) fail(400, 'payment_plan_unavailable')
+ const product = await creemRequest(
+ credentials,
+ '/v1/products?product_id=' + encodeURIComponent(productId),
+ undefined,
+ transport,
+ )
+ const price = interval === 1 ? plan.monthly_price : plan.quarterly_price
+ if (
+ product.mode !== 'test' ||
+ product.id !== productId ||
+ product.billing_type !== 'recurring' ||
+ product.billing_period !==
+ (interval === 1 ? 'every-month' : 'every-three-months') ||
+ product.currency !== plan.currency ||
+ !Number.isSafeInteger(price) ||
+ price <= 0 ||
+ product.price !== price ||
+ (product.usage_prices?.length ?? 0) > 0 ||
+ Number(product.trial_period_days ?? 0) > 0 ||
+ (product.status !== undefined && product.status !== 'active')
+ )
+ fail(422, 'payment_product_mismatch')
+ return {
+ productId,
+ price: Number(price),
+ currency: String(plan.currency),
+ name: String(product.name || productId),
+ }
+}
+export async function paymentMember(
+ db: PlatformD1,
+ userId: number,
+ workspaceId: number,
+ write = false,
+) {
+ if (!Number.isSafeInteger(workspaceId) || workspaceId < 1)
+ fail(400, 'workspace_unavailable')
+ const row = await db
+ .prepare(
+ 'SELECT m.role,u.email FROM platform_memberships m JOIN platform_users u ON u.id=m.user_id LEFT JOIN platform_account_controls c ON c.user_id=u.id WHERE m.workspace_id=? AND m.user_id=? AND u.email_verified=1 AND COALESCE(c.suspended,0)=0 AND NOT EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=u.id)',
+ )
+ .bind(workspaceId, userId)
+ .first<any>()
+ if (!row || (write && row.role !== 'admin'))
+ fail(403, 'workspace_admin_required')
+ return row as { role: string; email: string }
+}
+export async function paymentStatus(
+ db: PlatformD1,
+ userId: number,
+ workspaceId: number,
+) {
+ const membership = await paymentMember(db, userId, workspaceId)
+ const settings = await paymentSettings(db)
+ const subscriptions = await allRows<any>(
+ db
+ .prepare(
+ 'SELECT id,status,period_start,period_end,plan_id,interval,error FROM platform_payment_subscriptions WHERE workspace_id=? ORDER BY checked_at DESC LIMIT 10',
+ )
+ .bind(workspaceId),
+ )
+ const pending = await db
+ .prepare(
+ "SELECT id,state,plan_id,interval,error,checkout_url FROM platform_payment_checkouts WHERE workspace_id=? AND state IN('creating','open','uncertain') ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(workspaceId)
+ .first<any>()
+ const offers =
+ settings.enabled &&
+ settings.configured &&
+ 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',
+ ),
+ )
+ : []
+ return {
+ environment: 'test',
+ enabled: offers.length > 0,
+ canManage: membership.role === 'admin',
+ offers,
+ subscriptions,
+ pending: pending
+ ? {
+ id: pending.id,
+ state: pending.state,
+ planId: pending.plan_id,
+ interval: pending.interval,
+ error: pending.error,
+ url:
+ membership.role === 'admin' &&
+ pending.state === 'open' &&
+ pending.checkout_url
+ ? paymentURL(pending.checkout_url)
+ : null,
+ }
+ : null,
+ }
+}
+async function paymentRequestBudget(
+ db: PlatformD1,
+ userId: number,
+ now = Date.now(),
+) {
+ const window = Math.floor(now / 60000) * 60000
+ const row = await db
+ .prepare(
+ 'INSERT INTO platform_payment_requests(user_id,window_start,attempts) VALUES(?,?,1) ON CONFLICT(user_id,window_start) DO UPDATE SET attempts=attempts+1 WHERE attempts<20 RETURNING attempts',
+ )
+ .bind(userId, window)
+ .first()
+ if (!row) fail(429, 'payment_rate_limited')
+}
+async function acquireWorkspace(
+ db: PlatformD1,
+ workspaceId: number,
+ now: number,
+) {
+ const token = crypto.randomUUID()
+ const row = await db
+ .prepare(
+ 'INSERT INTO platform_payment_locks(workspace_id,token,expires_at) VALUES(?,?,?) ON CONFLICT(workspace_id) DO UPDATE SET token=excluded.token,expires_at=excluded.expires_at WHERE platform_payment_locks.expires_at<? RETURNING token',
+ )
+ .bind(workspaceId, token, now + 60000, now)
+ .first<any>()
+ if (!row || row.token !== token) fail(409, 'payment_busy')
+ return token
+}
+async function releaseWorkspace(
+ db: PlatformD1,
+ workspaceId: number,
+ token: string,
+) {
+ await db
+ .prepare(
+ 'DELETE FROM platform_payment_locks WHERE workspace_id=? AND token=?',
+ )
+ .bind(workspaceId, token)
+ .run()
+}
+
+/** A checkout snapshots the authenticated workspace and plan; a return URL can never grant access. */
+export async function createPaymentCheckout(
+ db: PlatformD1,
+ rootKey: string,
+ userId: number,
+ input: {
+ workspaceId: number
+ planId: string
+ interval: number
+ requestId: string
+ },
+ portalOrigin: string,
+ transport: PaymentFetch = fetch,
+ now = Date.now(),
+) {
+ const user = await paymentMember(db, userId, input.workspaceId, true)
+ if (
+ !identifier(input.requestId) ||
+ !identifier(input.planId) ||
+ ![1, 3].includes(input.interval)
+ )
+ fail(400, 'payment_checkout_invalid')
+ const settings = await paymentSettings(db)
+ if (
+ !settings.enabled ||
+ !settings.configured ||
+ !settings.workspaceIds.includes(input.workspaceId)
+ )
+ fail(403, 'payment_checkout_disabled')
+ const token = await acquireWorkspace(db, input.workspaceId, now)
+ try {
+ const previous = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_checkouts WHERE user_id=? AND request_id=?',
+ )
+ .bind(userId, input.requestId)
+ .first<any>()
+ if (previous) {
+ if (
+ previous.workspace_id !== input.workspaceId ||
+ previous.plan_id !== input.planId ||
+ previous.interval !== input.interval
+ )
+ fail(409, 'payment_request_reused')
+ if (previous.state === 'open' && previous.checkout_url)
+ return {
+ url: paymentURL(previous.checkout_url),
+ checkoutId: previous.id,
+ }
+ return fail(409, 'payment_confirmation_pending')
+ }
+ const active = await db
+ .prepare(
+ "SELECT id FROM platform_payment_subscriptions WHERE workspace_id=? AND status NOT IN('expired','canceled') LIMIT 1",
+ )
+ .bind(input.workspaceId)
+ .first()
+ if (active) fail(409, 'payment_subscription_exists')
+ const pending = await db
+ .prepare(
+ "SELECT id FROM platform_payment_checkouts WHERE workspace_id=? AND state IN('creating','open','uncertain') LIMIT 1",
+ )
+ .bind(input.workspaceId)
+ .first()
+ if (pending) fail(409, 'payment_confirmation_pending')
+ const mapping = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_products WHERE plan_id=? AND interval=? AND enabled=1',
+ )
+ .bind(input.planId, input.interval)
+ .first<any>()
+ if (!mapping) fail(400, 'payment_product_unavailable')
+ await paymentRequestBudget(db, userId, now)
+ const credentials = await paymentSecrets(db, rootKey)
+ const product = await validatePaymentProduct(
+ db,
+ credentials,
+ input.planId,
+ input.interval,
+ mapping.product_id,
+ transport,
+ )
+ const id = crypto.randomUUID(),
+ assignment = await db
+ .prepare(
+ 'SELECT revision FROM platform_workspace_plans WHERE workspace_id=?',
+ )
+ .bind(input.workspaceId)
+ .first<any>()
+ await db
+ .prepare(
+ "INSERT INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,state,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,'creating',?,?)",
+ )
+ .bind(
+ id,
+ input.workspaceId,
+ userId,
+ input.requestId,
+ input.planId,
+ input.interval,
+ mapping.product_id,
+ product.price,
+ product.currency,
+ assignment?.revision ?? 0,
+ now,
+ now,
+ )
+ .run()
+ try {
+ const success = new URL('/account/plan', portalOrigin)
+ success.searchParams.set('workspaceId', String(input.workspaceId))
+ success.searchParams.set('checkout', id)
+ const checkout = await creemRequest(
+ credentials,
+ '/v1/checkouts',
+ {
+ request_id: id,
+ product_id: mapping.product_id,
+ units: 1,
+ customer: { email: user.email },
+ success_url: success.href,
+ metadata: {
+ chronoframe_checkout_id: id,
+ referenceId: String(userId),
+ workspaceId: String(input.workspaceId),
+ },
+ },
+ transport,
+ )
+ if (
+ !identifier(checkout.id) ||
+ checkout.mode !== 'test' ||
+ checkout.request_id !== id ||
+ objectId(checkout.product) !== mapping.product_id
+ )
+ fail(502, 'payment_checkout_response_invalid')
+ const url = paymentURL(checkout.checkout_url)
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET provider_id=?,checkout_url=?,state='open',updated_at=? WHERE id=? AND state='creating'",
+ )
+ .bind(checkout.id, url, now, id)
+ .run()
+ return { url, checkoutId: id }
+ } catch (error) {
+ const rejected =
+ error instanceof SubscriptionError &&
+ [400, 401, 403, 404, 422].includes(
+ Number(
+ (error as SubscriptionError & { providerStatus?: number })
+ .providerStatus,
+ ),
+ )
+ // Definitive 4xx rejections can be retried after configuration repair; unknown outcomes cannot.
+ if (rejected) {
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='expired',error='payment_checkout_rejected',updated_at=? WHERE id=? AND state='creating'",
+ )
+ .bind(now, id)
+ .run()
+ throw error
+ }
+ // Never repeat an ambiguous provider create: the provider may have created a payable session.
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='uncertain',error='payment_confirmation_pending',updated_at=? WHERE id=? AND state='creating'",
+ )
+ .bind(now, id)
+ .run()
+ return fail(502, 'payment_confirmation_pending')
+ }
+ } finally {
+ await releaseWorkspace(db, input.workspaceId, token)
+ }
+}
+export async function createPaymentPortal(
+ db: PlatformD1,
+ rootKey: string,
+ userId: number,
+ workspaceId: number,
+ transport: PaymentFetch = fetch,
+) {
+ const member = await paymentMember(db, userId, workspaceId, true)
+ const row = await db
+ .prepare(
+ 'SELECT s.customer_id,c.user_id FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? ORDER BY s.checked_at DESC LIMIT 1',
+ )
+ .bind(workspaceId)
+ .first<any>()
+ if (!row) fail(404, 'payment_customer_unavailable')
+ if (
+ row.user_id !== userId ||
+ (await db
+ .prepare(
+ "SELECT 1 FROM platform_payment_subscriptions s WHERE s.customer_id=? AND NOT EXISTS(SELECT 1 FROM platform_memberships m WHERE m.workspace_id=s.workspace_id AND m.user_id=? AND m.role='admin') LIMIT 1",
+ )
+ .bind(row.customer_id, userId)
+ .first())
+ )
+ fail(403, 'payment_customer_scope_conflict')
+ await paymentRequestBudget(db, userId)
+ const credentials = await paymentSecrets(db, rootKey)
+ const customer = await creemRequest(
+ credentials,
+ '/v1/customers?customer_id=' + encodeURIComponent(row.customer_id),
+ undefined,
+ transport,
+ )
+ if (
+ customer.mode !== 'test' ||
+ customer.id !== row.customer_id ||
+ String(customer.email).toLowerCase() !== member.email.toLowerCase()
+ )
+ fail(403, 'payment_customer_scope_conflict')
+ const response = await creemRequest(
+ credentials,
+ '/v1/customers/billing',
+ { customer_id: row.customer_id },
+ transport,
+ )
+ return { url: paymentURL(response.customer_portal_link) }
+}
+
+/** Verify the exact raw bytes before parsing, and deduplicate durably before acknowledging delivery. */
+export async function receivePaymentEvent(
+ db: PlatformD1,
+ rootKey: string,
+ body: Uint8Array,
+ signature: string,
+ now = Date.now(),
+) {
+ if (body.byteLength > 65536 || !/^[a-fA-F0-9]{64}$/.test(signature))
+ fail(400, 'payment_signature_invalid')
+ const secret = (await paymentSecrets(db, rootKey)).webhookSecret
+ const key = await crypto.subtle.importKey(
+ 'raw',
+ enc.encode(secret),
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['verify'],
+ )
+ const expected = Uint8Array.from(signature.match(/../g)!, (b) =>
+ parseInt(b, 16),
+ )
+ if (
+ !(await crypto.subtle.verify('HMAC', key, expected, Uint8Array.from(body)))
+ )
+ fail(400, 'payment_signature_invalid')
+ let event: any
+ try {
+ event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body))
+ } catch {
+ return fail(400, 'payment_event_invalid')
+ }
+ if (
+ !identifier(event.id) ||
+ typeof event.eventType !== 'string' ||
+ event.eventType.length > 100 ||
+ !identifier(event.object?.id) ||
+ event.object.mode !== 'test' ||
+ !Number.isSafeInteger(event.created_at) ||
+ event.created_at < 1
+ )
+ fail(400, 'payment_event_invalid')
+ const type = event.eventType as string
+ const supported =
+ type === 'checkout.completed' ||
+ /^subscription\.(active|paid|trialing|canceled|scheduled_cancel|past_due|unpaid|expired|paused|update)$/.test(
+ type,
+ )
+ 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()
+ return { received: true }
+}
+
+async function synchronizePayment(
+ db: PlatformD1,
+ rootKey: string,
+ event: any,
+ transport: PaymentFetch,
+ now: number,
+) {
+ const credentials = await paymentSecrets(db, rootKey)
+ let checkout: any, providerCheckout: any, subscriptionId: string
+ if (event.type === 'checkout.completed') {
+ providerCheckout = await creemRequest(
+ credentials,
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(event.object_id),
+ undefined,
+ transport,
+ )
+ checkout = await db
+ .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')
+ .bind(String(providerCheckout.request_id ?? ''))
+ .first<any>()
+ subscriptionId = objectId(providerCheckout.subscription)
+ } else {
+ const known = await db
+ .prepare(
+ 'SELECT checkout_id FROM platform_payment_subscriptions WHERE id=?',
+ )
+ .bind(event.object_id)
+ .first<any>()
+ const probe = known
+ ? null
+ : await creemRequest(
+ credentials,
+ '/v1/subscriptions?subscription_id=' +
+ encodeURIComponent(event.object_id),
+ undefined,
+ transport,
+ )
+ checkout = await db
+ .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')
+ .bind(
+ String(
+ known?.checkout_id ||
+ probe?.metadata?.chronoframe_checkout_id ||
+ event.reference_id ||
+ '',
+ ),
+ )
+ .first<any>()
+ subscriptionId = event.object_id
+ }
+ if (!checkout || !checkout.user_id) return 'ignored'
+ if (!identifier(subscriptionId)) fail(409, 'payment_confirmation_pending')
+ const token = await acquireWorkspace(db, checkout.workspace_id, now)
+ try {
+ if (
+ await db
+ .prepare('SELECT id FROM platform_subscription_events WHERE id=?')
+ .bind('creem:' + event.id)
+ .first()
+ )
+ return 'done'
+ // Fetch after acquiring the workspace lease so out-of-order deliveries read current provider state.
+ const s = await creemRequest(
+ credentials,
+ '/v1/subscriptions?subscription_id=' + encodeURIComponent(subscriptionId),
+ undefined,
+ transport,
+ )
+ if (!providerCheckout) {
+ if (!checkout.provider_id) fail(409, 'payment_confirmation_pending')
+ providerCheckout = await creemRequest(
+ credentials,
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(checkout.provider_id),
+ undefined,
+ transport,
+ )
+ }
+ if (
+ providerCheckout.mode !== 'test' ||
+ providerCheckout.status !== 'completed' ||
+ providerCheckout.request_id !== checkout.id ||
+ objectId(providerCheckout.product) !== checkout.product_id ||
+ objectId(providerCheckout.subscription) !== subscriptionId ||
+ s.id !== subscriptionId ||
+ s.mode !== 'test' ||
+ objectId(s.customer) !== objectId(providerCheckout.customer) ||
+ !identifier(objectId(s.customer))
+ )
+ fail(422, 'payment_binding_invalid')
+ const known = await db
+ .prepare('SELECT * FROM platform_payment_subscriptions WHERE id=?')
+ .bind(subscriptionId)
+ .first<any>()
+ if (
+ known &&
+ (known.workspace_id !== checkout.workspace_id ||
+ known.checkout_id !== checkout.id)
+ )
+ fail(422, 'payment_binding_invalid')
+ let planId = checkout.plan_id,
+ interval = checkout.interval
+ if (known && objectId(s.product) === known.product_id) {
+ planId = known.plan_id
+ interval = known.interval
+ } else if (objectId(s.product) !== checkout.product_id) {
+ const mapping = await db
+ .prepare(
+ 'SELECT plan_id,interval FROM platform_payment_products WHERE product_id=? AND enabled=1',
+ )
+ .bind(String(objectId(s.product)))
+ .first<any>()
+ if (!known || !mapping) fail(422, 'payment_product_unavailable')
+ planId = mapping.plan_id
+ interval = mapping.interval
+ }
+ // Keep the immutable checkout quote; catalog edits must not invalidate an already paid purchase.
+ // Only an existing subscription changing products needs a freshly validated mapping.
+ if (known && known.product_id !== objectId(s.product))
+ await validatePaymentProduct(
+ db,
+ credentials,
+ planId,
+ interval,
+ objectId(s.product),
+ transport,
+ )
+ const terminal = ['expired', 'paused', 'canceled', 'unpaid'].includes(
+ s.status,
+ )
+ const start =
+ time(s.current_period_start_date) ||
+ (terminal ? known?.period_start || checkout.created_at : 0),
+ end =
+ time(s.current_period_end_date) ||
+ (terminal ? known?.period_end || now + 1 : 0),
+ updated = time(s.updated_at)
+ if (
+ !updated ||
+ !start ||
+ end <= start ||
+ start > now + 1000 ||
+ ![
+ 'active',
+ 'trialing',
+ 'scheduled_cancel',
+ 'past_due',
+ 'expired',
+ 'paused',
+ 'canceled',
+ 'unpaid',
+ ].includes(s.status)
+ )
+ fail(422, 'payment_subscription_invalid')
+ if (known && updated < known.provider_updated_at) return 'done'
+ const prior = await db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=?')
+ .bind(checkout.workspace_id)
+ .first<any>()
+ const account = await db
+ .prepare(
+ 'SELECT 1 FROM platform_account_deletions WHERE user_id=(SELECT owner_user_id FROM platform_workspaces WHERE id=?)',
+ )
+ .bind(checkout.workspace_id)
+ .first()
+ if (account) fail(409, 'payment_account_unavailable')
+ const canAssign = known
+ ? prior?.payment_subscription_id === subscriptionId &&
+ ['payment', 'expired_default'].includes(prior.source)
+ : (prior?.revision ?? 0) === checkout.assignment_revision ||
+ (prior?.source === 'expired_default' &&
+ prior.revision === checkout.assignment_revision + 1)
+ const entitled = [
+ 'active',
+ 'trialing',
+ 'scheduled_cancel',
+ 'past_due',
+ ].includes(s.status)
+ const until =
+ s.status === 'past_due' ? Math.min(end, known?.period_end ?? 0) : end
+ const active = entitled && until > now
+ const eventId = 'creem:' + event.id
+ const fence =
+ 'EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=? AND expires_at>?)'
+ const after = {
+ source: 'payment',
+ planId,
+ status: s.status,
+ periodStart: start,
+ periodEnd: until,
+ assigned: canAssign,
+ subscriptionId,
+ environment: 'test',
+ }
+ const anchor =
+ known && known.plan_id === planId ? known.quota_anchor : start
+ const statements = [
+ db
+ .prepare(
+ `INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,'payment',?,?,? WHERE ${fence}`,
+ )
+ .bind(
+ eventId,
+ checkout.workspace_id,
+ JSON.stringify({
+ planId: prior?.plan_id,
+ source: prior?.source,
+ revision: prior?.revision,
+ }),
+ JSON.stringify(after),
+ now,
+ checkout.workspace_id,
+ token,
+ now,
+ ),
+ db
+ .prepare(
+ `INSERT INTO platform_payment_subscriptions(id,workspace_id,checkout_id,customer_id,product_id,plan_id,interval,quota_anchor,status,period_start,period_end,provider_updated_at,checked_at,next_check_at,error) SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,? WHERE ${fence} ON CONFLICT(id) DO UPDATE SET product_id=excluded.product_id,plan_id=excluded.plan_id,interval=excluded.interval,quota_anchor=excluded.quota_anchor,status=excluded.status,period_start=excluded.period_start,period_end=excluded.period_end,provider_updated_at=excluded.provider_updated_at,checked_at=excluded.checked_at,next_check_at=excluded.next_check_at,error=excluded.error,revision=platform_payment_subscriptions.revision+1`,
+ )
+ .bind(
+ subscriptionId,
+ checkout.workspace_id,
+ checkout.id,
+ objectId(s.customer),
+ objectId(s.product),
+ planId,
+ interval,
+ anchor,
+ s.status,
+ start,
+ until,
+ updated,
+ now,
+ Math.max(now + 60000, Math.min(now + 900000, until)),
+ canAssign ? null : 'payment_grant_superseded',
+ checkout.workspace_id,
+ token,
+ now,
+ ),
+ db
+ .prepare(
+ `UPDATE platform_payment_checkouts SET provider_id=?,state='completed',error=NULL,updated_at=? WHERE id=? AND ${fence}`,
+ )
+ .bind(
+ providerCheckout.id,
+ now,
+ checkout.id,
+ checkout.workspace_id,
+ token,
+ now,
+ ),
+ ]
+ if (canAssign) {
+ statements.push(
+ db
+ .prepare(
+ `UPDATE platform_workspace_plans SET plan_id=${active ? '?' : EXPIRY_PLAN_SQL},source=?,starts_at=?,expires_at=?,billing_interval=?,payment_subscription_id=?,revision=revision+1 WHERE workspace_id=? AND revision=? AND ${fence}`,
+ )
+ .bind(
+ ...(active ? [planId] : []),
+ active ? 'payment' : 'expired_default',
+ anchor,
+ active ? until : null,
+ active ? interval : null,
+ subscriptionId,
+ checkout.workspace_id,
+ prior?.revision ?? 0,
+ checkout.workspace_id,
+ token,
+ now,
+ ),
+ )
+ statements.push(
+ ...subscriptionInvalidation(db, checkout.workspace_id, eventId),
+ )
+ }
+ const results = await db.batch(statements)
+ if (!results[0]?.meta.changes) fail(409, 'payment_lease_lost')
+ return 'done'
+ } finally {
+ await releaseWorkspace(db, checkout.workspace_id, token)
+ }
+}
+/** Durable signed-event inbox. Retries use authoritative API reads, not stale event snapshots. */
+export async function processPaymentEvents(
+ db: PlatformD1,
+ rootKey: string,
+ transport: PaymentFetch = fetch,
+ now = Date.now(),
+ limit = 5,
+) {
+ await db
+ .prepare(
+ "UPDATE platform_payment_events SET state=CASE WHEN EXISTS(SELECT 1 FROM platform_subscription_events r WHERE r.id='creem:'||platform_payment_events.id) THEN 'done' ELSE 'failed' END,error=CASE WHEN EXISTS(SELECT 1 FROM platform_subscription_events r WHERE r.id='creem:'||platform_payment_events.id) THEN NULL ELSE 'payment_attempts_exhausted' END,lease_token=NULL,lease_until=NULL WHERE state='pending' AND attempts>=8 AND (lease_until IS NULL OR lease_until<?)",
+ )
+ .bind(now)
+ .run()
+ 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 ?",
+ )
+ .bind(now, now, limit),
+ )
+ let processed = 0
+ for (const row of rows) {
+ const token = crypto.randomUUID()
+ const claim = await db
+ .prepare(
+ "UPDATE platform_payment_events SET lease_token=?,lease_until=?,attempts=attempts+1 WHERE id=? AND state='pending' AND attempts<8 AND available_at<=? AND (lease_until IS NULL OR lease_until<?) RETURNING attempts",
+ )
+ .bind(token, now + 60000, row.id, now, now)
+ .first<any>()
+ if (!claim) continue
+ try {
+ const state = await synchronizePayment(db, rootKey, row, transport, now)
+ await db
+ .prepare(
+ 'UPDATE platform_payment_events SET state=?,error=NULL,lease_token=NULL,lease_until=NULL WHERE id=? AND lease_token=?',
+ )
+ .bind(state, row.id, token)
+ .run()
+ processed++
+ } catch (e) {
+ const code =
+ e instanceof SubscriptionError ? e.code : 'payment_sync_failed'
+ await db
+ .prepare(
+ 'UPDATE platform_payment_events SET state=?,error=?,available_at=?,lease_token=NULL,lease_until=NULL WHERE id=? AND lease_token=?',
+ )
+ .bind(
+ claim.attempts >= 8 ? 'failed' : 'pending',
+ code,
+ now + Math.min(3600000, 30000 * 2 ** Math.min(7, claim.attempts - 1)),
+ row.id,
+ token,
+ )
+ .run()
+ }
+ }
+ return { processed }
+}
+export async function reconcilePayments(
+ db: PlatformD1,
+ rootKey: string,
+ transport: PaymentFetch = fetch,
+ now = Date.now(),
+) {
+ const settings = await paymentSettings(db)
+ if (!settings.configured) return
+ const due = await allRows<any>(
+ db
+ .prepare(
+ "SELECT id FROM platform_payment_subscriptions WHERE next_check_at<=? AND status NOT IN('expired','canceled') ORDER BY next_check_at LIMIT 3",
+ )
+ .bind(now),
+ )
+ for (const row of due) {
+ await db
+ .prepare(
+ "INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,created_at,available_at) VALUES(?,'subscription.update',?,?,?)",
+ )
+ .bind('sync_' + row.id + '_' + Math.floor(now / 60000), row.id, now, now)
+ .run()
+ await db
+ .prepare(
+ 'UPDATE platform_payment_subscriptions SET next_check_at=? WHERE id=?',
+ )
+ .bind(now + 900000, row.id)
+ .run()
+ }
+ // Open and uncertain checkouts are never silently retried or expired locally: verify with Creem first.
+ const open = await allRows<any>(
+ db
+ .prepare(
+ "SELECT id,provider_id FROM platform_payment_checkouts WHERE state IN('open','uncertain') AND provider_id IS NOT NULL AND updated_at<? ORDER BY updated_at LIMIT 3",
+ )
+ .bind(now - 60000),
+ )
+ for (const row of open) {
+ try {
+ const checkout = await creemRequest(
+ await paymentSecrets(db, rootKey),
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(row.provider_id),
+ undefined,
+ transport,
+ )
+ if (checkout.mode !== 'test' || checkout.request_id !== row.id) continue
+ if (checkout.status === 'expired')
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='expired',updated_at=?,error=NULL WHERE id=? AND state IN('open','uncertain')",
+ )
+ .bind(now, row.id)
+ .run()
+ else if (checkout.status === 'completed')
+ await db
+ .prepare(
+ "INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,reference_id,created_at,available_at) VALUES(?,'checkout.completed',?,?,?,?)",
+ )
+ .bind(
+ 'checkout_sync_' + row.id + '_' + Math.floor(now / 60000),
+ row.provider_id,
+ row.id,
+ now,
+ now,
+ )
+ .run()
+ } catch {
+ /* The signed inbox and the next bounded scan retain recoverability. */
+ }
+ }
+ await processPaymentEvents(db, rootKey, transport, now)
+ await db
+ .prepare('DELETE FROM platform_payment_requests WHERE window_start<?')
+ .bind(now - 86400000)
+ .run()
+}
+/** Reattach an ambiguous create only after Creem proves the original immutable request binding. */
+export async function recoverPaymentCheckout(
+ db: PlatformD1,
+ rootKey: string,
+ checkoutId: string,
+ providerId: string,
+ transport: PaymentFetch = fetch,
+ now = Date.now(),
+) {
+ if (!identifier(providerId)) fail(400, 'payment_checkout_invalid')
+ const row = await db
+ .prepare(
+ "SELECT * FROM platform_payment_checkouts WHERE id=? AND state IN('creating','uncertain','open')",
+ )
+ .bind(checkoutId)
+ .first<any>()
+ if (!row) fail(404, 'payment_checkout_unavailable')
+ const c = await creemRequest(
+ await paymentSecrets(db, rootKey),
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(providerId),
+ undefined,
+ transport,
+ )
+ if (
+ c.id !== providerId ||
+ c.mode !== 'test' ||
+ c.request_id !== row.id ||
+ objectId(c.product) !== row.product_id
+ )
+ fail(422, 'payment_binding_invalid')
+ const url = c.status === 'expired' ? null : paymentURL(c.checkout_url)
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET provider_id=?,checkout_url=?,state=?,error=NULL,updated_at=? WHERE id=? AND state IN('creating','uncertain','open')",
+ )
+ .bind(
+ providerId,
+ url,
+ c.status === 'expired' ? 'expired' : 'open',
+ now,
+ checkoutId,
+ )
+ .run()
+ if (c.status === 'completed')
+ await db
+ .prepare(
+ "INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,reference_id,created_at,available_at) VALUES(?,'checkout.completed',?,?,?,?)",
+ )
+ .bind(
+ 'recover_' + row.id + '_' + Math.floor(now / 60000),
+ providerId,
+ row.id,
+ now,
+ now,
+ )
+ .run()
+ return { ok: true }
+}
+/** Account erasure cannot remove the local ledger while an upstream subscription can still bill. */
+export async function closeAccountPayments(
+ db: PlatformD1,
+ rootKey: string,
+ userId: number,
+ transport: PaymentFetch = fetch,
+) {
+ const open = await allRows<any>(
+ db
+ .prepare(
+ "SELECT c.* FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE (w.owner_user_id=? OR c.user_id=?) AND c.state IN('creating','open','uncertain')",
+ )
+ .bind(userId, userId),
+ )
+ const rows = await allRows<any>(
+ db
+ .prepare(
+ "SELECT s.id,s.workspace_id FROM platform_payment_subscriptions s JOIN platform_workspaces w ON w.id=s.workspace_id JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE (w.owner_user_id=? OR c.user_id=?) AND s.status NOT IN('canceled','expired')",
+ )
+ .bind(userId, userId),
+ )
+ if (!open.length && !rows.length) return true
+ const credentials = await paymentSecrets(db, rootKey)
+ async function cancel(id: string) {
+ let s = await creemRequest(
+ credentials,
+ '/v1/subscriptions?subscription_id=' + encodeURIComponent(id),
+ undefined,
+ transport,
+ )
+ if (s.mode !== 'test' || s.id !== id) return false
+ if (!['canceled', 'expired'].includes(s.status))
+ s = await creemRequest(
+ credentials,
+ '/v1/subscriptions/' + encodeURIComponent(id) + '/cancel',
+ { mode: 'immediate' },
+ transport,
+ )
+ return (
+ s.mode === 'test' &&
+ s.id === id &&
+ ['canceled', 'expired'].includes(s.status)
+ )
+ }
+ for (const row of open) {
+ if (!row.provider_id) return false
+ const c = await creemRequest(
+ credentials,
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(row.provider_id),
+ undefined,
+ transport,
+ )
+ if (
+ c.mode !== 'test' ||
+ c.request_id !== row.id ||
+ objectId(c.product) !== row.product_id
+ )
+ return false
+ if (c.status === 'expired')
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='expired',updated_at=? WHERE id=?",
+ )
+ .bind(Date.now(), row.id)
+ .run()
+ else if (
+ c.status === 'completed' &&
+ identifier(objectId(c.subscription)) &&
+ (await cancel(objectId(c.subscription)))
+ )
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='completed',updated_at=? WHERE id=?",
+ )
+ .bind(Date.now(), row.id)
+ .run()
+ else return false
+ }
+ for (const row of rows) {
+ if (!(await cancel(row.id))) return false
+ const now = Date.now(),
+ eventId = 'account-close:' + row.id
+ const prior = await db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=?')
+ .bind(row.workspace_id)
+ .first<any>()
+ await db.batch([
+ db
+ .prepare(
+ "INSERT OR IGNORE INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) VALUES(?,?,'payment',?,?,?)",
+ )
+ .bind(
+ eventId,
+ row.workspace_id,
+ JSON.stringify({ planId: prior?.plan_id, source: prior?.source }),
+ JSON.stringify({
+ source: 'expired_default',
+ subscriptionId: row.id,
+ accountClosure: true,
+ }),
+ now,
+ ),
+ db
+ .prepare(
+ "UPDATE platform_payment_subscriptions SET status='canceled',checked_at=?,error=NULL,revision=revision+1 WHERE id=?",
+ )
+ .bind(now, row.id),
+ db
+ .prepare(
+ `UPDATE platform_workspace_plans SET plan_id=${EXPIRY_PLAN_SQL},source='expired_default',expires_at=NULL,billing_interval=NULL,revision=revision+1 WHERE workspace_id=? AND payment_subscription_id=? AND source IN('payment','expired_default')`,
+ )
+ .bind(row.workspace_id, row.id),
+ ...subscriptionInvalidation(db, row.workspace_id, eventId),
+ ])
+ }
+ return true
+}
diff --git a/tests/platform-payments.test.ts b/tests/platform-payments.test.ts
new file mode 100644
index 00000000..b729cfb1
--- /dev/null
+++ b/tests/platform-payments.test.ts
@@ -0,0 +1,962 @@
+import {
+ accountExemption,
+ DEFAULT_EXEMPTIONS,
+} from '../packages/platform/src/lifecycle-exemptions.ts'
+import { markAccount } from '../packages/platform/src/account-lifecycle.ts'
+import { purgeAccounts } from '../packages/platform/src/account-purge.ts'
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readFile, readdir } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import {
+ creemRequest,
+ sealPaymentSecrets,
+ paymentSecrets,
+ paymentSettings,
+ paymentStatus,
+ createPaymentCheckout,
+ createPaymentPortal,
+ receivePaymentEvent,
+ processPaymentEvents,
+ recoverPaymentCheckout,
+ closeAccountPayments,
+ validatePaymentProduct,
+ reconcilePayments,
+} from '../packages/platform/src/payments.ts'
+import {
+ resolveSubscription,
+ reconcileSubscriptions,
+} from '../packages/platform/src/subscriptions.ts'
+const require = createRequire(import.meta.url)
+const { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+)('miniflare')
+const root = 'local-payment-root-key-'.repeat(3),
+ credentials = {
+ apiKey: 'creem_test_local_fixture_only',
+ webhookSecret: 'fixture-webhook-signature-secret',
+ }
+async function fixture() {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-26',
+ script: 'export default {fetch(){return new Response("ok")}}',
+ d1Databases: ['DB'],
+ }),
+ ),
+ db = await mf.getD1Database('DB'),
+ now = Date.now()
+ for (const file of (
+ await readdir(new URL('../packages/platform/migrations/', import.meta.url))
+ )
+ .filter((f) => f.endsWith('.sql'))
+ .sort()) {
+ for (const sql of (
+ await readFile(
+ new URL('../packages/platform/migrations/' + file, import.meta.url),
+ 'utf8',
+ )
+ )
+ .replace(/^--.*$/gm, '')
+ .split(';')
+ .filter((s) => s.trim()))
+ await db.prepare(sql).run()
+ }
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,name,email_verified,created_at,updated_at) VALUES(1,'[email protected]','Owner',1,?,?),(2,'[email protected]','Other',1,?,?),(3,'[email protected]','Member',1,?,?)",
+ )
+ .bind(now, now, now, now, now, now)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspaces(id,name,owner_user_id,created_at) VALUES(1,'First',1,?),(2,'Second',2,?)",
+ )
+ .bind(now, now)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_memberships(workspace_id,user_id,role) VALUES(1,1,'admin'),(2,2,'admin'),(1,3,'member')",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspace_plans(workspace_id,plan_id,starts_at,source) VALUES(1,'free',?,'default'),(2,'free',?,'default')",
+ )
+ .bind(now - 86400000, now)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_plans(id,name,policy_json,currency,monthly_price,quarterly_price) SELECT 'pro','Pro',policy_json,'USD',1200,3000 FROM platform_plans WHERE id='free'",
+ )
+ .run()
+ await db
+ .prepare(
+ "UPDATE platform_payment_settings SET enabled=1,workspace_ids_json='[1]',credentials_ciphertext=?",
+ )
+ .bind(await sealPaymentSecrets(root, credentials))
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_payment_products(plan_id,interval,product_id,price,currency) VALUES('pro',1,'prod_month',1200,'USD'),('pro',3,'prod_quarter',3000,'USD')",
+ )
+ .run()
+ const checkouts = new Map<string, any>(),
+ subscriptions = new Map<string, any>(),
+ calls: string[] = []
+ let broken = false,
+ uncertain = false,
+ productPrice = 1200,
+ rejected = false
+ const transport = async (url: any, init: any = {}) => {
+ const u = new URL(String(url))
+ assert.equal(u.origin, 'https://test-api.creem.io')
+ assert.equal(init.headers['x-api-key'], credentials.apiKey)
+ assert.equal(init.redirect, 'manual')
+ calls.push((init.method ?? 'GET') + ' ' + u.pathname)
+ if (broken) return new Response('{}', { status: 503 })
+ if (u.pathname === '/v1/products') {
+ const quarter = u.searchParams.get('product_id') === 'prod_quarter'
+ return Response.json({
+ id: quarter ? 'prod_quarter' : 'prod_month',
+ mode: 'test',
+ billing_type: 'recurring',
+ billing_period: quarter ? 'every-three-months' : 'every-month',
+ price: quarter ? 3000 : productPrice,
+ currency: 'USD',
+ name: 'Pro',
+ })
+ }
+ if (u.pathname === '/v1/checkouts' && init.method === 'POST') {
+ if (rejected) return Response.json({}, { status: 401 })
+ const b = JSON.parse(init.body),
+ id = 'chk_' + (checkouts.size + 1)
+ const c = {
+ id,
+ mode: 'test',
+ status: 'pending',
+ request_id: b.request_id,
+ product: b.product_id,
+ metadata: b.metadata,
+ customer: { id: 'cust_fixture' },
+ checkout_url: 'https://checkout.creem.io/' + id,
+ }
+ checkouts.set(id, c)
+ if (uncertain)
+ throw new Error('Provider response lost after creating checkout')
+ return Response.json(c)
+ }
+ if (u.pathname === '/v1/checkouts')
+ return Response.json(
+ checkouts.get(u.searchParams.get('checkout_id')!) ?? {},
+ )
+ if (u.pathname === '/v1/subscriptions')
+ return Response.json(
+ subscriptions.get(u.searchParams.get('subscription_id')!) ?? {},
+ )
+ if (u.pathname === '/v1/customers')
+ return Response.json({
+ id: 'cust_fixture',
+ mode: 'test',
+ email: '[email protected]',
+ })
+ if (u.pathname === '/v1/customers/billing')
+ return Response.json({
+ customer_portal_link: 'https://creem.io/my-orders/login/fixture',
+ })
+ if (u.pathname.endsWith('/cancel')) {
+ const id = u.pathname.split('/')[3],
+ s = subscriptions.get(id)
+ assert.equal(JSON.parse(init.body).mode, 'immediate')
+ s.status = 'canceled'
+ return Response.json(s)
+ }
+ throw new Error('Unexpected Creem operation')
+ }
+ async function complete(id = 'chk_1') {
+ const c = checkouts.get(id),
+ s = {
+ id: 'sub_' + id,
+ mode: 'test',
+ status: 'active',
+ product: c.product,
+ customer: c.customer,
+ metadata: c.metadata,
+ current_period_start_date: new Date(now - 1000).toISOString(),
+ current_period_end_date: new Date(now + 30 * 86400000).toISOString(),
+ updated_at: new Date(now).toISOString(),
+ }
+ c.status = 'completed'
+ c.subscription = s.id
+ subscriptions.set(s.id, s)
+ return s
+ }
+ async function event(id: string, type: string, object: any, at = now) {
+ const body = new TextEncoder().encode(
+ JSON.stringify({ id, eventType: type, created_at: at, object }),
+ )
+ const key = await crypto.subtle.importKey(
+ 'raw',
+ new TextEncoder().encode(credentials.webhookSecret),
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['sign'],
+ )
+ const signature = [
+ ...new Uint8Array(await crypto.subtle.sign('HMAC', key, body)),
+ ]
+ .map((v) => v.toString(16).padStart(2, '0'))
+ .join('')
+ return {
+ body,
+ signature,
+ receive: () => receivePaymentEvent(db, root, body, signature, at),
+ }
+ }
+ const input = {
+ workspaceId: 1,
+ planId: 'pro',
+ interval: 1,
+ requestId: 'client_request_1',
+ }
+ return {
+ mf,
+ db,
+ now,
+ transport: transport as typeof fetch,
+ calls,
+ checkouts,
+ subscriptions,
+ input,
+ complete,
+ event,
+ setRejected(v: boolean) {
+ rejected = v
+ },
+ setBroken(v: boolean) {
+ broken = v
+ },
+ setUncertain(v: boolean) {
+ uncertain = v
+ },
+ setPrice(v: number) {
+ productPrice = v
+ },
+ }
+}
+
+test('Payment credentials are authenticated-encrypted, test-only, workspace-admin scoped and price checked', async () => {
+ const f = await fixture()
+ try {
+ const stored = await f.db
+ .prepare('SELECT credentials_ciphertext FROM platform_payment_settings')
+ .first<any>()
+ assert.ok(!stored.credentials_ciphertext.includes(credentials.apiKey))
+ assert.deepEqual(await paymentSecrets(f.db, root), credentials)
+ await assert.rejects(paymentSecrets(f.db, 'different-root-key-'.repeat(4)))
+ assert.deepEqual((await paymentSettings(f.db)).workspaceIds, [1])
+ assert.equal((await paymentStatus(f.db, 1, 1)).offers.length, 2)
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 3,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ ),
+ { statusCode: 403 },
+ )
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 2,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ ),
+ { statusCode: 403 },
+ )
+ f.setPrice(100)
+ await assert.rejects(
+ validatePaymentProduct(
+ f.db,
+ credentials,
+ 'pro',
+ 1,
+ 'prod_month',
+ f.transport,
+ ),
+ { code: 'payment_product_mismatch' },
+ )
+ assert.equal(f.calls.filter((v) => v === 'POST /v1/checkouts').length, 0)
+ await f.db
+ .prepare("UPDATE platform_payment_settings SET workspace_ids_json='[]'")
+ .run()
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ ),
+ { code: 'payment_checkout_disabled' },
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Concurrent checkout creation, raw signatures, durable deduplication and authoritative grants', async () => {
+ const f = await fixture()
+ try {
+ const results = await Promise.allSettled(
+ [1, 2, 3].map(() =>
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ ),
+ ),
+ )
+ assert.equal(f.calls.filter((v) => v === 'POST /v1/checkouts').length, 1)
+ assert.ok(results.some((v) => v.status === 'fulfilled'))
+ assert.equal((await resolveSubscription(f.db, 1, f.now)).id, 'free')
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ assert.equal(f.calls.filter((v) => v === 'POST /v1/checkouts').length, 1)
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...f.input, interval: 3 },
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ ),
+ { code: 'payment_request_reused' },
+ )
+ const s = await f.complete(),
+ e = await f.event(
+ 'evt_first',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ )
+ await assert.rejects(
+ receivePaymentEvent(f.db, root, e.body, '0'.repeat(64), f.now),
+ { code: 'payment_signature_invalid' },
+ )
+ const live = await f.event('evt_live', 'checkout.completed', {
+ ...f.checkouts.get('chk_1'),
+ mode: 'prod',
+ })
+ await assert.rejects(live.receive(), { code: 'payment_event_invalid' })
+ await Promise.all([e.receive(), e.receive(), e.receive()])
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_events')
+ .first<any>()
+ ).n,
+ 1,
+ )
+ await Promise.all(
+ [1, 2, 3].map(() => processPaymentEvents(f.db, root, f.transport, f.now)),
+ )
+ const current = await resolveSubscription(f.db, 1, f.now)
+ assert.equal(current.id, 'pro')
+ assert.equal(current.subscription.source, 'payment')
+ assert.equal(
+ current.subscription.expiresAt,
+ Date.parse(s.current_period_end_date),
+ )
+ const revision = current.subscription.revision
+ await e.receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 1)
+ assert.equal(
+ (await resolveSubscription(f.db, 1, f.now)).subscription.revision,
+ revision,
+ )
+ await assert.rejects(createPaymentPortal(f.db, root, 3, 1, f.transport), {
+ statusCode: 403,
+ })
+ assert.match(
+ (await createPaymentPortal(f.db, root, 1, 1, f.transport)).url,
+ /^https:\/\/creem.io\//,
+ )
+ await f.db
+ .prepare(
+ "INSERT INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,state,created_at,updated_at) SELECT 'scope_checkout',2,2,'scope_request',plan_id,interval,product_id,price,currency,1,'completed',created_at,updated_at FROM platform_payment_checkouts LIMIT 1",
+ )
+ .run()
+ await f.db
+ .prepare(
+ "INSERT INTO platform_payment_subscriptions(id,workspace_id,checkout_id,customer_id,product_id,plan_id,interval,quota_anchor,status,period_start,period_end,provider_updated_at,checked_at,next_check_at) SELECT 'sub_scope',2,'scope_checkout',customer_id,product_id,plan_id,interval,quota_anchor,'active',period_start,period_end,provider_updated_at,checked_at,next_check_at FROM platform_payment_subscriptions LIMIT 1",
+ )
+ .run()
+ await assert.rejects(createPaymentPortal(f.db, root, 1, 1, f.transport), {
+ code: 'payment_customer_scope_conflict',
+ })
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Renewal, scheduled cancellation, stale webhook snapshots and immediate cancellation follow provider truth', async () => {
+ const f = await fixture()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ const s = await f.complete()
+ await (
+ await f.event('evt_start', 'checkout.completed', f.checkouts.get('chk_1'))
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ const anchor = (await resolveSubscription(f.db, 1, f.now)).subscription
+ .startsAt
+ s.current_period_end_date = new Date(f.now + 60 * 86400000).toISOString()
+ s.updated_at = new Date(f.now + 1).toISOString()
+ await (
+ await f.event('evt_renew', 'subscription.paid', s, f.now + 1)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 1)
+ assert.equal(
+ (await resolveSubscription(f.db, 1, f.now + 1)).subscription.startsAt,
+ anchor,
+ )
+ s.status = 'scheduled_cancel'
+ s.updated_at = new Date(f.now + 2).toISOString()
+ await (
+ await f.event(
+ 'evt_scheduled',
+ 'subscription.scheduled_cancel',
+ s,
+ f.now + 2,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 2)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 2)).id, 'pro')
+ await (
+ await f.event(
+ 'evt_old',
+ 'subscription.paused',
+ { ...s, status: 'paused' },
+ f.now,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 3)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 3)).id, 'pro')
+ s.status = 'canceled'
+ s.updated_at = new Date(f.now + 4).toISOString()
+ await (
+ await f.event('evt_cancel', 'subscription.canceled', s, f.now + 4)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 4)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 4)).id, 'free')
+ s.status = 'unpaid'
+ s.updated_at = new Date(f.now + 5).toISOString()
+ await (
+ await f.event('evt_unpaid', 'subscription.unpaid', s, f.now + 5)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 5)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 5)).id, 'free')
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ "SELECT state FROM platform_payment_events WHERE id='evt_unpaid'",
+ )
+ .first<any>()
+ ).state,
+ 'done',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Ambiguous creates are not repeated; verified recovery and bounded retries restore the original checkout', async () => {
+ const f = await fixture()
+ try {
+ f.setUncertain(true)
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ ),
+ { code: 'payment_confirmation_pending' },
+ )
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...f.input, requestId: 'another' },
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ ),
+ { code: 'payment_confirmation_pending' },
+ )
+ assert.equal(f.calls.filter((v) => v === 'POST /v1/checkouts').length, 1)
+ const row = await f.db
+ .prepare('SELECT id FROM platform_payment_checkouts')
+ .first<any>()
+ await f.complete()
+ await recoverPaymentCheckout(
+ f.db,
+ root,
+ row.id,
+ 'chk_1',
+ f.transport,
+ f.now,
+ )
+ f.setBroken(true)
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ const e = await f.db
+ .prepare('SELECT * FROM platform_payment_events')
+ .first<any>()
+ assert.equal(e.state, 'pending')
+ assert.equal(e.attempts, 1)
+ assert.equal(e.available_at, f.now + 30000)
+ const count = f.calls.length
+ await processPaymentEvents(f.db, root, f.transport, f.now + 1)
+ assert.equal(f.calls.length, count)
+ f.setBroken(false)
+ await processPaymentEvents(f.db, root, f.transport, f.now + 30001)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 30001)).id, 'pro')
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Manual grants supersede late renewals; expiry reconciliation can safely recover a renewed payment term', async () => {
+ const f = await fixture()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ const s = await f.complete()
+ await (
+ await f.event('evt_begin', 'checkout.completed', f.checkouts.get('chk_1'))
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ const originalAnchor = (await resolveSubscription(f.db, 1, f.now))
+ .subscription.startsAt
+ const expiry = Date.parse(s.current_period_end_date)
+ await reconcileSubscriptions(f.db, expiry + 1)
+ s.current_period_start_date = new Date(expiry).toISOString()
+ s.current_period_end_date = new Date(expiry + 30 * 86400000).toISOString()
+ s.updated_at = new Date(expiry + 1).toISOString()
+ await (
+ await f.event('evt_after_expiry', 'subscription.paid', s, expiry + 1)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, expiry + 1)
+ assert.equal((await resolveSubscription(f.db, 1, expiry + 1)).id, 'pro')
+ assert.equal(
+ (await resolveSubscription(f.db, 1, expiry + 1)).subscription.startsAt,
+ originalAnchor,
+ )
+ await f.db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='free',source='manual',payment_subscription_id=NULL,revision=revision+1 WHERE workspace_id=1",
+ )
+ .run()
+ await (
+ await f.event('evt_late', 'subscription.paid', s, expiry + 2)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, expiry + 2)
+ assert.equal((await resolveSubscription(f.db, 1, expiry + 2)).id, 'free')
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT error FROM platform_payment_subscriptions')
+ .first<any>()
+ ).error,
+ 'payment_grant_superseded',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Account cleanup waits for upstream cancellation; open expired sessions are reconciled from the provider', async () => {
+ const f = await fixture()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ const s = await f.complete()
+ await (
+ await f.event(
+ 'evt_cleanup',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ f.setBroken(true)
+ await assert.rejects(closeAccountPayments(f.db, root, 1, f.transport))
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT status FROM platform_payment_subscriptions')
+ .first<any>()
+ ).status,
+ 'active',
+ )
+ f.setBroken(false)
+ assert.equal(await closeAccountPayments(f.db, root, 1, f.transport), true)
+ assert.equal(s.status, 'canceled')
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...f.input, requestId: 'next' },
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now + 1,
+ )
+ f.checkouts.get('chk_2').status = 'expired'
+ await reconcilePayments(f.db, root, f.transport, f.now + 60002)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ "SELECT state FROM platform_payment_checkouts WHERE provider_id='chk_2'",
+ )
+ .first<any>()
+ ).state,
+ 'expired',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Creem transport rejects redirects and live keys before any forwarded request', async () => {
+ let calls = 0
+ const transport = async (url: any, init: any) => {
+ calls++
+ assert.equal(new URL(url).origin, 'https://test-api.creem.io')
+ assert.equal(init.redirect, 'manual')
+ return new Response(null, {
+ status: 302,
+ headers: { location: 'https://attacker.example/' },
+ })
+ }
+ await assert.rejects(
+ creemRequest(
+ credentials,
+ '/v1/products/search',
+ undefined,
+ transport as typeof fetch,
+ ),
+ { code: 'payment_provider_request_failed' },
+ )
+ await assert.rejects(
+ creemRequest(
+ { ...credentials, apiKey: 'creem_live_fixture' },
+ '/v1/products/search',
+ undefined,
+ transport as typeof fetch,
+ ),
+ { code: 'payment_test_mode_required' },
+ )
+ assert.equal(calls, 1)
+})
+test('A single automatic trial-expiry transition does not suppress checkout; crashed inbox attempts stop at the budget', async () => {
+ const f = await fixture()
+ try {
+ await f.db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='pro',source='promotion',expires_at=? WHERE workspace_id=1",
+ )
+ .bind(f.now + 1)
+ .run()
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ await reconcileSubscriptions(f.db, f.now + 2)
+ await f.complete()
+ await (
+ await f.event(
+ 'evt_trial_expiry',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ f.now + 3,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 3)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 3)).id, 'pro')
+ await f.db
+ .prepare(
+ "INSERT INTO platform_payment_events(id,type,object_id,created_at,available_at,attempts,lease_token,lease_until) VALUES('evt_crashed','subscription.paid','sub_crashed',?,?,8,'running',?)",
+ )
+ .bind(f.now, f.now, f.now + 1000)
+ .run()
+ const count = f.calls.length
+ await processPaymentEvents(f.db, root, f.transport, f.now + 4)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ "SELECT state FROM platform_payment_events WHERE id='evt_crashed'",
+ )
+ .first<any>()
+ ).state,
+ 'pending',
+ )
+ await processPaymentEvents(f.db, root, f.transport, f.now + 1001)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ "SELECT state FROM platform_payment_events WHERE id='evt_crashed'",
+ )
+ .first<any>()
+ ).state,
+ 'failed',
+ )
+ assert.equal(f.calls.length, count)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Definitive provider rejections release the checkout slot without repeating an uncertain create', async () => {
+ const f = await fixture()
+ try {
+ f.setRejected(true)
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ ),
+ { code: 'payment_provider_request_failed' },
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT state FROM platform_payment_checkouts')
+ .first<any>()
+ ).state,
+ 'expired',
+ )
+ assert.equal(f.checkouts.size, 0)
+ f.setRejected(false)
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...f.input, requestId: 'retry_after_key_repair' },
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now + 1,
+ )
+ assert.equal(f.checkouts.size, 1)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Paid checkout snapshots survive price edits; actual purchasers qualify without borrowing another member subscription', async () => {
+ const f = await fixture()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ await f.db
+ .prepare("UPDATE platform_plans SET monthly_price=2400 WHERE id='pro'")
+ .run()
+ await f.complete()
+ await (
+ await f.event(
+ 'evt_saved_quote',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ assert.equal((await resolveSubscription(f.db, 1, f.now)).id, 'pro')
+ await f.db
+ .prepare(
+ "INSERT INTO platform_users(id,email,name,email_verified,created_at,updated_at) VALUES(4,'[email protected]','New owner',1,?,?)",
+ )
+ .bind(f.now, f.now)
+ .run()
+ await f.db
+ .prepare('UPDATE platform_workspaces SET owner_user_id=4 WHERE id=1')
+ .run()
+ assert.equal(
+ await accountExemption(f.db, 1, DEFAULT_EXEMPTIONS, f.now),
+ true,
+ )
+ assert.equal(
+ await accountExemption(f.db, 3, DEFAULT_EXEMPTIONS, f.now),
+ false,
+ )
+ await markAccount(
+ f.db,
+ 1,
+ 'Requested account deletion',
+ 'admin',
+ null,
+ f.now,
+ )
+ await purgeAccounts(
+ f.db,
+ {
+ billing: (id) => closeAccountPayments(f.db, root, id, f.transport),
+ domains: async () => true,
+ storage: async () => true,
+ },
+ f.now + 16 * 86400000,
+ )
+ assert.equal(
+ await f.db.prepare('SELECT id FROM platform_users WHERE id=1').first(),
+ null,
+ )
+ assert.ok(
+ await f.db
+ .prepare(
+ 'SELECT id FROM platform_workspaces WHERE id=1 AND owner_user_id=4',
+ )
+ .first(),
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT status FROM platform_payment_subscriptions')
+ .first<any>()
+ ).status,
+ 'canceled',
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT user_id FROM platform_payment_checkouts')
+ .first<any>()
+ ).user_id,
+ null,
+ )
+ assert.equal((await resolveSubscription(f.db, 1, f.now)).id, 'free')
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('Owned account erasure removes dependent payment rows only after cancellation succeeds', async () => {
+ const f = await fixture()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ await f.complete()
+ await (
+ await f.event('evt_erase', 'checkout.completed', f.checkouts.get('chk_1'))
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ await markAccount(
+ f.db,
+ 1,
+ 'Requested permanent cleanup',
+ 'admin',
+ null,
+ f.now,
+ )
+ await purgeAccounts(
+ f.db,
+ {
+ billing: (id) => closeAccountPayments(f.db, root, id, f.transport),
+ domains: async () => true,
+ storage: async () => true,
+ },
+ f.now + 16 * 86400000,
+ )
+ assert.equal(
+ await f.db.prepare('SELECT id FROM platform_users WHERE id=1').first(),
+ null,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')
+ .first<any>()
+ ).n,
+ 0,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_checkouts')
+ .first<any>()
+ ).n,
+ 0,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})