Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(cloud): activate registration promotion subscriptions automatically
Timothy Yinfbbbfeb391fd
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vueindex 0cf03e73..03d485f0 100644--- a/apps/cloud/app/pages/account/plan.vue+++ b/apps/cloud/app/pages/account/plan.vue@@ -81,6 +81,12 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value): $t('cloud.billing.noExpiry')}}</p>+ <p+ v-if="data.subscription.source === 'promotion'"+ class="cf-field-hint"+ >+ {{ $t('cloud.billing.signupOffer') }}+ </p><p class="cf-field-hint">{{ $t('cloud.billing.noRenewal') }}</p></div><CloudButtondiff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.jsonindex 5d44005d..e9133d96 100644--- a/apps/cloud/i18n/locales/en.json+++ b/apps/cloud/i18n/locales/en.json@@ -672,7 +672,10 @@"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"+ "connectionCount": "{count} existing storage connections",+ "event_signup_promotion": "Registration promotion activated",+ "event_signup_default": "Registration plan assigned",+ "signupOffer": "Your registration promotion is active until the expiration shown above."}}}diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.jsonindex 8ba85aef..c65c9f4c 100644--- a/apps/cloud/i18n/locales/zh-Hans.json+++ b/apps/cloud/i18n/locales/zh-Hans.json@@ -672,7 +672,10 @@"adminOnly": "仅工作空间管理员可以兑换激活码。","failed": "无法读取或保存订阅信息,请重试。","retry": "重试",- "connectionCount": "已有 {count} 个存储连接"+ "connectionCount": "已有 {count} 个存储连接",+ "event_signup_promotion": "注册活动套餐已开通",+ "event_signup_default": "注册默认套餐已分配",+ "signupOffer": "注册促销权益已生效,有效期见上方到期时间。"}}}diff --git a/apps/cloud/server/utils/account-auth.ts b/apps/cloud/server/utils/account-auth.tsindex f36039db..069012b7 100644--- a/apps/cloud/server/utils/account-auth.ts+++ b/apps/cloud/server/utils/account-auth.ts@@ -1,4 +1,5 @@-import type { PlatformD1 } from '@chronoframe/platform'+import { signupOfferForRegistration } from '../../../../packages/platform/src/subscriptions.ts'+import { createD1Provisioning, type PlatformD1 } from '@chronoframe/platform'import 'reflect-metadata'import { betterAuth, type BetterAuthOptions } from 'better-auth'import { APIError } from 'better-auth/api'@@ -27,6 +28,20 @@ export function accountAuthOptions(return {appName: 'ChronoFrame Cloud',databaseHooks: {+ user: {+ create: {+ before: async (user) => {+ const registeredAt = Date.now()+ const signupOffer = await signupOfferForRegistration(+ database as unknown as PlatformD1,+ registeredAt,+ )+ return {+ data: { ...user, createdAt: new Date(registeredAt), signupOffer },+ }+ },+ },+ },session: {create: {before: async (session) => {@@ -43,6 +58,17 @@ export function accountAuthOptions(control.public_reason ||'Account access has been suspended. Contact support.',})+ const db = database as unknown as PlatformD1+ const initialWorkspace = await db+ .prepare(+ 'SELECT id FROM platform_users WHERE id=? AND email_verified=1 AND signup_offer IS NOT NULL AND NOT EXISTS(SELECT 1 FROM platform_workspaces WHERE owner_user_id=platform_users.id)',+ )+ .bind(Number(session.userId))+ .first()+ if (initialWorkspace)+ await createD1Provisioning(db).defaultWorkspace(+ Number(session.userId),+ )return { data: session }},},@@ -72,6 +98,15 @@ export function accountAuthOptions(},user: {modelName: 'platform_users',+ additionalFields: {+ signupOffer: {+ type: 'string',+ fieldName: 'signup_offer',+ required: false,+ input: false,+ returned: false,+ },+ },fields: {emailVerified: 'email_verified',createdAt: 'created_at',diff --git a/packages/platform/migrations/0019_signup_promotions.sql b/packages/platform/migrations/0019_signup_promotions.sqlnew file mode 100644index 00000000..949aead0--- /dev/null+++ b/packages/platform/migrations/0019_signup_promotions.sql@@ -0,0 +1,16 @@+CREATE TABLE platform_signup_promotions (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ plan_id TEXT NOT NULL REFERENCES platform_plans(id),+ starts_at INTEGER,+ ends_at INTEGER NOT NULL,+ duration_unit TEXT NOT NULL CHECK(duration_unit IN('permanent','days','months')),+ duration_value INTEGER,+ priority INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1 CHECK(enabled IN(0,1)),+ created_at INTEGER NOT NULL,+ revision INTEGER NOT NULL DEFAULT 1,+ CHECK(starts_at IS NULL OR starts_at<ends_at)+);+CREATE INDEX platform_signup_promotions_eligibility ON platform_signup_promotions(enabled,ends_at);+ALTER TABLE platform_users ADD COLUMN signup_offer TEXT;diff --git a/packages/platform/src/subscriptions.ts b/packages/platform/src/subscriptions.tsindex 12b20a28..4d078585 100644--- a/packages/platform/src/subscriptions.ts+++ b/packages/platform/src/subscriptions.ts@@ -89,16 +89,127 @@ 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 function validateSignupPromotion(value: unknown) {+ const p = value as Record<string, unknown>+ if (+ !p ||+ typeof p.name !== 'string' ||+ !p.name.trim() ||+ p.name.trim().length > 120 ||+ typeof p.planId !== 'string' ||+ !p.planId ||+ typeof p.enabled !== 'boolean' ||+ !Number.isSafeInteger(p.endsAt) ||+ Number(p.endsAt) < 0 ||+ (p.startsAt !== null &&+ (!Number.isSafeInteger(p.startsAt) ||+ Number(p.startsAt) < 0 ||+ Number(p.startsAt) >= Number(p.endsAt))) ||+ !Number.isSafeInteger(p.priority) ||+ Math.abs(Number(p.priority)) > 10000+ )+ throw new SubscriptionError(400, 'invalid_signup_promotion')+ return {+ name: p.name.trim(),+ planId: p.planId,+ enabled: p.enabled,+ startsAt: p.startsAt as number | null,+ endsAt: Number(p.endsAt),+ priority: Number(p.priority),+ duration: duration(p.duration),+ }+}+/** Captured before the user insert and persisted with that row, never accepted from signup input. */+export async function signupOfferForRegistration(+ db: PlatformD1,+ registeredAt: number,+) {+ const offer = await db+ .prepare(+ `SELECT p.id,p.name,COALESCE(p.plan_id,${NEW_PLAN_SQL}) AS plan_id,p.duration_unit,p.duration_value,p.revision FROM (SELECT 1) seed LEFT JOIN platform_signup_promotions p ON p.id=(SELECT candidate.id FROM platform_signup_promotions candidate JOIN platform_plans plan ON plan.id=candidate.plan_id AND plan.active=1 WHERE candidate.enabled=1 AND candidate.created_at<=? AND (candidate.starts_at IS NULL OR candidate.starts_at<=?) AND candidate.ends_at>? ORDER BY candidate.priority DESC,candidate.created_at DESC,candidate.id LIMIT 1)`,+ )+ .bind(registeredAt, registeredAt, registeredAt)+ .first<{+ id: string | null+ name: string | null+ plan_id: string+ duration_unit: Duration['unit'] | null+ duration_value: number | null+ revision: number | null+ }>()+ if (!offer) throw new SubscriptionError(503, 'signup_offer_unavailable')+ const term: Duration = offer.id+ ? {+ unit: offer.duration_unit!,+ ...(offer.duration_value === null+ ? {}+ : { value: offer.duration_value }),+ }+ : { unit: 'permanent' }+ return JSON.stringify({+ promotionId: offer.id,+ promotionName: offer.name,+ promotionRevision: offer.revision,+ planId: offer.plan_id,+ startsAt: registeredAt,+ expiresAt: durationEnd(registeredAt, term),+ source: offer.id ? 'promotion' : 'default',+ })+}export async function ensureDefaultSubscription(db: PlatformD1,workspaceId: number,) {- await db+ const owner = 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=?`,+ 'SELECT u.signup_offer FROM platform_workspaces w JOIN platform_users u ON u.id=w.owner_user_id WHERE w.id=?',).bind(workspaceId)- .run()+ .first<{ signup_offer: string | null }>()+ if (owner?.signup_offer) {+ const offer = JSON.parse(owner.signup_offer) as {+ planId: string+ startsAt: number+ expiresAt: number | null+ source: string+ promotionId: string | null+ }+ const id = crypto.randomUUID()+ await db.batch([+ db+ .prepare(+ "INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,?,'null',?,? WHERE NOT EXISTS(SELECT 1 FROM platform_workspace_plans WHERE workspace_id=?)",+ )+ .bind(+ id,+ workspaceId,+ offer.promotionId ? 'signup_promotion' : 'signup_default',+ owner.signup_offer,+ offer.startsAt,+ workspaceId,+ ),+ db+ .prepare(+ 'INSERT OR IGNORE INTO platform_workspace_plans(workspace_id,plan_id,starts_at,expires_at,source) SELECT ?,?,?,?,? WHERE EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)',+ )+ .bind(+ workspaceId,+ offer.planId,+ offer.startsAt,+ offer.expiresAt,+ offer.source,+ id,+ ),+ ])+ } else {+ // Legacy accounts receive the ordinary default, never a retroactive promotion.+ 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,diff --git a/tests/cloud-account-security.test.ts b/tests/cloud-account-security.test.tsindex 2abc1904..8cf7e0c1 100644--- a/tests/cloud-account-security.test.ts+++ b/tests/cloud-account-security.test.ts@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'import test from 'node:test'import { createRequire } from 'node:module'import { createHmac } from 'node:crypto'-import { readFile } from 'node:fs/promises'+import { readFile, readdir } from 'node:fs/promises'import { createAccountAuth } from '../apps/cloud/server/utils/account-auth.ts'const require = createRequire(import.meta.url)@@ -46,11 +46,14 @@ test('Cloud account migration preserves identities and enforces verified registr.run()await migration('0002_visitor_access.sql')await migration('0003_account_security.sql')- await db- .prepare(- "CREATE TABLE platform_account_controls(user_id INTEGER PRIMARY KEY,suspended INTEGER NOT NULL DEFAULT 0,public_reason TEXT NOT NULL DEFAULT '')",+ for (const name of (+ await readdir(+ new URL('../packages/platform/migrations/', import.meta.url),)- .run()+ )+ .filter((n) => n.endsWith('.sql') && n > '0003_account_security.sql')+ .sort())+ await migration(name)assert.equal((await db.prepare('SELECT user_id FROM platform_memberships').first()).user_id,diff --git a/tests/platform-provisioning.test.ts b/tests/platform-provisioning.test.tsindex fca6e530..78a0021f 100644--- a/tests/platform-provisioning.test.ts+++ b/tests/platform-provisioning.test.ts@@ -90,6 +90,7 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc'0015_lifecycle.sql','0016_gallery_presentation.sql','0017_subscriptions.sql',+ '0019_signup_promotions.sql',])await migrate(migration)await dbdiff --git a/tests/signup-promotions.test.ts b/tests/signup-promotions.test.tsnew file mode 100644index 00000000..d8703727--- /dev/null+++ b/tests/signup-promotions.test.ts@@ -0,0 +1,289 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { readdir, readFile } from 'node:fs/promises'+import { createRequire } from 'node:module'+import { createAccountAuth } from '../apps/cloud/server/utils/account-auth.ts'+import { createD1Provisioning } from '../packages/platform/src/index.ts'+import {+ signupOfferForRegistration,+ resolveSubscription,+ validateSignupPromotion,+} from '../packages/platform/src/subscriptions.ts'+const require = createRequire(import.meta.url)+const { Miniflare, convertV4MiniflareOptions } = createRequire(+ require.resolve('wrangler/package.json'),+)('miniflare')+test('Signup promotions snapshot eligibility at actual registration, grant once and expire from registration', async () => {+ const mf = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ compatibilityDate: '2026-10-26',+ script: 'export default {fetch(){return new Response("ok")}}',+ d1Databases: ['DB'],+ }),+ )+ try {+ const db = await mf.getD1Database('DB')+ for (const file of (+ await readdir(+ new URL('../packages/platform/migrations/', import.meta.url),+ )+ )+ .filter((n) => n.endsWith('.sql'))+ .sort())+ for (const sql of (+ await readFile(+ new URL('../packages/platform/migrations/' + file, import.meta.url),+ 'utf8',+ )+ )+ .replace(/^--.*$/gm, '')+ .split(';')+ .filter((s) => s.trim()))+ await db.prepare(sql).run()+ const now = Date.now(),+ day = 86400000+ const free = await db+ .prepare("SELECT policy_json FROM platform_plans WHERE id='free'")+ .first()+ await db+ .prepare(+ "INSERT INTO platform_plans(id,name,policy_json) VALUES('trial','Trial',?)",+ )+ .bind(free.policy_json)+ .run()+ await db+ .prepare(+ "INSERT INTO platform_signup_promotions(id,name,plan_id,starts_at,ends_at,duration_unit,duration_value,priority,enabled,created_at) VALUES('before','Before cutoff','trial',NULL,?,'days',7,0,1,?),('trial14','14-day Trial','trial',?,?,'days',14,10,1,?),('off','Disabled','trial',NULL,?,'days',99,100,0,?)",+ )+ .bind(+ now + 100000,+ now - 20 * day,+ now,+ now + 100000,+ now - 20 * day,+ now + 100000,+ now - 20 * day,+ )+ .run()+ assert.equal(+ JSON.parse(await signupOfferForRegistration(db, now - 1)).promotionId,+ 'before',+ )+ assert.equal(+ JSON.parse(await signupOfferForRegistration(db, now)).promotionId,+ 'trial14',+ )+ assert.equal(+ JSON.parse(await signupOfferForRegistration(db, now + 100000 - 1))+ .promotionId,+ 'trial14',+ )+ assert.equal(+ JSON.parse(await signupOfferForRegistration(db, now + 100000))+ .promotionId,+ null,+ )+ assert.throws(() =>+ validateSignupPromotion({+ name: 'x',+ planId: 'trial',+ enabled: true,+ startsAt: now,+ endsAt: now,+ priority: 0,+ duration: { unit: 'days', value: 14 },+ }),+ )+ const sent: string[] = []+ const auth = createAccountAuth(+ db,+ {+ portalOrigin: 'https://app.chronoframe.art',+ secret: 'signup-test-secret-'.repeat(4),+ emailFrom: '[email protected]',+ },+ {+ send: async (m) => {+ sent.push(m.text)+ return { messageId: crypto.randomUUID() }+ },+ },+ )+ const call = async (path: string, body: any, cookie = '') =>+ auth.handler(+ new Request('https://app.chronoframe.art/api/auth' + path, {+ method: 'POST',+ headers: {+ origin: 'https://app.chronoframe.art',+ 'content-type': 'application/json',+ 'cf-connecting-ip': '192.0.2.10',+ cookie,+ },+ body: JSON.stringify(body),+ }),+ )+ const forged = await call('/sign-up/email', {+ email: '[email protected]',+ password: 'Strong-password-12345',+ name: 'Forged',+ signupOffer: '{"planId":"trial"}',+ })+ assert.equal(forged.status, 400)+ assert.equal(+ await db+ .prepare(+ "SELECT id FROM platform_users WHERE email='[email protected]'",+ )+ .first(),+ null,+ )+ const response = await call('/sign-up/email', {+ email: '[email protected]',+ password: 'Strong-password-12345',+ name: 'Trial user',+ createdAt: new Date(now - 40 * day).toISOString(),+ })+ assert.equal(response.status, 200, await response.clone().text())+ assert.ok(!(await response.text()).includes('signupOffer'))+ const registered = await db+ .prepare("SELECT * FROM platform_users WHERE email='[email protected]'")+ .first()+ const registeredAt = new Date(registered.created_at).getTime()+ const snapshot = JSON.parse(registered.signup_offer)+ assert.equal(snapshot.promotionId, 'trial14')+ assert.equal(snapshot.startsAt, registeredAt)+ assert.equal(snapshot.expiresAt, registeredAt + 14 * day)+ const otp = sent.at(-1)!.match(/\b[0-9]{6}\b/)![0]+ const verification = await call('/email-otp/verify-email', {+ email: '[email protected]',+ otp,+ })+ assert.equal(verification.status, 200, await verification.clone().text())+ assert.ok(!(await verification.clone().text()).includes('signupOffer'))+ const automatic = await db+ .prepare(+ 'SELECT wp.plan_id,wp.expires_at FROM platform_workspaces w JOIN platform_workspace_plans wp ON wp.workspace_id=w.id WHERE w.owner_user_id=?',+ )+ .bind(registered.id)+ .first()+ assert.equal(+ automatic.plan_id,+ 'trial',+ 'verified registration automatically activates the owned workspace before returning its session',+ )+ assert.equal(automatic.expires_at, registeredAt + 14 * day)+ const cookie = verification.headers+ .getSetCookie()+ .map((c) => c.split(';')[0])+ .join('; ')+ await call('/update-user', { signupOffer: '{"planId":"free"}' }, cookie)+ assert.equal(+ (+ await db+ .prepare('SELECT signup_offer FROM platform_users WHERE id=?')+ .bind(registered.id)+ .first()+ ).signup_offer,+ registered.signup_offer,+ )+ await db+ .prepare(+ 'UPDATE platform_signup_promotions SET enabled=0,revision=revision+1',+ )+ .run()+ const store = createD1Provisioning(db)+ const [first, second] = await Promise.all([+ store.defaultWorkspace(registered.id),+ store.defaultWorkspace(registered.id),+ ])+ assert.equal(first.id, second.id)+ const grant = await resolveSubscription(db, first.id)+ assert.equal(grant.id, 'trial')+ assert.equal(grant.subscription.source, 'promotion')+ assert.equal(grant.subscription.expiresAt, registeredAt + 14 * day)+ assert.equal(+ (+ await db+ .prepare(+ 'SELECT COUNT(*) AS n FROM platform_subscription_events WHERE workspace_id=?',+ )+ .bind(first.id)+ .first()+ ).n,+ 1,+ )+ assert.equal(+ (await resolveSubscription(db, first.id, registeredAt + 14 * day)).id,+ 'free',+ )+ await db+ .prepare(+ "UPDATE platform_workspace_plans SET plan_id='free',source='manual',expires_at=NULL,revision=revision+1 WHERE workspace_id=?",+ )+ .bind(first.id)+ .run()+ await store.defaultWorkspace(registered.id)+ assert.equal(+ (await resolveSubscription(db, first.id)).subscription.source,+ 'manual',+ 'signup provisioning never replaces a subsequent assignment',+ )+ await db+ .prepare(+ "INSERT INTO platform_users(email,email_verified,created_at,updated_at,signup_offer) VALUES('[email protected]',1,?,?,?)",+ )+ .bind(+ now - 15 * day,+ now,+ JSON.stringify({+ ...snapshot,+ startsAt: now - 15 * day,+ expiresAt: now - day,+ }),+ )+ .run()+ const late = await db+ .prepare("SELECT id FROM platform_users WHERE email='[email protected]'")+ .first()+ const lateWorkspace = await store.defaultWorkspace(late.id)+ assert.equal(+ (await resolveSubscription(db, lateWorkspace.id)).id,+ 'free',+ 'delayed verification cannot restart a trial',+ )+ await db.prepare('UPDATE platform_signup_promotions SET enabled=1').run()+ await db+ .prepare("UPDATE platform_plans SET active=0 WHERE id='trial'")+ .run()+ assert.equal(+ JSON.parse(await signupOfferForRegistration(db, Date.now())).planId,+ 'free',+ 'inactive target tiers cannot be awarded',+ )+ await db+ .prepare("UPDATE platform_plans SET active=1 WHERE id='trial'")+ .run()+ await db+ .prepare(+ "INSERT INTO platform_users(email,email_verified,created_at,updated_at) VALUES('[email protected]',1,?,?)",+ )+ .bind(now - 100, now)+ .run()+ const legacy = await db+ .prepare("SELECT id FROM platform_users WHERE email='[email protected]'")+ .first()+ assert.equal(+ (+ await resolveSubscription(+ db,+ (await store.defaultWorkspace(legacy.id)).id,+ )+ ).id,+ 'free',+ 'legacy accounts never pick up retrospective promotions',+ )+ } finally {+ await mf.dispose()+ }+})