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(sync): verify the second factor of a seed request inside a CLS context
Elian Dorane6ef66bfedb4
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.tsindex f8562a9416..39ee89bec3 100644--- a/apps/server/src/services/auth.spec.ts+++ b/apps/server/src/services/auth.spec.ts@@ -2,6 +2,7 @@ import { attributes, authenticateSetup, enterSetupMode, leaveSetupMode, options,import type { NextFunction, Request, Response } from "express";import { Application } from "express";import supertest from "supertest";+import { generateConfig, Totp } from "time2fa";import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import auth, { refreshAuth, verifyLoginCredentials } from "./auth";@@ -525,6 +526,36 @@ describe("Auth", () => {expect(recovery.next).toHaveBeenCalled();expect(recoverySpy).toHaveBeenLastCalledWith("recovery-code");});++ // `checkCredentials` runs as middleware, before the route handler opens a CLS context, and+ // `verifyTOTP()` records the code's time step as an option.+ it("checkCredentials accepts a real TOTP code outside a CLS context and records its time step", async () => {+ const { secret } = Totp.generateKey({ issuer: "Trilium", user: "spec" });+ cls.init(() => {+ options.setOption("mfaMethod", "totp");+ totp.setSecret(secret);+ });+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);+ vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);+ const [ code ] = Totp.generatePasscodes({ secret }, generateConfig());+ expect(code).toBeDefined();++ const res = makeRes();+ const next = vi.fn();+ await auth.checkCredentials(makeReq({+ headers: { "trilium-cred": Buffer.from("user:pw").toString("base64"), "trilium-totp": code }+ }), res as never, next);++ expect(res.statusCode).toBe(0);+ expect(next).toHaveBeenCalled();+ expect(Number(options.getOptionOrNull("totpLastUsedStep"))).toBeGreaterThan(0);++ cls.init(() => {+ totp.resetTotp();+ options.setOption("totpLastUsedStep", "");+ });+ });});describe("verifyLoginCredentials", () => {diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.tsindex 6fae4e4737..834d10622d 100644--- a/apps/server/src/services/auth.ts+++ b/apps/server/src/services/auth.ts@@ -1,4 +1,4 @@-import { attributes, isSetupAuthorized, isSetupAuthRequired, options, password as passwordService, password_encryption as passwordEncryptionService } from "@triliumnext/core";+import { attributes, cls, isSetupAuthorized, isSetupAuthRequired, options, password as passwordService, password_encryption as passwordEncryptionService } from "@triliumnext/core";import type { NextFunction, Request, Response } from "express";import config from "./config.js";@@ -275,7 +275,9 @@ async function checkCredentials(req: Request, res: Response, next: NextFunction)return;}- const failedFactor = await verifyLoginCredentials(password, totpToken);+ // Middleware runs before the route opens a CLS context, and `verifyTOTP()` and+ // `verifyRecoveryCode()` write options when they accept a code.+ const failedFactor = await cls.init(() => verifyLoginCredentials(password, totpToken));if (failedFactor === "password") {res.setHeader("Content-Type", "text/plain").status(401).send("Incorrect password");getLog().info(`WARNING: Wrong password from ${req.ip}, rejecting.`);