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): unify account authentication and security with Better Auth

Timothy Yin317ca3227c3f
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index a7bbb31e..51eb7d47 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -1016,10 +1016,119 @@
min-width: 0;
}
@media (max-width: 380px) {
- .cf-marketing-nav > .cf-button:not(.cf-button-icon) {
- display: none;
+ .cf-marketing-nav {
+ gap: 4px;
}
.cf-hero-title {
font-size: clamp(44px, 15vw, 56px);
}
}
+
+/* Account controls share the same surface, spacing and focus language. */
+.cf-brand-edition {
+ font-size: 0.78em;
+ font-weight: 500;
+ opacity: 0.8;
+}
+.cf-marketing-header {
+ height: auto;
+ min-height: 76px;
+ padding-block: 18px;
+ gap: 20px;
+}
+.cf-marketing-nav {
+ gap: 18px;
+}
+.cf-auth-tabs,
+.cf-security-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-block: 20px;
+}
+.cf-auth-form select {
+ width: 100%;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--card);
+ color: inherit;
+ font: inherit;
+}
+.cf-security-card {
+ padding: clamp(20px, 4vw, 32px);
+ margin-block: 20px;
+}
+.cf-security-card h2 {
+ margin: 0 0 8px;
+ font-size: 19px;
+}
+.cf-security-card p {
+ color: var(--muted-foreground);
+ line-height: 1.7;
+}
+.cf-security-card form {
+ display: grid;
+ gap: 12px;
+ max-width: 440px;
+ margin-block: 20px;
+}
+.cf-security-card label {
+ display: block;
+ font-size: 14px;
+ margin-block: 12px 8px;
+}
+.cf-security-card > .cf-input {
+ max-width: 440px;
+}
+.cf-totp-setup {
+ margin-block: 24px;
+}
+.cf-totp-setup img {
+ border-radius: 12px;
+ background: white;
+}
+.cf-secret-value {
+ overflow-wrap: anywhere;
+ font-family: monospace;
+}
+.cf-recovery-codes {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+ padding: 16px;
+ list-style: none;
+}
+.cf-passkey-list {
+ list-style: none;
+ padding: 0;
+}
+.cf-passkey-list li {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding-block: 16px;
+ border-top: 1px solid var(--border);
+}
+@media (max-width: 600px) {
+ .cf-marketing-header {
+ flex-wrap: wrap;
+ gap: 14px;
+ }
+ .cf-marketing-nav {
+ justify-content: flex-end;
+ flex: 1;
+ gap: 6px;
+ }
+ .cf-marketing-nav .cf-button {
+ padding-inline: 10px;
+ }
+ .cf-portal-header {
+ flex-wrap: wrap;
+ gap: 12px;
+ }
+ .cf-recovery-codes {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/apps/cloud/app/components/CloudAuthLayout.vue b/apps/cloud/app/components/CloudAuthLayout.vue
new file mode 100644
index 00000000..dffabeb0
--- /dev/null
+++ b/apps/cloud/app/components/CloudAuthLayout.vue
@@ -0,0 +1,49 @@
+<script setup lang="ts">
+import { ArrowLeft } from 'lucide-vue-next'
+const links = useCloudLinks()
+</script>
+<template>
+ <div class="cf-auth">
+ <aside
+ class="cf-auth-visual"
+ aria-label="About ChronoFrame Cloud"
+ >
+ <CloudBrand
+ cloud
+ light
+ />
+ <div>
+ <div class="cf-auth-quote">
+ <h2>A little space.<br />A different perspective.</h2>
+ <p>Your photographs deserve a home that feels like you.</p>
+ </div>
+ <p class="cf-auth-caption">
+ CHRONOFRAME CLOUD · MADE FOR THE WAY YOU SEE
+ </p>
+ </div>
+ </aside>
+ <main
+ id="main-content"
+ class="cf-auth-main"
+ tabindex="-1"
+ >
+ <div class="cf-auth-top">
+ <NuxtLink
+ :to="links.website"
+ external
+ class="cf-back-link"
+ ><ArrowLeft :size="15" />Back to home</NuxtLink
+ ><CloudThemeToggle />
+ </div>
+ <div class="cf-auth-form"><slot /></div>
+ <p class="cf-auth-bottom">
+ A home for your photographs.
+ <a
+ class="cf-text-link"
+ href="https://docs.chronoframe.art/"
+ >A little guidance, if you need it.</a
+ >
+ </p>
+ </main>
+ </div>
+</template>
diff --git a/apps/cloud/app/components/CloudBrand.vue b/apps/cloud/app/components/CloudBrand.vue
index 3d884a91..612086fe 100644
--- a/apps/cloud/app/components/CloudBrand.vue
+++ b/apps/cloud/app/components/CloudBrand.vue
@@ -1,18 +1,31 @@
<script setup lang="ts">
-defineProps<{ light?: boolean }>()
+defineProps<{ light?: boolean; cloud?: boolean }>()
+const links = useCloudLinks()
</script>
<template>
<NuxtLink
- to="/"
+ :to="links.website"
+ external
class="cf-brand"
:class="{ 'cf-brand-light': light }"
- aria-label="ChronoFrame home"
+ :aria-label="cloud ? 'ChronoFrame Cloud home' : 'ChronoFrame home'"
><img
src="/web-app-manifest-192x192.png"
width="34"
height="34"
class="cf-brand-logo"
alt=""
- /><span>ChronoFrame<span class="cf-brand-dot">.</span></span></NuxtLink
+ /><span
+ >ChronoFrame<span
+ v-if="cloud"
+ class="cf-brand-edition"
+ >
+ Cloud</span
+ ><span
+ v-else
+ class="cf-brand-dot"
+ >.</span
+ ></span
+ ></NuxtLink
>
</template>
diff --git a/apps/cloud/app/components/CloudPortalShell.vue b/apps/cloud/app/components/CloudPortalShell.vue
index 3d02331e..6e447a71 100644
--- a/apps/cloud/app/components/CloudPortalShell.vue
+++ b/apps/cloud/app/components/CloudPortalShell.vue
@@ -1,13 +1,28 @@
<script setup lang="ts">
-import { Images, UserRound, ArrowUpRight, BookOpen } from 'lucide-vue-next'
+import {
+ Images,
+ UserRound,
+ ArrowUpRight,
+ BookOpen,
+ ShieldCheck,
+ LogOut,
+} from 'lucide-vue-next'
const route = useRoute()
+const { busy, error, signOut } = useCloudSignOut()
</script>
<template>
<div class="cf-portal">
<header class="cf-portal-header">
- <CloudBrand />
+ <CloudBrand cloud />
<div class="cf-header-actions">
- <CloudBadge>Cloud preview</CloudBadge><CloudThemeToggle />
+ <CloudBadge>Cloud preview</CloudBadge
+ ><CloudButton
+ variant="ghost"
+ size="sm"
+ :loading="busy"
+ @click="signOut"
+ ><LogOut :size="15" />Sign out</CloudButton
+ ><CloudThemeToggle />
</div>
</header>
<div class="cf-portal-grid">
@@ -25,7 +40,22 @@ const route = useRoute()
:aria-current="route.path === '/account' ? 'page' : undefined"
><UserRound :size="18" />Account</NuxtLink
>
+ <NuxtLink
+ to="/account/security"
+ :class="{ active: route.path === '/account/security' }"
+ :aria-current="
+ route.path === '/account/security' ? 'page' : undefined
+ "
+ ><ShieldCheck :size="18" />Security</NuxtLink
+ >
</nav>
+ <p
+ v-if="error"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ error }}
+ </p>
<div class="cf-sidebar-bottom">
<p>A little guidance?</p>
<a
diff --git a/apps/cloud/app/composables/useCloudAccount.ts b/apps/cloud/app/composables/useCloudAccount.ts
new file mode 100644
index 00000000..d0664371
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudAccount.ts
@@ -0,0 +1,11 @@
+import { createAuthClient } from 'better-auth/vue'
+import { emailOTPClient, twoFactorClient } from 'better-auth/client/plugins'
+import { passkeyClient } from '@better-auth/passkey/client'
+/** Only browser ceremonies use this client; SSR identity is fetched through useRequestFetch. */
+export function useCloudAccount() {
+ return createAuthClient({
+ baseURL: useRequestURL().origin,
+ basePath: '/api/auth',
+ plugins: [emailOTPClient(), twoFactorClient(), passkeyClient()],
+ })
+}
diff --git a/apps/cloud/app/composables/useCloudLinks.ts b/apps/cloud/app/composables/useCloudLinks.ts
new file mode 100644
index 00000000..0a95c502
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudLinks.ts
@@ -0,0 +1,12 @@
+/** Production actions cross to the portal; preview/local auth stays on its own isolated origin. */
+export function useCloudLinks() {
+ const hostname = useRequestURL().hostname
+ const portal = ['chronoframe.art', 'app.chronoframe.art'].includes(hostname)
+ ? 'https://app.chronoframe.art'
+ : ''
+ return {
+ website: 'https://chronoframe.art/',
+ signin: portal + '/signin',
+ signup: portal + '/signup',
+ }
+}
diff --git a/apps/cloud/app/composables/useCloudSignOut.ts b/apps/cloud/app/composables/useCloudSignOut.ts
new file mode 100644
index 00000000..38828a7b
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudSignOut.ts
@@ -0,0 +1,25 @@
+/** One logout behavior for account settings and the portal account menu. */
+export function useCloudSignOut() {
+ const busy = ref(false),
+ error = ref('')
+ async function signOut() {
+ if (busy.value) return
+ busy.value = true
+ error.value = ''
+ try {
+ await $fetch('/api/auth/sign-out', { method: 'POST' })
+ clearNuxtData()
+ useEntryContext().value = null
+ useState('platform-site-catalog').value = null
+ useState('platform-user-id').value = null
+ useSettingsStore().$reset()
+ // Reset the document at the authentication boundary so no previous user's data survives.
+ await navigateTo('/signin', { external: true })
+ } catch {
+ error.value = 'We could not sign you out. Please try again.'
+ } finally {
+ busy.value = false
+ }
+ }
+ return { busy, error, signOut }
+}
diff --git a/apps/cloud/app/error.vue b/apps/cloud/app/error.vue
index 4b038c24..e12b0eac 100644
--- a/apps/cloud/app/error.vue
+++ b/apps/cloud/app/error.vue
@@ -28,8 +28,10 @@ const notFound = computed(() => props.error.statusCode === 404)
<div class="cf-header-actions">
<CloudButton
variant="secondary"
- @click="clearError({ redirect: '/' })"
- ><ArrowLeft :size="15" />Back to home</CloudButton
+ as-child
+ ><a href="https://chronoframe.art/"
+ ><ArrowLeft :size="15" />Back to home</a
+ ></CloudButton
><CloudButton
v-if="!notFound"
@click="reloadNuxtApp({ force: true })"
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index 670e2c80..c4f29fb8 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -21,7 +21,19 @@ export default defineNuxtRouteMiddleware(async (to) => {
return navigateTo('/sites', { redirectCode: 302 })
if (path === '/dashboard' || path.startsWith('/dashboard/'))
return navigateTo('/sites', { redirectCode: 302 })
- if (path === '/sites' || path.startsWith('/sites/')) {
+ if (['/signin', '/signup'].includes(path)) {
+ const session = await useRequestFetch()<{ authenticated: boolean }>(
+ '/api/auth/session',
+ ).catch(() => null)
+ if (session?.authenticated)
+ return navigateTo('/sites', { redirectCode: 302 })
+ }
+ if (
+ path === '/account' ||
+ path.startsWith('/account/') ||
+ path === '/sites' ||
+ path.startsWith('/sites/')
+ ) {
const fetcher = useRequestFetch()
const session = await fetcher<{
authenticated: boolean
@@ -42,7 +54,7 @@ export default defineNuxtRouteMiddleware(async (to) => {
const result = await fetcher<{ sites: EntrySiteSummary[] }>('/api/sites')
catalog.value = { userId: session.user.id, sites: result.sites }
}
- if (path !== '/sites') {
+ if (path.startsWith('/sites/')) {
const match = /^\/sites\/([1-9][0-9]*)$/.exec(path)
if (!match)
return abortNavigation(
diff --git a/apps/cloud/app/pages/account.vue b/apps/cloud/app/pages/account/index.vue
similarity index 72%
rename from apps/cloud/app/pages/account.vue
rename to apps/cloud/app/pages/account/index.vue
index 1571f031..271d3c0b 100644
--- a/apps/cloud/app/pages/account.vue
+++ b/apps/cloud/app/pages/account/index.vue
@@ -2,30 +2,9 @@
import { motion } from 'motion-v'
import { ShieldCheck, ArrowRight, LogOut } from 'lucide-vue-next'
const entrance = useCloudMotion()
-const busy = ref(false)
-const error = ref('')
-
-useSeoMeta({ title: 'Your account — ChronoFrame', robots: 'noindex' })
-const { data: session } = await useFetch('/api/auth/session')
-if (!session.value?.authenticated) await navigateTo('/signin')
-async function signOut() {
- if (busy.value) return
- busy.value = true
- error.value = ''
- try {
- await $fetch('/api/auth/logout', { method: 'POST' })
- clearNuxtData()
- useEntryContext().value = null
- useState('platform-site-catalog').value = null
- useState('platform-user-id').value = null
- useSettingsStore().$reset()
- await navigateTo('/signin')
- } catch {
- error.value = 'We could not sign you out. Please try again.'
- } finally {
- busy.value = false
- }
-}
+const { busy, error, signOut } = useCloudSignOut()
+useSeoMeta({ title: 'Your account — ChronoFrame Cloud', robots: 'noindex' })
+const { data: security } = await useFetch('/api/auth/security')
</script>
<template>
<CloudPortalShell
@@ -46,9 +25,15 @@ async function signOut() {
><div class="cf-setting-row">
<div>
<h2>Sign-in method</h2>
- <p>Email verification code. No password required.</p>
+ <p>{{ security?.email }}</p>
</div>
- <CloudBadge tone="success">Verified</CloudBadge>
+ <CloudButton
+ as-child
+ variant="secondary"
+ size="sm"
+ ><NuxtLink to="/account/security"
+ >Security settings <ArrowRight :size="14" /></NuxtLink
+ ></CloudButton>
</div>
<div class="cf-setting-row">
<div>
diff --git a/apps/cloud/app/pages/account/security.vue b/apps/cloud/app/pages/account/security.vue
new file mode 100644
index 00000000..b6bf5628
--- /dev/null
+++ b/apps/cloud/app/pages/account/security.vue
@@ -0,0 +1,354 @@
+<script setup lang="ts">
+import { accountError } from '../../utils/account-error'
+useSeoMeta({ title: 'Account security — ChronoFrame Cloud', robots: 'noindex' })
+const { data: security, refresh } = await useFetch<{
+ email: string
+ hasPassword: boolean
+ twoFactorEnabled: boolean
+ hasAuthenticator: boolean
+ passkeys: { id: number; name: string | null; createdAt: string }[]
+}>('/api/auth/security')
+const password = ref(''),
+ newPassword = ref(''),
+ code = ref(''),
+ passkeyName = ref('')
+const busy = ref(false),
+ error = ref(''),
+ notice = ref(''),
+ qr = ref(''),
+ totpURI = ref(''),
+ backupCodes = ref<string[]>([])
+async function run(action: () => Promise<void>) {
+ if (busy.value) return
+ busy.value = true
+ error.value = ''
+ notice.value = ''
+ try {
+ await action()
+ await refresh()
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ }
+}
+async function changePassword() {
+ await run(async () => {
+ await $fetch('/api/auth/change-password', {
+ method: 'POST',
+ body: {
+ currentPassword: password.value,
+ newPassword: newPassword.value,
+ revokeOtherSessions: true,
+ },
+ })
+ newPassword.value = ''
+ password.value = ''
+ notice.value = 'Password updated. Other sessions have been signed out.'
+ })
+}
+async function enable(method: 'otp' | 'totp') {
+ await run(async () => {
+ const result = await $fetch<{ totpURI?: string; backupCodes?: string[] }>(
+ '/api/auth/two-factor/enable',
+ { method: 'POST', body: { password: password.value, method } },
+ )
+ password.value = ''
+ if (result.totpURI) {
+ totpURI.value = result.totpURI
+ backupCodes.value = result.backupCodes ?? []
+ const QRCode = await import('qrcode')
+ qr.value = await QRCode.toDataURL(result.totpURI, {
+ width: 240,
+ margin: 2,
+ })
+ notice.value =
+ 'Scan the QR code, save your recovery codes, and enter a code to finish setup.'
+ } else notice.value = 'Email second-step verification is enabled.'
+ })
+}
+async function confirmAuthenticator() {
+ await run(async () => {
+ await $fetch('/api/auth/two-factor/verify-totp', {
+ method: 'POST',
+ body: { code: code.value },
+ })
+ code.value = ''
+ qr.value = ''
+ totpURI.value = ''
+ notice.value =
+ 'Authenticator verified and enabled. Keep your recovery codes somewhere safe.'
+ })
+}
+async function disable() {
+ await run(async () => {
+ await $fetch('/api/auth/two-factor/disable', {
+ method: 'POST',
+ body: { password: password.value },
+ })
+ password.value = ''
+ backupCodes.value = []
+ qr.value = ''
+ totpURI.value = ''
+ notice.value = 'Two-step verification has been disabled.'
+ })
+}
+async function regenerate() {
+ await run(async () => {
+ const result = await $fetch<{ backupCodes: string[] }>(
+ '/api/auth/two-factor/generate-backup-codes',
+ { method: 'POST', body: { password: password.value } },
+ )
+ backupCodes.value = result.backupCodes
+ password.value = ''
+ notice.value =
+ 'New recovery codes generated. Your previous codes no longer work.'
+ })
+}
+async function addPasskey() {
+ await run(async () => {
+ const result = await useCloudAccount().passkey.addPasskey({
+ name: passkeyName.value.trim() || 'My passkey',
+ })
+ if (result.error) throw result.error
+ passkeyName.value = ''
+ notice.value =
+ 'Passkey created. Its private key stays on your device or password manager.'
+ })
+}
+async function deletePasskey(id: number) {
+ await run(async () => {
+ await $fetch('/api/auth/passkey/delete-passkey', {
+ method: 'POST',
+ body: { id: String(id) },
+ })
+ notice.value = 'Passkey removed.'
+ })
+}
+</script>
+<template>
+ <CloudPortalShell
+ ><div class="cf-page-heading">
+ <div>
+ <p class="cf-eyebrow">YOUR ACCOUNT</p>
+ <h1 class="cf-page-title">Security</h1>
+ <p class="cf-page-description">
+ Keep your space yours. {{ security?.email }}
+ </p>
+ </div>
+ </div>
+ <p
+ v-if="error"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <p
+ v-if="notice"
+ class="cf-notice"
+ role="status"
+ >
+ {{ notice }}
+ </p>
+ <CloudCard class="cf-security-card"
+ ><h2>Password</h2>
+ <p>Use a unique password with at least 12 characters.</p>
+ <form
+ v-if="security?.hasPassword"
+ @submit.prevent="changePassword"
+ >
+ <label for="current-password">Current password</label
+ ><CloudInput
+ id="current-password"
+ v-model="password"
+ type="password"
+ autocomplete="current-password"
+ :disabled="busy"
+ required
+ /><label for="new-password">New password</label
+ ><CloudInput
+ id="new-password"
+ v-model="newPassword"
+ type="password"
+ autocomplete="new-password"
+ minlength="12"
+ maxlength="128"
+ :disabled="busy"
+ required
+ /><CloudButton
+ type="submit"
+ :loading="busy"
+ >Update password</CloudButton
+ >
+ </form>
+ <p v-else>
+ You signed in with an email code.
+ <NuxtLink
+ class="cf-text-link"
+ to="/forgot-password"
+ >Email yourself a link to set a password</NuxtLink
+ >
+ before enabling two-step verification.
+ </p></CloudCard
+ >
+ <CloudCard class="cf-security-card"
+ ><div class="cf-setting-row">
+ <div>
+ <h2>Two-step verification</h2>
+ <p>
+ After password sign-in, verify an email or authenticator code.
+ Passkeys already verify you on your device.
+ </p>
+ </div>
+ <CloudBadge
+ :tone="security?.twoFactorEnabled ? 'success' : 'neutral'"
+ >{{ security?.twoFactorEnabled ? 'Enabled' : 'Off' }}</CloudBadge
+ >
+ </div>
+ <template v-if="security?.hasPassword"
+ ><label for="security-password"
+ >Confirm your password to change security settings</label
+ ><CloudInput
+ id="security-password"
+ v-model="password"
+ type="password"
+ autocomplete="current-password"
+ :disabled="busy"
+ />
+ <div class="cf-security-actions">
+ <CloudButton
+ v-if="!security.twoFactorEnabled"
+ :disabled="busy || !password"
+ @click="enable('otp')"
+ >Enable email verification</CloudButton
+ ><CloudButton
+ v-if="!security.hasAuthenticator"
+ variant="secondary"
+ :disabled="busy || !password"
+ @click="enable('totp')"
+ >Set up authenticator</CloudButton
+ ><CloudButton
+ v-if="security.twoFactorEnabled"
+ variant="destructive"
+ :disabled="busy || !password"
+ @click="disable"
+ >Disable two-step verification</CloudButton
+ >
+ </div>
+ <div
+ v-if="totpURI"
+ class="cf-totp-setup"
+ >
+ <img
+ v-if="qr"
+ :src="qr"
+ width="240"
+ height="240"
+ alt="Scan this private QR code with your authenticator app"
+ />
+ <details>
+ <summary>Cannot scan the QR code?</summary>
+ <p class="cf-secret-value">{{ totpURI }}</p>
+ </details>
+ <form @submit.prevent="confirmAuthenticator">
+ <label for="totp-code">Authenticator code</label
+ ><CloudInput
+ id="totp-code"
+ v-model="code"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ pattern="[0-9]{6}"
+ maxlength="6"
+ required
+ :disabled="busy"
+ /><CloudButton
+ type="submit"
+ :loading="busy"
+ >Verify and enable</CloudButton
+ >
+ </form>
+ </div>
+ <div v-if="security.hasAuthenticator">
+ <p>
+ Authenticator connected. Recovery codes are single use. Generating
+ new codes replaces the old ones.
+ </p>
+ <CloudButton
+ variant="secondary"
+ :disabled="busy || !password"
+ @click="regenerate"
+ >Replace recovery codes</CloudButton
+ >
+ </div>
+ <div
+ v-if="backupCodes.length"
+ class="cf-notice"
+ >
+ <strong>Save these recovery codes privately.</strong>
+ <p>These are only shown here. Keep them outside this browser.</p>
+ <ul class="cf-recovery-codes">
+ <li
+ v-for="item in backupCodes"
+ :key="item"
+ >
+ <code>{{ item }}</code>
+ </li>
+ </ul>
+ <CloudButton
+ variant="secondary"
+ @click="backupCodes = []"
+ >I have saved my codes</CloudButton
+ >
+ </div></template
+ ></CloudCard
+ >
+ <CloudCard class="cf-security-card"
+ ><h2>Passkeys</h2>
+ <p>
+ Use your device lock, fingerprint or security key. Your device creates
+ the keys automatically.
+ </p>
+ <form @submit.prevent="addPasskey">
+ <label for="passkey-name">Passkey name</label
+ ><CloudInput
+ id="passkey-name"
+ v-model="passkeyName"
+ maxlength="80"
+ autocomplete="off"
+ placeholder="For example, my laptop"
+ :disabled="busy"
+ /><CloudButton
+ type="submit"
+ :loading="busy"
+ >Create passkey</CloudButton
+ >
+ </form>
+ <ul
+ v-if="security?.passkeys.length"
+ class="cf-passkey-list"
+ >
+ <li
+ v-for="key in security.passkeys"
+ :key="key.id"
+ >
+ <span>{{ key.name || 'Passkey' }}</span
+ ><CloudButton
+ variant="destructive"
+ size="sm"
+ :disabled="busy"
+ :aria-label="`Remove ${key.name || 'passkey'}`"
+ @click="deletePasskey(key.id)"
+ >Remove</CloudButton
+ >
+ </li>
+ </ul>
+ <p
+ v-else
+ class="cf-auth-hint"
+ >
+ No passkeys yet.
+ </p></CloudCard
+ ></CloudPortalShell
+ >
+</template>
diff --git a/apps/cloud/app/pages/forgot-password.vue b/apps/cloud/app/pages/forgot-password.vue
new file mode 100644
index 00000000..6992a252
--- /dev/null
+++ b/apps/cloud/app/pages/forgot-password.vue
@@ -0,0 +1,76 @@
+<script setup lang="ts">
+import { accountError } from '../utils/account-error'
+useSeoMeta({ title: 'Reset password — ChronoFrame Cloud', robots: 'noindex' })
+const email = ref(''),
+ busy = ref(false),
+ sent = ref(false),
+ error = ref('')
+async function submit() {
+ busy.value = true
+ error.value = ''
+ try {
+ await $fetch('/api/auth/request-password-reset', {
+ method: 'POST',
+ body: {
+ email: email.value,
+ redirectTo: `${useRequestURL().origin}/reset-password`,
+ },
+ })
+ sent.value = true
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <CloudAuthLayout
+ ><h1>A fresh start.</h1>
+ <p>
+ We will email you a link to reset your password. Existing email-code
+ accounts can use this to set their first password.
+ </p>
+ <p
+ v-if="sent"
+ class="cf-notice"
+ role="status"
+ >
+ If this address has an account, a password reset link is on its way. Check
+ your inbox.
+ </p>
+ <form
+ v-else
+ @submit.prevent="submit"
+ >
+ <label for="email">Email address</label
+ ><CloudInput
+ id="email"
+ v-model="email"
+ type="email"
+ autocomplete="email"
+ :disabled="busy"
+ required
+ />
+ <p
+ v-if="error"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ error }}
+ </p>
+ <CloudButton
+ type="submit"
+ :loading="busy"
+ >Send reset link</CloudButton
+ >
+ </form>
+ <p class="cf-auth-hint">
+ <NuxtLink
+ to="/signin"
+ class="cf-text-link"
+ >Back to sign in</NuxtLink
+ >
+ </p></CloudAuthLayout
+ >
+</template>
diff --git a/apps/cloud/app/pages/index.vue b/apps/cloud/app/pages/index.vue
index f850f6cc..f42e0704 100644
--- a/apps/cloud/app/pages/index.vue
+++ b/apps/cloud/app/pages/index.vue
@@ -9,10 +9,7 @@ import {
Check,
} from 'lucide-vue-next'
const entrance = useCloudMotion()
-const signInUrl =
- useRequestURL().hostname === 'chronoframe.art'
- ? 'https://app.chronoframe.art/signin'
- : '/signin'
+const links = useCloudLinks()
useSeoMeta({
title: 'ChronoFrame — A home for your photography',
description:
@@ -34,11 +31,23 @@ useSeoMeta({
:size="12"
aria-hidden="true"
class="cf-inline-icon" /></a
- ><CloudThemeToggle /><CloudButton
+ ><CloudThemeToggle />
+ <CloudButton
as-child
+ variant="secondary"
size="sm"
- ><NuxtLink :to="signInUrl"
- >Cloud access <ArrowUpRight :size="14" /></NuxtLink
+ ><NuxtLink
+ :to="links.signin"
+ external
+ >Log in</NuxtLink
+ ></CloudButton
+ ><CloudButton
+ as-child
+ size="sm"
+ ><NuxtLink
+ :to="links.signup"
+ external
+ >Get started <ArrowUpRight :size="14" /></NuxtLink
></CloudButton>
</nav>
</header>
@@ -58,8 +67,11 @@ useSeoMeta({
<CloudButton
as-child
size="lg"
- ><NuxtLink :to="signInUrl"
- >Explore Cloud <ArrowRight :size="16" /></NuxtLink></CloudButton
+ ><NuxtLink
+ :to="links.signup"
+ external
+ >Create your account
+ <ArrowRight :size="16" /></NuxtLink></CloudButton
><CloudButton
as-child
variant="secondary"
diff --git a/apps/cloud/app/pages/reset-password.vue b/apps/cloud/app/pages/reset-password.vue
new file mode 100644
index 00000000..9626a019
--- /dev/null
+++ b/apps/cloud/app/pages/reset-password.vue
@@ -0,0 +1,101 @@
+<script setup lang="ts">
+import { accountError } from '../utils/account-error'
+useSeoMeta({
+ title: 'Set a new password — ChronoFrame Cloud',
+ robots: 'noindex',
+ referrer: 'no-referrer',
+})
+const route = useRoute(),
+ password = ref(''),
+ confirmation = ref(''),
+ busy = ref(false),
+ done = ref(false),
+ error = ref('')
+const token = typeof route.query.token === 'string' ? route.query.token : ''
+async function submit() {
+ if (password.value !== confirmation.value) {
+ error.value = 'The passwords do not match.'
+ return
+ }
+ busy.value = true
+ error.value = ''
+ try {
+ await $fetch('/api/auth/reset-password', {
+ method: 'POST',
+ body: { token, newPassword: password.value },
+ })
+ password.value = ''
+ confirmation.value = ''
+ done.value = true
+ await navigateTo('/reset-password', { replace: true })
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <CloudAuthLayout
+ ><h1>Set a new password.</h1>
+ <p
+ v-if="done"
+ class="cf-notice"
+ role="status"
+ >
+ Your password has been updated. Sign in with your new password.
+ </p>
+ <form
+ v-else-if="token"
+ @submit.prevent="submit"
+ >
+ <label for="password">New password</label
+ ><CloudInput
+ id="password"
+ v-model="password"
+ type="password"
+ autocomplete="new-password"
+ minlength="12"
+ maxlength="128"
+ required
+ :disabled="busy"
+ /><label for="confirmation">Confirm password</label
+ ><CloudInput
+ id="confirmation"
+ v-model="confirmation"
+ type="password"
+ autocomplete="new-password"
+ minlength="12"
+ maxlength="128"
+ required
+ :disabled="busy"
+ />
+ <p
+ v-if="error"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ error }}
+ </p>
+ <CloudButton
+ type="submit"
+ :loading="busy"
+ >Save new password</CloudButton
+ >
+ </form>
+ <p
+ v-else
+ class="cf-notice"
+ >
+ This reset link is invalid or expired.
+ <NuxtLink to="/forgot-password">Request a new link</NuxtLink>.
+ </p>
+ <p class="cf-auth-hint">
+ <NuxtLink
+ to="/signin"
+ class="cf-text-link"
+ >Back to sign in</NuxtLink
+ >
+ </p></CloudAuthLayout
+ >
+</template>
diff --git a/apps/cloud/app/pages/signin.vue b/apps/cloud/app/pages/signin.vue
index ec7c891f..4d0b4568 100644
--- a/apps/cloud/app/pages/signin.vue
+++ b/apps/cloud/app/pages/signin.vue
@@ -1,220 +1,265 @@
<script setup lang="ts">
-import { motion } from 'motion-v'
-import { ArrowLeft, ArrowRight, Mail, ShieldCheck } from 'lucide-vue-next'
-const entrance = useCloudMotion()
-const codeInput = ref<{ $el: HTMLInputElement }>()
-const emailInput = ref<{ $el: HTMLInputElement }>()
-
-useSeoMeta({ title: 'Sign in — ChronoFrame', robots: 'noindex' })
+import { accountError } from '../utils/account-error'
const { data: status } = await useFetch('/api/auth/status')
-const email = ref('')
-const code = ref('')
-const challenge = ref<string>()
-const busy = ref(false)
-const error = ref('')
-async function resetChallenge() {
- challenge.value = undefined
- code.value = ''
+useSeoMeta({ title: 'Sign in — ChronoFrame Cloud', robots: 'noindex' })
+const email = ref(''),
+ password = ref(''),
+ code = ref('')
+const mode = ref<'password' | 'email'>('password')
+const step = ref<'credentials' | 'code' | 'second'>('credentials')
+function setMode(value: 'email' | 'password') {
+ mode.value = value
error.value = ''
- await nextTick()
- emailInput.value?.$el?.focus()
+}
+const factor = ref<'email' | 'totp' | 'recovery'>('email')
+const busy = ref(false),
+ error = ref('')
+const codeInput = ref<{ $el: HTMLInputElement }>()
+async function sendSecond() {
+ await $fetch('/api/auth/two-factor/send-otp', { method: 'POST', body: {} })
}
async function submit() {
- if (busy.value || !status.value?.enabled) return
+ if (busy.value) return
busy.value = true
error.value = ''
- let focusCode = false
try {
- if (!challenge.value) {
- const result = await $fetch('/api/auth/email/request', {
+ if (step.value === 'second') {
+ const endpoint =
+ factor.value === 'email'
+ ? 'verify-otp'
+ : factor.value === 'totp'
+ ? 'verify-totp'
+ : 'verify-backup-code'
+ await $fetch(`/api/auth/two-factor/${endpoint}`, {
method: 'POST',
- body: { email: email.value },
+ body:
+ factor.value === 'recovery'
+ ? { code: code.value }
+ : { code: code.value, trustDevice: false },
})
- challenge.value = result.challengeId
- focusCode = true
- } else {
- await $fetch('/api/auth/email/verify', {
+ } else if (mode.value === 'email' && step.value === 'credentials') {
+ await $fetch('/api/auth/email-otp/send-verification-otp', {
method: 'POST',
- body: {
- email: email.value,
- code: code.value,
- challengeId: challenge.value,
- },
+ body: { email: email.value, type: 'sign-in' },
})
- await navigateTo('/account')
+ step.value = 'code'
+ return
+ } else {
+ const result = await $fetch<{ twoFactorRedirect?: boolean }>(
+ mode.value === 'password'
+ ? '/api/auth/sign-in/email'
+ : '/api/auth/sign-in/email-otp',
+ {
+ method: 'POST',
+ body:
+ mode.value === 'password'
+ ? { email: email.value, password: password.value }
+ : { email: email.value, otp: code.value },
+ },
+ )
+ if (result.twoFactorRedirect) {
+ step.value = 'second'
+ code.value = ''
+ await sendSecond()
+ return
+ }
}
+ clearNuxtData()
+ await navigateTo('/sites', { external: true })
} catch (cause) {
- const status = (cause as { statusCode?: number }).statusCode
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ if (step.value !== 'credentials') {
+ await nextTick()
+ codeInput.value?.$el?.focus()
+ }
+ }
+}
+async function passkeySignIn() {
+ busy.value = true
+ error.value = ''
+ try {
+ const result = await useCloudAccount().signIn.passkey()
+ if (result.error) throw result.error
+ clearNuxtData()
+ await navigateTo('/sites', { external: true })
+ } catch {
error.value =
- status === 429
- ? 'Please wait before requesting another code.'
- : status === 401
- ? 'The code is invalid or expired. Try again or request a new code.'
- : 'Sign-in could not be completed. Please try again later.'
+ 'Passkey sign-in was not completed. Try again or use your email.'
} finally {
busy.value = false
}
- if (focusCode) {
- await nextTick()
- codeInput.value?.$el?.focus()
+}
+async function resend() {
+ busy.value = true
+ error.value = ''
+ try {
+ if (step.value === 'second') await sendSecond()
+ else
+ await $fetch('/api/auth/email-otp/send-verification-otp', {
+ method: 'POST',
+ body: { email: email.value, type: 'sign-in' },
+ })
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
}
}
</script>
<template>
- <div class="cf-auth">
- <aside
- class="cf-auth-visual"
- aria-label="About ChronoFrame"
- >
- <CloudBrand light />
- <div>
- <div class="cf-auth-quote">
- <h2>A little space.<br />A different perspective.</h2>
- <p>Your photographs deserve a home that feels like you.</p>
- </div>
- <p class="cf-auth-caption">CHRONOFRAME · MADE FOR THE WAY YOU SEE</p>
- </div>
- </aside>
- <main
- id="main-content"
- class="cf-auth-main"
- tabindex="-1"
- >
- <div class="cf-auth-top">
- <NuxtLink
- to="/"
- class="cf-back-link"
- ><ArrowLeft :size="15" />Back to home</NuxtLink
- ><CloudThemeToggle />
+ <CloudAuthLayout
+ ><CloudBadge>ChronoFrame Cloud</CloudBadge>
+ <h1>
+ {{
+ step === 'second'
+ ? 'One more step.'
+ : step === 'code'
+ ? 'Check your inbox.'
+ : 'Welcome back.'
+ }}
+ </h1>
+ <template v-if="status?.enabled"
+ ><p>
+ {{
+ step === 'second'
+ ? 'Complete your second verification to continue.'
+ : 'Your photographs. Your space.'
+ }}
+ </p>
+ <div
+ v-if="step === 'credentials'"
+ class="cf-auth-tabs"
+ aria-label="Sign-in method"
+ >
+ <CloudButton
+ :variant="mode === 'password' ? 'secondary' : 'ghost'"
+ :disabled="busy"
+ @click="setMode('password')"
+ >Password</CloudButton
+ ><CloudButton
+ :variant="mode === 'email' ? 'secondary' : 'ghost'"
+ :disabled="busy"
+ @click="setMode('email')"
+ >Email code</CloudButton
+ >
</div>
- <motion.div
- v-bind="entrance"
- class="cf-auth-form"
- ><CloudBadge>Cloud preview</CloudBadge>
- <h1>
- {{ challenge ? 'Check your inbox.' : 'Welcome to your space.' }}
- </h1>
- <template v-if="status?.enabled">
- <p
- v-if="challenge"
- role="status"
- >
- We sent a six-digit code to <strong>{{ email }}</strong
- >. It expires in 10 minutes.
- </p>
- <p v-else>Sign in with your email. No password to remember.</p>
- <form
- @submit.prevent="submit"
- :aria-busy="busy"
- >
- <label for="signin-email">Email address</label
- ><CloudInput
- id="signin-email"
- ref="emailInput"
- v-model="email"
- type="email"
- autocomplete="email"
- placeholder="[email protected]"
- :disabled="!!challenge || busy"
- required
- />
- <template v-if="challenge"
- ><label for="signin-code">Verification code</label
- ><CloudInput
- id="signin-code"
- ref="codeInput"
- v-model="code"
- class="cf-code-input"
- inputmode="numeric"
- autocomplete="one-time-code"
- pattern="[0-9]{6}"
- maxlength="6"
- :disabled="busy"
- :aria-invalid="!!error"
- :aria-describedby="error ? 'signin-error' : 'code-hint'"
- required
- />
- <p
- id="code-hint"
- class="cf-auth-hint"
- >
- Enter the six digits from your email.
- </p></template
- >
- <p
- v-if="error"
- id="signin-error"
- class="cf-error-message"
- role="alert"
- >
- {{ error }}
- </p>
- <CloudButton
- type="submit"
- :loading="busy"
- >{{
- busy
- ? challenge
- ? 'Signing in…'
- : 'Sending code…'
- : challenge
- ? 'Sign in'
- : 'Continue with email'
- }}<ArrowRight
- v-if="!busy"
- :size="16"
- /></CloudButton>
- <CloudButton
- v-if="challenge"
- variant="ghost"
- :disabled="busy"
- @click="resetChallenge"
- >Use another email or request a new code</CloudButton
- >
- <p
- v-else
- class="cf-auth-hint"
- >
- <ShieldCheck
- :size="13"
- style="
- display: inline;
- vertical-align: middle;
- margin-right: 4px;
- "
- />We only use your email to help you sign in.
- </p>
- </form>
- </template>
- <template v-else
- ><div
- class="cf-notice"
- role="status"
+ <form
+ @submit.prevent="submit"
+ :aria-busy="busy"
+ >
+ <template v-if="step !== 'second'"
+ ><label for="email">Email address</label
+ ><CloudInput
+ id="email"
+ v-model="email"
+ type="email"
+ autocomplete="username"
+ :disabled="busy || step === 'code'"
+ required
+ /></template>
+ <template v-if="mode === 'password' && step === 'credentials'"
+ ><label for="password">Password</label
+ ><CloudInput
+ id="password"
+ v-model="password"
+ type="password"
+ autocomplete="current-password"
+ :disabled="busy"
+ required
+ /><NuxtLink
+ class="cf-text-link"
+ to="/forgot-password"
+ >Forgot your password?</NuxtLink
+ ></template
+ >
+ <template v-if="step === 'second'"
+ ><label for="factor">Verification method</label
+ ><select
+ id="factor"
+ v-model="factor"
+ :disabled="busy"
+ @change="code = ''"
>
- <Mail
- :size="20"
- class="cf-notice-icon"
- /><strong
- >Email sign-in is not available on this deployment yet.</strong
- >Cloud access is still in preview. You can start your own gallery
- with the self-hosted edition today.
- </div>
- <CloudButton
- as-child
- variant="secondary"
- class="cf-action-spaced"
- ><a href="https://docs.chronoframe.art/guide/getting-started.html"
- >Explore Self-hosted<ArrowRight :size="16" /></a></CloudButton
- ></template>
- </motion.div>
- <p class="cf-auth-bottom">
- A home for your photographs.
- <a
+ <option value="email">Email code</option>
+ <option value="totp">Authenticator code</option>
+ <option value="recovery">Recovery code</option>
+ </select></template
+ >
+ <template v-if="step !== 'credentials'"
+ ><label for="code">{{
+ factor === 'recovery' && step === 'second'
+ ? 'Recovery code'
+ : 'Verification code'
+ }}</label
+ ><CloudInput
+ id="code"
+ ref="codeInput"
+ v-model="code"
+ autocomplete="one-time-code"
+ :inputmode="
+ factor === 'recovery' && step === 'second' ? 'text' : 'numeric'
+ "
+ :disabled="busy"
+ required
+ />
+ <p class="cf-auth-hint">
+ {{
+ step === 'code' || factor === 'email'
+ ? 'Enter the code from your email.'
+ : 'Use your authenticator or an unused recovery code.'
+ }}
+ </p></template
+ >
+ <p
+ v-if="error"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ error }}
+ </p>
+ <CloudButton
+ type="submit"
+ :loading="busy"
+ >{{
+ mode === 'email' && step === 'credentials'
+ ? 'Send sign-in code'
+ : 'Sign in'
+ }}</CloudButton
+ >
+ <CloudButton
+ v-if="
+ step !== 'credentials' && (step === 'code' || factor === 'email')
+ "
+ variant="ghost"
+ :disabled="busy"
+ @click="resend"
+ >Send a new code</CloudButton
+ >
+ </form>
+ <CloudButton
+ v-if="step === 'credentials'"
+ class="cf-action-spaced"
+ variant="secondary"
+ :disabled="busy"
+ @click="passkeySignIn"
+ >Sign in with a passkey</CloudButton
+ >
+ <p class="cf-auth-hint">
+ New here?
+ <NuxtLink
+ to="/signup"
class="cf-text-link"
- href="https://docs.chronoframe.art/"
- >A little guidance, if you need it.</a
+ >Create an account</NuxtLink
>
- </p>
- </main>
- </div>
+ </p></template
+ >
+ <p
+ v-else
+ class="cf-notice"
+ >
+ Email sign-in is not available on this deployment yet.
+ </p></CloudAuthLayout
+ >
</template>
diff --git a/apps/cloud/app/pages/signup.vue b/apps/cloud/app/pages/signup.vue
new file mode 100644
index 00000000..69d3597e
--- /dev/null
+++ b/apps/cloud/app/pages/signup.vue
@@ -0,0 +1,154 @@
+<script setup lang="ts">
+import { accountError } from '../utils/account-error'
+useSeoMeta({
+ title: 'Create an account — ChronoFrame Cloud',
+ robots: 'noindex',
+})
+const { data: status } = await useFetch('/api/auth/status')
+const email = ref(''),
+ password = ref(''),
+ code = ref(''),
+ sent = ref(false),
+ busy = ref(false),
+ error = ref('')
+const codeInput = ref<{ $el: HTMLInputElement }>()
+async function submit() {
+ busy.value = true
+ error.value = ''
+ try {
+ if (!sent.value) {
+ await $fetch('/api/auth/sign-up/email', {
+ method: 'POST',
+ body: {
+ email: email.value,
+ password: password.value,
+ name: email.value,
+ },
+ })
+ password.value = ''
+ sent.value = true
+ } else {
+ await $fetch('/api/auth/email-otp/verify-email', {
+ method: 'POST',
+ body: { email: email.value, otp: code.value },
+ })
+ clearNuxtData()
+ await navigateTo('/sites', { external: true })
+ }
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ if (sent.value) {
+ await nextTick()
+ codeInput.value?.$el?.focus()
+ }
+ }
+}
+async function resend() {
+ busy.value = true
+ error.value = ''
+ try {
+ await $fetch('/api/auth/email-otp/send-verification-otp', {
+ method: 'POST',
+ body: { email: email.value, type: 'email-verification' },
+ })
+ sent.value = true
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <CloudAuthLayout
+ ><CloudBadge>ChronoFrame Cloud</CloudBadge>
+ <h1>{{ sent ? 'Make it yours.' : 'A home for your photographs.' }}</h1>
+ <template v-if="status?.enabled"
+ ><p>
+ {{
+ sent
+ ? 'Verify your email to finish creating your account.'
+ : 'Create your account and find your own perspective.'
+ }}
+ </p>
+ <form
+ @submit.prevent="submit"
+ :aria-busy="busy"
+ >
+ <label for="email">Email address</label
+ ><CloudInput
+ id="email"
+ v-model="email"
+ type="email"
+ autocomplete="email"
+ :disabled="busy || sent"
+ required
+ /><template v-if="!sent"
+ ><label for="password">Password</label
+ ><CloudInput
+ id="password"
+ v-model="password"
+ type="password"
+ autocomplete="new-password"
+ minlength="12"
+ maxlength="128"
+ :disabled="busy"
+ required
+ />
+ <p class="cf-auth-hint">
+ Use at least 12 characters. A unique passphrase works well.
+ </p></template
+ ><template v-else
+ ><label for="code">Email verification code</label
+ ><CloudInput
+ id="code"
+ ref="codeInput"
+ v-model="code"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ pattern="[0-9]{6}"
+ maxlength="6"
+ :disabled="busy"
+ required
+ /></template>
+ <p
+ v-if="error"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <CloudButton
+ type="submit"
+ :loading="busy"
+ >{{
+ sent ? 'Verify email and continue' : 'Create account'
+ }}</CloudButton
+ ><CloudButton
+ variant="ghost"
+ :disabled="busy || !email"
+ @click="resend"
+ >{{
+ sent ? 'Send a new code' : 'Already started? Resend verification'
+ }}</CloudButton
+ >
+ </form>
+ <p class="cf-auth-hint">
+ Already have an account?
+ <NuxtLink
+ to="/signin"
+ class="cf-text-link"
+ >Log in</NuxtLink
+ >
+ </p></template
+ >
+ <p
+ v-else
+ class="cf-notice"
+ >
+ Registration is not available on this deployment yet.
+ </p></CloudAuthLayout
+ >
+</template>
diff --git a/apps/cloud/app/pages/sites/index.vue b/apps/cloud/app/pages/sites/index.vue
index b1253c41..6c997151 100644
--- a/apps/cloud/app/pages/sites/index.vue
+++ b/apps/cloud/app/pages/sites/index.vue
@@ -4,7 +4,7 @@ import { ArrowUpRight, Images, Compass, ShieldCheck } from 'lucide-vue-next'
const entrance = useCloudMotion()
import type { EntrySiteCatalog } from '@chronoframe/contracts/entry'
-useSeoMeta({ title: 'Your sites — ChronoFrame', robots: 'noindex' })
+useSeoMeta({ title: 'Your sites — ChronoFrame Cloud', robots: 'noindex' })
const userId = useState<number | null>('platform-user-id', () => null)
const catalog = useState<EntrySiteCatalog | null>(
'platform-site-catalog',
diff --git a/apps/cloud/app/types/qrcode.d.ts b/apps/cloud/app/types/qrcode.d.ts
new file mode 100644
index 00000000..7eef79c0
--- /dev/null
+++ b/apps/cloud/app/types/qrcode.d.ts
@@ -0,0 +1,6 @@
+declare module 'qrcode' {
+ export function toDataURL(
+ text: string,
+ options?: { width?: number; margin?: number },
+ ): Promise<string>
+}
diff --git a/apps/cloud/app/utils/account-error.ts b/apps/cloud/app/utils/account-error.ts
new file mode 100644
index 00000000..9553fff2
--- /dev/null
+++ b/apps/cloud/app/utils/account-error.ts
@@ -0,0 +1,29 @@
+/** Present actionable auth errors without exposing raw server/provider failures. */
+export function accountError(cause: unknown) {
+ const error = cause as {
+ statusCode?: number
+ data?: { message?: string; code?: string }
+ }
+ if (error.statusCode === 429)
+ return 'Too many attempts. Please wait before trying again.'
+ const code = error.data?.code ?? ''
+ if (code.includes('PASSWORD_TOO_SHORT'))
+ return 'Use a password with at least 12 characters.'
+ if (code.includes('EMAIL_NOT_VERIFIED'))
+ return 'Verify your email before signing in. You can request another code below.'
+ if (code.includes('USER_ALREADY_EXISTS'))
+ return 'An account may already use this email. Try signing in or resetting your password.'
+ if (
+ code.includes('OTP') ||
+ code.includes('TOTP') ||
+ code.includes('BACKUP_CODE')
+ )
+ return 'This code is invalid or expired. Check it and try again, or request a new code.'
+ if (code.includes('PASSWORD') || code.includes('CREDENTIAL'))
+ return 'The email or password is incorrect. Check your details or reset your password.'
+ if (code.includes('TOKEN'))
+ return 'This link is invalid or expired. Please request a new password reset email.'
+ if (code.includes('FRESH_SESSION') || code.includes('SESSION_IS_NOT_FRESH'))
+ return 'Please sign out and sign in again before changing security settings.'
+ return 'We could not complete this request. Please try again.'
+}
diff --git a/apps/cloud/nuxt.config.ts b/apps/cloud/nuxt.config.ts
index d227e526..e24cf7ba 100644
--- a/apps/cloud/nuxt.config.ts
+++ b/apps/cloud/nuxt.config.ts
@@ -12,6 +12,8 @@ export default defineNuxtConfig({
devServer: { port: 3001 },
nitro: {
...sharedUi.nitro,
+ // WebAuthn certificate validation uses reflection during module initialization.
+ moduleSideEffects: ['reflect-metadata'],
cloudflare: {
...sharedUi.nitro.cloudflare,
wrangler: { name: 'chronoframe-cloud', compatibility_date: '2026-10-22' },
diff --git a/apps/cloud/package.json b/apps/cloud/package.json
index a27507b9..a082cfcb 100644
--- a/apps/cloud/package.json
+++ b/apps/cloud/package.json
@@ -12,6 +12,7 @@
"deploy": "wrangler deploy --config .output/server/wrangler.json"
},
"dependencies": {
+ "@better-auth/passkey": "1.7.12",
"@chronoframe/console": "workspace:*",
"@chronoframe/contracts": "workspace:*",
"@chronoframe/core": "workspace:*",
@@ -24,6 +25,7 @@
"@pinia/nuxt": "^0.11.3",
"@unhead/vue": "3.4.2",
"@vueuse/nuxt": "14.4.0",
+ "better-auth": "1.7.12",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs-nuxt": "2.1.11",
@@ -37,6 +39,8 @@
"nuxt-og-image": "6.10.3",
"nuxt-site-config": "4.2.3",
"pinia": "^3.0.4",
+ "qrcode": "^1.5.4",
+ "reflect-metadata": "0.2.2",
"reka-ui": "^2.11.0",
"shadcn-nuxt": "^2.8.2",
"tailwind-merge": "^3.7.0",
diff --git a/apps/cloud/server/api/auth/[...all].ts b/apps/cloud/server/api/auth/[...all].ts
new file mode 100644
index 00000000..b10ea33e
--- /dev/null
+++ b/apps/cloud/server/api/auth/[...all].ts
@@ -0,0 +1,3 @@
+import { definePlatformHandler } from '../../../../shared/platform/runtime'
+import { forwardAccountRequest } from '../../utils/account-handler'
+export default definePlatformHandler((event) => forwardAccountRequest(event))
diff --git a/apps/cloud/server/api/auth/email/request.post.ts b/apps/cloud/server/api/auth/email/request.post.ts
deleted file mode 100644
index 7783d8b0..00000000
--- a/apps/cloud/server/api/auth/email/request.post.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { definePlatformHandler } from '../../../../../shared/platform/runtime'
-import { emailSignIn } from '../../../utils/platform-auth'
-export default definePlatformHandler(async (event) => {
- const body = await readBody(event)
- if (!body || typeof body.email !== 'string')
- throw createError({ statusCode: 400, statusMessage: 'Email required' })
- // In Workers, Cloudflare sets this header. Local development has no production fallback.
- const client = event.context.cloudflare
- ? getRequestHeader(event, 'cf-connecting-ip')
- : undefined
- if (!client)
- throw createError({
- statusCode: 503,
- statusMessage: 'Client context unavailable',
- })
- return (await emailSignIn(event)).request(body.email, client)
-})
diff --git a/apps/cloud/server/api/auth/email/verify.post.ts b/apps/cloud/server/api/auth/email/verify.post.ts
deleted file mode 100644
index fe40128f..00000000
--- a/apps/cloud/server/api/auth/email/verify.post.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { definePlatformHandler } from '../../../../../shared/platform/runtime'
-import { emailSignIn } from '../../../utils/platform-auth'
-import { createD1Sessions } from '../../../../../../packages/platform/src/index'
-import { createEmailCodeCrypto } from '../../../../../shared/platform/crypto'
-import {
- PLATFORM_COOKIE,
- platformDatabase,
-} from '../../../../../shared/platform/runtime'
-export default definePlatformHandler(async (event) => {
- const body = await readBody(event)
- if (
- !body ||
- typeof body.email !== 'string' ||
- typeof body.challengeId !== 'string' ||
- typeof body.code !== 'string'
- ) {
- throw createError({
- statusCode: 400,
- statusMessage: 'Email and code required',
- })
- }
- const result = await (
- await emailSignIn(event)
- ).verify(body.email, body.challengeId, body.code)
- const crypto = await createEmailCodeCrypto(
- useRuntimeConfig(event).platform.secret,
- )
- const token = crypto.randomId()
- const now = Date.now()
- const maxAge = 7 * 24 * 60 * 60
- await createD1Sessions(platformDatabase(event)).create(
- result.verifiedEmail,
- await crypto.mac(['platform-session', token]),
- now,
- now + maxAge * 1000,
- )
- setCookie(event, PLATFORM_COOKIE, token, {
- httpOnly: true,
- secure: true,
- sameSite: 'lax',
- path: '/',
- maxAge,
- })
- return { authenticated: true }
-})
diff --git a/apps/cloud/server/api/auth/logout.post.ts b/apps/cloud/server/api/auth/logout.post.ts
index eda5bf0b..988bb0e9 100644
--- a/apps/cloud/server/api/auth/logout.post.ts
+++ b/apps/cloud/server/api/auth/logout.post.ts
@@ -1,26 +1,4 @@
-import { definePlatformHandler } from '../../../../shared/platform/runtime'
-import { createD1Sessions } from '../../../../../packages/platform/src/index'
-import { createEmailCodeCrypto } from '../../../../shared/platform/crypto'
-import {
- PLATFORM_COOKIE,
- platformDatabase,
- platformPortalOrigin,
-} from '../../../../shared/platform/runtime'
-export default definePlatformHandler(async (event) => {
- const config = useRuntimeConfig(event).platform
- platformPortalOrigin(event, config.portalOrigin, true)
- const token = getCookie(event, PLATFORM_COOKIE)
- if (token) {
- const crypto = await createEmailCodeCrypto(config.secret)
- await createD1Sessions(platformDatabase(event)).revoke(
- await crypto.mac(['platform-session', token]),
- )
- }
- deleteCookie(event, PLATFORM_COOKIE, {
- secure: true,
- httpOnly: true,
- sameSite: 'lax',
- path: '/',
- })
- return { authenticated: false }
-})
+import { forwardAccountRequest } from '../../utils/account-handler'
+export default defineEventHandler((event) =>
+ forwardAccountRequest(event, '/sign-out'),
+)
diff --git a/apps/cloud/server/api/auth/security.get.ts b/apps/cloud/server/api/auth/security.get.ts
new file mode 100644
index 00000000..02f3d35e
--- /dev/null
+++ b/apps/cloud/server/api/auth/security.get.ts
@@ -0,0 +1,46 @@
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+export default definePlatformHandler(async (event) => {
+ const session = await requirePlatformSession(
+ event,
+ useRuntimeConfig(event).platform,
+ )
+ const db = platformDatabase(event)
+ const user = await db
+ .prepare(
+ 'SELECT email, two_factor_enabled AS twoFactorEnabled FROM platform_users WHERE id = ?',
+ )
+ .bind(session.userId)
+ .first<{ email: string; twoFactorEnabled: number }>()
+ const credential = await db
+ .prepare(
+ "SELECT id FROM platform_accounts WHERE user_id = ? AND provider_id = 'credential' AND password IS NOT NULL",
+ )
+ .bind(session.userId)
+ .first()
+ const factor = await db
+ .prepare('SELECT verified FROM platform_two_factors WHERE user_id = ?')
+ .bind(session.userId)
+ .first<{ verified: number }>()
+ const passkeys = await db
+ .prepare(
+ `SELECT COALESCE(json_group_array(json_object('id', id, 'name', name, 'createdAt', created_at)), '[]') AS items
+ FROM (SELECT id, name, created_at FROM platform_passkeys WHERE user_id = ? ORDER BY id DESC)`,
+ )
+ .bind(session.userId)
+ .first<{ items: string }>()
+ return {
+ email: user!.email,
+ hasPassword: !!credential,
+ twoFactorEnabled: !!user!.twoFactorEnabled,
+ hasAuthenticator: !!factor?.verified,
+ passkeys: JSON.parse(passkeys?.items ?? '[]') as {
+ id: number
+ name: string | null
+ createdAt: number
+ }[],
+ }
+})
diff --git a/apps/cloud/server/api/auth/status.get.ts b/apps/cloud/server/api/auth/status.get.ts
index d7225863..4f82802c 100644
--- a/apps/cloud/server/api/auth/status.get.ts
+++ b/apps/cloud/server/api/auth/status.get.ts
@@ -17,7 +17,7 @@ export default defineEventHandler(async (event) => {
if (!configured) return { enabled: false }
try {
await platformDatabase(event)
- .prepare('SELECT id FROM platform_users LIMIT 1')
+ .prepare('SELECT id FROM platform_auth_sessions LIMIT 1')
.first()
return { enabled: true }
} catch {
diff --git a/apps/cloud/server/middleware/00-account-session.ts b/apps/cloud/server/middleware/00-account-session.ts
new file mode 100644
index 00000000..ce49f76d
--- /dev/null
+++ b/apps/cloud/server/middleware/00-account-session.ts
@@ -0,0 +1,18 @@
+import { getCookie, getRequestHeaders } from 'h3'
+import { cloudAccount } from '../utils/cloud-account'
+/** Provide Cloud's account session to shared Site authorization, with numeric identity intact. */
+export default defineEventHandler((event) => {
+ event.context.platformSessionResolver = async () => {
+ if (!getCookie(event, '__Host-chronoframe-auth')) return null
+ const session = await cloudAccount(event).api.getSession({
+ headers: new Headers(getRequestHeaders(event) as HeadersInit),
+ })
+ const id = Number(session?.user.id)
+ return session &&
+ session.user.emailVerified &&
+ Number.isSafeInteger(id) &&
+ id > 0
+ ? { userId: id, expiresAt: new Date(session.session.expiresAt).getTime() }
+ : null
+ }
+})
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index 381d9956..ca92bb85 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -1,3 +1,4 @@
+import { accountRouteAllowed } from '../utils/account-routes'
/** Enable explicit platform endpoints only; never fall back to Self-hosted APIs. */
export default defineEventHandler((event) => {
setResponseHeader(event, 'Cache-Control', 'no-store')
@@ -12,15 +13,14 @@ export default defineEventHandler((event) => {
}
const platformRoute =
[
- '/api/auth/email/request',
- '/api/auth/email/verify',
'/api/auth/status',
'/api/auth/session',
'/api/auth/logout',
+ '/api/auth/security',
'/api/sites',
].includes(path) ||
/^\/api\/sites\/[1-9][0-9]*\/(?:context|events)$/.test(path)
- if (platformRoute) return
+ if (platformRoute || accountRouteAllowed(path, event.method)) return
if (path === '/api' || (path.startsWith('/api/') && path !== '/api/health')) {
throw createError({ statusCode: 503, statusMessage: 'Service unavailable' })
}
diff --git a/apps/cloud/server/utils/account-auth.ts b/apps/cloud/server/utils/account-auth.ts
new file mode 100644
index 00000000..cd911e82
--- /dev/null
+++ b/apps/cloud/server/utils/account-auth.ts
@@ -0,0 +1,228 @@
+import 'reflect-metadata'
+import { betterAuth, type BetterAuthOptions } from 'better-auth'
+import { APIError } from 'better-auth/api'
+import { createEmailCodeCrypto } from '../../../shared/platform/crypto.ts'
+import { emailOTP, twoFactor } from 'better-auth/plugins'
+import { passkey } from '@better-auth/passkey'
+import type { PlatformEmailBinding } from '../../../shared/platform/email.ts'
+
+export interface AccountAuthConfig {
+ portalOrigin: string
+ secret: string
+ emailFrom: string
+}
+/** Request-scoped Workers/D1 auth. Existing platform user IDs and memberships stay intact. */
+export function accountAuthOptions(
+ database: BetterAuthOptions['database'],
+ config: AccountAuthConfig,
+ email: PlatformEmailBinding,
+) {
+ const origin = new URL(config.portalOrigin)
+ const send = async (to: string, subject: string, text: string) => {
+ await email.send({ from: config.emailFrom, to, subject, text })
+ }
+ return {
+ appName: 'ChronoFrame Cloud',
+ baseURL: origin.origin,
+ basePath: '/api/auth',
+ secret: config.secret,
+ database,
+ trustedOrigins: [origin.origin],
+ telemetry: { enabled: false },
+ advanced: {
+ database: { generateId: 'serial' },
+ // Every auth cookie has a browser-enforced host prefix. Avoid Better Auth
+ // prepending __Secure- to our already-prefixed __Host- names.
+ cookiePrefix: '__Host-chronoframe-cloud',
+ useSecureCookies: false,
+ defaultCookieAttributes: {
+ secure: true,
+ httpOnly: true,
+ sameSite: 'lax',
+ path: '/',
+ },
+ cookies: { session_token: { name: '__Host-chronoframe-auth' } },
+ ipAddress: { ipAddressHeaders: ['cf-connecting-ip'] },
+ },
+ user: {
+ modelName: 'platform_users',
+ fields: {
+ emailVerified: 'email_verified',
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ },
+ },
+ session: {
+ modelName: 'platform_auth_sessions',
+ fields: {
+ userId: 'user_id',
+ expiresAt: 'expires_at',
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ ipAddress: 'ip_address',
+ userAgent: 'user_agent',
+ },
+ expiresIn: 7 * 24 * 60 * 60,
+ freshAge: 10 * 60,
+ cookieCache: { enabled: false },
+ },
+ account: {
+ modelName: 'platform_accounts',
+ fields: {
+ userId: 'user_id',
+ accountId: 'account_id',
+ providerId: 'provider_id',
+ accessToken: 'access_token',
+ refreshToken: 'refresh_token',
+ idToken: 'id_token',
+ accessTokenExpiresAt: 'access_token_expires_at',
+ refreshTokenExpiresAt: 'refresh_token_expires_at',
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ },
+ },
+ verification: {
+ modelName: 'platform_verifications',
+ fields: {
+ expiresAt: 'expires_at',
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ },
+ },
+ rateLimit: {
+ enabled: true,
+ storage: 'database',
+ modelName: 'platform_auth_rate_limits',
+ window: 60,
+ max: 30,
+ customRules: {
+ '/sign-in/email': { window: 60, max: 5 },
+ '/request-password-reset': { window: 60, max: 3 },
+ '/sign-up/email': { window: 60, max: 3 },
+ },
+ },
+ emailAndPassword: {
+ enabled: true,
+ requireEmailVerification: true,
+ minPasswordLength: 12,
+ maxPasswordLength: 128,
+ revokeSessionsOnPasswordReset: true,
+ resetPasswordTokenExpiresIn: 30 * 60,
+ async sendResetPassword({ user, url }) {
+ await send(
+ 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.`,
+ )
+ },
+ },
+ emailVerification: {
+ autoSignInAfterVerification: true,
+ sendOnSignUp: true,
+ },
+ plugins: [
+ emailOTP({
+ disableSignUp: true,
+ overrideDefaultEmailVerification: true,
+ expiresIn: 600,
+ allowedAttempts: 5,
+ storeOTP: {
+ hash: async (otp) =>
+ (await createEmailCodeCrypto(config.secret)).mac([
+ 'account-otp',
+ otp,
+ ]),
+ },
+ async sendVerificationOTP({ email: to, otp, type }) {
+ const purpose =
+ type === 'email-verification' ? 'verify your email' : 'sign in'
+ await send(
+ to,
+ 'Your ChronoFrame Cloud verification code',
+ `Your code to ${purpose} is ${otp}. It expires in 10 minutes. Never share this code.`,
+ )
+ },
+ }),
+ twoFactor({
+ issuer: 'ChronoFrame Cloud',
+ schema: {
+ user: { fields: { twoFactorEnabled: 'two_factor_enabled' } },
+ twoFactor: {
+ modelName: 'platform_two_factors',
+ fields: {
+ userId: 'user_id',
+ backupCodes: 'backup_codes',
+ failedVerificationCount: 'failed_verification_count',
+ lockedUntil: 'locked_until',
+ },
+ },
+ },
+ otpOptions: {
+ storeOTP: {
+ hash: async (otp) =>
+ (await createEmailCodeCrypto(config.secret)).mac([
+ 'account-second-factor',
+ otp,
+ ]),
+ },
+ 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.`,
+ )
+ },
+ },
+ accountLockout: {
+ enabled: true,
+ maxFailedAttempts: 5,
+ durationSeconds: 900,
+ },
+ }),
+ passkey({
+ rpName: 'ChronoFrame Cloud',
+ rpID: origin.hostname,
+ origin: origin.origin,
+ authenticatorSelection: {
+ residentKey: 'required',
+ userVerification: 'required',
+ },
+ registration: {
+ requireSession: true,
+ afterVerification: async ({ verification }) => {
+ if (!verification.registrationInfo?.userVerified)
+ throw new APIError('UNAUTHORIZED', {
+ message: 'Passkey user verification is required',
+ })
+ },
+ },
+ authentication: {
+ afterVerification: async ({ verification }) => {
+ if (!verification.authenticationInfo.userVerified)
+ throw new APIError('UNAUTHORIZED', {
+ message: 'Passkey user verification is required',
+ })
+ },
+ },
+ schema: {
+ passkey: {
+ modelName: 'platform_passkeys',
+ fields: {
+ userId: 'user_id',
+ publicKey: 'public_key',
+ credentialID: 'credential_id',
+ deviceType: 'device_type',
+ backedUp: 'backed_up',
+ createdAt: 'created_at',
+ },
+ },
+ },
+ }),
+ ],
+ } satisfies BetterAuthOptions
+}
+export function createAccountAuth(
+ ...args: Parameters<typeof accountAuthOptions>
+) {
+ return betterAuth(accountAuthOptions(...args))
+}
diff --git a/apps/cloud/server/utils/account-handler.ts b/apps/cloud/server/utils/account-handler.ts
new file mode 100644
index 00000000..c44a69fe
--- /dev/null
+++ b/apps/cloud/server/utils/account-handler.ts
@@ -0,0 +1,77 @@
+import {
+ createError,
+ getRequestURL,
+ getRequestHeaders,
+ readRawBody,
+ getHeader,
+ sendWebResponse,
+} from 'h3'
+import type { H3Event } from 'h3'
+import {
+ platformDatabase,
+ platformPortalOrigin,
+ platformRequestURL,
+} from '../../../shared/platform/runtime'
+import { createEmailCodeCrypto } from '../../../shared/platform/crypto'
+import { cloudAccount } from './cloud-account'
+import { accountRouteAllowed } from './account-routes'
+
+/** Keep credentials on the canonical origin and share account-level limits across Workers. */
+export async function forwardAccountRequest(event: H3Event, rewrite?: string) {
+ const config = useRuntimeConfig(event).platform
+ platformPortalOrigin(event, config.portalOrigin, event.method !== 'GET')
+ const path = rewrite ? '/api/auth' + rewrite : getRequestURL(event).pathname
+ if (!accountRouteAllowed(path, event.method))
+ throw createError({ statusCode: 404 })
+ if (Number(getHeader(event, 'content-length')) > 32 * 1024)
+ throw createError({ statusCode: 400 })
+ const raw = event.method === 'GET' ? undefined : await readRawBody(event)
+ if (raw && new TextEncoder().encode(raw).length > 32 * 1024)
+ throw createError({ statusCode: 400 })
+ if (
+ raw &&
+ [
+ '/api/auth/sign-up/email',
+ '/api/auth/sign-in/email',
+ '/api/auth/sign-in/email-otp',
+ '/api/auth/email-otp/send-verification-otp',
+ '/api/auth/request-password-reset',
+ ].includes(path)
+ ) {
+ let body: { email?: unknown }
+ try {
+ body = JSON.parse(raw)
+ } catch {
+ throw createError({ statusCode: 400 })
+ }
+ if (typeof body.email === 'string' && body.email.length <= 254) {
+ const mac = await createEmailCodeCrypto(config.secret)
+ const key = await mac.mac([
+ 'account-attempt',
+ path,
+ body.email.trim().toLowerCase(),
+ ])
+ const now = Math.floor(Date.now() / (15 * 60_000))
+ const row = await platformDatabase(event)
+ .prepare(`INSERT INTO platform_auth_attempts(key, window_start, attempts) VALUES (?, ?, 1)
+ ON CONFLICT(key) DO UPDATE SET attempts = CASE WHEN window_start = excluded.window_start THEN attempts + 1 ELSE 1 END, window_start = excluded.window_start RETURNING attempts`)
+ .bind(key, now)
+ .first<{ attempts: number }>()
+ const max = path.includes('sign-in') ? 15 : 5
+ if (!row || row.attempts > max) throw createError({ statusCode: 429 })
+ }
+ }
+ const url = new URL(
+ path + getRequestURL(event).search,
+ platformRequestURL(event).origin,
+ )
+ const request = new Request(url, {
+ method: event.method,
+ headers: new Headers(getRequestHeaders(event) as HeadersInit),
+ ...(raw ? { body: raw } : {}),
+ })
+ const response = await cloudAccount(event).handler(request)
+ response.headers.set('cache-control', 'no-store')
+ response.headers.set('referrer-policy', 'no-referrer')
+ return sendWebResponse(event, response)
+}
diff --git a/apps/cloud/server/utils/account-routes.ts b/apps/cloud/server/utils/account-routes.ts
new file mode 100644
index 00000000..1e8beb51
--- /dev/null
+++ b/apps/cloud/server/utils/account-routes.ts
@@ -0,0 +1,37 @@
+/** Explicit public account surface; internal OTP retrieval and unrelated plugin APIs stay closed. */
+export const ACCOUNT_POST_ROUTES = new Set([
+ '/sign-up/email',
+ '/sign-in/email',
+ '/sign-in/email-otp',
+ '/sign-out',
+ '/email-otp/send-verification-otp',
+ '/email-otp/verify-email',
+ '/request-password-reset',
+ '/reset-password',
+ '/change-password',
+ '/two-factor/enable',
+ '/two-factor/disable',
+ '/two-factor/send-otp',
+ '/two-factor/verify-otp',
+ '/two-factor/verify-totp',
+ '/two-factor/verify-backup-code',
+ '/two-factor/generate-backup-codes',
+ '/passkey/verify-registration',
+ '/passkey/verify-authentication',
+ '/passkey/delete-passkey',
+])
+export const ACCOUNT_GET_ROUTES = new Set([
+ '/get-session',
+ '/passkey/generate-register-options',
+ '/passkey/generate-authenticate-options',
+ '/passkey/list-user-passkeys',
+])
+export function accountRouteAllowed(path: string, method?: string) {
+ const endpoint = path.replace(/^\/api\/auth/, '')
+ return (
+ ((!method || method === 'POST') && ACCOUNT_POST_ROUTES.has(endpoint)) ||
+ ((!method || method === 'GET') &&
+ (ACCOUNT_GET_ROUTES.has(endpoint) ||
+ /^\/reset-password\/[a-zA-Z0-9_-]{10,256}$/.test(endpoint)))
+ )
+}
diff --git a/apps/cloud/server/utils/cloud-account.ts b/apps/cloud/server/utils/cloud-account.ts
new file mode 100644
index 00000000..98fa76a1
--- /dev/null
+++ b/apps/cloud/server/utils/cloud-account.ts
@@ -0,0 +1,17 @@
+import type { H3Event } from 'h3'
+import type { BetterAuthOptions } from 'better-auth'
+import { createAccountAuth } from './account-auth'
+import { platformDatabase } from '../../../shared/platform/runtime'
+import type { PlatformEmailBinding } from '../../../shared/platform/email'
+/** Cache only within this H3 request; never share an identity between requests. */
+export function cloudAccount(event: H3Event) {
+ if (!event.context.cloudAccountAuth) {
+ const config = useRuntimeConfig(event).platform
+ event.context.cloudAccountAuth = createAccountAuth(
+ platformDatabase(event) as unknown as BetterAuthOptions['database'],
+ config,
+ event.context.cloudflare?.env?.EMAIL as PlatformEmailBinding,
+ )
+ }
+ return event.context.cloudAccountAuth as ReturnType<typeof createAccountAuth>
+}
diff --git a/apps/cloud/server/utils/platform-auth.ts b/apps/cloud/server/utils/platform-auth.ts
deleted file mode 100644
index 9a99507f..00000000
--- a/apps/cloud/server/utils/platform-auth.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { createEmailCodeSignIn } from '../../../../packages/core/src/email-auth'
-import { createD1EmailCodeStore } from '../../../../packages/platform/src/index'
-import {
- platformDatabase,
- platformPortalOrigin,
-} from '../../../shared/platform/runtime'
-import { createEmailCodeCrypto } from '../../../shared/platform/crypto'
-import type { H3Event } from 'h3'
-import {
- createCloudflareEmailSender,
- platformEmailReady,
-} from '../../../shared/platform/email'
-
-export async function emailSignIn(event: H3Event) {
- const config = useRuntimeConfig(event).platform
- platformPortalOrigin(event, config.portalOrigin, true)
- const emailBinding = event.context.cloudflare?.env?.EMAIL
- if (
- !platformEmailReady(emailBinding, config.emailFrom) ||
- config.secret.length < 32
- ) {
- throw createError({
- statusCode: 503,
- statusMessage: 'Email sign-in is not configured',
- })
- }
- return createEmailCodeSignIn(
- createD1EmailCodeStore(platformDatabase(event)),
- await createEmailCodeCrypto(config.secret),
- createCloudflareEmailSender(emailBinding, config.emailFrom),
- )
-}
diff --git a/apps/shared/platform/runtime.ts b/apps/shared/platform/runtime.ts
index 3825795e..7ba9cacb 100644
--- a/apps/shared/platform/runtime.ts
+++ b/apps/shared/platform/runtime.ts
@@ -54,6 +54,8 @@ export async function platformSession(
event: H3Event,
secret: string,
): Promise<PlatformSession | null> {
+ if (event.context.platformSessionResolver)
+ return event.context.platformSessionResolver()
const token = getCookie(event, PLATFORM_COOKIE)
if (!token || secret.length < 32) return null
if (!/^[a-f0-9-]{36}$/.test(token)) return null
diff --git a/packages/platform/migrations/0003_account_security.sql b/packages/platform/migrations/0003_account_security.sql
new file mode 100644
index 00000000..95af1f6c
--- /dev/null
+++ b/packages/platform/migrations/0003_account_security.sql
@@ -0,0 +1,94 @@
+-- Add password, verified email, MFA and WebAuthn without changing platform identities.
+-- Existing users already proved email ownership through the previous email-code flow.
+ALTER TABLE platform_users ADD COLUMN name TEXT NOT NULL DEFAULT '';
+ALTER TABLE platform_users ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 1;
+ALTER TABLE platform_users ADD COLUMN image TEXT;
+ALTER TABLE platform_users ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE platform_users ADD COLUMN two_factor_enabled INTEGER NOT NULL DEFAULT 0;
+UPDATE platform_users SET name = email, updated_at = created_at;
+-- A one-time reauthentication is required; old challenge endpoints are retired.
+DELETE FROM platform_sessions;
+UPDATE platform_email_codes SET active = 0;
+
+CREATE TABLE platform_auth_sessions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ "expires_at" INTEGER NOT NULL,
+ "token" TEXT NOT NULL UNIQUE,
+ "created_at" INTEGER NOT NULL,
+ "updated_at" INTEGER NOT NULL,
+ "ip_address" TEXT,
+ "user_agent" TEXT,
+ "user_id" INTEGER NOT NULL REFERENCES platform_users(id) ON DELETE CASCADE
+);
+CREATE INDEX platform_auth_sessions_user_id_idx ON platform_auth_sessions("user_id");
+
+CREATE TABLE platform_accounts (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ "account_id" TEXT NOT NULL,
+ "provider_id" TEXT NOT NULL,
+ "user_id" INTEGER NOT NULL REFERENCES platform_users(id) ON DELETE CASCADE,
+ "access_token" TEXT,
+ "refresh_token" TEXT,
+ "id_token" TEXT,
+ "access_token_expires_at" INTEGER,
+ "refresh_token_expires_at" INTEGER,
+ "scope" TEXT,
+ "password" TEXT,
+ "created_at" INTEGER NOT NULL,
+ "updated_at" INTEGER NOT NULL
+);
+CREATE INDEX platform_accounts_user_id_idx ON platform_accounts("user_id");
+
+CREATE TABLE platform_verifications (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ "identifier" TEXT NOT NULL,
+ "value" TEXT NOT NULL,
+ "expires_at" INTEGER NOT NULL,
+ "created_at" INTEGER NOT NULL,
+ "updated_at" INTEGER NOT NULL
+);
+CREATE INDEX platform_verifications_identifier_idx ON platform_verifications("identifier");
+
+CREATE TABLE platform_two_factors (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ "secret" TEXT NOT NULL,
+ "backup_codes" TEXT NOT NULL,
+ "user_id" INTEGER NOT NULL REFERENCES platform_users(id) ON DELETE CASCADE,
+ "verified" INTEGER DEFAULT 1,
+ "failed_verification_count" INTEGER DEFAULT 0,
+ "locked_until" INTEGER
+);
+CREATE INDEX platform_two_factors_secret_idx ON platform_two_factors("secret");
+CREATE INDEX platform_two_factors_user_id_idx ON platform_two_factors("user_id");
+
+CREATE TABLE platform_passkeys (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ "name" TEXT,
+ "public_key" TEXT NOT NULL,
+ "user_id" INTEGER NOT NULL REFERENCES platform_users(id) ON DELETE CASCADE,
+ "credential_id" TEXT NOT NULL,
+ "counter" INTEGER NOT NULL,
+ "device_type" TEXT NOT NULL,
+ "backed_up" INTEGER NOT NULL,
+ "transports" TEXT,
+ "created_at" INTEGER,
+ "aaguid" TEXT
+);
+CREATE INDEX platform_passkeys_user_id_idx ON platform_passkeys("user_id");
+CREATE INDEX platform_passkeys_credential_id_idx ON platform_passkeys("credential_id");
+
+CREATE TABLE platform_auth_rate_limits (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ "key" TEXT NOT NULL UNIQUE,
+ "count" INTEGER NOT NULL,
+ "lastRequest" INTEGER NOT NULL
+);
+
+CREATE UNIQUE INDEX platform_accounts_provider_idx ON platform_accounts(provider_id, account_id);
+CREATE UNIQUE INDEX platform_two_factors_user_idx ON platform_two_factors(user_id);
+CREATE UNIQUE INDEX platform_passkeys_credential_idx ON platform_passkeys(credential_id);
+CREATE TABLE platform_auth_attempts (
+ key TEXT PRIMARY KEY,
+ window_start INTEGER NOT NULL,
+ attempts INTEGER NOT NULL
+);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c9f26ecd..bf02ec85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -709,6 +709,18 @@ importers:
apps/cloud:
dependencies:
+ better-auth:
+ specifier: 1.7.12
+ '@better-auth/passkey':
+ specifier: 1.7.12
+ qrcode:
+ specifier: ^1.5.4
+ version: 1.5.4
+ reflect-metadata:
+ specifier: 0.2.2
+ version: 0.2.2
shadcn-nuxt:
specifier: ^2.8.2
version: 2.8.2(@emnapi/[email protected])(@emnapi/[email protected])([email protected])
@@ -9416,6 +9428,336 @@ packages:
resolution:
integrity: sha512-MjHCs7tAO/xJDk80JUeHe2QtkOAN3a/qEK5zX4UTrZY0q1/pFglBdf88OUC+w0SNZJBIeCMjdth57ucK74hM5g==
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-SUStBGHJ13KnSO6+7U/1DSlfuOtln4jtOrFZqzQtxZVHZIrAoMjwHNGitlF+s7hvKbuC3Z14xjnqfLLqIqGfxw==
+ peerDependencies:
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ '@better-fetch/fetch': 1.3.2
+ '@opentelemetry/api': ^1.9.0
+ better-call: 1.4.4
+ jose: ^6.1.0
+ kysely: ^0.28.5 || ^0.29.0
+ nanostores: ^1.0.1
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-Qzoyuf05aK01Pc0k3EXv8Xj3XCT2m2dCWc5HoB7x+xX6N3Pm2eQsca+UIArsJcbuNEWWP3L51oIebnBoHJ5DTw==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ drizzle-orm: ^0.45.2 || >=1.0.0-rc.1 <2.0.0
+ peerDependenciesMeta:
+ drizzle-orm:
+ optional: true
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-1PaFXktLv4n3DmrGbPaCj5SsvcT40NnWw7NLua5/J1+8/A051N5ZzqOwJifXEIQX5k6NdwvmymwDQxKytduEAQ==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ kysely: ^0.28.17 || ^0.29.0
+ peerDependenciesMeta:
+ kysely:
+ optional: true
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-glaDwXzDptnddHqRuu7fj47FAssUcOzLNgdlTGJoEPrspkX69x2vnXwgAzNuApjZI21WLtPH/rQ6CN+DQGybPA==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-HKV4sgYSw/Gdt9AuHlESMkiKL72SWdGweDy1Wsyxoh06BpG7aNu4aSJ7marNpMdKZteyRbxWWqQkA9ediA8qFw==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ mongodb: ^6.0.0 || ^7.0.0
+ peerDependenciesMeta:
+ mongodb:
+ optional: true
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-DV775/rqg56sxOo13xo6RcFEtVYMXvUBWIhovadzsroZX7JF8VBQC+fLCcYoG1+n5yniI2l5r3PB5+Zt2UNYjg==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ '@better-fetch/fetch': 1.3.2
+ better-auth: ^1.7.12
+ better-call: 1.4.4
+ nanostores: ^1.0.1
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-FZRX6ORbwhDmeYE1Tl0IPtUn8v3BlVFgbJxDnm/DCNHxuFRf+0t4HfddUgYeYehHFR8aSDsdYX44fEFWM9877w==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0
+ prisma: ^5.0.0 || ^6.0.0 || ^7.0.0
+ peerDependenciesMeta:
+ '@prisma/client':
+ optional: true
+ prisma:
+ optional: true
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-DaDkKNnI99vKGGbWq9KJg2uYeaOjsK9nIBw9T2m2KG/RkxpvQRjYkZ00++up2bZQkR5pB1nukGbplza3UJG/Xg==
+ peerDependencies:
+ '@better-auth/core': ^1.7.12
+ '@better-auth/utils': ^0.4.2 || ^0.5.0
+ '@better-fetch/fetch': 1.3.2
+ '@better-auth/[email protected]':
+ resolution:
+ integrity: sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA==
+ '@better-fetch/[email protected]':
+ resolution:
+ integrity: sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow==
+ '@hexagon/[email protected]':
+ resolution:
+ integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==
+ '@levischuck/[email protected]':
+ resolution:
+ integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==
+ '@noble/[email protected]':
+ resolution:
+ integrity: sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==
+ engines:
+ node: '>= 20.19.0'
+ '@noble/[email protected]':
+ resolution:
+ integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==
+ engines:
+ node: '>= 20.19.0'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-llW/qjavL+tOxt5i9whUv4wsbsLpUwI6k/DrvKsdA/H7A/TB/6CosMFgvei28fcJ8ncD0c5lig1oBBlo4KGMCw==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-SlAiDoT/Cd8qaNmbTt78gqyaEvu2fQd6ML6KWJkdjXGrgDKnHHrusVkfQUelkfinL2p665IIADb0JBixtT8W1g==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-M/ED0yJ05qMK+UADPKnIa8vhAeewOJALSxTAZB7RQ/batRHhIJZkwznCcWAbFO5saHJ1yEQ+m4lncEcG9RnQSg==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-jj1alGEKev7/un+cI+exyVK9m31lmP7cCBMCZuCb0wkFQH2zmKmJzNiG4wqXFNzlcP8timHLnzf3lV3OxBpb/Q==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-ykSAWRu8KkmzU8LRpk9ZQC3zuLmBEtoSMjIv9XHVamD5W7amqreV5wttKqnvtjWOzzSJQxA/HVT8/tHwpEEGSQ==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-lragjkjQGnQ5luxC+sxoAfAO/jBiQ7hOEGlDKJUk7MC5zY3AzjB2DU0GyPUH1Sswdv10t7DurY0zylOYMLb88w==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-gDdFjpqV0weJjgNUvueUVf4D8uVbpq+VbG0TsxLAY2QGljAkJyL9qwQ7avol9j0jaYSJ7Ey7v7RZp0M3GTcQSA==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-S2sBJmbfI09Kzdt9cEhE6pDNjHpVTkURs+811+PxS8AvsTLxC4woMNRhxHYaIbClkkNfAVt0tZxJdINVfUmzuA==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-8xh4avo53/vXO6UEv9yaoJ83hY581geaLTygf61NPIXP5AeIZCPjJhpTaYU23IZkG+NpLN/C9FYzWp7hphIT9A==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-Fgvnd9REmLxEj/4cbDP54dNUNUXkzUksXLqEHqs1mHBuSRjSTCUSPM/WQIZYSvrdG7ND9CX1AQtPoIBekhgQSA==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-J1sHAwGNlk+8J+FeR1eLVc6Gq0T9f9ITc3HWyPYgJraoW6U8AJuQiWVJ3SCEpltfTdpOY7fHdHT5oKAsbK/jww==
+ engines:
+ node: '>=14'
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==
+ '@peculiar/[email protected]':
+ resolution:
+ integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==
+ engines:
+ node: '>=20.0.0'
+ '@simplewebauthn/[email protected]':
+ resolution:
+ integrity: sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ==
+ '@simplewebauthn/[email protected]':
+ resolution:
+ integrity: sha512-LelX/lcy5cjc15A86i/aNxHhB5eU7dd20QsbP0VLAf9e38+SLlsnqCCyecx3xqfGofhmX05h1J9fKRYWxw+luA==
+ engines:
+ node: '>=20.0.0'
+ resolution:
+ integrity: sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==
+ engines:
+ node: '>=12.0.0'
+ resolution:
+ integrity: sha512-f1fEG0QdTslzbmFA+vOGFFW/XXCWkG4kBxLeH9n1vp1otTH9+ZzV6EJ6797GStWeiYYgS5Vnt9xqE12KwSyAAw==
+ peerDependencies:
+ '@lynx-js/react': '*'
+ '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0
+ '@sveltejs/kit': ^2.0.0 || ^3.0.0
+ '@tanstack/react-start': ^1.0.0
+ '@tanstack/solid-start': ^1.0.0
+ drizzle-kit: '>=0.31.4 || >=1.0.0-beta.1'
+ drizzle-orm: ^0.45.2 || >=1.0.0-rc.1 <2.0.0
+ mongodb: ^6.0.0 || ^7.0.0
+ mysql2: ^3.0.0
+ next: ^14.0.0 || ^15.0.0 || ^16.0.0
+ pg: ^8.0.0
+ prisma: ^5.0.0 || ^6.0.0 || ^7.0.0
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ solid-js: ^1.0.0
+ svelte: ^4.0.0 || ^5.0.0
+ vitest: ^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0
+ vue: ^3.0.0
+ peerDependenciesMeta:
+ '@lynx-js/react':
+ optional: true
+ '@prisma/client':
+ optional: true
+ '@sveltejs/kit':
+ optional: true
+ '@tanstack/react-start':
+ optional: true
+ '@tanstack/solid-start':
+ optional: true
+ drizzle-kit:
+ optional: true
+ drizzle-orm:
+ optional: true
+ mongodb:
+ optional: true
+ mysql2:
+ optional: true
+ next:
+ optional: true
+ pg:
+ optional: true
+ prisma:
+ optional: true
+ react:
+ optional: true
+ react-dom:
+ optional: true
+ solid-js:
+ optional: true
+ svelte:
+ optional: true
+ vitest:
+ optional: true
+ vue:
+ optional: true
+ resolution:
+ integrity: sha512-Gq4XdGFy4dmUxFEAX2nj0ycFcFbD9ZWh8YROouZoyXeF1M11TpYbplk0pDByTFF8Wz+MYa6W9052c9m7dD+mfw==
+ peerDependencies:
+ zod: ^4.0.0
+ peerDependenciesMeta:
+ zod:
+ optional: true
+ resolution:
+ integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==
+ resolution:
+ integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==
+ resolution:
+ integrity: sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==
+ resolution:
+ integrity: sha512-fmIq+7kv4WbFm2tcfznRzikqB4cuNpgZ40PSU2fAJ2/OO5XhojqnTPrmgrCjYSRJVwBln03XcRXJGnw9H099IQ==
+ engines:
+ node: '>=22.0.0'
+ resolution:
+ integrity: sha512-FixtE239Gl6Gz0ZGCK0WzvNwObNCIwVT+L7zQcf1QgcA6AzBxblzqe9OT88qiucNkhsjSOqiogSaF5jVbJiqSA==
+ engines:
+ node: ^20.0.0 || >=22.0.0
+ resolution:
+ integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==
+ engines:
+ node: '>=10.13.0'
+ resolution:
+ integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==
+ resolution:
+ integrity: sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==
+ engines:
+ node: '>=16.0.0'
+ resolution:
+ integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==
+ engines:
+ node: '>=10.13.0'
+ hasBin: true
+ resolution:
+ integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==
+ resolution:
+ integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==
+ engines:
+ node: '>=0.10.0'
+ resolution:
+ integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==
+ resolution:
+ integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==
+ resolution:
+ integrity: sha512-Npd1Pt+4zb3BrSZDPd2qFwRpS6b1EUEasRrO8xS0zMJi0fApXXK5YuzP0minyJnxwnFHoVoJwA55q0A0cu63gQ==
+ resolution:
+ integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
+ resolution:
+ integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==
+ engines:
+ node: '>= 6.0.0'
+ resolution:
+ integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==
+ resolution:
+ integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==
+ engines:
+ node: '>=8'
+ resolution:
+ integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==
+ resolution:
+ integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==
+ engines:
+ node: '>=6'
+ resolution:
+ integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==
+ engines:
+ node: '>=8'
+
snapshots:
'@adonisjs/[email protected]':
@@ -18332,3 +18674,259 @@ snapshots:
- '@emnapi/core'
- '@emnapi/runtime'
- magicast
+
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ '@better-fetch/fetch': 1.3.2
+ '@standard-schema/spec': 1.1.0
+ better-call: 1.4.4([email protected])
+ jose: 6.2.13
+ kysely: 0.29.7
+ nanostores: 1.5.5
+ zod: 4.6.6
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ optionalDependencies:
+ drizzle-orm: 0.45.4(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ optionalDependencies:
+ kysely: 0.29.7
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ '@better-fetch/fetch': 1.3.2
+ '@simplewebauthn/browser': 13.3.0
+ '@simplewebauthn/server': 13.3.3
+ better-call: 1.4.4([email protected])
+ nanostores: 1.5.5
+ zod: 4.6.6
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ : dependencies:
+ '@better-auth/utils': 0.5.0
+ '@better-fetch/fetch': 1.3.2
+ '@better-auth/[email protected]':
+ dependencies:
+ '@noble/hashes': 2.4.0
+ '@better-fetch/[email protected]': {}
+ '@hexagon/[email protected]': {}
+ '@levischuck/[email protected]': {}
+ '@noble/[email protected]': {}
+ '@noble/[email protected]': {}
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ '@peculiar/asn1-x509-attr': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.11.0
+ '@peculiar/asn1-pkcs8': 2.11.0
+ '@peculiar/asn1-rsa': 2.11.0
+ '@peculiar/asn1-schema': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.11.0
+ '@peculiar/asn1-pfx': 2.11.0
+ '@peculiar/asn1-pkcs8': 2.11.0
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ '@peculiar/asn1-x509-attr': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/utils': 2.0.3
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/utils': 2.0.3
+ asn1js: 3.1.0
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.11.0
+ '@peculiar/asn1-csr': 2.11.0
+ '@peculiar/asn1-ecc': 2.11.0
+ '@peculiar/asn1-pkcs9': 2.11.0
+ '@peculiar/asn1-rsa': 2.11.0
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ pvtsutils: 1.3.6
+ reflect-metadata: 0.2.2
+ tslib: 2.8.1
+ tsyringe: 4.10.0
+ '@simplewebauthn/[email protected]': {}
+ '@simplewebauthn/[email protected]':
+ dependencies:
+ '@hexagon/base64': 1.1.28
+ '@levischuck/tiny-cbor': 0.2.11
+ '@peculiar/asn1-android': 2.11.0
+ '@peculiar/asn1-ecc': 2.11.0
+ '@peculiar/asn1-rsa': 2.11.0
+ '@peculiar/asn1-schema': 2.11.0
+ '@peculiar/asn1-x509': 2.11.0
+ '@peculiar/x509': 1.14.3
+ dependencies:
+ pvtsutils: 1.3.6
+ pvutils: 1.2.0
+ tslib: 2.8.1
+ : dependencies:
+ '@better-auth/memory-adapter': 1.7.12(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/mongo-adapter': 1.7.12(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/prisma-adapter': 1.7.12(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/telemetry': 1.7.12(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
+ '@better-auth/utils': 0.5.0
+ '@better-fetch/fetch': 1.3.2
+ '@noble/ciphers': 2.4.0
+ '@noble/hashes': 2.4.0
+ better-call: 1.4.4([email protected])
+ defu: 6.1.7
+ jose: 6.2.13
+ kysely: 0.29.7
+ nanostores: 1.5.5
+ zod: 4.6.6
+ optionalDependencies:
+ drizzle-kit: 0.31.11
+ drizzle-orm: 0.45.4(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])
+ vue: 3.5.43([email protected])
+ transitivePeerDependencies:
+ - '@opentelemetry/api'
+ dependencies:
+ '@better-auth/utils': 0.5.0
+ '@better-fetch/fetch': 1.3.2
+ rou3: 0.9.2
+ set-cookie-parser: 3.2.1
+ optionalDependencies:
+ zod: 4.6.6
+ dependencies:
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+ wrap-ansi: 6.2.0
+ : optionalDependencies:
+ '@cloudflare/workers-types': 4.20260402.1
+ '@opentelemetry/api': 1.9.0
+ '@types/better-sqlite3': 9.6.0
+ better-sqlite3: 12.11.1
+ kysely: 0.29.7
+ dependencies:
+ tslib: 2.8.1
+ dependencies:
+ dijkstrajs: 1.0.3
+ pngjs: 5.0.0
+ yargs: 15.4.1
+ dependencies:
+ tslib: 1.14.1
+ dependencies:
+ ansi-styles: 4.3.0
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+ dependencies:
+ camelcase: 5.3.1
+ decamelize: 1.2.0
+ dependencies:
+ cliui: 6.0.0
+ decamelize: 1.2.0
+ find-up: 4.1.0
+ get-caller-file: 2.0.5
+ require-directory: 2.1.1
+ require-main-filename: 2.0.0
+ set-blocking: 2.0.0
+ string-width: 4.2.3
+ which-module: 2.0.1
+ y18n: 4.0.3
+ yargs-parser: 18.1.3
diff --git a/tests/cloud-account-security.test.ts b/tests/cloud-account-security.test.ts
new file mode 100644
index 00000000..abaf6f21
--- /dev/null
+++ b/tests/cloud-account-security.test.ts
@@ -0,0 +1,419 @@
+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 { createAccountAuth } from '../apps/cloud/server/utils/account-auth.ts'
+
+const require = createRequire(import.meta.url)
+const wranglerRequire = createRequire(require.resolve('wrangler/package.json'))
+const { Miniflare, convertV4MiniflareOptions } = wranglerRequire('miniflare')
+
+test('Cloud account migration preserves identities and enforces verified registration, MFA and reset tokens', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-22',
+ script: 'export default {fetch(){return new Response("test")}}',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ async function migration(name: string) {
+ const sql = await readFile(
+ new URL('../packages/platform/migrations/' + name, import.meta.url),
+ 'utf8',
+ )
+ for (const statement of sql
+ .replace(/^--.*$/gm, '')
+ .split(';')
+ .map((s) => s.trim())
+ .filter(Boolean))
+ await db.prepare(statement).run()
+ }
+ await migration('0001_platform.sql')
+ await db
+ .prepare(
+ "INSERT INTO platform_users (id,email,created_at) VALUES(42,'[email protected]',1)",
+ )
+ .run()
+ await db
+ .prepare("INSERT INTO platform_workspaces VALUES(1,'Existing workspace')")
+ .run()
+ await db
+ .prepare("INSERT INTO platform_memberships VALUES(42,1,'admin')")
+ .run()
+ await migration('0002_visitor_access.sql')
+ await migration('0003_account_security.sql')
+ assert.equal(
+ (await db.prepare('SELECT user_id FROM platform_memberships').first())
+ .user_id,
+ 42,
+ )
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT email_verified FROM platform_users WHERE id=42')
+ .first()
+ ).email_verified,
+ 1,
+ )
+ const messages: { to: string; subject: string; text: string }[] = []
+ const auth = createAccountAuth(
+ db,
+ {
+ portalOrigin: 'https://app.chronoframe.art',
+ emailFrom: '[email protected]',
+ secret: crypto.randomUUID() + crypto.randomUUID(),
+ },
+ {
+ send: async (message) => {
+ messages.push(message)
+ return { messageId: crypto.randomUUID() }
+ },
+ },
+ )
+ let cookies = new Map<string, string>()
+ let requestId = 1
+ async function call(path: string, body?: unknown, csrf = true) {
+ const response = await auth.handler(
+ new Request('https://app.chronoframe.art/api/auth' + path, {
+ method: body ? 'POST' : 'GET',
+ headers: {
+ ...(csrf
+ ? { origin: 'https://app.chronoframe.art' }
+ : { origin: 'https://evil.example.com' }),
+ 'content-type': 'application/json',
+ 'cf-connecting-ip': `192.0.2.${requestId++}`,
+ cookie: [...cookies].map(([k, v]) => k + '=' + v).join('; '),
+ },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ }),
+ )
+ for (const cookie of response.headers.getSetCookie()) {
+ const pair = cookie.split(';')[0]!
+ const i = pair.indexOf('=')
+ cookies.set(pair.slice(0, i), pair.slice(i + 1))
+ }
+ const text = await response.text()
+ let data: any
+ try {
+ data = JSON.parse(text)
+ } catch {
+ data = text
+ }
+ return { response, data }
+ }
+ const email = '[email protected]',
+ password = 'A!' + crypto.randomUUID()
+ assert.equal(
+ (
+ await call(
+ '/sign-up/email',
+ { email, password, name: 'New photographer' },
+ false,
+ )
+ ).response.status,
+ 403,
+ )
+ const signup = await call('/sign-up/email', {
+ email,
+ password,
+ name: 'New photographer',
+ })
+ assert.equal(signup.response.status, 200, JSON.stringify(signup.data))
+ assert.equal((await call('/get-session')).data, null)
+ assert.ok(
+ (await call('/sign-in/email', { email, password })).response.status >=
+ 400,
+ 'unverified password cannot create a session',
+ )
+ const otp = messages.at(-1)!.text.match(/\b[0-9]{6}\b/)![0]
+ const verified = await call('/email-otp/verify-email', { email, otp })
+ assert.equal(verified.response.status, 200, JSON.stringify(verified.data))
+ assert.equal((await call('/get-session')).data.user.emailVerified, true)
+ const sessionCookie = verified.response.headers
+ .getSetCookie()
+ .find((c) => c.startsWith('__Host-chronoframe-auth='))
+ assert.ok(
+ sessionCookie,
+ 'session uses the browser-enforced host prefix without a double prefix',
+ )
+ assert.match(sessionCookie, /Secure/)
+ assert.match(sessionCookie, /HttpOnly/)
+ assert.match(sessionCookie, /SameSite=Lax/i)
+ assert.doesNotMatch(sessionCookie, /Domain=/i)
+ assert.ok(
+ (await call('/email-otp/verify-email', { email, otp })).response.status >=
+ 400,
+ )
+ const passkey = await call('/passkey/generate-register-options')
+ assert.equal(passkey.response.status, 200, JSON.stringify(passkey.data))
+ assert.equal(passkey.data.rp.id, 'app.chronoframe.art')
+ assert.equal(
+ passkey.data.authenticatorSelection.userVerification,
+ 'required',
+ )
+ assert.equal(
+ (await call('/two-factor/enable', { password, method: 'otp' })).response
+ .status,
+ 200,
+ )
+ await call('/sign-out', {})
+ const login = await call('/sign-in/email', { email, password })
+ assert.equal(login.response.status, 200, JSON.stringify(login.data))
+ assert.equal(login.data.twoFactorRedirect, true)
+ assert.equal(
+ (await call('/get-session')).data,
+ null,
+ 'password alone must not issue an authenticated session',
+ )
+ assert.equal((await call('/two-factor/send-otp', {})).response.status, 200)
+ const second = messages.at(-1)!.text.match(/\b[0-9]{6}\b/)![0]
+ const secondVerified = await call('/two-factor/verify-otp', {
+ code: second,
+ })
+ assert.equal(
+ secondVerified.response.status,
+ 200,
+ JSON.stringify(secondVerified.data),
+ )
+ assert.ok((await call('/get-session')).data.user)
+ assert.equal(
+ (await call('/two-factor/disable', { password })).response.status,
+ 200,
+ )
+ const setup = await call('/two-factor/enable', { password, method: 'totp' })
+ assert.equal(setup.response.status, 200, JSON.stringify(setup.data))
+ assert.ok(setup.data.totpURI.startsWith('otpauth://'))
+ assert.ok(setup.data.backupCodes.length >= 8)
+ function totp(uri: string) {
+ const secret = new URL(uri).searchParams.get('secret')!
+ let bits = ''
+ for (const c of secret.replace(/=+$/, ''))
+ bits += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
+ .indexOf(c.toUpperCase())
+ .toString(2)
+ .padStart(5, '0')
+ const key = Buffer.from(
+ (bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)),
+ )
+ const counter = Buffer.alloc(8)
+ counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30000)))
+ const h = createHmac('sha1', key).update(counter).digest(),
+ offset = h[19]! & 15
+ return ((h.readUInt32BE(offset) & 0x7fffffff) % 1000000)
+ .toString()
+ .padStart(6, '0')
+ }
+ const storedFactor = await db
+ .prepare('SELECT secret, backup_codes FROM platform_two_factors')
+ .first()
+ assert.ok(
+ !storedFactor.secret.includes(
+ new URL(setup.data.totpURI).searchParams.get('secret'),
+ ),
+ 'authenticator seed is encrypted at rest',
+ )
+ assert.ok(
+ !storedFactor.backup_codes.includes(setup.data.backupCodes[0]),
+ 'recovery codes are protected at rest',
+ )
+ const enrollmentCode = totp(setup.data.totpURI)
+ assert.equal(
+ (await call('/two-factor/verify-totp', { code: enrollmentCode })).response
+ .status,
+ 200,
+ )
+ await call('/sign-out', {})
+ assert.equal(
+ (await call('/sign-in/email', { email, password })).data
+ .twoFactorRedirect,
+ true,
+ )
+ assert.equal((await call('/get-session')).data, null)
+ assert.ok(
+ (await call('/two-factor/verify-totp', { code: 'invalid' })).response
+ .status >= 400,
+ )
+ for (let attempt = 0; attempt < 5; attempt++) {
+ await call('/sign-in/email', { email, password })
+ assert.ok(
+ (await call('/two-factor/verify-totp', { code: 'invalid' })).response
+ .status >= 400,
+ )
+ }
+ assert.ok(
+ (
+ await call('/two-factor/verify-backup-code', {
+ code: setup.data.backupCodes[0],
+ })
+ ).response.status >= 400,
+ 'account lockout survives fresh challenges and changing IPs',
+ )
+ // Reset only the local fixture lock so the independent recovery lifecycle can continue.
+ await db
+ .prepare(
+ 'UPDATE platform_two_factors SET failed_verification_count = 0, locked_until = NULL',
+ )
+ .run()
+ await call('/sign-in/email', { email, password })
+ assert.equal(
+ (
+ await call('/two-factor/verify-backup-code', {
+ code: setup.data.backupCodes[0],
+ })
+ ).response.status,
+ 200,
+ )
+ await call('/sign-out', {})
+ assert.equal(
+ (await call('/sign-in/email', { email, password })).data
+ .twoFactorRedirect,
+ true,
+ )
+ assert.ok(
+ (
+ await call('/two-factor/verify-backup-code', {
+ code: setup.data.backupCodes[0],
+ })
+ ).response.status >= 400,
+ 'recovery codes are one use',
+ )
+ assert.equal(
+ (
+ await call('/two-factor/verify-backup-code', {
+ code: setup.data.backupCodes[1],
+ })
+ ).response.status,
+ 200,
+ )
+ await call('/two-factor/disable', { password })
+ assert.ok(
+ (
+ await call('/request-password-reset', {
+ email,
+ redirectTo: 'https://evil.example.com/reset',
+ })
+ ).response.status >= 400,
+ )
+
+ const reset = await call('/request-password-reset', {
+ email,
+ redirectTo: 'https://app.chronoframe.art/reset-password',
+ })
+ assert.equal(reset.response.status, 200, JSON.stringify(reset.data))
+ const link = messages.at(-1)!.text.match(/https:\/\/\S+/)![0]
+ const token = new URL(link).pathname.split('/').at(-1)
+ const newPassword = 'B!' + crypto.randomUUID()
+ const changed = await call('/reset-password', { token, newPassword })
+ assert.equal(changed.response.status, 200, JSON.stringify(changed.data))
+ assert.equal(
+ (await call('/get-session')).data,
+ null,
+ 'password reset revokes prior sessions',
+ )
+ assert.ok(
+ (await call('/reset-password', { token, newPassword })).response.status >=
+ 400,
+ )
+ cookies = new Map()
+ assert.ok(
+ (await call('/sign-in/email', { email, password })).response.status >=
+ 400,
+ )
+ assert.equal(
+ (await call('/sign-in/email', { email, password: newPassword })).response
+ .status,
+ 200,
+ )
+ assert.ok(
+ (
+ await call('/change-password', {
+ currentPassword: password,
+ newPassword: 'Changed!' + crypto.randomUUID(),
+ revokeOtherSessions: true,
+ })
+ ).response.status >= 400,
+ )
+ assert.equal(
+ (
+ await call('/change-password', {
+ currentPassword: newPassword,
+ newPassword: 'Changed!' + crypto.randomUUID(),
+ revokeOtherSessions: true,
+ })
+ ).response.status,
+ 200,
+ )
+ await call('/sign-out', {})
+ // Existing verified code-only users retain their original numeric identity.
+ await call('/email-otp/send-verification-otp', {
+ email: '[email protected]',
+ type: 'sign-in',
+ })
+ const existingCode = messages.at(-1)!.text.match(/\b[0-9]{6}\b/)![0]
+ assert.equal(
+ (
+ await call('/sign-in/email-otp', {
+ email: '[email protected]',
+ otp: existingCode,
+ })
+ ).response.status,
+ 200,
+ )
+ assert.equal(Number((await call('/get-session')).data.user.id), 42)
+ await call('/sign-out', {})
+ assert.ok(
+ (
+ await call('/sign-in/email-otp', {
+ email: '[email protected]',
+ otp: existingCode,
+ })
+ ).response.status >= 400,
+ )
+ await call('/request-password-reset', {
+ email: '[email protected]',
+ redirectTo: 'https://app.chronoframe.art/reset-password',
+ })
+ const existingResetLink = messages.at(-1)!.text.match(/https:\/\/\S+/)![0]
+ const existingPassword = 'Existing!' + crypto.randomUUID()
+ const setFirstPassword = await call('/reset-password', {
+ token: new URL(existingResetLink).pathname.split('/').at(-1),
+ newPassword: existingPassword,
+ })
+ assert.equal(
+ setFirstPassword.response.status,
+ 200,
+ JSON.stringify(setFirstPassword.data),
+ )
+ assert.equal(
+ (
+ await call('/sign-in/email', {
+ email: '[email protected]',
+ password: existingPassword,
+ })
+ ).response.status,
+ 200,
+ )
+ assert.equal(
+ Number((await call('/get-session')).data.user.id),
+ 42,
+ 'setting a first password does not replace a migrated identity',
+ )
+ await call('/sign-out', {})
+ const before = messages.length
+ await call('/email-otp/send-verification-otp', {
+ email: '[email protected]',
+ type: 'sign-in',
+ })
+ assert.equal(
+ messages.length,
+ before,
+ 'unknown accounts cannot silently register through email sign-in',
+ )
+ } finally {
+ await mf.dispose()
+ }
+})