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
import { attributes, authenticateSetup, enterSetupMode, leaveSetupMode, options, password as passwordService, password_encryption as passwordEncryptionService, resetSetupAuth } from "@triliumnext/core";
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";
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";
import totp from "./totp";
let app: Application;
describe("Auth", () => {
beforeAll(async () => {
const buildApp = (await (import("../../src/app.js"))).default;
app = await buildApp();
});
describe("Auth", () => {
beforeAll(() => {
config.General.noAuthentication = false;
refreshAuth();
});
it("bootstrap login payload asks for TOTP when enabled", async () => {
cls.init(() => {
options.setOption("mfaMethod", "totp");
options.setOption("totpVerificationHash", "hi");
});
// The login screen is rendered client-side now; the server reports the TOTP
// requirement through the (unauthenticated) bootstrap payload.
const response = await supertest(app).get("/bootstrap").expect(200);
expect(response.body.loggedIn).toBe(false);
expect(response.body.login?.totpEnabled).toBe(true);
});
it("bootstrap login payload doesn't ask for TOTP when disabled", async () => {
cls.init(() => {
options.setOption("totpVerificationHash", "");
});
const response = await supertest(app).get("/bootstrap").expect(200);
expect(response.body.login?.totpEnabled).toBe(false);
});
});
describe("No auth", () => {
beforeAll(() => {
config.General.noAuthentication = true;
refreshAuth();
});
it("doesn't ask for authentication when disabled, even if TOTP is enabled", async () => {
cls.init(() => {
options.setOption("mfaMethod", "totp");
options.setOption("totpVerificationHash", "hi");
});
await supertest(app)
.get("/")
.expect(200);
});
it("doesn't ask for authentication when disabled, with TOTP disabled", async () => {
cls.init(() => {
options.setOption("totpVerificationHash", "");
});
await supertest(app)
.get("/")
.expect(200);
});
});
describe("middleware (direct invocation)", () => {
function makeRes() {
const res = {
statusCode: 0 as number,
headers: {} as Record<string, string>,
body: undefined as unknown,
redirectedTo: undefined as string | undefined,
setHeader(k: string, v: string) {
res.headers[k] = v;
return res;
},
status(c: number) {
res.statusCode = c;
return res;
},
json(o: unknown) {
res.body = o;
return res;
},
send(o: unknown) {
res.body = o;
return res;
},
redirect(loc: string) {
res.redirectedTo = loc;
}
};
return res;
}
function makeReq(overrides: Record<string, unknown> = {}) {
return {
method: "GET",
path: "/test",
query: {},
ip: "127.0.0.1",
sessionID: "sid",
headers: {},
session: {},
...overrides
} as never;
}
beforeAll(() => {
config.General.noAuthentication = false;
refreshAuth();
});
afterEach(() => {
vi.restoreAllMocks();
});
it("checkAuth lets the request through when the DB is not initialized", () => {
const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
const next = vi.fn();
auth.checkAuth(makeReq(), makeRes() as never, next);
expect(next).toHaveBeenCalled();
spy.mockRestore();
});
it("checkAuth lets internal electron requests through", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
const req = makeReq();
markAsInternalElectronRequest(req as object);
const next = vi.fn();
auth.checkAuth(req, makeRes() as never, next);
expect(next).toHaveBeenCalled();
});
it("checkAuth serves the SPA (next) when not logged in (no bare-domain redirect)", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
cls.init(() => options.setOption("redirectBareDomain", "false"));
const res = makeRes();
const next = vi.fn();
// The login screen is served by the SPA now, so checkAuth falls through.
auth.checkAuth(makeReq({ session: { loggedIn: false } }), res as never, next);
expect(next).toHaveBeenCalled();
expect(res.redirectedTo).toBeUndefined();
});
it("checkAuth honours redirectBareDomain: redirects to share when a shareRoot exists, else serves the SPA", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
cls.init(() => options.setOption("redirectBareDomain", "true"));
// No shareRoot configured: fall through to the SPA login screen instead of a
// 404 dead-end (#7869).
const labelSpy = vi.spyOn(attributes, "getNotesWithLabel").mockReturnValue([]);
const resLogin = makeRes();
const nextLogin = vi.fn();
auth.checkAuth(makeReq({ path: "/", session: { loggedIn: false } }), resLogin as never, nextLogin);
expect(nextLogin).toHaveBeenCalled();
expect(resLogin.statusCode).not.toBe(404);
labelSpy.mockReturnValue([{ noteId: "x" } as never]);
const resShare = makeRes();
auth.checkAuth(makeReq({ path: "/", session: { loggedIn: false } }), resShare as never, vi.fn());
expect(resShare.redirectedTo).toBe("share");
cls.init(() => options.setOption("redirectBareDomain", "false"));
});
it("checkAuth limits the bare-domain redirect to bare root requests (#10552)", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
vi.spyOn(attributes, "getNotesWithLabel").mockReturnValue([{ noteId: "x" } as never]);
cls.init(() => options.setOption("redirectBareDomain", "true"));
// An explicit login navigation (GET /login redirects to the root with the
// `?login` marker) must reach the SPA login screen, not the share page.
const resLogin = makeRes();
const nextLogin = vi.fn();
auth.checkAuth(makeReq({ path: "/", query: { login: "" }, session: { loggedIn: false } }), resLogin as never, nextLogin);
expect(nextLogin).toHaveBeenCalled();
expect(resLogin.redirectedTo).toBeUndefined();
// SPA sub-requests such as /bootstrap must fall through too, or the login
// screen can never render its `loggedIn: false` payload.
const resBootstrap = makeRes();
const nextBootstrap = vi.fn();
auth.checkAuth(makeReq({ path: "/bootstrap", session: { loggedIn: false } }), resBootstrap as never, nextBootstrap);
expect(nextBootstrap).toHaveBeenCalled();
expect(resBootstrap.redirectedTo).toBeUndefined();
cls.init(() => options.setOption("redirectBareDomain", "false"));
});
it("checkAuth destroys the session and redirects when auth state changed", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
const destroy = vi.fn((cb: (err?: Error) => void) => cb());
const res = makeRes();
auth.checkAuth(
makeReq({
session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: false }, destroy }
}),
res as never,
vi.fn()
);
expect(destroy).toHaveBeenCalled();
expect(res.redirectedTo).toBe("login");
// also exercise the destroy-error logging branch
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const destroyErr = vi.fn((cb: (err?: Error) => void) => cb(new Error("boom")));
auth.checkAuth(
makeReq({
session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: false }, destroy: destroyErr }
}),
makeRes() as never,
vi.fn()
);
expect(errSpy).toHaveBeenCalled();
errSpy.mockRestore();
});
it("checkAuth passes through when SSO is enabled and the OIDC session is authenticated", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(true);
const nextOk = vi.fn();
auth.checkAuth(
makeReq({
session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: true } },
oidc: { isAuthenticated: () => true }
}),
makeRes() as never,
nextOk
);
expect(nextOk).toHaveBeenCalled();
// The unauthenticated / lapsed-OIDC case is covered by the regression test below.
});
it("checkAuth does not bounce a stale SSO session to /login (regression: infinite /↔/login loop)", () => {
// Repro of the redirect loop shipped in v0.104.0. When OIDC/SSO is enabled and the
// Trilium session still carries loggedIn:true but the OIDC appSession has lapsed
// (oidc.isAuthenticated() === false), checkAuth 302s to "login" — but loginPage
// (routes/login.ts) 302s straight back to "." (the SPA root), so the browser
// ping-pongs /↔/login until it aborts with ERR_TOO_MANY_REDIRECTS.
//
// This desync is reachable by any active OAuth user, not just a stale-cookie dev
// artifact: the OIDC appSession has a hard absolute cap (express-openid-connect
// default 7d) that activity can't extend, while trilium.sid is rolling with a much
// longer window (default cookieMaxAge 21d). Once the OIDC cap lapses on a still-live
// trilium session, every navigation loops.
//
// Correct behaviour: treat the stale session as logged out and fall through to serve
// the SPA, which renders the login screen from the bootstrap loggedIn:false payload —
// no redirect, so no loop.
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(true);
const res = makeRes();
const next = vi.fn();
// save() flushes the loggedIn:false flip before handoff; invoke its callback so next() runs.
const save = vi.fn((cb: (err?: unknown) => void) => cb());
const session = { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: true }, save };
auth.checkAuth(
makeReq({ session, oidc: { isAuthenticated: () => false } }),
res as never,
next
);
// The loop half we must break: never 302 to the login route (which comes right back).
expect(res.redirectedTo).not.toBe("login");
// Instead fall through so the SPA renders the login screen in place.
expect(next).toHaveBeenCalled();
// And the stale flag is cleared (and persisted) so subsequent requests take the logged-out path.
expect(session.loggedIn).toBe(false);
expect(save).toHaveBeenCalled();
});
it("checkAuth falls through to next on the normal logged-in path", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
const next = vi.fn();
auth.checkAuth(
makeReq({ session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: false } } }),
makeRes() as never,
next
);
expect(next).toHaveBeenCalled();
});
it("checkApiAuthOrElectron rejects unauthenticated and allows internal electron", () => {
const res = makeRes();
auth.checkApiAuthOrElectron(makeReq({ session: { loggedIn: false } }), res as never, vi.fn());
expect(res.statusCode).toBe(401);
const req = makeReq({ session: { loggedIn: false } });
markAsInternalElectronRequest(req as object);
const next = vi.fn();
auth.checkApiAuthOrElectron(req, makeRes() as never, next);
expect(next).toHaveBeenCalled();
});
it("checkApiAuthOrElectron passes through when DB not initialized", () => {
const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
const next = vi.fn();
auth.checkApiAuthOrElectron(makeReq(), makeRes() as never, next);
expect(next).toHaveBeenCalled();
spy.mockRestore();
});
it("checkApiAuth handles electron, unauthenticated, and authenticated paths", () => {
// DB not initialized -> next
const dbSpy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
const next1 = vi.fn();
auth.checkApiAuth(makeReq(), makeRes() as never, next1);
expect(next1).toHaveBeenCalled();
dbSpy.mockRestore();
// internal electron -> next
const electronReq = makeReq();
markAsInternalElectronRequest(electronReq as object);
const next2 = vi.fn();
auth.checkApiAuth(electronReq, makeRes() as never, next2);
expect(next2).toHaveBeenCalled();
// not logged in -> reject
const res = makeRes();
auth.checkApiAuth(makeReq({ session: { loggedIn: false } }), res as never, vi.fn());
expect(res.statusCode).toBe(401);
// logged in -> next
const next3 = vi.fn();
auth.checkApiAuth(makeReq({ session: { loggedIn: true } }), makeRes() as never, next3);
expect(next3).toHaveBeenCalled();
});
it("checkAppInitialized always calls next", () => {
const next = vi.fn();
auth.checkAppInitialized(makeReq(), makeRes() as never, next);
expect(next).toHaveBeenCalled();
});
it("checkPasswordSet / checkPasswordNotSet branch on whether a password is set", () => {
// password set
const setSpy = vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
const nextSet = vi.fn();
auth.checkPasswordSet(makeReq(), makeRes() as never, nextSet);
expect(nextSet).toHaveBeenCalled();
const resNotSet = makeRes();
auth.checkPasswordNotSet(makeReq(), resNotSet as never, vi.fn());
expect(resNotSet.redirectedTo).toBe("login");
setSpy.mockRestore();
// password not set
const unsetSpy = vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(false);
const resSet = makeRes();
auth.checkPasswordSet(makeReq(), resSet as never, vi.fn());
// The set-password screen is now served by the SPA at the root.
expect(resSet.redirectedTo).toBe(".");
const nextNotSet = vi.fn();
auth.checkPasswordNotSet(makeReq(), makeRes() as never, nextNotSet);
expect(nextNotSet).toHaveBeenCalled();
unsetSpy.mockRestore();
});
it("checkAppNotInitialized rejects when initialized, else calls next", () => {
const res = makeRes();
auth.checkAppNotInitialized(makeReq(), res as never, vi.fn());
expect(res.statusCode).toBe(401);
const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
const next = vi.fn();
auth.checkAppNotInitialized(makeReq(), makeRes() as never, next);
expect(next).toHaveBeenCalled();
spy.mockRestore();
});
it("checkEtapiToken accepts a valid token header and rejects an invalid one", () => {
const { authToken } = cls.init(() => etapiTokens.createToken("auth-spec-token"));
const next = vi.fn();
auth.checkEtapiToken(makeReq({ headers: { authorization: authToken } }), makeRes() as never, next);
expect(next).toHaveBeenCalled();
const res = makeRes();
auth.checkEtapiToken(makeReq({ headers: { authorization: "bogus_token" } }), res as never, vi.fn());
expect(res.statusCode).toBe(401);
});
it("checkCredentials walks DB/password/header/verification branches", async () => {
// DB not initialized -> 400
const dbSpy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
const res1 = makeRes();
await auth.checkCredentials(makeReq(), res1 as never, vi.fn());
expect(res1.statusCode).toBe(400);
dbSpy.mockRestore();
// password not set -> 400
const unsetSpy = vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(false);
const res2 = makeRes();
await auth.checkCredentials(makeReq(), res2 as never, vi.fn());
expect(res2.statusCode).toBe(400);
unsetSpy.mockRestore();
// password set from here on
vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
// non-string trilium-cred header -> 400
const res3 = makeRes();
await auth.checkCredentials(makeReq({ headers: { "trilium-cred": ["a", "b"] } }), res3 as never, vi.fn());
expect(res3.statusCode).toBe(400);
// wrong password -> 401. verifyPassword is async, so it's mocked to resolve a
// boolean and the call is awaited.
const verifySpy = vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(false as never);
const cred = Buffer.from("user:wrongpass").toString("base64");
const res4 = makeRes();
await auth.checkCredentials(makeReq({ headers: { "trilium-cred": cred } }), res4 as never, vi.fn());
expect(res4.statusCode).toBe(401);
// The username before the colon is stripped; only the password is verified.
expect(verifySpy).toHaveBeenLastCalledWith("wrongpass");
// correct password (no colon in decoded cred path also exercised) -> next
verifySpy.mockResolvedValue(true as never);
const credNoColon = Buffer.from("justpassword").toString("base64");
const next = vi.fn();
await auth.checkCredentials(makeReq({ headers: { "trilium-cred": credNoColon } }), makeRes() as never, next);
expect(next).toHaveBeenCalled();
// No colon → the whole cred is treated as username and the password is "".
expect(verifySpy).toHaveBeenLastCalledWith("");
// missing trilium-cred header -> falls back to "" -> next (with verify mocked true)
const nextNoHeader = vi.fn();
await auth.checkCredentials(makeReq({ headers: {} }), makeRes() as never, nextNoHeader);
expect(nextNoHeader).toHaveBeenCalled();
});
// verifyPassword is async, so its resolved value — not the Promise object — must drive
// the result. These two cases mock it the way it really behaves (resolving a boolean)
// and await the call, asserting the verification outcome actually gates the response;
// a synchronous mock would not exercise that.
it("checkCredentials rejects a password that fails async verification", async () => {
vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);
vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(false as never);
const cred = Buffer.from("user:wrongpass").toString("base64");
const res = makeRes();
const next = vi.fn();
await auth.checkCredentials(makeReq({ headers: { "trilium-cred": cred } }), res as never, next);
expect(next).not.toHaveBeenCalled();
expect(res.statusCode).toBe(401);
});
it("checkCredentials calls next when async verification succeeds", async () => {
vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);
vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
const cred = Buffer.from("user:correctpass").toString("base64");
const next = vi.fn();
await auth.checkCredentials(makeReq({ headers: { "trilium-cred": cred } }), makeRes() as never, next);
expect(next).toHaveBeenCalled();
});
it("checkCredentials requires a valid second factor when TOTP is enabled", async () => {
vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);
vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
const verifyPasswordSpy = vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
vi.spyOn(totp, "verifyTOTP").mockImplementation((token) => token === "123456");
const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(false);
const cred = Buffer.from("user:correctpass").toString("base64");
async function call(headers: Record<string, unknown>) {
const res = makeRes();
const next = vi.fn();
await auth.checkCredentials(makeReq({ headers: { "trilium-cred": cred, ...headers } }), res as never, next);
return { res, next };
}
// Missing token -> 401 before the password is checked, so the answer reveals nothing about it.
const missing = await call({});
expect(missing.next).not.toHaveBeenCalled();
expect(missing.res.statusCode).toBe(401);
expect(missing.res.body).toBe("TOTP token is required");
expect(verifyPasswordSpy).not.toHaveBeenCalled();
const wrong = await call({ "trilium-totp": "000000" });
expect(wrong.next).not.toHaveBeenCalled();
expect(wrong.res.statusCode).toBe(401);
expect(wrong.res.body).toBe("Incorrect TOTP token");
// A wrong password is reported as such and never reaches the recovery codes.
verifyPasswordSpy.mockResolvedValueOnce(false as never);
recoverySpy.mockClear();
const wrongPassword = await call({ "trilium-totp": "000000" });
expect(wrongPassword.res.statusCode).toBe(401);
expect(wrongPassword.res.body).toBe("Incorrect password");
expect(recoverySpy).not.toHaveBeenCalled();
const valid = await call({ "trilium-totp": "123456" });
expect(valid.next).toHaveBeenCalled();
recoverySpy.mockReturnValue(true);
const recovery = await call({ "trilium-totp": "recovery-code" });
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", () => {
// 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, "verifyTOTP").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, "verifyTOTP").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, "verifyTOTP").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, "verifyTOTP").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, "verifyTOTP").mockReturnValue(false);
vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(false);
expect(await verifyLoginCredentials("correct", "000000")).toBe("totp");
});
});
}, 60_000);
/**
* The gate that stands in for everything else while an instance is in setup mode with a knowledge
* base still behind it.
*
* Driven directly rather than over HTTP: setup mode makes the whole application report itself
* uninitialized, which is not a state the shared test fixture can be put into and taken back out of
* around a supertest call.
*/
describe("the setup wizard's gate", () => {
type GateOpts = {
token?: string;
internalElectron?: boolean;
/** Which guard to drive; `checkSetupAuth` by default. */
middleware?: "checkSetupAuth" | "checkApiAuth" | "checkApiAuthOrElectron";
};
/** A request carrying the token, or nothing, plus what the middleware did with it. */
function callGate({ token, internalElectron = false, middleware = "checkSetupAuth" }: GateOpts = {}) {
const req = {
headers: token ? { "trilium-setup-auth": token } : {},
method: "POST",
path: "/api/database/backup-database",
session: {}
} as unknown as Request;
if (internalElectron) {
markAsInternalElectronRequest(req);
}
const outcome = { passed: false, status: 0 };
const res = {
setHeader: () => res,
status: (code: number) => {
outcome.status = code;
return res;
},
send: () => res
} as unknown as Response & { setHeader: () => unknown };
const next: NextFunction = () => {
outcome.passed = true;
};
auth[middleware](req, res as unknown as Response, next);
return outcome;
}
beforeAll(() => {
config.General.noAuthentication = false;
refreshAuth();
});
beforeEach(() => {
resetSetupAuth();
// An instance the app sent back to setup, with the fixture's knowledge base behind it.
enterSetupMode({ lang: "en" });
});
afterEach(() => {
leaveSetupMode();
resetSetupAuth();
});
it("refuses a request that has not unlocked the knowledge base", () => {
// Nothing else in this file covers it: every other check here gives way while the database
// reports itself uninitialized, which is exactly what setup mode makes it report.
expect(callGate()).toEqual({ passed: false, status: 401 });
expect(callGate({ token: "not a token" })).toEqual({ passed: false, status: 401 });
});
it("lets through a request carrying the token the password bought", async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
const token = await authenticateSetup("whatever the fixture's is");
expect(callGate({ token: token ?? "" })).toMatchObject({ passed: true });
vi.restoreAllMocks();
});
it("lets the desktop's own renderer through, since nobody else can be it", () => {
expect(callGate({ internalElectron: true })).toMatchObject({ passed: true });
});
it("asks nothing of an instance that has already said it trusts whoever can reach it", () => {
config.General.noAuthentication = true;
refreshAuth();
try {
expect(callGate()).toMatchObject({ passed: true });
} finally {
config.General.noAuthentication = false;
refreshAuth();
}
});
it("stands down once the knowledge base is gone, which is where a first run begins", () => {
leaveSetupMode();
expect(callGate()).toMatchObject({ passed: true });
});
describe("and the rest of the API, which stands down for the same reason", () => {
// The wizard's own routes are not the only ones reachable while it is open. Every ordinary
// API guard gives way on an instance that reports itself uninitialized — which setup mode
// makes it report — and the database is attached the whole time, so anything reaching it
// through SQL rather than through becca works. Backing the knowledge base up and then
// downloading that backup is two such requests, and would have been the whole of it.
for (const middleware of [ "checkApiAuth", "checkApiAuthOrElectron" ] as const) {
it(`refuses an unauthenticated request through ${middleware} while the wizard is locked`, () => {
expect(callGate({ middleware })).toEqual({ passed: false, status: 401 });
});
it(`lets ${middleware} through once the wizard has been unlocked`, async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
const token = await authenticateSetup("whatever the fixture's is");
// The client sends the token on every request once it holds one, so the rest of the
// wizard's own needs — keyboard actions, options, network addresses — keep working.
expect(callGate({ middleware, token: token ?? "" })).toMatchObject({ passed: true });
vi.restoreAllMocks();
});
it(`lets ${middleware} through on a first run, which has nothing to protect`, () => {
// No marker, so nothing behind the wizard, and no database open either: the state
// the bypass was written for, and the one it has to go on allowing.
leaveSetupMode();
vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
expect(callGate({ middleware })).toMatchObject({ passed: true });
vi.restoreAllMocks();
});
}
});
});