mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-14 18:41:08 +02:00
feat(auth): add TOTP two-factor authentication across all apps
Uses Better Auth's built-in twoFactor plugin for TOTP + backup codes: Backend (mana-core-auth): - twoFactor plugin in better-auth.config.ts (issuer: ManaCore) - twoFactorEnabled field on users table, backupCodes as encrypted text - 2FA redirect detection in signIn flow - Passthrough controller forwards /two-factor/* to Better Auth - Security event types for 2FA operations Client (shared-auth): - enableTwoFactor, disableTwoFactor, verifyTwoFactor, verifyBackupCode, generateBackupCodes methods with session-to-token exchange UI (shared-auth-ui): - LoginPage: 2FA code input view after password login, backup code toggle - TwoFactorSetup: settings component with enable/disable/QR code/backup codes App integration: - All 19 auth stores have verifyTwoFactor() and verifyBackupCode() - All 19 login pages pass onVerifyTwoFactor and onVerifyBackupCode callbacks - ManaCore settings page has TwoFactorSetup component Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
90e6135637
commit
f5a9edcfb6
49 changed files with 1800 additions and 169 deletions
|
|
@ -122,6 +122,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -58,6 +58,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -122,6 +122,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -65,6 +65,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -105,6 +105,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -49,6 +49,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -122,6 +122,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -56,6 +56,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -122,6 +122,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -55,6 +55,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -106,6 +106,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -50,6 +50,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -138,6 +138,46 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async enableTwoFactor(password: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available' };
|
||||
return authService.enableTwoFactor(password);
|
||||
},
|
||||
|
||||
async disableTwoFactor(password: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available' };
|
||||
return authService.disableTwoFactor(password);
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async generateBackupCodes(password: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available' };
|
||||
return authService.generateBackupCodes(password);
|
||||
},
|
||||
|
||||
async registerPasskey(friendlyName?: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available' };
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { Button, Input, Card, PageHeader, GlobalSettingsSection } from '@manacore/shared-ui';
|
||||
import { PasskeyManager } from '@manacore/shared-auth-ui';
|
||||
import { PasskeyManager, TwoFactorSetup } from '@manacore/shared-auth-ui';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { creditsService } from '$lib/api/credits';
|
||||
import type { CreditBalance } from '$lib/api/credits';
|
||||
|
|
@ -294,6 +294,19 @@
|
|||
</div>
|
||||
</Card>
|
||||
|
||||
<!-- Two-Factor Authentication Section -->
|
||||
<Card>
|
||||
<div class="p-6">
|
||||
<TwoFactorSetup
|
||||
enabled={!!authStore.user?.twoFactorEnabled}
|
||||
onEnable={(password) => authStore.enableTwoFactor(password)}
|
||||
onDisable={(password) => authStore.disableTwoFactor(password)}
|
||||
onGenerateBackupCodes={(password) => authStore.generateBackupCodes(password)}
|
||||
primaryColor="#6366f1"
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<!-- My Data & Danger Zone -->
|
||||
<Card>
|
||||
<div class="p-6">
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect="/dashboard"
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -93,6 +93,24 @@ export const authStore = {
|
|||
return true;
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = toManaUser(userData);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = toManaUser(userData);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
return authService.isPasskeyAvailable();
|
||||
},
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect="/decks"
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -107,6 +107,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -52,6 +52,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -120,6 +120,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -54,6 +54,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -109,6 +109,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -45,6 +45,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -120,6 +120,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect="/app/gallery"
|
||||
registerPath="/auth/signup"
|
||||
|
|
|
|||
|
|
@ -115,6 +115,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -54,6 +54,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -84,6 +84,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -119,6 +119,29 @@ export const auth = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -42,6 +42,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={auth.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => auth.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => auth.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => auth.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -113,6 +113,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -60,6 +60,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -117,6 +117,28 @@ export const authStore = {
|
|||
}
|
||||
},
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -60,6 +60,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -118,6 +118,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -133,6 +133,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -57,6 +57,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
|
|
@ -122,6 +122,29 @@ export const authStore = {
|
|||
/**
|
||||
* Check if passkeys are available in this browser
|
||||
*/
|
||||
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyTwoFactor(code, trustDevice);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async verifyBackupCode(code: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return { success: false, error: 'Auth not available on server' };
|
||||
const result = await authService.verifyBackupCode(code);
|
||||
if (result.success) {
|
||||
const userData = await authService.getUserFromToken();
|
||||
user = userData;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
isPasskeyAvailable(): boolean {
|
||||
const authService = getAuthService();
|
||||
if (!authService) return false;
|
||||
|
|
|
|||
|
|
@ -55,6 +55,8 @@
|
|||
onResendVerification={handleResendVerification}
|
||||
passkeyAvailable={authStore.isPasskeyAvailable()}
|
||||
onSignInWithPasskey={() => authStore.signInWithPasskey()}
|
||||
onVerifyTwoFactor={(code, trust) => authStore.verifyTwoFactor(code, trust)}
|
||||
onVerifyBackupCode={(code) => authStore.verifyBackupCode(code)}
|
||||
{goto}
|
||||
successRedirect={redirectTo}
|
||||
registerPath="/register"
|
||||
|
|
|
|||
691
packages/shared-auth-ui/src/components/TwoFactorSetup.svelte
Normal file
691
packages/shared-auth-ui/src/components/TwoFactorSetup.svelte
Normal file
|
|
@ -0,0 +1,691 @@
|
|||
<script lang="ts">
|
||||
import type { AuthResult } from '../types';
|
||||
|
||||
export interface TwoFactorSetupTranslations {
|
||||
title: string;
|
||||
statusEnabled: string;
|
||||
statusDisabled: string;
|
||||
enableButton: string;
|
||||
disableButton: string;
|
||||
regenerateButton: string;
|
||||
passwordLabel: string;
|
||||
passwordPlaceholder: string;
|
||||
confirmButton: string;
|
||||
cancelButton: string;
|
||||
setupTitle: string;
|
||||
setupStep1: string;
|
||||
setupStep2: string;
|
||||
manualEntryLabel: string;
|
||||
copyButton: string;
|
||||
copiedButton: string;
|
||||
doneButton: string;
|
||||
disableConfirmTitle: string;
|
||||
disableConfirmText: string;
|
||||
backupCodesTitle: string;
|
||||
backupCodesWarning: string;
|
||||
copyCodesButton: string;
|
||||
copiedCodesButton: string;
|
||||
}
|
||||
|
||||
const defaultTranslations: TwoFactorSetupTranslations = {
|
||||
title: 'Zwei-Faktor-Authentifizierung',
|
||||
statusEnabled: 'Aktiviert',
|
||||
statusDisabled: 'Deaktiviert',
|
||||
enableButton: 'Aktivieren',
|
||||
disableButton: 'Deaktivieren',
|
||||
regenerateButton: 'Backup-Codes erneuern',
|
||||
passwordLabel: 'Passwort zur Bestätigung',
|
||||
passwordPlaceholder: 'Passwort',
|
||||
confirmButton: 'Bestätigen',
|
||||
cancelButton: 'Abbrechen',
|
||||
setupTitle: '2FA einrichten',
|
||||
setupStep1: '1. Scanne den QR-Code oder gib den Schlüssel manuell ein',
|
||||
setupStep2: '2. Sichere deine Backup-Codes',
|
||||
manualEntryLabel: 'Schlüssel für manuelle Eingabe:',
|
||||
copyButton: 'Kopieren',
|
||||
copiedButton: 'Kopiert!',
|
||||
doneButton: 'Fertig',
|
||||
disableConfirmTitle: '2FA deaktivieren',
|
||||
disableConfirmText:
|
||||
'Bist du sicher, dass du die Zwei-Faktor-Authentifizierung deaktivieren möchtest?',
|
||||
backupCodesTitle: 'Neue Backup-Codes',
|
||||
backupCodesWarning: 'Speichere diese Codes sicher ab. Sie ersetzen die bisherigen Codes.',
|
||||
copyCodesButton: 'Codes kopieren',
|
||||
copiedCodesButton: 'Kopiert!',
|
||||
};
|
||||
|
||||
interface Props {
|
||||
enabled: boolean;
|
||||
onEnable: (
|
||||
password: string
|
||||
) => Promise<{ success: boolean; totpURI?: string; backupCodes?: string[]; error?: string }>;
|
||||
onDisable: (password: string) => Promise<{ success: boolean; error?: string }>;
|
||||
onGenerateBackupCodes: (
|
||||
password: string
|
||||
) => Promise<{ success: boolean; backupCodes?: string[]; error?: string }>;
|
||||
primaryColor?: string;
|
||||
translations?: Partial<TwoFactorSetupTranslations>;
|
||||
}
|
||||
|
||||
let {
|
||||
enabled,
|
||||
onEnable,
|
||||
onDisable,
|
||||
onGenerateBackupCodes,
|
||||
primaryColor = '#6366f1',
|
||||
translations = {},
|
||||
}: Props = $props();
|
||||
|
||||
const t = $derived({ ...defaultTranslations, ...translations });
|
||||
|
||||
type View =
|
||||
| 'status'
|
||||
| 'enable-password'
|
||||
| 'setup'
|
||||
| 'disable-password'
|
||||
| 'regenerate-password'
|
||||
| 'backup-codes';
|
||||
|
||||
let view = $state<View>('status');
|
||||
let password = $state('');
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let totpURI = $state<string | null>(null);
|
||||
let backupCodes = $state<string[]>([]);
|
||||
let copied = $state(false);
|
||||
let codesCopied = $state(false);
|
||||
|
||||
/** Extract the secret from an otpauth:// URI */
|
||||
function extractSecret(uri: string): string {
|
||||
try {
|
||||
const url = new URL(uri);
|
||||
return url.searchParams.get('secret') || uri;
|
||||
} catch {
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
view = 'status';
|
||||
password = '';
|
||||
error = null;
|
||||
totpURI = null;
|
||||
backupCodes = [];
|
||||
copied = false;
|
||||
codesCopied = false;
|
||||
}
|
||||
|
||||
async function handleEnable() {
|
||||
if (!password) return;
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
const result = await onEnable(password);
|
||||
loading = false;
|
||||
|
||||
if (result.success && result.totpURI) {
|
||||
totpURI = result.totpURI;
|
||||
backupCodes = result.backupCodes || [];
|
||||
view = 'setup';
|
||||
password = '';
|
||||
} else {
|
||||
error = result.error || 'Fehler beim Aktivieren';
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDisable() {
|
||||
if (!password) return;
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
const result = await onDisable(password);
|
||||
loading = false;
|
||||
|
||||
if (result.success) {
|
||||
reset();
|
||||
} else {
|
||||
error = result.error || 'Fehler beim Deaktivieren';
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRegenerateBackupCodes() {
|
||||
if (!password) return;
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
const result = await onGenerateBackupCodes(password);
|
||||
loading = false;
|
||||
|
||||
if (result.success && result.backupCodes) {
|
||||
backupCodes = result.backupCodes;
|
||||
view = 'backup-codes';
|
||||
password = '';
|
||||
} else {
|
||||
error = result.error || 'Fehler beim Erneuern der Codes';
|
||||
}
|
||||
}
|
||||
|
||||
async function copyToClipboard(text: string, type: 'uri' | 'codes') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
if (type === 'uri') {
|
||||
copied = true;
|
||||
setTimeout(() => (copied = false), 2000);
|
||||
} else {
|
||||
codesCopied = true;
|
||||
setTimeout(() => (codesCopied = false), 2000);
|
||||
}
|
||||
} catch {
|
||||
// Clipboard API not available
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="two-factor-setup">
|
||||
{#if view === 'status'}
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{t.title}</h3>
|
||||
<div class="status-badge" class:status-enabled={enabled} class:status-disabled={!enabled}>
|
||||
<span class="status-dot"></span>
|
||||
{enabled ? t.statusEnabled : t.statusDisabled}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="action-buttons">
|
||||
{#if enabled}
|
||||
<button
|
||||
type="button"
|
||||
class="action-button secondary"
|
||||
style:border-color={primaryColor}
|
||||
onclick={() => {
|
||||
view = 'regenerate-password';
|
||||
error = null;
|
||||
}}
|
||||
>
|
||||
{t.regenerateButton}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-button danger"
|
||||
onclick={() => {
|
||||
view = 'disable-password';
|
||||
error = null;
|
||||
}}
|
||||
>
|
||||
{t.disableButton}
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
class="action-button primary"
|
||||
style:background-color={primaryColor + '60'}
|
||||
style:border-color={primaryColor}
|
||||
onclick={() => {
|
||||
view = 'enable-password';
|
||||
error = null;
|
||||
}}
|
||||
>
|
||||
{t.enableButton}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if view === 'enable-password' || view === 'disable-password' || view === 'regenerate-password'}
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
{#if view === 'disable-password'}
|
||||
{t.disableConfirmTitle}
|
||||
{:else if view === 'regenerate-password'}
|
||||
{t.backupCodesTitle}
|
||||
{:else}
|
||||
{t.title}
|
||||
{/if}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{#if view === 'disable-password'}
|
||||
<p class="confirm-text">{t.disableConfirmText}</p>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<div class="error-message" role="alert">
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (view === 'enable-password') handleEnable();
|
||||
else if (view === 'disable-password') handleDisable();
|
||||
else handleRegenerateBackupCodes();
|
||||
}}
|
||||
>
|
||||
<div class="input-group">
|
||||
<label for="2fa-password" class="input-label">{t.passwordLabel}</label>
|
||||
<input
|
||||
id="2fa-password"
|
||||
type="password"
|
||||
bind:value={password}
|
||||
placeholder={t.passwordPlaceholder}
|
||||
required
|
||||
autocomplete="current-password"
|
||||
class="input-field"
|
||||
style:--ring-color={primaryColor}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="action-buttons">
|
||||
<button type="button" class="action-button secondary" onclick={reset}>
|
||||
{t.cancelButton}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !password}
|
||||
class="action-button primary"
|
||||
style:background-color={view === 'disable-password' ? '#ef444460' : primaryColor + '60'}
|
||||
style:border-color={view === 'disable-password' ? '#ef4444' : primaryColor}
|
||||
>
|
||||
{loading ? '...' : t.confirmButton}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{:else if view === 'setup'}
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{t.setupTitle}</h3>
|
||||
</div>
|
||||
|
||||
<div class="setup-step">
|
||||
<p class="step-label">{t.setupStep1}</p>
|
||||
|
||||
{#if totpURI}
|
||||
<div class="qr-section">
|
||||
<img
|
||||
src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={encodeURIComponent(
|
||||
totpURI
|
||||
)}"
|
||||
alt="QR Code for TOTP setup"
|
||||
width="200"
|
||||
height="200"
|
||||
class="qr-image"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="manual-entry">
|
||||
<p class="manual-label">{t.manualEntryLabel}</p>
|
||||
<div class="secret-display">
|
||||
<code class="secret-code">{extractSecret(totpURI)}</code>
|
||||
<button
|
||||
type="button"
|
||||
class="copy-button"
|
||||
style:color={primaryColor}
|
||||
onclick={() => copyToClipboard(extractSecret(totpURI || ''), 'uri')}
|
||||
>
|
||||
{copied ? t.copiedButton : t.copyButton}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if backupCodes.length > 0}
|
||||
<div class="setup-step">
|
||||
<p class="step-label">{t.setupStep2}</p>
|
||||
<p class="backup-warning">{t.backupCodesWarning}</p>
|
||||
|
||||
<div class="backup-grid">
|
||||
{#each backupCodes as code}
|
||||
<code class="backup-code">{code}</code>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="copy-button"
|
||||
style:color={primaryColor}
|
||||
style:margin-top="0.5rem"
|
||||
onclick={() => copyToClipboard(backupCodes.join('\n'), 'codes')}
|
||||
>
|
||||
{codesCopied ? t.copiedCodesButton : t.copyCodesButton}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="action-buttons" style:margin-top="1.5rem">
|
||||
<button
|
||||
type="button"
|
||||
class="action-button primary"
|
||||
style:background-color={primaryColor + '60'}
|
||||
style:border-color={primaryColor}
|
||||
onclick={reset}
|
||||
>
|
||||
{t.doneButton}
|
||||
</button>
|
||||
</div>
|
||||
{:else if view === 'backup-codes'}
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{t.backupCodesTitle}</h3>
|
||||
</div>
|
||||
|
||||
<p class="backup-warning">{t.backupCodesWarning}</p>
|
||||
|
||||
<div class="backup-grid">
|
||||
{#each backupCodes as code}
|
||||
<code class="backup-code">{code}</code>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="copy-button"
|
||||
style:color={primaryColor}
|
||||
style:margin-top="0.5rem"
|
||||
onclick={() => copyToClipboard(backupCodes.join('\n'), 'codes')}
|
||||
>
|
||||
{codesCopied ? t.copiedCodesButton : t.copyCodesButton}
|
||||
</button>
|
||||
|
||||
<div class="action-buttons" style:margin-top="1.5rem">
|
||||
<button
|
||||
type="button"
|
||||
class="action-button primary"
|
||||
style:background-color={primaryColor + '60'}
|
||||
style:border-color={primaryColor}
|
||||
onclick={reset}
|
||||
>
|
||||
{t.doneButton}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.two-factor-setup {
|
||||
padding: 1rem;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
:global(.light) .two-factor-setup {
|
||||
border-color: rgba(0, 0, 0, 0.1);
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
}
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
:global(.light) .section-title {
|
||||
color: rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
padding: 0.25rem 0.625rem;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.status-enabled {
|
||||
color: #22c55e;
|
||||
background: rgba(34, 197, 94, 0.15);
|
||||
}
|
||||
|
||||
.status-disabled {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
:global(.light) .status-disabled {
|
||||
color: rgba(0, 0, 0, 0.5);
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
flex: 1;
|
||||
height: 2.75rem;
|
||||
border: 2px solid;
|
||||
border-radius: 0.5rem;
|
||||
font-weight: 500;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
:global(.light) .action-button {
|
||||
color: rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
|
||||
.action-button.primary {
|
||||
border-style: solid;
|
||||
}
|
||||
|
||||
.action-button.secondary {
|
||||
background: transparent;
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
:global(.light) .action-button.secondary {
|
||||
border-color: rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.action-button.danger {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
border-color: #ef4444;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.action-button:hover:not(:disabled) {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.action-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.confirm-text {
|
||||
font-size: 0.875rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
:global(.light) .confirm-text {
|
||||
color: rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
.input-group {
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.input-label {
|
||||
display: block;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.375rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
:global(.light) .input-label {
|
||||
color: rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
|
||||
.input-field {
|
||||
width: 100%;
|
||||
height: 2.75rem;
|
||||
padding: 0 0.75rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.9375rem;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
color: #fff;
|
||||
transition:
|
||||
border-color 0.2s,
|
||||
box-shadow 0.2s;
|
||||
}
|
||||
|
||||
:global(.light) .input-field {
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
border-color: rgba(0, 0, 0, 0.1);
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.input-field:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px var(--ring-color, currentColor);
|
||||
}
|
||||
|
||||
.error-message {
|
||||
padding: 0.625rem 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
border-radius: 0.5rem;
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
color: #ef4444;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.error-message p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.setup-step {
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.step-label {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
:global(.light) .step-label {
|
||||
color: rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
|
||||
.qr-section {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.qr-image {
|
||||
border-radius: 0.5rem;
|
||||
background: #fff;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.manual-entry {
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.manual-label {
|
||||
font-size: 0.8125rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
margin-bottom: 0.375rem;
|
||||
}
|
||||
|
||||
:global(.light) .manual-label {
|
||||
color: rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
.secret-display {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 0.5rem;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
:global(.light) .secret-display {
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
border-color: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.secret-code {
|
||||
flex: 1;
|
||||
font-size: 0.8125rem;
|
||||
font-family: monospace;
|
||||
word-break: break-all;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
:global(.light) .secret-code {
|
||||
color: rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
|
||||
.copy-button {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
padding: 0.25rem;
|
||||
}
|
||||
|
||||
.copy-button:hover {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.backup-warning {
|
||||
font-size: 0.8125rem;
|
||||
color: #f59e0b;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.backup-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(7rem, 1fr));
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.backup-code {
|
||||
padding: 0.375rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
font-size: 0.8125rem;
|
||||
font-family: monospace;
|
||||
text-align: center;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
:global(.light) .backup-code {
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
border-color: rgba(0, 0, 0, 0.1);
|
||||
color: rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -9,6 +9,7 @@ export { default as AuthGateModal } from './components/AuthGateModal.svelte';
|
|||
export { default as SessionExpiredBanner } from './components/SessionExpiredBanner.svelte';
|
||||
export { default as AuthGate } from './components/AuthGate.svelte';
|
||||
export { default as PasskeyManager } from './components/PasskeyManager.svelte';
|
||||
export { default as TwoFactorSetup } from './components/TwoFactorSetup.svelte';
|
||||
|
||||
// Utilities
|
||||
export {
|
||||
|
|
@ -28,3 +29,4 @@ export type {
|
|||
AuthGateTranslations,
|
||||
} from './types';
|
||||
export type { PasskeyManagerTranslations } from './components/PasskeyManager.svelte';
|
||||
export type { TwoFactorSetupTranslations } from './components/TwoFactorSetup.svelte';
|
||||
|
|
|
|||
|
|
@ -86,6 +86,8 @@
|
|||
buildTime?: string;
|
||||
onSignInWithPasskey?: () => Promise<AuthResult>;
|
||||
passkeyAvailable?: boolean;
|
||||
onVerifyTwoFactor?: (code: string, trustDevice?: boolean) => Promise<AuthResult>;
|
||||
onVerifyBackupCode?: (code: string) => Promise<AuthResult>;
|
||||
}
|
||||
|
||||
let {
|
||||
|
|
@ -110,6 +112,8 @@
|
|||
buildTime = '',
|
||||
onSignInWithPasskey,
|
||||
passkeyAvailable = false,
|
||||
onVerifyTwoFactor,
|
||||
onVerifyBackupCode,
|
||||
}: Props = $props();
|
||||
|
||||
const t = $derived({ ...defaultTranslations, ...translations });
|
||||
|
|
@ -137,6 +141,9 @@
|
|||
let showEmailNotVerified = $state(false);
|
||||
let resendingVerification = $state(false);
|
||||
let verificationEmailSent = $state(false);
|
||||
let showTwoFactor = $state(false);
|
||||
let twoFactorCode = $state('');
|
||||
let useBackupCode = $state(false);
|
||||
|
||||
// Theme state - can be toggled manually, defaults to system preference
|
||||
let userThemePreference = $state<'light' | 'dark' | null>(null);
|
||||
|
|
@ -229,6 +236,12 @@
|
|||
const result = await onSignIn(email, password);
|
||||
loading = false;
|
||||
|
||||
// Check if 2FA is required
|
||||
if ((result as any).twoFactorRedirect) {
|
||||
showTwoFactor = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
showSuccess = true;
|
||||
successAnnouncement = t.signInSuccess;
|
||||
|
|
@ -258,6 +271,30 @@
|
|||
}
|
||||
}
|
||||
|
||||
async function handleTwoFactorVerify() {
|
||||
if (!twoFactorCode) return;
|
||||
loading = true;
|
||||
clearError();
|
||||
|
||||
const handler = useBackupCode ? onVerifyBackupCode : onVerifyTwoFactor;
|
||||
if (!handler) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await handler(twoFactorCode);
|
||||
loading = false;
|
||||
|
||||
if (result.success) {
|
||||
showSuccess = true;
|
||||
successAnnouncement = t.signInSuccess;
|
||||
setTimeout(() => goto(successRedirect), 600);
|
||||
} else {
|
||||
setError(result.error || t.signInFailed, 'general');
|
||||
twoFactorCode = '';
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePasskeySignIn() {
|
||||
if (!onSignInWithPasskey) return;
|
||||
loading = true;
|
||||
|
|
@ -352,198 +389,290 @@
|
|||
<!-- Form Section -->
|
||||
<div class="form-section">
|
||||
<div class="form-card" class:shake={shakeError}>
|
||||
{#if showVerifiedBanner}
|
||||
<div class="verified-banner" role="status" aria-live="polite">
|
||||
<Check size={18} class="text-green-500 shrink-0" />
|
||||
<p>{t.emailVerified}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="verified-banner-close"
|
||||
onclick={() => (showVerifiedBanner = false)}
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{#if showTwoFactor}
|
||||
<!-- 2FA Verification -->
|
||||
<div class="form-header">
|
||||
<h2 class="form-title">Zwei-Faktor-Authentifizierung</h2>
|
||||
<p class="form-subtitle">
|
||||
{useBackupCode
|
||||
? 'Gib einen Backup-Code ein'
|
||||
: 'Gib den Code aus deiner Authenticator-App ein'}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="form-header">
|
||||
<h2 class="form-title">{t.title}</h2>
|
||||
<p class="form-subtitle">{t.subtitle}</p>
|
||||
</div>
|
||||
{#if error}
|
||||
<div class="error-message" role="alert">
|
||||
<Warning size={18} class="text-red-500 shrink-0" />
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleTwoFactorVerify();
|
||||
}}
|
||||
>
|
||||
<div class="input-group">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={twoFactorCode}
|
||||
placeholder={useBackupCode ? 'Backup-Code' : '000000'}
|
||||
required
|
||||
autocomplete="one-time-code"
|
||||
inputmode={useBackupCode ? 'text' : 'numeric'}
|
||||
maxlength={useBackupCode ? 20 : 6}
|
||||
class="input-field"
|
||||
style:--ring-color={primaryColor}
|
||||
style:text-align="center"
|
||||
style:font-size="1.5rem"
|
||||
style:letter-spacing="0.5rem"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !twoFactorCode}
|
||||
class="submit-button"
|
||||
style:background-color={primaryColor + '60'}
|
||||
style:border-color={primaryColor}
|
||||
>
|
||||
{loading ? 'Prüfe...' : 'Bestätigen'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{#if passkeyAvailable && onSignInWithPasskey}
|
||||
<button
|
||||
type="button"
|
||||
onclick={handlePasskeySignIn}
|
||||
disabled={loading || showSuccess}
|
||||
class="passkey-button"
|
||||
style:border-color={primaryColor}
|
||||
class="forgot-link"
|
||||
style:color={primaryColor}
|
||||
style:display="block"
|
||||
style:width="100%"
|
||||
style:text-align="center"
|
||||
style:margin-top="1rem"
|
||||
onclick={() => {
|
||||
useBackupCode = !useBackupCode;
|
||||
twoFactorCode = '';
|
||||
clearError();
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M2 18v3c0 .6.4 1 1 1h4v-3h3v-3h2l1.4-1.4a6.5 6.5 0 1 0-4-4Z" />
|
||||
<circle cx="16.5" cy="7.5" r=".5" fill="currentColor" />
|
||||
</svg>
|
||||
<span>Passkey</span>
|
||||
{useBackupCode ? 'Authenticator-App verwenden' : 'Backup-Code verwenden'}
|
||||
</button>
|
||||
<div class="divider">
|
||||
<span>{t.orDivider}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if verificationEmailSent}
|
||||
<div class="verified-banner" role="status" aria-live="polite">
|
||||
<Check size={18} class="text-green-500 shrink-0" />
|
||||
<p>{t.verificationEmailSent}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="verified-banner-close"
|
||||
onclick={() => (verificationEmailSent = false)}
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<div class="error-message" id="form-error" role="alert" aria-live="assertive">
|
||||
<Warning size={18} class="text-red-500 shrink-0" />
|
||||
<div class="error-content">
|
||||
<p>{error}</p>
|
||||
{#if showEmailNotVerified && onResendVerification}
|
||||
<button
|
||||
type="button"
|
||||
class="resend-link"
|
||||
onclick={handleResendVerification}
|
||||
disabled={resendingVerification}
|
||||
style:color={primaryColor}
|
||||
>
|
||||
{resendingVerification ? t.resendingVerification : t.resendVerification}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleLogin();
|
||||
}}
|
||||
aria-busy={loading}
|
||||
>
|
||||
<!-- Email -->
|
||||
<div class="input-group">
|
||||
<label for="email" class="sr-only">{t.emailPlaceholder}</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
bind:this={emailInput}
|
||||
bind:value={email}
|
||||
placeholder={t.emailPlaceholder}
|
||||
required
|
||||
autocomplete="email"
|
||||
aria-invalid={errorField === 'email'}
|
||||
class="input-field"
|
||||
class:input-error={errorField === 'email'}
|
||||
style:--ring-color={errorField === 'email' ? '#ef4444' : primaryColor}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Password -->
|
||||
<div class="input-group">
|
||||
<label for="password" class="sr-only">{t.passwordPlaceholder}</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
bind:this={passwordInput}
|
||||
bind:value={password}
|
||||
placeholder={t.passwordPlaceholder}
|
||||
required
|
||||
autocomplete="current-password"
|
||||
aria-invalid={errorField === 'password'}
|
||||
class="input-field has-icon"
|
||||
class:input-error={errorField === 'password'}
|
||||
style:--ring-color={errorField === 'password' ? '#ef4444' : primaryColor}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="forgot-link"
|
||||
style:color={primaryColor}
|
||||
style:display="block"
|
||||
style:width="100%"
|
||||
style:text-align="center"
|
||||
style:margin-top="0.5rem"
|
||||
onclick={() => {
|
||||
showTwoFactor = false;
|
||||
twoFactorCode = '';
|
||||
useBackupCode = false;
|
||||
clearError();
|
||||
}}
|
||||
>
|
||||
Zurück zum Login
|
||||
</button>
|
||||
{:else}
|
||||
{#if showVerifiedBanner}
|
||||
<div class="verified-banner" role="status" aria-live="polite">
|
||||
<Check size={18} class="text-green-500 shrink-0" />
|
||||
<p>{t.emailVerified}</p>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (showPassword = !showPassword)}
|
||||
class="password-toggle"
|
||||
aria-label={showPassword ? t.hidePassword : t.showPassword}
|
||||
class="verified-banner-close"
|
||||
onclick={() => (showVerifiedBanner = false)}
|
||||
aria-label="Close"
|
||||
>
|
||||
{#if showPassword}
|
||||
<EyeSlash size={20} />
|
||||
{:else}
|
||||
<Eye size={20} />
|
||||
{/if}
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="form-header">
|
||||
<h2 class="form-title">{t.title}</h2>
|
||||
<p class="form-subtitle">{t.subtitle}</p>
|
||||
</div>
|
||||
|
||||
<!-- Remember & Forgot -->
|
||||
<div class="options-row">
|
||||
<label class="remember-label">
|
||||
<input type="checkbox" bind:checked={rememberMe} style:accent-color={primaryColor} />
|
||||
<span>{t.rememberMe}</span>
|
||||
</label>
|
||||
{#if passkeyAvailable && onSignInWithPasskey}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => goto(forgotPasswordPath)}
|
||||
class="forgot-link"
|
||||
style:color={primaryColor}
|
||||
onclick={handlePasskeySignIn}
|
||||
disabled={loading || showSuccess}
|
||||
class="passkey-button"
|
||||
style:border-color={primaryColor}
|
||||
>
|
||||
{t.forgotPassword}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Submit -->
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || showSuccess}
|
||||
class="submit-button"
|
||||
style:background-color={showSuccess ? '#22c55e' : primaryColor + '60'}
|
||||
style:border-color={showSuccess ? '#22c55e' : primaryColor}
|
||||
>
|
||||
{#if loading}
|
||||
<svg
|
||||
class="spinner"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke-opacity="0.25" />
|
||||
<path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round" />
|
||||
<path d="M2 18v3c0 .6.4 1 1 1h4v-3h3v-3h2l1.4-1.4a6.5 6.5 0 1 0-4-4Z" />
|
||||
<circle cx="16.5" cy="7.5" r=".5" fill="currentColor" />
|
||||
</svg>
|
||||
<span>{t.signingIn}</span>
|
||||
{:else if showSuccess}
|
||||
<Check size={20} />
|
||||
<span>{t.success}</span>
|
||||
{:else}
|
||||
<SignIn size={20} />
|
||||
<span>{t.signInButton}</span>
|
||||
{/if}
|
||||
</button>
|
||||
</form>
|
||||
<span>Passkey</span>
|
||||
</button>
|
||||
<div class="divider">
|
||||
<span>{t.orDivider}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<p class="register-link">
|
||||
{t.noAccount}
|
||||
<button type="button" onclick={() => goto(registerPath)} style:color={primaryColor}>
|
||||
{t.createAccount}
|
||||
</button>
|
||||
</p>
|
||||
{#if verificationEmailSent}
|
||||
<div class="verified-banner" role="status" aria-live="polite">
|
||||
<Check size={18} class="text-green-500 shrink-0" />
|
||||
<p>{t.verificationEmailSent}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="verified-banner-close"
|
||||
onclick={() => (verificationEmailSent = false)}
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<div class="error-message" id="form-error" role="alert" aria-live="assertive">
|
||||
<Warning size={18} class="text-red-500 shrink-0" />
|
||||
<div class="error-content">
|
||||
<p>{error}</p>
|
||||
{#if showEmailNotVerified && onResendVerification}
|
||||
<button
|
||||
type="button"
|
||||
class="resend-link"
|
||||
onclick={handleResendVerification}
|
||||
disabled={resendingVerification}
|
||||
style:color={primaryColor}
|
||||
>
|
||||
{resendingVerification ? t.resendingVerification : t.resendVerification}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleLogin();
|
||||
}}
|
||||
aria-busy={loading}
|
||||
>
|
||||
<!-- Email -->
|
||||
<div class="input-group">
|
||||
<label for="email" class="sr-only">{t.emailPlaceholder}</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
bind:this={emailInput}
|
||||
bind:value={email}
|
||||
placeholder={t.emailPlaceholder}
|
||||
required
|
||||
autocomplete="email"
|
||||
aria-invalid={errorField === 'email'}
|
||||
class="input-field"
|
||||
class:input-error={errorField === 'email'}
|
||||
style:--ring-color={errorField === 'email' ? '#ef4444' : primaryColor}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Password -->
|
||||
<div class="input-group">
|
||||
<label for="password" class="sr-only">{t.passwordPlaceholder}</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
bind:this={passwordInput}
|
||||
bind:value={password}
|
||||
placeholder={t.passwordPlaceholder}
|
||||
required
|
||||
autocomplete="current-password"
|
||||
aria-invalid={errorField === 'password'}
|
||||
class="input-field has-icon"
|
||||
class:input-error={errorField === 'password'}
|
||||
style:--ring-color={errorField === 'password' ? '#ef4444' : primaryColor}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (showPassword = !showPassword)}
|
||||
class="password-toggle"
|
||||
aria-label={showPassword ? t.hidePassword : t.showPassword}
|
||||
>
|
||||
{#if showPassword}
|
||||
<EyeSlash size={20} />
|
||||
{:else}
|
||||
<Eye size={20} />
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Remember & Forgot -->
|
||||
<div class="options-row">
|
||||
<label class="remember-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:checked={rememberMe}
|
||||
style:accent-color={primaryColor}
|
||||
/>
|
||||
<span>{t.rememberMe}</span>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => goto(forgotPasswordPath)}
|
||||
class="forgot-link"
|
||||
style:color={primaryColor}
|
||||
>
|
||||
{t.forgotPassword}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Submit -->
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || showSuccess}
|
||||
class="submit-button"
|
||||
style:background-color={showSuccess ? '#22c55e' : primaryColor + '60'}
|
||||
style:border-color={showSuccess ? '#22c55e' : primaryColor}
|
||||
>
|
||||
{#if loading}
|
||||
<svg
|
||||
class="spinner"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke-opacity="0.25" />
|
||||
<path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round" />
|
||||
</svg>
|
||||
<span>{t.signingIn}</span>
|
||||
{:else if showSuccess}
|
||||
<Check size={20} />
|
||||
<span>{t.success}</span>
|
||||
{:else}
|
||||
<SignIn size={20} />
|
||||
<span>{t.signInButton}</span>
|
||||
{/if}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="register-link">
|
||||
{t.noAccount}
|
||||
<button type="button" onclick={() => goto(registerPath)} style:color={primaryColor}>
|
||||
{t.createAccount}
|
||||
</button>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
|
|
|||
|
|
@ -567,6 +567,186 @@ export function createAuthService(config: AuthServiceConfig) {
|
|||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Enable 2FA - returns TOTP URI for QR code and backup codes
|
||||
*/
|
||||
async enableTwoFactor(
|
||||
password: string
|
||||
): Promise<{ success: boolean; totpURI?: string; backupCodes?: string[]; error?: string }> {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/auth/two-factor/enable`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
return { success: false, error: err.message || 'Failed to enable 2FA' };
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return { success: true, totpURI: data.totpURI, backupCodes: data.backupCodes };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to enable 2FA',
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Disable 2FA
|
||||
*/
|
||||
async disableTwoFactor(password: string): Promise<AuthResult> {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/auth/two-factor/disable`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
return { success: false, error: err.message || 'Failed to disable 2FA' };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to disable 2FA',
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Verify TOTP code during login (when 2FA is required)
|
||||
*/
|
||||
async verifyTwoFactor(code: string, trustDevice?: boolean): Promise<AuthResult> {
|
||||
try {
|
||||
const storage = getStorageAdapter();
|
||||
|
||||
const response = await fetch(`${baseUrl}/api/auth/two-factor/verify-totp`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, trustDevice }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
return { success: false, error: err.message || 'Invalid code' };
|
||||
}
|
||||
|
||||
// After 2FA verification, we need to get tokens
|
||||
// The session cookie is now set by Better Auth
|
||||
// Exchange session for JWT tokens via session-to-token
|
||||
const tokenResponse = await fetch(`${baseUrl}/api/v1/auth/session-to-token`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (tokenResponse.ok) {
|
||||
const tokenData = await tokenResponse.json();
|
||||
if (tokenData.accessToken && tokenData.refreshToken) {
|
||||
await Promise.all([
|
||||
storage.setItem(storageKeys.APP_TOKEN, tokenData.accessToken),
|
||||
storage.setItem(storageKeys.REFRESH_TOKEN, tokenData.refreshToken),
|
||||
storage.setItem(storageKeys.USER_EMAIL, tokenData.user?.email || ''),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
trackAuth('login', { method: '2fa' });
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Verification failed',
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Verify backup code during login
|
||||
*/
|
||||
async verifyBackupCode(code: string): Promise<AuthResult> {
|
||||
try {
|
||||
const storage = getStorageAdapter();
|
||||
|
||||
const response = await fetch(`${baseUrl}/api/auth/two-factor/verify-backup-code`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
return { success: false, error: err.message || 'Invalid backup code' };
|
||||
}
|
||||
|
||||
// Exchange session for JWT tokens
|
||||
const tokenResponse = await fetch(`${baseUrl}/api/v1/auth/session-to-token`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (tokenResponse.ok) {
|
||||
const tokenData = await tokenResponse.json();
|
||||
if (tokenData.accessToken && tokenData.refreshToken) {
|
||||
await Promise.all([
|
||||
storage.setItem(storageKeys.APP_TOKEN, tokenData.accessToken),
|
||||
storage.setItem(storageKeys.REFRESH_TOKEN, tokenData.refreshToken),
|
||||
storage.setItem(storageKeys.USER_EMAIL, tokenData.user?.email || ''),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
trackAuth('login', { method: 'backup_code' });
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Verification failed',
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate new backup codes (replaces existing ones)
|
||||
*/
|
||||
async generateBackupCodes(
|
||||
password: string
|
||||
): Promise<{ success: boolean; backupCodes?: string[]; error?: string }> {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/auth/two-factor/generate-backup-codes`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
return { success: false, error: err.message || 'Failed to generate backup codes' };
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return { success: true, backupCodes: data.backupCodes };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to generate backup codes',
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the current app token
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
* but our NestJS API uses `/api/v1/*` as the global prefix.
|
||||
*/
|
||||
|
||||
import { Controller, Get, Param, Query, Req, Res, HttpStatus } from '@nestjs/common';
|
||||
import { Controller, Get, Post, All, Param, Query, Req, Res, HttpStatus } from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { BetterAuthService } from './services/better-auth.service';
|
||||
|
|
@ -32,6 +32,77 @@ export class BetterAuthPassthroughController {
|
|||
this.logger = loggerService.setContext('BetterAuthPassthrough');
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward requests to Better Auth's handler
|
||||
*
|
||||
* Converts Express request to Fetch Request and passes it to Better Auth.
|
||||
* Copies response status, headers (including Set-Cookie), and body back.
|
||||
*/
|
||||
private async forwardToBetterAuth(req: Request, res: Response) {
|
||||
const baseUrl = this.configService.get<string>('BASE_URL') || 'http://localhost:3001';
|
||||
const url = new URL(req.originalUrl, baseUrl);
|
||||
|
||||
const headers = new Headers();
|
||||
for (const [key, value] of Object.entries(req.headers)) {
|
||||
if (value && typeof value === 'string') {
|
||||
headers.set(key, value);
|
||||
} else if (Array.isArray(value)) {
|
||||
headers.set(key, value[0]);
|
||||
}
|
||||
}
|
||||
|
||||
const fetchRequest = new Request(url.toString(), {
|
||||
method: req.method,
|
||||
headers,
|
||||
body: req.method !== 'GET' && req.method !== 'HEAD' ? JSON.stringify(req.body) : undefined,
|
||||
});
|
||||
|
||||
const handler = this.betterAuthService.getHandler();
|
||||
const response = await handler(fetchRequest);
|
||||
|
||||
res.status(response.status);
|
||||
|
||||
response.headers.forEach((value: string, key: string) => {
|
||||
if (key.toLowerCase() === 'set-cookie') {
|
||||
res.append(key, value);
|
||||
} else {
|
||||
res.setHeader(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
const body = await response.text();
|
||||
try {
|
||||
return res.json(JSON.parse(body));
|
||||
} catch {
|
||||
return res.send(body);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-Factor Authentication passthrough
|
||||
*
|
||||
* Forwards all /api/auth/two-factor/* requests to Better Auth's handler.
|
||||
* The twoFactor plugin registers these routes:
|
||||
* - POST /two-factor/enable
|
||||
* - POST /two-factor/disable
|
||||
* - POST /two-factor/verify-totp
|
||||
* - POST /two-factor/verify-backup-code
|
||||
* - POST /two-factor/get-totp-uri
|
||||
* - POST /two-factor/generate-backup-codes
|
||||
*/
|
||||
@All('two-factor/*')
|
||||
async twoFactorPassthrough(@Req() req: Request, @Res() res: Response) {
|
||||
try {
|
||||
return await this.forwardToBetterAuth(req, res);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
'Two-factor passthrough failed',
|
||||
error instanceof Error ? error.stack : undefined
|
||||
);
|
||||
return res.status(500).json({ error: 'Two-factor request failed' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle SSO get-session request
|
||||
*
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
|
|||
import { jwt } from 'better-auth/plugins/jwt';
|
||||
import { organization } from 'better-auth/plugins/organization';
|
||||
import { oidcProvider } from 'better-auth/plugins/oidc-provider';
|
||||
import { twoFactor } from 'better-auth/plugins/two-factor';
|
||||
import { getDb } from '../db/connection';
|
||||
import { organizations, members, invitations } from '../db/schema/organizations.schema';
|
||||
import {
|
||||
|
|
@ -31,6 +32,7 @@ import {
|
|||
oauthAccessTokens,
|
||||
oauthAuthorizationCodes,
|
||||
oauthConsents,
|
||||
twoFactorAuth,
|
||||
} from '../db/schema/auth.schema';
|
||||
import type { JWTPayloadContext } from './types/better-auth.types';
|
||||
import {
|
||||
|
|
@ -96,6 +98,9 @@ export function createBetterAuth(databaseUrl: string) {
|
|||
// JWT plugin table
|
||||
jwks: jwks,
|
||||
|
||||
// Two-Factor Authentication table
|
||||
twoFactor: twoFactorAuth,
|
||||
|
||||
// OIDC Provider tables
|
||||
oauthApplication: oauthApplications,
|
||||
oauthAccessToken: oauthAccessTokens,
|
||||
|
|
@ -403,6 +408,21 @@ export function createBetterAuth(databaseUrl: string) {
|
|||
},
|
||||
],
|
||||
}),
|
||||
/**
|
||||
* Two-Factor Authentication Plugin (TOTP)
|
||||
*
|
||||
* Provides TOTP-based 2FA with backup codes.
|
||||
* Endpoints provided automatically by Better Auth passthrough:
|
||||
* - POST /two-factor/enable (requires password)
|
||||
* - POST /two-factor/disable (requires password)
|
||||
* - POST /two-factor/verify-totp (during login)
|
||||
* - POST /two-factor/verify-backup-code (during login)
|
||||
* - POST /two-factor/get-totp-uri
|
||||
* - POST /two-factor/generate-backup-codes
|
||||
*/
|
||||
twoFactor({
|
||||
issuer: 'ManaCore',
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -478,6 +478,23 @@ export class BetterAuthService {
|
|||
}
|
||||
}
|
||||
|
||||
// Check if 2FA is required
|
||||
if (
|
||||
result &&
|
||||
typeof result === 'object' &&
|
||||
'twoFactorRedirect' in result &&
|
||||
(result as any).twoFactorRedirect
|
||||
) {
|
||||
this.logger.debug('SignIn: 2FA required, returning redirect');
|
||||
return {
|
||||
twoFactorRedirect: true,
|
||||
user: null,
|
||||
accessToken: '',
|
||||
refreshToken: '',
|
||||
expiresIn: 0,
|
||||
} as any;
|
||||
}
|
||||
|
||||
if (!hasUser(result)) {
|
||||
throw new UnauthorizedException('Invalid credentials');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ export const users = authSchema.table('users', {
|
|||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
// Custom fields (not required by Better Auth)
|
||||
role: userRoleEnum('role').default('user').notNull(),
|
||||
twoFactorEnabled: boolean('two_factor_enabled').default(false),
|
||||
deletedAt: timestamp('deleted_at', { withTimezone: true }),
|
||||
});
|
||||
|
||||
|
|
@ -103,7 +104,7 @@ export const twoFactorAuth = authSchema.table('two_factor_auth', {
|
|||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
secret: text('secret').notNull(),
|
||||
enabled: boolean('enabled').default(false).notNull(),
|
||||
backupCodes: jsonb('backup_codes'),
|
||||
backupCodes: text('backup_codes').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
enabledAt: timestamp('enabled_at', { withTimezone: true }),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -49,6 +49,11 @@ export const SecurityEventType = {
|
|||
PASSKEY_LOGIN_FAILURE: 'passkey_login_failure',
|
||||
PASSKEY_DELETED: 'passkey_deleted',
|
||||
|
||||
// Two-Factor Authentication
|
||||
TWO_FACTOR_ENABLED: 'two_factor_enabled',
|
||||
TWO_FACTOR_DISABLED: 'two_factor_disabled',
|
||||
TWO_FACTOR_VERIFIED: 'two_factor_verified',
|
||||
|
||||
// Organizations
|
||||
ORG_CREATED: 'org_created',
|
||||
ORG_DELETED: 'org_deleted',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue