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 local portal development setup with seeded account and mail capture

Timothy Yin6abac131a7ce
diff --git a/apps/cloud/README.md b/apps/cloud/README.md
index 78825555..18e28b33 100644
--- a/apps/cloud/README.md
+++ b/apps/cloud/README.md
@@ -41,6 +41,39 @@ Images ship locally so core UI has no runtime image-host dependency.
## Running and deployment boundaries
+### Local portal development
+
+From the repository root:
+
+```powershell
+pnpm install --frozen-lockfile
+pnpm build:deps
+pnpm setup:cloud
+pnpm dev:cloud
+```
+
+Open `http://localhost:3001/signin`. The setup command creates missing app-local
+`.env` values, applies all platform migrations to local D1, and seeds a verified
+`[email protected]` account, a workspace, a Free subscription and an
+unpublished sample site. Read the generated password in
+`apps/cloud/.data/local-account.json`. Re-running setup applies new migrations
+without resetting existing credentials, edited site settings or other local data.
+Existing `.env` values are preserved; ensure `NUXT_PLATFORM_PORTAL_ORIGIN` is
+`http://localhost:3001` and session/platform secrets contain at least 32 characters.
+Restart the development server after changing `.env`.
+
+During `dev:cloud`, a development-only Nitro plugin supplies local D1 and captures
+email in the terminal and `apps/cloud/.data/mail.jsonl`, including verification
+codes and reset links. No email is delivered. Database files live under
+`apps/cloud/.wrangler/state/v3`; both directories and `.env` are ignored by Git.
+`wrangler.local.json` contains only a dummy local database ID, with remote bindings
+disabled. The plugin is excluded from production builds.
+
+This supports account, workspace, site settings and billing UI development.
+The sample site has no photos or configured object storage. Uploads, processing,
+public domain routing and live payments require their respective services;
+setup does not provision them or connect to production.
+
Run `pnpm build:deps` followed by `pnpm dev:cloud` or `pnpm build:cloud` at the
repository root. The launcher uses the Cloud app directory and its optional `.env`,
never the Self-hosted root `.env`. Generated output is local to this app.
diff --git a/apps/cloud/nuxt.config.ts b/apps/cloud/nuxt.config.ts
index 4fd97250..6d069c6a 100644
--- a/apps/cloud/nuxt.config.ts
+++ b/apps/cloud/nuxt.config.ts
@@ -1,6 +1,7 @@
import { CLOUD_CAPABILITIES } from '../../packages/contracts/src/entry'
import { sharedUi } from '../nuxt.shared'
import { fileURLToPath } from 'node:url'
+import { mkdirSync } from 'node:fs'
const galleryPages = fileURLToPath(
new URL('../../packages/gallery/app/pages/', import.meta.url),
)
@@ -70,6 +71,37 @@ export default defineNuxtConfig({
},
css: ['~/assets/console-tailwind.css', '~/assets/cloud.css'],
hooks: {
+ 'nitro:config'(config) {
+ if (config.dev) {
+ const temporary = fileURLToPath(
+ new URL('./.wrangler/tmp', import.meta.url),
+ )
+ if (process.platform === 'win32') {
+ mkdirSync(temporary, { recursive: true })
+ process.env.TMP = temporary
+ process.env.TEMP = temporary
+ }
+ config.cloudflare ||= {}
+ config.cloudflare.dev = {
+ configPath: fileURLToPath(
+ new URL('./wrangler.local.json', import.meta.url),
+ ),
+ persistDir: fileURLToPath(
+ new URL('./.wrangler/state/v3', import.meta.url),
+ ),
+ }
+ config.runtimeConfig ||= {}
+ config.runtimeConfig.cloudLocalMailDirectory = fileURLToPath(
+ new URL('./.data', import.meta.url),
+ )
+ config.plugins ||= []
+ config.plugins.push(
+ fileURLToPath(
+ new URL('../../scripts/cloud-local-runtime.ts', import.meta.url),
+ ),
+ )
+ }
+ },
'pages:extend'(pages) {
// The portal shares console capabilities, not the public gallery route tree.
for (let index = pages.length - 1; index >= 0; index--) {
diff --git a/apps/cloud/server/utils/account-auth.ts b/apps/cloud/server/utils/account-auth.ts
index 0965d0b6..d899e2e2 100644
--- a/apps/cloud/server/utils/account-auth.ts
+++ b/apps/cloud/server/utils/account-auth.ts
@@ -12,6 +12,7 @@ import { passkey } from '@better-auth/passkey'
import type { PlatformEmailBinding } from '../../../shared/platform/email.ts'
export interface AccountAuthConfig {
+ localDevelopment?: boolean
portalOrigin: string
secret: string
emailFrom: string
@@ -201,6 +202,8 @@ export function accountAuthOptions(
user.email,
{ name: user.name, minutes: '30' },
url,
+ undefined,
+ config.localDevelopment === true,
)
},
},
diff --git a/apps/cloud/server/utils/cloud-account.ts b/apps/cloud/server/utils/cloud-account.ts
index aa07b7ec..7e3ad7bc 100644
--- a/apps/cloud/server/utils/cloud-account.ts
+++ b/apps/cloud/server/utils/cloud-account.ts
@@ -12,7 +12,7 @@ export function cloudAccount(event: H3Event) {
| undefined
event.context.cloudAccountAuth = createAccountAuth(
platformDatabase(event) as unknown as BetterAuthOptions['database'],
- config,
+ { ...config, localDevelopment: import.meta.dev },
event.context.cloudflare?.env?.EMAIL as PlatformEmailBinding,
execution ? (task) => execution.waitUntil(task) : undefined,
)
diff --git a/apps/cloud/wrangler.local.json b/apps/cloud/wrangler.local.json
new file mode 100644
index 00000000..fdc0a62d
--- /dev/null
+++ b/apps/cloud/wrangler.local.json
@@ -0,0 +1,12 @@
+{
+ "name": "chronoframe-cloud-local",
+ "compatibility_date": "2026-10-22",
+ "d1_databases": [
+ {
+ "binding": "DB",
+ "database_name": "chronoframe-cloud-local",
+ "database_id": "00000000-0000-0000-0000-000000000001",
+ "remote": false
+ }
+ ]
+}
diff --git a/package.json b/package.json
index bf1bb7ef..de71847f 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"check:ui": "node scripts/check-ui-boundaries.mjs",
"prepare": "node scripts/self-hosted.mjs prepare",
"dev:cloud": "node scripts/saas-entry.mjs cloud dev",
+ "setup:cloud": "node scripts/setup-cloud-local.mjs",
"build:cloud": "node scripts/saas-entry.mjs cloud build",
"prepare:cloud": "node scripts/saas-entry.mjs cloud prepare",
"dev:site": "node scripts/saas-entry.mjs site dev",
diff --git a/packages/platform/src/mail.ts b/packages/platform/src/mail.ts
index 2f6c1e2a..eee04620 100644
--- a/packages/platform/src/mail.ts
+++ b/packages/platform/src/mail.ts
@@ -167,11 +167,32 @@ export function renderMail(
template: MailTemplate,
variables: Record<string, string>,
url?: string,
+ allowLocalLinks = false,
) {
const t = validateMailTemplate(template),
fill = (s: string) =>
s.replace(/{{\s*([^{}]+?)\s*}}/g, (_, k) => variables[k] ?? '')
- if (url && !/^(https:\/\/|mailto:support@chronoframe\.art$)/.test(url))
+ const localLink =
+ url &&
+ allowLocalLinks &&
+ (() => {
+ try {
+ const parsed = new URL(url)
+ return (
+ parsed.protocol === 'http:' &&
+ parsed.hostname === 'localhost' &&
+ !parsed.username &&
+ !parsed.password
+ )
+ } catch {
+ return false
+ }
+ })()
+ if (
+ url &&
+ !localLink &&
+ !/^(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),
@@ -201,11 +222,12 @@ export async function sendMail(
variables: Record<string, string>,
url?: string,
fallback?: string,
+ allowLocalLinks = false,
) {
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),
+ ...renderMail(template, variables, url, allowLocalLinks),
to,
})
if (!result?.messageId) throw new Error('Email delivery failed')
diff --git a/scripts/cloud-local-runtime.ts b/scripts/cloud-local-runtime.ts
new file mode 100644
index 00000000..fd5e430e
--- /dev/null
+++ b/scripts/cloud-local-runtime.ts
@@ -0,0 +1,32 @@
+import { randomUUID } from 'node:crypto'
+import { appendFile, mkdir } from 'node:fs/promises'
+import { join } from 'node:path'
+
+// Registered only by Nuxt's development configuration, never in a Worker build.
+export default defineNitroPlugin(async (app) => {
+ const mailbox = String(useRuntimeConfig().cloudLocalMailDirectory)
+ await mkdir(mailbox, { recursive: true })
+ const EMAIL = {
+ async send(message: { to: string; subject: string; text: string }) {
+ const messageId = randomUUID()
+ await appendFile(
+ join(mailbox, 'mail.jsonl'),
+ JSON.stringify({
+ ...message,
+ messageId,
+ createdAt: new Date().toISOString(),
+ }) + '\n',
+ )
+ console.info(
+ `[Cloud local mail] ${message.to}: ${message.subject}\n${message.text}`,
+ )
+ return { messageId }
+ },
+ }
+ app.hooks.hook('request', (event) => {
+ event.context.cloudflare = {
+ ...event.context.cloudflare,
+ env: { ...event.context.cloudflare?.env, EMAIL },
+ }
+ })
+})
diff --git a/scripts/cloud-local.mjs b/scripts/cloud-local.mjs
new file mode 100644
index 00000000..e67089ac
--- /dev/null
+++ b/scripts/cloud-local.mjs
@@ -0,0 +1,29 @@
+import { fileURLToPath } from 'node:url'
+import { mkdir } from 'node:fs/promises'
+import { join } from 'node:path'
+
+export const cloudApp = fileURLToPath(
+ new URL('../apps/cloud/', import.meta.url),
+)
+export const cloudLocalState = fileURLToPath(
+ new URL('../apps/cloud/.wrangler/state/v3', import.meta.url),
+)
+
+export async function localCloudPlatform() {
+ // Workerd's Windows sandbox needs a writable temporary directory in the project.
+ if (process.platform === 'win32') {
+ const temporary = join(cloudApp, '.wrangler', 'tmp')
+ await mkdir(temporary, { recursive: true })
+ process.env.TMP = temporary
+ process.env.TEMP = temporary
+ }
+ const { getPlatformProxy } = await import('wrangler')
+ return getPlatformProxy({
+ configPath: fileURLToPath(
+ new URL('../apps/cloud/wrangler.local.json', import.meta.url),
+ ),
+ persist: { path: cloudLocalState },
+ remoteBindings: false,
+ envFiles: [],
+ })
+}
diff --git a/scripts/setup-cloud-local.mjs b/scripts/setup-cloud-local.mjs
new file mode 100644
index 00000000..91604564
--- /dev/null
+++ b/scripts/setup-cloud-local.mjs
@@ -0,0 +1,125 @@
+import { randomBytes, createHash } from 'node:crypto'
+import { readFile, writeFile, mkdir, readdir } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { unstable_splitSqlQuery as splitSqlQuery } from 'wrangler'
+import { cloudApp, localCloudPlatform } from './cloud-local.mjs'
+
+const envPath = join(cloudApp, '.env')
+let env
+try {
+ env = await readFile(envPath, 'utf8')
+} catch (error) {
+ if (error.code !== 'ENOENT') throw error
+ env = ''
+}
+const defaults = {
+ NUXT_PLATFORM_PORTAL_ORIGIN: 'http://localhost:3001',
+ NUXT_SESSION_PASSWORD: randomBytes(32).toString('hex'),
+ NUXT_PLATFORM_SECRET: randomBytes(32).toString('hex'),
+ NUXT_PLATFORM_STORAGE_SECRET: randomBytes(32).toString('hex'),
+ NUXT_PLATFORM_EMAIL_FROM: '[email protected]',
+}
+for (const [key, value] of Object.entries(defaults)) {
+ if (!new RegExp(`^\\s*${key}\\s*=`, 'm').test(env))
+ env += `\n${key}=${value}\n`
+}
+await writeFile(envPath, env)
+await mkdir(join(cloudApp, '.data'), { recursive: true })
+const credentialsPath = join(cloudApp, '.data', 'local-account.json')
+let credentials
+try {
+ credentials = JSON.parse(await readFile(credentialsPath, 'utf8'))
+} catch (error) {
+ if (error.code !== 'ENOENT') throw error
+ credentials = {
+ email: '[email protected]',
+ password: randomBytes(24).toString('base64url'),
+ }
+ await writeFile(
+ credentialsPath,
+ JSON.stringify(credentials, null, 2) + '\n',
+ { mode: 0o600 },
+ )
+}
+const platform = await localCloudPlatform()
+try {
+ const db = platform.env.DB
+ await db
+ .prepare(
+ 'CREATE TABLE IF NOT EXISTS cloud_local_migrations (name TEXT PRIMARY KEY, checksum TEXT NOT NULL)',
+ )
+ .run()
+ const directory = fileURLToPath(
+ new URL('../packages/platform/migrations/', import.meta.url),
+ )
+ for (const name of (await readdir(directory))
+ .filter((name) => name.endsWith('.sql'))
+ .sort()) {
+ const sql = await readFile(join(directory, name), 'utf8')
+ const checksum = createHash('sha256').update(sql).digest('hex')
+ const applied = await db
+ .prepare('SELECT checksum FROM cloud_local_migrations WHERE name=?')
+ .bind(name)
+ .first()
+ if (applied) {
+ if (applied.checksum !== checksum)
+ throw new Error(`Applied migration changed: ${name}`)
+ continue
+ }
+ await db.batch([
+ ...splitSqlQuery(sql).map((query) => db.prepare(query)),
+ db
+ .prepare(
+ 'INSERT INTO cloud_local_migrations(name,checksum) VALUES(?,?)',
+ )
+ .bind(name, checksum),
+ ])
+ console.info(`Applied ${name}`)
+ }
+ const require = createRequire(join(cloudApp, 'package.json'))
+ const { hashPassword } = await import(
+ pathToFileURL(require.resolve('better-auth/crypto')).href
+ )
+ const now = Date.now()
+ const password = await hashPassword(credentials.password)
+ await db.batch([
+ db
+ .prepare(
+ 'INSERT INTO platform_users(email,name,email_verified,created_at,updated_at,last_login_at) VALUES(?,?,1,?,?,?) ON CONFLICT(email) DO NOTHING',
+ )
+ .bind(credentials.email, 'Local Developer', now, now, now),
+ db
+ .prepare(`INSERT INTO platform_accounts(account_id,provider_id,user_id,password,created_at,updated_at)
+ SELECT CAST(id AS TEXT),'credential',id,?,?,? FROM platform_users WHERE email=?
+ ON CONFLICT(provider_id,account_id) DO NOTHING`)
+ .bind(password, now, now, credentials.email),
+ db
+ .prepare(`INSERT INTO platform_workspaces(name,owner_user_id,created_at)
+ SELECT 'Local Studio',id,? FROM platform_users WHERE email=?
+ ON CONFLICT(owner_user_id) DO NOTHING`)
+ .bind(now, credentials.email),
+ db
+ .prepare(`INSERT INTO platform_memberships(user_id,workspace_id,role)
+ SELECT owner_user_id,id,'admin' FROM platform_workspaces WHERE owner_user_id=(SELECT id FROM platform_users WHERE email=?)
+ ON CONFLICT(user_id,workspace_id) DO NOTHING`)
+ .bind(credentials.email),
+ db
+ .prepare(`INSERT INTO platform_workspace_plans(workspace_id,plan_id,starts_at,source)
+ SELECT id,'free',?,'default' FROM platform_workspaces WHERE owner_user_id=(SELECT id FROM platform_users WHERE email=?)
+ ON CONFLICT(workspace_id) DO NOTHING`)
+ .bind(now, credentials.email),
+ db
+ .prepare(`INSERT INTO platform_sites(workspace_id,name,slug,created_at,provision_key,gallery_title,gallery_author)
+ SELECT id,'Local Gallery','local-gallery',?,'local-demo','Local Gallery','Local Developer'
+ FROM platform_workspaces WHERE owner_user_id=(SELECT id FROM platform_users WHERE email=?)
+ ON CONFLICT(workspace_id,provision_key) DO NOTHING`)
+ .bind(now, credentials.email),
+ ])
+ console.info(
+ `Local Cloud ready. Account: ${credentials.email}\nCredentials: ${credentialsPath}\nRun pnpm dev:cloud, then open http://localhost:3001/signin`,
+ )
+} finally {
+ await platform.dispose()
+}
diff --git a/tests/account-lifecycle-mail.test.ts b/tests/account-lifecycle-mail.test.ts
index 17c4abc4..badaaa89 100644
--- a/tests/account-lifecycle-mail.test.ts
+++ b/tests/account-lifecycle-mail.test.ts
@@ -465,6 +465,19 @@ test('Templates escape content, validate headers, preserve auth requirements and
validateMailTemplate({ ...template, body: '{{unknown}}' }),
)
assert.throws(() => renderMail(template, {}, 'javascript:alert(1)'))
+ assert.throws(() =>
+ renderMail(template, {}, 'http://localhost:3001/reset-password'),
+ )
+ assert.doesNotThrow(() =>
+ renderMail(template, {}, 'http://localhost:3001/reset-password', true),
+ )
+ for (const url of [
+ 'http://example.com/reset',
+ 'http://localhost.example.com/reset',
+ 'http://user@localhost/reset',
+ 'javascript:alert(1)',
+ ])
+ assert.throws(() => renderMail(template, {}, url, true))
assert.throws(() =>
validateLifecycleSettings({
enabled: true,