Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(mfa): don't burn a recovery code on a wrong-password login
Elian Dorandc808d09f79a
diff --git a/apps/server/src/routes/api/login.ts b/apps/server/src/routes/api/login.tsindex 0068e40544..5cc2860e81 100644--- a/apps/server/src/routes/api/login.ts+++ b/apps/server/src/routes/api/login.ts@@ -4,14 +4,13 @@* Protected session routes (loginToProtectedSession, logoutFromProtectedSession,* touchProtectedSession) are now in core and registered via buildSharedApiRoutes.*/-import { app_info as appInfo, date_utils as dateUtils, getInstanceId, options, password_encryption as passwordEncryptionService } from "@triliumnext/core";+import { app_info as appInfo, date_utils as dateUtils, getInstanceId, options } from "@triliumnext/core";import type { Request } from "express";-import recoveryCodeService from "../../services/encryption/recovery_codes";+import { verifyLoginCredentials } from "../../services/auth.js";import etapiTokenService from "../../services/etapi_tokens.js";import sql from "../../services/sql.js";import sqlInit from "../../services/sql_init.js";-import totp from "../../services/totp";import utils from "../../services/utils.js";/**@@ -133,13 +132,7 @@ async function token(req: Request) {const password = req.body.password;const submittedTotpToken = req.body.totpToken;- if (totp.isTotpEnabled()) {- if (!verifyTOTP(submittedTotpToken)) {- return [401, "Incorrect credential"];- }- }-- if (!(await passwordEncryptionService.verifyPassword(password))) {+ if (await verifyLoginCredentials(password, submittedTotpToken)) {return [401, "Incorrect credential"];}@@ -151,14 +144,6 @@ async function token(req: Request) {return { token: authToken };}-function verifyTOTP(submittedTotpToken: string) {- if (totp.validateTOTP(submittedTotpToken)) return true;-- const recoveryCodeValidates = recoveryCodeService.verifyRecoveryCode(submittedTotpToken);-- return recoveryCodeValidates;-}-export default {loginSync,tokendiff --git a/apps/server/src/routes/login.ts b/apps/server/src/routes/login.tsindex 11f5215663..4c55b2db52 100644--- a/apps/server/src/routes/login.ts+++ b/apps/server/src/routes/login.ts@@ -1,10 +1,10 @@-import { i18n, password as passwordService, password_encryption, ValidationError } from "@triliumnext/core";+import { i18n, password as passwordService, ValidationError } from "@triliumnext/core";import type { Request, Response } from 'express';import appPath from "../services/app_path.js";import assetPath, { assetUrlFragment } from "../services/asset_path.js";+import { verifyLoginCredentials } from "../services/auth.js";import openIDEncryption from '../services/encryption/open_id_encryption.js';-import recoveryCodeService from '../services/encryption/recovery_codes.js';import { getLog } from "@triliumnext/core";import openID from '../services/open_id.js';import totp from '../services/totp.js';@@ -111,15 +111,9 @@ async function login(req: Request, res: Response) {const submittedPassword = req.body.password;const submittedTotpToken = req.body.totpToken;- if (totp.isTotpEnabled()) {- if (!verifyTOTP(submittedTotpToken)) {- sendLoginError(req, res, 'totp');- return;- }- }-- if (!(await password_encryption.verifyPassword(submittedPassword))) {- sendLoginError(req, res, 'password');+ const failedFactor = await verifyLoginCredentials(submittedPassword, submittedTotpToken);+ if (failedFactor) {+ sendLoginError(req, res, failedFactor);return;}@@ -143,14 +137,6 @@ async function login(req: Request, res: Response) {});}-function verifyTOTP(submittedTotpToken: string) {- if (totp.validateTOTP(submittedTotpToken)) return true;-- const recoveryCodeValidates = recoveryCodeService.verifyRecoveryCode(submittedTotpToken);-- return recoveryCodeValidates;-}-function sendLoginError(req: Request, res: Response, errorType: 'password' | 'totp' = 'password') {// note that logged IP address is usually meaningless since the traffic should come from a reverse proxyif (totp.isTotpEnabled()) {diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.tsindex 09b0dd66ab..f2a0fac3c4 100644--- a/apps/server/src/services/auth.spec.ts+++ b/apps/server/src/services/auth.spec.ts@@ -3,10 +3,11 @@ import { Application } from "express";import supertest from "supertest";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";-import auth, { refreshAuth } from "./auth";+import auth, { refreshAuth, verifyLoginCredentials } from "./auth";import { cls } from "@triliumnext/core";import config from "./config";import { markAsInternalElectronRequest } from "./electron_request";+import recoveryCodeService from "./encryption/recovery_codes";import etapiTokens from "./etapi_tokens";import openID from "./open_id";import sqlInit from "./sql_init";@@ -417,4 +418,68 @@ describe("Auth", () => {expect(next).toHaveBeenCalled();});});++ describe("verifyLoginCredentials", () => {+ // Any string works — verifyRecoveryCode is mocked, so the actual code format is irrelevant.+ const RECOVERY_CODE = "AAAAAAAAAAAAAAAAAAAAAA==";++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("does not consume a recovery code when the password is wrong", async () => {+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(false as never);+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);+ const validateSpy = vi.spyOn(totp, "validateTOTP").mockReturnValue(false);+ const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(true);++ expect(await verifyLoginCredentials("wrong-password", RECOVERY_CODE)).toBe("password");++ // The second factor must never be evaluated when the password is wrong: verifying a+ // recovery code consumes it, so doing so here would burn a single-use code on a login+ // that ultimately fails on the password.+ expect(validateSpy).not.toHaveBeenCalled();+ expect(recoverySpy).not.toHaveBeenCalled();+ });++ it("returns null for a correct password when TOTP is disabled", async () => {+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);+ const validateSpy = vi.spyOn(totp, "validateTOTP").mockReturnValue(false);++ expect(await verifyLoginCredentials("correct", "")).toBeNull();+ // With TOTP disabled the second factor is skipped entirely.+ expect(validateSpy).not.toHaveBeenCalled();+ });++ it("returns null for a correct password with a valid TOTP token, without touching recovery codes", async () => {+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);+ vi.spyOn(totp, "validateTOTP").mockReturnValue(true);+ const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(false);++ expect(await verifyLoginCredentials("correct", "123456")).toBeNull();+ // A valid TOTP token short-circuits, so recovery codes are never inspected.+ expect(recoverySpy).not.toHaveBeenCalled();+ });++ it("consumes a recovery code only after the password is verified", async () => {+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);+ vi.spyOn(totp, "validateTOTP").mockReturnValue(false);+ const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(true);++ expect(await verifyLoginCredentials("correct", RECOVERY_CODE)).toBeNull();+ expect(recoverySpy).toHaveBeenCalledWith(RECOVERY_CODE);+ });++ it("rejects a correct password paired with an invalid second factor", async () => {+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);+ vi.spyOn(totp, "validateTOTP").mockReturnValue(false);+ vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(false);++ expect(await verifyLoginCredentials("correct", "000000")).toBe("totp");+ });+ });}, 60_000);diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.tsindex 1b316b5d09..868126e817 100644--- a/apps/server/src/services/auth.ts+++ b/apps/server/src/services/auth.ts@@ -3,6 +3,7 @@ import type { NextFunction, Request, Response } from "express";import config from "./config.js";import { isInternalElectronRequest } from "./electron_request.js";+import recoveryCodeService from "./encryption/recovery_codes.js";import etapiTokenService from "./etapi_tokens.js";import { getLog } from "@triliumnext/core";import openID from "./open_id.js";@@ -182,6 +183,38 @@ async function checkCredentials(req: Request, res: Response, next: NextFunction)}}+export type LoginFactor = "password" | "totp";++/**+ * Verifies submitted login credentials, returning the factor that failed or `null` when they are all+ * valid.+ *+ * The password is checked BEFORE the TOTP / recovery-code second factor on purpose: verifying a+ * recovery code consumes it (codes are single-use, see {@link recoveryCodeService.verifyRecoveryCode}).+ * Checking the second factor first would burn a recovery code on a login attempt that then fails on a+ * wrong password — silently wasting one of the user's limited codes. Password-first guarantees a+ * recovery code is only ever consumed once the rest of the login is known to succeed.+ */+export async function verifyLoginCredentials(password: string, totpToken: string): Promise<LoginFactor | null> {+ if (!(await passwordEncryptionService.verifyPassword(password))) {+ return "password";+ }++ if (totp.isTotpEnabled() && !verifyTOTP(totpToken)) {+ return "totp";+ }++ return null;+}++function verifyTOTP(submittedTotpToken: string) {+ if (totp.validateTOTP(submittedTotpToken)) {+ return true;+ }++ return recoveryCodeService.verifyRecoveryCode(submittedTotpToken);+}+export default {checkAuth,checkApiAuth,