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 account retention policies and transactional email templates

Timothy Yin76d0d037e0cc
diff --git a/.github/workflows/deploy-saas.yml b/.github/workflows/deploy-saas.yml
index 536d0cbc..beaf3ea2 100644
--- a/.github/workflows/deploy-saas.yml
+++ b/.github/workflows/deploy-saas.yml
@@ -168,7 +168,6 @@ jobs:
if (entry === 'cloud') {
const origin = process.env.PLATFORM_PORTAL_ORIGIN
if (!origin || new URL(origin).protocol !== 'https:' || new URL(origin).origin !== origin) throw new Error('Configure PLATFORM_PORTAL_ORIGIN as an exact HTTPS origin in the selected GitHub Environment variables')
- if (!process.env.PLATFORM_EMAIL_FROM) throw new Error('Configure PLATFORM_EMAIL_FROM in the selected GitHub Environment variables')
}
}
}
@@ -218,11 +217,11 @@ jobs:
target.vars = { ...target.vars, NUXT_PLATFORM_PORTAL_ORIGIN: portalOrigin }
}
const emailFrom = process.env.PLATFORM_EMAIL_FROM
- if (process.env.ENTRY === 'cloud' && emailFrom) {
- if (!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(emailFrom)) throw new Error('Invalid platform email sender address')
+ if (process.env.ENTRY === 'cloud') {
+ if (emailFrom && !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(emailFrom)) throw new Error('Invalid platform email sender address')
const target = process.env.DEPLOY_ENVIRONMENT === 'staging' ? config.previews : config
- target.send_email = [{ name: 'EMAIL', remote: true, allowed_sender_addresses: [emailFrom] }]
- target.vars = { ...target.vars, NUXT_PLATFORM_EMAIL_FROM: emailFrom }
+ target.send_email = [{ name: 'EMAIL', remote: true }]
+ if (emailFrom) target.vars = { ...target.vars, NUXT_PLATFORM_EMAIL_FROM: emailFrom }
if (process.env.DEPLOY_ENVIRONMENT === 'staging') delete config.send_email
}
const { configureDomainDeployment } = await import('./scripts/domain-deployment.mjs')
diff --git a/apps/cloud/.env.example b/apps/cloud/.env.example
index 09811880..480b8012 100644
--- a/apps/cloud/.env.example
+++ b/apps/cloud/.env.example
@@ -4,8 +4,10 @@
# Platform runtime configuration. Email sign-in also requires migrated D1.
# NUXT_PLATFORM_PORTAL_ORIGIN=https://app.chronoframe.art
# NUXT_PLATFORM_SECRET=use-an-independent-random-secret-of-at-least-32-bytes
+# Optional legacy verification sender fallback. D1 mail templates take precedence.
# EMAIL is a Cloudflare Email Sending send_email binding, not an API key.
# DB is a D1 binding, not a string environment variable.
-# The deploy workflow reads PLATFORM_EMAIL_FROM and PLATFORM_D1_DATABASE_ID
-# from the selected GitHub Environment variables. No mail provider key is needed.
+# The deploy workflow reads PLATFORM_D1_DATABASE_ID from GitHub Environment variables.
+# PLATFORM_EMAIL_FROM is optional; business senders are configured in D1.
+# The EMAIL binding must allow those verified senders. No mail provider key is needed.
diff --git a/apps/cloud/server/api/auth/status.get.ts b/apps/cloud/server/api/auth/status.get.ts
index 4f82802c..d6894f64 100644
--- a/apps/cloud/server/api/auth/status.get.ts
+++ b/apps/cloud/server/api/auth/status.get.ts
@@ -10,7 +10,7 @@ export default defineEventHandler(async (event) => {
origin === config.portalOrigin &&
platformEmailReady(
event.context.cloudflare?.env?.EMAIL,
- config.emailFrom,
) &&
config.secret.length >= 32 &&
!!event.context.cloudflare?.env?.DB
diff --git a/apps/cloud/server/plugins/account-lifecycle.ts b/apps/cloud/server/plugins/account-lifecycle.ts
new file mode 100644
index 00000000..85cbe370
--- /dev/null
+++ b/apps/cloud/server/plugins/account-lifecycle.ts
@@ -0,0 +1,103 @@
+import {
+ scanAccounts,
+ deliverLifecycleMail,
+} from '../../../../packages/platform/src/account-lifecycle'
+import { purgeAccounts } from '../../../../packages/platform/src/account-purge'
+import type { PlatformD1 } from '@chronoframe/platform'
+import { createStorageVault } from '../../../../packages/platform/src/storage-vault'
+import { createStorageCipher } from '@chronoframe/storage/credential-cipher'
+import { createCloudS3 } from '@chronoframe/storage/s3-edge'
+import { domainServices } from '../../../shared/platform/domains'
+import type { MailBinding } from '../../../../packages/platform/src/mail'
+export default defineNitroPlugin((app) => {
+ app.hooks.hook('cloudflare:scheduled', async ({ env }) => {
+ const db = env.DB as PlatformD1 | undefined
+ if (!db) return
+ const now = Date.now()
+ await scanAccounts(db, now)
+ await deliverLifecycleMail(
+ db,
+ env.EMAIL as MailBinding,
+ String(env.NUXT_PLATFORM_PORTAL_ORIGIN || 'https://app.chronoframe.art'),
+ now,
+ )
+ const runtime = {
+ public: {
+ siteBaseDomain: String(
+ env.NUXT_PUBLIC_SITE_BASE_DOMAIN || 'chronoframe.art',
+ ),
+ },
+ platform: {
+ domainEnabled: env.NUXT_PLATFORM_DOMAIN_ENABLED,
+ domainRoutingReady: env.NUXT_PLATFORM_DOMAIN_ROUTING_READY,
+ domainProviderToken: env.NUXT_PLATFORM_DOMAIN_PROVIDER_TOKEN,
+ domainZoneId: env.NUXT_PLATFORM_DOMAIN_ZONE_ID,
+ domainCnameTarget: env.NUXT_PLATFORM_DOMAIN_CNAME_TARGET,
+ domainSiteWorker: env.NUXT_PLATFORM_DOMAIN_SITE_WORKER,
+ },
+ }
+ const domains = domainServices(db, runtime)
+ await purgeAccounts(
+ db,
+ {
+ async domains(siteId) {
+ await db
+ .prepare(
+ "UPDATE platform_custom_domains SET state='deleting',purge_requested=1,next_check_at=0,revision=revision+1,lease_token=NULL,lease_until=NULL WHERE site_id=? AND (state<>'deleted' OR purge_requested=0 OR provider_id IS NOT NULL OR route_id IS NOT NULL OR provider_attempted=1 OR route_attempted=1)",
+ )
+ .bind(siteId)
+ .run()
+ const domain = await db
+ .prepare(
+ 'SELECT hostname FROM platform_custom_domains WHERE site_id=? LIMIT 1',
+ )
+ .bind(siteId)
+ .first<{ hostname: string }>()
+ if (domain) {
+ if (!domains.config.enabled)
+ throw new Error('Domain service required')
+ await domains.manager.reconcile(domain.hostname, 1)
+ }
+ return !(await db
+ .prepare(
+ 'SELECT hostname FROM platform_custom_domains WHERE site_id=? LIMIT 1',
+ )
+ .bind(siteId)
+ .first())
+ },
+ async storage(siteId, connectionId, revision) {
+ const key = String(env.NUXT_PLATFORM_STORAGE_SECRET || '')
+ if (key.length < 32) throw new Error('Storage credentials required')
+ const vault = createStorageVault(
+ db,
+ siteId,
+ await createStorageCipher(key),
+ )
+ const connection = await vault.resolve(connectionId, revision)
+ if (!connection) throw new Error('Storage connection unavailable')
+ return createCloudS3(
+ { ...connection.config, ...connection.credentials },
+ {
+ allowedHosts: [
+ ...String(env.NUXT_PLATFORM_S3_ENDPOINT_HOSTS || '')
+ .split(',')
+ .map((h) => h.trim())
+ .filter(Boolean),
+ ...('poolId' in connection
+ ? [new URL(connection.config.endpoint).hostname]
+ : []),
+ ],
+ },
+ ).purgeTenant(siteId)
+ },
+ },
+ now,
+ )
+ await db
+ .prepare(
+ "DELETE FROM platform_mail_outbox WHERE state IN('sent','cancelled') AND available_at<?",
+ )
+ .bind(now - 30 * 86400000)
+ .run()
+ })
+})
diff --git a/apps/cloud/server/utils/account-auth.ts b/apps/cloud/server/utils/account-auth.ts
index fb78bcde..a992b864 100644
--- a/apps/cloud/server/utils/account-auth.ts
+++ b/apps/cloud/server/utils/account-auth.ts
@@ -1,3 +1,4 @@
+import { sendMail } from '../../../../packages/platform/src/mail.ts'
import { signupOfferForRegistration } from '../../../../packages/platform/src/subscriptions.ts'
import type { PlatformD1 } from '@chronoframe/platform'
import { createD1Provisioning } from '../../../../packages/platform/src/provisioning.ts'
@@ -23,9 +24,7 @@ export function accountAuthOptions(
defer?: (task: Promise<unknown>) => void,
) {
const origin = new URL(config.portalOrigin)
- const send = async (to: string, subject: string, text: string) => {
- await email.send({ from: config.emailFrom, to, subject, text })
- }
+ const db = database as unknown as PlatformD1
return {
appName: 'ChronoFrame Cloud',
databaseHooks: {
@@ -72,6 +71,25 @@ export function accountAuthOptions(
)
return { data: session }
},
+ after: async (session) => {
+ const updated = await db
+ .prepare(
+ 'UPDATE platform_users SET last_login_at=? WHERE id=? AND NOT EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=platform_users.id) RETURNING id',
+ )
+ .bind(Date.now(), Number(session.userId))
+ .first()
+ if (!updated) {
+ await db
+ .prepare('DELETE FROM platform_auth_sessions WHERE id=?')
+ .bind(Number(session.id))
+ .run()
+ throw new APIError('FORBIDDEN', {
+ code: 'ACCOUNT_DELETED',
+ message:
+ 'This account has been deleted. Contact [email protected] to request restoration.',
+ })
+ }
+ },
},
},
},
@@ -171,10 +189,13 @@ export function accountAuthOptions(
revokeSessionsOnPasswordReset: true,
resetPasswordTokenExpiresIn: 30 * 60,
async sendResetPassword({ user, url }) {
- await send(
+ await sendMail(
+ db,
+ email,
+ 'password-reset',
user.email,
- 'Reset your ChronoFrame Cloud password',
- `Use this link to set a new password:\n\n${url}\n\nThis link expires in 30 minutes and can only be used once. If you did not request it, ignore this email.`,
+ { name: user.name, minutes: '30' },
+ url,
)
},
},
@@ -198,10 +219,14 @@ export function accountAuthOptions(
async sendVerificationOTP({ email: to, otp, type }) {
const purpose =
type === 'email-verification' ? 'verify your email' : 'sign in'
- await send(
+ await sendMail(
+ db,
+ email,
+ 'verification',
to,
- 'Your ChronoFrame Cloud verification code',
- `Your code to ${purpose} is ${otp}. It expires in 10 minutes. Never share this code.`,
+ { code: otp, purpose, minutes: '10' },
+ undefined,
+ config.emailFrom,
)
},
}),
@@ -228,11 +253,10 @@ export function accountAuthOptions(
]),
},
async sendOTP({ user, otp }) {
- await send(
- user.email,
- 'Complete your ChronoFrame Cloud sign-in',
- `Your second-step verification code is ${otp}. It expires in 3 minutes. Never share this code.`,
- )
+ await sendMail(db, email, 'second-factor', user.email, {
+ code: otp,
+ minutes: '3',
+ })
},
},
accountLockout: {
diff --git a/apps/shared/platform/email.ts b/apps/shared/platform/email.ts
index 7b4eb0cd..5a8669b3 100644
--- a/apps/shared/platform/email.ts
+++ b/apps/shared/platform/email.ts
@@ -7,6 +7,7 @@ export interface PlatformEmailBinding {
to: string
subject: string
text: string
+ html?: string
}): Promise<{ messageId: string }>
}
diff --git a/packages/platform/migrations/0020_account_lifecycle_mail.sql b/packages/platform/migrations/0020_account_lifecycle_mail.sql
new file mode 100644
index 00000000..811bf178
--- /dev/null
+++ b/packages/platform/migrations/0020_account_lifecycle_mail.sql
@@ -0,0 +1,18 @@
+ALTER TABLE platform_users ADD COLUMN last_login_at INTEGER;
+ALTER TABLE platform_users ADD COLUMN lifecycle_grace_until INTEGER NOT NULL DEFAULT 0;
+UPDATE platform_users SET last_login_at=COALESCE((SELECT MAX(CASE WHEN typeof(created_at)='integer' THEN created_at ELSE CAST(strftime('%s',created_at) AS INTEGER)*1000 END) FROM platform_auth_sessions WHERE user_id=platform_users.id),CASE WHEN typeof(created_at)='integer' THEN created_at ELSE CAST(strftime('%s',created_at) AS INTEGER)*1000 END);
+CREATE TABLE platform_lifecycle_settings(id INTEGER PRIMARY KEY CHECK(id=1),enabled INTEGER NOT NULL DEFAULT 1 CHECK(enabled IN(0,1)),unverified_days INTEGER NOT NULL DEFAULT 14 CHECK(unverified_days BETWEEN 1 AND 3650),inactive_days INTEGER NOT NULL DEFAULT 90 CHECK(inactive_days BETWEEN 1 AND 3650),retention_days INTEGER NOT NULL DEFAULT 15 CHECK(retention_days BETWEEN 1 AND 3650),warning_days_json TEXT NOT NULL DEFAULT '[7,3]' CHECK(json_valid(warning_days_json)),activated_at INTEGER NOT NULL,revision INTEGER NOT NULL DEFAULT 1);
+INSERT INTO platform_lifecycle_settings(id,activated_at) VALUES(1,CAST(strftime('%s','now') AS INTEGER)*1000);
+CREATE TABLE platform_account_deletions(user_id INTEGER PRIMARY KEY REFERENCES platform_users(id),generation TEXT NOT NULL,state TEXT NOT NULL DEFAULT 'marked' CHECK(state IN('marked','purging')),source TEXT NOT NULL,reason TEXT NOT NULL,marked_at INTEGER NOT NULL,purge_at INTEGER NOT NULL,previous_suspended INTEGER NOT NULL,previous_reason TEXT NOT NULL,revision INTEGER NOT NULL DEFAULT 1,error TEXT,next_attempt_at INTEGER NOT NULL DEFAULT 0,lease_token TEXT,lease_until INTEGER);
+CREATE INDEX platform_deletions_due ON platform_account_deletions(purge_at,next_attempt_at);
+CREATE TABLE platform_lifecycle_audit(id TEXT PRIMARY KEY,user_id INTEGER NOT NULL,actor_id INTEGER,action TEXT NOT NULL,reason TEXT NOT NULL,created_at INTEGER NOT NULL);
+CREATE TABLE platform_mail_templates(kind TEXT PRIMARY KEY,config_json TEXT NOT NULL CHECK(json_valid(config_json)),revision INTEGER NOT NULL DEFAULT 1);
+CREATE TABLE platform_mail_outbox(id TEXT PRIMARY KEY,user_id INTEGER NOT NULL,kind TEXT NOT NULL,cycle TEXT NOT NULL,to_email TEXT NOT NULL,payload_json TEXT NOT NULL,available_at INTEGER NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN('pending','sent','cancelled')),lease_token TEXT,lease_until INTEGER,error TEXT,UNIQUE(user_id,kind,cycle));
+CREATE INDEX platform_mail_pending ON platform_mail_outbox(state,available_at);
+CREATE TABLE platform_lifecycle_cursor(id INTEGER PRIMARY KEY CHECK(id=1),value INTEGER NOT NULL DEFAULT 0);
+INSERT INTO platform_lifecycle_cursor(id) VALUES(1);
+CREATE TABLE platform_purge_storage_done(user_id INTEGER NOT NULL,site_id INTEGER NOT NULL,connection_id TEXT NOT NULL,revision INTEGER NOT NULL,PRIMARY KEY(user_id,site_id,connection_id,revision));
+CREATE TABLE platform_deletion_sites(user_id INTEGER NOT NULL,site_id INTEGER PRIMARY KEY REFERENCES platform_sites(id),suspended INTEGER NOT NULL,reason TEXT NOT NULL,revision INTEGER NOT NULL);
+
+ALTER TABLE platform_lifecycle_settings ADD COLUMN exemptions_json TEXT NOT NULL DEFAULT '{"enabled":true,"match":"any","rules":[{"kind":"active-subscription","sources":["manual","activation","payment"],"planIds":[]}]}' CHECK(json_valid(exemptions_json));
+ALTER TABLE platform_users ADD COLUMN lifecycle_was_exempt INTEGER NOT NULL DEFAULT 0 CHECK(lifecycle_was_exempt IN(0,1));
diff --git a/packages/platform/src/account-lifecycle.ts b/packages/platform/src/account-lifecycle.ts
new file mode 100644
index 00000000..391cf9c9
--- /dev/null
+++ b/packages/platform/src/account-lifecycle.ts
@@ -0,0 +1,449 @@
+import {
+ accountExemption,
+ validateExemptions,
+ DEFAULT_EXEMPTIONS,
+ type LifecycleExemptions,
+} from './lifecycle-exemptions.ts'
+import type { PlatformD1 } from './index.ts'
+import { allRows } from './subscriptions.ts'
+import { sendMail, type MailBinding, type MailKind } from './mail.ts'
+export const DAY = 86400000
+export type LifecycleSettings = {
+ enabled: boolean
+ unverifiedDays: number
+ inactiveDays: number
+ retentionDays: number
+ warningDays: number[]
+ exemptions?: LifecycleExemptions
+}
+export function validateLifecycleSettings(v: unknown): LifecycleSettings {
+ const s = v as LifecycleSettings
+ if (
+ !s ||
+ typeof s.enabled !== 'boolean' ||
+ ![s.unverifiedDays, s.inactiveDays].every(
+ (n) => Number.isSafeInteger(n) && n >= 1 && n <= 3650,
+ ) ||
+ !Number.isSafeInteger(s.retentionDays) ||
+ s.retentionDays < 1 ||
+ s.retentionDays > 3650 ||
+ !Array.isArray(s.warningDays) ||
+ s.warningDays.length < 1 ||
+ s.warningDays.length > 5 ||
+ !s.warningDays.every(
+ (n) =>
+ Number.isSafeInteger(n) &&
+ n > 0 &&
+ n < Math.min(s.unverifiedDays, s.inactiveDays),
+ ) ||
+ new Set(s.warningDays).size !== s.warningDays.length
+ )
+ throw new Error('Invalid lifecycle settings')
+ return {
+ ...s,
+ warningDays: [...s.warningDays].sort((a, b) => b - a),
+ exemptions: validateExemptions(s.exemptions ?? DEFAULT_EXEMPTIONS),
+ }
+}
+export async function lifecycleSettings(db: PlatformD1) {
+ const s = await db
+ .prepare('SELECT * FROM platform_lifecycle_settings WHERE id=1')
+ .first<any>()
+ if (!s) throw new Error('Lifecycle configuration unavailable')
+ return {
+ ...validateLifecycleSettings({
+ enabled: !!s.enabled,
+ unverifiedDays: s.unverified_days,
+ inactiveDays: s.inactive_days,
+ retentionDays: s.retention_days,
+ warningDays: JSON.parse(s.warning_days_json),
+ exemptions: JSON.parse(s.exemptions_json),
+ }),
+ revision: s.revision as number,
+ activatedAt: s.activated_at as number,
+ }
+}
+export const timeValue = (value: number | string) =>
+ typeof value === 'number' ? value : new Date(value).getTime()
+export function deletionDeadline(
+ user: any,
+ s: Awaited<ReturnType<typeof lifecycleSettings>>,
+) {
+ const verified = !!user.email_verified,
+ anchor = verified
+ ? (user.last_login_at ?? timeValue(user.created_at))
+ : timeValue(user.created_at)
+ return Math.max(
+ anchor + (verified ? s.inactiveDays : s.unverifiedDays) * DAY,
+ s.activatedAt + Math.max(...s.warningDays) * DAY,
+ user.lifecycle_grace_until ?? 0,
+ )
+}
+export const automaticReason = (verified: boolean) =>
+ verified
+ ? 'No recent sign-in was recorded within the inactivity period.'
+ : 'Your email address has not been verified within the verification period.'
+const date = (v: number) =>
+ new Date(v).toISOString().replace('T', ' ').replace('.000Z', ' UTC')
+export async function markAccount(
+ db: PlatformD1,
+ userId: number,
+ reason: string,
+ source: string,
+ actorId: number | null,
+ now = Date.now(),
+ expected?: {
+ login: number | null
+ verified: number
+ settingsRevision: number
+ },
+) {
+ if (
+ !Number.isSafeInteger(userId) ||
+ userId < 1 ||
+ reason.trim().length < 3 ||
+ reason.length > 500
+ )
+ throw new Error('Invalid deletion request')
+ const s = await lifecycleSettings(db)
+ const policyEpoch = await db
+ .prepare('SELECT revision FROM platform_policy_epoch WHERE id=1')
+ .first<{ revision: number }>()
+ if (expected && (await accountExemption(db, userId, s.exemptions!, now)))
+ return false
+ const generation = crypto.randomUUID(),
+ purgeAt = now + s.retentionDays * DAY
+ const guard =
+ 'EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=? AND generation=?)',
+ args = [userId, generation]
+ const row = await db
+ .prepare('SELECT email,name FROM platform_users WHERE id=?')
+ .bind(userId)
+ .first<{ email: string; name: string }>()
+ if (!row) throw new Error('Account not found')
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO platform_account_deletions(user_id,generation,source,reason,marked_at,purge_at,previous_suspended,previous_reason) SELECT u.id,?,?,?,?,?,COALESCE(c.suspended,0),COALESCE(c.public_reason,'') FROM platform_users u LEFT JOIN platform_account_controls c ON c.user_id=u.id WHERE u.id=? AND NOT EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=u.id) ${expected ? 'AND u.last_login_at IS ? AND u.email_verified=? AND EXISTS(SELECT 1 FROM platform_lifecycle_settings WHERE id=1 AND enabled=1 AND revision=?) AND EXISTS(SELECT 1 FROM platform_policy_epoch WHERE id=1 AND revision=?)' : ''}`,
+ )
+ .bind(
+ generation,
+ source,
+ reason.trim(),
+ now,
+ purgeAt,
+ userId,
+ ...(expected
+ ? [
+ expected.login,
+ expected.verified,
+ expected.settingsRevision,
+ policyEpoch!.revision,
+ ]
+ : []),
+ ),
+ db
+ .prepare(
+ `INSERT INTO platform_account_controls(user_id,suspended,public_reason) SELECT ?,1,? WHERE ${guard} ON CONFLICT(user_id) DO UPDATE SET suspended=1,public_reason=excluded.public_reason,revision=revision+1`,
+ )
+ .bind(
+ userId,
+ `Account deleted: ${reason.trim()} Contact [email protected] before ${date(purgeAt)} to request restoration.`,
+ ...args,
+ ),
+ db
+ .prepare(
+ `INSERT OR IGNORE INTO platform_deletion_sites(user_id,site_id,suspended,reason,revision) SELECT ?,s.id,s.suspended,s.suspension_reason,s.revision FROM platform_sites s JOIN platform_workspaces w ON w.id=s.workspace_id WHERE w.owner_user_id=? AND ${guard}`,
+ )
+ .bind(userId, userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_sites SET suspended=1,suspension_reason='Owner account marked for deletion',revision=revision+1 WHERE id IN(SELECT site_id FROM platform_deletion_sites WHERE user_id=?) AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `DELETE FROM platform_auth_sessions WHERE user_id=? AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(`DELETE FROM platform_sessions WHERE user_id=? AND ${guard}`)
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_custom_domains SET next_check_at=0,revision=revision+1,lease_token=NULL,lease_until=NULL WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id IN(SELECT id FROM platform_workspaces WHERE owner_user_id=?)) AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_policy_epoch SET revision=revision+1 WHERE id=1 AND ${guard}`,
+ )
+ .bind(...args),
+ db
+ .prepare(
+ `INSERT INTO platform_lifecycle_audit(id,user_id,actor_id,action,reason,created_at) SELECT ?,?,?,'mark',?,? WHERE ${guard}`,
+ )
+ .bind(generation, userId, actorId, reason.trim(), now, ...args),
+ db
+ .prepare(
+ `INSERT OR IGNORE INTO platform_mail_outbox(id,user_id,kind,cycle,to_email,payload_json,available_at) SELECT ?,?,'account-deleted',?,?,?,? WHERE ${guard}`,
+ )
+ .bind(
+ crypto.randomUUID(),
+ userId,
+ generation,
+ row.email,
+ JSON.stringify({
+ reason: reason.trim(),
+ purgeAt: date(purgeAt),
+ retentionDays: String(s.retentionDays),
+ name: row.name,
+ }),
+ now,
+ ...args,
+ ),
+ ])
+ return !!(await db
+ .prepare(
+ 'SELECT user_id FROM platform_account_deletions WHERE user_id=? AND generation=?',
+ )
+ .bind(...args)
+ .first())
+}
+export async function restoreAccount(
+ db: PlatformD1,
+ userId: number,
+ revision: number,
+ actorId: number,
+ reason: string,
+ now = Date.now(),
+) {
+ const s = await lifecycleSettings(db),
+ id = crypto.randomUUID(),
+ guard =
+ "EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=? AND state='marked' AND purge_at>? AND revision=?)",
+ args = [userId, now, revision]
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO platform_lifecycle_audit(id,user_id,actor_id,action,reason,created_at) SELECT ?,?,?,'restore',?,? WHERE ${guard}`,
+ )
+ .bind(id, userId, actorId, reason, now, ...args),
+ db
+ .prepare(
+ `UPDATE platform_account_controls SET suspended=(SELECT previous_suspended FROM platform_account_deletions WHERE user_id=?),public_reason=(SELECT previous_reason FROM platform_account_deletions WHERE user_id=?),revision=revision+1 WHERE user_id=? AND ${guard}`,
+ )
+ .bind(userId, userId, userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_users SET last_login_at=?,lifecycle_grace_until=? WHERE id=? AND ${guard}`,
+ )
+ .bind(now, now + s.unverifiedDays * DAY, userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_mail_outbox SET state='cancelled' WHERE user_id=? AND state='pending' AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_custom_domains SET next_check_at=0,revision=revision+1,lease_token=NULL,lease_until=NULL WHERE site_id IN(SELECT id FROM platform_sites WHERE workspace_id IN(SELECT id FROM platform_workspaces WHERE owner_user_id=?)) AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `UPDATE platform_policy_epoch SET revision=revision+1 WHERE id=1 AND ${guard}`,
+ )
+ .bind(...args),
+ db
+ .prepare(
+ `UPDATE platform_sites SET suspended=(SELECT suspended FROM platform_deletion_sites d WHERE d.site_id=platform_sites.id),suspension_reason=(SELECT reason FROM platform_deletion_sites d WHERE d.site_id=platform_sites.id),revision=revision+1 WHERE id IN(SELECT site_id FROM platform_deletion_sites WHERE user_id=?) AND revision=(SELECT revision+1 FROM platform_deletion_sites WHERE site_id=platform_sites.id) AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `DELETE FROM platform_deletion_sites WHERE user_id=? AND ${guard}`,
+ )
+ .bind(userId, ...args),
+ db
+ .prepare(
+ `DELETE FROM platform_account_deletions WHERE ${guard} AND user_id=?`,
+ )
+ .bind(...args, userId),
+ ])
+ return !!(await db
+ .prepare('SELECT id FROM platform_lifecycle_audit WHERE id=?')
+ .bind(id)
+ .first())
+}
+export async function scanAccounts(
+ db: PlatformD1,
+ now = Date.now(),
+ limit = 50,
+) {
+ const s = await lifecycleSettings(db)
+ if (!s.enabled) return
+ // Keyset cursor prevents a fixed first page from starving older or newer accounts.
+ const state = await db
+ .prepare('SELECT value FROM platform_lifecycle_cursor WHERE id=1')
+ .first<{ value: number }>()
+ const users = await allRows<any>(
+ db
+ .prepare(
+ 'SELECT * FROM platform_users WHERE id>? AND NOT EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=platform_users.id) ORDER BY id LIMIT ?',
+ )
+ .bind(state?.value ?? 0, limit),
+ )
+ for (const u of users) {
+ if (await accountExemption(db, u.id, s.exemptions!, now)) {
+ await db
+ .prepare('UPDATE platform_users SET lifecycle_was_exempt=1 WHERE id=?')
+ .bind(u.id)
+ .run()
+ continue
+ }
+ if (u.lifecycle_was_exempt) {
+ u.lifecycle_grace_until = Math.max(
+ u.lifecycle_grace_until,
+ now + Math.max(...s.warningDays) * DAY,
+ )
+ await db
+ .prepare(
+ 'UPDATE platform_users SET lifecycle_was_exempt=0,lifecycle_grace_until=MAX(lifecycle_grace_until,?) WHERE id=?',
+ )
+ .bind(u.lifecycle_grace_until, u.id)
+ .run()
+ }
+ const deadline = deletionDeadline(u, s),
+ reason = automaticReason(!!u.email_verified)
+ if (deadline <= now) {
+ await markAccount(
+ db,
+ u.id,
+ reason,
+ u.email_verified ? 'inactive' : 'unverified',
+ null,
+ now,
+ {
+ login: u.last_login_at,
+ verified: u.email_verified,
+ settingsRevision: s.revision,
+ },
+ )
+ continue
+ }
+ const warning = s.warningDays.find(
+ (days, index) =>
+ now >= deadline - days * DAY &&
+ (index === s.warningDays.length - 1 ||
+ now < deadline - s.warningDays[index + 1]! * DAY),
+ )
+ if (warning !== undefined)
+ await db
+ .prepare(
+ "INSERT OR IGNORE INTO platform_mail_outbox(id,user_id,kind,cycle,to_email,payload_json,available_at) VALUES(?,?,'deletion-warning',?,?,?,?)",
+ )
+ .bind(
+ crypto.randomUUID(),
+ u.id,
+ `${deadline}:${warning}`,
+ u.email,
+ JSON.stringify({
+ deadline,
+ reason,
+ deletionAt: date(deadline),
+ purgeAt: date(deadline + s.retentionDays * DAY),
+ action: u.email_verified
+ ? 'Sign in before the deletion date to keep your account.'
+ : 'Verify your email address before the deletion date to keep your account.',
+ name: u.name,
+ }),
+ now,
+ )
+ .run()
+ }
+ await db
+ .prepare('UPDATE platform_lifecycle_cursor SET value=? WHERE id=1')
+ .bind(users.length === limit ? users.at(-1).id : 0)
+ .run()
+}
+export async function deliverLifecycleMail(
+ db: PlatformD1,
+ email: MailBinding,
+ portal: string,
+ now = Date.now(),
+) {
+ const s = await lifecycleSettings(db)
+ const rows = await allRows<any>(
+ db
+ .prepare(
+ "SELECT * FROM platform_mail_outbox WHERE state='pending' AND available_at<=? AND (lease_until IS NULL OR lease_until<?) ORDER BY available_at,id LIMIT 10",
+ )
+ .bind(now, now),
+ )
+ for (const row of rows) {
+ const token = crypto.randomUUID(),
+ claimed = await db
+ .prepare(
+ "UPDATE platform_mail_outbox SET lease_token=?,lease_until=? WHERE id=? AND state='pending' AND (lease_until IS NULL OR lease_until<?) RETURNING id",
+ )
+ .bind(token, now + 120000, row.id, now)
+ .first()
+ if (!claimed) continue
+ const p = JSON.parse(row.payload_json),
+ u = await db
+ .prepare('SELECT * FROM platform_users WHERE id=?')
+ .bind(row.user_id)
+ .first<any>(),
+ marked = await db
+ .prepare('SELECT * FROM platform_account_deletions WHERE user_id=?')
+ .bind(row.user_id)
+ .first<any>()
+ const valid =
+ u &&
+ (row.kind === 'account-deleted'
+ ? marked?.generation === row.cycle
+ : s.enabled &&
+ !marked &&
+ !(await accountExemption(db, row.user_id, s.exemptions!, now)) &&
+ deletionDeadline(u, s) === p.deadline &&
+ p.deadline > now)
+ if (!valid) {
+ await db
+ .prepare(
+ "UPDATE platform_mail_outbox SET state='cancelled',lease_token=NULL,lease_until=NULL WHERE id=? AND lease_token=?",
+ )
+ .bind(row.id, token)
+ .run()
+ continue
+ }
+ try {
+ await sendMail(
+ db,
+ email,
+ row.kind as MailKind,
+ row.to_email,
+ p,
+ row.kind === 'account-deleted'
+ ? 'mailto:[email protected]'
+ : portal + '/signin',
+ )
+ await db
+ .prepare(
+ "UPDATE platform_mail_outbox SET state='sent',lease_token=NULL,lease_until=NULL,error=NULL WHERE id=? AND lease_token=?",
+ )
+ .bind(row.id, token)
+ .run()
+ } catch {
+ await db
+ .prepare(
+ "UPDATE platform_mail_outbox SET attempts=attempts+1,available_at=?,error='email_delivery_failed',lease_token=NULL,lease_until=NULL WHERE id=? AND lease_token=?",
+ )
+ .bind(
+ now + Math.min(3600000, 60000 * 2 ** Math.min(row.attempts, 6)),
+ row.id,
+ token,
+ )
+ .run()
+ }
+ }
+}
diff --git a/packages/platform/src/account-purge.ts b/packages/platform/src/account-purge.ts
new file mode 100644
index 00000000..40440b85
--- /dev/null
+++ b/packages/platform/src/account-purge.ts
@@ -0,0 +1,263 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows } from './subscriptions.ts'
+export interface AccountCleanup {
+ domains(siteId: number): Promise<boolean>
+ storage(
+ siteId: number,
+ connectionId: string,
+ revision: number,
+ ): Promise<boolean>
+}
+/** External resources are acknowledged before deleting the credentials/catalog needed to retry. */
+export async function purgeAccounts(
+ db: PlatformD1,
+ cleanup: AccountCleanup,
+ now = Date.now(),
+) {
+ const row = await db
+ .prepare(
+ 'SELECT * FROM platform_account_deletions WHERE purge_at<=? AND next_attempt_at<=? AND (lease_until IS NULL OR lease_until<?) ORDER BY purge_at,user_id LIMIT 1',
+ )
+ .bind(now, now, now)
+ .first<any>()
+ if (!row) return
+ const token = crypto.randomUUID(),
+ lock = await db
+ .prepare(
+ "UPDATE platform_account_deletions SET state='purging',revision=revision+1,lease_token=?,lease_until=? WHERE user_id=? AND purge_at<=? AND (lease_until IS NULL OR lease_until<?) RETURNING user_id",
+ )
+ .bind(token, now + 300000, row.user_id, now, now)
+ .first()
+ if (!lock) return
+ const id = row.user_id
+ try {
+ // A purging account cannot be restored; all existing leases are fenced before external cleanup.
+ await db
+ .prepare(
+ "UPDATE cloud_processing_jobs SET state='cancelled',lease_until=NULL,attempt_id=NULL WHERE site_id IN(SELECT s.id FROM platform_sites s JOIN platform_workspaces w ON w.id=s.workspace_id WHERE w.owner_user_id=?) AND state IN('queued','running','retry_wait')",
+ )
+ .bind(id)
+ .run()
+ const sites = await allRows<{ id: number }>(
+ db
+ .prepare(
+ 'SELECT s.id FROM platform_sites s JOIN platform_workspaces w ON w.id=s.workspace_id WHERE w.owner_user_id=? ORDER BY s.id',
+ )
+ .bind(id),
+ )
+ let pending = false
+ for (const site of sites) {
+ if (!(await cleanup.domains(site.id))) {
+ pending = true
+ break
+ }
+ const connection = await db
+ .prepare(
+ 'SELECT v.connection_id,v.revision FROM cloud_storage_versions v WHERE v.site_id=? AND NOT EXISTS(SELECT 1 FROM platform_purge_storage_done d WHERE d.user_id=? AND d.site_id=v.site_id AND d.connection_id=v.connection_id AND d.revision=v.revision) ORDER BY v.connection_id,v.revision LIMIT 1',
+ )
+ .bind(site.id, id)
+ .first<{ connection_id: string; revision: number }>()
+ if (connection) {
+ if (
+ await cleanup.storage(
+ site.id,
+ connection.connection_id,
+ connection.revision,
+ )
+ )
+ await db
+ .prepare(
+ 'INSERT OR IGNORE INTO platform_purge_storage_done VALUES(?,?,?,?)',
+ )
+ .bind(id, site.id, connection.connection_id, connection.revision)
+ .run()
+ pending = true
+ break
+ }
+ }
+ if (pending) {
+ await db
+ .prepare(
+ 'UPDATE platform_account_deletions SET lease_token=NULL,lease_until=NULL,next_attempt_at=?,error=NULL WHERE user_id=? AND lease_token=?',
+ )
+ .bind(now + 60000, id, token)
+ .run()
+ return
+ }
+ // Build a child-first deletion order from the actual installed schema, including future site tables.
+ const tables = await allRows<{ name: string }>(
+ db.prepare(
+ "SELECT name FROM sqlite_master WHERE type='table' AND (name GLOB 'platform_*' OR name GLOB 'cloud_*')",
+ ),
+ )
+ const names = new Set(tables.map((t) => t.name)),
+ siteTables: string[] = [],
+ deps = new Map<string, string[]>()
+ for (const { name } of tables) {
+ if (!/^[a-zA-Z0-9_]+$/.test(name)) continue
+ const cols = await allRows<{ name: string }>(
+ db.prepare(`PRAGMA table_info("${name}")`),
+ )
+ if (cols.some((c) => c.name === 'site_id')) {
+ siteTables.push(name)
+ deps.set(
+ name,
+ (
+ await allRows<{ table: string }>(
+ db.prepare(`PRAGMA foreign_key_list("${name}")`),
+ )
+ )
+ .map((f) => f.table)
+ .filter((t) => t !== name),
+ )
+ }
+ }
+ const remaining = new Set(siteTables),
+ order: string[] = []
+ while (remaining.size) {
+ const child = [...remaining].find(
+ (t) =>
+ ![...remaining].some(
+ (other) => other !== t && deps.get(other)?.includes(t),
+ ),
+ )
+ if (!child) throw new Error('Cleanup schema dependency cycle')
+ order.push(child)
+ remaining.delete(child)
+ }
+ const owned =
+ 'SELECT s.id FROM platform_sites s JOIN platform_workspaces w ON w.id=s.workspace_id WHERE w.owner_user_id=?',
+ workspaces = 'SELECT id FROM platform_workspaces WHERE owner_user_id=?'
+ const statements = order.map((t) =>
+ db.prepare(`DELETE FROM "${t}" WHERE site_id IN(${owned})`).bind(id),
+ )
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM platform_sites WHERE workspace_id IN(${workspaces})`,
+ )
+ .bind(id),
+ )
+ // Remove memberships in others' spaces without deleting those spaces or their files.
+ statements.push(
+ db
+ .prepare(
+ 'UPDATE cloud_uploads SET owner_id=COALESCE((SELECT w.owner_user_id FROM platform_sites s JOIN platform_workspaces w ON w.id=s.workspace_id WHERE s.id=cloud_uploads.site_id),(SELECT MIN(user_id) FROM platform_memberships WHERE workspace_id=(SELECT workspace_id FROM platform_sites WHERE id=cloud_uploads.site_id) AND user_id<>?)) WHERE owner_id=?',
+ )
+ .bind(id, id),
+ )
+ statements.push(
+ db
+ .prepare(
+ 'DELETE FROM platform_activation_redemptions WHERE user_id=? OR workspace_id IN(' +
+ workspaces +
+ ') OR code_id IN(SELECT id FROM platform_activation_codes WHERE created_by=?)',
+ )
+ .bind(id, id, id),
+ )
+ statements.push(
+ db
+ .prepare('DELETE FROM platform_activation_codes WHERE created_by=?')
+ .bind(id),
+ )
+ statements.push(
+ db
+ .prepare(
+ 'UPDATE platform_subscription_events SET actor_id=NULL WHERE actor_id=?',
+ )
+ .bind(id),
+ )
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM platform_subscription_events WHERE workspace_id IN(${workspaces})`,
+ )
+ .bind(id),
+ )
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM platform_workspace_plans WHERE workspace_id IN(${workspaces})`,
+ )
+ .bind(id),
+ )
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM platform_memberships WHERE user_id=? OR workspace_id IN(${workspaces})`,
+ )
+ .bind(id, id),
+ )
+ statements.push(
+ db
+ .prepare('DELETE FROM platform_workspaces WHERE owner_user_id=?')
+ .bind(id),
+ )
+ for (const t of [
+ 'platform_admin_roles',
+ 'platform_sessions',
+ 'platform_accounts',
+ 'platform_passkeys',
+ 'platform_two_factors',
+ 'platform_auth_sessions',
+ 'platform_activation_attempts',
+ 'platform_account_controls',
+ 'platform_mail_outbox',
+ 'platform_purge_storage_done',
+ ])
+ if (names.has(t))
+ statements.push(db.prepare(`DELETE FROM ${t} WHERE user_id=?`).bind(id))
+ statements.push(
+ db
+ .prepare(
+ 'DELETE FROM platform_verifications WHERE instr(identifier,(SELECT email FROM platform_users WHERE id=?))>0',
+ )
+ .bind(id),
+ )
+ statements.push(
+ db
+ .prepare(
+ "UPDATE platform_lifecycle_audit SET reason='Account erased',actor_id=CASE WHEN actor_id=? THEN NULL ELSE actor_id END WHERE user_id=? OR actor_id=?",
+ )
+ .bind(id, id, id),
+ )
+ if (names.has('platform_admin_audit'))
+ statements.push(
+ db
+ .prepare(
+ "UPDATE platform_admin_audit SET before_json=NULL,after_json=NULL,reason='Account erased' WHERE target=? AND action IN('user','account-mark','account-restore')",
+ )
+ .bind(String(id)),
+ )
+ // Keep a minimal event trail without deletion reasons or mail payloads.
+ statements.push(
+ db
+ .prepare(
+ "INSERT INTO platform_lifecycle_audit(id,user_id,action,reason,created_at) VALUES(?,?,'purge','Retention period elapsed; external cleanup confirmed',?)",
+ )
+ .bind(crypto.randomUUID(), id, now),
+ )
+ statements.push(
+ db
+ .prepare(
+ 'DELETE FROM platform_account_deletions WHERE user_id=? AND lease_token=?',
+ )
+ .bind(id, token),
+ )
+ statements.push(
+ db
+ .prepare(
+ 'DELETE FROM platform_users WHERE id=? AND NOT EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=?)',
+ )
+ .bind(id, id),
+ )
+ await db.batch(statements)
+ } catch {
+ await db
+ .prepare(
+ "UPDATE platform_account_deletions SET error='resource_cleanup_failed',next_attempt_at=?,lease_token=NULL,lease_until=NULL WHERE user_id=? AND lease_token=?",
+ )
+ .bind(now + 300000, id, token)
+ .run()
+ }
+}
diff --git a/packages/platform/src/lifecycle-exemptions.ts b/packages/platform/src/lifecycle-exemptions.ts
new file mode 100644
index 00000000..4efacc0e
--- /dev/null
+++ b/packages/platform/src/lifecycle-exemptions.ts
@@ -0,0 +1,136 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows } from './subscriptions.ts'
+export const SUBSCRIPTION_SOURCES = [
+ 'manual',
+ 'activation',
+ 'promotion',
+ 'payment',
+] as const
+export type ExemptionRule = {
+ kind: 'active-subscription' | 'ever-subscribed'
+ sources: string[]
+ planIds: string[]
+}
+export type LifecycleExemptions = {
+ enabled: boolean
+ match: 'any' | 'all'
+ rules: ExemptionRule[]
+}
+export const DEFAULT_EXEMPTIONS: LifecycleExemptions = {
+ enabled: true,
+ match: 'any',
+ rules: [
+ {
+ kind: 'active-subscription',
+ sources: ['manual', 'activation', 'payment'],
+ planIds: [],
+ },
+ ],
+}
+export function validateExemptions(value: unknown): LifecycleExemptions {
+ const v = value as LifecycleExemptions
+ if (
+ !v ||
+ typeof v.enabled !== 'boolean' ||
+ !['any', 'all'].includes(v.match) ||
+ !Array.isArray(v.rules) ||
+ v.rules.length > 16 ||
+ (v.enabled && !v.rules.length)
+ )
+ throw new Error('Invalid exemption rules')
+ for (const r of v.rules) {
+ if (
+ !r ||
+ !['active-subscription', 'ever-subscribed'].includes(r.kind) ||
+ !Array.isArray(r.sources) ||
+ !r.sources.length ||
+ r.sources.length > 4 ||
+ !r.sources.every((s) => SUBSCRIPTION_SOURCES.includes(s as any)) ||
+ new Set(r.sources).size !== r.sources.length ||
+ !Array.isArray(r.planIds) ||
+ r.planIds.length > 100 ||
+ !r.planIds.every(
+ (p) => typeof p === 'string' && /^[a-zA-Z0-9_.-]{1,128}$/.test(p),
+ ) ||
+ new Set(r.planIds).size !== r.planIds.length
+ )
+ throw new Error('Invalid exemption condition')
+ }
+ return {
+ enabled: v.enabled,
+ match: v.match,
+ rules: v.rules.map((r) => ({
+ kind: r.kind,
+ sources: [...r.sources],
+ planIds: [...r.planIds],
+ })),
+ }
+}
+/** Grants belong to owned workspaces. Merely joining another subscriber's workspace cannot exempt an account. */
+export async function accountExemption(
+ db: PlatformD1,
+ userId: number,
+ config: LifecycleExemptions,
+ now = Date.now(),
+) {
+ if (!config.enabled) return false
+ const current = await allRows<any>(
+ db
+ .prepare(
+ 'SELECT p.*,plan.active FROM platform_workspace_plans p JOIN platform_workspaces w ON w.id=p.workspace_id JOIN platform_plans plan ON plan.id=p.plan_id WHERE w.owner_user_id=?',
+ )
+ .bind(userId),
+ )
+ const events = config.rules.some((r) => r.kind === 'ever-subscribed')
+ ? await allRows<any>(
+ db
+ .prepare(
+ 'SELECT e.kind,e.before_json,e.after_json FROM platform_subscription_events e JOIN platform_workspaces w ON w.id=e.workspace_id WHERE w.owner_user_id=?',
+ )
+ .bind(userId),
+ )
+ : []
+ const historical: any[] = []
+ for (const e of events)
+ for (const json of [e.before_json, e.after_json]) {
+ try {
+ const p = JSON.parse(json)
+ if (p && typeof p === 'object')
+ historical.push({
+ plan_id: p.planId ?? p.plan_id,
+ source:
+ p.source ??
+ (
+ {
+ assigned: 'manual',
+ redeemed: 'activation',
+ signup_promotion: 'promotion',
+ } as Record<string, string>
+ )[e.kind],
+ })
+ } catch {
+ throw new Error('Invalid subscription history')
+ }
+ }
+ const matches = (r: ExemptionRule) => {
+ const entries =
+ r.kind === 'active-subscription'
+ ? current.filter(
+ (p) =>
+ p.active === 1 &&
+ p.starts_at <= now &&
+ (p.expires_at === null || p.expires_at > now),
+ )
+ : current.concat(historical)
+ return entries.some(
+ (p) =>
+ p.plan_id &&
+ p.plan_id !== 'free' &&
+ r.sources.includes(p.source) &&
+ (!r.planIds.length || r.planIds.includes(p.plan_id)),
+ )
+ }
+ return config.match === 'all'
+ ? config.rules.every(matches)
+ : config.rules.some(matches)
+}
diff --git a/packages/platform/src/mail.ts b/packages/platform/src/mail.ts
new file mode 100644
index 00000000..326c8468
--- /dev/null
+++ b/packages/platform/src/mail.ts
@@ -0,0 +1,213 @@
+import type { PlatformD1 } from './index.ts'
+export const MAIL_KINDS = [
+ 'verification',
+ 'password-reset',
+ 'second-factor',
+ 'deletion-warning',
+ 'account-deleted',
+] as const
+export type MailKind = (typeof MAIL_KINDS)[number]
+export type MailTemplate = {
+ senderName: string
+ from: string
+ subject: string
+ heading: string
+ body: string
+ button: string
+ footer: string
+ accent: string
+}
+const content: Record<MailKind, [string, string, string, string]> = {
+ verification: [
+ 'Your ChronoFrame Cloud verification code',
+ 'Your verification code',
+ 'Your code to {{purpose}} is {{code}}. It expires in {{minutes}} minutes. Never share this code.',
+ '',
+ ],
+ 'password-reset': [
+ 'Reset your ChronoFrame Cloud password',
+ 'Set a new password',
+ 'Use the button below to set a new password. This link expires in {{minutes}} minutes and can only be used once. If you did not request it, ignore this email.',
+ 'Reset password',
+ ],
+ 'second-factor': [
+ 'Complete your ChronoFrame Cloud sign-in',
+ 'Confirm it is you',
+ 'Your second-step verification code is {{code}}. It expires in {{minutes}} minutes. Never share this code.',
+ '',
+ ],
+ 'deletion-warning': [
+ 'Your ChronoFrame Cloud account is scheduled for deletion',
+ 'Keep your account',
+ '{{reason}} Your account will be marked as deleted and sign-in disabled on {{deletionAt}}. All owned workspaces, sites, domains and files will be permanently removed on {{purgeAt}}. {{action}} Contact [email protected] if you need help.',
+ 'Open ChronoFrame Cloud',
+ ],
+ 'account-deleted': [
+ 'Your ChronoFrame Cloud account has been deleted',
+ 'Your account has been marked as deleted',
+ '{{reason}} Sign-in is now disabled. After the {{retentionDays}}-day recovery period, all owned workspaces, sites, domains and files will be permanently removed on {{purgeAt}}. Until then, contact [email protected] to request restoration.',
+ 'Contact support',
+ ],
+}
+export function defaultMailTemplate(
+ kind: MailKind,
+ fallback?: string,
+): MailTemplate {
+ const c = content[kind]
+ return {
+ senderName: 'ChronoFrame Cloud',
+ from:
+ fallback ||
+ `${kind === 'verification' || kind === 'second-factor' ? 'verify' : kind === 'password-reset' ? 'security' : 'accounts'}@noreply.chronoframe.art`,
+ subject: c[0],
+ heading: c[1],
+ body: c[2],
+ button: c[3],
+ footer:
+ 'ChronoFrame Cloud · Your photography. Your perspective.\nNeed help? [email protected]',
+ accent: '#354d38',
+ }
+}
+const placeholders = new Set([
+ 'name',
+ 'code',
+ 'purpose',
+ 'minutes',
+ 'deletionAt',
+ 'purgeAt',
+ 'reason',
+ 'action',
+ 'retentionDays',
+])
+export function validateMailTemplate(value: unknown): MailTemplate {
+ const t = value as MailTemplate
+ if (!t || typeof t !== 'object') throw new Error('Invalid mail template')
+ for (const [k, max] of [
+ ['senderName', 80],
+ ['from', 254],
+ ['subject', 200],
+ ['heading', 200],
+ ['body', 6000],
+ ['button', 80],
+ ['footer', 1000],
+ ['accent', 7],
+ ] as const) {
+ if (
+ typeof t[k] !== 'string' ||
+ t[k].length > max ||
+ (!t[k].trim() && !['button', 'footer'].includes(k))
+ )
+ throw new Error('Invalid mail template')
+ if (['from', 'senderName', 'subject'].includes(k) && /[\r\n<>]/.test(t[k]))
+ throw new Error('Invalid mail header')
+ for (const p of t[k].matchAll(/{{\s*([^{}]+?)\s*}}/g))
+ if (!placeholders.has(p[1]!)) throw new Error('Unknown template variable')
+ }
+ if (/[,:;"\\]/.test(t.senderName)) throw new Error('Invalid sender name')
+ if (
+ !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(
+ t.from,
+ ) ||
+ !/^#[0-9a-f]{6}$/i.test(t.accent)
+ )
+ throw new Error('Invalid mail sender or color')
+ return Object.fromEntries(
+ Object.keys(defaultMailTemplate('verification')).map((k) => [
+ k,
+ t[k as keyof MailTemplate],
+ ]),
+ ) as MailTemplate
+}
+export function validateMailContent(kind: MailKind, value: unknown) {
+ const t = validateMailTemplate(value)
+ const required =
+ kind === 'verification' || kind === 'second-factor'
+ ? ['code', 'minutes']
+ : kind === 'deletion-warning'
+ ? ['reason', 'deletionAt', 'purgeAt', 'action']
+ : kind === 'account-deleted'
+ ? ['reason', 'purgeAt', 'retentionDays']
+ : []
+ for (const name of required)
+ if (!new RegExp('\\{\\{\\s*' + name + '\\s*\\}\\}').test(t.body))
+ throw new Error('Required mail variable missing: ' + name)
+ if (kind === 'password-reset' && !t.button.trim())
+ throw new Error('Password reset button required')
+ if (kind === 'account-deleted' && !t.body.includes('[email protected]'))
+ throw new Error('Recovery contact required')
+ return t
+}
+export async function mailTemplate(
+ db: PlatformD1,
+ kind: MailKind,
+ fallback?: string,
+) {
+ const row = await db
+ .prepare(
+ 'SELECT config_json,revision FROM platform_mail_templates WHERE kind=?',
+ )
+ .bind(kind)
+ .first<{ config_json: string; revision: number }>()
+ return {
+ template: row
+ ? validateMailContent(kind, JSON.parse(row.config_json))
+ : defaultMailTemplate(kind, fallback),
+ revision: row?.revision ?? 0,
+ }
+}
+const escape = (s: string) =>
+ s.replace(
+ /[&<>"']/g,
+ (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[
+ c
+ ]!,
+ )
+export function renderMail(
+ template: MailTemplate,
+ variables: Record<string, string>,
+ url?: string,
+) {
+ const t = validateMailTemplate(template),
+ fill = (s: string) =>
+ s.replace(/{{\s*([^{}]+?)\s*}}/g, (_, k) => variables[k] ?? '')
+ if (url && !/^(https:\/\/|mailto:support@chronoframe\.art$)/.test(url))
+ throw new Error('Unsafe mail link')
+ const subject = fill(t.subject).replace(/[\r\n]/g, ' '),
+ heading = fill(t.heading),
+ body = fill(t.body),
+ footer = fill(t.footer),
+ button = fill(t.button)
+ const text = [heading, body, url && button ? `${button}: ${url}` : '', footer]
+ .filter(Boolean)
+ .join('\n\n')
+ const html = `<!doctype html><html><body style="margin:0;background:#f5f5f0;color:#242b24;font:16px/1.65 Arial,sans-serif"><div style="max-width:560px;margin:36px auto;padding:32px;background:#fff;border:1px solid #dedfd5;border-radius:14px"><div style="font-weight:700;font-size:18px;color:${t.accent}">ChronoFrame Cloud</div><h1 style="font-size:26px;line-height:1.3;margin:32px 0 20px">${escape(heading)}</h1><div style="white-space:pre-line">${escape(body)}</div>${url && button ? `<p style="margin:28px 0"><a href="${escape(url)}" style="display:inline-block;padding:12px 20px;background:${t.accent};color:white;text-decoration:none;border-radius:8px">${escape(button)}</a></p>` : ''}<hr style="border:0;border-top:1px solid #e5e5dd;margin:32px 0 20px"><div style="font-size:12px;color:#73796c;white-space:pre-line">${escape(footer)}</div></div></body></html>`
+ return { from: `${t.senderName} <${t.from}>`, subject, text, html }
+}
+export interface MailBinding {
+ send(message: {
+ from: string
+ to: string
+ subject: string
+ text: string
+ html?: string
+ }): Promise<{ messageId: string }>
+}
+export async function sendMail(
+ db: PlatformD1,
+ binding: MailBinding,
+ kind: MailKind,
+ to: string,
+ variables: Record<string, string>,
+ url?: string,
+ fallback?: string,
+) {
+ if (!binding?.send) throw new Error('Email service unavailable')
+ const { template } = await mailTemplate(db, kind, fallback)
+ const result = await binding.send({
+ ...renderMail(template, variables, url),
+ to,
+ })
+ if (!result?.messageId) throw new Error('Email delivery failed')
+ return result
+}
diff --git a/packages/storage/src/s3-edge.ts b/packages/storage/src/s3-edge.ts
index c8ea9b6c..eaf3c079 100644
--- a/packages/storage/src/s3-edge.ts
+++ b/packages/storage/src/s3-edge.ts
@@ -11,6 +11,9 @@ import {
GetBucketCorsCommand,
ListPartsCommand,
ListMultipartUploadsCommand,
+ ListObjectsV2Command,
+ GetBucketVersioningCommand,
+ ListObjectVersionsCommand,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import { FetchHttpHandler } from '@smithy/fetch-http-handler'
@@ -153,6 +156,89 @@ export function createCloudS3(
etag: r.ETag ?? '',
}
},
+ /** Bounded tenant-prefix cleanup, never a bucket-wide delete. Repeat until empty. */
+ async purgeTenant(siteId: number) {
+ if (!Number.isSafeInteger(siteId) || siteId < 1)
+ throw new Error('Invalid site')
+ const prefix = `chronoframe/${siteId}/`
+ let versioned = false
+ try {
+ const status = await client.send(
+ new GetBucketVersioningCommand({ Bucket }),
+ )
+ versioned = status.Status === 'Enabled' || status.Status === 'Suspended'
+ } catch (error) {
+ // R2 has no object-versioning API. Other providers must explicitly confirm their state.
+ const e = error as {
+ name?: string
+ $metadata?: { httpStatusCode?: number }
+ }
+ if (
+ !/^[a-f0-9]{32}(?:\.(?:eu|fedramp))?\.r2\.cloudflarestorage\.com$/.test(
+ new URL(endpoint).hostname,
+ ) ||
+ !(e.name === 'NotImplemented' || e.$metadata?.httpStatusCode === 501)
+ )
+ throw error
+ }
+ if (versioned) {
+ const versions = await client.send(
+ new ListObjectVersionsCommand({
+ Bucket,
+ Prefix: prefix,
+ MaxKeys: 20,
+ }),
+ )
+ const entries = [
+ ...(versions.Versions ?? []),
+ ...(versions.DeleteMarkers ?? []),
+ ]
+ for (const entry of entries) {
+ if (!entry.Key?.startsWith(prefix) || !entry.VersionId)
+ throw new Error('Invalid version scope')
+ await client.send(
+ new DeleteObjectCommand({
+ Bucket,
+ Key: entry.Key,
+ VersionId: entry.VersionId,
+ }),
+ )
+ }
+ if (entries.length || versions.IsTruncated) return false
+ }
+ const uploads = await client.send(
+ new ListMultipartUploadsCommand({
+ Bucket,
+ Prefix: prefix,
+ MaxUploads: 10,
+ }),
+ )
+ for (const upload of uploads.Uploads ?? []) {
+ if (!upload.Key?.startsWith(prefix) || !upload.UploadId)
+ throw new Error('Invalid multipart scope')
+ await client.send(
+ new AbortMultipartUploadCommand({
+ Bucket,
+ Key: upload.Key,
+ UploadId: upload.UploadId,
+ }),
+ )
+ }
+ const objects = await client.send(
+ new ListObjectsV2Command({ Bucket, Prefix: prefix, MaxKeys: 20 }),
+ )
+ for (const object of objects.Contents ?? []) {
+ if (!object.Key?.startsWith(prefix))
+ throw new Error('Invalid object scope')
+ await client.send(new DeleteObjectCommand({ Bucket, Key: object.Key }))
+ }
+ return !(
+ uploads.Uploads?.length ||
+ uploads.IsTruncated ||
+ objects.Contents?.length ||
+ objects.IsTruncated
+ )
+ },
async remove(key: string) {
await client.send(new DeleteObjectCommand({ Bucket, Key: safeKey(key) }))
},
diff --git a/tests/account-lifecycle-mail.test.ts b/tests/account-lifecycle-mail.test.ts
new file mode 100644
index 00000000..9a4cb603
--- /dev/null
+++ b/tests/account-lifecycle-mail.test.ts
@@ -0,0 +1,753 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readdir, readFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import {
+ DAY,
+ scanAccounts,
+ markAccount,
+ restoreAccount,
+ deliverLifecycleMail,
+ lifecycleSettings,
+ validateLifecycleSettings,
+ deletionDeadline,
+} from '../packages/platform/src/account-lifecycle.ts'
+import { purgeAccounts } from '../packages/platform/src/account-purge.ts'
+import {
+ defaultMailTemplate,
+ renderMail,
+ validateMailTemplate,
+} from '../packages/platform/src/mail.ts'
+import { createAccountAuth } from '../apps/cloud/server/utils/account-auth.ts'
+const require = createRequire(import.meta.url),
+ { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+ )('miniflare')
+async function fixture() {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-26',
+ script: 'export default {fetch(){return new Response("ok")}}',
+ d1Databases: ['DB'],
+ }),
+ ),
+ db = await mf.getD1Database('DB')
+ for (const file of (
+ await readdir(new URL('../packages/platform/migrations/', import.meta.url))
+ )
+ .filter((f) => f.endsWith('.sql'))
+ .sort())
+ for (const sql of (
+ await readFile(
+ new URL('../packages/platform/migrations/' + file, import.meta.url),
+ 'utf8',
+ )
+ )
+ .replace(/^--.*$/gm, '')
+ .split(';')
+ .filter((s) => s.trim()))
+ await db.prepare(sql).run()
+ return { mf, db }
+}
+test('Lifecycle notices, current-login race, restore, retained deadline and retryable external purge', async () => {
+ const { mf, db } = await fixture()
+ try {
+ const now = Date.now(),
+ messages: any[] = [],
+ binding = {
+ send: async (m: any) => {
+ messages.push(m)
+ return { messageId: 'id' }
+ },
+ }
+ await db
+ .prepare('UPDATE platform_lifecycle_settings SET activated_at=?')
+ .bind(now - 200 * DAY)
+ .run()
+ for (const [id, verified, age] of [
+ [1, 0, 7],
+ [2, 1, 83],
+ [3, 1, 90],
+ [4, 1, 10],
+ [5, 0, 11],
+ ])
+ await db
+ .prepare(
+ 'INSERT INTO platform_users(id,email,name,email_verified,created_at,updated_at,last_login_at) VALUES(?,?,?,?,?,?,?)',
+ )
+ .bind(
+ id,
+ `user${id}@example.com`,
+ 'User',
+ verified,
+ now - age * DAY,
+ now - age * DAY,
+ now - age * DAY,
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_auth_sessions(token,user_id,created_at,updated_at,expires_at) VALUES('old',3,?,?,?)",
+ )
+ .bind(now - DAY, now - DAY, now + DAY)
+ .run()
+ await scanAccounts(db, now)
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT COUNT(*) AS n FROM platform_account_deletions')
+ .first()
+ ).n,
+ 1,
+ )
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_auth_sessions WHERE user_id=3',
+ )
+ .first()
+ ).n,
+ 0,
+ )
+ await deliverLifecycleMail(db, binding, 'https://app.chronoframe.art', now)
+ assert.equal(messages.length, 4)
+ assert.ok(
+ messages.every(
+ (m) =>
+ m.from.startsWith('ChronoFrame Cloud <') &&
+ m.html.includes('<!doctype html>') &&
+ m.text.includes('[email protected]'),
+ ),
+ )
+ assert.equal(
+ messages.filter((m) => m.subject.includes('scheduled')).length,
+ 3,
+ )
+ await scanAccounts(db, now)
+ await deliverLifecycleMail(db, binding, 'https://app.chronoframe.art', now)
+ assert.equal(messages.length, 4)
+ // Resolved verification and new login invalidate queued warnings before sending.
+ await scanAccounts(db, now + 4 * DAY)
+ await db
+ .prepare(
+ 'UPDATE platform_users SET email_verified=1,last_login_at=? WHERE id IN(1,2)',
+ )
+ .bind(now + 4 * DAY)
+ .run()
+ const prior = messages.length
+ await deliverLifecycleMail(
+ db,
+ binding,
+ 'https://app.chronoframe.art',
+ now + 4 * DAY,
+ )
+ assert.ok(
+ messages
+ .slice(prior)
+ .every(
+ (m) => !['[email protected]', '[email protected]'].includes(m.to),
+ ),
+ )
+ assert.equal(
+ await markAccount(
+ db,
+ 2,
+ 'Outdated inactivity scan',
+ 'inactive',
+ null,
+ now + 4 * DAY,
+ { login: now - 83 * DAY, verified: 1, settingsRevision: 1 },
+ ),
+ false,
+ )
+ const deletion = await db
+ .prepare('SELECT * FROM platform_account_deletions WHERE user_id=3')
+ .first()
+ await db
+ .prepare(
+ 'UPDATE platform_lifecycle_settings SET retention_days=1,revision=revision+1',
+ )
+ .run()
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT purge_at FROM platform_account_deletions WHERE user_id=3',
+ )
+ .first()
+ ).purge_at,
+ deletion.purge_at,
+ )
+ assert.equal(
+ await restoreAccount(
+ db,
+ 3,
+ deletion.revision,
+ 4,
+ 'Customer requested restoration',
+ now + DAY,
+ ),
+ true,
+ )
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT suspended FROM platform_account_controls WHERE user_id=3',
+ )
+ .first()
+ ).suspended,
+ 0,
+ )
+ // Existing suspension is retained when restoring a deletion mark.
+ await db
+ .prepare(
+ "INSERT INTO platform_account_controls(user_id,suspended,public_reason) VALUES(4,1,'Existing suspension')",
+ )
+ .run()
+ assert.equal(
+ await markAccount(db, 4, 'Manual cleanup request', 'manual', 2, now),
+ true,
+ )
+ const d4 = await db
+ .prepare('SELECT * FROM platform_account_deletions WHERE user_id=4')
+ .first()
+ assert.equal(
+ await restoreAccount(
+ db,
+ 4,
+ d4.revision,
+ 2,
+ 'Restore original account status',
+ now + 100,
+ ),
+ true,
+ )
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT public_reason FROM platform_account_controls WHERE user_id=4',
+ )
+ .first()
+ ).public_reason,
+ 'Existing suspension',
+ )
+ // Clean two owned sites; retain shared spaces owned by another user and their files.
+ await db.prepare('DELETE FROM platform_account_deletions').run()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspaces(id,name,owner_user_id) VALUES(1,'Owned',3),(2,'Other',4)",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_sites(id,workspace_id,name,slug,published) VALUES(1,1,'Site','mine',1),(2,2,'Other','other',1)",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_memberships VALUES(3,1,'admin'),(3,2,'member'),(4,2,'admin')",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO cloud_storage_connections(site_id,id,current_revision) VALUES(1,'s3',1)",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO cloud_storage_versions VALUES(1,'s3',1,'{}','encrypted')",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO cloud_photos(site_id,id,source_version,title) VALUES(1,'p','1','P'),(2,'p','1','Other')",
+ )
+ .run()
+ await db
+ .prepare("INSERT INTO cloud_albums(site_id,id,title) VALUES(1,'a','A')")
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO cloud_album_photos(site_id,album_id,photo_id) VALUES(1,'a','p')",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_domains(hostname,site_id,verified,active) VALUES('mine.example.com',1,1,1)",
+ )
+ .run()
+ assert.equal(
+ await markAccount(
+ db,
+ 3,
+ 'Manual cleanup after recovery',
+ 'manual',
+ 2,
+ now,
+ ),
+ true,
+ )
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT suspended FROM platform_sites WHERE id=1')
+ .first()
+ ).suspended,
+ 1,
+ )
+ let domainReady = false,
+ storageReady = false,
+ storageCalls = 0
+ const cleanup = {
+ domains: async () => domainReady,
+ storage: async () => {
+ storageCalls++
+ if (!storageReady) throw new Error('Provider unavailable')
+ return true
+ },
+ }
+ await purgeAccounts(db, cleanup, now + DAY - 1)
+ assert.equal(storageCalls, 0)
+ await purgeAccounts(db, cleanup, now + DAY)
+ assert.equal(storageCalls, 0)
+ domainReady = true
+ await purgeAccounts(db, cleanup, now + DAY + 60000)
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT error FROM platform_account_deletions WHERE user_id=3',
+ )
+ .first()
+ ).error,
+ 'resource_cleanup_failed',
+ )
+ assert.ok(
+ await db.prepare('SELECT id FROM platform_users WHERE id=3').first(),
+ )
+ assert.ok(await db.prepare('SELECT * FROM cloud_storage_versions').first())
+ assert.equal(
+ await restoreAccount(db, 3, 1, 2, 'Too late to restore', now + 2 * DAY),
+ false,
+ )
+ storageReady = true
+ await purgeAccounts(db, cleanup, now + 2 * DAY)
+ await purgeAccounts(db, cleanup, now + 2 * DAY + 60000)
+ assert.equal(
+ await db.prepare('SELECT id FROM platform_users WHERE id=3').first(),
+ null,
+ )
+ assert.equal(
+ await db.prepare('SELECT id FROM platform_workspaces WHERE id=1').first(),
+ null,
+ )
+ assert.ok(
+ await db.prepare('SELECT id FROM cloud_photos WHERE site_id=2').first(),
+ )
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_memberships WHERE user_id=3',
+ )
+ .first()
+ ).n,
+ 0,
+ )
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_mail_outbox WHERE user_id=3',
+ )
+ .first()
+ ).n,
+ 0,
+ )
+ } finally {
+ await mf.dispose()
+ }
+})
+test('Templates escape content, validate headers, preserve auth requirements and retry notifications', async () => {
+ const template = defaultMailTemplate('verification'),
+ m = renderMail(template, {
+ code: '<script>123456</script>',
+ purpose: 'verify',
+ minutes: '10',
+ })
+ assert.ok(m.html.includes('&lt;script&gt;'))
+ assert.ok(!m.html.includes('<script>'))
+ assert.match(m.text, /123456/)
+ assert.throws(() =>
+ validateMailTemplate({
+ ...template,
+ }),
+ )
+ assert.throws(() =>
+ validateMailTemplate({ ...template, body: '{{unknown}}' }),
+ )
+ assert.throws(() => renderMail(template, {}, 'javascript:alert(1)'))
+ assert.throws(() =>
+ validateLifecycleSettings({
+ enabled: true,
+ unverifiedDays: 14,
+ inactiveDays: 90,
+ retentionDays: 15,
+ warningDays: [14, 3],
+ }),
+ )
+ const { mf, db } = await fixture()
+ try {
+ const now = Date.now()
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,created_at,last_login_at,email_verified) VALUES(1,'[email protected]',?,?,1)",
+ )
+ .bind(now, now)
+ .run()
+ await markAccount(db, 1, 'Manual deletion example', 'manual', null, now)
+ let calls = 0
+ const failing = {
+ send: async () => {
+ calls++
+ throw new Error('SMTP secret must not be persisted')
+ },
+ }
+ await deliverLifecycleMail(db, failing, 'https://app.chronoframe.art', now)
+ assert.equal(calls, 1)
+ assert.equal(
+ (await db.prepare('SELECT error FROM platform_mail_outbox').first())
+ .error,
+ 'email_delivery_failed',
+ )
+ await deliverLifecycleMail(
+ db,
+ failing,
+ 'https://app.chronoframe.art',
+ now + 59999,
+ )
+ assert.equal(calls, 1)
+ const auth = createAccountAuth(
+ db,
+ {
+ portalOrigin: 'https://app.chronoframe.art',
+ secret: 'secret'.repeat(8),
+ emailFrom: '[email protected]',
+ },
+ failing,
+ )
+ // Live suspension reason blocks creating a session, including all auth methods.
+ const options = (
+ await import('../apps/cloud/server/utils/account-auth.ts')
+ ).accountAuthOptions(
+ db as any,
+ {
+ portalOrigin: 'https://app.chronoframe.art',
+ secret: 'secret'.repeat(8),
+ emailFrom: '',
+ },
+ failing,
+ )
+ await assert.rejects(
+ options.databaseHooks.session.create.before({ userId: '1' } as any),
+ /Account deleted/,
+ )
+ assert.ok(auth)
+ const settings = await lifecycleSettings(db)
+ assert.ok(
+ deletionDeadline(
+ { email_verified: 0, created_at: now - 100 * DAY },
+ settings,
+ ) >=
+ settings.activatedAt + 7 * DAY,
+ )
+ } finally {
+ await mf.dispose()
+ }
+})
+test('S3 cleanup lists and deletes only the exact tenant prefix, including unfinished multiparts', async () => {
+ const { createCloudS3 } = await import('../packages/storage/src/s3-edge.ts')
+ let objects = true,
+ multipart = true
+ const removed: string[] = [],
+ aborted: string[] = []
+ const s3 = createCloudS3(
+ {
+ endpoint:
+ 'https://0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com',
+ region: 'auto',
+ bucket: 'photos',
+ accessKeyId: 'fake',
+ secretAccessKey: 'fake',
+ },
+ {
+ fetch: (async (input, init) => {
+ const url = new URL(
+ input instanceof Request ? input.url : String(input),
+ ),
+ method =
+ init?.method ?? (input instanceof Request ? input.method : 'GET')
+ if (url.searchParams.has('versioning'))
+ return new Response('<VersioningConfiguration/>', {
+ headers: { 'content-type': 'application/xml' },
+ })
+ if (url.searchParams.has('uploads')) {
+ assert.equal(url.searchParams.get('prefix'), 'chronoframe/7/')
+ return new Response(
+ `<ListMultipartUploadsResult>${multipart ? '<Upload><Key>chronoframe/7/pending</Key><UploadId>pending-id</UploadId></Upload>' : ''}<IsTruncated>false</IsTruncated></ListMultipartUploadsResult>`,
+ { headers: { 'content-type': 'application/xml' } },
+ )
+ }
+ if (url.searchParams.has('list-type')) {
+ assert.equal(url.searchParams.get('prefix'), 'chronoframe/7/')
+ return new Response(
+ `<ListBucketResult>${objects ? '<Contents><Key>chronoframe/7/original.jpg</Key><Size>10</Size></Contents>' : ''}<IsTruncated>false</IsTruncated></ListBucketResult>`,
+ { headers: { 'content-type': 'application/xml' } },
+ )
+ }
+ assert.equal(method, 'DELETE')
+ assert.ok(url.pathname.startsWith('/photos/chronoframe/7/'))
+ if (url.searchParams.has('uploadId')) {
+ aborted.push(url.pathname)
+ multipart = false
+ } else {
+ removed.push(url.pathname)
+ objects = false
+ }
+ return new Response(null, { status: 204 })
+ }) as typeof fetch,
+ },
+ )
+ assert.equal(await s3.purgeTenant(7), false)
+ assert.equal(await s3.purgeTenant(7), true)
+ assert.equal(removed.length, 1)
+ assert.equal(aborted.length, 1)
+ await assert.rejects(s3.purgeTenant(0))
+})
+test('Subscription exemptions match live/expired history, sources, tiers and combinations; manual marks remain possible', async () => {
+ const { accountExemption, validateExemptions, DEFAULT_EXEMPTIONS } =
+ await import('../packages/platform/src/lifecycle-exemptions.ts')
+ const { mf, db } = await fixture()
+ try {
+ const now = Date.now(),
+ policy = (
+ await db
+ .prepare("SELECT policy_json FROM platform_plans WHERE id='free'")
+ .first()
+ ).policy_json
+ await db
+ .prepare('UPDATE platform_lifecycle_settings SET activated_at=?')
+ .bind(now - 200 * DAY)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_plans(id,name,policy_json) VALUES('pro','Pro',?),('trial','Trial',?)",
+ )
+ .bind(policy, policy)
+ .run()
+ for (let id = 1; id <= 4; id++) {
+ await db
+ .prepare(
+ 'INSERT INTO platform_users(id,email,created_at,last_login_at,email_verified) VALUES(?,?,?,?,1)',
+ )
+ .bind(id, `exempt${id}@example.com`, now - 100 * DAY, now - 100 * DAY)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspaces(id,name,owner_user_id) VALUES(?,'Space',?)",
+ )
+ .bind(id, id)
+ .run()
+ }
+ await db
+ .prepare(
+ "INSERT INTO platform_workspace_plans(workspace_id,plan_id,source,starts_at,expires_at) VALUES(1,'pro','activation',?,?),(2,'pro','manual',?,?),(3,'trial','promotion',?,?),(4,'free','default',?,NULL)",
+ )
+ .bind(
+ now - DAY,
+ now + DAY,
+ now - 20 * DAY,
+ now - DAY,
+ now - DAY,
+ now + DAY,
+ now - 100 * DAY,
+ )
+ .run()
+ assert.equal(await accountExemption(db, 1, DEFAULT_EXEMPTIONS, now), true)
+ assert.equal(
+ await accountExemption(db, 1, DEFAULT_EXEMPTIONS, now + DAY),
+ false,
+ )
+ assert.equal(await accountExemption(db, 2, DEFAULT_EXEMPTIONS, now), false)
+ assert.equal(await accountExemption(db, 3, DEFAULT_EXEMPTIONS, now), false)
+ assert.equal(await accountExemption(db, 4, DEFAULT_EXEMPTIONS, now), false)
+ const ever = validateExemptions({
+ enabled: true,
+ match: 'any',
+ rules: [
+ {
+ kind: 'ever-subscribed',
+ sources: ['manual', 'activation'],
+ planIds: ['pro'],
+ },
+ ],
+ })
+ assert.equal(await accountExemption(db, 2, ever, now), true)
+ // Prior snapshots survive replacement with the expiry default.
+ await db
+ .prepare(
+ "INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) VALUES('history',2,'expired',?, ?,?)",
+ )
+ .bind(
+ JSON.stringify({ plan_id: 'pro', source: 'manual' }),
+ JSON.stringify({ planId: 'free', source: 'expired_default' }),
+ now,
+ )
+ .run()
+ await db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='free',source='expired_default' WHERE workspace_id=2",
+ )
+ .run()
+ assert.equal(await accountExemption(db, 2, ever, now), true)
+ const all = validateExemptions({
+ enabled: true,
+ match: 'all',
+ rules: [
+ ...ever.rules,
+ {
+ kind: 'active-subscription',
+ sources: ['activation'],
+ planIds: ['pro'],
+ },
+ ],
+ })
+ assert.equal(await accountExemption(db, 1, all, now), true)
+ assert.equal(await accountExemption(db, 2, all, now), false)
+ const trial = validateExemptions({
+ enabled: true,
+ match: 'any',
+ rules: [
+ {
+ kind: 'active-subscription',
+ sources: ['promotion'],
+ planIds: ['trial'],
+ },
+ ],
+ })
+ assert.equal(await accountExemption(db, 3, trial, now), true)
+ await db
+ .prepare("INSERT INTO platform_memberships VALUES(4,1,'member')")
+ .run()
+ assert.equal(await accountExemption(db, 4, DEFAULT_EXEMPTIONS, now), false)
+ await scanAccounts(db, now)
+ assert.equal(
+ await db
+ .prepare(
+ 'SELECT user_id FROM platform_account_deletions WHERE user_id=1',
+ )
+ .first(),
+ null,
+ )
+ assert.ok(
+ await db
+ .prepare(
+ 'SELECT user_id FROM platform_account_deletions WHERE user_id=2',
+ )
+ .first(),
+ )
+ await scanAccounts(db, now + DAY)
+ assert.equal(
+ await db
+ .prepare(
+ 'SELECT user_id FROM platform_account_deletions WHERE user_id=1',
+ )
+ .first(),
+ null,
+ )
+ const transitioned = await db
+ .prepare(
+ 'SELECT lifecycle_grace_until,lifecycle_was_exempt FROM platform_users WHERE id=1',
+ )
+ .first()
+ assert.equal(transitioned.lifecycle_grace_until, now + 8 * DAY)
+ assert.equal(transitioned.lifecycle_was_exempt, 0)
+ assert.equal(
+ await markAccount(
+ db,
+ 1,
+ 'Manual removal bypasses automatic exemptions',
+ 'manual',
+ 4,
+ now,
+ ),
+ true,
+ )
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,created_at,last_login_at,email_verified) VALUES(5,'[email protected]',?,?,1)",
+ )
+ .bind(now - 100 * DAY, now - 100 * DAY)
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspaces(id,name,owner_user_id) VALUES(5,'Concurrent',5)",
+ )
+ .run()
+ const raced = {
+ prepare: db.prepare.bind(db),
+ batch: async (statements: any[]) => {
+ await db.batch([
+ db
+ .prepare(
+ "INSERT INTO platform_workspace_plans(workspace_id,plan_id,source,starts_at,expires_at) VALUES(5,'pro','activation',?,?)",
+ )
+ .bind(now, now + DAY),
+ db.prepare(
+ 'UPDATE platform_policy_epoch SET revision=revision+1 WHERE id=1',
+ ),
+ ])
+ return db.batch(statements)
+ },
+ }
+ assert.equal(
+ await markAccount(
+ raced as any,
+ 5,
+ 'Stale scan racing an upgrade',
+ 'inactive',
+ null,
+ now,
+ { login: now - 100 * DAY, verified: 1, settingsRevision: 1 },
+ ),
+ false,
+ )
+ assert.equal(
+ await db
+ .prepare(
+ 'SELECT user_id FROM platform_account_deletions WHERE user_id=5',
+ )
+ .first(),
+ null,
+ )
+ assert.throws(() =>
+ validateExemptions({ enabled: true, match: 'any', rules: [] }),
+ )
+ assert.throws(() =>
+ validateExemptions({
+ enabled: true,
+ match: 'any',
+ rules: [
+ { kind: 'ever-subscribed', sources: ['arbitrary'], planIds: [] },
+ ],
+ }),
+ )
+ } finally {
+ await mf.dispose()
+ }
+})