Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

fix: resolves broken 2fa login

towfiqi7f69a7f2caa0
diff --git a/backend/__tests__/controllers/SettingsController.test.ts b/backend/__tests__/controllers/SettingsController.test.ts
index 28251bc..c33e34b 100644
--- a/backend/__tests__/controllers/SettingsController.test.ts
+++ b/backend/__tests__/controllers/SettingsController.test.ts
@@ -95,6 +95,59 @@ describe('SettingsController', () => {
});
});
+ describe('2FA data in responses', () => {
+ const rowWithTotp = () => ({
+ id: 1,
+ settings: {
+ title: 'Pluton',
+ totp: { enabled: true, secret: 'encrypted-secret', recoveryCodes: ['hash1', 'hash2'] },
+ } as any,
+ });
+ const publicTotp = { enabled: true, configured: true };
+
+ it('should not send the TOTP secret or recovery codes from getMainSettings', async () => {
+ mockSettingsService.getMainSettings.mockResolvedValue(rowWithTotp() as any);
+
+ await settingsController.getMainSettings(mockRequest as Request, mockResponse as Response);
+
+ const result = mockJson.mock.calls[0][0].result;
+ expect(result.settings.totp).toEqual(publicTotp);
+ expect(result.settings.title).toBe('Pluton');
+ });
+
+ it('should not send the TOTP secret or recovery codes from getSettings', async () => {
+ mockRequest.params = { id: '1' };
+ mockSettingsService.getSettings.mockResolvedValue(rowWithTotp() as any);
+
+ await settingsController.getSettings(mockRequest as Request, mockResponse as Response);
+
+ expect(mockJson.mock.calls[0][0].result.settings.totp).toEqual(publicTotp);
+ });
+
+ it('should not send the TOTP secret or recovery codes from updateSettings', async () => {
+ mockRequest.params = { id: '1' };
+ mockRequest.body = { settings: { title: 'Pluton' } };
+ mockSettingsService.updateSettings.mockResolvedValue(rowWithTotp() as any);
+
+ await settingsController.updateSettings(mockRequest as Request, mockResponse as Response);
+
+ expect(mockJson.mock.calls[0][0].result.settings.totp).toEqual(publicTotp);
+ });
+
+ it('should report configured false when no secret is saved', async () => {
+ const row = rowWithTotp();
+ row.settings.totp = { enabled: false, secret: '', recoveryCodes: [] };
+ mockSettingsService.getMainSettings.mockResolvedValue(row as any);
+
+ await settingsController.getMainSettings(mockRequest as Request, mockResponse as Response);
+
+ expect(mockJson.mock.calls[0][0].result.settings.totp).toEqual({
+ enabled: false,
+ configured: false,
+ });
+ });
+ });
+
describe('getSettings', () => {
it('should return 400 if settings ID is missing', async () => {
mockRequest.params = {};
diff --git a/backend/__tests__/controllers/UserController.test.ts b/backend/__tests__/controllers/UserController.test.ts
index 7f3f9da..69ce9b3 100644
--- a/backend/__tests__/controllers/UserController.test.ts
+++ b/backend/__tests__/controllers/UserController.test.ts
@@ -2,9 +2,22 @@ import { Request, Response } from 'express';
import { UserController } from '../../src/controllers/UserController';
import { configService } from '../../src/services/ConfigService';
import jwt from 'jsonwebtoken';
+import Cryptr from 'cryptr';
+import * as otpauth from 'otpauth';
jest.mock('jsonwebtoken');
+const TOTP_SECRET = new otpauth.Secret().base32;
+const totpSettings = (enabled = true) => ({
+ id: 1,
+ settings: {
+ title: 'Pluton',
+ totp: { enabled, secret: new Cryptr('test-secret').encrypt(TOTP_SECRET), recoveryCodes: [] },
+ },
+});
+const currentTotpCode = () =>
+ new otpauth.TOTP({ secret: otpauth.Secret.fromBase32(TOTP_SECRET) }).generate();
+
const mockVerifyPassword = jest.fn();
const mockHashAndStorePassword = jest.fn();
@@ -29,6 +42,8 @@ describe('UserController', () => {
let mockStatus: jest.Mock;
let mockCookie: jest.Mock;
let mockClearCookie: jest.Mock;
+ let mockSettingsService: { getMainSettings: jest.Mock; consumeRecoveryCode: jest.Mock };
+ let mockSession: Record<string, any>;
beforeEach(() => {
jest.clearAllMocks();
@@ -47,11 +62,20 @@ describe('UserController', () => {
clearCookie: mockClearCookie,
};
+ mockSession = {
+ regenerate: jest.fn((cb: (err?: any) => void) => cb()),
+ destroy: jest.fn((cb: (err?: any) => void) => cb()),
+ };
mockRequest = {
body: {},
+ session: mockSession as any,
};
- userController = new UserController();
+ mockSettingsService = {
+ getMainSettings: jest.fn().mockResolvedValue({ id: 1, settings: {} }),
+ consumeRecoveryCode: jest.fn().mockResolvedValue(false),
+ };
+ userController = new UserController(mockSettingsService as any);
});
describe('validateUser', () => {
@@ -149,6 +173,103 @@ describe('UserController', () => {
});
});
+ describe('loginUser with 2FA enabled', () => {
+ it('should require the 2FA step and not set the token cookie', async () => {
+ mockRequest.body = { username: 'testuser', password: 'testpass' };
+ mockVerifyPassword.mockReturnValue(true);
+ mockSettingsService.getMainSettings.mockResolvedValue(totpSettings());
+
+ await userController.loginUser(mockRequest as Request, mockResponse as Response);
+
+ expect(mockCookie).not.toHaveBeenCalled();
+ expect(mockSession.regenerate).toHaveBeenCalled();
+ expect(mockSession.pendingTotpUser).toBe('testuser');
+ expect(mockStatus).toHaveBeenCalledWith(200);
+ expect(mockJson).toHaveBeenCalledWith({ success: true, totpRequired: true, error: null });
+ });
+
+ it('should log in directly when 2FA is configured but disabled', async () => {
+ mockRequest.body = { username: 'testuser', password: 'testpass' };
+ mockVerifyPassword.mockReturnValue(true);
+ (jwt.sign as jest.Mock).mockReturnValue('mock-token');
+ mockSettingsService.getMainSettings.mockResolvedValue(totpSettings(false));
+
+ await userController.loginUser(mockRequest as Request, mockResponse as Response);
+
+ expect(mockCookie).toHaveBeenCalledWith('token', 'mock-token', expect.any(Object));
+ expect(mockJson).toHaveBeenCalledWith({ success: true, error: null });
+ });
+ });
+
+ describe('verifyTotp', () => {
+ beforeEach(() => {
+ mockSettingsService.getMainSettings.mockResolvedValue(totpSettings());
+ (jwt.sign as jest.Mock).mockReturnValue('mock-token');
+ });
+
+ it('should return 401 without a pending password login', async () => {
+ mockRequest.body = { code: currentTotpCode() };
+
+ await userController.verifyTotp(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(401);
+ expect(mockCookie).not.toHaveBeenCalled();
+ });
+
+ it('should set the token cookie for a valid TOTP code', async () => {
+ mockSession.pendingTotpUser = 'testuser';
+ mockRequest.body = { code: currentTotpCode() };
+
+ await userController.verifyTotp(mockRequest as Request, mockResponse as Response);
+
+ expect(jwt.sign).toHaveBeenCalledWith({ user: 'testuser' }, 'test-secret', {
+ expiresIn: '7d',
+ });
+ expect(mockCookie).toHaveBeenCalledWith('token', 'mock-token', expect.any(Object));
+ expect(mockSession.destroy).toHaveBeenCalled();
+ expect(mockSettingsService.consumeRecoveryCode).not.toHaveBeenCalled();
+ expect(mockJson).toHaveBeenCalledWith({ success: true, error: null });
+ });
+
+ it('should accept a valid recovery code', async () => {
+ mockSession.pendingTotpUser = 'testuser';
+ mockRequest.body = { code: 'ABCDE12345' };
+ mockSettingsService.consumeRecoveryCode.mockResolvedValue(true);
+
+ await userController.verifyTotp(mockRequest as Request, mockResponse as Response);
+
+ expect(mockSettingsService.consumeRecoveryCode).toHaveBeenCalledWith('ABCDE12345');
+ expect(mockCookie).toHaveBeenCalled();
+ });
+
+ it('should return 401 for an invalid code and count the attempt', async () => {
+ mockSession.pendingTotpUser = 'testuser';
+ mockRequest.body = { code: '000000' };
+
+ await userController.verifyTotp(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(401);
+ expect(mockCookie).not.toHaveBeenCalled();
+ expect(mockSession.totpAttempts).toBe(1);
+ expect(mockSession.destroy).not.toHaveBeenCalled();
+ });
+
+ it('should end the pending login after too many invalid codes', async () => {
+ mockSession.pendingTotpUser = 'testuser';
+ mockSession.totpAttempts = 4;
+ mockRequest.body = { code: '000000' };
+
+ await userController.verifyTotp(mockRequest as Request, mockResponse as Response);
+
+ expect(mockSession.destroy).toHaveBeenCalled();
+ expect(mockStatus).toHaveBeenCalledWith(401);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Too many invalid codes. Please log in again.',
+ });
+ });
+ });
+
describe('logoutUser', () => {
it('should clear cookie and return success', async () => {
await userController.logoutUser(mockRequest as Request, mockResponse as Response);
diff --git a/backend/__tests__/routes/users.test.ts b/backend/__tests__/routes/users.test.ts
index b5c8332..7d509d7 100644
--- a/backend/__tests__/routes/users.test.ts
+++ b/backend/__tests__/routes/users.test.ts
@@ -5,6 +5,9 @@ import { UserController } from '../../src/controllers/UserController';
import { configService } from '../../src/services/ConfigService';
import jwt from 'jsonwebtoken';
import Cookies from 'cookies';
+import session from 'express-session';
+import Cryptr from 'cryptr';
+import * as otpauth from 'otpauth';
jest.mock('jsonwebtoken');
jest.mock('cookies');
@@ -25,17 +28,27 @@ jest.mock('../../src/services/ConfigService', () => ({
},
}));
+const TOTP_SECRET = new otpauth.Secret().base32;
+const currentTotpCode = () =>
+ new otpauth.TOTP({ secret: otpauth.Secret.fromBase32(TOTP_SECRET) }).generate();
+
describe('User Routes', () => {
let app: Express;
let userController: UserController;
+ let mockSettingsService: { getMainSettings: jest.Mock; consumeRecoveryCode: jest.Mock };
beforeEach(() => {
jest.clearAllMocks();
mockVerifyPassword.mockReturnValue(false);
mockHashAndStorePassword.mockReturnValue('$2a$10$mockhash');
- userController = new UserController();
+ mockSettingsService = {
+ getMainSettings: jest.fn().mockResolvedValue({ id: 1, settings: {} }),
+ consumeRecoveryCode: jest.fn().mockResolvedValue(false),
+ };
+ userController = new UserController(mockSettingsService as any);
app = express();
+ app.use(session({ secret: 'test-session-secret', resave: false, saveUninitialized: false }));
app.use(express.json());
app.use('/api/user', createUserRouter(userController));
});
@@ -91,6 +104,74 @@ describe('User Routes', () => {
});
});
+ describe('2FA login flow', () => {
+ beforeEach(() => {
+ (jwt.sign as jest.Mock).mockReturnValue('mock-token');
+ mockVerifyPassword.mockReturnValue(true);
+ mockSettingsService.getMainSettings.mockResolvedValue({
+ id: 1,
+ settings: {
+ totp: {
+ enabled: true,
+ secret: new Cryptr('test-secret').encrypt(TOTP_SECRET),
+ recoveryCodes: [],
+ },
+ },
+ });
+ });
+
+ const tokenCookieSet = (res: request.Response) =>
+ ([] as string[]).concat(res.headers['set-cookie'] || []).some(c => c.startsWith('token='));
+
+ it('should not issue the token cookie after the password step', async () => {
+ const response = await request(app)
+ .post('/api/user/login')
+ .send({ username: 'testuser', password: 'testpass' });
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ success: true, totpRequired: true, error: null });
+ expect(tokenCookieSet(response)).toBe(false);
+ });
+
+ it('should reject verify-otp without the password step', async () => {
+ const response = await request(app)
+ .post('/api/user/verify-otp')
+ .send({ code: currentTotpCode() });
+
+ expect(response.status).toBe(401);
+ expect(tokenCookieSet(response)).toBe(false);
+ });
+
+ it('should issue the token cookie after password and a valid code', async () => {
+ const agent = request.agent(app);
+ await agent.post('/api/user/login').send({ username: 'testuser', password: 'testpass' });
+
+ const response = await agent.post('/api/user/verify-otp').send({ code: currentTotpCode() });
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ success: true, error: null });
+ expect(tokenCookieSet(response)).toBe(true);
+
+ // The pending login is consumed and cannot be reused
+ const reuse = await agent.post('/api/user/verify-otp').send({ code: currentTotpCode() });
+ expect(reuse.status).toBe(401);
+ });
+
+ it('should require the password again after too many invalid codes', async () => {
+ const agent = request.agent(app);
+ await agent.post('/api/user/login').send({ username: 'testuser', password: 'testpass' });
+
+ for (let i = 0; i < 5; i++) {
+ const res = await agent.post('/api/user/verify-otp').send({ code: '000000' });
+ expect(res.status).toBe(401);
+ }
+
+ const response = await agent.post('/api/user/verify-otp').send({ code: currentTotpCode() });
+ expect(response.status).toBe(401);
+ expect(response.body.error).toBe('Login session expired. Please log in again.');
+ });
+ });
+
describe('GET /api/user/validate', () => {
it('should return 401 if no token is provided', async () => {
(Cookies as jest.MockedClass<typeof Cookies>).mockImplementation(
diff --git a/backend/__tests__/services/SettingsService.test.ts b/backend/__tests__/services/SettingsService.test.ts
index 0a3fe8c..aefb50a 100644
--- a/backend/__tests__/services/SettingsService.test.ts
+++ b/backend/__tests__/services/SettingsService.test.ts
@@ -125,6 +125,66 @@ describe('SettingsService', () => {
// );
// });
+ describe('2FA data', () => {
+ const storedTotp = { enabled: true, secret: 'stored-secret', recoveryCodes: ['hash1'] };
+
+ beforeEach(() => {
+ mockSettingsStore.update.mockImplementation(
+ async (id, settings) => ({ id, settings }) as any
+ );
+ });
+
+ it('should keep the stored secret and recovery codes when the request has fake values', async () => {
+ mockSettingsStore.getById.mockResolvedValue({ id: 1, settings: { totp: storedTotp } } as any);
+
+ await settingsService.updateSettings(settingsId, {
+ title: 'T',
+ totp: { enabled: true, secret: 'attacker-secret', recoveryCodes: ['attacker-hash'] },
+ } as AppSettings);
+
+ expect(mockSettingsStore.update.mock.calls[0][1].totp).toEqual(storedTotp);
+ });
+
+ it('should keep the stored 2FA data when the request has no totp block', async () => {
+ mockSettingsStore.getById.mockResolvedValue({ id: 1, settings: { totp: storedTotp } } as any);
+
+ await settingsService.updateSettings(settingsId, { title: 'T' } as AppSettings);
+
+ expect(mockSettingsStore.update.mock.calls[0][1].totp).toEqual(storedTotp);
+ });
+
+ it('should let the toggle turn 2FA off and on', async () => {
+ mockSettingsStore.getById.mockResolvedValue({ id: 1, settings: { totp: storedTotp } } as any);
+
+ await settingsService.updateSettings(settingsId, {
+ totp: { enabled: false, configured: true },
+ } as any);
+ expect(mockSettingsStore.update.mock.calls[0][1].totp).toEqual({
+ ...storedTotp,
+ enabled: false,
+ });
+
+ await settingsService.updateSettings(settingsId, {
+ totp: { enabled: true, configured: true },
+ } as any);
+ expect(mockSettingsStore.update.mock.calls[1][1].totp).toEqual(storedTotp);
+ });
+
+ it('should not enable 2FA when no secret is stored', async () => {
+ mockSettingsStore.getById.mockResolvedValue({ id: 1, settings: {} } as any);
+
+ await settingsService.updateSettings(settingsId, {
+ totp: { enabled: true, secret: 'attacker-secret', recoveryCodes: [] },
+ } as any);
+
+ expect(mockSettingsStore.update.mock.calls[0][1].totp).toEqual({
+ enabled: false,
+ secret: '',
+ recoveryCodes: [],
+ });
+ });
+ });
+
it('should throw an AppError if the store fails to update', async () => {
mockSettingsStore.update.mockResolvedValue(null);
@@ -134,6 +194,41 @@ describe('SettingsService', () => {
});
});
+ // ----------------------------------------
+ // consumeRecoveryCode
+ // ----------------------------------------
+ describe('consumeRecoveryCode', () => {
+ const { createHash } = jest.requireActual('crypto');
+ const hash = (code: string) => createHash('sha256').update(code).digest('hex');
+ const row = () =>
+ ({
+ id: 1,
+ settings: {
+ title: 'T',
+ totp: { enabled: true, secret: 's', recoveryCodes: [hash('AAAAA11111'), hash('BBBBB22222')] },
+ },
+ }) as any;
+
+ it('should accept a stored code and remove it', async () => {
+ mockSettingsStore.getFirst.mockResolvedValue(row());
+
+ const result = await settingsService.consumeRecoveryCode(' aaaaa11111 ');
+
+ expect(result).toBe(true);
+ expect(mockSettingsStore.update).toHaveBeenCalledWith(1, {
+ title: 'T',
+ totp: { enabled: true, secret: 's', recoveryCodes: [hash('BBBBB22222')] },
+ });
+ });
+
+ it('should reject an unknown code without updating', async () => {
+ mockSettingsStore.getFirst.mockResolvedValue(row());
+
+ expect(await settingsService.consumeRecoveryCode('CCCCC33333')).toBe(false);
+ expect(mockSettingsStore.update).not.toHaveBeenCalled();
+ });
+ });
+
// ----------------------------------------
// validateIntegration
// ----------------------------------------
diff --git a/backend/src/controllers/SettingsController.ts b/backend/src/controllers/SettingsController.ts
index 501c0b3..9249e3b 100644
--- a/backend/src/controllers/SettingsController.ts
+++ b/backend/src/controllers/SettingsController.ts
@@ -2,16 +2,27 @@ import { Request, Response } from 'express';
import { createReadStream } from 'fs';
import { SettingsService } from '../services/SettingsService';
import { AppSettings, IntegrationTypes } from '../types/settings';
+import { Settings } from '../db/schema/settings';
export class SettingsController {
constructor(protected settingsService: SettingsService) {}
+ // The TOTP secret and recovery code hashes must never leave the server.
+ protected toPublicSettings(row: Settings | null) {
+ const totp = row?.settings?.totp;
+ if (!row || !totp) return row;
+ return {
+ ...row,
+ settings: { ...row.settings, totp: { enabled: totp.enabled, configured: !!totp.secret } },
+ };
+ }
+
async getMainSettings(req: Request, res: Response): Promise<void> {
try {
const appSettings = await this.settingsService.getMainSettings();
res.status(appSettings ? 200 : 404).json({
success: true,
- result: appSettings,
+ result: this.toPublicSettings(appSettings),
});
return;
} catch (error: any) {
@@ -35,7 +46,7 @@ export class SettingsController {
const appSettings = await this.settingsService.getSettings(parseInt(req.params.id, 10));
res.status(appSettings ? 200 : 404).json({
success: true,
- result: appSettings,
+ result: this.toPublicSettings(appSettings),
});
} catch (error: any) {
res.status(500).json({
@@ -62,7 +73,7 @@ export class SettingsController {
);
res.status(updatedSettings ? 200 : 404).json({
success: true,
- result: updatedSettings,
+ result: this.toPublicSettings(updatedSettings),
});
return;
} catch (error: any) {
diff --git a/backend/src/controllers/UserController.ts b/backend/src/controllers/UserController.ts
index f53eab8..aa75bdc 100644
--- a/backend/src/controllers/UserController.ts
+++ b/backend/src/controllers/UserController.ts
@@ -5,12 +5,27 @@ import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { SettingsService } from '../services/SettingsService';
+const MAX_TOTP_ATTEMPTS = 5;
+
export class UserController {
constructor(private settingsService: SettingsService) {}
async validateUser(req: Request, res: Response): Promise<void> {
res.status(200).json({ success: true });
}
+ private issueAuthCookie(res: Response, userName: string): void {
+ const sessionDuration = configService.config.SESSION_DURATION || 7;
+ const token = jwt.sign({ user: userName }, configService.config.SECRET, {
+ expiresIn: `${sessionDuration}d`,
+ });
+ res.cookie('token', token, {
+ httpOnly: true,
+ sameSite: 'lax',
+ maxAge: sessionDuration * 24 * 60 * 60 * 1000,
+ secure: configService.config.APP_URL?.startsWith('https'),
+ });
+ }
+
async loginUser(req: Request, res: Response): Promise<void> {
const { username, password } = req.body;
if (!username || !password) {
@@ -21,18 +36,24 @@ export class UserController {
const theUserName = configService.config.USER_NAME;
if (username === theUserName && configService.verifyPassword(password)) {
- // Express way of setting cookies
- const sessionDuration = configService.config.SESSION_DURATION || 7;
- const token = jwt.sign({ user: theUserName }, configService.config.SECRET, {
- expiresIn: `${sessionDuration}d`,
- });
- res.cookie('token', token, {
- httpOnly: true,
- sameSite: 'lax',
- maxAge: sessionDuration * 24 * 60 * 60 * 1000,
- secure: configService.config.APP_URL?.startsWith('https'),
- });
+ const appSettings = await this.settingsService.getMainSettings();
+ const totpConfig = appSettings?.settings?.totp;
+
+ if (totpConfig?.enabled && totpConfig.secret) {
+ // Password is correct, but the session token is only issued after the 2FA step.
+ req.session.regenerate(err => {
+ if (err) {
+ res.status(500).json({ success: false, error: 'Could not start login session.' });
+ return;
+ }
+ req.session.pendingTotpUser = theUserName;
+ req.session.totpAttempts = 0;
+ res.status(200).json({ success: true, totpRequired: true, error: null });
+ });
+ return;
+ }
+ this.issueAuthCookie(res, theUserName);
res.status(200).json({ success: true, error: null });
return;
}
@@ -44,9 +65,18 @@ export class UserController {
async verifyTotp(req: Request, res: Response): Promise<void> {
const { code } = req.body;
+ const pendingUser = req.session?.pendingTotpUser;
+
+ if (!pendingUser) {
+ res.status(401).json({ success: false, error: 'Login session expired. Please log in again.' });
+ return;
+ }
+
+ if (!code || typeof code !== 'string') {
+ res.status(400).json({ success: false, error: 'Verification code is missing.' });
+ return;
+ }
- // 1. Fetch settings to get the secret
- // This assumes you have access to settingsService
const appSettings = await this.settingsService.getMainSettings();
const totpConfig = appSettings?.settings?.totp;
@@ -56,48 +86,43 @@ export class UserController {
}
try {
- // 2. Decrypt the stored secret
const cryptr = new Cryptr(configService.config.SECRET);
const decryptedSecret = cryptr.decrypt(totpConfig.secret);
- // 3. Re-create the TOTP instance with the exact same parameters
const appName = appSettings?.settings?.title || 'Pluton';
- const userIdentifier = 'admin';
const totp = new otpauth.TOTP({
issuer: appName,
- label: userIdentifier,
+ label: 'admin',
secret: otpauth.Secret.fromBase32(decryptedSecret),
algorithm: 'SHA1',
digits: 6,
period: 30,
});
- // 4. Validate the token
- const delta = totp.validate({
- token: code,
- window: 1, // Allows codes from the previous, current, and next time periods
- });
-
- if (delta === null) {
- // Code is invalid
+ // window: 1 allows codes from the previous, current, and next time periods
+ const isValidTotp = totp.validate({ token: code.trim(), window: 1 }) !== null;
+ const isValid = isValidTotp || (await this.settingsService.consumeRecoveryCode(code));
+
+ if (!isValid) {
+ const attempts = (req.session.totpAttempts || 0) + 1;
+ if (attempts >= MAX_TOTP_ATTEMPTS) {
+ req.session.destroy(() => {
+ res.status(401).json({
+ success: false,
+ error: 'Too many invalid codes. Please log in again.',
+ });
+ });
+ return;
+ }
+ req.session.totpAttempts = attempts;
res.status(401).json({ success: false, error: 'Invalid verification code.' });
return;
}
- // 5. Code is valid! Proceed with login
- // (The JWT generation and cookie setting logic from your original loginUser method goes here)
- const sessionDuration = configService.config.SESSION_DURATION || 7;
- const token = jwt.sign({ user: 'admin' }, configService.config.SECRET, {
- expiresIn: `${sessionDuration}d`,
+ req.session.destroy(() => {
+ this.issueAuthCookie(res, pendingUser);
+ res.status(200).json({ success: true, error: null });
});
-
- res.cookie('token', token, {
- httpOnly: true,
- sameSite: 'lax',
- maxAge: sessionDuration * 24 * 60 * 60 * 1000,
- secure: configService.config.APP_URL?.startsWith('https'),
- });
- res.status(200).json({ success: true, error: null });
} catch (error) {
console.error('Error during 2FA verification:', error);
res.status(500).json({ success: false, error: 'An error occurred during verification.' });
diff --git a/backend/src/services/SettingsService.ts b/backend/src/services/SettingsService.ts
index da63de3..7c0107a 100644
--- a/backend/src/services/SettingsService.ts
+++ b/backend/src/services/SettingsService.ts
@@ -41,6 +41,20 @@ export class SettingsService {
try {
// Validate the plan data using the schema
let parsedSettings = { ...settings };
+
+ // The TOTP secret and recovery codes are only written by the 2FA setup and login flows.
+ const storedTotp = (await this.settingsStore.getById(id))?.settings?.totp;
+ if (parsedSettings.totp !== undefined || storedTotp) {
+ const requestedEnabled = parsedSettings.totp
+ ? parsedSettings.totp.enabled
+ : storedTotp?.enabled;
+ parsedSettings.totp = {
+ enabled: !!requestedEnabled && !!storedTotp?.secret,
+ secret: storedTotp?.secret || '',
+ recoveryCodes: storedTotp?.recoveryCodes || [],
+ };
+ }
+
try {
const parsedSettingsEntry = settingsUpdateSchema
.partial()
@@ -293,6 +307,28 @@ export class SettingsService {
return { recoveryCodes };
}
+ /**
+ * Checks a 2FA recovery code and removes it on match, so each code works only once.
+ */
+ public async consumeRecoveryCode(code: string): Promise<boolean> {
+ const appSettings = await this.settingsStore.getFirst();
+ const totp = appSettings?.settings?.totp;
+ if (!appSettings || !totp?.recoveryCodes?.length) {
+ return false;
+ }
+
+ const hashedCode = createHash('sha256').update(code.trim().toUpperCase()).digest('hex');
+ if (!totp.recoveryCodes.includes(hashedCode)) {
+ return false;
+ }
+
+ await this.settingsStore.update(appSettings.id, {
+ ...appSettings.settings,
+ totp: { ...totp, recoveryCodes: totp.recoveryCodes.filter(c => c !== hashedCode) },
+ } as AppSettings);
+ return true;
+ }
+
async getSelfBackupStatus() {
return await this.selfBackupService.getStatus();
}
diff --git a/backend/src/types/express-session.d.ts b/backend/src/types/express-session.d.ts
index 56328d7..15ce6cb 100644
--- a/backend/src/types/express-session.d.ts
+++ b/backend/src/types/express-session.d.ts
@@ -3,5 +3,7 @@ import 'express-session';
declare module 'express-session' {
interface SessionData {
totpSecret?: string;
+ pendingTotpUser?: string;
+ totpAttempts?: number;
}
}
diff --git a/backend/src/types/settings.ts b/backend/src/types/settings.ts
index 97cb90c..54917c2 100644
--- a/backend/src/types/settings.ts
+++ b/backend/src/types/settings.ts
@@ -82,6 +82,7 @@ export interface AppSettings {
enabled: boolean;
secret: string;
recoveryCodes: string[];
+ configured?: boolean;
};
reporting: {
emails: string[];
diff --git a/frontend/src/components/Settings/GeneralSettings/GeneralSettings.tsx b/frontend/src/components/Settings/GeneralSettings/GeneralSettings.tsx
index de3a07f..d94993d 100644
--- a/frontend/src/components/Settings/GeneralSettings/GeneralSettings.tsx
+++ b/frontend/src/components/Settings/GeneralSettings/GeneralSettings.tsx
@@ -19,7 +19,7 @@ const GeneralSettings = ({ settings, settingsID, onUpdate }: GeneralSettingsProp
const [show2FASetup, setShow2FASetup] = useState(false);
const { totp } = settings || {};
- const is2FASetupComplete = totp?.secret;
+ const is2FASetupComplete = totp?.configured;
const update2FASetting = (enabled: boolean) => {
if (enabled === true && !is2FASetupComplete) {
diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx
index d80c7c9..006943a 100644
--- a/frontend/src/router.tsx
+++ b/frontend/src/router.tsx
@@ -1,6 +1,7 @@
import { Routes, Route, Navigate } from 'react-router';
import Plans from './routes/Plans/Plans';
import Login from './routes/Login/Login';
+import VerifyOtp from './routes/Login/VerifyOtp';
import Setup from './routes/Setup/Setup';
import { useAuth } from './services/users';
import App from './components/App/App/App';
@@ -89,6 +90,14 @@ export function AppRoutes() {
</PublicRoute>
}
/>
+ <Route
+ path="login/verify-otp"
+ element={
+ <PublicRoute>
+ <VerifyOtp />
+ </PublicRoute>
+ }
+ />
<Route path="setup" element={<Setup />} />
</Routes>
);
diff --git a/frontend/src/routes/Login/Login.module.scss b/frontend/src/routes/Login/Login.module.scss
index 03df73d..f4aaa6e 100644
--- a/frontend/src/routes/Login/Login.module.scss
+++ b/frontend/src/routes/Login/Login.module.scss
@@ -92,3 +92,13 @@
border-radius: 5px;
margin-top: 15px;
}
+
+.loginBackLink {
+ margin-top: 15px;
+ text-align: center;
+ font-size: 0.75rem;
+ a {
+ color: var(--content-text-color);
+ opacity: 0.8;
+ }
+}
diff --git a/frontend/src/routes/Login/VerifyOtp.tsx b/frontend/src/routes/Login/VerifyOtp.tsx
new file mode 100644
index 0000000..ba884cd
--- /dev/null
+++ b/frontend/src/routes/Login/VerifyOtp.tsx
@@ -0,0 +1,83 @@
+import { useState } from 'react';
+import { Link, useNavigate } from 'react-router';
+import classes from './Login.module.scss';
+import Logo from '../../components/common/Logo/Logo';
+import { APP_NAME } from '../../utils/constants';
+import Icon from '../../components/common/Icon/Icon';
+import { useVerifyTwoFactorOTP } from '../../services/settings';
+import PageTitle from '../../components/App/PageTitle/PageTitle';
+
+const VerifyOtp = () => {
+ const [error, setError] = useState<string>('');
+ const [code, setCode] = useState<string>('');
+ const navigate = useNavigate();
+ const verifyMutation = useVerifyTwoFactorOTP();
+
+ const showError = (msg: string) => {
+ setError(msg);
+ setTimeout(() => setError(''), 5000);
+ };
+
+ const handleVerify = () => {
+ if (!code.trim()) {
+ showError('Please Insert the Code from your Authenticator App or a Recovery Code.');
+ return;
+ }
+
+ verifyMutation.mutate(
+ { code: code.trim() },
+ {
+ onError: (error: Error) => {
+ // The pending login session is gone (expired or too many attempts)
+ if (error.message.toLowerCase().includes('log in again')) {
+ navigate('/login');
+ return;
+ }
+ showError(error.message);
+ },
+ },
+ );
+ };
+
+ return (
+ <div className={classes.loginPage}>
+ <PageTitle title={`Two-Factor Authentication`} />
+ <div className={classes.loginLogo}>
+ <h3>
+ <Logo size={36} /> <span>{APP_NAME}</span>
+ </h3>
+ </div>
+ <div className={classes.container}>
+ <form
+ className="loginForm"
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleVerify();
+ }}
+ >
+ <div className={classes.loginInput}>
+ <Icon type="password" classes={classes.loginInputIcon} />
+ <input
+ className={`${error ? 'inputError' : ''}`}
+ type="text"
+ value={code}
+ placeholder="Authentication Code"
+ autoComplete="one-time-code"
+ autoFocus
+ onChange={(event) => setCode(event.target.value)}
+ />
+ </div>
+ <button className={classes.loginButton} type="submit" disabled={verifyMutation.isPending}>
+ {verifyMutation.isPending ? 'Verifying...' : 'Verify'}
+ </button>
+ {error && <div className={classes.loginErrorMsg}>{error}</div>}
+ <div className={classes.loginBackLink}>
+ <Link to="/login">Back to Login</Link>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+export default VerifyOtp;
diff --git a/frontend/src/services/settings.ts b/frontend/src/services/settings.ts
index adbf66c..d622a84 100644
--- a/frontend/src/services/settings.ts
+++ b/frontend/src/services/settings.ts
@@ -429,15 +429,13 @@ export async function verifyTwoFactorOTP({ code }: { code: string }) {
export function useVerifyTwoFactorOTP() {
const navigate = useNavigate();
+ const queryClient = useQueryClient();
return useMutation({
mutationFn: verifyTwoFactorOTP,
- onSuccess: (res) => {
- console.log('# 2FA verification successful! :', res);
+ onSuccess: () => {
+ queryClient.resetQueries({ queryKey: ['auth'] });
navigate('/');
},
- onError: (res) => {
- console.log('# 2FA verification failed! :', res);
- },
});
}