Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(cloud): add pricing, subscriptions and activation codes

Timothy Yin7c51fb36763c
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 94c226ad..3e7af691 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -2840,3 +2840,353 @@ a.cf-domain-address:hover {
min-width: 0;
flex: 1;
}
+.cf-pricing {
+ max-width: 1240px;
+ margin: 0 auto;
+ padding: 44px 24px 80px;
+}
+.cf-pricing-heading {
+ text-align: center;
+ max-width: 720px;
+ margin: 0 auto 36px;
+}
+.cf-pricing-heading h1 {
+ font-size: clamp(30px, 4vw, 48px);
+ letter-spacing: -0.045em;
+ line-height: 1.15;
+ margin: 12px 0;
+}
+.cf-pricing-heading > p {
+ color: var(--muted-foreground);
+ margin: 12px 0;
+}
+.cf-billing-toggle {
+ display: inline-flex;
+ margin: 18px 0 4px;
+ padding: 4px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: var(--secondary);
+ gap: 4px;
+}
+.cf-billing-toggle label {
+ position: relative;
+ padding: 8px 18px;
+ border-radius: 7px;
+ cursor: pointer;
+ font-size: 13px;
+}
+.cf-billing-toggle label.active {
+ background: var(--card);
+ box-shadow: 0 1px 4px #00000012;
+ color: var(--foreground);
+}
+.cf-billing-toggle input {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ cursor: pointer;
+}
+.cf-billing-toggle label:has(input:focus-visible) {
+ outline: 2px solid var(--ring);
+}
+.cf-pricing-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));
+ gap: 18px;
+}
+.cf-pricing-card {
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+ background: var(--card);
+ padding: 26px;
+ border: 1px solid var(--border);
+ border-radius: 14px;
+}
+.cf-pricing-card.is-default {
+ border-color: var(--primary);
+ box-shadow: 0 0 0 1px var(--primary);
+}
+.cf-plan-card-heading {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+.cf-plan-card-heading h2 {
+ font-size: 19px;
+}
+.cf-plan-description {
+ font-size: 13px;
+ color: var(--muted-foreground);
+ min-height: 40px;
+ line-height: 1.6;
+}
+.cf-plan-price strong {
+ font-size: 35px;
+ font-weight: 600;
+ letter-spacing: -0.04em;
+ overflow-wrap: anywhere;
+}
+.cf-plan-price > span {
+ font-size: 12px;
+ margin-left: 5px;
+ color: var(--muted-foreground);
+}
+.cf-price-caption {
+ font-size: 11px;
+ color: var(--muted-foreground);
+ min-height: 30px;
+}
+.cf-plan-features {
+ display: grid;
+ gap: 12px;
+ list-style: none;
+ padding: 16px 0 0;
+ border-top: 1px solid var(--border);
+}
+.cf-plan-features li {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ font-size: 12px;
+}
+.cf-plan-features li span {
+ color: var(--muted-foreground);
+}
+.cf-plan-features strong {
+ white-space: nowrap;
+ font-weight: 550;
+}
+.cf-rule-details {
+ border-top: 1px solid var(--border);
+ padding-top: 14px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+.cf-rule-details summary {
+ cursor: pointer;
+ color: var(--foreground);
+}
+.cf-rule-details p {
+ margin-top: 12px;
+}
+.cf-plan-comparison {
+ margin-top: 48px;
+}
+.cf-plan-comparison h2,
+.cf-plan-section-heading h2,
+.cf-plan-page section > h2 {
+ font-size: 18px;
+ font-weight: 600;
+ margin-bottom: 8px;
+}
+.cf-table-scroll {
+ overflow: auto;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ margin-top: 18px;
+ background: var(--card);
+}
+.cf-table-scroll table {
+ width: 100%;
+ border-collapse: collapse;
+ white-space: nowrap;
+ text-align: left;
+}
+.cf-table-scroll th,
+.cf-table-scroll td {
+ font-size: 12px;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--border);
+}
+.cf-table-scroll th {
+ font-weight: 550;
+}
+.cf-table-scroll thead {
+ background: var(--secondary);
+}
+.cf-plan-page {
+ display: grid;
+ gap: 26px;
+}
+.cf-plan-page .cf-page-heading {
+ margin-bottom: 0;
+}
+.cf-workspace-picker {
+ display: grid;
+ gap: 7px;
+ font-size: 12px;
+ max-width: 360px;
+}
+.cf-plan-page select,
+.cf-redeem-page select {
+ font: inherit;
+ border: 1px solid var(--border);
+ background: var(--card);
+ color: var(--foreground);
+ padding: 9px 12px;
+ border-radius: 7px;
+ max-width: 100%;
+}
+.cf-current-plan {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 20px;
+ padding: 24px;
+}
+.cf-current-plan h2 {
+ font-size: 26px;
+ font-weight: 600;
+ margin: 6px 0;
+}
+.cf-current-plan p {
+ font-size: 13px;
+ color: var(--muted-foreground);
+}
+.cf-plan-section-heading {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 15px;
+ margin-bottom: 16px;
+}
+.cf-quota-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr));
+ gap: 12px;
+}
+.cf-quota-card {
+ border: 1px solid var(--border);
+ background: var(--card);
+ border-radius: 10px;
+ padding: 18px;
+}
+.cf-quota-card h3 {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ font-weight: 500;
+ margin: 0 0 12px;
+}
+.cf-quota-card p {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+.cf-quota-card strong {
+ font-size: 23px;
+ letter-spacing: -0.035em;
+ font-weight: 550;
+}
+.cf-quota-card p > span,
+.cf-quota-card small {
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.cf-quota-track {
+ height: 4px;
+ border-radius: 4px;
+ background: var(--secondary);
+ overflow: hidden;
+ margin: 14px 0 8px;
+}
+.cf-quota-track > span {
+ display: block;
+ height: 100%;
+ background: var(--primary);
+}
+.cf-quota-track .is-over {
+ background: var(--destructive);
+}
+.cf-billing-details {
+ font-size: 13px;
+ border-top: 1px solid var(--border);
+ padding-top: 20px;
+}
+.cf-billing-details summary {
+ cursor: pointer;
+}
+.cf-billing-details dl,
+.cf-redemption-preview dl {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ gap: 10px;
+ font-size: 12px;
+ margin: 18px 0;
+}
+.cf-billing-details dd,
+.cf-redemption-preview dd {
+ margin: 0;
+ text-align: right;
+}
+.cf-subscription-history {
+ list-style: none;
+ padding: 0;
+}
+.cf-subscription-history li {
+ display: flex;
+ justify-content: space-between;
+ gap: 15px;
+ padding: 12px 0;
+ border-bottom: 1px solid var(--border);
+ font-size: 12px;
+}
+.cf-subscription-history time {
+ color: var(--muted-foreground);
+}
+.cf-redeem-page {
+ max-width: 650px;
+}
+.cf-redeem-page > .cf-card {
+ padding: 24px;
+}
+.cf-redemption-preview {
+ margin-top: 24px;
+ padding-top: 20px;
+ border-top: 1px solid var(--border);
+}
+.cf-redemption-preview h2 {
+ font-size: 17px;
+}
+.cf-redemption-preview p {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ margin-bottom: 18px;
+}
+.cf-redeem-page .cf-error-message {
+ margin-top: 14px;
+}
+@media (max-width: 640px) {
+ .cf-pricing {
+ padding: 28px 16px 50px;
+ }
+ .cf-pricing-card {
+ padding: 20px;
+ }
+ .cf-current-plan {
+ align-items: flex-start;
+ flex-direction: column;
+ padding: 18px;
+ }
+ .cf-plan-section-heading {
+ align-items: flex-start;
+ }
+ .cf-plan-page select,
+ .cf-redeem-page select {
+ font-size: 16px;
+ }
+ .cf-subscription-history li {
+ flex-direction: column;
+ gap: 3px;
+ }
+ .cf-pricing-heading {
+ text-align: left;
+ }
+ .cf-redeem-page > .cf-card {
+ padding: 18px;
+ }
+}
diff --git a/apps/cloud/app/components/CloudMarketingHeader.vue b/apps/cloud/app/components/CloudMarketingHeader.vue
new file mode 100644
index 00000000..0e9cfde1
--- /dev/null
+++ b/apps/cloud/app/components/CloudMarketingHeader.vue
@@ -0,0 +1,95 @@
+<script setup lang="ts">
+import { ArrowUpRight, ArrowRight, Menu } from 'lucide-vue-next'
+import { PopoverRoot, PopoverTrigger, PopoverContent } from 'reka-ui'
+const route = useRoute()
+const mobileMenuOpen = ref(false),
+ links = useCloudLinks()
+</script>
+<template>
+ <header class="cf-marketing-header">
+ <CloudBrand />
+ <nav
+ class="cf-marketing-nav"
+ :aria-label="$t('cloud.messages.mainNavigation')"
+ >
+ <NuxtLink
+ to="/pricing"
+ :aria-current="route.path === '/pricing' ? 'page' : undefined"
+ >{{ $t('cloud.billing.pricing') }}</NuxtLink
+ ><a href="https://docs.chronoframe.art/">{{
+ $t('cloud.messages.documentation')
+ }}</a
+ ><a href="https://github.com/HoshinoSuzumi/chronoframe"
+ >GitHub
+ <ArrowUpRight
+ :size="12"
+ aria-hidden="true"
+ class="cf-inline-icon" /></a
+ ><CloudThemeToggle />
+ <CloudButton
+ as-child
+ variant="secondary"
+ size="sm"
+ ><NuxtLink
+ :to="links.signin"
+ external
+ >{{ $t('cloud.messages.logIn') }}</NuxtLink
+ ></CloudButton
+ ><CloudButton
+ as-child
+ size="sm"
+ ><NuxtLink
+ :to="links.signup"
+ external
+ >{{ $t('cloud.messages.getStarted')
+ }}<ArrowUpRight :size="14" /></NuxtLink
+ ></CloudButton>
+ </nav>
+ <div class="cf-mobile-header-actions">
+ <CloudButton
+ as-child
+ size="sm"
+ ><NuxtLink
+ :to="links.signup"
+ external
+ >{{ $t('cloud.messages.signUp') }}</NuxtLink
+ ></CloudButton
+ >
+ <PopoverRoot v-model:open="mobileMenuOpen">
+ <PopoverTrigger as-child
+ ><CloudButton
+ variant="ghost"
+ size="icon"
+ :aria-label="$t('cloud.messages.openNavigation')"
+ ><Menu :size="20" /></CloudButton
+ ></PopoverTrigger>
+ <PopoverContent
+ class="cf-mobile-menu"
+ align="end"
+ :side-offset="12"
+ :collision-padding="20"
+ :aria-label="$t('cloud.messages.navigation')"
+ >
+ <nav :aria-label="$t('cloud.messages.mobileNavigation')">
+ <NuxtLink
+ :to="links.signin"
+ external
+ >{{ $t('cloud.messages.logIn') }}<ArrowRight :size="16"
+ /></NuxtLink>
+ <NuxtLink to="/pricing">{{ $t('cloud.billing.pricing') }}</NuxtLink
+ ><a href="https://docs.chronoframe.art/"
+ >{{ $t('cloud.messages.documentation') }}<ArrowUpRight :size="15"
+ /></a>
+ <a href="https://github.com/HoshinoSuzumi/chronoframe"
+ >GitHub <ArrowUpRight :size="15"
+ /></a>
+ </nav>
+ <div class="cf-mobile-menu-theme">
+ <span>{{ $t('cloud.messages.appearance') }}</span
+ ><CloudThemeToggle />
+ </div>
+ </PopoverContent>
+ </PopoverRoot>
+ </div>
+ </header>
+</template>
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vue
new file mode 100644
index 00000000..7222cce5
--- /dev/null
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -0,0 +1,204 @@
+<script setup lang="ts">
+import {
+ BILLING_LIMITS,
+ allowance,
+ price,
+ conditionText,
+} from '../utils/billing-format'
+const props = withDefaults(defineProps<{ portal?: boolean }>(), {
+ portal: false,
+ }),
+ { t, locale } = useI18n(),
+ links = useCloudLinks(),
+ interval = ref<1 | 3>(1)
+const { data, error, refresh } = await useFetch<any>('/api/billing/catalog', {
+ key: 'public-pricing-catalog',
+})
+const amount = (plan: any) =>
+ interval.value === 1 ? plan.monthlyPrice : plan.quarterlyPrice
+const action = (plan: any) =>
+ !props.portal && plan.id === data.value?.newPlanId
+ ? links.signup
+ : links.redeem
+</script>
+<template>
+ <div class="cf-pricing">
+ <div class="cf-pricing-heading">
+ <p class="cf-eyebrow">ChronoFrame Cloud</p>
+ <h1>{{ $t('cloud.billing.pricing') }}</h1>
+ <p>{{ $t('cloud.billing.pricingHelp') }}</p>
+ <fieldset class="cf-billing-toggle">
+ <legend class="sr-only">{{ $t('cloud.billing.interval') }}</legend>
+ <label
+ v-for="n in [1, 3] as const"
+ :key="n"
+ :class="{ active: interval === n }"
+ ><input
+ v-model="interval"
+ type="radio"
+ name="billing-interval"
+ :value="n"
+ /><span>{{
+ $t('cloud.billing.' + (n === 1 ? 'monthly' : 'quarterly'))
+ }}</span></label
+ >
+ </fieldset>
+ <p class="cf-field-hint">{{ $t('cloud.billing.paymentsPlanned') }}</p>
+ </div>
+ <CloudCard
+ v-if="error"
+ role="alert"
+ ><p>{{ $t('cloud.billing.failed') }}</p>
+ <CloudButton @click="refresh">{{
+ $t('cloud.billing.retry')
+ }}</CloudButton></CloudCard
+ ><template v-else-if="data"
+ ><div class="cf-pricing-grid">
+ <article
+ v-for="plan in data.plans"
+ :key="plan.id"
+ class="cf-pricing-card"
+ :class="{ 'is-default': plan.id === data.newPlanId }"
+ >
+ <div class="cf-plan-card-heading">
+ <h2>{{ plan.name }}</h2>
+ <CloudBadge v-if="plan.id === data.newPlanId">{{
+ $t('cloud.billing.defaultTier')
+ }}</CloudBadge>
+ </div>
+ <p class="cf-plan-description">
+ {{ plan.description || $t('cloud.billing.simplePlan') }}
+ </p>
+ <div class="cf-plan-price">
+ <strong>{{
+ amount(plan) === 0
+ ? $t('cloud.billing.free')
+ : price(amount(plan), plan.currency, locale)
+ }}</strong
+ ><span v-if="amount(plan) !== null && amount(plan) > 0"
+ >/{{
+ $t('cloud.billing.' + (interval === 1 ? 'month' : 'quarter'))
+ }}</span
+ >
+ </div>
+ <p class="cf-price-caption">
+ {{
+ amount(plan) === null
+ ? $t('cloud.billing.notPriced')
+ : interval === 3 && amount(plan) > 0
+ ? '≈ ' +
+ price(amount(plan)! / 3, plan.currency, locale) +
+ ' / ' +
+ $t('cloud.billing.month')
+ : $t('cloud.billing.noCheckout')
+ }}
+ </p>
+ <CloudButton
+ as-child
+ :variant="plan.id === data.newPlanId ? 'default' : 'secondary'"
+ ><NuxtLink
+ :to="action(plan)"
+ :external="!portal"
+ >{{
+ $t(
+ !portal && plan.id === data.newPlanId
+ ? 'cloud.billing.createAccount'
+ : 'cloud.billing.redeem',
+ )
+ }}</NuxtLink
+ ></CloudButton
+ >
+ <ul class="cf-plan-features">
+ <li
+ v-for="key in BILLING_LIMITS"
+ :key="key"
+ >
+ <span>{{ $t('cloud.billing.' + key) }}</span
+ ><strong>{{
+ allowance(key, plan.policy.limits[key], locale)
+ }}</strong>
+ </li>
+ </ul>
+ <details
+ v-if="plan.policy.rules.length"
+ class="cf-rule-details"
+ >
+ <summary>{{ $t('cloud.billing.conditions') }}</summary>
+ <div
+ v-for="(rule, index) in plan.policy.rules"
+ :key="index"
+ >
+ <p>{{ index + 1 }}. {{ conditionText(rule.when, t) }}</p>
+ <ul>
+ <li
+ v-for="(value, key) in rule.limits"
+ :key="key"
+ >
+ {{ $t('cloud.billing.' + key) }}:
+ {{ allowance(String(key), Number(value), locale) }}
+ </li>
+ </ul>
+ </div>
+ </details>
+ </article>
+ </div>
+ <div
+ v-if="!data.plans.length"
+ class="cf-notice"
+ >
+ {{ $t('cloud.billing.noPlans') }}
+ </div>
+ <section
+ v-else
+ class="cf-plan-comparison"
+ >
+ <h2>{{ $t('cloud.billing.compare') }}</h2>
+ <p class="cf-field-hint">{{ $t('cloud.billing.comparisonHelp') }}</p>
+ <div class="cf-table-scroll">
+ <table>
+ <caption class="sr-only">
+ {{
+ $t('cloud.billing.compare')
+ }}
+ </caption>
+ <thead>
+ <tr>
+ <th scope="col">{{ $t('cloud.billing.allowance') }}</th>
+ <th
+ v-for="plan in data.plans"
+ :key="plan.id"
+ scope="col"
+ >
+ {{ plan.name }}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="key in BILLING_LIMITS"
+ :key="key"
+ >
+ <th scope="row">{{ $t('cloud.billing.' + key) }}</th>
+ <td
+ v-for="plan in data.plans"
+ :key="plan.id"
+ >
+ {{ allowance(key, plan.policy.limits[key], locale) }}
+ </td>
+ </tr>
+ <tr>
+ <th scope="row">{{ $t('cloud.billing.conditions') }}</th>
+ <td
+ v-for="plan in data.plans"
+ :key="plan.id"
+ >
+ {{ plan.policy.rules.length || '—' }}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </section></template
+ >
+ </div>
+</template>
diff --git a/apps/cloud/app/components/CloudUserMenu.vue b/apps/cloud/app/components/CloudUserMenu.vue
index 59217031..b3f95ce1 100644
--- a/apps/cloud/app/components/CloudUserMenu.vue
+++ b/apps/cloud/app/components/CloudUserMenu.vue
@@ -1,7 +1,13 @@
<script setup lang="ts">
const { t } = useI18n()
-import { ChevronsUpDown, UserRound, LogOut } from 'lucide-vue-next'
+import {
+ ChevronsUpDown,
+ UserRound,
+ LogOut,
+ CreditCard,
+ Ticket,
+} from 'lucide-vue-next'
import {
DropdownMenuRoot,
DropdownMenuTrigger,
@@ -69,6 +75,15 @@ const initials = computed(() =>
}}</NuxtLink
></DropdownMenuItem
>
+ <DropdownMenuItem as-child
+ ><NuxtLink to="/account/plan"
+ ><CreditCard :size="16" />{{ $t('cloud.billing.plan') }}</NuxtLink
+ ></DropdownMenuItem
+ ><DropdownMenuItem as-child
+ ><NuxtLink to="/account/redeem"
+ ><Ticket :size="16" />{{ $t('cloud.billing.redeem') }}</NuxtLink
+ ></DropdownMenuItem
+ >
<DropdownMenuSeparator class="cf-menu-separator" />
<DropdownMenuItem
:disabled="busy"
diff --git a/apps/cloud/app/composables/useCloudLinks.ts b/apps/cloud/app/composables/useCloudLinks.ts
index 0a95c502..e9aa5f61 100644
--- a/apps/cloud/app/composables/useCloudLinks.ts
+++ b/apps/cloud/app/composables/useCloudLinks.ts
@@ -8,5 +8,7 @@ export function useCloudLinks() {
website: 'https://chronoframe.art/',
signin: portal + '/signin',
signup: portal + '/signup',
+ redeem: portal + '/account/redeem',
+ portalPricing: portal ? portal + '/pricing' : '/pricing?portal=1',
}
}
diff --git a/apps/cloud/app/composables/useWorkspaceBilling.ts b/apps/cloud/app/composables/useWorkspaceBilling.ts
new file mode 100644
index 00000000..b8900fb4
--- /dev/null
+++ b/apps/cloud/app/composables/useWorkspaceBilling.ts
@@ -0,0 +1,40 @@
+export async function useWorkspaceBilling(adminOnly = false) {
+ const route = useRoute(),
+ user = usePortalIdentity(),
+ fetcher = useRequestFetch()
+ const { data: list, error: listError } = await useFetch<{
+ workspaces: { id: number; name: string; role: string }[]
+ }>('/api/billing/workspaces', { key: 'billing-workspaces-' + user.value?.id })
+ const workspaces = computed(() =>
+ (list.value?.workspaces ?? []).filter(
+ (w) => !adminOnly || w.role === 'admin',
+ ),
+ )
+ const selected = ref(
+ workspaces.value.some((w) => w.id === Number(route.query.workspaceId))
+ ? Number(route.query.workspaceId)
+ : (workspaces.value[0]?.id ?? 0),
+ )
+ const { data, error, status, refresh } = await useAsyncData(
+ computed(
+ () => 'workspace-billing-' + user.value?.id + '-' + selected.value,
+ ),
+ () =>
+ selected.value
+ ? fetcher<any>('/api/billing/plan', {
+ query: { workspaceId: selected.value },
+ })
+ : Promise.resolve(null),
+ )
+ onMounted(async () => {
+ if (!workspaces.value.length && !listError.value) {
+ try {
+ list.value = await $fetch('/api/billing/workspaces', { method: 'POST' })
+ selected.value = workspaces.value[0]?.id ?? 0
+ } catch {
+ /* Do not restore revoked memberships. */
+ }
+ }
+ })
+ return { workspaces, selected, data, error, listError, status, refresh }
+}
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index c4d11f08..0522f8d0 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -21,6 +21,9 @@ export default defineNuxtRouteMiddleware(async (to) => {
return navigateTo('/sites', { redirectCode: 302 })
}
if (
+ (path === '/pricing' &&
+ (useRequestURL().hostname === 'app.chronoframe.art' ||
+ to.query.portal === '1')) ||
path === '/account' ||
path.startsWith('/account/') ||
path === '/sites' ||
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
new file mode 100644
index 00000000..6383bcb5
--- /dev/null
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -0,0 +1,204 @@
+<script setup lang="ts">
+import { BILLING_LIMITS, allowance } from '../../utils/billing-format'
+definePageMeta({ layout: 'portal' })
+const { t, locale } = useI18n(),
+ links = useCloudLinks(),
+ { workspaces, selected, data, error, listError, status, refresh } =
+ await useWorkspaceBilling()
+useSeoMeta({
+ title: t('cloud.billing.plan') + ' — ChronoFrame Cloud',
+ robots: 'noindex',
+})
+useIntervalFn(() => {
+ if (document.visibilityState === 'visible' && status.value !== 'pending')
+ void refresh()
+}, 15000)
+const used = (key: string) =>
+ key === 'fileBytes' ? null : Number(data.value?.usage[key] ?? 0)
+const ratio = (key: string) =>
+ Math.min(
+ 100,
+ Math.round(
+ ((used(key) ?? 0) / Math.max(1, data.value?.plan.limits[key] ?? 0)) * 100,
+ ),
+ )
+const date = (time: number) => new Date(time).toLocaleString(locale.value)
+</script>
+<template>
+ <div class="cf-plan-page">
+ <div class="cf-page-heading">
+ <div>
+ <h1 class="cf-page-title">{{ $t('cloud.billing.plan') }}</h1>
+ <p class="cf-page-description">{{ $t('cloud.billing.planHelp') }}</p>
+ </div>
+ <CloudButton
+ as-child
+ variant="secondary"
+ ><NuxtLink :to="links.portalPricing">{{
+ $t('cloud.billing.compare')
+ }}</NuxtLink></CloudButton
+ >
+ </div>
+ <label class="cf-workspace-picker"
+ >{{ $t('cloud.billing.workspace')
+ }}<select v-model="selected">
+ <option
+ v-for="w in workspaces"
+ :key="w.id"
+ :value="w.id"
+ >
+ {{ w.name }}
+ </option>
+ </select></label
+ ><CloudCard
+ v-if="error || listError"
+ role="alert"
+ ><p>{{ $t('cloud.billing.failed') }}</p>
+ <CloudButton @click="refresh">{{
+ $t('cloud.billing.retry')
+ }}</CloudButton></CloudCard
+ ><template v-else-if="data"
+ ><CloudCard class="cf-current-plan"
+ ><div>
+ <span class="cf-eyebrow">{{ $t('cloud.billing.current') }}</span>
+ <h2>{{ data.plan.name }}</h2>
+ <p>
+ {{
+ data.subscription.expiresAt
+ ? $t('cloud.billing.expires', {
+ date: date(data.subscription.expiresAt),
+ })
+ : $t('cloud.billing.noExpiry')
+ }}
+ </p>
+ <p class="cf-field-hint">{{ $t('cloud.billing.noRenewal') }}</p>
+ </div>
+ <CloudButton
+ v-if="data.workspace.role === 'admin'"
+ as-child
+ ><NuxtLink :to="links.redeem + '?workspaceId=' + selected">{{
+ $t('cloud.billing.redeem')
+ }}</NuxtLink></CloudButton
+ ></CloudCard
+ >
+ <section>
+ <div class="cf-plan-section-heading">
+ <div>
+ <h2>{{ $t('cloud.billing.usage') }}</h2>
+ <p class="cf-field-hint">
+ {{
+ $t('cloud.billing.period', {
+ start: date(data.quotaPeriod.start),
+ end: date(data.quotaPeriod.end),
+ })
+ }}
+ </p>
+ </div>
+ <CloudButton
+ variant="ghost"
+ :disabled="status === 'pending'"
+ @click="refresh"
+ >{{ $t('cloud.billing.refresh') }}</CloudButton
+ >
+ </div>
+ <div class="cf-quota-grid">
+ <article
+ v-for="key in BILLING_LIMITS"
+ :key="key"
+ class="cf-quota-card"
+ >
+ <h3>{{ $t('cloud.billing.' + key) }}</h3>
+ <template v-if="key === 'byos'"
+ ><p>
+ <strong>{{
+ data.plan.limits.byos
+ ? $t('cloud.billing.yes')
+ : $t('cloud.billing.no')
+ }}</strong>
+ </p>
+ <small>{{
+ $t('cloud.billing.connectionCount', { count: data.usage.byos })
+ }}</small></template
+ >
+ <p v-else-if="used(key) === null">
+ <strong>{{
+ allowance(key, data.plan.limits[key], locale)
+ }}</strong
+ ><span>{{ $t('cloud.billing.perFile') }}</span>
+ </p>
+ <template v-else
+ ><p>
+ <strong>{{ allowance(key, used(key)!, locale) }}</strong
+ ><span
+ >/ {{ allowance(key, data.plan.limits[key], locale) }}</span
+ >
+ </p>
+ <div
+ class="cf-quota-track"
+ role="progressbar"
+ :aria-label="$t('cloud.billing.' + key)"
+ :aria-valuemin="0"
+ :aria-valuemax="100"
+ :aria-valuenow="ratio(key)"
+ >
+ <span
+ :style="{ width: ratio(key) + '%' }"
+ :class="{ 'is-over': used(key)! > data.plan.limits[key] }"
+ />
+ </div>
+ <small
+ :class="{
+ 'cf-error-message': used(key)! > data.plan.limits[key],
+ }"
+ >{{
+ used(key)! > data.plan.limits[key]
+ ? $t('cloud.billing.overQuota')
+ : $t('cloud.billing.remaining', {
+ value: allowance(
+ key,
+ Math.max(0, data.plan.limits[key] - used(key)!),
+ locale,
+ ),
+ })
+ }}</small
+ ></template
+ >
+ </article>
+ </div>
+ <p class="cf-field-hint">{{ $t('cloud.billing.usageHelp') }}</p>
+ </section>
+ <details class="cf-billing-details">
+ <summary>{{ $t('cloud.billing.byosAllowances') }}</summary>
+ <dl>
+ <template
+ v-for="key in BILLING_LIMITS"
+ :key="key"
+ ><dt>{{ $t('cloud.billing.' + key) }}</dt>
+ <dd>
+ {{ allowance(key, data.plan.byosLimits[key], locale) }}
+ </dd></template
+ >
+ </dl>
+ </details>
+ <section v-if="data.history.length">
+ <h2>{{ $t('cloud.billing.history') }}</h2>
+ <ol class="cf-subscription-history">
+ <li
+ v-for="(event, index) in data.history"
+ :key="index"
+ >
+ <span>{{ $t('cloud.billing.event_' + event.kind) }}</span
+ ><time>{{ date(event.created_at) }}</time>
+ </li>
+ </ol>
+ </section></template
+ >
+ <div
+ v-else
+ role="status"
+ class="cf-notice"
+ >
+ {{ $t('cloud.billing.loading') }}
+ </div>
+ </div>
+</template>
diff --git a/apps/cloud/app/pages/account/redeem.vue b/apps/cloud/app/pages/account/redeem.vue
new file mode 100644
index 00000000..7c2616d3
--- /dev/null
+++ b/apps/cloud/app/pages/account/redeem.vue
@@ -0,0 +1,201 @@
+<script setup lang="ts">
+import { billingError } from '../../utils/billing-format'
+definePageMeta({ layout: 'portal' })
+const { t, locale } = useI18n(),
+ { workspaces, selected, error, listError, refresh } =
+ await useWorkspaceBilling(true),
+ code = ref(''),
+ preview = ref<any>(null),
+ busy = ref(false),
+ failure = ref(''),
+ receipt = ref<any>(null),
+ requestId = ref('')
+useSeoMeta({
+ title: t('cloud.billing.redeem') + ' — ChronoFrame Cloud',
+ robots: 'noindex',
+})
+watch([code, selected], () => {
+ preview.value = null
+ receipt.value = null
+ requestId.value = ''
+ failure.value = ''
+})
+async function inspect() {
+ busy.value = true
+ failure.value = ''
+ try {
+ preview.value = await $fetch('/api/billing/redeem', {
+ method: 'POST',
+ body: {
+ action: 'preview',
+ workspaceId: selected.value,
+ code: code.value,
+ },
+ })
+ requestId.value = crypto.randomUUID()
+ } catch (error) {
+ failure.value = billingError(error, t)
+ } finally {
+ busy.value = false
+ }
+}
+async function redeem() {
+ if (!preview.value || busy.value) return
+ busy.value = true
+ failure.value = ''
+ try {
+ receipt.value = await $fetch('/api/billing/redeem', {
+ method: 'POST',
+ body: {
+ action: 'redeem',
+ workspaceId: selected.value,
+ code: code.value,
+ revision: preview.value.revision,
+ requestId: requestId.value,
+ },
+ })
+ preview.value = null
+ await refresh().catch(() => {})
+ } catch (error: any) {
+ failure.value = billingError(error, t)
+ const code = error?.data?.data?.code ?? error?.data?.code
+ if (['subscription_changed', 'redemption_changed'].includes(code)) {
+ preview.value = null
+ requestId.value = ''
+ }
+ } finally {
+ busy.value = false
+ }
+}
+const date = (time: number) => new Date(time).toLocaleString(locale.value)
+</script>
+<template>
+ <div class="cf-redeem-page">
+ <div class="cf-page-heading">
+ <div>
+ <h1 class="cf-page-title">{{ $t('cloud.billing.redeem') }}</h1>
+ <p class="cf-page-description">{{ $t('cloud.billing.redeemHelp') }}</p>
+ </div>
+ </div>
+ <CloudCard
+ ><form
+ class="cf-form"
+ @submit.prevent="inspect"
+ >
+ <label class="cf-field"
+ >{{ $t('cloud.billing.workspace')
+ }}<select
+ v-model="selected"
+ :disabled="busy || !!receipt"
+ >
+ <option
+ v-for="w in workspaces"
+ :key="w.id"
+ :value="w.id"
+ >
+ {{ w.name }}
+ </option>
+ </select></label
+ ><label class="cf-field"
+ >{{ $t('cloud.billing.code')
+ }}<CloudInput
+ v-model="code"
+ required
+ maxlength="128"
+ autocomplete="off"
+ spellcheck="false"
+ placeholder="CF-…"
+ :disabled="busy || !!receipt"
+ /></label>
+ <p class="cf-field-hint">{{ $t('cloud.billing.codeHelp') }}</p>
+ <CloudButton
+ v-if="!preview && !receipt"
+ type="submit"
+ :disabled="busy || !selected || !code.trim()"
+ >{{
+ busy ? $t('cloud.billing.loading') : $t('cloud.billing.checkCode')
+ }}</CloudButton
+ >
+ <p
+ v-if="!workspaces.length"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ $t('cloud.billing.adminOnly') }}
+ </p>
+ </form>
+ <div
+ v-if="preview"
+ class="cf-redemption-preview"
+ >
+ <h2>{{ $t('cloud.billing.confirmRedeem') }}</h2>
+ <dl>
+ <dt>{{ $t('cloud.billing.current') }}</dt>
+ <dd>{{ preview.current.planName }}</dd>
+ <dt>{{ $t('cloud.billing.newTier') }}</dt>
+ <dd>{{ preview.grant.planName }}</dd>
+ <dt>{{ $t('cloud.billing.expiry') }}</dt>
+ <dd>
+ {{
+ preview.grant.expiresAt
+ ? date(preview.grant.expiresAt)
+ : $t('cloud.billing.noExpiry')
+ }}
+ </dd>
+ </dl>
+ <p>
+ {{
+ $t(
+ 'cloud.billing.' +
+ (preview.grant.mode === 'extend'
+ ? 'extendHelp'
+ : 'replaceHelp'),
+ )
+ }}
+ </p>
+ <CloudButton
+ :disabled="busy"
+ @click="redeem"
+ >{{ $t('cloud.billing.confirmRedeem') }}</CloudButton
+ ><CloudButton
+ variant="ghost"
+ :disabled="busy"
+ @click="preview = null"
+ >{{ $t('cloud.billing.cancel') }}</CloudButton
+ >
+ </div>
+ <div
+ v-if="receipt"
+ class="cf-notice"
+ role="status"
+ >
+ <h2>{{ $t('cloud.billing.redeemed') }}</h2>
+ <p>
+ {{ receipt.grant.planName }} ·
+ {{
+ receipt.grant.expiresAt
+ ? date(receipt.grant.expiresAt)
+ : $t('cloud.billing.noExpiry')
+ }}
+ </p>
+ <NuxtLink :to="'/account/plan?workspaceId=' + selected">{{
+ $t('cloud.billing.viewPlan')
+ }}</NuxtLink>
+ </div>
+ <p
+ v-if="listError || error"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ $t('cloud.billing.failed') }}
+ </p>
+ <p
+ v-if="failure"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ failure }}
+ </p></CloudCard
+ >
+ </div>
+</template>
diff --git a/apps/cloud/app/pages/index.vue b/apps/cloud/app/pages/index.vue
index e763a657..e3334d8e 100644
--- a/apps/cloud/app/pages/index.vue
+++ b/apps/cloud/app/pages/index.vue
@@ -9,10 +9,7 @@ import {
HardDrive,
Code2,
Check,
- Menu,
} from 'lucide-vue-next'
-import { PopoverRoot, PopoverTrigger, PopoverContent } from 'reka-ui'
-const mobileMenuOpen = ref(false)
const entrance = useCloudMotion()
const links = useCloudLinks()
useSeoMeta({
@@ -24,88 +21,7 @@ useSeoMeta({
</script>
<template>
<div class="cf-marketing">
- <header class="cf-marketing-header">
- <CloudBrand />
- <nav
- class="cf-marketing-nav"
- :aria-label="$t('cloud.messages.mainNavigation')"
- >
- <a href="https://docs.chronoframe.art/">{{
- $t('cloud.messages.documentation')
- }}</a
- ><a href="https://github.com/HoshinoSuzumi/chronoframe"
- >GitHub
- <ArrowUpRight
- :size="12"
- aria-hidden="true"
- class="cf-inline-icon" /></a
- ><CloudThemeToggle />
- <CloudButton
- as-child
- variant="secondary"
- size="sm"
- ><NuxtLink
- :to="links.signin"
- external
- >{{ $t('cloud.messages.logIn') }}</NuxtLink
- ></CloudButton
- ><CloudButton
- as-child
- size="sm"
- ><NuxtLink
- :to="links.signup"
- external
- >{{ $t('cloud.messages.getStarted')
- }}<ArrowUpRight :size="14" /></NuxtLink
- ></CloudButton>
- </nav>
- <div class="cf-mobile-header-actions">
- <CloudButton
- as-child
- size="sm"
- ><NuxtLink
- :to="links.signup"
- external
- >{{ $t('cloud.messages.signUp') }}</NuxtLink
- ></CloudButton
- >
- <PopoverRoot v-model:open="mobileMenuOpen">
- <PopoverTrigger as-child
- ><CloudButton
- variant="ghost"
- size="icon"
- :aria-label="$t('cloud.messages.openNavigation')"
- ><Menu :size="20" /></CloudButton
- ></PopoverTrigger>
- <PopoverContent
- class="cf-mobile-menu"
- align="end"
- :side-offset="12"
- :collision-padding="20"
- :aria-label="$t('cloud.messages.navigation')"
- >
- <nav :aria-label="$t('cloud.messages.mobileNavigation')">
- <NuxtLink
- :to="links.signin"
- external
- >{{ $t('cloud.messages.logIn') }}<ArrowRight :size="16"
- /></NuxtLink>
- <a href="https://docs.chronoframe.art/"
- >{{ $t('cloud.messages.documentation')
- }}<ArrowUpRight :size="15"
- /></a>
- <a href="https://github.com/HoshinoSuzumi/chronoframe"
- >GitHub <ArrowUpRight :size="15"
- /></a>
- </nav>
- <div class="cf-mobile-menu-theme">
- <span>{{ $t('cloud.messages.appearance') }}</span
- ><CloudThemeToggle />
- </div>
- </PopoverContent>
- </PopoverRoot>
- </div>
- </header>
+ <CloudMarketingHeader />
<main
id="main-content"
tabindex="-1"
diff --git a/apps/cloud/app/pages/pricing.vue b/apps/cloud/app/pages/pricing.vue
new file mode 100644
index 00000000..bd04e858
--- /dev/null
+++ b/apps/cloud/app/pages/pricing.vue
@@ -0,0 +1,32 @@
+<script setup lang="ts">
+const route = useRoute(),
+ portal =
+ useRequestURL().hostname === 'app.chronoframe.art' ||
+ route.query.portal === '1',
+ { t } = useI18n()
+definePageMeta({ layout: false })
+useSeoMeta({
+ title: t('cloud.billing.pricing') + ' — ChronoFrame Cloud',
+ description: t('cloud.billing.pricingHelp'),
+ ...(portal ? { robots: 'noindex' } : {}),
+})
+</script>
+<template>
+ <NuxtLayout
+ v-if="portal"
+ name="portal"
+ ><CloudPricing portal
+ /></NuxtLayout>
+ <div
+ v-else
+ class="cf-marketing"
+ >
+ <CloudMarketingHeader />
+ <main
+ id="main-content"
+ tabindex="-1"
+ >
+ <CloudPricing />
+ </main>
+ </div>
+</template>
diff --git a/apps/cloud/app/utils/billing-format.ts b/apps/cloud/app/utils/billing-format.ts
new file mode 100644
index 00000000..6b9772e2
--- /dev/null
+++ b/apps/cloud/app/utils/billing-format.ts
@@ -0,0 +1,78 @@
+export const BILLING_LIMITS = [
+ 'storageBytes',
+ 'fileBytes',
+ 'sites',
+ 'photos',
+ 'customDomains',
+ 'byos',
+ 'monthlyBytes',
+] as const
+export function allowance(key: string, value: number, locale: string) {
+ if (key === 'byos') return value ? '✓' : '—'
+ if (key.endsWith('Bytes')) {
+ if (!value) return '0 B'
+ const i = Math.min(3, Math.floor(Math.log(value) / Math.log(1024)))
+ return (
+ new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(
+ value / 1024 ** i,
+ ) +
+ ' ' +
+ ['B', 'KiB', 'MiB', 'GiB'][i]
+ )
+ }
+ return new Intl.NumberFormat(locale).format(value)
+}
+export function price(amount: number | null, currency: string, locale: string) {
+ return amount === null
+ ? '—'
+ : new Intl.NumberFormat(locale, {
+ style: 'currency',
+ currency,
+ maximumFractionDigits: 2,
+ }).format(amount / 100)
+}
+export function conditionText(c: any, t: (key: string) => string): string {
+ if (c.all)
+ return (
+ '(' +
+ c.all
+ .map((v: any) => conditionText(v, t))
+ .join(' ' + t('cloud.billing.and') + ' ') +
+ ')'
+ )
+ if (c.any)
+ return (
+ '(' +
+ c.any
+ .map((v: any) => conditionText(v, t))
+ .join(' ' + t('cloud.billing.or') + ' ') +
+ ')'
+ )
+ const value =
+ typeof c.value === 'boolean'
+ ? t('cloud.billing.' + (c.value ? 'yes' : 'no'))
+ : c.field === 'storageMode'
+ ? t('cloud.billing.' + c.value)
+ : String(c.value)
+ return (
+ t('cloud.billing.' + c.field) +
+ ' ' +
+ { eq: '=', gte: '≥', lte: '≤' }[c.op as 'eq'] +
+ ' ' +
+ value
+ )
+}
+export function billingError(error: any, t: (key: string) => string) {
+ const code = error?.data?.data?.code ?? error?.data?.code
+ const key = (
+ {
+ invalid_activation_code: 'invalidCode',
+ permanent_plan_active: 'permanentActive',
+ activation_rate_limit: 'rateLimit',
+ subscription_changed: 'changed',
+ workspace_admin_required: 'adminOnly',
+ redemption_changed: 'changed',
+ } as Record<string, string>
+ )[code]
+ return t('cloud.billing.' + (key ?? 'failed'))
+}
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index 56645ccb..2b789afc 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -436,7 +436,7 @@
"photoMembershipCount": "Photographs · {count}",
"securityFor": "Manage sign-in methods for {email}.",
"uploadProgress": "{progress}% · Uploading to your private bucket",
- "uploadUsage": "Workspace: {photos} / {photoLimit} photographs · {bytes} / {uploadLimit} GiB uploaded in 30 days",
+ "uploadUsage": "Workspace: {photos} / {photoLimit} photographs · {bytes} / {uploadLimit} GiB uploaded this quota month",
"connectionRevision": "{bucket} · revision {revision}",
"admin": "Admin",
"member": "Member",
@@ -596,6 +596,83 @@
"clear": "Clear link {number}",
"invalid": "Enter a valid HTTPS profile URL.",
"duplicate": "This profile is already listed."
+ },
+ "billing": {
+ "plan": "Plan & usage",
+ "pricing": "Pricing",
+ "pricingHelp": "A place for every collection. Compare the plans and choose room to grow.",
+ "interval": "Billing interval",
+ "monthly": "Monthly",
+ "quarterly": "Quarterly",
+ "month": "month",
+ "quarter": "quarter",
+ "paymentsPlanned": "Online payments are not enabled yet. Prices are a preview; eligible activation codes can be redeemed now.",
+ "defaultTier": "New account default",
+ "simplePlan": "Your photographs, with room to make it yours.",
+ "free": "Free",
+ "notPriced": "Price not configured",
+ "noCheckout": "No charge will be made on this page.",
+ "createAccount": "Create your account",
+ "redeem": "Redeem code",
+ "conditions": "Conditional allowances",
+ "noPlans": "No plans are currently listed.",
+ "compare": "Compare plans",
+ "comparisonHelp": "Base allowances shown below. Conditional rules are applied in order; later matches override selected values. Stock limits do not multiply with quarterly billing.",
+ "allowance": "Allowance",
+ "storageBytes": "Platform storage",
+ "fileBytes": "Maximum file size",
+ "sites": "Sites",
+ "photos": "Photographs (including pending uploads)",
+ "customDomains": "Custom domains",
+ "byos": "Custom S3 storage",
+ "monthlyBytes": "Monthly uploads",
+ "and": "AND",
+ "or": "OR",
+ "yes": "Enabled",
+ "no": "Not included",
+ "platform": "Platform storage",
+ "storageMode": "Storage mode",
+ "workspaceAgeDays": "Workspace age (days)",
+ "emailVerified": "Verified email",
+ "planHelp": "Your current subscription and live workspace-wide allowances.",
+ "workspace": "Workspace",
+ "current": "Current plan",
+ "expires": "Expires {date}",
+ "noExpiry": "No expiration",
+ "noRenewal": "No automatic renewal or online charge is enabled. At expiration, the configured default plan applies.",
+ "usage": "Live usage",
+ "period": "Monthly quota period: {start} — {end}",
+ "refresh": "Refresh",
+ "perFile": "per file",
+ "overQuota": "Over current allowance; existing media is retained.",
+ "remaining": "{value} remaining",
+ "usageHelp": "Storage includes pending uploads and reserved processing outputs. Photograph counts include pending uploads. Monthly uploads reset each calendar-month quota period, including on quarterly terms.",
+ "byosAllowances": "Allowances with custom S3 storage",
+ "history": "Subscription history",
+ "event_assigned": "Plan assigned",
+ "event_redeemed": "Activation code redeemed",
+ "event_expired": "Expired plan reverted",
+ "loading": "Loading…",
+ "redeemHelp": "Apply a plan to a workspace you administer. Review the change before confirming.",
+ "code": "Activation code",
+ "codeHelp": "Each account can redeem each code once. Inactive, expired or exhausted codes cannot be used.",
+ "checkCode": "Check code",
+ "confirmRedeem": "Confirm redemption",
+ "newTier": "New plan",
+ "expiry": "Expiration",
+ "extendHelp": "This extends the current plan from its existing expiration. No payment is collected.",
+ "replaceHelp": "This replaces the current tier immediately. Its allowances apply as soon as redemption succeeds. Existing media is retained. No payment is collected.",
+ "cancel": "Cancel",
+ "redeemed": "Code redeemed",
+ "viewPlan": "View plan and usage",
+ "invalidCode": "This code is invalid, unavailable, expired, exhausted or has already been redeemed.",
+ "permanentActive": "Your current plan already has no expiration. This code was not consumed.",
+ "rateLimit": "Too many attempts. Wait a few minutes and try again.",
+ "changed": "Your subscription changed. Check the code again before confirming.",
+ "adminOnly": "Only workspace administrators can redeem activation codes.",
+ "failed": "Could not load or save subscription information. Try again.",
+ "retry": "Try again",
+ "connectionCount": "{count} existing storage connections"
}
}
}
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 5505ac34..0868cd07 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -436,7 +436,7 @@
"photoMembershipCount": "照片 · {count}",
"securityFor": "管理 {email} 的登录方式。",
"uploadProgress": "{progress}% · 正在上传到你的私有存储桶",
- "uploadUsage": "工作空间:{photos} / {photoLimit} 张照片 · 30 天上传 {bytes} / {uploadLimit} GiB",
+ "uploadUsage": "工作空间:{photos} / {photoLimit} 张照片 · 本配额月上传 {bytes} / {uploadLimit} GiB",
"connectionRevision": "{bucket} · 凭证版本 {revision}",
"admin": "管理员",
"member": "成员",
@@ -596,6 +596,83 @@
"clear": "清空链接 {number}",
"invalid": "请输入有效的 HTTPS 个人主页链接。",
"duplicate": "该个人主页已添加。"
+ },
+ "billing": {
+ "plan": "套餐与用量",
+ "pricing": "定价",
+ "pricingHelp": "为每一份影像珍藏,选择适合的空间与权益。",
+ "interval": "计费周期",
+ "monthly": "按月",
+ "quarterly": "按季",
+ "month": "月",
+ "quarter": "季",
+ "paymentsPlanned": "尚未启用在线支付,价格仅供预览;持有有效激活码的用户现在即可兑换。",
+ "defaultTier": "新账号默认层级",
+ "simplePlan": "让照片成为主角,为你的故事留出空间。",
+ "free": "免费",
+ "notPriced": "价格尚未配置",
+ "noCheckout": "此页面不会发起扣款。",
+ "createAccount": "创建账号",
+ "redeem": "兑换激活码",
+ "conditions": "条件权益",
+ "noPlans": "暂无公开的套餐。",
+ "compare": "对比套餐",
+ "comparisonHelp": "下方展示基础权益;条件规则按顺序执行,后匹配的规则覆盖指定值。季付不会将存量配额翻倍。",
+ "allowance": "权益",
+ "storageBytes": "平台存储",
+ "fileBytes": "单文件上限",
+ "sites": "站点数量",
+ "photos": "照片数量(含待上传)",
+ "customDomains": "自定义域名",
+ "byos": "自定义 S3 存储",
+ "monthlyBytes": "月度上传量",
+ "and": "且",
+ "or": "或",
+ "yes": "已包含",
+ "no": "不包含",
+ "platform": "平台存储",
+ "storageMode": "存储模式",
+ "workspaceAgeDays": "工作空间年龄(天)",
+ "emailVerified": "邮箱已验证",
+ "planHelp": "查看当前订阅及整个工作空间的实时配额使用情况。",
+ "workspace": "工作空间",
+ "current": "当前层级",
+ "expires": "到期时间:{date}",
+ "noExpiry": "长期有效",
+ "noRenewal": "尚未启用自动续费或在线扣款,到期后自动回退到配置的默认层级。",
+ "usage": "实时用量",
+ "period": "月度配额周期:{start} — {end}",
+ "refresh": "刷新",
+ "perFile": "每个文件",
+ "overQuota": "已超过当前配额,现有媒体仍予保留。",
+ "remaining": "剩余 {value}",
+ "usageHelp": "存储统计包含待上传和处理任务预留空间,照片数量包含待上传项。上传量按月度配额周期重置,季付订阅同样每月结算上传量。",
+ "byosAllowances": "使用自定义 S3 时的权益",
+ "history": "订阅记录",
+ "event_assigned": "指派套餐",
+ "event_redeemed": "兑换激活码",
+ "event_expired": "到期回退",
+ "loading": "加载中…",
+ "redeemHelp": "为你管理的工作空间兑换套餐,确认前可先核对变更内容。",
+ "code": "激活码",
+ "codeHelp": "每个账号对同一码仅可兑换一次。已停用、过期、兑换完毕或对应层级不可用的码均不可兑换。",
+ "checkCode": "检查激活码",
+ "confirmRedeem": "确认兑换",
+ "newTier": "兑换后层级",
+ "expiry": "到期时间",
+ "extendHelp": "将在当前到期时间后延长同一层级的使用时长,本次操作不会扣款。",
+ "replaceHelp": "兑换成功后立即切换至所示层级并使用其配额,现有媒体保留。本次操作不会扣款。",
+ "cancel": "取消",
+ "redeemed": "兑换成功",
+ "viewPlan": "查看套餐与用量",
+ "invalidCode": "激活码无效、不可用、已过期、已达兑换上限或已被你兑换。",
+ "permanentActive": "当前套餐已长期有效,该激活码未被消耗。",
+ "rateLimit": "尝试次数过多,请稍后重试。",
+ "changed": "订阅状态已变化,请重新检查激活码后确认。",
+ "adminOnly": "仅工作空间管理员可以兑换激活码。",
+ "failed": "无法读取或保存订阅信息,请重试。",
+ "retry": "重试",
+ "connectionCount": "已有 {count} 个存储连接"
}
}
}
diff --git a/apps/cloud/server/api/billing/catalog.get.ts b/apps/cloud/server/api/billing/catalog.get.ts
new file mode 100644
index 00000000..b4ba3207
--- /dev/null
+++ b/apps/cloud/server/api/billing/catalog.get.ts
@@ -0,0 +1,10 @@
+import { pricingCatalog } from '../../../../../packages/platform/src/billing'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../shared/platform/runtime'
+import { setResponseHeader } from 'h3'
+export default definePlatformHandler(async (event) => {
+ setResponseHeader(event, 'Cache-Control', 'no-store')
+ return pricingCatalog(platformDatabase(event))
+})
diff --git a/apps/cloud/server/api/billing/plan.get.ts b/apps/cloud/server/api/billing/plan.get.ts
new file mode 100644
index 00000000..296a3af3
--- /dev/null
+++ b/apps/cloud/server/api/billing/plan.get.ts
@@ -0,0 +1,18 @@
+import { workspaceBilling } from '../../../../../packages/platform/src/billing'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { getQuery, createError, setResponseHeader } from 'h3'
+export default definePlatformHandler(async (event) => {
+ const user = await requirePlatformSession(
+ event,
+ useRuntimeConfig(event).platform,
+ ),
+ id = Number(getQuery(event).workspaceId)
+ if (!Number.isSafeInteger(id) || id < 1)
+ throw createError({ statusCode: 400 })
+ setResponseHeader(event, 'Cache-Control', 'no-store')
+ return workspaceBilling(platformDatabase(event), user.userId, id)
+})
diff --git a/apps/cloud/server/api/billing/redeem.post.ts b/apps/cloud/server/api/billing/redeem.post.ts
new file mode 100644
index 00000000..3833a6d1
--- /dev/null
+++ b/apps/cloud/server/api/billing/redeem.post.ts
@@ -0,0 +1,39 @@
+import {
+ previewActivation,
+ redeemActivation,
+} from '../../../../../packages/platform/src/activation'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { createError } from 'h3'
+import { siteManagementBody } from '../../utils/site-management'
+export default definePlatformHandler(async (event) => {
+ const user = await requirePlatformSession(
+ event,
+ useRuntimeConfig(event).platform,
+ )
+ platformPortalOrigin(
+ event,
+ useRuntimeConfig(event).platform.portalOrigin,
+ true,
+ )
+ const body = await siteManagementBody(event, 4096),
+ id = Number(body?.workspaceId)
+ if (
+ !Number.isSafeInteger(id) ||
+ id < 1 ||
+ !['preview', 'redeem'].includes(body?.action)
+ )
+ throw createError({ statusCode: 400 })
+ const db = platformDatabase(event)
+ return body.action === 'preview'
+ ? previewActivation(db, user.userId, id, body.code)
+ : redeemActivation(db, user.userId, id, {
+ code: body.code,
+ requestId: body.requestId,
+ revision: body.revision,
+ })
+})
diff --git a/apps/cloud/server/api/billing/workspaces.get.ts b/apps/cloud/server/api/billing/workspaces.get.ts
new file mode 100644
index 00000000..5726f8ae
--- /dev/null
+++ b/apps/cloud/server/api/billing/workspaces.get.ts
@@ -0,0 +1,14 @@
+import { billingWorkspaces } from '../../../../../packages/platform/src/billing'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+export default definePlatformHandler(async (event) => {
+ const user = await requirePlatformSession(
+ event,
+ useRuntimeConfig(event).platform,
+ ),
+ db = platformDatabase(event)
+ return { workspaces: await billingWorkspaces(db, user.userId) }
+})
diff --git a/apps/cloud/server/api/billing/workspaces.post.ts b/apps/cloud/server/api/billing/workspaces.post.ts
new file mode 100644
index 00000000..5637213c
--- /dev/null
+++ b/apps/cloud/server/api/billing/workspaces.post.ts
@@ -0,0 +1,16 @@
+import { billingWorkspaces } from '../../../../../packages/platform/src/billing'
+import { createD1Provisioning } from '../../../../../packages/platform/src/index'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+export default definePlatformHandler(async (event) => {
+ const config = useRuntimeConfig(event).platform,
+ user = await requirePlatformSession(event, config)
+ platformPortalOrigin(event, config.portalOrigin, true)
+ const db = platformDatabase(event)
+ await createD1Provisioning(db).defaultWorkspace(user.userId)
+ return { workspaces: await billingWorkspaces(db, user.userId) }
+})
diff --git a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
index 7e47844b..11276c3f 100644
--- a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
+++ b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
@@ -142,12 +142,12 @@ export default definePlatformHandler(async (event) => {
.first<{ bytes: number }>()
const usage = (
await sql<{ photos: number; pending: number; bytes: number }>(
- `SELECT (SELECT COUNT(*) FROM cloud_photos WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND deleted=0) AS photos,(SELECT COUNT(*) FROM cloud_uploads WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND state='pending' AND expires_at>?) AS pending,COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND created_at>?),0) AS bytes`,
+ `SELECT (SELECT COUNT(*) FROM cloud_photos WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND deleted=0) AS photos,(SELECT COUNT(*) FROM cloud_uploads WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND state='pending' AND expires_at>?) AS pending,COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND created_at>=?),0) AS bytes`,
site.workspaceId,
site.workspaceId,
now,
site.workspaceId,
- now - 30 * 86400000,
+ plan.quotaPeriod.start,
)
)[0]
return {
@@ -156,6 +156,8 @@ export default definePlatformHandler(async (event) => {
byosLimits: (await workspaceEntitlements(raw, site.workspaceId, 'byos'))
.limits,
plan: { id: plan.id, name: plan.name },
+ quotaPeriod: plan.quotaPeriod,
+ subscription: plan.subscription,
storageBytes: storageUsage?.bytes ?? 0,
}
}
@@ -228,7 +230,7 @@ export default definePlatformHandler(async (event) => {
managed ? bytes + videoBytes : 0,
now,
entitlement.limits.photos,
- now - 30 * 86400000,
+ entitlement.quotaPeriod.start,
now,
bytes + videoBytes,
entitlement.limits.monthlyBytes,
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index 9aaa892c..89f7ef9e 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -18,6 +18,10 @@ export default defineEventHandler((event) => {
'/api/auth/logout',
'/api/auth/security',
'/api/sites',
+ '/api/billing/catalog',
+ '/api/billing/workspaces',
+ '/api/billing/plan',
+ '/api/billing/redeem',
'/api/workspaces/default',
].includes(path) ||
/^\/api\/sites\/[1-9][0-9]*\/(?:context|events|settings|domains)$/.test(
diff --git a/apps/cloud/server/plugins/domains.ts b/apps/cloud/server/plugins/domains.ts
index 9da3cdb8..f5c8dbe4 100644
--- a/apps/cloud/server/plugins/domains.ts
+++ b/apps/cloud/server/plugins/domains.ts
@@ -1,3 +1,4 @@
+import { reconcileSubscriptions } from '../../../../packages/platform/src/subscriptions'
import { domainServices } from '../../../shared/platform/domains'
import type { PlatformD1 } from '@chronoframe/platform'
/** A maximum of 20 provider reservations plus 10 unverified claims bounds this one-host-per-minute queue. */
@@ -5,6 +6,7 @@ export default defineNitroPlugin((app) => {
app.hooks.hook('cloudflare:scheduled', async ({ env }) => {
const db = env.DB as PlatformD1 | undefined
if (!db) return
+ await reconcileSubscriptions(db)
const runtime = {
public: {
siteBaseDomain: String(
diff --git a/apps/shared/platform/runtime.ts b/apps/shared/platform/runtime.ts
index 782d866e..82da465f 100644
--- a/apps/shared/platform/runtime.ts
+++ b/apps/shared/platform/runtime.ts
@@ -1,3 +1,4 @@
+import { SubscriptionError } from '../../../packages/platform/src/subscriptions.ts'
import { DomainError } from '../../../packages/platform/src/domains.ts'
import { StorageConnectionError } from '@chronoframe/storage/connection-probe'
import {
@@ -79,6 +80,12 @@ export function definePlatformHandler<T>(
try {
return await handler(event)
} catch (error) {
+ if (error instanceof SubscriptionError)
+ throw createError({
+ statusCode: error.statusCode,
+ statusMessage: 'Subscription request could not be completed',
+ data: { code: error.code },
+ })
if (error instanceof DomainError) {
const allowed = [
'domain_invalid',
diff --git a/packages/platform/migrations/0017_subscriptions.sql b/packages/platform/migrations/0017_subscriptions.sql
new file mode 100644
index 00000000..15d28b9a
--- /dev/null
+++ b/packages/platform/migrations/0017_subscriptions.sql
@@ -0,0 +1,22 @@
+ALTER TABLE platform_plans ADD COLUMN currency TEXT NOT NULL DEFAULT 'USD';
+ALTER TABLE platform_plans ADD COLUMN monthly_price INTEGER CHECK(monthly_price IS NULL OR monthly_price>=0);
+ALTER TABLE platform_plans ADD COLUMN quarterly_price INTEGER CHECK(quarterly_price IS NULL OR quarterly_price>=0);
+ALTER TABLE platform_plans ADD COLUMN listed INTEGER NOT NULL DEFAULT 1 CHECK(listed IN(0,1));
+ALTER TABLE platform_plans ADD COLUMN description TEXT NOT NULL DEFAULT '';
+ALTER TABLE platform_plans ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0;
+UPDATE platform_plans SET monthly_price=0,quarterly_price=0 WHERE id='free';
+CREATE TABLE platform_billing_settings(id INTEGER PRIMARY KEY CHECK(id=1),new_plan_id TEXT NOT NULL REFERENCES platform_plans(id),expiry_plan_id TEXT NOT NULL REFERENCES platform_plans(id),revision INTEGER NOT NULL DEFAULT 1);
+INSERT INTO platform_billing_settings(id,new_plan_id,expiry_plan_id) VALUES(1,'free','free');
+ALTER TABLE platform_workspace_plans ADD COLUMN starts_at INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE platform_workspace_plans ADD COLUMN expires_at INTEGER;
+ALTER TABLE platform_workspace_plans ADD COLUMN source TEXT NOT NULL DEFAULT 'manual';
+ALTER TABLE platform_workspace_plans ADD COLUMN billing_interval INTEGER CHECK(billing_interval IS NULL OR billing_interval IN(1,3));
+UPDATE platform_workspace_plans SET starts_at=COALESCE((SELECT created_at FROM platform_workspaces WHERE id=workspace_id),0);
+INSERT OR IGNORE INTO platform_workspace_plans(workspace_id,plan_id,starts_at,source) SELECT id,'free',created_at,'default' FROM platform_workspaces;
+CREATE INDEX platform_subscription_expiry ON platform_workspace_plans(expires_at) WHERE expires_at IS NOT NULL;
+CREATE TABLE platform_subscription_events(id TEXT PRIMARY KEY,workspace_id INTEGER NOT NULL REFERENCES platform_workspaces(id),actor_id INTEGER REFERENCES platform_users(id),kind TEXT NOT NULL,before_json TEXT NOT NULL,after_json TEXT NOT NULL,created_at INTEGER NOT NULL);
+CREATE INDEX platform_subscription_events_workspace ON platform_subscription_events(workspace_id,created_at);
+CREATE TABLE platform_activation_codes(id TEXT PRIMARY KEY,code_hash TEXT NOT NULL UNIQUE,display TEXT NOT NULL,batch_id TEXT NOT NULL,plan_id TEXT NOT NULL REFERENCES platform_plans(id),duration_unit TEXT NOT NULL CHECK(duration_unit IN('permanent','days','months')),duration_value INTEGER,redeem_until INTEGER,max_uses INTEGER CHECK(max_uses IS NULL OR max_uses>0),uses INTEGER NOT NULL DEFAULT 0,enabled INTEGER NOT NULL DEFAULT 1 CHECK(enabled IN(0,1)),revision INTEGER NOT NULL DEFAULT 1,created_at INTEGER NOT NULL,created_by INTEGER NOT NULL REFERENCES platform_users(id));
+CREATE INDEX platform_activation_batch ON platform_activation_codes(batch_id);
+CREATE TABLE platform_activation_redemptions(claim_id TEXT NOT NULL UNIQUE,code_id TEXT NOT NULL REFERENCES platform_activation_codes(id),user_id INTEGER NOT NULL REFERENCES platform_users(id),workspace_id INTEGER NOT NULL REFERENCES platform_workspaces(id),request_id TEXT NOT NULL,receipt_json TEXT NOT NULL,created_at INTEGER NOT NULL,PRIMARY KEY(code_id,user_id),UNIQUE(user_id,request_id));
+CREATE TABLE platform_activation_attempts(user_id INTEGER NOT NULL,window_start INTEGER NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(user_id,window_start));
diff --git a/packages/platform/src/activation.ts b/packages/platform/src/activation.ts
new file mode 100644
index 00000000..4edc0b13
--- /dev/null
+++ b/packages/platform/src/activation.ts
@@ -0,0 +1,283 @@
+import type { PlatformD1 } from './index.ts'
+import {
+ duration,
+ durationEnd,
+ extendDurationEnd,
+ resolveSubscription,
+ subscriptionInvalidation,
+ SubscriptionError,
+ type Duration,
+} from './subscriptions.ts'
+function invalid(): never {
+ throw new SubscriptionError(400, 'invalid_activation_code')
+}
+const uuid = (v: unknown) =>
+ typeof v === 'string' &&
+ /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(v)
+export async function activationHash(value: unknown) {
+ if (typeof value !== 'string' || value.length > 128) invalid()
+ const code = value.trim().toUpperCase().replace(/[-\s]/g, '')
+ if (!/^CF[0-9A-F]{32}$/.test(code)) invalid()
+ const hash = await crypto.subtle.digest(
+ 'SHA-256',
+ new TextEncoder().encode(code),
+ )
+ return [...new Uint8Array(hash)]
+ .map((n) => n.toString(16).padStart(2, '0'))
+ .join('')
+}
+/** Raw codes are returned only to the generating operator; only digests are stored. */
+export async function generateActivationCodes(
+ input: {
+ count: unknown
+ planId: unknown
+ duration: unknown
+ redeemUntil?: unknown
+ maxUses?: unknown
+ },
+ actor: number,
+ now = Date.now(),
+) {
+ if (
+ !Number.isSafeInteger(input.count) ||
+ Number(input.count) < 1 ||
+ Number(input.count) > 500 ||
+ typeof input.planId !== 'string'
+ )
+ throw new SubscriptionError(400, 'invalid_code_batch')
+ const term = duration(input.duration),
+ until = input.redeemUntil ?? null,
+ max = input.maxUses ?? null
+ if (
+ (until !== null &&
+ (!Number.isSafeInteger(until) || Number(until) <= now)) ||
+ (max !== null &&
+ (!Number.isSafeInteger(max) ||
+ Number(max) < 1 ||
+ Number(max) > 100000000))
+ )
+ throw new SubscriptionError(400, 'invalid_code_batch')
+ const batchId = crypto.randomUUID(),
+ codes = []
+ for (let i = 0; i < Number(input.count); i++) {
+ const bytes = crypto.getRandomValues(new Uint8Array(16)),
+ hex = [...bytes]
+ .map((n) => n.toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase(),
+ raw = 'CF-' + hex.match(/.{4}/g)!.join('-')
+ codes.push({
+ id: crypto.randomUUID(),
+ code: raw,
+ hash: await activationHash(raw),
+ display: 'CF-…-' + hex.slice(-4),
+ batchId,
+ planId: input.planId,
+ duration: term,
+ redeemUntil: until as number | null,
+ maxUses: max as number | null,
+ createdAt: now,
+ createdBy: actor,
+ })
+ }
+ return { batchId, codes }
+}
+async function permitted(db: PlatformD1, userId: number, workspaceId: number) {
+ const member = await db
+ .prepare(
+ "SELECT 1 FROM platform_memberships m JOIN platform_users u ON u.id=m.user_id LEFT JOIN platform_account_controls c ON c.user_id=u.id WHERE m.user_id=? AND m.workspace_id=? AND m.role='admin' AND u.email_verified=1 AND COALESCE(c.suspended,0)=0",
+ )
+ .bind(userId, workspaceId)
+ .first()
+ if (!member) throw new SubscriptionError(403, 'workspace_admin_required')
+}
+async function attempt(db: PlatformD1, userId: number, now: number) {
+ const window = Math.floor(now / 900000) * 900000
+ const row = await db
+ .prepare(
+ 'INSERT INTO platform_activation_attempts(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) throw new SubscriptionError(429, 'activation_rate_limit')
+}
+interface CodeRow {
+ id: string
+ plan_id: string
+ name: string
+ duration_unit: Duration['unit']
+ duration_value: number | null
+ revision: number
+}
+async function available(
+ db: PlatformD1,
+ hash: string,
+ userId: number,
+ now: number,
+) {
+ return db
+ .prepare(
+ `SELECT c.id,c.plan_id,p.name,c.duration_unit,c.duration_value,c.revision FROM platform_activation_codes c JOIN platform_plans p ON p.id=c.plan_id WHERE c.code_hash=? AND c.enabled=1 AND p.active=1 AND (c.redeem_until IS NULL OR c.redeem_until>?) AND (c.max_uses IS NULL OR c.uses<c.max_uses) AND NOT EXISTS(SELECT 1 FROM platform_activation_redemptions r WHERE r.code_id=c.id AND r.user_id=?)`,
+ )
+ .bind(hash, now, userId)
+ .first<CodeRow>()
+}
+function effect(
+ code: CodeRow,
+ current: Awaited<ReturnType<typeof resolveSubscription>>,
+ now: number,
+) {
+ const term: Duration = {
+ unit: code.duration_unit,
+ ...(code.duration_value === null ? {} : { value: code.duration_value }),
+ }
+ const same =
+ current.id === code.plan_id &&
+ !['default', 'expired_default'].includes(current.subscription.source)
+ if (same && current.subscription.expiresAt === null)
+ throw new SubscriptionError(409, 'permanent_plan_active')
+ return {
+ planId: code.plan_id,
+ planName: code.name,
+ mode: same ? 'extend' : 'replace',
+ startsAt: same ? current.subscription.startsAt : now,
+ expiresAt: same
+ ? extendDurationEnd(
+ current.subscription.startsAt,
+ Math.max(now, current.subscription.expiresAt!),
+ term,
+ )
+ : durationEnd(now, term),
+ source: 'activation',
+ interval: null,
+ }
+}
+export async function previewActivation(
+ db: PlatformD1,
+ userId: number,
+ workspaceId: number,
+ value: unknown,
+ now = Date.now(),
+) {
+ await permitted(db, userId, workspaceId)
+ await attempt(db, userId, now)
+ const hash = await activationHash(value),
+ code = await available(db, hash, userId, now)
+ if (!code) invalid()
+ const current = await resolveSubscription(db, workspaceId, now)
+ return {
+ current: {
+ planId: current.id,
+ planName: current.name,
+ expiresAt: current.subscription.expiresAt,
+ },
+ grant: effect(code, current, now),
+ revision: current.assignment_revision,
+ }
+}
+export async function redeemActivation(
+ db: PlatformD1,
+ userId: number,
+ workspaceId: number,
+ input: { code: unknown; requestId: unknown; revision: unknown },
+ now = Date.now(),
+) {
+ await permitted(db, userId, workspaceId)
+ if (
+ !uuid(input.requestId) ||
+ !Number.isSafeInteger(input.revision) ||
+ Number(input.revision) < 0
+ )
+ throw new SubscriptionError(400, 'invalid_redemption')
+ const previous = await db
+ .prepare(
+ 'SELECT workspace_id,receipt_json FROM platform_activation_redemptions WHERE user_id=? AND request_id=?',
+ )
+ .bind(userId, input.requestId as string)
+ .first<{ workspace_id: number; receipt_json: string }>()
+ if (previous) {
+ if (previous.workspace_id !== workspaceId)
+ throw new SubscriptionError(409, 'redemption_changed')
+ return JSON.parse(previous.receipt_json)
+ }
+ await attempt(db, userId, now)
+ const hash = await activationHash(input.code),
+ code = await available(db, hash, userId, now)
+ if (!code) invalid()
+ const current = await resolveSubscription(db, workspaceId, now)
+ if (current.assignment_revision !== input.revision)
+ throw new SubscriptionError(409, 'subscription_changed')
+ const grant = effect(code, current, now),
+ eventId = crypto.randomUUID(),
+ receipt = {
+ requestId: input.requestId,
+ workspaceId,
+ grant,
+ redeemedAt: now,
+ }
+ const guard = `EXISTS(SELECT 1 FROM platform_activation_codes c JOIN platform_plans p ON p.id=c.plan_id WHERE c.id=? AND c.revision=? AND c.enabled=1 AND p.active=1 AND (c.redeem_until IS NULL OR c.redeem_until>?) AND (c.max_uses IS NULL OR c.uses<c.max_uses)) AND COALESCE((SELECT revision FROM platform_workspace_plans WHERE workspace_id=?),0)=? AND EXISTS(SELECT 1 FROM platform_memberships m JOIN platform_users u ON u.id=m.user_id LEFT JOIN platform_account_controls ac ON ac.user_id=u.id WHERE m.workspace_id=? AND m.user_id=? AND m.role='admin' AND u.email_verified=1 AND COALESCE(ac.suspended,0)=0)`
+ try {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO platform_activation_redemptions(claim_id,code_id,user_id,workspace_id,request_id,receipt_json,created_at) SELECT ?,?,?,?,?,?,? WHERE ${guard}`,
+ )
+ .bind(
+ eventId,
+ code.id,
+ userId,
+ workspaceId,
+ input.requestId as string,
+ JSON.stringify(receipt),
+ now,
+ code.id,
+ code.revision,
+ now,
+ workspaceId,
+ Number(input.revision),
+ workspaceId,
+ userId,
+ ),
+ db
+ .prepare(
+ 'UPDATE platform_activation_codes SET uses=uses+1 WHERE id=? AND EXISTS(SELECT 1 FROM platform_activation_redemptions WHERE claim_id=?)',
+ )
+ .bind(code.id, eventId),
+ db
+ .prepare(
+ `INSERT INTO platform_workspace_plans(workspace_id,plan_id,starts_at,expires_at,source,billing_interval) SELECT ?,?,?,?,'activation',NULL WHERE EXISTS(SELECT 1 FROM platform_activation_redemptions WHERE claim_id=?) ON CONFLICT(workspace_id) DO UPDATE SET plan_id=excluded.plan_id,starts_at=excluded.starts_at,expires_at=excluded.expires_at,source='activation',billing_interval=NULL,revision=platform_workspace_plans.revision+1`,
+ )
+ .bind(
+ workspaceId,
+ grant.planId,
+ grant.startsAt,
+ grant.expiresAt,
+ eventId,
+ ),
+ db
+ .prepare(
+ "INSERT INTO platform_subscription_events(id,workspace_id,actor_id,kind,before_json,after_json,created_at) SELECT ?,?,?,'redeemed',?,?,? WHERE EXISTS(SELECT 1 FROM platform_activation_redemptions WHERE claim_id=?)",
+ )
+ .bind(
+ eventId,
+ workspaceId,
+ userId,
+ JSON.stringify(current.subscription),
+ JSON.stringify(grant),
+ now,
+ eventId,
+ ),
+ ...subscriptionInvalidation(db, workspaceId, eventId),
+ ])
+ } catch (error) {
+ if (!/UNIQUE constraint/.test(String(error))) throw error
+ }
+ const result = await db
+ .prepare(
+ 'SELECT workspace_id,receipt_json FROM platform_activation_redemptions WHERE user_id=? AND request_id=?',
+ )
+ .bind(userId, input.requestId as string)
+ .first<{ workspace_id: number; receipt_json: string }>()
+ if (!result || result.workspace_id !== workspaceId) invalid()
+ return JSON.parse(result.receipt_json)
+}
diff --git a/packages/platform/src/billing.ts b/packages/platform/src/billing.ts
new file mode 100644
index 00000000..6530812a
--- /dev/null
+++ b/packages/platform/src/billing.ts
@@ -0,0 +1,166 @@
+import type { PlatformD1 } from './index.ts'
+import {
+ allRows,
+ resolveSubscription,
+ SubscriptionError,
+} from './subscriptions.ts'
+import { workspaceEntitlements, validatePolicy } from './entitlements.ts'
+export const CURRENCIES = [
+ 'USD',
+ 'CNY',
+ 'HKD',
+ 'EUR',
+ 'GBP',
+ 'AUD',
+ 'CAD',
+ 'SGD',
+] as const
+export function validatePricing(value: unknown) {
+ const p = value as Record<string, unknown>
+ if (
+ !p ||
+ !CURRENCIES.includes(p.currency as (typeof CURRENCIES)[number]) ||
+ typeof p.listed !== 'boolean' ||
+ typeof p.description !== 'string' ||
+ p.description.length > 500 ||
+ !Number.isSafeInteger(p.sortOrder) ||
+ Number(p.sortOrder) < -10000 ||
+ Number(p.sortOrder) > 10000
+ )
+ throw new SubscriptionError(400, 'invalid_pricing')
+ for (const key of ['monthlyPrice', 'quarterlyPrice'])
+ if (
+ p[key] !== null &&
+ (!Number.isSafeInteger(p[key]) ||
+ Number(p[key]) < 0 ||
+ Number(p[key]) > 10000000000)
+ )
+ throw new SubscriptionError(400, 'invalid_pricing')
+ return {
+ currency: p.currency as string,
+ monthlyPrice: p.monthlyPrice as number | null,
+ quarterlyPrice: p.quarterlyPrice as number | null,
+ listed: p.listed,
+ description: p.description,
+ sortOrder: Number(p.sortOrder),
+ }
+}
+export async function pricingCatalog(db: PlatformD1) {
+ const rows = await allRows<{
+ id: string
+ name: string
+ policy_json: string
+ currency: string
+ monthly_price: number | null
+ quarterly_price: number | null
+ description: string
+ }>(
+ db.prepare(
+ 'SELECT id,name,policy_json,currency,monthly_price,quarterly_price,description FROM platform_plans WHERE active=1 AND listed=1 ORDER BY sort_order,id',
+ ),
+ )
+ const settings = await db
+ .prepare('SELECT new_plan_id FROM platform_billing_settings WHERE id=1')
+ .first<{ new_plan_id: string }>()
+ return {
+ paymentAvailable: false,
+ newPlanId: settings?.new_plan_id ?? 'free',
+ plans: rows.map(
+ ({ policy_json, monthly_price, quarterly_price, ...row }) => ({
+ ...row,
+ monthlyPrice: monthly_price,
+ quarterlyPrice: quarterly_price,
+ policy: validatePolicy(JSON.parse(policy_json)),
+ }),
+ ),
+ }
+}
+export async function billingWorkspaces(db: PlatformD1, userId: number) {
+ return allRows<{ id: number; name: string; role: 'admin' | 'member' }>(
+ db
+ .prepare(
+ "SELECT w.id,w.name,m.role FROM platform_workspaces w JOIN platform_memberships m ON m.workspace_id=w.id WHERE m.user_id=? AND m.role IN('admin','member') ORDER BY w.id",
+ )
+ .bind(userId),
+ )
+}
+export async function workspaceBilling(
+ db: PlatformD1,
+ userId: number,
+ workspaceId: number,
+ now = Date.now(),
+) {
+ const membership = await db
+ .prepare(
+ "SELECT w.id,w.name,m.role FROM platform_workspaces w JOIN platform_memberships m ON m.workspace_id=w.id WHERE w.id=? AND m.user_id=? AND m.role IN('admin','member')",
+ )
+ .bind(workspaceId, userId)
+ .first<{ id: number; name: string; role: string }>()
+ if (!membership) throw new SubscriptionError(404, 'workspace_unavailable')
+ const plan = await workspaceEntitlements(db, workspaceId, 'platform', now),
+ byos = await workspaceEntitlements(db, workspaceId, 'byos', now),
+ current = await resolveSubscription(db, workspaceId, now),
+ sites = `SELECT id FROM platform_sites WHERE workspace_id=?`
+ const usage = await db
+ .prepare(`SELECT (SELECT COUNT(*) FROM platform_sites WHERE workspace_id=?) AS sites,
+ (SELECT COUNT(*) FROM platform_custom_domains WHERE site_id IN(${sites}) AND state<>'deleted') AS customDomains,
+ (SELECT COUNT(*) FROM cloud_storage_connections WHERE site_id IN(${sites}) AND pool_id IS NULL) AS byos,
+ (SELECT COUNT(*) FROM cloud_photos WHERE site_id IN(${sites}) AND deleted=0) AS photographs,
+ (SELECT COUNT(*) FROM cloud_uploads WHERE site_id IN(${sites}) AND state='pending' AND expires_at>?) AS pending,
+ COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id IN(${sites}) AND created_at>=? AND created_at<?),0)+COALESCE((SELECT SUM(expected_bytes+expected_video_bytes) FROM cloud_uploads WHERE site_id IN(${sites}) AND state='pending' AND expires_at>?),0) AS monthlyBytes,
+ COALESCE((SELECT SUM(u.expected_bytes+u.expected_video_bytes) FROM cloud_uploads u JOIN cloud_photos p ON p.site_id=u.site_id AND p.id=u.photo_id JOIN cloud_storage_connections c ON c.site_id=u.site_id AND c.id=u.connection_id WHERE u.site_id IN(${sites}) AND u.state='completed' AND p.deleted=0 AND c.pool_id IS NOT NULL),0)
+ +COALESCE((SELECT SUM(a.bytes) FROM cloud_media_assets a JOIN cloud_photos p ON p.site_id=a.site_id AND p.id=a.photo_id JOIN cloud_storage_connections c ON c.site_id=a.site_id AND c.id=a.connection_id WHERE a.site_id IN(${sites}) AND p.deleted=0 AND c.pool_id IS NOT NULL),0)
+ +COALESCE((SELECT SUM(reserved_storage_bytes) FROM cloud_uploads WHERE site_id IN(${sites}) AND state='pending' AND expires_at>?),0)
+ +COALESCE((SELECT SUM(reserved_output_bytes) FROM cloud_processing_jobs WHERE site_id IN(${sites}) AND state IN('queued','running','retry_wait')),0) AS storageBytes`)
+ .bind(
+ workspaceId,
+ workspaceId,
+ workspaceId,
+ workspaceId,
+ workspaceId,
+ now,
+ workspaceId,
+ current.quotaPeriod.start,
+ current.quotaPeriod.end,
+ workspaceId,
+ now,
+ workspaceId,
+ workspaceId,
+ workspaceId,
+ now,
+ workspaceId,
+ )
+ .first<Record<string, number>>()
+ const history = await allRows<{
+ kind: string
+ created_at: number
+ after_json: string
+ }>(
+ db
+ .prepare(
+ 'SELECT kind,created_at,after_json FROM platform_subscription_events WHERE workspace_id=? ORDER BY created_at DESC,id DESC LIMIT 10',
+ )
+ .bind(workspaceId),
+ )
+ return {
+ workspace: membership,
+ plan: {
+ id: plan.id,
+ name: plan.name,
+ limits: plan.limits,
+ byosLimits: byos.limits,
+ },
+ subscription: current.subscription,
+ quotaPeriod: current.quotaPeriod,
+ usage: {
+ ...usage,
+ photos: (usage?.photographs ?? 0) + (usage?.pending ?? 0),
+ },
+ history: history.map(({ after_json, ...event }) => ({
+ ...event,
+ grant: JSON.parse(after_json),
+ })),
+ paymentAvailable: false,
+ serverTime: now,
+ }
+}
diff --git a/packages/platform/src/entitlements.ts b/packages/platform/src/entitlements.ts
index e4a69722..5777e237 100644
--- a/packages/platform/src/entitlements.ts
+++ b/packages/platform/src/entitlements.ts
@@ -1,3 +1,4 @@
+import { resolveSubscription } from './subscriptions.ts'
import type { PlatformD1 } from './index.ts'
export const LIMIT_KEYS = [
@@ -137,27 +138,14 @@ export async function workspaceEntitlements(
db: PlatformD1,
workspaceId: number,
storageMode: 'platform' | 'byos' = 'platform',
+ now = Date.now(),
) {
- const row = await db
- .prepare(`SELECT p.id,p.name,p.revision,p.policy_json,w.owner_user_id,
- w.created_at AS created_at,COALESCE(u.email_verified,0) AS email_verified
- FROM platform_workspaces w LEFT JOIN platform_users u ON u.id=w.owner_user_id
- JOIN platform_plans p ON p.id=COALESCE((SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=w.id),'free') WHERE w.id=?`)
- .bind(workspaceId)
- .first<{
- id: string
- name: string
- revision: number
- policy_json: string
- created_at: number
- email_verified: number
- }>()
- if (!row) throw new Error('Workspace plan unavailable')
+ const row = await resolveSubscription(db, workspaceId, now)
const context: PolicyContext = {
storageMode,
workspaceAgeDays: Math.max(
0,
- Math.floor((Date.now() - Number(row.created_at)) / 86400000),
+ Math.floor((now - Number(row.created_at)) / 86400000),
),
emailVerified: !!row.email_verified,
}
@@ -165,6 +153,8 @@ export async function workspaceEntitlements(
id: row.id,
name: row.name,
revision: row.revision,
+ subscription: row.subscription,
+ quotaPeriod: row.quotaPeriod,
limits: evaluatePolicy(
validatePolicy(JSON.parse(row.policy_json)),
context,
@@ -179,7 +169,7 @@ export function workspaceUsageSQL(siteId: number) {
const sites = `SELECT id FROM platform_sites WHERE workspace_id=(SELECT workspace_id FROM platform_sites WHERE id=${siteId})`
return {
photos: `(SELECT COUNT(*) FROM cloud_photos WHERE site_id IN (${sites}) AND deleted=0)+(SELECT COUNT(*) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?)`,
- monthly: `COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id IN (${sites}) AND created_at>?),0)+COALESCE((SELECT SUM(expected_bytes+expected_video_bytes) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?),0)`,
+ monthly: `COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id IN (${sites}) AND created_at>=?),0)+COALESCE((SELECT SUM(expected_bytes+expected_video_bytes) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?),0)`,
storage: `COALESCE((SELECT SUM(u.expected_bytes+u.expected_video_bytes) FROM cloud_uploads u JOIN cloud_photos p ON p.site_id=u.site_id AND p.id=u.photo_id JOIN cloud_storage_connections c ON c.site_id=u.site_id AND c.id=u.connection_id WHERE u.site_id IN (${sites}) AND u.state='completed' AND p.deleted=0 AND c.pool_id IS NOT NULL),0)
+COALESCE((SELECT SUM(a.bytes) FROM cloud_media_assets a JOIN cloud_photos p ON p.site_id=a.site_id AND p.id=a.photo_id JOIN cloud_storage_connections c ON c.site_id=a.site_id AND c.id=a.connection_id WHERE a.site_id IN (${sites}) AND p.deleted=0 AND c.pool_id IS NOT NULL),0)
+COALESCE((SELECT SUM(reserved_storage_bytes) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?),0)
diff --git a/packages/platform/src/provisioning.ts b/packages/platform/src/provisioning.ts
index 669c91bf..05571e1c 100644
--- a/packages/platform/src/provisioning.ts
+++ b/packages/platform/src/provisioning.ts
@@ -1,3 +1,4 @@
+import { ensureDefaultSubscription } from './subscriptions.ts'
import {
parseGalleryPresentation,
type GalleryPresentation,
@@ -112,6 +113,7 @@ export function createD1Provisioning(
.bind(userId, userId)
.first<{ id: number; name: string; role: string }>()
if (!workspace) throw new ProvisioningError(403, 'Workspace unavailable')
+ await ensureDefaultSubscription(db, workspace.id)
return workspace
}
async function get(userId: number, siteId: number) {
diff --git a/packages/platform/src/subscriptions.ts b/packages/platform/src/subscriptions.ts
new file mode 100644
index 00000000..1f49775e
--- /dev/null
+++ b/packages/platform/src/subscriptions.ts
@@ -0,0 +1,222 @@
+import type { PlatformD1, D1Statement } from './index.ts'
+export async function allRows<T>(statement: D1Statement): Promise<T[]> {
+ const result = await (
+ statement as D1Statement & { all<R>(): Promise<{ results: R[] }> }
+ ).all<T>()
+ return result.results
+}
+export type Duration = { unit: 'permanent' | 'days' | 'months'; value?: number }
+export class SubscriptionError extends Error {
+ statusCode: number
+ code: string
+ constructor(statusCode: number, code: string) {
+ super(code)
+ this.statusCode = statusCode
+ this.code = code
+ }
+}
+export function duration(value: unknown): Duration {
+ const d = value as Duration
+ if (
+ !d ||
+ typeof d !== 'object' ||
+ Array.isArray(d) ||
+ !['permanent', 'days', 'months'].includes(d.unit)
+ )
+ throw new SubscriptionError(400, 'invalid_duration')
+ if (d.unit === 'permanent') return { unit: 'permanent' }
+ if (
+ !Number.isSafeInteger(d.value) ||
+ d.value! < 1 ||
+ d.value! > (d.unit === 'days' ? 36500 : 1200)
+ )
+ throw new SubscriptionError(400, 'invalid_duration')
+ return { unit: d.unit, value: d.value }
+}
+/** Add UTC calendar months, clamping the day without overflowing into a later month. */
+export function addMonths(time: number, months: number) {
+ const date = new Date(time),
+ day = date.getUTCDate()
+ date.setUTCDate(1)
+ date.setUTCMonth(date.getUTCMonth() + months)
+ const last = new Date(
+ Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0),
+ ).getUTCDate()
+ date.setUTCDate(Math.min(day, last))
+ return date.getTime()
+}
+export function durationEnd(start: number, d: Duration) {
+ return d.unit === 'permanent'
+ ? null
+ : d.unit === 'days'
+ ? start + d.value! * 86400000
+ : addMonths(start, d.value!)
+}
+/** Continue an existing calendar-month term without losing its original month-end anchor. */
+export function extendDurationEnd(anchor: number, end: number, term: Duration) {
+ if (term.unit !== 'months') return durationEnd(end, term)
+ const a = new Date(anchor),
+ e = new Date(end),
+ months =
+ (e.getUTCFullYear() - a.getUTCFullYear()) * 12 +
+ e.getUTCMonth() -
+ a.getUTCMonth()
+ return months >= 0 && addMonths(anchor, months) === end
+ ? addMonths(anchor, months + term.value!)
+ : addMonths(end, term.value!)
+}
+export function monthlyPeriod(
+ anchor: number,
+ now: number,
+ end: number | null = null,
+) {
+ const a = new Date(anchor),
+ n = new Date(now)
+ let months = Math.max(
+ 0,
+ (n.getUTCFullYear() - a.getUTCFullYear()) * 12 +
+ n.getUTCMonth() -
+ a.getUTCMonth(),
+ )
+ if (addMonths(anchor, months) > now) months--
+ const start = addMonths(anchor, Math.max(0, months))
+ return {
+ start,
+ end: Math.min(addMonths(anchor, Math.max(0, months) + 1), end ?? Infinity),
+ }
+}
+export const EXPIRY_PLAN_SQL =
+ "COALESCE((SELECT p.id FROM platform_billing_settings b JOIN platform_plans p ON p.id=b.expiry_plan_id AND p.active=1 WHERE b.id=1),'free')"
+export const NEW_PLAN_SQL =
+ "COALESCE((SELECT p.id FROM platform_billing_settings b JOIN platform_plans p ON p.id=b.new_plan_id AND p.active=1 WHERE b.id=1),'free')"
+export async function ensureDefaultSubscription(
+ db: PlatformD1,
+ workspaceId: number,
+) {
+ await db
+ .prepare(
+ `INSERT OR IGNORE INTO platform_workspace_plans(workspace_id,plan_id,starts_at,source) SELECT id,${NEW_PLAN_SQL},created_at,'default' FROM platform_workspaces WHERE id=?`,
+ )
+ .bind(workspaceId)
+ .run()
+}
+export async function resolveSubscription(
+ db: PlatformD1,
+ workspaceId: number,
+ now = Date.now(),
+) {
+ const row = await db
+ .prepare(`SELECT p.id,p.name,p.revision,p.policy_json,p.currency,p.monthly_price,p.quarterly_price,w.created_at,w.owner_user_id,COALESCE(u.email_verified,0) AS email_verified,
+ COALESCE(wp.revision,0) AS assignment_revision,CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.source ELSE 'default' END AS source,
+ CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.starts_at ELSE COALESCE(wp.expires_at,wp.starts_at,w.created_at) END AS starts_at,
+ CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN wp.expires_at ELSE NULL END AS expires_at,wp.billing_interval,
+ CASE WHEN wp.expires_at<=? OR assigned.active=0 OR wp.source='expired_default' THEN 1 ELSE 0 END AS expired
+ FROM platform_workspaces w LEFT JOIN platform_users u ON u.id=w.owner_user_id LEFT JOIN platform_workspace_plans wp ON wp.workspace_id=w.id LEFT JOIN platform_plans assigned ON assigned.id=wp.plan_id
+ JOIN platform_plans p ON p.id=CASE WHEN assigned.active=1 AND wp.source<>'expired_default' AND (wp.expires_at IS NULL OR wp.expires_at>?) THEN assigned.id ELSE ${EXPIRY_PLAN_SQL} END WHERE w.id=?`)
+ .bind(now, now, now, now, now, workspaceId)
+ .first<{
+ id: string
+ name: string
+ revision: number
+ policy_json: string
+ currency: string
+ monthly_price: number | null
+ quarterly_price: number | null
+ created_at: number
+ owner_user_id: number
+ email_verified: number
+ assignment_revision: number
+ source: string
+ starts_at: number
+ expires_at: number | null
+ billing_interval: 1 | 3 | null
+ expired: number
+ }>()
+ if (!row) throw new SubscriptionError(404, 'workspace_unavailable')
+ const subscription = {
+ source: row.source,
+ startsAt: row.starts_at,
+ expiresAt: row.expires_at,
+ interval: row.expired ? null : row.billing_interval,
+ revision: row.assignment_revision,
+ }
+ return {
+ ...row,
+ subscription,
+ quotaPeriod: monthlyPeriod(row.starts_at, now, row.expires_at),
+ }
+}
+/** Execute alongside the successful grant/event write, so stale updates cannot invalidate newer work. */
+export function subscriptionInvalidation(
+ db: PlatformD1,
+ workspaceId: number,
+ eventId: string,
+): D1Statement[] {
+ return [
+ db
+ .prepare(
+ 'UPDATE platform_policy_epoch SET revision=revision+1 WHERE id=1 AND EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)',
+ )
+ .bind(eventId),
+ db
+ .prepare(
+ "UPDATE platform_custom_domains SET next_check_at=0 WHERE state<>'deleted' AND site_id IN(SELECT id FROM platform_sites WHERE workspace_id=?) AND EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)",
+ )
+ .bind(workspaceId, eventId),
+ ]
+}
+/** Reads enforce expiry immediately; this bounded job persists transitions and queues provider cleanup. */
+export async function reconcileSubscriptions(
+ db: PlatformD1,
+ now = Date.now(),
+ limit = 5,
+) {
+ const rows = await allRows<{
+ workspace_id: number
+ plan_id: string
+ revision: number
+ starts_at: number
+ expires_at: number | null
+ }>(
+ db
+ .prepare(
+ 'SELECT wp.* FROM platform_workspace_plans wp JOIN platform_plans p ON p.id=wp.plan_id WHERE wp.expires_at<=? OR p.active=0 ORDER BY COALESCE(wp.expires_at,0),wp.workspace_id LIMIT ?',
+ )
+ .bind(now, limit),
+ )
+ let changed = 0
+ for (const row of rows) {
+ const id = crypto.randomUUID(),
+ after = {
+ planId: (await resolveSubscription(db, row.workspace_id, now)).id,
+ }
+ const results = await db.batch([
+ db
+ .prepare(
+ "INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,'expired',?,?,? WHERE EXISTS(SELECT 1 FROM platform_workspace_plans wp JOIN platform_plans p ON p.id=wp.plan_id WHERE wp.workspace_id=? AND wp.revision=? AND (wp.expires_at<=? OR p.active=0))",
+ )
+ .bind(
+ id,
+ row.workspace_id,
+ JSON.stringify(row),
+ JSON.stringify(after),
+ now,
+ row.workspace_id,
+ row.revision,
+ now,
+ ),
+ db
+ .prepare(
+ `UPDATE platform_workspace_plans SET plan_id=${EXPIRY_PLAN_SQL},starts_at=COALESCE(expires_at,starts_at),expires_at=NULL,source='expired_default',billing_interval=NULL,revision=revision+1 WHERE workspace_id=? AND revision=? AND EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)`,
+ )
+ .bind(row.workspace_id, row.revision, id),
+ ...subscriptionInvalidation(db, row.workspace_id, id),
+ ])
+ changed += results[0]?.meta.changes ?? 0
+ }
+ await db
+ .prepare('DELETE FROM platform_activation_attempts WHERE window_start<?')
+ .bind(now - 86400000)
+ .run()
+ return { changed }
+}
diff --git a/scripts/domain-deployment.mjs b/scripts/domain-deployment.mjs
index b140892c..cbd4a071 100644
--- a/scripts/domain-deployment.mjs
+++ b/scripts/domain-deployment.mjs
@@ -71,11 +71,7 @@ export function configureDomainDeployment(
delete config.routes
delete config.route
delete config.triggers
- if (
- environment === 'production' &&
- entry === 'cloud' &&
- vars.NUXT_PLATFORM_DOMAIN_ENABLED === 'true'
- )
+ if (environment === 'production' && entry === 'cloud')
config.triggers = { crons: ['* * * * *'] }
return config
}
diff --git a/tests/cloud-domains.test.ts b/tests/cloud-domains.test.ts
index dd8e276a..02133aa1 100644
--- a/tests/cloud-domains.test.ts
+++ b/tests/cloud-domains.test.ts
@@ -745,6 +745,10 @@ test('Deployment isolates named Previews and leaves customer route ownership wit
PLATFORM_DOMAIN_ZONE_ID: 'a'.repeat(32),
PLATFORM_DOMAIN_PROVIDER_TOKEN: 'fake-provider-token-'.repeat(2),
})
+ assert.deepEqual(
+ configureDomainDeployment({}, 'cloud', 'production', {}).triggers,
+ { crons: ['* * * * *'] },
+ )
assert.equal('routes' in config, false)
assert.deepEqual(config.triggers, { crons: ['* * * * *'] })
assert.equal(
diff --git a/tests/platform-provisioning.test.ts b/tests/platform-provisioning.test.ts
index 8c379156..fca6e530 100644
--- a/tests/platform-provisioning.test.ts
+++ b/tests/platform-provisioning.test.ts
@@ -89,6 +89,7 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc
'0014_entitlements.sql',
'0015_lifecycle.sql',
'0016_gallery_presentation.sql',
+ '0017_subscriptions.sql',
])
await migrate(migration)
await db
diff --git a/tests/platform-subscriptions.test.ts b/tests/platform-subscriptions.test.ts
new file mode 100644
index 00000000..83e26c3a
--- /dev/null
+++ b/tests/platform-subscriptions.test.ts
@@ -0,0 +1,488 @@
+import { createDomainManager } from '../packages/platform/src/domains.ts'
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readFile, readdir } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import {
+ createD1Provisioning,
+ createD1Directory,
+} from '../packages/platform/src/index.ts'
+import {
+ workspaceEntitlements,
+ FREE_LIMITS,
+} from '../packages/platform/src/entitlements.ts'
+import {
+ addMonths,
+ extendDurationEnd,
+ monthlyPeriod,
+ resolveSubscription,
+ reconcileSubscriptions,
+} from '../packages/platform/src/subscriptions.ts'
+import {
+ generateActivationCodes,
+ previewActivation,
+ redeemActivation,
+} from '../packages/platform/src/activation.ts'
+import {
+ pricingCatalog,
+ workspaceBilling,
+} from '../packages/platform/src/billing.ts'
+const require = createRequire(import.meta.url),
+ { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+ )('miniflare')
+test('Calendar subscription periods clamp UTC month ends without multiplying stock quotas', () => {
+ const jan = Date.UTC(2024, 0, 31, 12)
+ assert.equal(addMonths(jan, 1), Date.UTC(2024, 1, 29, 12))
+ assert.equal(addMonths(jan, 3), Date.UTC(2024, 3, 30, 12))
+ assert.equal(
+ extendDurationEnd(jan, addMonths(jan, 1), { unit: 'months', value: 1 }),
+ Date.UTC(2024, 2, 31, 12),
+ )
+ assert.deepEqual(monthlyPeriod(jan, Date.UTC(2024, 2, 15)), {
+ start: Date.UTC(2024, 1, 29, 12),
+ end: Date.UTC(2024, 2, 31, 12),
+ })
+})
+test('Real D1 defaults, live expiry, activation races/idempotency and workspace usage share one entitlement source', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ script: 'export default {fetch(){return new Response("ok")}}',
+ compatibilityDate: '2026-10-26',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ for (const file of (await readdir('packages/platform/migrations'))
+ .filter((f) => f.endsWith('.sql'))
+ .sort())
+ for (const sql of (
+ await readFile('packages/platform/migrations/' + file, 'utf8')
+ )
+ .replace(/^--.*$/gm, '')
+ .split(';')
+ .map((s) => s.trim())
+ .filter(Boolean))
+ await db.prepare(sql).run()
+ const now = Date.now()
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,email_verified,created_at,updated_at) VALUES(1,'[email protected]',1,?,?),(2,'[email protected]',1,?,?),(3,'[email protected]',1,?,?)",
+ )
+ .bind(now, now, now, now, now, now)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_plans(id,name,policy_json,monthly_price,quarterly_price) VALUES('pro','Pro',?,900,2400),('starter','Starter',?,0,0)",
+ )
+ .bind(
+ JSON.stringify({
+ limits: { ...FREE_LIMITS, sites: 10, customDomains: 3 },
+ rules: [],
+ }),
+ JSON.stringify({ limits: { ...FREE_LIMITS, sites: 2 }, rules: [] }),
+ )
+ .run()
+ const store = createD1Provisioning(db),
+ one = await store.defaultWorkspace(1)
+ assert.equal((await workspaceEntitlements(db, one.id)).id, 'free')
+ await db
+ .prepare(
+ "UPDATE platform_billing_settings SET new_plan_id='pro',expiry_plan_id='starter' WHERE id=1",
+ )
+ .run()
+ const two = await store.defaultWorkspace(2),
+ three = await store.defaultWorkspace(3)
+ assert.equal((await workspaceEntitlements(db, two.id)).id, 'pro')
+ assert.equal(
+ (await workspaceEntitlements(db, one.id)).id,
+ 'free',
+ 'changing signup default does not change existing grants',
+ )
+ await db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='pro',expires_at=?,source='manual' WHERE workspace_id=?",
+ )
+ .bind(now - 1, one.id)
+ .run()
+ assert.equal(
+ (await workspaceEntitlements(db, one.id)).id,
+ 'starter',
+ 'live reads expire before scheduler runs',
+ )
+ await reconcileSubscriptions(db, now)
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=?',
+ )
+ .bind(one.id)
+ .first()
+ ).plan_id,
+ 'starter',
+ )
+ await db
+ .prepare(
+ "UPDATE platform_billing_settings SET expiry_plan_id='free' WHERE id=1",
+ )
+ .run()
+ assert.equal(
+ (await workspaceEntitlements(db, one.id)).id,
+ 'free',
+ 'persisted expiry followers honor later default changes',
+ )
+ await db
+ .prepare(
+ "UPDATE platform_billing_settings SET expiry_plan_id='starter' WHERE id=1",
+ )
+ .run()
+ const catalog = await pricingCatalog(db)
+ assert.equal(catalog.paymentAvailable, false)
+ assert.equal(
+ catalog.plans.find((p) => p.id === 'pro')!.quarterlyPrice,
+ 2400,
+ )
+ async function code(maxUses: number | null = 1, planId = 'pro') {
+ const batch = await generateActivationCodes(
+ { count: 1, planId, duration: { unit: 'months', value: 1 }, maxUses },
+ 1,
+ now,
+ )
+ const c = batch.codes[0]!
+ await db
+ .prepare(
+ 'INSERT INTO platform_activation_codes(id,code_hash,display,batch_id,plan_id,duration_unit,duration_value,redeem_until,max_uses,created_at,created_by) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
+ )
+ .bind(
+ c.id,
+ c.hash,
+ c.display,
+ c.batchId,
+ c.planId,
+ c.duration.unit,
+ c.duration.value ?? null,
+ c.redeemUntil,
+ c.maxUses,
+ now,
+ 1,
+ )
+ .run()
+ return c
+ }
+ // Default grants may be replaced by a finite activation grant without being considered a paid permanent grant.
+ const first = await code(),
+ preview = await previewActivation(db, 1, one.id, first.code, now),
+ requestId = crypto.randomUUID()
+ const input = { code: first.code, requestId, revision: preview.revision }
+ const duplicate = await Promise.all([
+ redeemActivation(db, 1, one.id, input, now),
+ redeemActivation(db, 1, one.id, input, now),
+ ])
+ assert.deepEqual(duplicate[0], duplicate[1])
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT uses FROM platform_activation_codes WHERE id=?')
+ .bind(first.id)
+ .first()
+ ).uses,
+ 1,
+ )
+ assert.equal((await workspaceEntitlements(db, one.id)).id, 'pro')
+ await assert.rejects(previewActivation(db, 1, one.id, first.code, now), {
+ code: 'invalid_activation_code',
+ })
+ const extension = await code(null)
+ const extended = await previewActivation(db, 1, one.id, extension.code, now)
+ assert.equal(extended.grant.mode, 'extend')
+ const result = await redeemActivation(
+ db,
+ 1,
+ one.id,
+ {
+ code: extension.code,
+ revision: extended.revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ )
+ assert.equal(result.grant.expiresAt, addMonths(addMonths(now, 1), 1))
+ assert.equal(result.grant.startsAt, now)
+ const shared = await code(1)
+ const a = await previewActivation(db, 2, two.id, shared.code, now),
+ b = await previewActivation(db, 3, three.id, shared.code, now)
+ const race = await Promise.allSettled([
+ redeemActivation(
+ db,
+ 2,
+ two.id,
+ {
+ code: shared.code,
+ revision: a.revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ ),
+ redeemActivation(
+ db,
+ 3,
+ three.id,
+ {
+ code: shared.code,
+ revision: b.revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ ),
+ ])
+ assert.equal(race.filter((r) => r.status === 'fulfilled').length, 1)
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT uses FROM platform_activation_codes WHERE id=?')
+ .bind(shared.id)
+ .first()
+ ).uses,
+ 1,
+ )
+ // No private audit/receipt/grant may survive a failed final event write.
+ const rollback = await code(null)
+ const prior = await resolveSubscription(db, one.id, now)
+ await db
+ .prepare(
+ "CREATE TRIGGER fail_grant_event BEFORE INSERT ON platform_subscription_events BEGIN SELECT RAISE(ABORT,'forced event failure'); END",
+ )
+ .run()
+ await assert.rejects(
+ redeemActivation(
+ db,
+ 1,
+ one.id,
+ {
+ code: rollback.code,
+ revision: prior.assignment_revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ ),
+ )
+ await db.prepare('DROP TRIGGER fail_grant_event').run()
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT uses FROM platform_activation_codes WHERE id=?')
+ .bind(rollback.id)
+ .first()
+ ).uses,
+ 0,
+ )
+ assert.equal(
+ (await resolveSubscription(db, one.id, now)).assignment_revision,
+ prior.assignment_revision,
+ )
+ const unrestricted = await code(null)
+ const snapshots = await Promise.all([
+ resolveSubscription(db, two.id, now),
+ resolveSubscription(db, three.id, now),
+ ])
+ const allUsers = await Promise.all([
+ redeemActivation(
+ db,
+ 2,
+ two.id,
+ {
+ code: unrestricted.code,
+ revision: snapshots[0]!.assignment_revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ ),
+ redeemActivation(
+ db,
+ 3,
+ three.id,
+ {
+ code: unrestricted.code,
+ revision: snapshots[1]!.assignment_revision,
+ requestId: crypto.randomUUID(),
+ },
+ now,
+ ),
+ ])
+ assert.equal(allUsers.length, 2)
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT uses FROM platform_activation_codes WHERE id=?')
+ .bind(unrestricted.id)
+ .first()
+ ).uses,
+ 2,
+ )
+ const deadline = await code(null)
+ await db
+ .prepare('UPDATE platform_activation_codes SET redeem_until=? WHERE id=?')
+ .bind(now, deadline.id)
+ .run()
+ await assert.rejects(previewActivation(db, 1, one.id, deadline.code, now), {
+ code: 'invalid_activation_code',
+ })
+ await db
+ .prepare(
+ "INSERT INTO platform_memberships(user_id,workspace_id,role) VALUES(1,?,'admin')",
+ )
+ .bind(two.id)
+ .run()
+ await assert.rejects(
+ previewActivation(db, 1, two.id, first.code, now),
+ { code: 'invalid_activation_code' },
+ 'one redemption per user across workspaces',
+ )
+ const emptyDefault = await store.create(1, {
+ name: 'Billing gallery',
+ slug: 'billing-gallery',
+ requestId: crypto.randomUUID(),
+ })
+ await db
+ .prepare(
+ "INSERT INTO cloud_uploads(site_id,id,owner_id,photo_id,source_version,connection_id,object_key,expected_bytes,expires_at,state) VALUES(?,'billing-upload',1,'billing-upload','1','ledger-only','test/key',123,?,'completed')",
+ )
+ .bind(emptyDefault.siteId, now + 1000)
+ .run()
+ await db
+ .prepare(
+ 'INSERT INTO cloud_usage_events(site_id,upload_id,bytes,created_at) VALUES(?,?,?,?)',
+ )
+ .bind(emptyDefault.siteId, 'billing-upload', 123, now)
+ .run()
+ const measured = await workspaceBilling(db, 1, one.id, now)
+ assert.equal(
+ measured.usage.monthlyBytes,
+ 123,
+ 'events exactly at the quota start are included',
+ )
+ const inactive = await code(null, 'starter')
+ await db
+ .prepare("UPDATE platform_plans SET active=0 WHERE id='starter'")
+ .run()
+ await assert.rejects(previewActivation(db, 1, one.id, inactive.code, now), {
+ code: 'invalid_activation_code',
+ })
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT uses FROM platform_activation_codes WHERE id=?')
+ .bind(inactive.id)
+ .first()
+ ).uses,
+ 0,
+ )
+ const usage = await workspaceBilling(db, 1, one.id, now)
+ assert.equal(usage.usage.sites, 1)
+ assert.equal(usage.usage.storageBytes, 0)
+ assert.equal(usage.plan.limits.sites, 10)
+ await assert.rejects(workspaceBilling(db, 2, one.id), {
+ code: 'workspace_unavailable',
+ })
+ assert.equal(
+ (await workspaceBilling(db, 1, one.id, addMonths(now, 1))).usage
+ .monthlyBytes,
+ 0,
+ 'monthly usage resets even within a longer term',
+ )
+ await db
+ .prepare(
+ "INSERT INTO platform_custom_domains(hostname,site_id,generation,state,verified_at,provider_id,route_id,provider_attempted,route_attempted,created_at,expires_at,next_check_at) VALUES('paid.example.com',?,'code-billing-domain','active',?,'provider-1','route-1',1,1,?,9999999999999,0)",
+ )
+ .bind(emptyDefault.siteId, now, now)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_domains(hostname,site_id,verified,active,kind) VALUES('paid.example.com',?,1,1,'custom')",
+ )
+ .bind(emptyDefault.siteId)
+ .run()
+ await db
+ .prepare(
+ 'UPDATE platform_workspace_plans SET expires_at=?,revision=revision+1 WHERE workspace_id=?',
+ )
+ .bind(now - 1, one.id)
+ .run()
+ assert.equal(
+ await createD1Directory(db).getPublishedSiteByHost('paid.example.com'),
+ null,
+ 'expired custom-domain rights stop public traffic immediately',
+ )
+ await reconcileSubscriptions(db, now)
+ let billable = true,
+ route = true
+ const controller = createDomainManager(
+ db,
+ {
+ enabled: true,
+ routingReady: true,
+ baseDomain: 'chronoframe.art',
+ cnameTarget: 'cname.chronoframe.art',
+ limit: 20,
+ },
+ {
+ now: () => now,
+ dns: async () => 'ready',
+ id: () => crypto.randomUUID(),
+ provider: {
+ count: async () => (billable ? 1 : 0),
+ find: async () =>
+ billable
+ ? { id: 'provider-1', status: 'active', ssl: 'active' }
+ : null,
+ get: async () =>
+ billable
+ ? { id: 'provider-1', status: 'active', ssl: 'active' }
+ : null,
+ create: async () => {
+ billable = true
+ return { id: 'provider-1', status: 'active', ssl: 'active' }
+ },
+ retry: async () => {},
+ remove: async () => {
+ billable = false
+ },
+ findRoute: async () =>
+ route ? { id: 'route-1', owned: true } : null,
+ createRoute: async () => {
+ route = true
+ return 'route-1'
+ },
+ removeRoute: async () => {
+ route = false
+ },
+ },
+ },
+ )
+ await controller.reconcile('paid.example.com')
+ assert.equal(billable, false)
+ assert.equal(route, false)
+ const quota = (await resolveSubscription(db, one.id, now)).quotaPeriod
+ assert.equal(quota.start, now - 1)
+ const rateWindow = now + 9000000
+ for (let i = 0; i < 20; i++)
+ await assert.rejects(
+ () => previewActivation(db, 1, one.id, 'invalid-code', rateWindow),
+ (error: any) => error.code === 'invalid_activation_code',
+ )
+ await assert.rejects(
+ () => previewActivation(db, 1, one.id, 'invalid-code', rateWindow),
+ (error: any) => error.code === 'activation_rate_limit',
+ )
+ await assert.rejects(
+ () =>
+ previewActivation(db, 1, one.id, 'invalid-code', rateWindow + 900000),
+ (error: any) => error.code === 'invalid_activation_code',
+ )
+ } finally {
+ await mf.dispose()
+ }
+})