Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(payments): add provider profiles and retire Creem runtime
Timothy Yinff4c5b13384f
diff --git a/apps/admin b/apps/adminindex 0e26cbf1..133bde99 160000--- a/apps/admin+++ b/apps/admin@@ -1 +1 @@-Subproject commit 0e26cbf18a88104fce4f27b7fd04e9794ebbe90b+Subproject commit 133bde9980bbfb2c86f615179cba384cf658068adiff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vueindex 59b0700a..5802b490 100644--- a/apps/cloud/app/components/CloudPricing.vue+++ b/apps/cloud/app/components/CloudPricing.vue@@ -99,11 +99,6 @@ const offer = (plan: any) =>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) returnconst workspaceId = billing.selected.value,@@ -303,15 +298,6 @@ async function checkout(plan: any) {variant="secondary">{{ $t('cloud.billing.current') }}</CfButton>- <CfButton- 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') }}</CfButton- ><CfButtonv-else-if="portal && offer(plan)":loading="paying === plan.id + ':' + interval"diff --git a/apps/cloud/app/composables/useCheckoutReturn.ts b/apps/cloud/app/composables/useCheckoutReturn.tsdeleted file mode 100644index a85b03d2..00000000--- a/apps/cloud/app/composables/useCheckoutReturn.ts+++ /dev/null@@ -1,97 +0,0 @@-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'- | 'inactive'- | 'superseded'- >(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,- providerCheckoutId:- typeof route.query.checkout_id === 'string'- ? route.query.checkout_id- : undefined,- subscriptionId:- typeof route.query.subscription_id === 'string'- ? route.query.subscription_id- : undefined,- },- },- )- if (!alive || current !== generation) return- await refresh()- if (!alive || current !== generation) return- if (['completed', 'inactive', 'superseded'].includes(result.state)) {- state.value = result.state as 'completed' | 'inactive' | 'superseded'- return- }- if (result.state === 'expired') {- state.value = 'expired'- return- }- } catch (e: any) {- if (!alive || current !== generation) return- if ([400, 401, 403, 404, 422].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,- route.query.checkout_id,- route.query.subscription_id,- 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/useCloudPayments.ts b/apps/cloud/app/composables/useCloudPayments.tsindex b4a5893f..799391e7 100644--- a/apps/cloud/app/composables/useCloudPayments.ts+++ b/apps/cloud/app/composables/useCloudPayments.ts@@ -41,23 +41,5 @@ export function useCloudPayments(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 }+ return { data, busy, error, refresh }}diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vueindex fb58f38c..3621c616 100644--- a/apps/cloud/app/pages/account/plan.vue+++ b/apps/cloud/app/pages/account/plan.vue@@ -7,14 +7,6 @@ const { t, locale } = useI18n(),const { selected, data, error, listError, status, refresh, retry, ready } =billingconst 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 (@@ -51,19 +43,6 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)<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) }}- <CfButton- v-if="['pending', 'failed'].includes(returned.state.value)"- variant="ghost"- @click="returned.retry"- >{{ $t('cloud.payments.checkAgain') }}</CfButton- >- </p><CfCardv-if="error || listError"role="alert"@@ -107,15 +86,6 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)</p></div><div class="cf-plan-management">- <CfButton- v-if="- payments.data.value?.canManage &&- payments.data.value.subscriptions.length- "- :loading="payments.busy.value"- @click="payments.portal"- >{{ $t('cloud.payments.manage') }}</CfButton- ><CfButtonv-if="data.workspace.role === 'admin'"as-childdiff --git a/apps/cloud/server/api/webhooks/creem.post.ts b/apps/cloud/server/api/webhooks/creem.post.tsindex d62fe50f..0e3bbc4f 100644--- a/apps/cloud/server/api/webhooks/creem.post.ts+++ b/apps/cloud/server/api/webhooks/creem.post.ts@@ -1,49 +1,9 @@-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+import { createError, defineEventHandler } from 'h3'++// Retired endpoint: never read, accept or process a legacy callback.+export default defineEventHandler(() => {+ throw createError({+ statusCode: 410,+ statusMessage: 'payment_provider_retired',+ })})diff --git a/apps/cloud/server/plugins/payments.ts b/apps/cloud/server/plugins/payments.tsindex 1b9d57b2..56431f54 100644--- a/apps/cloud/server/plugins/payments.ts+++ b/apps/cloud/server/plugins/payments.ts@@ -1,22 +1,10 @@-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) {- await syncPaymentProducts(- db,- String(env.NUXT_PLATFORM_STORAGE_SECRET || ''),- ).catch(() => console.error('payment_product_sync_failed'))- await expirePaymentEventPayloads(db).catch(() =>- console.error('payment_payload_expiry_failed'),- )- await reconcilePayments(- db,- String(env.NUXT_PLATFORM_STORAGE_SECRET || ''),- )- }+ // Local data retention continues independently of payment availability.+ if (db) await expirePaymentEventPayloads(db)})})diff --git a/docs/payment-providers.md b/docs/payment-providers.mdnew file mode 100644index 00000000..8429fb51--- /dev/null+++ b/docs/payment-providers.md@@ -0,0 +1,11 @@+# Payment provider configuration++Apply platform migration `0028_payment_providers.sql` before deploying the Cloud and Admin changes. The migration copies the legacy encrypted Creem credentials into a read-only provider profile, selects that profile for existing installations, and disables automatic Creem synchronization. It preserves the payment switch and purchase method introduced in PR #503.++Admin → Payments supports multiple named provider profiles and an independent current-provider selection. Profiles have a stable ID, display name, test/live environment and an encrypted credentials JSON object. Credential fields depend on the future provider adapter; use string keys and values. Leaving the credentials field blank preserves the saved values. Credentials never appear in configuration responses or audit records. Saves and selection changes require an audit reason and the current revision.++Creem is retired. It cannot create checkouts, open a customer portal, accept webhooks, synchronize products or subscriptions, replay events, recover test checkouts, or process checkout returns. Historical subscriptions remain read-only. Existing paid-through entitlements continue to use the ordinary local subscription expiry rules. Account erasure does not contact Creem because its historical subscriptions were sandbox-only.++This change adds configuration storage and selection, not a new payment adapter. New profiles are marked `not_integrated`, and Creem is marked `retired`. Selecting a profile does not make it executable. Public catalogs report online payment unavailable until a supported adapter is implemented. The existing disabled-payment and activation-code purchase behavior is unchanged.++Scheduled local webhook-payload retention continues even when payments are disabled. No provider work is queued or processed. The old Creem webhook URL returns HTTP 410 without accepting the payload.diff --git a/packages/platform/migrations/0028_payment_providers.sql b/packages/platform/migrations/0028_payment_providers.sqlnew file mode 100644index 00000000..a90cfa72--- /dev/null+++ b/packages/platform/migrations/0028_payment_providers.sql@@ -0,0 +1,13 @@+-- Provider configuration is independent from the purchase method and availability switch.+CREATE TABLE platform_payment_providers(+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ environment TEXT NOT NULL CHECK(environment IN('test','live')),+ credentials_ciphertext TEXT,+ revision INTEGER NOT NULL DEFAULT 1,+ updated_at INTEGER NOT NULL DEFAULT 0+);+INSERT INTO platform_payment_providers(id,name,environment,credentials_ciphertext,updated_at)+SELECT 'creem','Creem','test',credentials_ciphertext,updated_at FROM platform_payment_settings WHERE id=1;+ALTER TABLE platform_payment_settings ADD COLUMN current_provider TEXT REFERENCES platform_payment_providers(id);+UPDATE platform_payment_settings SET current_provider='creem',auto_sync=0,revision=revision+1 WHERE id=1;diff --git a/packages/platform/src/billing.ts b/packages/platform/src/billing.tsindex 8f6c83c5..496ccd3c 100644--- a/packages/platform/src/billing.ts+++ b/packages/platform/src/billing.ts@@ -68,7 +68,10 @@ export async function pricingCatalog(db: PlatformD1) {.first<{ new_plan_id: string }>()const payment = await paymentSettings(db)return {- paymentAvailable: payment.enabled && payment.purchaseMethod === 'payment',+ paymentAvailable:+ payment.enabled &&+ payment.providerAvailable &&+ payment.purchaseMethod === 'payment',purchaseMethod: payment.enabled? payment.purchaseMethod: 'activation_code',diff --git a/packages/platform/src/payment-product-sync.ts b/packages/platform/src/payment-product-sync.tsindex fbc57ed8..0ae66004 100644--- a/packages/platform/src/payment-product-sync.ts+++ b/packages/platform/src/payment-product-sync.ts@@ -1,19 +1,7 @@-import type { PlatformD1 } from './index.ts'-import { allRows, SubscriptionError } from './subscriptions.ts'+import { allRows } 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('')-}+import type { PlatformD1 } from './index.ts'+import type { PaymentFetch } from './payments.ts'const names: Record<string, string> = {byos: 'Custom S3 storage',storageBytes: 'Platform storage',@@ -72,13 +60,9 @@ export function paymentProductSnapshot(plan: any, interval: number) {},}}-/** 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()+/** Compatibility boundary for retired Creem synchronization. */+export async function queuePaymentProductSync(_db: PlatformD1) {+ /* Retired: never enqueue Creem work. */}export async function paymentProductSyncStatus(db: PlatformD1) {return allRows<any>(@@ -87,305 +71,13 @@ export async function paymentProductSyncStatus(db: PlatformD1) {),)}-/** The lease and both source revisions fence publication; existing subscription prices are never mutated. */+/** Retired synchronization never reads credentials or contacts a provider. */export async function syncPaymentProducts(- db: PlatformD1,- root: string,- transport: PaymentFetch = fetch,- now = Date.now(),- limit = 2,+ _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- }- let 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')- // An idempotent create can return a product whose description was edited later.- if (- actual.name !== body.name ||- actual.description !== body.description- ) {- await creemRequest(- credentials,- '/v1/products/' + encodeURIComponent(productId!),- { name: body.name, description: body.description },- transport,- { method: 'PATCH' },- )- 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 ||- actual.name !== body.name ||- actual.description !== body.description- )- 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 }+ return { processed: 0 }}diff --git a/packages/platform/src/payment-providers.ts b/packages/platform/src/payment-providers.tsnew file mode 100644index 00000000..1d1bb81d--- /dev/null+++ b/packages/platform/src/payment-providers.ts@@ -0,0 +1,232 @@+import type { PlatformD1 } from './index.ts'+import { allRows, SubscriptionError } from './subscriptions.ts'++const enc = new TextEncoder()+async function providerKey(secret: string) {+ if (secret.length < 32)+ throw new SubscriptionError(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('provider-credentials-v1'),+ },+ material,+ { name: 'AES-GCM', length: 256 },+ false,+ ['encrypt', 'decrypt'],+ )+}+export async function sealProviderCredentials(+ secret: string,+ id: string,+ environment: string,+ credentials: Record<string, string>,+) {+ const nonce = crypto.getRandomValues(new Uint8Array(12))+ const body = await crypto.subtle.encrypt(+ {+ name: 'AES-GCM',+ iv: nonce,+ additionalData: enc.encode(`${id}:${environment}`),+ },+ await providerKey(secret),+ enc.encode(JSON.stringify(credentials)),+ )+ return JSON.stringify([+ btoa(String.fromCharCode(...nonce)),+ btoa(String.fromCharCode(...new Uint8Array(body))),+ ])+}+export async function openProviderCredentials(+ secret: string,+ id: string,+ environment: string,+ envelope: string,+) {+ const [nonce, body] = JSON.parse(envelope)+ const plain = await crypto.subtle.decrypt(+ {+ name: 'AES-GCM',+ iv: Uint8Array.from(atob(nonce), (c) => c.charCodeAt(0)),+ additionalData: enc.encode(`${id}:${environment}`),+ },+ await providerKey(secret),+ Uint8Array.from(atob(body), (c) => c.charCodeAt(0)),+ )+ return JSON.parse(new TextDecoder().decode(plain)) as Record<string, string>+}+export async function paymentProviders(db: PlatformD1) {+ const rows = await allRows<any>(+ db.prepare(+ 'SELECT id,name,environment,revision,credentials_ciphertext IS NOT NULL AS configured FROM platform_payment_providers ORDER BY id',+ ),+ )+ return rows.map((row) => ({+ ...row,+ configured: !!row.configured,+ available: false,+ status: row.id === 'creem' ? 'retired' : 'not_integrated',+ }))+}+/** Configurations can be prepared before an adapter exists. No unknown provider may execute payments. */+export async function savePaymentProvider(+ db: PlatformD1,+ secret: string,+ actorId: number,+ input: any,+) {+ if (+ !input ||+ typeof input.id !== 'string' ||+ !/^[a-z][a-z0-9_-]{0,63}$/.test(input.id) ||+ typeof input.name !== 'string' ||+ !input.name.trim() ||+ input.name.length > 100 ||+ !['test', 'live'].includes(input.environment) ||+ !Number.isSafeInteger(input.revision) ||+ input.revision < 0 ||+ typeof input.reason !== 'string' ||+ input.reason.trim().length < 5 ||+ input.reason.length > 500+ )+ throw new SubscriptionError(400, 'payment_provider_invalid')+ if (input.id === 'creem')+ throw new SubscriptionError(410, 'payment_provider_retired')+ const prior = await db+ .prepare('SELECT * FROM platform_payment_providers WHERE id=?')+ .bind(input.id)+ .first<any>()+ if ((prior?.revision ?? 0) !== input.revision)+ throw new SubscriptionError(409, 'payment_revision_conflict')+ let envelope = prior?.credentials_ciphertext ?? null+ if (input.credentials !== undefined) {+ if (+ !input.credentials ||+ Array.isArray(input.credentials) ||+ typeof input.credentials !== 'object' ||+ Object.keys(input.credentials).length > 30 ||+ Object.entries(input.credentials).some(+ ([k, v]) =>+ !/^[a-zA-Z][a-zA-Z0-9_]{0,63}$/.test(k) ||+ typeof v !== 'string' ||+ v.length > 4096,+ ) ||+ JSON.stringify(input.credentials).length > 12000+ )+ throw new SubscriptionError(400, 'payment_credentials_invalid')+ envelope = await sealProviderCredentials(+ secret,+ input.id,+ input.environment,+ input.credentials,+ )+ } else if (prior && prior.environment !== input.environment && envelope) {+ // Preserve credentials while rebinding the authenticated environment context.+ envelope = await sealProviderCredentials(+ secret,+ input.id,+ input.environment,+ await openProviderCredentials(+ secret,+ input.id,+ prior.environment,+ envelope,+ ),+ )+ }+ const auditId = crypto.randomUUID(),+ now = Date.now()+ const results = await db.batch([+ db+ .prepare(+ "INSERT INTO platform_admin_audit(id,actor_id,action,target,reason,after_json,created_at) SELECT ?,?,'payment-provider',?,?,?,? WHERE COALESCE((SELECT revision FROM platform_payment_providers WHERE id=?),0)=?",+ )+ .bind(+ auditId,+ actorId,+ input.id,+ input.reason.trim(),+ JSON.stringify({+ name: input.name.trim(),+ environment: input.environment,+ configured: !!envelope,+ }),+ now,+ input.id,+ input.revision,+ ),+ db+ .prepare(+ 'INSERT INTO platform_payment_providers(id,name,environment,credentials_ciphertext,updated_at) SELECT ?,?,?,?,? WHERE EXISTS(SELECT 1 FROM platform_admin_audit WHERE id=?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,environment=excluded.environment,credentials_ciphertext=excluded.credentials_ciphertext,updated_at=excluded.updated_at,revision=platform_payment_providers.revision+1',+ )+ .bind(+ input.id,+ input.name.trim(),+ input.environment,+ envelope,+ now,+ auditId,+ ),+ ])+ if (!results[0]?.meta.changes)+ throw new SubscriptionError(409, 'payment_revision_conflict')+ return { ok: true }+}+export async function selectPaymentProvider(+ db: PlatformD1,+ actorId: number,+ input: any,+) {+ if (+ !input ||+ !Number.isSafeInteger(input.revision) ||+ typeof input.reason !== 'string' ||+ input.reason.trim().length < 5 ||+ input.reason.length > 500 ||+ (input.id !== null &&+ (typeof input.id !== 'string' ||+ !/^[a-z][a-z0-9_-]{0,63}$/.test(input.id)))+ )+ throw new SubscriptionError(400, 'payment_provider_invalid')+ if (+ input.id !== null &&+ !(await db+ .prepare('SELECT id FROM platform_payment_providers WHERE id=?')+ .bind(input.id)+ .first())+ )+ throw new SubscriptionError(400, 'payment_provider_invalid')+ const id = crypto.randomUUID(),+ now = Date.now()+ const results = await db.batch([+ db+ .prepare(+ "INSERT INTO platform_admin_audit(id,actor_id,action,target,reason,after_json,created_at) SELECT ?,?,'payment-provider-select','platform',?,?,? WHERE EXISTS(SELECT 1 FROM platform_payment_settings WHERE id=1 AND revision=?)",+ )+ .bind(+ id,+ actorId,+ input.reason.trim(),+ JSON.stringify({ currentProvider: input.id }),+ now,+ input.revision,+ ),+ db+ .prepare(+ 'UPDATE platform_payment_settings SET current_provider=?,revision=revision+1,updated_at=? WHERE id=1 AND revision=? AND EXISTS(SELECT 1 FROM platform_admin_audit WHERE id=?)',+ )+ .bind(input.id, now, input.revision, id),+ ])+ if (!results[0]?.meta.changes)+ throw new SubscriptionError(409, 'payment_revision_conflict')+ return { ok: true }+}diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.tsindex 3691ffd3..cb4d3e9c 100644--- a/packages/platform/src/payments.ts+++ b/packages/platform/src/payments.ts@@ -1,32 +1,11 @@-import { sealPaymentEventPayload } from './payment-events.ts'import type { PlatformD1 } from './index.ts'-import {- allRows,- SubscriptionError,- subscriptionInvalidation,- EXPIRY_PLAN_SQL,-} from './subscriptions.ts'+import { allRows, SubscriptionError } 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)-// Either echoed field can bind the response; conflicting supplied fields never pass.-function checkoutBound(value: any, id: string) {- const request = value?.request_id,- metadata = value?.metadata?.chronoframe_checkout_id- return (- (request == null || request === id) &&- (metadata == null || metadata === id) &&- (request === id || metadata === id)- )-}-const time = (v: unknown) =>- typeof v === 'string' && Number.isFinite(Date.parse(v)) ? Date.parse(v) : 0export type PaymentFetch = typeof fetchexport type PaymentSecrets = { apiKey: string; webhookSecret: string }@@ -100,69 +79,31 @@ export async function paymentSecrets(export async function paymentSettings(db: PlatformD1) {const row = await db.prepare(- 'SELECT enabled,purchase_method,environment,revision,catalog_revision,auto_sync,payload_retention_days,credentials_ciphertext IS NOT NULL AS configured FROM platform_payment_settings WHERE id=1',+ 'SELECT s.current_provider,s.enabled,s.purchase_method,s.revision,s.catalog_revision,s.payload_retention_days,p.environment,p.credentials_ciphertext IS NOT NULL AS configured FROM platform_payment_settings s LEFT JOIN platform_payment_providers p ON p.id=s.current_provider WHERE s.id=1',).first<any>()return {enabled: !!row.enabled,+ currentProvider: row.current_provider as string | null,+ // No active adapter remains after retiring the Creem sandbox.+ providerAvailable: false,purchaseMethod: row.purchase_method as 'payment' | 'activation_code',- autoSync: !!row.auto_sync,+ autoSync: false,catalogRevision: Number(row.catalog_revision),payloadRetentionDays: Number(row.payload_retention_days),- environment: 'test' as const,+ environment: row.environment as 'test' | 'live' | null,revision: Number(row.revision),configured: !!row.configured,}}export async function creemRequest(- credentials: PaymentSecrets,- path: string,- body?: unknown,- transport: PaymentFetch = fetch,- options: { method?: 'PATCH'; idempotencyKey?: string } = {},+ _credentials: PaymentSecrets,+ _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: 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',- signal: AbortSignal.timeout(10000),- })- } catch (error) {- return fail(- 502,- ['TimeoutError', 'AbortError'].includes(- String((error as { name?: string })?.name),- )- ? 'payment_provider_timeout'- : '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')- }+ throw new SubscriptionError(410, 'payment_provider_retired')}export function paymentURL(value: unknown) {try {@@ -181,54 +122,14 @@ export function paymentURL(value: unknown) {}}export async function validatePaymentProduct(- db: PlatformD1,- credentials: PaymentSecrets,- planId: string,- interval: number,- productId: string,- transport: PaymentFetch = fetch,+ _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),- }+ throw new SubscriptionError(410, 'payment_provider_retired')}export async function paymentMember(db: PlatformD1,@@ -262,1393 +163,108 @@ export async function paymentStatus().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.purchaseMethod === 'payment' &&- settings.configured- ? 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 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)))",- ),- )- : []+return {- environment: 'test',+ environment: settings.environment,purchaseMethod: settings.enabled? settings.purchaseMethod: 'activation_code',- enabled: offers.length > 0,+ enabled: false,canManage: membership.role === 'admin',- offers,+ 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,+ pending: 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. */+/** Legacy API compatibility: retired checkout operations fail before reading or mutating data. */export async function createPaymentCheckout(- db: PlatformD1,- rootKey: string,- userId: number,- input: {+ _db: PlatformD1,+ _rootKey: string,+ _userId: number,+ _input: {workspaceId: numberplanId: stringinterval: numberrequestId: string},- portalOrigin: string,- transport: PaymentFetch = fetch,- now = Date.now(),+ _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.purchaseMethod !== 'payment' ||- !settings.configured- )- 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')- 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(- 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 (!checkout || typeof checkout !== 'object' || !identifier(checkout.id))- fail(502, 'payment_checkout_response_invalid')- // Retain a returned identifier even if a later field or redirect check fails.- // Recovery still verifies the original immutable binding before trusting it.- await db- .prepare(- "UPDATE platform_payment_checkouts SET provider_id=? WHERE id=? AND state='creating'",- )- .bind(checkout.id, id)- .run()- if (checkout.mode !== 'test')- fail(- 502,- checkout.mode === 'sandbox'- ? 'payment_checkout_mode_sandbox'- : checkout.mode === 'prod'- ? 'payment_checkout_mode_prod'- : 'payment_checkout_mode_invalid',- )- if (!checkoutBound(checkout, id))- fail(502, 'payment_checkout_request_invalid')- if (objectId(checkout.product) !== mapping.product_id)- fail(502, 'payment_checkout_product_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- }- const codes = [- 'payment_provider_timeout',- 'payment_provider_unavailable',- 'payment_provider_request_failed',- 'payment_provider_response_invalid',- 'payment_checkout_response_invalid',- 'payment_checkout_mode_sandbox',- 'payment_checkout_mode_prod',- 'payment_checkout_mode_invalid',- 'payment_checkout_request_invalid',- 'payment_checkout_product_invalid',- 'payment_redirect_invalid',- ]- const cause =- error instanceof SubscriptionError && codes.includes(error.code)- ? error.code- : 'payment_checkout_create_failed'- const status = Number(- (error as { providerStatus?: number })?.providerStatus,- )- const diagnostic =- cause +- (Number.isInteger(status) && status >= 100 && status <= 599- ? ':' + status- : '')- // Never repeat an ambiguous provider create: the provider may have created a payable session.- // Persist only bounded codes/status, never provider bodies, keys, customer data or URLs.- await db- .prepare(- "UPDATE platform_payment_checkouts SET state='uncertain',error=?,updated_at=? WHERE id=? AND state='creating'",- )- .bind(diagnostic, now, id)- .run()- return fail(502, 'payment_confirmation_pending')- }- } finally {- await releaseWorkspace(db, input.workspaceId, token)- }+ throw new SubscriptionError(410, 'payment_provider_retired')}export async function createPaymentPortal(- db: PlatformD1,- rootKey: string,- userId: number,- workspaceId: number,- transport: PaymentFetch = fetch,+ _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) }+ throw new SubscriptionError(410, 'payment_provider_retired')}-/** Verify the exact raw bytes before parsing, and deduplicate durably before acknowledging delivery. */+/** Retired callbacks cannot enter the durable inbox. */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- let reference = identifier(ref) ? ref : null- let retainPayload = true- if (!supported) {- const sub = objectId(event.object.subscription)- const association = await db- .prepare(- 'SELECT c.id FROM platform_payment_checkouts c LEFT JOIN platform_payment_subscriptions s ON s.checkout_id=c.id WHERE c.user_id IS NOT NULL AND (c.id=? OR c.provider_id=? OR s.id=?) LIMIT 1',- )- .bind(- reference ?? '',- event.object.id,- identifier(sub) ? sub : event.object.id,- )- .first<{ id: string }>()- reference = association?.id ?? null- retainPayload = !!association- }- const payload = retainPayload- ? await sealPaymentEventPayload(rootKey, event.id, body)- : null- 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,- reference,- event.created_at,- supported ? 'pending' : 'ignored',- now,- ),- ...(payload- ? [- db- .prepare(- 'INSERT OR IGNORE INTO platform_payment_event_payloads(event_id,ciphertext,received_at) SELECT ?,?,? WHERE changes()=1 AND (?=1 OR EXISTS(SELECT 1 FROM platform_payment_checkouts WHERE id=? AND user_id IS NOT NULL))',- )- .bind(event.id, payload, now, supported ? 1 : 0, reference),- ]- : []),- ])- return { received: true }-}--async function paymentRecordId(prefix: string, providerId: string) {- const hash = await crypto.subtle.digest('SHA-256', enc.encode(providerId))- return (- prefix +- '_' +- [...new Uint8Array(hash)]- .map((v) => v.toString(16).padStart(2, '0'))- .join('')- )-}-/** A portal repurchase is a new immutable checkout, linked to a proven prior subscription. */-async function portalResubscriptionCheckout(- db: PlatformD1,- origin: any,- c: any,- s: any,- credentials: PaymentSecrets,- transport: PaymentFetch,- now: number,-) {- const predecessorId = c.metadata?.resubscribed_from_subscription_id- if (- origin.state !== 'completed' ||- !origin.provider_id ||- !identifier(predecessorId) ||- s.metadata?.resubscribed_from_subscription_id !== predecessorId ||- s.metadata?.chronoframe_checkout_id !== origin.id ||- !checkoutBound(c, origin.id)- )- fail(422, 'payment_binding_invalid')- const predecessor = await db- .prepare(- 'SELECT s.*,c.origin_checkout_id,c.user_id FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.id=?',- )- .bind(predecessorId)- .first<any>()- if (- !predecessor ||- predecessor.workspace_id !== origin.workspace_id ||- predecessor.user_id !== origin.user_id ||- ![predecessor.checkout_id, predecessor.origin_checkout_id].includes(- origin.id,- ) ||- predecessor.customer_id !== objectId(c.customer) ||- predecessor.customer_id !== objectId(s.customer)- )- fail(422, 'payment_binding_invalid')- await paymentMember(db, origin.user_id, origin.workspace_id, true)- const old = await creemRequest(- credentials,- '/v1/subscriptions?subscription_id=' + encodeURIComponent(predecessorId),- undefined,- transport,- )- if (- old.id !== predecessorId ||- old.mode !== 'test' ||- !['canceled', 'expired'].includes(old.status) ||- objectId(old.customer) !== predecessor.customer_id- )- fail(422, 'payment_binding_invalid')- const mapping = await db- .prepare(- 'SELECT * FROM platform_payment_products WHERE product_id=? AND enabled=1',- )- .bind(objectId(c.product))- .first<any>()- if (!mapping || objectId(s.product) !== mapping.product_id)- fail(422, 'payment_product_unavailable')- const quote = await validatePaymentProduct(- db,- credentials,- mapping.plan_id,- mapping.interval,- mapping.product_id,- transport,- )- return {- ...origin,- id: await paymentRecordId('resub', c.id),- origin_checkout_id: origin.id,- predecessor_subscription_id: predecessorId,- provider_id: c.id,- request_id: 'portal_' + crypto.randomUUID(),- plan_id: mapping.plan_id,- interval: mapping.interval,- product_id: mapping.product_id,- price: quote.price,- currency: quote.currency,- checkout_url: null,- state: 'completed',- error: null,- created_at: now,- updated_at: now,- }-}--async function synchronizePayment(- db: PlatformD1,- rootKey: string,- event: any,- transport: PaymentFetch,- now: number,+ _db: PlatformD1,+ _rootKey: string,+ _body: Uint8Array,+ _signature: string,+ _now = Date.now(),) {- const credentials = await paymentSecrets(db, rootKey)- let checkout: any,- providerCheckout: any,- subscriptionId: string,- awaitingPortalCheckout = false- if (event.type === 'checkout.completed') {- providerCheckout = await creemRequest(- credentials,- '/v1/checkouts?checkout_id=' + encodeURIComponent(event.object_id),- undefined,- transport,- )- if (- providerCheckout.id !== event.object_id ||- providerCheckout.mode !== 'test'- )- fail(422, 'payment_binding_invalid')- checkout =- (await db- .prepare('SELECT * FROM platform_payment_checkouts WHERE provider_id=?')- .bind(providerCheckout.id)- .first<any>()) ??- (await db- .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')- .bind(- String(- providerCheckout.request_id ??- providerCheckout.metadata?.chronoframe_checkout_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>()- // The new subscription's metadata identifies the origin, not its new checkout ID.- // Wait for checkout.completed (or an authenticated return) to prove that checkout.- awaitingPortalCheckout =- !known && !!probe?.metadata?.resubscribed_from_subscription_id- subscriptionId = event.object_id- }- if (!checkout || !checkout.user_id) {- await db- .prepare('DELETE FROM platform_payment_event_payloads WHERE event_id=?')- .bind(event.id)- .run()- return 'ignored'- }- if (checkout.error === 'payment_test_abandoned') return 'ignored'- if (awaitingPortalCheckout) fail(409, 'payment_confirmation_pending')- if (!identifier(subscriptionId)) fail(409, 'payment_confirmation_pending')- const token = await acquireWorkspace(db, checkout.workspace_id, now)- try {- const currentCheckout = await db- .prepare('SELECT error FROM platform_payment_checkouts WHERE id=?')- .bind(checkout.id)- .first<any>()- if (currentCheckout?.error === 'payment_test_abandoned') return 'ignored'- 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,- )- }- const stored = await db- .prepare('SELECT * FROM platform_payment_checkouts WHERE provider_id=?')- .bind(providerCheckout.id)- .first<any>()- if (stored) {- if (- stored.workspace_id !== checkout.workspace_id ||- stored.user_id !== checkout.user_id- )- fail(422, 'payment_binding_invalid')- checkout = stored- }- if (- !identifier(providerCheckout.id) ||- (event.type === 'checkout.completed' &&- providerCheckout.id !== event.object_id) ||- providerCheckout.mode !== 'test' ||- providerCheckout.status !== 'completed' ||- 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 materialize = providerCheckout.id !== checkout.provider_id- if (materialize)- checkout = await portalResubscriptionCheckout(- db,- checkout,- providerCheckout,- s,- credentials,- transport,- now,- )- if (- !checkoutBound(- providerCheckout,- checkout.origin_checkout_id ?? checkout.id,- ) ||- objectId(providerCheckout.product) !== checkout.product_id ||- (checkout.predecessor_subscription_id &&- (providerCheckout.metadata?.resubscribed_from_subscription_id !==- checkout.predecessor_subscription_id ||- s.metadata?.resubscribed_from_subscription_id !==- checkout.predecessor_subscription_id ||- s.metadata?.chronoframe_checkout_id !== checkout.origin_checkout_id))- )- 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)- : checkout.predecessor_subscription_id- ? prior?.payment_subscription_id ===- checkout.predecessor_subscription_id &&- ['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 ?? Math.min(start, now))- : end- const active = entitled && until > now- const anchor =- known && known.plan_id === planId ? known.quota_anchor : start- const assignmentNeedsWrite =- canAssign &&- (prior?.source !== (active ? 'payment' : 'expired_default') ||- (active &&- (prior.plan_id !== planId ||- prior.starts_at !== anchor ||- prior.expires_at !== until ||- prior.billing_interval !== interval)))- // A reconciliation heartbeat is not a new payment or a new entitlement revision.- // Still restore a linked paid subscription after a temporary grant expires.- if (- known &&- updated === known.provider_updated_at &&- known.status === s.status &&- known.product_id === objectId(s.product) &&- known.plan_id === planId &&- known.interval === interval &&- known.period_start === start &&- known.period_end === until &&- !assignmentNeedsWrite- ) {- await db- .prepare(- 'UPDATE platform_payment_subscriptions SET checked_at=?,next_check_at=?,error=? WHERE id=? AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=? AND expires_at>?)',- )- .bind(- now,- Math.max(now + 60000, Math.min(now + 900000, until)),- canAssign ? null : 'payment_grant_superseded',- subscriptionId,- checkout.workspace_id,- token,- now,- )- .run()- return 'done'- }- 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 statements = [- ...(materialize- ? [- db- .prepare(- `INSERT OR IGNORE INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,provider_id,checkout_url,state,created_at,updated_at,origin_checkout_id,predecessor_subscription_id) SELECT ?,?,?,?,?,?,?,?,?,?,?,NULL,'completed',?,?,?,? WHERE ${fence}`,- )- .bind(- checkout.id,- checkout.workspace_id,- checkout.user_id,- checkout.request_id,- checkout.plan_id,- checkout.interval,- checkout.product_id,- checkout.price,- checkout.currency,- prior?.revision ?? 0,- checkout.provider_id,- now,- now,- checkout.origin_checkout_id,- checkout.predecessor_subscription_id,- checkout.workspace_id,- token,- now,- ),- ]- : []),- 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[materialize ? 1 : 0]?.meta.changes)- fail(409, 'payment_lease_lost')- return 'done'- } finally {- await releaseWorkspace(db, checkout.workspace_id, token)- }+ throw new SubscriptionError(410, 'payment_provider_retired')}-/** Durable signed-event inbox. Retries use authoritative API reads, not stale event snapshots. */+/** The historical inbox is retained without replay. */export async function processPaymentEvents(- db: PlatformD1,- rootKey: string,- transport: PaymentFetch = fetch,- now = Date.now(),- limit = 5,- onlyId?: string,+ _db: PlatformD1,+ _rootKey: string,+ _transport: PaymentFetch = fetch,+ _now = Date.now(),+ _limit = 5,+ _onlyId?: string,) {- 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<?) AND (? IS NULL OR id=?) ORDER BY available_at,id LIMIT ?",- )- .bind(now, now, onlyId ?? null, onlyId ?? null, 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 }+ // Creem processing is retired; preserve historical records.}export async function reconcilePayments(- db: PlatformD1,- rootKey: string,- transport: PaymentFetch = fetch,- now = Date.now(),+ _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' || !checkoutBound(checkout, 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()+ // Creem processing is retired; preserve historical records.}-/** Reattach an ambiguous create only after Creem proves the original immutable request binding. */+/** Retired test checkouts cannot be recovered. */export async function recoverPaymentCheckout(- db: PlatformD1,- rootKey: string,- checkoutId: string,- providerId: string,- transport: PaymentFetch = fetch,- now = Date.now(),+ _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' ||- !checkoutBound(c, 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 }+ throw new SubscriptionError(410, 'payment_provider_retired')}-/** Account erasure cannot remove the local ledger while an upstream subscription can still bill. */+/** Retired sandbox records do not require an upstream cancellation during erasure. */export async function closeAccountPayments(- db: PlatformD1,- rootKey: string,- userId: number,- transport: PaymentFetch = fetch,+ _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' ||- !checkoutBound(c, 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),- ])- }+ // Historical Creem subscriptions were sandbox-only and cannot bill.return true}-/** A return only requests authoritative reconciliation; query parameters never grant access. */+/** Historical return URLs cannot trigger reconciliation or grant access. */export async function refreshPaymentCheckout(- db: PlatformD1,- rootKey: string,- userId: number,- workspaceId: number,- checkoutId: string,- transport: PaymentFetch = fetch,- now = Date.now(),- hints: { providerCheckoutId?: string; subscriptionId?: string } = {},+ _db: PlatformD1,+ _rootKey: string,+ _userId: number,+ _workspaceId: number,+ _checkoutId: string,+ _transport: PaymentFetch = fetch,+ _now = Date.now(),+ _hints: { providerCheckoutId?: string; subscriptionId?: string } = {},) {- await paymentMember(db, userId, workspaceId, true)- if (- !identifier(checkoutId) ||- (hints.providerCheckoutId !== undefined &&- !identifier(hints.providerCheckoutId)) ||- (hints.subscriptionId !== undefined && !identifier(hints.subscriptionId))- )- 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')- const providerId = hints.providerCheckoutId ?? row.provider_id- if (!providerId) return { state: 'pending' }- if (row.state === 'expired' && providerId === row.provider_id)- return { state: 'expired' }- const checkout = await creemRequest(- await paymentSecrets(db, rootKey),- '/v1/checkouts?checkout_id=' + encodeURIComponent(providerId),- undefined,- transport,- )- if (- checkout.id !== providerId ||- checkout.mode !== 'test' ||- !checkoutBound(checkout, row.origin_checkout_id ?? row.id) ||- (providerId === row.provider_id &&- objectId(checkout.product) !== row.product_id) ||- (hints.subscriptionId !== undefined &&- objectId(checkout.subscription) !== hints.subscriptionId)- )- fail(422, 'payment_binding_invalid')- if (checkout.status === 'expired') {- if (providerId === row.provider_id)- 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()- const current = await db- .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')- .bind(row.id)- .first<any>()- return {- state:- providerId === row.provider_id && current?.state === 'completed'- ? 'pending'- : 'expired',- }- }- if (checkout.status !== 'completed') return { state: 'pending' }- // Bounded authenticated reads reconcile current provider truth, including historical returns.- const eventId = 'return_' + crypto.randomUUID()- await db- .prepare(- "INSERT INTO platform_payment_events(id,type,object_id,reference_id,created_at,available_at) VALUES(?,'checkout.completed',?,?,?,?)",- )- .bind(eventId, providerId, row.id, now, now)- .run()- await processPaymentEvents(db, rootKey, transport, now, 1, eventId)- const current = await db- .prepare(- 'SELECT s.id,s.status,s.period_end,p.payment_subscription_id,p.source FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id JOIN platform_workspace_plans p ON p.workspace_id=s.workspace_id WHERE c.provider_id=? AND c.workspace_id=? AND c.user_id=?',- )- .bind(providerId, workspaceId, userId)- .first<any>()- if (!current) return { state: 'pending' }- if (- !['active', 'trialing', 'scheduled_cancel', 'past_due'].includes(- current.status,- ) ||- current.period_end <= now- )- return { state: 'inactive' }- if (- current.payment_subscription_id !== current.id ||- current.source !== 'payment'- )- return { state: 'superseded' }- return { state: 'completed' }+ throw new SubscriptionError(410, 'payment_provider_retired')}diff --git a/tests/payment-providers.test.ts b/tests/payment-providers.test.tsnew file mode 100644index 00000000..392887aa--- /dev/null+++ b/tests/payment-providers.test.ts@@ -0,0 +1,271 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { readFile, readdir } from 'node:fs/promises'+import { createRequire } from 'node:module'+import {+ paymentProviders,+ savePaymentProvider,+ selectPaymentProvider,+ openProviderCredentials,+} from '../packages/platform/src/payment-providers.ts'+import {+ paymentSettings,+ creemRequest,+ receivePaymentEvent,+ processPaymentEvents,+ reconcilePayments,+ refreshPaymentCheckout,+ recoverPaymentCheckout,+ createPaymentPortal,+ createPaymentCheckout,+ closeAccountPayments,+} from '../packages/platform/src/payments.ts'+import {+ syncPaymentProducts,+ queuePaymentProductSync,+} from '../packages/platform/src/payment-product-sync.ts'+import { pricingCatalog } from '../packages/platform/src/billing.ts'+const require = createRequire(import.meta.url)+const { Miniflare, convertV4MiniflareOptions } = createRequire(+ require.resolve('wrangler/package.json'),+)('miniflare')+const key = 'provider-test-root-secret-'.repeat(3)+async function fixture(upgrade = false) {+ const mf = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ compatibilityDate: '2026-10-26',+ script: 'export default {fetch(){return new Response("ok")}}',+ d1Databases: ['DB'],+ }),+ )+ const db = await mf.getD1Database('DB')+ for (const file of (+ await readdir(new URL('../packages/platform/migrations/', import.meta.url))+ )+ .filter((f) => f.endsWith('.sql'))+ .sort()) {+ if (upgrade && file === '0028_payment_providers.sql')+ await db+ .prepare(+ "UPDATE platform_payment_settings SET enabled=1,purchase_method='activation_code',auto_sync=1,credentials_ciphertext='legacy-encrypted-envelope' WHERE id=1",+ )+ .run()+ for (const q of (+ await readFile(+ new URL('../packages/platform/migrations/' + file, import.meta.url),+ 'utf8',+ )+ )+ .replace(/^--.*$/gm, '')+ .match(/\s*CREATE TRIGGER[\s\S]+?END;|[^;]+;/g) ?? [])+ await db.prepare(q).run()+ }+ await db+ .prepare(+ 'CREATE TABLE platform_admin_audit(id TEXT PRIMARY KEY,actor_id INTEGER,action TEXT,target TEXT,reason TEXT,after_json TEXT,created_at INTEGER)',+ )+ .run()+ return { mf, db }+}+test('provider profiles are isolated, encrypted, redacted, audited and revision protected', async () => {+ const { mf, db } = await fixture()+ try {+ const input = {+ id: 'stripe',+ name: 'Stripe',+ environment: 'test',+ revision: 0,+ reason: 'Configure provider',+ credentials: {+ apiKey: 'secret-stripe-value',+ webhookSecret: 'secret-webhook-value',+ },+ }+ await savePaymentProvider(db, key, 1, input)+ await savePaymentProvider(db, key, 1, {+ ...input,+ id: 'paddle',+ name: 'Paddle',+ credentials: { apiKey: 'secret-paddle-value' },+ })+ await assert.rejects(savePaymentProvider(db, key, 1, input), {+ code: 'payment_revision_conflict',+ })+ const row = await db+ .prepare("SELECT * FROM platform_payment_providers WHERE id='stripe'")+ .first<any>()+ assert.ok(!row.credentials_ciphertext.includes(input.credentials.apiKey))+ assert.deepEqual(+ await openProviderCredentials(+ key,+ 'stripe',+ 'test',+ row.credentials_ciphertext,+ ),+ input.credentials,+ )+ await assert.rejects(+ openProviderCredentials(+ key,+ 'paddle',+ 'test',+ row.credentials_ciphertext,+ ),+ )+ await savePaymentProvider(db, key, 1, {+ ...input,+ credentials: undefined,+ revision: 1,+ environment: 'live',+ })+ const changed = await db+ .prepare("SELECT * FROM platform_payment_providers WHERE id='stripe'")+ .first<any>()+ assert.deepEqual(+ await openProviderCredentials(+ key,+ 'stripe',+ 'live',+ changed.credentials_ciphertext,+ ),+ input.credentials,+ )+ const safe = JSON.stringify({+ providers: await paymentProviders(db),+ audit: (await db.prepare('SELECT * FROM platform_admin_audit').all())+ .results,+ })+ assert.ok(!safe.includes('secret-stripe-value'))+ assert.ok(!safe.includes('secret-paddle-value'))+ assert.ok(!safe.includes('credentials_ciphertext'))+ let settings = await paymentSettings(db)+ await selectPaymentProvider(db, 1, {+ id: 'stripe',+ revision: settings.revision,+ reason: 'Select provider',+ })+ assert.equal((await paymentSettings(db)).currentProvider, 'stripe')+ await assert.rejects(+ selectPaymentProvider(db, 1, {+ id: 'paddle',+ revision: settings.revision,+ reason: 'Stale selection',+ }),+ { code: 'payment_revision_conflict' },+ )+ settings = await paymentSettings(db)+ await selectPaymentProvider(db, 1, {+ id: 'paddle',+ revision: settings.revision,+ reason: 'Switch provider',+ })+ assert.equal((await paymentSettings(db)).currentProvider, 'paddle')+ await assert.rejects(+ savePaymentProvider(db, key, 1, { ...input, id: 'creem' }),+ { code: 'payment_provider_retired' },+ )+ for (const enabled of [0, 1]) {+ for (const mode of ['payment', 'activation_code']) {+ await db+ .prepare(+ 'UPDATE platform_payment_settings SET enabled=?,purchase_method=?',+ )+ .bind(enabled, mode)+ .run()+ const catalog = await pricingCatalog(db)+ assert.equal(catalog.purchaseMethod, enabled ? mode : 'activation_code')+ assert.equal(catalog.paymentAvailable, false)+ }+ }+ } finally {+ await mf.dispose()+ }+})+test('retired Creem entry points never call providers or mutate the historical ledger, including when disabled', async () => {+ const { mf, db } = await fixture()+ let calls = 0+ const transport: typeof fetch = async () => {+ calls+++ throw Error('Unexpected network')+ }+ try {+ const before = JSON.stringify(+ (await db.prepare('SELECT * FROM platform_payment_product_sync').all())+ .results,+ )+ for (const enabled of [0, 1]) {+ await db+ .prepare('UPDATE platform_payment_settings SET enabled=?,auto_sync=1')+ .bind(enabled)+ .run()+ await queuePaymentProductSync(db)+ assert.deepEqual(await syncPaymentProducts(db, key, transport), {+ processed: 0,+ })+ await reconcilePayments(db, key, transport)+ await processPaymentEvents(db, key, transport)+ for (const action of [+ () =>+ creemRequest(+ { apiKey: 'creem_test_old', webhookSecret: 'old' },+ '/v1/products',+ undefined,+ transport,+ ),+ () => receivePaymentEvent(db, key, new Uint8Array(), ''),+ () => refreshPaymentCheckout(db, key, 1, 1, 'old', transport),+ () => recoverPaymentCheckout(db, key, 'old', 'checkout_old', transport),+ () => createPaymentPortal(db, key, 1, 1, transport),+ () =>+ createPaymentCheckout(+ db,+ key,+ 1,+ { workspaceId: 1, planId: 'pro', interval: 1, requestId: 'old' },+ 'https://portal.invalid',+ transport,+ ),+ ])+ await assert.rejects(action(), { code: 'payment_provider_retired' })+ assert.equal(await closeAccountPayments(db, key, 1, transport), true)+ }+ assert.equal(calls, 0)+ assert.equal(+ (+ await db+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_events')+ .first<any>()+ ).n,+ 0,+ )+ assert.equal(+ JSON.stringify(+ (await db.prepare('SELECT * FROM platform_payment_product_sync').all())+ .results,+ ),+ before,+ )+ } finally {+ await mf.dispose()+ }+})++test('upgrade preserves purchase controls and the legacy encrypted profile while stopping synchronization', async () => {+ const { mf, db } = await fixture(true)+ try {+ const settings = await paymentSettings(db)+ assert.equal(settings.currentProvider, 'creem')+ assert.equal(settings.enabled, true)+ assert.equal(settings.purchaseMethod, 'activation_code')+ assert.equal(settings.providerAvailable, false)+ assert.equal(settings.autoSync, false)+ const profile = await db+ .prepare("SELECT * FROM platform_payment_providers WHERE id='creem'")+ .first<any>()+ assert.equal(profile.credentials_ciphertext, 'legacy-encrypted-envelope')+ assert.equal((await paymentProviders(db))[0].status, 'retired')+ } finally {+ await mf.dispose()+ }+})diff --git a/tests/platform-payments.test.ts b/tests/platform-payments.test.tsindex 2aa09737..d6dea17c 100644--- a/tests/platform-payments.test.ts+++ b/tests/platform-payments.test.ts@@ -259,7 +259,8 @@ async function fixture() {}}-test('Payment credentials are authenticated-encrypted, test-only, workspace-admin scoped and price checked', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Payment credentials are authenticated-encrypted, test-only, workspace-admin scoped and price checked', async () => {const f = await fixture()try {const stored = await f.db@@ -346,7 +347,8 @@ test('Payment credentials are authenticated-encrypted, test-only, workspace-admi}})-test('Concurrent checkout creation, raw signatures, durable deduplication and authoritative grants', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Concurrent checkout creation, raw signatures, durable deduplication and authoritative grants', async () => {const f = await fixture()try {const results = await Promise.allSettled(@@ -453,7 +455,8 @@ test('Concurrent checkout creation, raw signatures, durable deduplication and au}})-test('Renewal, scheduled cancellation, stale webhook snapshots and immediate cancellation follow provider truth', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Renewal, scheduled cancellation, stale webhook snapshots and immediate cancellation follow provider truth', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -533,7 +536,8 @@ test('Renewal, scheduled cancellation, stale webhook snapshots and immediate can}})-test('Ambiguous creates are not repeated; verified recovery and bounded retries restore the original checkout', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Ambiguous creates are not repeated; verified recovery and bounded retries restore the original checkout', async () => {const f = await fixture()try {f.setUncertain(true)@@ -593,7 +597,8 @@ test('Ambiguous creates are not repeated; verified recovery and bounded retries}})-test('Manual grants supersede late renewals; expiry reconciliation can safely recover a renewed payment term', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Manual grants supersede late renewals; expiry reconciliation can safely recover a renewed payment term', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -649,7 +654,8 @@ test('Manual grants supersede late renewals; expiry reconciliation can safely re}})-test('Account cleanup waits for upstream cancellation; open expired sessions are reconciled from the provider', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Account cleanup waits for upstream cancellation; open expired sessions are reconciled from the provider', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -709,7 +715,8 @@ test('Account cleanup waits for upstream cancellation; open expired sessions are}})-test('Creem transport rejects redirects and live keys before any forwarded request', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Creem transport rejects redirects and live keys before any forwarded request', async () => {let calls = 0const transport = async (url: any, init: any) => {calls++@@ -740,7 +747,8 @@ test('Creem transport rejects redirects and live keys before any forwarded reque)assert.equal(calls, 1)})-test('A single automatic trial-expiry transition does not suppress checkout; crashed inbox attempts stop at the budget', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('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@@ -805,7 +813,8 @@ test('A single automatic trial-expiry transition does not suppress checkout; cra}})-test('Definitive provider rejections release the checkout slot without repeating an uncertain create', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Definitive provider rejections release the checkout slot without repeating an uncertain create', async () => {const f = await fixture()try {f.setRejected(true)@@ -846,7 +855,8 @@ test('Definitive provider rejections release the checkout slot without repeating}})-test('Paid checkout snapshots survive price edits; actual purchasers qualify without borrowing another member subscription', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Paid checkout snapshots survive price edits; actual purchasers qualify without borrowing another member subscription', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -1000,7 +1010,8 @@ test('Paid checkout snapshots survive price edits; actual purchasers qualify witawait f.mf.dispose()}})-test('Owned account erasure removes dependent payment rows only after cancellation succeeds', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Owned account erasure removes dependent payment rows only after cancellation succeeds', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -1077,7 +1088,8 @@ test('Owned account erasure removes dependent payment rows only after cancellati}})-test('Unchanged reconciliation does not churn grants, and an expiring activation preserves paid subscription recovery', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Unchanged reconciliation does not churn grants, and an expiring activation preserves paid subscription recovery', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -1183,7 +1195,8 @@ test('Unchanged reconciliation does not churn grants, and an expiring activation}})-test('First past-due confirmation stores a real boundary without inventing a paid entitlement', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('First past-due confirmation stores a real boundary without inventing a paid entitlement', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -1229,7 +1242,8 @@ test('First past-due confirmation stores a real boundary without inventing a pai}})-test('Ambiguous checkout diagnostics preserve safe causes and recoverable provider identifiers', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Ambiguous checkout diagnostics preserve safe causes and recoverable provider identifiers', async () => {for (const scenario of ['redirect','mode',@@ -1331,7 +1345,8 @@ test('Ambiguous checkout diagnostics preserve safe causes and recoverable provid}})-test('Abandoned sandbox attempts cannot grant access through late callbacks or block a fresh checkout', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Abandoned sandbox attempts cannot grant access through late callbacks or block a fresh checkout', async () => {const f = await fixture()try {f.setUncertain(true)@@ -1415,7 +1430,8 @@ test('Abandoned sandbox attempts cannot grant access through late callbacks or b}})-test('Checkout return reconciliation verifies provider truth and ownership without trusting the browser return', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Checkout return reconciliation verifies provider truth and ownership without trusting the browser return', async () => {const f = await fixture()try {const checkout = await createPaymentCheckout(@@ -1513,7 +1529,8 @@ test('Checkout return reconciliation verifies provider truth and ownership witho}})-test('Signed webhook payloads are encrypted, bound to their event, paginated and expired without losing the inbox', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Signed webhook payloads are encrypted, bound to their event, paginated and expired without losing the inbox', async () => {const f = await fixture()try {const association = await createPaymentCheckout(@@ -1711,7 +1728,8 @@ function productTransport(f: any) {}}-test('Automatic catalog sync publishes month/quarter products, updates rights and preserves existing billed prices', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Automatic catalog sync publishes month/quarter products, updates rights and preserves existing billed prices', async () => {const f = await fixture(),p = productTransport(f)try {@@ -1854,7 +1872,8 @@ test('Automatic catalog sync publishes month/quarter products, updates rights an}})-test('Product creation retries are idempotent and a concurrent plan edit cannot publish an outdated product', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('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)@@ -1890,7 +1909,8 @@ test('Product creation retries are idempotent and a concurrent plan edit cannot}})-test('An authoritative expired checkout return releases the pending checkout without waiting for cron', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('An authoritative expired checkout return releases the pending checkout without waiting for cron', async () => {const f = await fixture()try {const first = await createPaymentCheckout(@@ -1939,7 +1959,8 @@ test('An authoritative expired checkout return releases the pending checkout wit}})-test('Customer portal resubscription keeps the canceled purchase and binds a new paid subscription', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Customer portal resubscription keeps the canceled purchase and binds a new paid subscription', async () => {const f = await fixture()try {await createPaymentCheckout(@@ -2106,7 +2127,8 @@ async function portalCase() {}}-test('Portal return verifies the new checkout before webhooks and historical canceled returns stay inactive', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Portal return verifies the new checkout before webhooks and historical canceled returns stay inactive', async () => {const f = await portalCase()try {assert.deepEqual(@@ -2180,7 +2202,8 @@ test('Portal return verifies the new checkout before webhooks and historical can}})-test('Portal replay and late predecessor cancellation cannot downgrade the replacement or duplicate grants', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Portal replay and late predecessor cancellation cannot downgrade the replacement or duplicate grants', async () => {for (const paidFirst of [true, false]) {const f = await portalCase()try {@@ -2264,7 +2287,8 @@ test('Portal replay and late predecessor cancellation cannot downgrade the repla}})-test('Portal lineage rejects foreign customers, conflicting metadata, active predecessors and unavailable products', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Portal lineage rejects foreign customers, conflicting metadata, active predecessors and unavailable products', async () => {for (const scenario of ['customer','marker',@@ -2360,7 +2384,8 @@ test('Portal lineage rejects foreign customers, conflicting metadata, active pre}})-test('Portal replacement records payment without overriding a later manual grant', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Portal replacement records payment without overriding a later manual grant', async () => {const f = await portalCase()try {await f.db@@ -2403,7 +2428,8 @@ test('Portal replacement records payment without overriding a later manual grant}})-test('Portal subscription chains preserve origin history and remain removable by account erasure', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Portal subscription chains preserve origin history and remain removable by account erasure', async () => {const f = await portalCase()try {await (@@ -2494,7 +2520,8 @@ test('Portal subscription chains preserve origin history and remain removable by}})-test('A late portal repurchase cannot replace a newer independently purchased subscription', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('A late portal repurchase cannot replace a newer independently purchased subscription', async () => {const f = await portalCase()try {await createPaymentCheckout(@@ -2549,7 +2576,8 @@ test('A late portal repurchase cannot replace a newer independently purchased su}})-test('Disabled payments and activation-code mode expose redemption and reject checkout without contacting a provider', async () => {+// Historical Creem sandbox coverage; retired in favor of payment-providers.test.ts.+test.skip('Disabled payments and activation-code mode expose redemption and reject checkout without contacting a provider', async () => {const f = await fixture()try {for (const [enabled, method, effective] of [