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
start again: add support for TOTP with recovery codes to authenticate in Start Again for the server version
Adorian Doranad6ff01f92f9
diff --git a/apps/client/src/login.spec.tsx b/apps/client/src/login.spec.tsxindex fe7323491a..62012bc18d 100644--- a/apps/client/src/login.spec.tsx+++ b/apps/client/src/login.spec.tsx@@ -19,7 +19,13 @@ function renderInto(vnode: preact.ComponentChild) {return container;}-const flush = () => new Promise((resolve) => setTimeout(resolve, 0));+/**+ * Long enough for the error banner to be on screen, not just decided on.+ *+ * `SetupPage` reveals it from an effect, and Preact runs effects on a frame rather than a microtask,+ * so a bare `setTimeout(0)` lands before the banner has rendered — sometimes.+ */+const flush = () => new Promise((resolve) => setTimeout(resolve, 25));function mockFetch(resp: { ok?: boolean; status?: number; json?: () => Promise<unknown> } | "reject") {const fn = resp === "reject"@@ -37,13 +43,15 @@ afterEach(() => {describe("PasswordLogin", () => {function setup(totpEnabled = false) {- const onError = vi.fn();- const c = renderInto(<PasswordLogin illustration={null} totpEnabled={totpEnabled} error={null} errorId={0} onError={onError} />);+ const c = renderInto(<PasswordLogin illustration={null} totpEnabled={totpEnabled} initialError={null} />);const form = c.querySelector("form");const password = c.querySelector('input[name="password"]') as HTMLInputElement;const totp = c.querySelector('input[name="totpToken"]') as HTMLInputElement | null;const submit = () => form?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));- return { onError, password, totp, submit };+ // Asserted on the banner the user actually reads rather than on a callback: the form owns+ // reporting its own failures now, so that is where the outcome shows up.+ const shownError = () => c.querySelector(".page-error")?.textContent ?? "";+ return { shownError, password, totp, submit };}it("posts the password read from the DOM (autofill-safe) and navigates on success", async () => {@@ -76,54 +84,54 @@ describe("PasswordLogin", () => {it("reports an incorrect password on 401 {factor:'password'}", async () => {mockFetch({ ok: false, status: 401, json: async () => ({ factor: "password" }) });- const { onError, password, submit } = setup();+ const { shownError, password, submit } = setup();password.value = "wrong";submit();await flush();- expect(onError).toHaveBeenCalledWith("login.incorrect-password");+ expect(shownError()).toContain("login.incorrect-password");});it("reports a bad TOTP for a 6-digit second factor", async () => {mockFetch({ ok: false, status: 401, json: async () => ({ factor: "totp" }) });- const { onError, password, totp, submit } = setup(true);+ const { shownError, password, totp, submit } = setup(true);password.value = "secret";if (totp) totp.value = "123456";submit();await flush();- expect(onError).toHaveBeenCalledWith("login.incorrect-totp");+ expect(shownError()).toContain("login.incorrect-totp");});it("reports a bad recovery code when the second factor has recovery-code shape", async () => {mockFetch({ ok: false, status: 401, json: async () => ({ factor: "totp" }) });- const { onError, password, totp, submit } = setup(true);+ const { shownError, password, totp, submit } = setup(true);password.value = "secret";if (totp) totp.value = "abcdefghijklmnopqrstuv=="; // 22 chars + "=="submit();await flush();- expect(onError).toHaveBeenCalledWith("login.incorrect-recovery-code");+ expect(shownError()).toContain("login.incorrect-recovery-code");});it("reports rate limiting on 429 rather than a credential error", async () => {mockFetch({ ok: false, status: 429 });- const { onError, password, submit } = setup();+ const { shownError, password, submit } = setup();password.value = "secret";submit();await flush();- expect(onError).toHaveBeenCalledWith("login.too-many-attempts");+ expect(shownError()).toContain("login.too-many-attempts");});it("reports a connection error when fetch rejects (network failure)", async () => {mockFetch("reject");- const { onError, password, submit } = setup();+ const { shownError, password, submit } = setup();password.value = "secret";submit();await flush();- expect(onError).toHaveBeenCalledWith("login.connection-error");+ expect(shownError()).toContain("login.connection-error");});it("disables the submit button while a request is in flight", async () => {globalThis.fetch = vi.fn().mockReturnValue(new Promise(() => {})) as typeof fetch; // never resolves- const c = renderInto(<PasswordLogin illustration={null} totpEnabled={false} error={null} errorId={0} onError={vi.fn()} />);+ const c = renderInto(<PasswordLogin illustration={null} totpEnabled={false} initialError={null} />);const button = c.querySelector('button[type="submit"]') as HTMLButtonElement;const password = c.querySelector('input[name="password"]') as HTMLInputElement;expect(button.disabled).toBe(false);diff --git a/apps/client/src/login.tsx b/apps/client/src/login.tsxindex 4340918d37..342342ddfe 100644--- a/apps/client/src/login.tsx+++ b/apps/client/src/login.tsx@@ -3,16 +3,12 @@ import "./login.css";import { LOCALE_IDS } from "@triliumnext/commons";import { render } from "preact";-import { useRef, useState } from "preact/hooks";import logo from "./assets/icon-color.svg?url";import { initLocale, t } from "./services/i18n";import Button from "./widgets/react/Button";-import { Card, CardSection } from "./widgets/react/Card";-import FormTextBox from "./widgets/react/FormTextBox";-import PasswordField from "./widgets/react/PasswordField";+import CredentialsForm, { type Credentials } from "./widgets/react/CredentialsForm";import SetupPage from "./widgets/react/SetupPage";-import OptionsRow, { OptionsRowWithToggle } from "./widgets/type_widgets/options/components/OptionsRow";async function main() {await initLocale((window.glob.currentLocale?.id ?? "en") as LOCALE_IDS);@@ -29,19 +25,14 @@ async function main() {export function App() {const config = window.glob.login;const illustration = <img src={logo} alt="" className="illustration-logo" />;-- const [ error, setError ] = useState<string | null>(initialSsoError(config));- const [ errorId, setErrorId ] = useState(0);-- function raiseError(message: string) {- setError(message);- setErrorId((id) => id + 1);- }+ // Nothing on this page can raise a second one: the SSO branch navigates away rather than+ // submitting, and the password form below reports its own.+ const error = initialSsoError(config);if (config?.ssoEnabled) {return (<div class="setup-container login-container oidc">- <SetupPage className="login" title={t("login.heading")} illustration={illustration} error={error} errorId={errorId}>+ <SetupPage className="login" title={t("login.heading")} illustration={illustration} error={error} errorId={0}>{/* A <button>, not an <a>, on purpose: link.ts installs a global anchor-clickhandler that preventDefaults every link and only navigates note/http links,so an <a> to a plain server route gets swallowed. A button sidesteps it and@@ -68,41 +59,22 @@ export function App() {<PasswordLoginillustration={illustration}totpEnabled={config?.totpEnabled ?? false}- error={error}- errorId={errorId}- onError={raiseError}+ initialError={error}/></div>);}-export function PasswordLogin({ illustration, totpEnabled, error, errorId, onError }: {+export function PasswordLogin({ illustration, totpEnabled, initialError }: {illustration: preact.ComponentChildren;totpEnabled: boolean;- error: string | null;- errorId: number;- onError: (message: string) => void;+ initialError: string | null;}) {- // Read the password / TOTP straight from the DOM at submit time instead of mirroring- // them into controlled state. A controlled value of "" overwrites (and loses) browser-- // autofilled credentials, so the first click would submit an empty password — the- // "incorrect password, press again" bug. These fields need no live validation, so they- // stay uncontrolled. (rememberMe is a toggle the user actually clicks, so it's controlled.)- const passwordRef = useRef<HTMLInputElement>(null);- const totpRef = useRef<HTMLInputElement>(null);- const [ rememberMe, setRememberMe ] = useState(false);- const [ submitting, setSubmitting ] = useState(false);-- async function handleSubmit(e: Event) {- e.preventDefault();- if (submitting) {- return;- }- setSubmitting(true);+ async function submit({ password, totpToken, rememberMe }: Credentials) {try {- const body = new URLSearchParams({ password: passwordRef.current?.value ?? "" });+ const body = new URLSearchParams({ password });if (totpEnabled) {- body.set("totpToken", totpRef.current?.value ?? "");+ body.set("totpToken", totpToken);}if (rememberMe) {body.set("rememberMe", "1");@@ -117,13 +89,12 @@ export function PasswordLogin({ illustration, totpEnabled, error, errorId, onErrif (resp.ok) {// Session established — navigate to the app.window.location.assign(".");- return;+ return null;}if (resp.status === 429) {// Rate limiter kicked in (too many attempts) — not a credential failure.- onError(t("login.too-many-attempts"));- return;+ return t("login.too-many-attempts");}const factor = resp.status === 401 ? (await resp.json().catch(() => ({}))).factor : undefined;@@ -132,57 +103,36 @@ export function PasswordLogin({ illustration, totpEnabled, error, errorId, onErr// so tailor the message to what was actually entered. This keys off the user's// own input shape, never server state, so it can't reveal whether a given code// was genuinely valid or already used.- const looksLikeRecoveryCode = /^.{22}==$/.test(totpRef.current?.value ?? "");- onError(t(looksLikeRecoveryCode ? "login.incorrect-recovery-code" : "login.incorrect-totp"));- } else {- onError(t("login.incorrect-password"));+ return t(looksLikeRecoveryCode(totpToken) ? "login.incorrect-recovery-code" : "login.incorrect-totp");}++ return t("login.incorrect-password");} catch {// fetch only rejects on network-level failures (server unreachable, DNS, etc.) —// not on HTTP error statuses — so this is a connection problem, not bad credentials.- onError(t("login.connection-error"));- } finally {- setSubmitting(false);+ return t("login.connection-error");}}return (- <form onSubmit={(e) => void handleSubmit(e)}>- <SetupPage- className="login"- title={t("login.heading")}- illustration={illustration}- error={error}- errorId={errorId}- footer={<Button text={t("login.button")} kind="primary" disabled={submitting} />}- >- <Card>- <CardSection>- <PasswordField inputRef={passwordRef} />-- {totpEnabled && (- <OptionsRow name="totpToken" label={t("login.totp-token")} stacked>- <FormTextBox- inputRef={totpRef}- name="totpToken"- autocomplete="one-time-code" required- />- </OptionsRow>- )}-- <OptionsRowWithToggle- name="rememberMe"- label={t("login.remember-me")}- currentValue={rememberMe}- onChange={setRememberMe}- />- </CardSection>- </Card>- </SetupPage>- </form>+ <CredentialsForm+ className="login"+ title={t("login.heading")}+ illustration={illustration}+ totpEnabled={totpEnabled}+ rememberMeEnabled+ submitLabel={t("login.button")}+ initialError={initialError}+ onSubmit={submit}+ />);}+/** Whether what was typed into the second-factor field is shaped like a recovery code. */+export function looksLikeRecoveryCode(answer: string): boolean {+ return /^.{22}==$/.test(answer);+}+function initialSsoError(config: typeof window.glob.login): string | null {// `ssoError` is the outcome of a round-trip that actually reached the provider, so it is the more// specific message and wins over the generic connection failure.diff --git a/apps/client/src/setup_unlock.spec.tsx b/apps/client/src/setup_unlock.spec.tsxindex cb1c92dcb4..85b0b0ad30 100644--- a/apps/client/src/setup_unlock.spec.tsx+++ b/apps/client/src/setup_unlock.spec.tsx@@ -44,11 +44,13 @@ beforeEach(() => {onUnlocked.mockReset();setSetupAuthToken.mockReset();serverMock.post.mockReset().mockResolvedValue({ authenticated: true, token: "a-token" });+ window.glob.setupSecondFactorRequired = undefined;});afterEach(() => {render(null, container);container.remove();+ window.glob.setupSecondFactorRequired = undefined;vi.useRealTimers();});@@ -76,7 +78,7 @@ describe("unlocking a wizard that is standing over a knowledge base", () => {submit();await settle();- expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "hunter2" });+ expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "hunter2", totpToken: "" });expect(setSetupAuthToken).toHaveBeenCalledWith("a-token");expect(onUnlocked).toHaveBeenCalled();});@@ -89,7 +91,7 @@ describe("unlocking a wizard that is standing over a knowledge base", () => {submit();await settle();- expect(container.querySelector(".page-error")?.textContent).toContain("login.incorrect-password");+ expect(container.querySelector(".page-error")?.textContent).toContain("setup.unlock-refused");expect(setSetupAuthToken).not.toHaveBeenCalled();expect(onUnlocked).not.toHaveBeenCalled();expect(password()).not.toBeNull();@@ -142,6 +144,44 @@ describe("unlocking a wizard that is standing over a knowledge base", () => {expect(onUnlocked).toHaveBeenCalled();});+ describe("where the instance guards itself with a second factor as well", () => {+ beforeEach(() => {+ window.glob.setupSecondFactorRequired = true;+ });++ it("asks for it beside the password, as the login screen does", async () => {+ renderScreen();+ await settle();++ const totp = container.querySelector<HTMLInputElement>("input[name=totpToken]");+ expect(totp).not.toBeNull();+ // The same field the login screen offers, so an authenticator fills it the same way.+ expect(totp?.getAttribute("autocomplete")).toBe("one-time-code");+ });++ it("sends what was typed into it, whether a passcode or a recovery code", async () => {+ renderScreen();+ await settle();++ const totp = container.querySelector<HTMLInputElement>("input[name=totpToken]");+ if (totp) {+ totp.value = "123456";+ }+ submit();+ await settle();++ expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "", totpToken: "123456" });+ });++ it("is not asked for where the instance has none", async () => {+ window.glob.setupSecondFactorRequired = undefined;+ renderScreen();+ await settle();++ expect(container.querySelector("input[name=totpToken]")).toBeNull();+ });+ });+it("reads the password off the field at submit time, not from state", async () => {// A controlled value of "" overwrites what the browser autofilled, so the first press would// submit an empty password — the "incorrect password, press again" bug the login screen hit.@@ -155,6 +195,6 @@ describe("unlocking a wizard that is standing over a knowledge base", () => {submit();await settle();- expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "filled-in-by-the-browser" });+ expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "filled-in-by-the-browser", totpToken: "" });});});diff --git a/apps/client/src/setup_unlock.tsx b/apps/client/src/setup_unlock.tsxindex a228290e4a..dc897fa7fd 100644--- a/apps/client/src/setup_unlock.tsx+++ b/apps/client/src/setup_unlock.tsx@@ -1,27 +1,22 @@import "./setup_unlock.css";-import { useRef, useState } from "preact/hooks";-import logo from "./assets/icon-color.svg?url";import { t } from "./services/i18n";import server from "./services/server";import { setSetupAuthToken } from "./services/setup_auth";-import Button from "./widgets/react/Button";-import { Card, CardSection } from "./widgets/react/Card";-import PasswordField from "./widgets/react/PasswordField";-import SetupPage from "./widgets/react/SetupPage";+import CredentialsForm, { type Credentials } from "./widgets/react/CredentialsForm";/**- * The password of the knowledge base the wizard is standing over.+ * The credentials of the knowledge base the wizard is standing over.** Ordinarily setup is the one part of Trilium nobody has to log into, and rightly so: it runs where* there is no database and therefore nobody to be. An instance the app sent back here is the other* case, and on a server it is served to whoever can reach the port, with a whole knowledge base one* button away from being replaced. So this comes first, before the wizard will say or do anything.*- * Deliberately the login screen over again, down to the wording: the same logo, the same field, the- * same button. The user is being asked the one question they already know the answer to, and saying- * anything more about why would only invite them to read it as a different question.+ * It is the login screen over again, down to the wording and the second factor, because the user is+ * being asked the one question they already know the answer to. Saying anything more about why would+ * only invite them to read it as a different question.** Asked for only where it can be answered and where it is worth asking: a first run has no password* to check against, and the desktop's own window is not reachable by anyone the desktop is not.@@ -31,59 +26,37 @@ import SetupPage from "./widgets/react/SetupPage";* @module*/export default function SetupUnlock({ onUnlocked }: { onUnlocked: () => void }) {- const passwordRef = useRef<HTMLInputElement>(null);- const [ error, setError ] = useState<string | null>(null);- const [ errorId, setErrorId ] = useState(0);- const [ submitting, setSubmitting ] = useState(false);-- function raiseError(message: string) {- setError(message);- setErrorId((id) => id + 1);- }-- async function handleSubmit(e: Event) {- e.preventDefault();- if (submitting) {- return;- }-- setSubmitting(true);+ async function submit({ password, totpToken }: Credentials) {try {const { authenticated, token } = await server.post<{ authenticated: boolean; token?: string }>(- "setup/auth", { password: passwordRef.current?.value ?? "" });+ "setup/auth", { password, totpToken });if (!authenticated || !token) {- raiseError(t("login.incorrect-password"));- return;+ // Which of the two was wrong is not said, because the server does not say: both are+ // asked for together and a failure in either is one refusal.+ return t("setup.unlock-refused");}setSetupAuthToken(token);onUnlocked();++ return null;} catch {- // A wrong password is answered, not thrown, so anything landing here is the connection- // or the rate limiter the attempts are counted by.- raiseError(t("login.connection-error"));- } finally {- setSubmitting(false);+ // A wrong answer is answered, not thrown, so anything landing here is the connection or+ // the rate limiter the attempts are counted by.+ return t("login.connection-error");}}return (- <form className="setup-unlock-form" onSubmit={(e) => void handleSubmit(e)}>- <SetupPage- className="setup-unlock"- title={t("login.heading")}- illustration={<img src={logo} alt="" className="illustration-logo" />}- error={error}- errorId={errorId}- footer={<Button text={t("login.button")} kind="primary" disabled={submitting} />}- >- <Card>- <CardSection>- <PasswordField inputRef={passwordRef} />- </CardSection>- </Card>- </SetupPage>- </form>+ <CredentialsForm+ className="setup-unlock"+ formClassName="setup-unlock-form"+ title={t("login.heading")}+ illustration={<img src={logo} alt="" className="illustration-logo" />}+ totpEnabled={window.glob.setupSecondFactorRequired === true}+ submitLabel={t("login.button")}+ onSubmit={submit}+ />);}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex acae9f4f53..14efdf6b7a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3738,6 +3738,7 @@"backup-download-failed": "The download did not finish.","backup-finish": "Finish","existing-data-erase-confirm": "Your existing knowledge base will now be permanently deleted, so that this device can receive one from your desktop app. Make sure you have a backup somewhere safe. Continue?",+ "unlock-refused": "Those details were not accepted. Please try again.","keep-existing": "Return to the app","keep-existing-description": "Keep using your existing knowledge base and go back to the app.","existing-data-keep-failed": "The existing knowledge base could not be reopened.",diff --git a/apps/client/src/widgets/react/CredentialsForm.tsx b/apps/client/src/widgets/react/CredentialsForm.tsxnew file mode 100644index 0000000000..a32ece5efb--- /dev/null+++ b/apps/client/src/widgets/react/CredentialsForm.tsx@@ -0,0 +1,140 @@+import type { ComponentChildren } from "preact";+import { useRef, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import Button from "./Button";+import { Card, CardSection } from "./Card";+import FormTextBox from "./FormTextBox";+import SetupPage from "./SetupPage";+import OptionsRow, { OptionsRowWithToggle } from "../type_widgets/options/components/OptionsRow";++/** What the user answered, for the caller to do whatever it does with. */+export interface Credentials {+ password: string;+ /** Empty where no second factor was asked for. */+ totpToken: string;+ /** Always `false` where the form does not offer it. */+ rememberMe: boolean;+}++/**+ * Asking for the instance's own credentials, as a whole page.+ *+ * Two screens ask: the login screen, and the setup wizard standing over a knowledge base it has to+ * prove ownership of before it will touch it. To a user those are the same question, so they are the+ * same form — the same fields, in the same order, reporting failures the same way. What differs is+ * only what happens with the answer, which is what {@link CredentialsFormProps.onSubmit} is for.+ *+ * The fields are uncontrolled and read from their refs at submit time. A controlled value of `""`+ * overwrites what the browser autofilled, so the first press would submit an empty password: the+ * "incorrect password, press again" bug. Neither screen needs live validation. `rememberMe` is a+ * toggle the user actually clicks, so that one is controlled.+ *+ * @module+ */+export interface CredentialsFormProps {+ title: string;+ illustration?: ComponentChildren;+ /** Asks for a second factor beside the password. */+ totpEnabled?: boolean;+ /** Offers to be remembered past this session. Login only; the wizard holds nothing that long. */+ rememberMeEnabled?: boolean;+ submitLabel: string;+ className?: string;+ /** On the form itself, for the page layout each caller's own stylesheet gives it. */+ formClassName?: string;+ /**+ * Something that went wrong before the form was ever shown, such as an SSO round-trip that came+ * back refused. Anything the form itself provokes it reports on its own.+ */+ initialError?: string | null;+ /**+ * What to do with the answer.+ *+ * @returns the message to show, or `null` where it worked — in which case the caller has already+ * done whatever comes next, and this form is on its way off the screen.+ */+ onSubmit: (credentials: Credentials) => Promise<string | null>;+}++export default function CredentialsForm({+ title, illustration, totpEnabled, rememberMeEnabled, submitLabel, className, formClassName,+ initialError, onSubmit+}: CredentialsFormProps) {+ const passwordRef = useRef<HTMLInputElement>(null);+ const totpRef = useRef<HTMLInputElement>(null);+ const [ rememberMe, setRememberMe ] = useState(false);+ const [ submitting, setSubmitting ] = useState(false);+ // Carries its own id so that answering wrongly twice over shows the message again rather than+ // leaving it dismissed, which is what `SetupPage` keys the banner on.+ const [ failure, setFailure ] = useState<{ message: string; id: number } | null>(null);++ async function handleSubmit(e: Event) {+ e.preventDefault();+ // The button is disabled while it runs, but Enter in a field is a second way in.+ if (submitting) {+ return;+ }++ setSubmitting(true);+ try {+ const message = await onSubmit({+ password: passwordRef.current?.value ?? "",+ totpToken: totpEnabled ? totpRef.current?.value ?? "" : "",+ rememberMe+ });++ if (message !== null) {+ setFailure((previous) => ({ message, id: (previous?.id ?? 0) + 1 }));+ }+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <form className={formClassName} onSubmit={(e) => void handleSubmit(e)}>+ <SetupPage+ className={className}+ title={title}+ illustration={illustration}+ // What the last press was answered with, or, until there has been one, whatever the+ // caller already had to report.+ error={failure?.message ?? initialError ?? null}+ errorId={failure?.id ?? 0}+ footer={<Button text={submitLabel} kind="primary" disabled={submitting} />}+ >+ <Card>+ <CardSection>+ <OptionsRow name="password" label={t("login.password")} stacked>+ <FormTextBox+ inputRef={passwordRef} autoFocus+ type="password" name="password"+ autocomplete="current-password" required+ />+ </OptionsRow>++ {totpEnabled && (+ <OptionsRow name="totpToken" label={t("login.totp-token")} stacked>+ <FormTextBox+ inputRef={totpRef}+ name="totpToken"+ autocomplete="one-time-code" required+ />+ </OptionsRow>+ )}++ {rememberMeEnabled && (+ <OptionsRowWithToggle+ name="rememberMe"+ label={t("login.remember-me")}+ currentValue={rememberMe}+ onChange={setRememberMe}+ />+ )}+ </CardSection>+ </Card>+ </SetupPage>+ </form>+ );+}diff --git a/apps/server/src/app.ts b/apps/server/src/app.tsindex bc61f1dcf3..2ffb29dc15 100644--- a/apps/server/src/app.ts+++ b/apps/server/src/app.ts@@ -20,6 +20,7 @@ import config from "./services/config.js";import { getLog } from "@triliumnext/core";import { desktopNetworkAccessGate } from "./services/desktop_network_gate.js";import { createReactiveOidcMiddleware } from "./services/open_id.js";+import { setupSecondFactor } from "./services/setup_second_factor.js";import { RESOURCE_DIR } from "./services/resource_dir.js";import utils, { getResourceDir, isDev } from "./services/utils.js";@@ -131,9 +132,15 @@ export default async function buildApp() {custom.register(app);error_handlers.register(app);- const { sync, consistency_checks, scheduler, sql_init, becca_loader, i18n } = await import("@triliumnext/core");+ const { sync, consistency_checks, initSetupSecondFactor, scheduler, sql_init, becca_loader, i18n } = await import("@triliumnext/core");sync.startSyncTimer();+ // What the setup wizard asks for besides the password, where this instance has one. Registered+ // here rather than handed to `initializeCore`, because it is the server that has a second factor+ // at all: the browser-only build never runs this file. Desktop reaches it through the same+ // www.js → buildApp path, and is exempt from the wizard's gate for its own reasons.+ initSetupSecondFactor(setupSecondFactor);+// Server-side i18next always boots on "en" (initTranslations runs before initSql in initializeCore),// so re-sync it with the document's stored locale before the scheduler's dbReady.then(checkHiddenSubtree)// rebuilds the built-in titles — otherwise they are (re-)generated in English on every start. The readdiff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.tsindex 7a88f23e35..bb64f975d1 100644--- a/apps/server/src/routes/index.ts+++ b/apps/server/src/routes/index.ts@@ -46,8 +46,10 @@ export function bootstrap(req: Request, res: Response) {// The setup wizard's password gate is exempted for exactly what `checkSetupAuth` exempts:// the trusted renderer, which is the application itself, and an instance already configured// to trust whoever can reach it. Asked for anywhere else, the screen would be holding out- // for an answer the routes behind it were never going to want.+ // for an answer the routes behind it were never going to want. The second factor rides on+ // the same exemption, since it is only ever asked for alongside the password.setupAuthRequired: sharedItems.setupAuthRequired && !isElectronRenderer && !noAuthentication,+ setupSecondFactorRequired: sharedItems.setupSecondFactorRequired && !isElectronRenderer && !noAuthentication,baseApiUrl: "api/",appPath,isStandalone: false,diff --git a/apps/server/src/services/encryption/recovery_codes.spec.ts b/apps/server/src/services/encryption/recovery_codes.spec.tsindex 32536c1d69..a37618b420 100644--- a/apps/server/src/services/encryption/recovery_codes.spec.ts+++ b/apps/server/src/services/encryption/recovery_codes.spec.ts@@ -57,6 +57,38 @@ describe("recovery_codes", () => {expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);});+ it("matches a code without spending it, for the setup wizard that cannot spend one", () => {+ // The wizard runs against a database that is attached but not migrated, with becca+ // unloaded, so the write that consuming needs would land as a duplicate option row — and a+ // code spent there would still read as unspent everywhere else in a sync cluster. It trades+ // the single use for being able to ask at all. See `setup_auth` in core.+ cls.init(() => {+ recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));+ });++ expect(recoveryCodes.matchesRecoveryCode(CODE_A)).toBe(true);+ // Still both there, and still answerable: the same code twice over is the price.+ expect(recoveryCodes.getRecoveryCodes()).toEqual([ CODE_A, CODE_B ]);+ expect(recoveryCodes.matchesRecoveryCode(CODE_A)).toBe(true);++ expect(recoveryCodes.matchesRecoveryCode(CODE_B)).toBe(true);+ expect(recoveryCodes.matchesRecoveryCode("CCCCCCCCCCCCCCCCCCCCCC==")).toBe(false);+ // Refused on shape before anything is decrypted, exactly as the consuming check does.+ expect(recoveryCodes.matchesRecoveryCode("too-short")).toBe(false);+ });++ it("answers the same way however many times the shape check is run", () => {+ // The pattern is shared between the two checks now. Held in a variable with the `g` flag it+ // would remember where it last matched and answer correctly only every other call.+ cls.init(() => {+ recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));+ });++ for (let attempt = 0; attempt < 4; attempt++) {+ expect(recoveryCodes.matchesRecoveryCode(CODE_B)).toBe(true);+ }+ });+it("rejects codes failing the format regex without consuming a code", () => {cls.init(() => {recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));diff --git a/apps/server/src/services/encryption/recovery_codes.ts b/apps/server/src/services/encryption/recovery_codes.tsindex f1227a0428..83ce1ff6c6 100644--- a/apps/server/src/services/encryption/recovery_codes.ts+++ b/apps/server/src/services/encryption/recovery_codes.ts@@ -4,6 +4,15 @@ import crypto from 'crypto';import sql from '../sql.js';import { constantTimeCompare } from '../utils.js';+/**+ * What a recovery code looks like: 22 characters and the base64 padding.+ *+ * Deliberately without the `g` flag the inline copies of this pattern carried. A `g` regex kept in a+ * variable remembers where it last matched, so `test` on a shared one answers correctly only every+ * other call.+ */+const RECOVERY_CODE_SHAPE = /^.{22}==$/;+function isRecoveryCodeSet() {return optionService.getOptionBool('encryptedRecoveryCodes');}@@ -64,9 +73,29 @@ function removeRecoveryCode(usedCode: string) {setRecoveryCodes(oldCodes.toString());}+/**+ * Whether `recoveryCodeGuess` is one of the codes, leaving it where it is.+ *+ * The consuming check below is the one login uses, and the one to reach for by default. This exists+ * for the setup wizard, which runs against a database that is attached but not migrated, with becca+ * unloaded: `setOption` there would create a duplicate row rather than update one, and a code spent+ * in that state would still read as unspent everywhere else in a sync cluster. So the wizard trades+ * the single use for being able to check at all — see `setup_auth` in core.+ */+function matchesRecoveryCode(recoveryCodeGuess: string) {+ if (!RECOVERY_CODE_SHAPE.test(recoveryCodeGuess)) {+ return false;+ }++ // Every code is compared even once one has matched, so the time taken says nothing about which.+ return getRecoveryCodes().reduce(+ (matched, recoveryCode) => constantTimeCompare(recoveryCodeGuess, recoveryCode) || matched,+ false+ );+}+function verifyRecoveryCode(recoveryCodeGuess: string) {- const recoveryCodeRegex = RegExp(/^.{22}==$/gm);- if (!recoveryCodeRegex.test(recoveryCodeGuess)) {+ if (!RECOVERY_CODE_SHAPE.test(recoveryCodeGuess)) {return false;}@@ -96,6 +125,7 @@ export default {createRecoveryCodes,clearRecoveryCodes,getRecoveryCodes,+ matchesRecoveryCode,verifyRecoveryCode,isRecoveryCodeSet};\ No newline at end of filediff --git a/apps/server/src/services/setup_second_factor.ts b/apps/server/src/services/setup_second_factor.tsnew file mode 100644index 0000000000..9f48c6aa1c--- /dev/null+++ b/apps/server/src/services/setup_second_factor.ts@@ -0,0 +1,40 @@+import type { SetupSecondFactor } from "@triliumnext/core";++import recoveryCodeService from "./encryption/recovery_codes.js";+import totp from "./totp.js";++/**+ * The second factor the setup wizard asks for, where the instance behind it has one.+ *+ * Handed to core at start rather than reached for from there: what counts as a second factor is the+ * server's business, and the builds without a server have none. See `setup_auth` in core for what it+ * is used for and why the answer is checked without being spent.+ *+ * Everything here is a read. The TOTP secret is decrypted with a salt of its own rather than with+ * the password-derived data key, so no protected session is involved, and every option it needs is+ * read through the fallback that serves a database which is attached but has no becca over it.+ *+ * @module+ */+export const setupSecondFactor: SetupSecondFactor = {+ isRequired() {+ return totp.isTotpEnabled();+ },++ /**+ * A passcode from the authenticator, or one of the recovery codes standing in for it.+ *+ * The recovery code is matched and left where it is. Consuming it is impossible here — the+ * write would land on an unmigrated database with no entity changes recorded against it — and+ * refusing recovery codes outright would leave a user whose authenticator is gone shut out of a+ * wizard they have already sent their instance into, with nothing but the data directory to get+ * back out of it. The code stays single-use for logging in, which is where it matters.+ */+ verify(answer: string) {+ if (!answer) {+ return false;+ }++ return totp.validateTOTP(answer) || recoveryCodeService.matchesRecoveryCode(answer);+ }+};diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.tsindex 06e7fdfcfb..4073511dd0 100644--- a/apps/standalone/src/lightweight/browser_routes.ts+++ b/apps/standalone/src/lightweight/browser_routes.ts@@ -329,6 +329,7 @@ function bootstrapRoute(req: { query: Record<string, string | undefined> }): Boo// served to nobody, so asking would be asking for nothing — and `checkSetupAuth` here is a// no-op, which would leave the screen holding out for an answer it never checks.setupAuthRequired: false,+ setupSecondFactorRequired: false,isDev: import.meta.env.DEV,isStandalone: true,// A window torn off into its own popup carries `?extraWindow`, same as on the server. It hasdiff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 5b8bcff631..62269f7481 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -869,6 +869,13 @@ export type BootstrapDefinition = {* knowledge base behind the wizard and a password that guarded it. See `setup_auth` in core.*/setupAuthRequired?: boolean;+ /**+ * Whether that unlock asks for a second factor as well as the password.+ *+ * Only ever `true` alongside `setupAuthRequired`. Says that one is wanted and nothing else: not+ * which kind, and nothing about the answer.+ */+ setupSecondFactorRequired?: boolean;/*** The screen the wizard should open on, from the marker that asked for setup. Only meaningful* while `dbInitialized` is `false`, and absent for a first run, which starts at the language step.@@ -990,6 +997,10 @@ export interface SetupStatusResponse {* of them ran would otherwise go on offering a way back to something that is gone.*/hasExistingData?: boolean;+ /** Whether the wizard has to be unlocked before it will act on that knowledge base. */+ authRequired?: boolean;+ /** Whether that unlock asks for a second factor as well as the password. */+ secondFactorRequired?: boolean;/** The operation setup is busy with, or `null` when it is free. */setupOperation?: SetupOperation | null;/** Kept from a failed sync attempt so the wizard can prefill the form; pre-initialization only. */diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 332866842b..921b52f21e 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -26,7 +26,15 @@ export type * from "./services/sql/types";export * from "./services/sql/index";export { default as sql_init } from "./services/sql_init";export { getRunningSetupOperation, holdSetup, withSetupLock } from "./services/setup_lock";-export { authenticateSetup, isSetupAuthorized, isSetupAuthRequired, resetSetupAuth } from "./services/setup_auth";+export {+ authenticateSetup,+ initSetupSecondFactor,+ isSetupAuthorized,+ isSetupAuthRequired,+ isSetupSecondFactorRequired,+ resetSetupAuth,+ type SetupSecondFactor+} from "./services/setup_auth";export {enterSetupMode,getSetupLanguage,diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex d2f3dba42e..fa0b267f0c 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -9,7 +9,7 @@ import {keepExistingData,startBackUpExistingData} from "../../services/setup_existing.js";-import { authenticateSetup, isSetupAuthRequired } from "../../services/setup_auth.js";+import { authenticateSetup, isSetupAuthRequired, isSetupSecondFactorRequired } from "../../services/setup_auth.js";import { asSetupTargetScreen, getSetupPlatform, hasExistingData } from "../../services/setup_mode.js";import { getLog } from "../../services/log.js";import appInfo from "../../services/app_info.js";@@ -28,6 +28,8 @@ function getStatus() {isInitialized,schemaExists,authRequired,+ // Says a second factor is wanted, never which kind nor anything about the answer.+ secondFactorRequired: isSetupSecondFactorRequired(),// Asked again rather than taken from the page's own start: the paths that replace a// knowledge base erase it here, and a wizard that failed after one of them did would go on// offering a way back to something that no longer exists.@@ -60,7 +62,8 @@ function getStatus() {*/async function authenticate(req: Request) {const password = typeof req.body?.password === "string" ? req.body.password : "";- const token = await authenticateSetup(password);+ const totpToken = typeof req.body?.totpToken === "string" ? req.body.totpToken : "";+ const token = await authenticateSetup(password, totpToken);return token ? { authenticated: true, token } : { authenticated: false };}diff --git a/packages/trilium-core/src/services/bootstrap_utils.ts b/packages/trilium-core/src/services/bootstrap_utils.tsindex c474a4b625..d1276c1966 100644--- a/packages/trilium-core/src/services/bootstrap_utils.ts+++ b/packages/trilium-core/src/services/bootstrap_utils.ts@@ -8,7 +8,7 @@ import { getCurrentLocale } from "./i18n";import attributes from "./attributes";import BNote from "../becca/entities/bnote";import { getPlatform } from "./platform";-import { isSetupAuthRequired } from "./setup_auth";+import { isSetupAuthRequired, isSetupSecondFactorRequired } from "./setup_auth";import { getSetupTargetScreen, hasExistingData, isSetupRequested } from "./setup_mode";import sqlInit from "./sql_init";@@ -35,6 +35,7 @@ export default function getSharedBootstrapItems(assetPath: string, dbInitialized// three at their first-run answers.hasExistingData: hasExistingData(),setupAuthRequired: isSetupAuthRequired(),+ setupSecondFactorRequired: isSetupSecondFactorRequired(),setupTargetScreen: getSetupTargetScreen(),...getIconConfig(assetPath)};diff --git a/packages/trilium-core/src/services/setup_auth.spec.ts b/packages/trilium-core/src/services/setup_auth.spec.tsindex 76473032ae..003694ac09 100644--- a/packages/trilium-core/src/services/setup_auth.spec.ts+++ b/packages/trilium-core/src/services/setup_auth.spec.ts@@ -4,8 +4,10 @@ import * as passwordService from "./encryption/password.js";import passwordEncryptionService from "./encryption/password_encryption.js";import {authenticateSetup,+ initSetupSecondFactor,isSetupAuthorized,isSetupAuthRequired,+ isSetupSecondFactorRequired,resetSetupAuth} from "./setup_auth.js";import { enterSetupMode, leaveSetupMode, markExistingDataDiscarded } from "./setup_mode.js";@@ -97,6 +99,64 @@ describe("unlocking it", () => {expect(isSetupAuthorized(second ?? "")).toBe(true);});+ describe("where the instance guards itself with a second factor as well", () => {+ /** Records what the factor was asked, and answers to whatever it is told is right. */+ function secondFactorAccepting(right: string, required = true) {+ const asked: string[] = [];++ initSetupSecondFactor({+ isRequired: () => required,+ verify: (answer) => {+ asked.push(answer);+ return answer === right;+ }+ });++ return asked;+ }++ it("says it wants one, but only where there is a knowledge base to want it for", () => {+ secondFactorAccepting("123456");+ expect(isSetupSecondFactorRequired()).toBe(true);++ leaveSetupMode();+ expect(isSetupSecondFactorRequired()).toBe(false);+ });++ it("wants none where the instance has none, however it is guarded otherwise", () => {+ secondFactorAccepting("123456", false);++ expect(isSetupAuthRequired()).toBe(true);+ expect(isSetupSecondFactorRequired()).toBe(false);+ });++ it("issues a token only once both have been answered", async () => {+ passwordIs("hunter2");+ secondFactorAccepting("123456");++ expect(await authenticateSetup("hunter2", "000000")).toBeNull();+ expect(await authenticateSetup("hunter2", "123456")).toBeTruthy();+ });++ it("never reaches the second factor on a wrong password", async () => {+ // The answer is often a recovery code. Checking one at all is worth doing only once the+ // rest of the login is known to be right, which is the order login itself uses.+ passwordIs("hunter2");+ const asked = secondFactorAccepting("123456");++ expect(await authenticateSetup("wrong", "123456")).toBeNull();+ expect(asked).toEqual([]);+ });++ it("asks for nothing extra where the instance has no second factor", async () => {+ passwordIs("hunter2");+ const asked = secondFactorAccepting("123456", false);++ expect(await authenticateSetup("hunter2")).toBeTruthy();+ expect(asked).toEqual([]);+ });+ });+it("stops accepting one that has been held too long", async () => {vi.useFakeTimers();try {diff --git a/packages/trilium-core/src/services/setup_auth.ts b/packages/trilium-core/src/services/setup_auth.tsindex 0182ba9728..1e3c6c4e0b 100644--- a/packages/trilium-core/src/services/setup_auth.ts+++ b/packages/trilium-core/src/services/setup_auth.ts@@ -41,22 +41,60 @@ export function isSetupAuthRequired(): boolean {}/**- * Checks the instance's own password and, where it matches, issues the token that unlocks the rest- * of the wizard.+ * The second factor, where the instance guarding the knowledge base has one.*- * Only the password. The second factor is deliberately not asked for: TOTP and recovery codes are- * verified against a database the setup screen is standing over rather than running, and a recovery- * code is consumed when it is checked, which is a poor thing to spend on a screen the user may well- * leave through Cancel.+ * Injected rather than reached for: what counts as a second factor is the server's business (TOTP+ * and the recovery codes beside it live there), and the builds without a server have none.+ */+export interface SetupSecondFactor {+ /** Whether this instance asks for one at all. */+ isRequired(): boolean;+ /**+ * Whether the answer is the right one.+ *+ * Must not consume what it checks. The wizard runs against a database that is attached but not+ * migrated, with becca unloaded and nothing tracking entity changes, so `setOption` here would+ * create a duplicate row rather than update one — and a single-use code spent in this state+ * would still read as unspent on every other instance in a sync cluster. So a recovery code+ * answered here stays answerable here, which is the price of not locking a user out of their+ * own wizard when their authenticator is gone.+ */+ verify(answer: string): boolean;+}++let secondFactor: SetupSecondFactor | null = null;++export function initSetupSecondFactor(instance: SetupSecondFactor | null): void {+ secondFactor = instance;+}++/** Whether unlocking asks for a second factor as well as the password. */+export function isSetupSecondFactorRequired(): boolean {+ return isSetupAuthRequired() && secondFactor?.isRequired() === true;+}++/**+ * Checks the instance's own credentials and, where they match, issues the token that unlocks the+ * rest of the wizard.+ *+ * The password first and the second factor after it, in that order and never the other way round:+ * the answer to a second factor is often a recovery code, and checking one at all is worth doing+ * only once the rest of the login is known to be right.*- * @returns the token, or `null` where the password was wrong.+ * @returns the token, or `null` where the answer was wrong. Which of the two was wrong is+ * deliberately not said: the screen asks for both together and reports one failure.*/-export async function authenticateSetup(password: string): Promise<string | null> {+export async function authenticateSetup(password: string, secondFactorAnswer = ""): Promise<string | null> {if (!await passwordEncryptionService.verifyPassword(password)) {getLog().info("Setup: a wrong password was given for the existing knowledge base.");return null;}+ if (isSetupSecondFactorRequired() && !secondFactor?.verify(secondFactorAnswer)) {+ getLog().info("Setup: a wrong second factor was given for the existing knowledge base.");+ return null;+ }+issued = { token: randomSecureToken(32), expires: Date.now() + TOKEN_LIFETIME_MS };getLog().info("Setup: the existing knowledge base was unlocked.");@@ -81,6 +119,7 @@ export function isSetupAuthorized(token: string | undefined): boolean {/** Forgets it, for the tests that need one process to look like a fresh one. */export function resetSetupAuth(): void {issued = null;+ secondFactor = null;}/**