Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix(cloud): require authenticators after email-code sign-in
Timothy Yin658250d2e252
diff --git a/apps/cloud/app/pages/account/security.vue b/apps/cloud/app/pages/account/security.vueindex b6bf5628..a41b23a2 100644--- a/apps/cloud/app/pages/account/security.vue+++ b/apps/cloud/app/pages/account/security.vue@@ -197,8 +197,9 @@ async function deletePasskey(id: number) {<div><h2>Two-step verification</h2><p>- After password sign-in, verify an email or authenticator code.- Passkeys already verify you on your device.+ After password sign-in, verify an email or authenticator code. A+ connected authenticator also protects email-code sign-in. Passkeys+ already verify you on your device.</p></div><CloudBadgediff --git a/apps/cloud/app/pages/signin.vue b/apps/cloud/app/pages/signin.vueindex 4d0b4568..e9d8ad90 100644--- a/apps/cloud/app/pages/signin.vue+++ b/apps/cloud/app/pages/signin.vue@@ -11,6 +11,7 @@ function setMode(value: 'email' | 'password') {mode.value = valueerror.value = ''}+const authenticatorRequired = ref(false)const factor = ref<'email' | 'totp' | 'recovery'>('email')const busy = ref(false),error = ref('')@@ -45,7 +46,10 @@ async function submit() {step.value = 'code'return} else {- const result = await $fetch<{ twoFactorRedirect?: boolean }>(+ const result = await $fetch<{+ twoFactorRedirect?: boolean+ twoFactorMethods?: string[]+ }>(mode.value === 'password'? '/api/auth/sign-in/email': '/api/auth/sign-in/email-otp',@@ -60,7 +64,10 @@ async function submit() {if (result.twoFactorRedirect) {step.value = 'second'code.value = ''- await sendSecond()+ authenticatorRequired.value =+ !!result.twoFactorMethods?.includes('totp')+ factor.value = authenticatorRequired.value ? 'totp' : 'email'+ if (!authenticatorRequired.value) await sendSecond()return}}@@ -182,7 +189,12 @@ async function resend() {:disabled="busy"@change="code = ''">- <option value="email">Email code</option>+ <option+ v-if="!authenticatorRequired"+ value="email"+ >+ Email code+ </option><option value="totp">Authenticator code</option><option value="recovery">Recovery code</option></select></templatediff --git a/apps/cloud/app/utils/account-error.ts b/apps/cloud/app/utils/account-error.tsindex 9553fff2..b5acd4f0 100644--- a/apps/cloud/app/utils/account-error.ts+++ b/apps/cloud/app/utils/account-error.ts@@ -7,6 +7,8 @@ export function accountError(cause: unknown) {if (error.statusCode === 429)return 'Too many attempts. Please wait before trying again.'const code = error.data?.code ?? ''+ if (code === 'AUTHENTICATOR_REQUIRED')+ return 'Use your authenticator or an unused recovery code to finish signing in.'if (code.includes('PASSWORD_TOO_SHORT'))return 'Use a password with at least 12 characters.'if (code.includes('EMAIL_NOT_VERIFIED'))diff --git a/apps/cloud/server/utils/account-auth.ts b/apps/cloud/server/utils/account-auth.tsindex cd911e82..64a28348 100644--- a/apps/cloud/server/utils/account-auth.ts+++ b/apps/cloud/server/utils/account-auth.ts@@ -2,7 +2,8 @@ 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 { emailOTP } from 'better-auth/plugins'+import { accountFactors } from './account-factors.ts'import { passkey } from '@better-auth/passkey'import type { PlatformEmailBinding } from '../../../shared/platform/email.ts'@@ -16,6 +17,7 @@ export function accountAuthOptions(database: BetterAuthOptions['database'],config: AccountAuthConfig,email: PlatformEmailBinding,+ defer?: (task: Promise<unknown>) => void,) {const origin = new URL(config.portalOrigin)const send = async (to: string, subject: string, text: string) => {@@ -31,6 +33,7 @@ export function accountAuthOptions(telemetry: { enabled: false },advanced: {database: { generateId: 'serial' },+ backgroundTasks: defer ? { handler: defer } : undefined,// Every auth cookie has a browser-enforced host prefix. Avoid Better Auth// prepending __Secure- to our already-prefixed __Host- names.cookiePrefix: '__Host-chronoframe-cloud',@@ -143,7 +146,7 @@ export function accountAuthOptions()},}),- twoFactor({+ accountFactors({issuer: 'ChronoFrame Cloud',schema: {user: { fields: { twoFactorEnabled: 'two_factor_enabled' } },diff --git a/apps/cloud/server/utils/account-factors.ts b/apps/cloud/server/utils/account-factors.tsnew file mode 100644index 00000000..7aec0b59--- /dev/null+++ b/apps/cloud/server/utils/account-factors.ts@@ -0,0 +1,85 @@+import { twoFactor } from 'better-auth/plugins'+import {+ APIError,+ createAuthMiddleware,+ type DispatchContext,+} from 'better-auth/api'++/** Reuse Better Auth's challenge/session lifecycle for verified email-code logins too. */+export function accountFactors(options: Parameters<typeof twoFactor>[0]) {+ const emailEntry = (path: string | undefined) =>+ ['/sign-in/email-otp', '/email-otp/verify-email'].includes(path ?? '')+ const plugin = twoFactor(options)+ const credentialGate = plugin.hooks.after[0]!+ return {+ ...plugin,+ hooks: {+ ...plugin.hooks,+ before: [+ {+ matcher: (ctx: { path?: string }) =>+ !!ctx.path?.startsWith('/two-factor/'),+ handler: createAuthMiddleware(async (ctx) => {+ // This portal does not offer remembered-device bypasses.+ if (ctx.body && typeof ctx.body === 'object')+ ctx.body.trustDevice = false+ if (+ !['/two-factor/send-otp', '/two-factor/verify-otp'].includes(+ ctx.path ?? '',+ )+ )+ return+ const cookie = ctx.context.createAuthCookie('two_factor')+ const identifier = await ctx.getSignedCookie(+ cookie.name,+ ctx.context.secret,+ )+ if (!identifier) return+ const pending =+ await ctx.context.internalAdapter.findVerificationValue(+ identifier,+ )+ if (!pending) return+ const authenticator = await ctx.context.adapter.findOne<{+ verified: boolean+ }>({+ model: 'twoFactor',+ where: [{ field: 'userId', value: pending.value }],+ })+ // A second email code cannot replace a connected authenticator.+ if (authenticator?.verified)+ throw new APIError('FORBIDDEN', {+ code: 'AUTHENTICATOR_REQUIRED',+ message: 'Use your authenticator or a recovery code.',+ })+ }),+ },+ ],+ after: [+ {+ matcher: (ctx: Parameters<typeof credentialGate.matcher>[0]) =>+ credentialGate.matcher(ctx) || emailEntry(ctx.path),+ handler: Object.assign(+ async (input: Parameters<typeof credentialGate.handler>[0]) => {+ const ctx = input as typeof input & DispatchContext+ if (emailEntry(ctx.path)) {+ const userId = ctx.context.newSession?.user.id+ if (!userId) return { response: undefined, headers: undefined }+ const authenticator = await ctx.context.adapter.findOne<{+ verified: boolean+ }>({+ model: 'twoFactor',+ where: [{ field: 'userId', value: userId }],+ })+ if (!authenticator?.verified)+ return { response: undefined, headers: undefined }+ }+ return credentialGate.handler(ctx)+ },+ { options: credentialGate.handler.options },+ ),+ },+ ],+ },+ }+}diff --git a/apps/cloud/server/utils/cloud-account.ts b/apps/cloud/server/utils/cloud-account.tsindex 98fa76a1..aa07b7ec 100644--- a/apps/cloud/server/utils/cloud-account.ts+++ b/apps/cloud/server/utils/cloud-account.ts@@ -7,10 +7,14 @@ import type { PlatformEmailBinding } from '../../../shared/platform/email'export function cloudAccount(event: H3Event) {if (!event.context.cloudAccountAuth) {const config = useRuntimeConfig(event).platform+ const execution = event.context.cloudflare?.context as+ | { waitUntil(task: Promise<unknown>): void }+ | undefinedevent.context.cloudAccountAuth = createAccountAuth(platformDatabase(event) as unknown as BetterAuthOptions['database'],config,event.context.cloudflare?.env?.EMAIL as PlatformEmailBinding,+ execution ? (task) => execution.waitUntil(task) : undefined,)}return event.context.cloudAccountAuth as ReturnType<typeof createAccountAuth>diff --git a/tests/cloud-account-security.test.ts b/tests/cloud-account-security.test.tsindex abaf6f21..a1cd5b0c 100644--- a/tests/cloud-account-security.test.ts+++ b/tests/cloud-account-security.test.ts@@ -227,6 +227,46 @@ test('Cloud account migration preserves identities and enforces verified registr200,)await call('/sign-out', {})+ for (const type of ['sign-in', 'email-verification']) {+ await call('/email-otp/send-verification-otp', { email, type })+ const emailCode = messages.at(-1)!.text.match(/\b[0-9]{6}\b/)![0]+ const entry = await call(+ type === 'sign-in' ? '/sign-in/email-otp' : '/email-otp/verify-email',+ { email, otp: emailCode },+ )+ assert.equal(+ entry.data.twoFactorRedirect,+ true,+ JSON.stringify(entry.data),+ )+ assert.equal(+ (await call('/get-session')).data,+ null,+ 'email proof must not create a session before TOTP',+ )+ assert.equal(+ (await call('/two-factor/send-otp', {})).response.status,+ 403,+ )+ assert.equal(+ (await call('/two-factor/verify-otp', { code: emailCode })).response+ .status,+ 403,+ 'email cannot substitute for the authenticator',+ )+ assert.equal(+ (+ await call('/two-factor/verify-totp', {+ code: totp(setup.data.totpURI),+ trustDevice: true,+ })+ ).response.status,+ 200,+ )+ assert.ok((await call('/get-session')).data.user)+ await call('/sign-out', {})+ }+ await call('/sign-out', {})assert.equal((await call('/sign-in/email', { email, password })).data.twoFactorRedirect,@@ -413,6 +453,68 @@ test('Cloud account migration preserves identities and enforces verified registrbefore,'unknown accounts cannot silently register through email sign-in',)+ let finishDelivery!: () => void+ const delivery = new Promise<void>((resolve) => {+ finishDelivery = resolve+ })+ let delivered = false+ const background: Promise<unknown>[] = []+ const deferredAuth = createAccountAuth(+ db,+ {+ portalOrigin: 'https://app.chronoframe.art',+ emailFrom: '[email protected]',+ secret: crypto.randomUUID() + crypto.randomUUID(),+ },+ {+ send: async () => {+ await delivery+ delivered = true+ return { messageId: 'local-background-test' }+ },+ },+ (task) => {+ background.push(task)+ },+ )+ try {+ const queued = await Promise.race([+ deferredAuth.handler(+ new Request(+ 'https://app.chronoframe.art/api/auth/email-otp/send-verification-otp',+ {+ method: 'POST',+ headers: {+ origin: 'https://app.chronoframe.art',+ 'content-type': 'application/json',+ 'cf-connecting-ip': '203.0.113.25',+ },+ body: JSON.stringify({+ email: '[email protected]',+ type: 'sign-in',+ }),+ },+ ),+ ),+ new Promise<never>((_, reject) => {+ const timeout = setTimeout(+ () => reject(new Error('Email provider delayed the auth response')),+ 1500,+ )+ timeout.unref()+ }),+ ])+ assert.equal(queued.status, 200)+ assert.equal(delivered, false)+ assert.ok(+ background.length > 0,+ 'delivery is attached to the platform background task handler',+ )+ } finally {+ finishDelivery()+ await Promise.all(background)+ }+ assert.equal(delivered, true)} finally {await mf.dispose()}