Skip to content

Build your personal knowledge base with Trilium Notes

start again: add the initial implementation

Adorian Dorana90dcedeaad4
diff --git a/apps/client/src/services/server.ts b/apps/client/src/services/server.ts
index 56b542baef..021974de52 100644
--- a/apps/client/src/services/server.ts
+++ b/apps/client/src/services/server.ts
@@ -1,4 +1,5 @@
import { t } from "./i18n.js";
+import { getSetupAuthToken } from "./setup_auth.js";
import utils, { isShare } from "./utils.js";
import ValidationError from "./validation_error.js";
@@ -26,7 +27,10 @@ async function getHeaders(headers?: Headers) {
"trilium-component-id": glob.componentId,
"trilium-local-now-datetime": utils.localNowDateTime(),
"trilium-hoisted-note-id": activeNoteContext ? activeNoteContext.hoistedNoteId : null,
- "x-csrf-token": glob.csrfToken
+ "x-csrf-token": glob.csrfToken,
+ // What unlocks the setup wizard where a knowledge base is sitting behind it. Null on every
+ // other page, and dropped below along with every other header that has no value.
+ "trilium-setup-auth": getSetupAuthToken()
};
for (const headerName in headers) {
diff --git a/apps/client/src/services/setup_auth.ts b/apps/client/src/services/setup_auth.ts
new file mode 100644
index 0000000000..341af456c5
--- /dev/null
+++ b/apps/client/src/services/setup_auth.ts
@@ -0,0 +1,25 @@
+/**
+ * The token that unlocks a setup wizard with a knowledge base behind it.
+ *
+ * A module of its own, and a very small one, because of who needs it: the request layer sends it on
+ * every call, and the wizard's first screen is what obtains it. Either importing the other would
+ * close a loop, since the wizard reaches the server through that same request layer.
+ *
+ * Held in memory only. A reload of the wizard asks for the password again, which is the right answer
+ * for a screen that can erase a knowledge base and is often left open on a shared machine.
+ *
+ * See `setup_auth` in core for what the token is and why a session cannot take its place.
+ *
+ * @module
+ */
+
+let token: string | null = null;
+
+/** What the request layer puts on every call; `null` everywhere but an unlocked wizard. */
+export function getSetupAuthToken(): string | null {
+ return token;
+}
+
+export function setSetupAuthToken(value: string): void {
+ token = value;
+}
diff --git a/apps/client/src/services/setup_mode.spec.ts b/apps/client/src/services/setup_mode.spec.ts
index b4f2e5f00f..0777e453ff 100644
--- a/apps/client/src/services/setup_mode.spec.ts
+++ b/apps/client/src/services/setup_mode.spec.ts
@@ -1,29 +1,43 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
+ get: vi.fn(),
post: vi.fn(),
+ remove: vi.fn(),
restartDesktopApp: vi.fn(),
isElectron: vi.fn(() => false),
isStandalone: false
}));
-vi.mock("./server", () => ({ default: { post: mocks.post } }));
+vi.mock("./server", () => ({
+ default: { get: mocks.get, post: mocks.post, remove: mocks.remove }
+}));
vi.mock("./utils", () => ({
restartDesktopApp: mocks.restartDesktopApp,
isElectron: mocks.isElectron,
get isStandalone() { return mocks.isStandalone; }
}));
+// t() returns the key so assertions are deterministic and not tied to English text.
+vi.mock("./i18n", () => ({ t: (key: string) => key }));
async function freshModule() {
vi.resetModules();
return import("./setup_mode.js");
}
+/** happy-dom has no `confirm` of its own, so it is stubbed rather than spied on. */
+const nativeConfirm = vi.fn(() => true);
+
beforeEach(() => {
+ mocks.get.mockReset().mockResolvedValue({ requested: false });
mocks.post.mockReset().mockResolvedValue(undefined);
+ mocks.remove.mockReset().mockResolvedValue(undefined);
mocks.restartDesktopApp.mockReset();
mocks.isElectron.mockReset().mockReturnValue(false);
mocks.isStandalone = false;
+ nativeConfirm.mockReset().mockReturnValue(true);
+ vi.stubGlobal("confirm", nativeConfirm);
+ window.electronApi = undefined;
});
describe("asking the next start to be the setup wizard", () => {
@@ -69,3 +83,63 @@ describe("asking the next start to be the setup wizard", () => {
expect((await freshModule()).canBootToSetup()).toBe(true);
});
});
+
+describe("starting over", () => {
+ it("asks with the browser's own dialog, then goes back to setup from the top", async () => {
+ mocks.isStandalone = true;
+ const { startOver } = await freshModule();
+
+ await expect(startOver()).resolves.toBe("restarting");
+
+ // Nothing is asked for but the wizard's first screen: what follows is the offer of a backup
+ // and then every way of starting a knowledge base.
+ expect(nativeConfirm).toHaveBeenCalledWith("database.start_over_confirm");
+ expect(mocks.post).toHaveBeenCalledWith("setup/boot");
+ expect(mocks.restartDesktopApp).toHaveBeenCalled();
+ });
+
+ it("asks with the operating system's own where there is one to ask with", async () => {
+ // A note script can reach every dialog Trilium draws for itself, so neither of these is one.
+ mocks.isElectron.mockReturnValue(true);
+ const confirmStartOver = vi.fn(async () => true);
+ window.electronApi = { dialog: { confirmStartOver } } as never;
+ const { startOver } = await freshModule();
+
+ await expect(startOver()).resolves.toBe("restarting");
+
+ expect(confirmStartOver).toHaveBeenCalled();
+ expect(nativeConfirm).not.toHaveBeenCalled();
+ });
+
+ it("writes nothing down when the answer is no", async () => {
+ mocks.isStandalone = true;
+ nativeConfirm.mockReturnValue(false);
+ const { startOver } = await freshModule();
+
+ await expect(startOver()).resolves.toBe("cancelled");
+
+ expect(mocks.post).not.toHaveBeenCalled();
+ expect(mocks.restartDesktopApp).not.toHaveBeenCalled();
+ });
+
+ it("leaves the request standing on a server, which restarts itself for nobody", async () => {
+ const { startOver } = await freshModule();
+
+ await expect(startOver()).resolves.toBe("pending");
+
+ expect(mocks.post).toHaveBeenCalledWith("setup/boot");
+ // Reloading would restart the browser and leave the server holding the database open.
+ expect(mocks.restartDesktopApp).not.toHaveBeenCalled();
+ });
+
+ it("says whether one is still waiting, and takes it back", async () => {
+ const { cancelStartOver, isStartOverPending } = await freshModule();
+
+ mocks.get.mockResolvedValue({ requested: true });
+ await expect(isStartOverPending()).resolves.toBe(true);
+ expect(mocks.get).toHaveBeenCalledWith("setup/boot");
+
+ await cancelStartOver();
+ expect(mocks.remove).toHaveBeenCalledWith("setup/boot");
+ });
+});
diff --git a/apps/client/src/services/setup_mode.ts b/apps/client/src/services/setup_mode.ts
index bcb4f154b7..f81938e53c 100644
--- a/apps/client/src/services/setup_mode.ts
+++ b/apps/client/src/services/setup_mode.ts
@@ -1,5 +1,6 @@
import type { SetupTargetScreen } from "@triliumnext/commons";
+import { t } from "./i18n";
import server from "./server";
import { isElectron, isStandalone, restartDesktopApp } from "./utils";
@@ -41,3 +42,68 @@ export async function bootToSetup(options: { targetScreen?: SetupTargetScreen }
export function canBootToSetup(): boolean {
return isElectron() || isStandalone;
}
+
+/**
+ * What became of a start-over the user asked for.
+ *
+ * `restarting` is the ordinary answer and nothing follows it: the application is on its way down.
+ * `pending` belongs to a server, which is restarted by whoever runs it rather than by itself, so
+ * the request sits in the data directory until then and the interface has to say so.
+ */
+export type StartOverOutcome = "cancelled" | "restarting" | "pending";
+
+/**
+ * Sends the instance back to the setup screen, from the top.
+ *
+ * The same marker every other way into the wizard writes, with no screen named: the wizard opens on
+ * its first screen, offers a copy of the knowledge base, and then offers every way of starting one.
+ * Nothing is erased here, and nothing is erased by the restart either.
+ *
+ * The confirmation is the operating system's own rather than one of the application's: a note
+ * script can reach every dialog Trilium draws for itself, and this is the way to a screen that can
+ * replace a knowledge base.
+ */
+export async function startOver(): Promise<StartOverOutcome> {
+ if (!await confirmStartOver()) {
+ return "cancelled";
+ }
+
+ await server.post("setup/boot");
+
+ if (!canBootToSetup()) {
+ // Reloading would only restart the browser, leaving the server up with the database open
+ // and the marker unread. The owner restarts it, and until they do the request stands.
+ return "pending";
+ }
+
+ restartDesktopApp();
+
+ return "restarting";
+}
+
+/** Whether a start-over asked for earlier is still waiting for the restart that acts on it. */
+export async function isStartOverPending(): Promise<boolean> {
+ const { requested } = await server.get<{ requested: boolean }>("setup/boot");
+
+ return requested;
+}
+
+/** Takes the request back, which only means anything before that restart. */
+export async function cancelStartOver(): Promise<void> {
+ await server.remove("setup/boot");
+}
+
+/**
+ * The last thing between a knowledge base and the screen that can replace it.
+ *
+ * An OS message box on the desktop, for the reason the security toggles use one, and the browser's
+ * own `confirm` everywhere else: both are drawn by something other than Trilium, so neither can be
+ * dismissed by a script running inside it.
+ */
+async function confirmStartOver(): Promise<boolean> {
+ if (window.electronApi) {
+ return await window.electronApi.dialog.confirmStartOver();
+ }
+
+ return window.confirm(t("database.start_over_confirm"));
+}
diff --git a/apps/client/src/setup.css b/apps/client/src/setup.css
index cdd65c7ae0..767e19f73e 100644
--- a/apps/client/src/setup.css
+++ b/apps/client/src/setup.css
@@ -55,46 +55,65 @@ body.setup {
body.desktop & {
gap: 0.75rem;
}
+ }
- .setup-option-card {
- padding: .75em 1.5em;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 1rem;
-
- &.disabled {
- cursor: not-allowed;
- opacity: 0.5;
- background-color: transparent;
- border-color: var(--main-border-color)
- }
+ .setup-option-card {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ padding: .75em 1.5em;
+ cursor: pointer;
+
+ &.disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+ background-color: transparent;
+ border-color: var(--main-border-color)
+ }
- &:not(.disabled):hover {
- background-color: var(--card-background-hover-color);
- filter: contrast(105%);
- transition: background-color .2s ease-out;
- }
+ &:not(.disabled):hover {
+ background-color: var(--card-background-hover-color);
+ filter: contrast(105%);
+ transition: background-color .2s ease-out;
+ }
- .tn-icon {
- font-size: 2.5em;
- color: var(--muted-text-color);
- }
+ .tn-icon {
+ font-size: 2.5em;
+ color: var(--muted-text-color);
+ }
- h3 {
- margin-bottom: 4px;
- font-size: 1.15em;
- font-weight: normal;
+ h3 {
+ margin-bottom: 4px;
+ font-size: 1.15em;
+ font-weight: normal;
- body.desktop & {
- font-size: 1.3em;
- }
+ body.desktop & {
+ font-size: 1.3em;
}
+ }
+
+ p:last-of-type {
+ margin-bottom: 0;
+ font-size: .85em;
+ color: var(--muted-text-color);
+ }
+ }
+
+ /* Apart from the four above, which all replace the knowledge base, and quieter than
+ them: this is the one that changes nothing. */
+ .setup-keep-card {
+ margin-top: 1.5rem;
+ background-color: transparent;
+
+ .tn-icon {
+ font-size: 1.75em;
+ }
+
+ h3 {
+ font-size: 1em;
- p:last-of-type {
- margin-bottom: 0;
- font-size: .85em;
- color: var(--muted-text-color);
+ body.desktop & {
+ font-size: 1.05em;
}
}
}
diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsx
index 1abb4451f5..bdcb711bee 100644
--- a/apps/client/src/setup.spec.tsx
+++ b/apps/client/src/setup.spec.tsx
@@ -206,27 +206,37 @@ describe("where the wizard opens", () => {
expect(initialState({ setupTargetScreen: "restore-backup" })).toBe("restoreFromBackup");
});
- it("asks about the existing knowledge base before anything else, wherever it was headed", () => {
- expect(initialState({ initialSetup: false })).toBe("existingData");
- expect(initialState({ initialSetup: false, setupTargetScreen: "restore-backup" }))
+ it("offers a copy of the existing knowledge base before anything else, wherever it was headed", () => {
+ expect(initialState({ hasExistingData: true })).toBe("existingData");
+ expect(initialState({ hasExistingData: true, setupTargetScreen: "restore-backup" }))
.toBe("existingData");
});
it("goes straight to the backup screen, which is the one that replaces nothing", () => {
- // Unlike a restore, a backup leaves the knowledge base exactly as it is, so the question
- // about what to do with it would be asking about something that is not happening.
- expect(initialState({ initialSetup: false, setupTargetScreen: "backup-database" }))
+ // Unlike a restore, a backup leaves the knowledge base exactly as it is, so the offer of a
+ // copy would be offering the very thing the screen after it is about to make.
+ expect(initialState({ hasExistingData: true, setupTargetScreen: "backup-database" }))
.toBe("backupDatabase");
// Except where there is nothing to back up, which is not a state the app can ask for.
expect(initialState({ setupTargetScreen: "backup-database" })).toBe("selectLanguage");
});
+ it("asks for the password first where the wizard is standing over a knowledge base", () => {
+ // Before everything, including the resumed sync below: what is behind the wizard is a real
+ // knowledge base, and every screen past this one can replace it.
+ expect(initialState({ setupAuthRequired: true, hasExistingData: true })).toBe("unlock");
+ expect(initialState({ setupAuthRequired: true, hasExistingData: true, syncInProgress: true }))
+ .toBe("unlock");
+ expect(initialState({ setupAuthRequired: true, hasExistingData: true, setupTargetScreen: "restore-backup" }))
+ .toBe("unlock");
+ });
+
it("resumes an interrupted sync before anything else, since that one cannot wait", () => {
expect(initialState({ syncInProgress: true })).toBe("syncFromServerInProgress");
expect(initialState({ syncInProgress: true, setupTargetScreen: "restore-backup" }))
.toBe("syncFromServerInProgress");
- expect(initialState({ syncInProgress: true, initialSetup: false, setupTargetScreen: "backup-database" }))
+ expect(initialState({ syncInProgress: true, hasExistingData: true, setupTargetScreen: "backup-database" }))
.toBe("syncFromServerInProgress");
});
@@ -239,7 +249,7 @@ describe("where the wizard opens", () => {
// Which decides whether that screen offers a way back: there is one only where the user
// walked into the restore through the wizard's own menu.
expect(openedAtRestore({ setupTargetScreen: "restore-backup" })).toBe(true);
- expect(openedAtRestore({ initialSetup: false, setupTargetScreen: "restore-backup" })).toBe(true);
+ expect(openedAtRestore({ hasExistingData: true, setupTargetScreen: "restore-backup" })).toBe(true);
expect(openedAtRestore({})).toBe(false);
expect(openedAtRestore({ setupTargetScreen: "backup-database" })).toBe(false);
});
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsx
index 674c4f9f1e..7d79610ac5 100644
--- a/apps/client/src/setup.tsx
+++ b/apps/client/src/setup.tsx
@@ -11,8 +11,9 @@ import { getCurrentLanguage, initLocale, t } from "./services/i18n";
import server from "./services/server";
import { isElectron, isMobileApp } from "./services/utils";
import SetupBackupDatabase from "./setup_backup";
-import ExistingData, { keepExistingData } from "./setup_existing";
+import ExistingData, { deleteExistingData, hasExistingData, keepExistingData } from "./setup_existing";
import RestoreFromBackup from "./setup_restore";
+import SetupUnlock from "./setup_unlock";
import Admonition, { ExtendedAdmonition } from "./widgets/react/Admonition";
import Button from "./widgets/react/Button";
import { Card, CardFrame, CardSection } from "./widgets/react/Card";
@@ -42,12 +43,14 @@ async function main() {
document.body.replaceChildren(bodyWrapper);
}
-type State = "backupDatabase" | "existingData" | "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";
+type State = "unlock" | "backupDatabase" | "existingData" | "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";
-const STATE_ORDER: State[] = ["backupDatabase", "existingData", "selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];
+const STATE_ORDER: State[] = ["unlock", "backupDatabase", "existingData", "selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];
export function renderState(state: State, setState: (state: State) => void) {
switch (state) {
+ // Nothing else in the wizard can be reached until this is answered, which is the point.
+ case "unlock": return <SetupUnlock onUnlocked={() => setState(afterUnlock(window.glob))} />;
// Leads nowhere by design: the wizard was opened to take a backup of the database it is
// sitting on, so the only way out of it is back into that database.
case "backupDatabase": return <SetupBackupDatabase onDone={() => void onExistingDataKept()} />;
@@ -58,13 +61,14 @@ export function renderState(state: State, setState: (state: State) => void) {
/>
);
case "selectLanguage": return <SelectLanguage setState={setState} />;
- case "firstOptions": return <SetupOptions setState={setState} />;
+ case "firstOptions": return <SetupOptions setState={setState} onKeep={() => void onExistingDataKept()} />;
case "createNewDocumentOptions": return <CreateNewDocumentOptions setState={setState} />;
- case "createNewDocumentWithDemo": return <CreateNewDocumentInProgress withDemo />;
- case "createNewDocumentEmpty": return <CreateNewDocumentInProgress />;
+ case "createNewDocumentWithDemo": return <CreateNewDocumentInProgress withDemo setState={setState} />;
+ case "createNewDocumentEmpty": return <CreateNewDocumentInProgress setState={setState} />;
// No way back where the wizard was opened for this and nothing else: the menu it would
// return to was never shown, and on an instance that had a database it is not a menu the
- // user asked for.
+ // user asked for. Nothing is erased on the way in either — a restore checks the backup and
+ // only then swaps the database, so an unusable file leaves the user with what they had.
case "restoreFromBackup": return (
<RestoreFromBackup
onBack={openedAtRestore(window.glob) ? undefined : () => setState("firstOptions")}
@@ -112,33 +116,44 @@ function App() {
/** What the wizard needs to know from the bootstrap to decide where it opens and where it goes next. */
interface SetupGlob {
syncInProgress?: boolean;
- initialSetup?: boolean;
+ hasExistingData?: boolean;
+ setupAuthRequired?: boolean;
setupTargetScreen?: SetupTargetScreen;
}
/**
* Where the wizard opens.
*
- * A first run starts at the language step and works forward. Three things come in already knowing
- * better: a sync interrupted after it created the schema, an instance with a knowledge base still
- * behind the wizard, which has to answer for that before anything else, and an instance sent to a
- * particular screen through a `setup.json` marker.
+ * A first run starts at the language step and works forward. Everything else comes in already
+ * knowing better: a wizard with a knowledge base behind it that has to be unlocked before it will
+ * do anything, a sync interrupted after it created the schema, an instance offered a copy of what is
+ * behind the wizard, and an instance sent to a particular screen through a `setup.json` marker.
*/
export function initialState(glob: SetupGlob): State {
+ // First of all, because everything below it acts on a knowledge base that is still there.
+ if (glob.setupAuthRequired) {
+ return "unlock";
+ }
+
if (glob.syncInProgress) {
return "syncFromServerInProgress";
}
+ return afterUnlock(glob);
+}
+
+/** The rest of the wizard, once there is nothing left standing in front of it. */
+function afterUnlock(glob: SetupGlob): State {
// Asked for by a running instance that wants its database held still long enough to be copied.
- // It skips the question below because it answers it: nothing here is being replaced or erased,
- // and the instance goes back to the same database when the screen is done with.
- if (glob.setupTargetScreen === "backup-database" && glob.initialSetup === false) {
+ // It skips the screen below because that screen is the same offer, made where the user is on
+ // their way somewhere else; here the copy is the whole errand.
+ if (glob.setupTargetScreen === "backup-database" && glob.hasExistingData) {
return "backupDatabase";
}
- // Before the language, before the menu: everything past this point replaces or erases what is
- // already here, and the user has not been asked about that yet.
- if (glob.initialSetup === false) {
+ // Before the language, before the menu: this is the one moment the database is open and nothing
+ // is running against it, which is what taking a copy of it needs.
+ if (glob.hasExistingData) {
return "existingData";
}
@@ -204,12 +219,44 @@ function SelectLanguage({ setState }: { setState: (state: State) => void }) {
);
}
-function SetupOptions({ setState }: { setState: (state: State) => void }) {
+function SetupOptions({ setState, onKeep }: { setState: (state: State) => void; onKeep: () => void }) {
+ const [ error, setError ] = useState<string | null>(null);
+ const [ errorId, setErrorId ] = useState(0);
+
+ /**
+ * Clears the way for a knowledge base that another desktop will push, then waits for it.
+ *
+ * The one path that cannot erase at the moment the database is created, because that moment
+ * belongs to the other device rather than to anything pressed here: this instance only waits,
+ * and it decides it has a database by seeing a schema appear, which the old one would satisfy on
+ * its own. So arriving on the screen is what commits, and it is asked about with the browser's
+ * own dialog for the same reason every other erasure in the wizard is.
+ */
+ async function syncFromDesktop() {
+ if (hasExistingData()) {
+ if (!window.confirm(t("setup.existing-data-erase-confirm"))) {
+ return;
+ }
+
+ try {
+ await deleteExistingData();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ setErrorId((previous) => previous + 1);
+ return;
+ }
+ }
+
+ setState("syncFromDesktop");
+ }
+
return (
<SetupPage
title={t("setup.heading")}
className="setup-options-container"
illustration={<img src={logo} alt="Setup illustration" className="illustration-logo" />}
+ error={error}
+ errorId={errorId}
onBack={() => setState("selectLanguage")}
>
<div class="setup-options">
@@ -239,9 +286,23 @@ function SetupOptions({ setState }: { setState: (state: State) => void }) {
title={t("setup.sync-from-desktop")}
description={t("setup.sync-from-desktop-description")}
disabled={glob.isStandalone}
- onClick={() => setState("syncFromDesktop")}
+ onClick={() => void syncFromDesktop()}
/>
</div>
+
+ {/* The way out, offered only while there is something to go back to. Set apart from the
+ four above rather than made a fifth of them: those replace the knowledge base and
+ this one is how the user leaves it exactly as they found it. */}
+ {hasExistingData() && (
+ <CardFrame className="setup-option-card setup-keep-card" onClick={onKeep}>
+ <Icon icon="bx bx-log-in-circle" />
+
+ <div>
+ <h3>{t("setup.keep-existing")}</h3>
+ <p>{t("setup.keep-existing-description")}</p>
+ </div>
+ </CardFrame>
+ )}
</SetupPage>
);
}
@@ -462,21 +523,71 @@ function CreateNewDocumentOptions({ setState }: { setState: (state: State) => vo
);
}
-function CreateNewDocumentInProgress({ withDemo = false }: { withDemo?: boolean }) {
+/**
+ * The wait while the database is created, and what became of it if it was not.
+ *
+ * A failure has to be said out loud rather than left to the spinner: this screen has nothing to
+ * poll and no other way of ending, so a request that comes back with an error would otherwise leave
+ * it turning for as long as the user was willing to watch it.
+ */
+function CreateNewDocumentInProgress({ withDemo = false, setState }: {
+ withDemo?: boolean;
+ setState: (state: State) => void;
+}) {
+ const [ error, setError ] = useState<string | null>(null);
+
useEffect(() => {
- server.post(`setup/new-document${withDemo ? "" : "?skipDemoDb"}`, { locale: getCurrentLanguage() }).then(onSetupFinished);
+ server.post(`setup/new-document${withDemo ? "" : "?skipDemoDb"}`, { locale: getCurrentLanguage() })
+ .then(onSetupFinished)
+ .catch((e: unknown) => setError(messageOf(e)));
}, [ withDemo ]);
return (
<SetupPage
className="create-new-document"
- title={t("setup.create-new-document-title")}
- description={t("setup.create-new-document-description")}
- illustration={<Icon icon="bx bx-loader-circle bx-spin" className="illustration-icon" />}
+ title={error ? t("setup.create-new-document-failed") : t("setup.create-new-document-title")}
+ description={error ? undefined : t("setup.create-new-document-description")}
+ illustration={
+ <Icon
+ icon={error ? "bx bx-error-circle" : "bx bx-loader-circle bx-spin"}
+ className="illustration-icon"
+ />
+ }
+ error={error}
+ // Only once there is something to go back from: while it is running there is nothing to
+ // return to that would not leave a half-created database behind.
+ onBack={error ? () => setState("createNewDocumentOptions") : undefined}
/>
);
}
+/**
+ * Whatever the failure has to say for itself.
+ *
+ * A rejected request is not an `Error`: the client's own layer rejects with the response body as a
+ * string, or with a bare word when the browser dropped the request.
+ */
+function messageOf(e: unknown): string {
+ if (e instanceof Error) {
+ return e.message;
+ }
+ if (typeof e === "string") {
+ try {
+ const parsed: unknown = JSON.parse(e);
+ if (typeof parsed === "object" && parsed !== null && "message" in parsed
+ && typeof parsed.message === "string") {
+ return parsed.message;
+ }
+ } catch {
+ // Not JSON, so it is already whatever the server had to say.
+ }
+
+ return e;
+ }
+
+ return String(e);
+}
+
export function SyncFromServer({ setState }: { setState: (state: State) => void }) {
const [ syncServerHost, setSyncServerHost ] = useState("");
const [ password, setPassword ] = useState("");
diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsx
index 1ae084bfe3..ce452d2759 100644
--- a/apps/client/src/setup_existing.spec.tsx
+++ b/apps/client/src/setup_existing.spec.tsx
@@ -87,12 +87,6 @@ async function askForBackup() {
await settle();
}
-/**
- * The last question before the erase, answered here so the tests get past it. happy-dom has no
- * `confirm` of its own, so it is stubbed rather than spied on.
- */
-const confirmErase = vi.fn(() => true);
-
beforeEach(() => {
vi.useFakeTimers();
onProceed.mockReset();
@@ -102,8 +96,6 @@ beforeEach(() => {
openMock.download.mockClear();
electronMock.isElectron.mockReset().mockReturnValue(false);
electronMock.openPath.mockClear();
- confirmErase.mockReset().mockReturnValue(true);
- vi.stubGlobal("confirm", confirmErase);
window.electronApi = undefined;
});
@@ -114,7 +106,7 @@ afterEach(() => {
vi.useRealTimers();
});
-describe("choosing what happens to the existing knowledge base", () => {
+describe("offering a copy of the existing knowledge base", () => {
it("will not continue until one of the two has been chosen", async () => {
renderScreens();
await settle();
@@ -134,45 +126,46 @@ describe("choosing what happens to the existing knowledge base", () => {
choose("back-up");
await settle();
- choose("delete");
+ choose("skip");
await settle();
const checked = [ ...container.querySelectorAll<HTMLInputElement>("input[type=radio]") ]
.filter((radio) => radio.checked)
.map((radio) => radio.value);
// Two groups as far as the browser is concerned, one answer as far as the screen is.
- expect(checked).toEqual([ "delete" ]);
+ expect(checked).toEqual([ "skip" ]);
});
- it("warns about erasure only once erasure is what was chosen", async () => {
+ it("says what continuing without a copy does and does not cost, once that is the answer", async () => {
renderScreens();
await settle();
expect(container.querySelector(".existing-data-warning")).toBeNull();
- choose("delete");
+ choose("skip");
await settle();
expect(container.querySelector(".existing-data-warning")?.textContent)
- .toContain("setup.existing-data-delete-warning");
+ .toContain("setup.existing-data-skip-warning");
- // Changing one's mind takes the warning away with it.
+ // Changing one's mind takes it away again.
choose("back-up");
await settle();
expect(container.querySelector(".existing-data-warning")).toBeNull();
});
- it("erases and moves on when that is the answer", async () => {
+ it("moves on without erasing anything when the copy is declined", async () => {
renderScreens();
await settle();
- choose("delete");
+ choose("skip");
await settle();
button("setup.continue")?.click();
await settle();
- expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");
expect(onProceed).toHaveBeenCalled();
- // Nothing was backed up, since nothing was asked to be.
+ // Neither backed up nor erased: the knowledge base is untouched until the user picks a path
+ // in the menu that follows, and each of those erases for itself.
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup", expect.anything());
});
@@ -242,41 +235,24 @@ describe("backing it up first", () => {
});
});
- it("says what was written, and erases nothing until that is confirmed", async () => {
+ it("says what was written, and erases nothing on the way out of it", async () => {
statusAnswers({ state: "done", fraction: 1, result: BACKUP });
await backUpAndWait();
expect(serverMock.post)
.toHaveBeenCalledWith("setup/existing/backup", expect.objectContaining({ compress: false }));
- // The path in full: the option holding a custom backup directory is in the database that is
- // about to go, so this may be the last chance to read it.
+ // The path in full: the option holding a custom backup directory is in the database the user
+ // is on their way to replacing, so this may be the last chance to read it.
expect(container.textContent).toContain(BACKUP.fileName);
// The folder, not the whole path: the file name is on the line above it.
expect(container.textContent).toContain(BACKUP.directoryPath);
expect(container.textContent).not.toContain(BACKUP.filePath);
expect(container.textContent).toContain("200 MiB");
- expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
button("setup.continue")?.click();
await settle();
- expect(confirmErase).toHaveBeenCalledWith("setup.existing-data-erase-confirm");
- expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");
expect(onProceed).toHaveBeenCalled();
- });
-
- it("erases nothing when the last question is answered no", async () => {
- confirmErase.mockReturnValue(false);
- statusAnswers({ state: "done", fraction: 1, result: BACKUP });
- await backUpAndWait();
-
- button("setup.continue")?.click();
- await settle();
-
- expect(confirmErase).toHaveBeenCalled();
expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
- expect(onProceed).not.toHaveBeenCalled();
- // Still on the screen it was answered from, so the backup can be taken again or kept.
- expect(container.textContent).toContain(BACKUP.fileName);
});
it("shows how far along the write is, once the writer has said anything", async () => {
@@ -426,25 +402,8 @@ describe("backing up straight to a download on standalone", () => {
arrivingButton("setup.continue")?.click();
await settle();
- // Asked once more before the data goes, since this screen is about the copy rather than
- // about what continuing costs.
- expect(confirmErase).toHaveBeenCalledWith("setup.existing-data-erase-confirm");
- expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");
expect(onProceed).toHaveBeenCalled();
- });
-
- it("keeps the data when that last question is answered no", async () => {
- confirmErase.mockReturnValue(false);
- downloadDatabase.mockResolvedValue({ status: "done" });
- await reachDownloadScreen();
-
- arrivingButton("setup.backup-download")?.click();
- await settle();
- arrivingButton("setup.continue")?.click();
- await settle();
-
expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
- expect(onProceed).not.toHaveBeenCalled();
});
it("shows what stopped a failed download, and keeps Continue out of reach", async () => {
diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsx
index 460db5b937..16a5ee6e87 100644
--- a/apps/client/src/setup_existing.tsx
+++ b/apps/client/src/setup_existing.tsx
@@ -23,25 +23,26 @@ import SetupPage from "./widgets/react/SetupPage";
import SlidePages from "./widgets/react/SlidePages";
/**
- * What happens to the knowledge base that was already here.
+ * The offer to save the knowledge base that was already here.
*
* The wizard is normally the first thing an instance ever shows. When the app asks for it instead,
- * there is a database behind it, and every path onwards from here replaces or erases that database.
- * So this is the first screen, before the menu, and nothing else can be reached until it is answered.
+ * there is a database behind it, and most of what the menu offers will eventually replace it. So
+ * this is the first screen, before the menu: the one chance to take a copy while the database is
+ * open but nothing is running against it.
*
- * Three screens, one question. The choice, the wait while a backup is written, and what was written.
- * Every one of them can be left through Cancel, which puts the instance back the way it was: nothing
- * is touched until the last Continue.
+ * Nothing here is destructive. The copy is taken or it is not, and either way the instance still
+ * has everything it had; the erasure happens later, inside whichever path the user picks, and only
+ * for the paths that create a database. Cancel, available on every screen, puts the instance back.
*
* @module
*/
-/** What the user decided to do with the database that is already here. */
-type Choice = "back-up" | "delete";
+/** What the user decided about a copy of the database that is already here. */
+type Choice = "back-up" | "skip";
const CHOICES: { value: Choice; label: string }[] = [
{ value: "back-up", label: "setup.existing-data-back-up" },
- { value: "delete", label: "setup.existing-data-delete" }
+ { value: "skip", label: "setup.existing-data-skip" }
];
/** The screens, in the order they can be reached, which is also the order they slide in. */
@@ -55,8 +56,9 @@ const STEP_ORDER: Step[] = [ "choice", "backup-parameters", "backing-up", "downl
* and what the user has answered so far lives here rather than being spread through the wizard's own
* state machine.
*
- * @param onProceed the database is gone; carry on with the rest of setup.
- * @param onKept nothing was touched; the app is coming back.
+ * @param onProceed the question has been answered; carry on to the menu. The knowledge base is still
+ * there, and stays there until the user picks something that replaces it.
+ * @param onKept the app is coming back; the wizard is over.
*/
export default function ExistingData({ onProceed, onKept }: { onProceed: () => void; onKept: () => void }) {
const [ step, setStep ] = useState<Step>("choice");
@@ -71,33 +73,6 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
setErrorId((previous) => previous + 1);
}
- /** Erases the database and moves on, which is the one irreversible thing these screens do. */
- async function erase() {
- try {
- await deleteExistingData();
- onProceed();
- } catch (e) {
- setStep("choice");
- raiseError(messageOf(e) ?? t("setup.existing-data-delete-failed"));
- }
- }
-
- /**
- * The same, asked about first, for the screens reached by taking a backup.
- *
- * Those screens are about the copy that was just made, and the erasure is what Continue does
- * once the user is done reading about it — which is exactly the sort of thing a hand already
- * moving towards the button does not notice. The wizard has no dialog stack of its own, so this
- * is the browser's own, which is both unmissable and available on every platform.
- */
- async function confirmAndErase() {
- if (!window.confirm(t("setup.existing-data-erase-confirm"))) {
- return;
- }
-
- await erase();
- }
-
/**
* Asks what the backup should be before taking it, which every platform does.
*
@@ -147,7 +122,7 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
error={error}
errorId={errorId}
onBackUp={() => void backUp()}
- onDelete={() => void erase()}
+ onSkip={onProceed}
onCancel={() => void keep()}
/>
)}
@@ -174,14 +149,14 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
{shown === "downloading" && settings && (
<ExistingDataDownloading
settings={settings}
- onContinue={() => void confirmAndErase()}
+ onContinue={onProceed}
onCancel={() => void keep()}
/>
)}
{shown === "backed-up" && backup && (
<ExistingDataBackedUp
backup={backup}
- onContinue={() => void confirmAndErase()}
+ onContinue={onProceed}
onCancel={() => void keep()}
/>
)}
@@ -227,11 +202,11 @@ function messageOfBody(body: string): string {
return body;
}
-export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCancel }: {
+export function ExistingDataChoice({ error, errorId, onBackUp, onSkip, onCancel }: {
error?: string;
errorId?: number;
onBackUp: () => void;
- onDelete: () => void;
+ onSkip: () => void;
onCancel: () => void;
}) {
const [ choice, setChoice ] = useState<Choice | null>(null);
@@ -239,9 +214,10 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCance
return (
<SetupPage
className="existing-data"
- // A question and nothing else: the answer decides whether a knowledge base survives,
- // and a paragraph above it is the part someone in a hurry reads past.
+ // A question and nothing else: a paragraph above it is the part someone in a hurry
+ // reads past, and this is the one offer of a copy they will get.
title={t("setup.existing-data")}
+ description={t("setup.existing-data-description")}
illustration={<Icon icon="bx bx-data" className="illustration-icon" />}
error={error}
errorId={errorId}
@@ -251,22 +227,20 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCance
<Button
text={t("setup.continue")}
kind="primary"
- // Neither is chosen to begin with: one of them erases a knowledge base, and a
- // default would make that the answer of anyone who pressed on without reading.
+ // Neither is chosen to begin with: a default would make the backup the
+ // answer of anyone who pressed on without reading, either way round.
disabled={choice === null}
- onClick={() => (choice === "back-up" ? onBackUp() : onDelete())}
+ onClick={() => (choice === "back-up" ? onBackUp() : onSkip())}
/>
</>
}
>
<Card className="existing-data-choices">
- {/* A segment each, rather than two rows in one: this is the question the whole screen
- is for, and one of the answers erases a knowledge base. Which is checked is held
- here rather than by the browser's own grouping, so the two stay exclusive. */}
+ {/* A segment each, rather than two rows in one: this is the question the whole
+ screen is for. Which is checked is held here rather than by the browser's own
+ grouping, so the two stay exclusive. */}
{CHOICES.map(({ value, label }) => (
- // The answer that erases everything is coloured as such, so it is recognisable
- // before it is read rather than after.
- <CardSection key={value} className={value === "delete" ? "existing-data-destructive" : undefined}>
+ <CardSection key={value}>
<FormRadioGroup
name="existing-data-choice"
currentValue={choice ?? ""}
@@ -277,9 +251,9 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCance
))}
</Card>
- {choice === "delete" && (
- <Admonition type="caution" className="existing-data-warning">
- {t("setup.existing-data-delete-warning")}
+ {choice === "skip" && (
+ <Admonition type="note" className="existing-data-warning">
+ {t("setup.existing-data-skip-warning")}
</Admonition>
)}
</SetupPage>
@@ -377,11 +351,11 @@ export function ExistingDataDownloading({ settings, onContinue, onCancel }: {
}
/**
- * What was written, before the database it was written from is erased.
+ * What was written, and where.
*
* The path is shown in full and not abbreviated: a custom backup directory is an option in a
- * database that is about to stop existing, so this may be the last time the user can see where their
- * backup actually went.
+ * database the user is on their way to replacing, so this may be the last time they can see where
+ * their backup actually went.
*/
export function ExistingDataBackedUp({ backup, onContinue, onCancel }: {
backup: SetupExistingBackup;
@@ -523,12 +497,33 @@ export async function getBackupDefaults(): Promise<SetupBackupDefaults> {
}
}
-/** Erases it, which is the point of no return. */
-export function deleteExistingData(): Promise<void> {
- return server.post("setup/existing/delete");
+/**
+ * Erases it, which is the point of no return.
+ *
+ * Called from the wizard only where the erasure cannot ride along with the thing that replaces the
+ * database: creating a document and syncing from a server both erase server-side as their first
+ * step, but a database pushed by another desktop arrives on its own schedule, so that path has to
+ * clear the way before it starts waiting.
+ */
+export async function deleteExistingData(): Promise<void> {
+ await server.post("setup/existing/delete");
+ discarded = true;
}
-/** Leaves it alone and opens it, which is what every Cancel on these screens does. */
+/** Leaves it alone and opens it, which is what every Cancel in the wizard does. */
export function keepExistingData(): Promise<void> {
return server.post("setup/existing/keep");
}
+
+/**
+ * Whether there is still a knowledge base behind the wizard.
+ *
+ * What the start of the wizard reported, minus anything erased since. The flag is not re-read from
+ * the server because the two answers cannot disagree: the only erasure this page can cause is the
+ * one below.
+ */
+export function hasExistingData(): boolean {
+ return !discarded && window.glob.hasExistingData === true;
+}
+
+let discarded = false;
diff --git a/apps/client/src/setup_unlock.tsx b/apps/client/src/setup_unlock.tsx
new file mode 100644
index 0000000000..bfc307a82e
--- /dev/null
+++ b/apps/client/src/setup_unlock.tsx
@@ -0,0 +1,94 @@
+import { useState } from "preact/hooks";
+
+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 FormGroup from "./widgets/react/FormGroup";
+import FormTextBox from "./widgets/react/FormTextBox";
+import Icon from "./widgets/react/Icon";
+import SetupPage from "./widgets/react/SetupPage";
+
+/**
+ * The password 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.
+ *
+ * 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.
+ *
+ * @param onUnlocked the wizard may carry on.
+ *
+ * @module
+ */
+export default function SetupUnlock({ onUnlocked }: { onUnlocked: () => void }) {
+ const [ password, setPassword ] = useState("");
+ const [ wrong, setWrong ] = useState(false);
+ const [ busy, setBusy ] = useState(false);
+
+ async function unlock() {
+ setBusy(true);
+ try {
+ const { authenticated, token } = await server.post<{ authenticated: boolean; token?: string }>(
+ "setup/auth", { password });
+
+ if (!authenticated || !token) {
+ setWrong(true);
+ return;
+ }
+
+ setSetupAuthToken(token);
+ onUnlocked();
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <SetupPage
+ className="setup-unlock"
+ title={t("setup.unlock-title")}
+ description={t("setup.unlock-description")}
+ illustration={<Icon icon="bx bx-lock-alt" className="illustration-icon" />}
+ footer={
+ <Button
+ text={t("setup.continue")}
+ kind="primary"
+ disabled={!password || busy}
+ onClick={() => void unlock()}
+ />
+ }
+ >
+ <form onSubmit={(e) => {
+ e.preventDefault();
+ if (password && !busy) {
+ void unlock();
+ }
+ }}>
+ <Card>
+ <CardSection>
+ <FormGroup
+ label={t("setup.unlock-password")} name="setupPassword"
+ error={wrong ? t("setup.wrong-password") : undefined}
+ >
+ <FormTextBox
+ type="password"
+ currentValue={password}
+ onChange={(value) => {
+ setPassword(value);
+ setWrong(false);
+ }}
+ autocomplete="current-password"
+ required
+ />
+ </FormGroup>
+ </CardSection>
+ </Card>
+ </form>
+ </SetupPage>
+ );
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index e9fd7b7c47..dc5ef256eb 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2054,6 +2054,14 @@
"default-content-language-description": "The language notes are written in unless one is set on the note itself, in the Basic Properties section. It affects features such as right-to-left alignment and which quotation marks typing produces.",
"default-content-language-auto": "Based on the application's language"
},
+ "database": {
+ "start_over_title": "Start over",
+ "start_over_description": "Switch to a new blank database, start again syncing with a new server or restore a backup. You will be prompted to backup your data before discarding the existing data.",
+ "start_over": "Start over",
+ "start_over_confirm": "Trilium will go back to the setup screen, where you can start a new knowledge base, restore a backup or sync from another device. You will be offered a backup of your current data first, and nothing is deleted until you choose one of those. Continue?",
+ "start_over_pending": "The setup screen will appear the next time this server is restarted. Restart the server when you are ready, or cancel below to leave everything as it is.",
+ "start_over_cancel": "Cancel start over"
+ },
"backup": {
"title": "Backup",
"automatic_backup": "Automatic backup",
@@ -3664,6 +3672,7 @@
"create-new-document-options-empty-description": "Start with a blank knowledge base. You can import demo notes later.",
"create-new-document-title": "Preparing your knowledge base",
"create-new-document-description": "This will only take a moment.",
+ "create-new-document-failed": "Your knowledge base could not be created",
"sync-illustration-this-device": "This device",
"sync-illustration-desktop-app": "Your desktop app",
"sync-illustration-server": "Your server",
@@ -3696,9 +3705,10 @@
"continue": "Continue",
"your-ip-addresses": "Addresses for this device",
"existing-data": "Save your existing data?",
+ "existing-data-description": "Your current knowledge base is still here and stays untouched until you choose what to do next. This is a good moment to take a copy of it.",
"existing-data-back-up": "Yes, create a backup",
- "existing-data-delete": "No, delete everything",
- "existing-data-delete-warning": "Once you press Continue, the existing knowledge base is permanently erased. There is no way to recover it afterwards.",
+ "existing-data-skip": "No, continue without a backup",
+ "existing-data-skip-warning": "Nothing is deleted yet. Your knowledge base is only replaced once you choose to create a new one, restore a backup or sync from another device.",
"existing-data-cancel": "Cancel",
"existing-data-backing-up": "Backing up",
"existing-data-backing-up-message": "Creating a backup...",
@@ -3731,8 +3741,12 @@
"backup-downloaded": "The download has completed. Press \"Finish\" to return to the application.",
"backup-download-failed": "The download did not finish.",
"backup-finish": "Finish",
- "existing-data-erase-confirm": "Now the existing data will be discarded. Make sure you keep the backup file somewhere safe. Continue?",
- "existing-data-delete-failed": "The existing knowledge base could not be deleted.",
+ "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-title": "Unlock your knowledge base",
+ "unlock-description": "This device already holds a knowledge base. Enter the password you use to log in, so that only you can decide what happens to it.",
+ "unlock-password": "Password",
+ "keep-existing": "Continue to the app",
+ "keep-existing-description": "Leave everything as it is and go back to your knowledge base.",
"existing-data-keep-failed": "The existing knowledge base could not be reopened.",
"restore-from-backup": "Restore from backup",
"restore-from-backup-description": "Continue using an existing knowledge base, restored from a backup file.",
diff --git a/apps/client/src/widgets/type_widgets/ContentWidget.tsx b/apps/client/src/widgets/type_widgets/ContentWidget.tsx
index 3329a5ad09..af9cffad73 100644
--- a/apps/client/src/widgets/type_widgets/ContentWidget.tsx
+++ b/apps/client/src/widgets/type_widgets/ContentWidget.tsx
@@ -10,6 +10,7 @@ import SpellcheckSettings from "./options/spellcheck";
import PasswordSettings from "./options/password";
import EtapiSettings from "./options/etapi";
import BackupSettings from "./options/backup";
+import DatabaseSettings from "./options/database";
import SyncOptions from "./options/sync";
import DesktopSettings from "./options/desktop";
import OtherSettings from "./options/other";
@@ -21,7 +22,7 @@ import "./ContentWidget.css";
import { t } from "../../services/i18n";
import BackendLog from "./code/BackendLog";
-export type OptionPages = "_optionsAppearance" | "_optionsShortcuts" | "_optionsTextNotes" | "_optionsCodeNotes" | "_optionsContentManager" | "_optionsMedia" | "_optionsSpellcheck" | "_optionsPassword" | "_optionsEtapi" | "_optionsBackup" | "_optionsSync" | "_optionsDesktop" | "_optionsOther" | "_optionsLocalization" | "_optionsSecurity" | "_optionsAdvanced" | "_optionsLlm";
+export type OptionPages = "_optionsAppearance" | "_optionsShortcuts" | "_optionsTextNotes" | "_optionsCodeNotes" | "_optionsContentManager" | "_optionsMedia" | "_optionsSpellcheck" | "_optionsPassword" | "_optionsEtapi" | "_optionsBackup" | "_optionsDatabase" | "_optionsSync" | "_optionsDesktop" | "_optionsOther" | "_optionsLocalization" | "_optionsSecurity" | "_optionsAdvanced" | "_optionsLlm";
const CONTENT_WIDGETS: Record<OptionPages | "_backendLog", (props: TypeWidgetProps) => JSX.Element> = {
_optionsAppearance: AppearanceSettings,
@@ -34,6 +35,7 @@ const CONTENT_WIDGETS: Record<OptionPages | "_backendLog", (props: TypeWidgetPro
_optionsPassword: PasswordSettings,
_optionsEtapi: EtapiSettings,
_optionsBackup: BackupSettings,
+ _optionsDatabase: DatabaseSettings,
_optionsSync: SyncOptions,
_optionsDesktop: DesktopSettings,
_optionsOther: OtherSettings,
diff --git a/apps/client/src/widgets/type_widgets/options/database.css b/apps/client/src/widgets/type_widgets/options/database.css
new file mode 100644
index 0000000000..8f2ddd53ff
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/database.css
@@ -0,0 +1,17 @@
+.options-section.start-over {
+ .start-over-actions {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 12px;
+ }
+
+ /* Coloured like every other action that cannot be taken back, so it is recognised before it is
+ read rather than after. */
+ .start-over-button {
+ color: var(--dropdown-item-icon-destructive-color);
+ }
+
+ .start-over-pending {
+ margin-top: 12px;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
new file mode 100644
index 0000000000..5bfd12ed8c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
@@ -0,0 +1,116 @@
+import { render } from "preact";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// t() returns the key so assertions are deterministic and not tied to English text.
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+const setupMode = vi.hoisted(() => ({
+ canBootToSetup: vi.fn(() => true),
+ startOver: vi.fn(async () => "restarting" as string),
+ isStartOverPending: vi.fn(async () => false),
+ cancelStartOver: vi.fn(async () => {})
+}));
+vi.mock("../../../services/setup_mode", () => setupMode);
+
+// The page header renders the note's own title, which needs a note context this spec has no use for.
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => null }));
+
+import DatabaseSettings from "./database";
+
+let container: HTMLDivElement;
+
+/** Preact flushes effects and state through the microtask queue plus a frame. */
+const settle = () => vi.advanceTimersByTimeAsync(50);
+
+function renderPage() {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ render(<DatabaseSettings />, container);
+
+ return container;
+}
+
+/** By name rather than by label: one label is a prefix of the other. */
+function button(name: string): HTMLButtonElement | null {
+ return container.querySelector<HTMLButtonElement>(`button[name='${name}']`);
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ setupMode.canBootToSetup.mockReset().mockReturnValue(true);
+ setupMode.startOver.mockReset().mockResolvedValue("restarting");
+ setupMode.isStartOverPending.mockReset().mockResolvedValue(false);
+ setupMode.cancelStartOver.mockReset().mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe("starting over from Options", () => {
+ it("offers the button, and asks nothing of its own before handing over", async () => {
+ renderPage();
+ await settle();
+
+ // The confirmation is the operating system's or the browser's, not one of this page's.
+ expect(container.querySelector(".start-over-pending")).toBeNull();
+
+ button("start-over-button")?.click();
+ await settle();
+
+ expect(setupMode.startOver).toHaveBeenCalled();
+ });
+
+ it("does not ask a build that restarts itself whether anything is pending", async () => {
+ // There is nothing to wait for: the request is acted on by the restart it causes.
+ renderPage();
+ await settle();
+
+ expect(setupMode.isStartOverPending).not.toHaveBeenCalled();
+ });
+
+ it("says a request is standing where the restart is somebody else's to make", async () => {
+ setupMode.canBootToSetup.mockReturnValue(false);
+ setupMode.startOver.mockResolvedValue("pending");
+ renderPage();
+ await settle();
+
+ button("start-over-button")?.click();
+ await settle();
+
+ expect(container.querySelector(".start-over-pending")?.textContent)
+ .toContain("database.start_over_pending");
+ // The button that made it is gone, so it cannot be pressed twice over.
+ expect(button("start-over-button")).toBeNull();
+ });
+
+ it("takes it back, which is all a server owner can do until they restart", async () => {
+ setupMode.canBootToSetup.mockReturnValue(false);
+ setupMode.isStartOverPending.mockResolvedValue(true);
+ renderPage();
+ await settle();
+
+ // Read on arrival: the request outlives the page that made it, so reopening Options is
+ // otherwise no way to find out that one is waiting.
+ expect(container.querySelector(".start-over-pending")).not.toBeNull();
+
+ button("cancel-start-over-button")?.click();
+ await settle();
+
+ expect(setupMode.cancelStartOver).toHaveBeenCalled();
+ expect(container.querySelector(".start-over-pending")).toBeNull();
+ });
+
+ it("says nothing where the pending question cannot be answered", async () => {
+ setupMode.canBootToSetup.mockReturnValue(false);
+ setupMode.isStartOverPending.mockRejectedValue(new Error("no answer"));
+ renderPage();
+ await settle();
+
+ // What is lost is a notice; the button below it is what the page is for.
+ expect(container.querySelector(".start-over-pending")).toBeNull();
+ expect(button("start-over-button")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsx
new file mode 100644
index 0000000000..b07a3ad186
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/database.tsx
@@ -0,0 +1,108 @@
+import "./database.css";
+
+import { useEffect, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import {
+ canBootToSetup,
+ cancelStartOver,
+ isStartOverPending,
+ startOver
+} from "../../../services/setup_mode";
+import Admonition from "../../react/Admonition";
+import Button from "../../react/Button";
+import OptionsPageHeader from "./components/OptionsPageHeader";
+import OptionsSection from "./components/OptionsSection";
+
+/**
+ * What can be done to the knowledge base as a whole, rather than to anything inside it.
+ *
+ * One entry for now, and the one that needed a page of its own: starting over is neither a backup
+ * nor a setting, and it is the only thing in Options that leaves the application entirely.
+ */
+export default function DatabaseSettings() {
+ return (
+ <>
+ <OptionsPageHeader />
+ <StartOverSection />
+ </>
+ );
+}
+
+/**
+ * Going back to the setup screen, from where the knowledge base can be replaced.
+ *
+ * Two shapes, decided by whether the instance can restart itself. The desktop and the browser-only
+ * build go there and then, so the button is the whole of it. A server is restarted by whoever runs
+ * it, so the request outlives the page that made it, and the section has to say that a start-over is
+ * waiting and offer to call it off.
+ */
+function StartOverSection() {
+ const [ pending, setPending ] = useState(false);
+ const [ busy, setBusy ] = useState(false);
+
+ useEffect(() => {
+ // Only ever true where nothing acts on the request until a human restarts the server, which
+ // is also the only place the answer is worth waiting for.
+ if (canBootToSetup()) {
+ return;
+ }
+
+ void isStartOverPending().then(setPending).catch(() => {
+ // The section still works without knowing; the button is what matters here.
+ });
+ }, []);
+
+ async function begin() {
+ setBusy(true);
+ try {
+ setPending(await startOver() === "pending");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function cancel() {
+ setBusy(true);
+ try {
+ await cancelStartOver();
+ setPending(false);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <OptionsSection title={t("database.start_over_title")} className="start-over">
+ <p className="options-section-description">{t("database.start_over_description")}</p>
+
+ {pending ? (
+ <>
+ <Admonition type="warning" className="start-over-pending">
+ {t("database.start_over_pending")}
+ </Admonition>
+
+ <div className="start-over-actions">
+ <Button
+ name="cancel-start-over-button"
+ text={t("database.start_over_cancel")}
+ disabled={busy}
+ onClick={() => void cancel()}
+ />
+ </div>
+ </>
+ ) : (
+ <div className="start-over-actions">
+ <Button
+ name="start-over-button"
+ className="start-over-button"
+ icon="bx bx-reset"
+ text={t("database.start_over")}
+ disabled={busy}
+ onClick={() => void begin()}
+ />
+ </div>
+ )}
+ </OptionsSection>
+ );
+}
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index 31c72ddb99..524aaf6bef 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -698,6 +698,11 @@ describe("preload script", () => {
await dialog().pickDirectory();
expect(ipcRendererInvoked).toContainEqual({ channel: "dialog-pick-directory", args: [undefined] });
});
+
+ it("confirmStartOver invokes its IPC channel, passing nothing it could steer", async () => {
+ await dialog().confirmStartOver();
+ expect(ipcRendererInvoked).toContainEqual({ channel: "dialog-confirm-start-over", args: [] });
+ });
});
describe("restore", () => {
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index c3222ce66e..eabfb28f7e 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -238,6 +238,9 @@ contextBridge.exposeInMainWorld("electronApi", {
dialog: {
pickDirectory(opts?: { defaultPath?: string }) {
return ipcRenderer.invoke("dialog-pick-directory", opts);
+ },
+ confirmStartOver(): Promise<boolean> {
+ return ipcRenderer.invoke("dialog-confirm-start-over");
}
},
diff --git a/apps/desktop/src/services/dialog.spec.ts b/apps/desktop/src/services/dialog.spec.ts
index 3f13be8da9..1bccea6b9a 100644
--- a/apps/desktop/src/services/dialog.spec.ts
+++ b/apps/desktop/src/services/dialog.spec.ts
@@ -5,13 +5,17 @@ const electronMock = vi.hoisted(() => ({
handlers: new Map<string, (...args: unknown[]) => unknown>(),
handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => electronMock.handlers.set(channel, handler)),
showOpenDialog: vi.fn<(...args: unknown[]) => Promise<{ canceled: boolean; filePaths: string[] }>>(),
+ showMessageBox: vi.fn<(...args: unknown[]) => Promise<{ response: number }>>(),
getFocusedWindow: vi.fn<() => object | null>(() => ({}))
}));
vi.mock("electron", () => ({
default: {
ipcMain: { handle: electronMock.handle },
- dialog: { showOpenDialog: electronMock.showOpenDialog },
+ dialog: {
+ showOpenDialog: electronMock.showOpenDialog,
+ showMessageBox: electronMock.showMessageBox
+ },
BrowserWindow: { getFocusedWindow: electronMock.getFocusedWindow }
}
}));
@@ -65,3 +69,35 @@ describe("desktop native directory picker", () => {
expect(electronMock.showOpenDialog).not.toHaveBeenCalled();
});
});
+
+describe("the native confirmation before starting over", () => {
+ const confirmStartOver = () =>
+ electronMock.handlers.get("dialog-confirm-start-over")?.({}) as Promise<boolean>;
+
+ beforeEach(() => {
+ electronMock.handlers.clear();
+ vi.clearAllMocks();
+ setupDialogHandlers();
+ });
+
+ it("only agrees when the second button is the one that was pressed", async () => {
+ electronMock.showMessageBox.mockResolvedValue({ response: 1 });
+ expect(await confirmStartOver()).toBe(true);
+
+ electronMock.showMessageBox.mockResolvedValue({ response: 0 });
+ expect(await confirmStartOver()).toBe(false);
+ });
+
+ it("defaults to cancelling, and offers no way to stop being asked", async () => {
+ // A note script can pop this dialog; what it must never be able to do is get past it, or
+ // wear the user down until they stop seeing it.
+ electronMock.showMessageBox.mockResolvedValue({ response: 0 });
+ await confirmStartOver();
+
+ const [ options ] = electronMock.showMessageBox.mock.calls[0] as [ {
+ type: string; defaultId: number; cancelId: number; checkboxLabel?: string;
+ } ];
+ expect(options).toMatchObject({ type: "warning", defaultId: 0, cancelId: 0 });
+ expect(options.checkboxLabel).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/services/dialog.ts b/apps/desktop/src/services/dialog.ts
index ac6d192011..622372c92f 100644
--- a/apps/desktop/src/services/dialog.ts
+++ b/apps/desktop/src/services/dialog.ts
@@ -29,4 +29,20 @@ export function setupDialogHandlers() {
return { status: "selected", path: filePaths[0] };
});
+
+ electron.ipcMain.handle("dialog-confirm-start-over", async (): Promise<boolean> => {
+ // Cancel is both the default and what Escape picks: the other button leads to a screen from
+ // which the knowledge base can be replaced, and nobody arrives here by accident twice.
+ const { response } = await electron.dialog.showMessageBox({
+ type: "warning",
+ buttons: [ t("start-over-dialog.cancel"), t("start-over-dialog.confirm") ],
+ defaultId: 0,
+ cancelId: 0,
+ title: t("start-over-dialog.title"),
+ message: t("start-over-dialog.message"),
+ detail: t("start-over-dialog.detail")
+ });
+
+ return response === 1;
+ });
}
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 326173b5fa..97abdede75 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -302,6 +302,7 @@
"multi-factor-authentication-title": "MFA",
"etapi-title": "ETAPI",
"backup-title": "Backup",
+ "database-title": "Database",
"sync-title": "Sync",
"other": "Other",
"advanced-title": "Advanced",
@@ -511,5 +512,12 @@
"sql-console-warning": "The SQL console allows executing arbitrary SQL queries against the database.",
"lan-access": "network access",
"lan-access-warning": "The app and your shared notes will be served over the network — reachable from a browser on this computer and from other devices on your local network."
+ },
+ "start-over-dialog": {
+ "title": "Start over",
+ "message": "Restart Trilium and go back to the setup screen?",
+ "detail": "You will be offered a backup of your current knowledge base first. Nothing is deleted until you choose to create a new knowledge base, restore a backup or sync from another device.\n\nDo not continue if a script or an unfamiliar note prompted you to.",
+ "cancel": "Cancel",
+ "confirm": "Restart & start over"
}
}
diff --git a/apps/server/src/routes/api/setup_restore.ts b/apps/server/src/routes/api/setup_restore.ts
index 477ef91e49..a4b8fd22c7 100644
--- a/apps/server/src/routes/api/setup_restore.ts
+++ b/apps/server/src/routes/api/setup_restore.ts
@@ -16,11 +16,12 @@ import {
* The setup screen's way back from a backup: list what is already on disk, take a file that is not,
* and restore whichever the user picks.
*
- * Every endpoint here is reachable without authentication, because before the database exists there
- * is nobody to authenticate — the same footing the rest of the setup wizard stands on. What that
- * costs is bounded deliberately: one upload at a time, a ceiling on its size, a session that expires,
- * and a path from the listing that is checked against the backup directories rather than taken at
- * its word.
+ * Every endpoint here is reachable without authentication on a first run, because before a database
+ * exists there is nobody to authenticate — the same footing the rest of the setup wizard stands on.
+ * What that costs is bounded deliberately: one upload at a time, a ceiling on its size, a session
+ * that expires, and a path from the listing that is checked against the backup directories rather
+ * than taken at its word. Where a knowledge base IS sitting behind the wizard there is somebody to
+ * authenticate, and `checkSetupAuth` asks for them: a restore replaces that database.
*
* @module
*/
diff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.ts
index f3443b52cc..7a88f23e35 100644
--- a/apps/server/src/routes/index.ts
+++ b/apps/server/src/routes/index.ts
@@ -40,8 +40,14 @@ export function bootstrap(req: Request, res: Response) {
// global flag told every such browser it was already logged in, so it skipped
// login and then had every API call rejected with "Logged in session not found".
const isElectronRenderer = isInternalElectronRequest(req);
+ const sharedItems = getSharedBootstrapItems(assetPath, isDbInitialized);
const commonItems = {
- ...getSharedBootstrapItems(assetPath, isDbInitialized),
+ ...sharedItems,
+ // 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.
+ setupAuthRequired: sharedItems.setupAuthRequired && !isElectronRenderer && !noAuthentication,
baseApiUrl: "api/",
appPath,
isStandalone: false,
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 42b5c9198a..884e5b430c 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -62,15 +62,17 @@ function register(app: express.Application) {
// Restoring a backup, which only the setup screen offers: `checkAppNotInitialized` is what keeps
// it from ever running against a live database, since before the database exists there is no
- // session to authenticate against and the whole wizard stands unauthenticated. None of these may
- // be transactional — the swap detaches the database, which a wrapping transaction would be in the
+ // session to authenticate against and the whole wizard stands unauthenticated. Where a knowledge
+ // base is sitting behind the wizard there IS something to authenticate against, and
+ // `checkSetupAuth` asks for it — a restore replaces that database. None of these may be
+ // transactional — the swap detaches the database, which a wrapping transaction would be in the
// middle of.
- asyncRoute(PST, "/api/setup/restore/upload/begin", [auth.checkAppNotInitialized], setupRestoreRoute.beginUpload, apiResultHandler);
- asyncRoute(PST, "/api/setup/restore/upload/:uploadId/chunk", [auth.checkAppNotInitialized], setupRestoreRoute.uploadChunk, apiResultHandler);
- asyncRoute(GET, "/api/setup/restore/upload/:uploadId", [auth.checkAppNotInitialized], setupRestoreRoute.uploadStatus, apiResultHandler);
- asyncRoute(PST, "/api/setup/restore/upload/:uploadId/finish", [auth.checkAppNotInitialized], setupRestoreRoute.finishUpload, apiResultHandler);
- asyncRoute(DEL, "/api/setup/restore/upload/:uploadId", [auth.checkAppNotInitialized], setupRestoreRoute.abortUpload, apiResultHandler);
- asyncRoute(PST, "/api/setup/restore/start", [auth.checkAppNotInitialized], setupRestoreRoute.start, apiResultHandler);
+ asyncRoute(PST, "/api/setup/restore/upload/begin", [auth.checkAppNotInitialized, auth.checkSetupAuth], setupRestoreRoute.beginUpload, apiResultHandler);
+ asyncRoute(PST, "/api/setup/restore/upload/:uploadId/chunk", [auth.checkAppNotInitialized, auth.checkSetupAuth], setupRestoreRoute.uploadChunk, apiResultHandler);
+ asyncRoute(GET, "/api/setup/restore/upload/:uploadId", [auth.checkAppNotInitialized, auth.checkSetupAuth], setupRestoreRoute.uploadStatus, apiResultHandler);
+ asyncRoute(PST, "/api/setup/restore/upload/:uploadId/finish", [auth.checkAppNotInitialized, auth.checkSetupAuth], setupRestoreRoute.finishUpload, apiResultHandler);
+ asyncRoute(DEL, "/api/setup/restore/upload/:uploadId", [auth.checkAppNotInitialized, auth.checkSetupAuth], setupRestoreRoute.abortUpload, apiResultHandler);
+ asyncRoute(PST, "/api/setup/restore/start", [auth.checkAppNotInitialized, auth.checkSetupAuth], setupRestoreRoute.start, apiResultHandler);
// Readable throughout, including once the restore has succeeded: that is how the screen learns it
// is over and the application can be opened.
asyncRoute(GET, "/api/setup/restore/status", [], setupRestoreRoute.status, apiResultHandler);
@@ -103,6 +105,7 @@ function register(app: express.Application) {
checkApiAuth: auth.checkApiAuth,
checkApiAuthOrElectron: auth.checkApiAuthOrElectron,
checkAppNotInitialized: auth.checkAppNotInitialized,
+ checkSetupAuth: auth.checkSetupAuth,
checkCredentials: auth.checkCredentials,
loginRateLimiter,
uploadMiddlewareWithErrorHandling,
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index 803bd7ac7d..a9070d2be2 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -1,7 +1,8 @@
-import { attributes, options, password as passwordService, password_encryption as passwordEncryptionService } from "@triliumnext/core";
+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 { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import auth, { refreshAuth, verifyLoginCredentials } from "./auth";
import { cls } from "@triliumnext/core";
@@ -545,3 +546,91 @@ describe("Auth", () => {
});
});
}, 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", () => {
+ /** A request carrying the token, or nothing, plus what the middleware did with it. */
+ function callGate({ token, internalElectron = false }: { token?: string; internalElectron?: boolean } = {}) {
+ const req = { headers: token ? { "trilium-setup-auth": token } : {}, method: "POST", path: "/api/setup/existing/delete" } 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.checkSetupAuth(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 });
+ });
+});
diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.ts
index 95b1178595..353e8ca62f 100644
--- a/apps/server/src/services/auth.ts
+++ b/apps/server/src/services/auth.ts
@@ -1,4 +1,4 @@
-import { attributes, options, password as passwordService, password_encryption as passwordEncryptionService } from "@triliumnext/core";
+import { attributes, 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";
@@ -177,6 +177,32 @@ function checkAppNotInitialized(req: Request, res: Response, next: NextFunction)
}
}
+/**
+ * Guards the setup routes that could replace or erase a knowledge base sitting behind the wizard.
+ *
+ * The rest of the authentication in this file stands down while the database is uninitialized, which
+ * is exactly what an instance in setup mode reports, so nothing else here covers these routes. See
+ * `setup_auth` in core for why the session cannot be used and what is used instead.
+ *
+ * Three ways past it, all of them cases where there is nothing to guard against: an instance with no
+ * knowledge base behind the wizard, which is the ordinary first run; the desktop's own renderer,
+ * which reaches the server over the custom protocol and is the application itself; and an instance
+ * configured for no authentication, which has already said it trusts whoever can reach it.
+ */
+function checkSetupAuth(req: Request, res: Response, next: NextFunction) {
+ if (!isSetupAuthRequired() || isInternalElectronRequest(req) || noAuthentication) {
+ return next();
+ }
+
+ const token = req.headers["trilium-setup-auth"];
+ if (typeof token !== "string" || !isSetupAuthorized(token)) {
+ reject(req, res, "The existing knowledge base has not been unlocked.");
+ return;
+ }
+
+ next();
+}
+
function checkEtapiToken(req: Request, res: Response, next: NextFunction) {
if (etapiTokenService.isValidAuthHeader(req.headers.authorization)) {
next();
@@ -260,6 +286,7 @@ export default {
checkPasswordSet,
checkPasswordNotSet,
checkAppNotInitialized,
+ checkSetupAuth,
checkApiAuthOrElectron,
checkEtapiToken,
checkCredentials
diff --git a/apps/server/src/services/setup_marker.spec.ts b/apps/server/src/services/setup_marker.spec.ts
index 8f88c76102..c611546daf 100644
--- a/apps/server/src/services/setup_marker.spec.ts
+++ b/apps/server/src/services/setup_marker.spec.ts
@@ -1,7 +1,8 @@
import { SETUP_MARKER_FILE_NAME } from "@triliumnext/commons";
+import { getSql } from "@triliumnext/core";
import fs from "fs";
import path from "path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, describe, expect, it } from "vitest";
import dataDirs from "./data_dir.js";
import { consumeSetupMarker, setupPlatform } from "./setup_marker.js";
@@ -51,4 +52,47 @@ describe("writing the marker", () => {
// Removing what is not there is how a cancelled request ends, and is not a failure.
await expect(setupPlatform.removeMarker()).resolves.toBeUndefined();
});
+
+ it("says whether one is waiting, which is all an owner has to go on until they restart", async () => {
+ await expect(setupPlatform.hasMarker()).resolves.toBe(false);
+
+ await setupPlatform.writeMarker({ lang: "en" });
+ await expect(setupPlatform.hasMarker()).resolves.toBe(true);
+
+ await setupPlatform.removeMarker();
+ await expect(setupPlatform.hasMarker()).resolves.toBe(false);
+ });
});
+
+/**
+ * Last in the file on purpose: this one really does erase the database, which for the rest of this
+ * process means the fixture every other spec here would have been sharing.
+ */
+describe("erasing the database the wizard was booted away from", () => {
+ afterAll(() => {
+ // A `document.db` left behind in the test data directory is found by later runs, which then
+ // fail on a database that has no schema. Closed before it is removed: on Windows an open
+ // handle is enough to make the file undeletable, which is the very reason the erase this
+ // spec covers detaches first.
+ getSql().detachConnection();
+ for (const file of documentFiles()) {
+ fs.rmSync(file, { force: true });
+ }
+ });
+
+ it("leaves an empty database open behind it, which is what the rest of the wizard writes to", async () => {
+ await setupPlatform.removeDatabase();
+
+ // Creating a document, taking a pushed sync seed and converging a sync all run against this
+ // connection moments later. Detaching without putting one back failed every one of them
+ // with "DB not open", on a screen with no way of saying so.
+ expect(getSql().getValue("SELECT 1")).toBe(1);
+ expect(fs.existsSync(dataDirs.DOCUMENT_PATH)).toBe(true);
+ });
+});
+
+function documentFiles(): string[] {
+ const document = dataDirs.DOCUMENT_PATH;
+
+ return [ document, `${document}-wal`, `${document}-shm` ];
+}
diff --git a/apps/server/src/services/setup_marker.ts b/apps/server/src/services/setup_marker.ts
index c0dd264a17..a4ce451dca 100644
--- a/apps/server/src/services/setup_marker.ts
+++ b/apps/server/src/services/setup_marker.ts
@@ -3,6 +3,7 @@ import { getLog, getSql, parseSetupMarker, type SetupPlatform } from "@triliumne
import fs from "fs";
import path from "path";
+import config from "./config.js";
import dataDirs from "./data_dir.js";
/**
@@ -61,6 +62,10 @@ export const setupPlatform: SetupPlatform = {
fs.writeFileSync(markerPath(), JSON.stringify(marker, null, 4), "utf8");
},
+ async hasMarker() {
+ return fs.existsSync(markerPath());
+ },
+
async removeMarker() {
fs.rmSync(markerPath(), { force: true });
},
@@ -74,5 +79,11 @@ export const setupPlatform: SetupPlatform = {
for (const file of [ document, `${document}-wal`, `${document}-shm` ]) {
fs.rmSync(file, { force: true });
}
+
+ // And an empty one opened in its place, because everything the wizard does from here writes
+ // to a database: creating a document, taking a pushed sync seed, converging a sync. Opening
+ // a path with nothing at it creates it empty, which is the state a first run begins in — so
+ // this leaves the instance exactly where a machine that had never run Trilium would be.
+ getSql().attachFromFile(document, config.General.readOnly);
}
};
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
index c6a0e90db2..911218f878 100644
--- a/apps/standalone/src/lightweight/browser_routes.spec.ts
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -254,7 +254,7 @@ describe("route wrapper branches (via controlled handlers)", () => {
it("provides no-op middleware and an init guard", async () => {
buildRouter();
// No-op middleware stubs do nothing and never throw.
- for (const mw of [ctx.checkApiAuth, ctx.checkApiAuthOrElectron, ctx.checkCredentials, ctx.loginRateLimiter, ctx.uploadMiddlewareWithErrorHandling, ctx.importMiddlewareWithErrorHandling, ctx.csrfMiddleware]) {
+ for (const mw of [ctx.checkApiAuth, ctx.checkApiAuthOrElectron, ctx.checkSetupAuth, ctx.checkCredentials, ctx.loginRateLimiter, ctx.uploadMiddlewareWithErrorHandling, ctx.importMiddlewareWithErrorHandling, ctx.csrfMiddleware]) {
expect(() => (mw as () => void)()).not.toThrow();
}
// checkAppNotInitialized throws while the DB is initialized...
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index ff2be3f160..06e7fdfcfb 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -288,6 +288,10 @@ export function registerRoutes(router: BrowserRouter): void {
checkApiAuth: noopMiddleware,
checkApiAuthOrElectron: noopMiddleware,
checkAppNotInitialized,
+ // Nothing reaches this build but the page it is part of: there is no port, no session and
+ // nobody else who could ask. The wizard's password gate exists for instances served over a
+ // network, which this one never is.
+ checkSetupAuth: noopMiddleware,
checkCredentials: noopMiddleware,
loginRateLimiter: noopMiddleware,
uploadMiddlewareWithErrorHandling: noopMiddleware,
@@ -321,6 +325,10 @@ function bootstrapRoute(req: { query: Record<string, string | undefined> }): Boo
const isDbInitialized = sql_init.isDbInitialized();
const commonItems = {
...getSharedBootstrapItems(assetPath, isDbInitialized),
+ // The setup wizard's password gate exists for instances served over a network. This one is
+ // 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,
isDev: import.meta.env.DEV,
isStandalone: true,
// A window torn off into its own popup carries `?extraWindow`, same as on the server. It has
diff --git a/apps/standalone/src/lightweight/setup_marker.ts b/apps/standalone/src/lightweight/setup_marker.ts
index e380a9f402..4f89e5a26e 100644
--- a/apps/standalone/src/lightweight/setup_marker.ts
+++ b/apps/standalone/src/lightweight/setup_marker.ts
@@ -41,6 +41,17 @@ export async function consumeSetupMarker(): Promise<SetupMarker | null> {
return parseSetupMarker(raw);
}
+/** Whether one is lying there waiting to be read, which on this platform is only ever briefly. */
+export async function hasSetupMarker(): Promise<boolean> {
+ try {
+ const root = await navigator.storage.getDirectory();
+ await root.getFileHandle(SETUP_MARKER_FILE_NAME);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
/** Leaves the marker that makes the next start the wizard. */
export async function writeSetupMarker(marker: SetupMarker): Promise<void> {
const root = await navigator.storage.getDirectory();
diff --git a/apps/standalone/src/lightweight/sql_provider.spec.ts b/apps/standalone/src/lightweight/sql_provider.spec.ts
index 0b1520f0d8..ba841223aa 100644
--- a/apps/standalone/src/lightweight/sql_provider.spec.ts
+++ b/apps/standalone/src/lightweight/sql_provider.spec.ts
@@ -90,6 +90,28 @@ describe("BrowserSqlProvider unsupported operations", () => {
});
});
+/**
+ * What the SQL service reaches for when it has to let go of the database: erasing the knowledge base
+ * from the setup wizard replaces the pool entry underneath, and the service's own prepared
+ * statements belong to the connection being closed. Going through `detachConnection` is what drops
+ * them; a provider that cannot be detached would send it straight at this one instead, leaving them
+ * behind for the next request to use against a database that is gone.
+ */
+describe("BrowserSqlProvider detaching", () => {
+ it("lets go of the database and says so, which is how the service knows to stop asking", () => {
+ const own = newProviderWithModule();
+ own.loadFromMemory();
+ expect(own.isAttached()).toBe(true);
+
+ own.detach();
+
+ expect(own.isAttached()).toBe(false);
+ // What the service checks before detaching a second time, on its way to a restore that
+ // follows an erasure.
+ expect(() => own.detach()).not.toThrow();
+ });
+});
+
// Statements are cached by SQL string and raw()/pluck() flags are sticky on the
// cached instance, so each mode-sensitive assertion uses a distinct query string.
describe("WasmStatement reads and writes", () => {
diff --git a/apps/standalone/src/lightweight/sql_provider.ts b/apps/standalone/src/lightweight/sql_provider.ts
index acffe57eb6..7aa00c48d2 100644
--- a/apps/standalone/src/lightweight/sql_provider.ts
+++ b/apps/standalone/src/lightweight/sql_provider.ts
@@ -625,6 +625,22 @@ export default class BrowserSqlProvider implements DatabaseProvider {
this.sahPoolDbName = undefined;
}
+ /**
+ * Lets go of the database so the pool entry behind it can be replaced or unlinked.
+ *
+ * The same thing as {@link close} here, since there is no file handle to release beyond the
+ * connection itself. It exists under this name so the erase and the swap can go through the SQL
+ * service, which holds prepared statements of its own that belong to the connection being let
+ * go of and have to be dropped with it.
+ */
+ detach(): void {
+ this.close();
+ }
+
+ isAttached(): boolean {
+ return this.db !== undefined;
+ }
+
/**
* Get the number of rows changed by the last INSERT, UPDATE, or DELETE statement.
*/
diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.ts
index 84c50cebf5..9fd06138dd 100644
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@ -282,6 +282,7 @@ async function initialize(): Promise<void> {
coreModule = await import("@triliumnext/core");
const {
consumeSetupMarker,
+ hasSetupMarker,
removeSetupMarker,
writeSetupMarker
} = await import('./lightweight/setup_marker.js');
@@ -310,6 +311,7 @@ async function initialize(): Promise<void> {
setupMarker: await consumeSetupMarker(),
setupPlatform: {
writeMarker: writeSetupMarker,
+ hasMarker: hasSetupMarker,
removeMarker: removeSetupMarker,
removeDatabase: removeStandaloneDatabase
},
@@ -423,7 +425,7 @@ async function dispatch(request: LocalRequest) {
*/
async function removeStandaloneDatabase(): Promise<void> {
const pool = sqlProvider?.sahPool;
- if (!sqlProvider || !pool) {
+ if (!sqlProvider || !pool || !coreModule) {
throw new Error("The database is not open, so there is nothing to erase.");
}
@@ -434,7 +436,10 @@ async function removeStandaloneDatabase(): Promise<void> {
} = await import('./lightweight/database_restore.js');
const live = await readCurrentDatabaseName();
- sqlProvider.close();
+ // Through the SQL service rather than straight at the provider: it holds prepared statements of
+ // its own, bound to the connection this closes, and the wizard goes on using the same worker
+ // afterwards — creating a document runs against the database opened below, in this very request.
+ coreModule.getSql().detachConnection();
try {
pool.unlink(live);
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index c4f46993fb..edf4c5b919 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -685,6 +685,16 @@ export interface ElectronDialogApi {
* before any path comes back.
*/
pickDirectory(opts?: { defaultPath?: string }): Promise<NativeDirectoryPickResult>;
+
+ /**
+ * Prompts a native message box before the application restarts into the setup screen, where the
+ * user may replace or erase their knowledge base.
+ *
+ * An OS dialog rather than one of the application's own, for the reason the security toggles use
+ * one: a note script can reach every dialog the app draws for itself, and this one guards the
+ * path to losing everything. It is never suppressible, so there is no "don't ask again" here.
+ */
+ confirmStartOver(): Promise<boolean>;
}
/**
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 347239feff..67df936e98 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -853,13 +853,22 @@ export type BootstrapDefinition = {
*/
syncInProgress?: boolean;
/**
- * Whether this is the instance's first run, with no database behind the setup screen.
+ * Whether there is still a knowledge base behind the setup screen.
*
- * Only meaningful while `dbInitialized` is `false`. It is `false` when setup was asked for by a
- * running instance through a `setup.json` marker, which means there is a database to go back to
- * and the wizard may offer to leave without doing anything.
+ * Only meaningful while `dbInitialized` is `false`. It is `true` when setup was asked for by a
+ * running instance through a `setup.json` marker and the user has not yet picked a path that
+ * replaces the database, which means there is something to offer a backup of and somewhere to
+ * go back to. A first run never has one, and neither does a wizard that has got past that point.
*/
- initialSetup?: boolean;
+ hasExistingData?: boolean;
+ /**
+ * Whether the setup screen has to be unlocked with the instance's own password before it will
+ * do anything.
+ *
+ * Only meaningful while `dbInitialized` is `false`, and only ever `true` where there is a
+ * knowledge base behind the wizard and a password that guarded it. See `setup_auth` in core.
+ */
+ setupAuthRequired?: 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.
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index a7d5b5c09e..fc3c67c74c 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -26,9 +26,12 @@ 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 {
+ enterSetupMode,
getSetupLanguage,
getSetupTargetScreen,
+ hasExistingData,
isInitialSetup,
isSetupRequested,
leaveSetupMode,
diff --git a/packages/trilium-core/src/routes/api/setup.spec.ts b/packages/trilium-core/src/routes/api/setup.spec.ts
index 07d395ef73..496d7ac883 100644
--- a/packages/trilium-core/src/routes/api/setup.spec.ts
+++ b/packages/trilium-core/src/routes/api/setup.spec.ts
@@ -1,8 +1,15 @@
-import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import appInfo from "../../services/app_info";
+import * as passwordService from "../../services/encryption/password";
import optionService from "../../services/options";
import setupService from "../../services/setup";
+import {
+ enterSetupMode,
+ initSetupPlatform,
+ leaveSetupMode,
+ markExistingDataDiscarded
+} from "../../services/setup_mode";
import sqlInit from "../../services/sql_init";
import { CoreApiTester } from "../../test/api_tester";
@@ -130,3 +137,91 @@ describe("Setup API (core)", () => {
expect(setupSync).toHaveBeenCalledWith("http://host", "", "pw", 0);
});
});
+
+describe("Setup API with a knowledge base behind the wizard (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ beforeEach(() => {
+ initSetupPlatform(platform);
+ enterSetupMode({ lang: "en" });
+ });
+
+ afterEach(() => {
+ leaveSetupMode();
+ Object.values(platform).forEach((fn) => fn.mockClear());
+ vi.restoreAllMocks();
+ });
+
+ it("erases it before creating a document, which is the moment the user commits to that", async () => {
+ const createInitial = vi.spyOn(sqlInit, "createInitialDatabase").mockResolvedValue(undefined);
+
+ const res = await api.post("/api/setup/new-document", { query: { skipDemoDb: "1" } });
+
+ expect(res.status).toBe(204);
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+ expect(createInitial).toHaveBeenCalled();
+ });
+
+ it("erases it before syncing from a server, for the same reason", async () => {
+ vi.spyOn(setupService, "setupSyncFromSyncServer").mockResolvedValue({ result: "success" });
+
+ const res = await api.post("/api/setup/sync-from-server", {
+ body: { syncServerHost: "http://host", syncProxy: "", password: "pw" }
+ });
+
+ expect(res.status).toBe(200);
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+ });
+
+ it("refuses a pushed sync seed until the local user has cleared the way for it", async () => {
+ // The push comes from the other device and carries nothing this instance issued, so what
+ // stands in for a token is the state: a schema is created here by wiping what is in the way.
+ const createForSync = vi.spyOn(sqlInit, "createDatabaseForSync").mockResolvedValue(undefined as never);
+
+ const refused = await api.post<{ error: string }>("/api/setup/sync-seed", {
+ body: { syncVersion: appInfo.syncVersion, options: [] }
+ });
+
+ expect(refused.status).toBe(400);
+ expect(createForSync).not.toHaveBeenCalled();
+
+ markExistingDataDiscarded();
+ const accepted = await api.post("/api/setup/sync-seed", {
+ body: { syncVersion: appInfo.syncVersion, options: [] }
+ });
+
+ expect(accepted.status).toBe(204);
+ expect(createForSync).toHaveBeenCalled();
+ });
+
+ it("withholds the stored sync server while the wizard is locked", async () => {
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
+ vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
+
+ const locked = await api.get<{ authRequired: boolean; syncServerHost?: string }>("/api/setup/status");
+
+ expect(locked.body.authRequired).toBe(true);
+ // A live instance's own sync server, on an endpoint anybody who can reach the port may read.
+ expect(locked.body.syncServerHost).toBeUndefined();
+ });
+
+ it("answers whether a start-over is waiting, and takes the request back", async () => {
+ platform.hasMarker.mockResolvedValue(true);
+ const pending = await api.get<{ requested: boolean }>("/api/setup/boot");
+ expect(pending.body.requested).toBe(true);
+
+ const cancelled = await api.delete("/api/setup/boot");
+ expect(cancelled.status).toBe(204);
+ expect(platform.removeMarker).toHaveBeenCalled();
+ });
+});
+
+/** A platform whose marker and database are only ever written down as having been asked for. */
+const platform = {
+ writeMarker: vi.fn(async () => {}),
+ hasMarker: vi.fn(async () => false),
+ removeMarker: vi.fn(async () => {}),
+ removeDatabase: vi.fn(async () => {})
+};
diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.ts
index f2ad8d403c..4b510b7ff6 100644
--- a/packages/trilium-core/src/routes/api/setup.ts
+++ b/packages/trilium-core/src/routes/api/setup.ts
@@ -3,12 +3,14 @@ import setupService from "../../services/setup.js";
import { getRunningSetupOperation, withSetupLock } from "../../services/setup_lock.js";
import {
deleteExistingData,
+ discardExistingData,
getExistingBackupDefaults,
getExistingBackupStatus,
keepExistingData,
startBackUpExistingData
} from "../../services/setup_existing.js";
-import { asSetupTargetScreen, getSetupPlatform } from "../../services/setup_mode.js";
+import { authenticateSetup, isSetupAuthRequired } 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";
import optionService from "../../services/options.js";
@@ -18,10 +20,14 @@ import { SetupSyncFromServerResponse } from "@triliumnext/commons";
function getStatus() {
const isInitialized = sqlInit.isDbInitialized();
const schemaExists = sqlInit.schemaExists();
+ // Whether the wizard has to be unlocked before it will do anything, which the screen has to know
+ // before it can ask. Says only that a password is wanted, never anything about the password.
+ const authRequired = isSetupAuthRequired();
return {
isInitialized,
schemaExists,
+ authRequired,
syncVersion: appInfo.syncVersion,
// What another tab, or this one after a reload, has already started. Lets the wizard say so
// rather than only finding out by being refused.
@@ -29,8 +35,10 @@ function getStatus() {
// After a FAILED sync-from-server attempt the sync options are already stored in
// the partial DB; expose them so the wizard can prefill the form when the user
// goes back to correct it (#10548). Pre-initialization only: this endpoint is
- // unauthenticated, and once the instance is live the host must not leak here.
- ...(schemaExists && !isInitialized
+ // unauthenticated, and once the instance is live the host must not leak here. Withheld
+ // too while the wizard is locked, since that is a live instance's own database sitting
+ // behind it, and its sync server is not for anyone who can reach the port to read.
+ ...(schemaExists && !isInitialized && !authRequired
? {
syncServerHost: optionService.getOptionOrNull("syncServerHost") ?? "",
syncProxy: optionService.getOptionOrNull("syncProxy") ?? ""
@@ -39,6 +47,20 @@ function getStatus() {
};
}
+/**
+ * Unlocks the wizard with the password of the knowledge base sitting behind it.
+ *
+ * Rate limited from the outside like every other password check. Answers with the token the rest of
+ * the setup routes want, or with a plain no: which of the two is the only thing it ever says about
+ * the password.
+ */
+async function authenticate(req: Request) {
+ const password = typeof req.body?.password === "string" ? req.body.password : "";
+ const token = await authenticateSetup(password);
+
+ return token ? { authenticated: true, token } : { authenticated: false };
+}
+
/**
* Asks the next start of this instance to come up in the setup wizard rather than in the app.
*
@@ -57,6 +79,24 @@ async function bootToSetup(req: Request) {
getLog().info(`Boot to setup requested${targetScreen ? ` for "${targetScreen}"` : ""}.`);
}
+/**
+ * Whether a request made earlier is still waiting to be acted on.
+ *
+ * Of interest only where the instance cannot restart itself: an owner who asked their server to
+ * start over restarts it by hand, and until they do, this is the difference between a request that
+ * was made and one that was not.
+ */
+async function isBootToSetupRequested() {
+ return { requested: await getSetupPlatform().hasMarker() };
+}
+
+/** Calls it off, for a request made and then thought better of before the restart. */
+async function cancelBootToSetup() {
+ await getSetupPlatform().removeMarker();
+
+ getLog().info("Boot to setup cancelled.");
+}
+
/**
* Starts backing up the database the wizard was booted away from.
*
@@ -105,31 +145,63 @@ async function keepExisting() {
await keepExistingData();
}
+/**
+ * The knowledge base the wizard was booted away from, where there is one, is erased here rather
+ * than on the way into the wizard: this is the first moment the user has committed to replacing it.
+ * Inside the lock, so the erasure and what replaces it are one operation as far as any other
+ * request is concerned.
+ */
async function setupNewDocument(req: Request) {
const { skipDemoDb } = req.query;
const locale = req.body?.locale;
- await withSetupLock("new-document", () => sqlInit.createInitialDatabase(skipDemoDb !== undefined, locale));
+ await withSetupLock("new-document", async () => {
+ await discardExistingData();
+ await sqlInit.createInitialDatabase(skipDemoDb !== undefined, locale);
+ });
}
/**
- * The lock covers fetching the seed and creating the schema, not the sync that follows: an
- * interrupted sync is resumed and retried across later requests, and a failed one has to leave the
- * user free to take another path instead.
+ * The lock covers erasing what was there, fetching the seed and creating the schema, not the sync
+ * that follows: an interrupted sync is resumed and retried across later requests, and a failed one
+ * has to leave the user free to take another path instead.
*/
function setupSyncFromServer(req: Request): Promise<SetupSyncFromServerResponse> {
const { syncServerHost, syncProxy, password, syncMaxBlobContentSize } = req.body;
const maxBlobContentSize = Number.isFinite(syncMaxBlobContentSize) && syncMaxBlobContentSize > 0 ? syncMaxBlobContentSize : 0;
- return withSetupLock("sync-from-server", () =>
- setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password, maxBlobContentSize));
+ return withSetupLock("sync-from-server", async () => {
+ await discardExistingData();
+
+ return setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password, maxBlobContentSize);
+ });
}
+/**
+ * Takes a database pushed by another desktop, which is how the sync-from-desktop path is fed.
+ *
+ * The push arrives from the other device and carries nothing this instance issued, so it cannot be
+ * held to the wizard's own password. What holds it instead is the state it is allowed to arrive in:
+ * a schema is created here by wiping whatever is in the way, so this is refused outright while there
+ * is still a knowledge base behind the wizard. The local user clears that themselves, on the screen
+ * that starts waiting for the push, and that screen is behind the password.
+ *
+ * A first run has nothing behind the wizard and is unaffected, which is the case this route exists
+ * for.
+ */
async function saveSyncSeed(req: Request) {
const { options, syncVersion } = req.body;
const log = getLog();
+ if (hasExistingData()) {
+ const message = "This instance still holds a knowledge base of its own. Choose \"Connect a desktop app\" on its setup screen first.";
+
+ log.error(`Refused a pushed sync seed: ${message}`);
+
+ return [ 400, { error: message } ];
+ }
+
if (appInfo.syncVersion !== syncVersion) {
const message = `Could not setup sync since local sync protocol version is ${appInfo.syncVersion} while remote is ${syncVersion}. To fix this issue, use same Trilium version on all instances.`;
@@ -189,7 +261,10 @@ function getSyncSeed() {
export default {
getStatus,
+ authenticate,
bootToSetup,
+ isBootToSetupRequested,
+ cancelBootToSetup,
backUpExisting,
existingBackupDefaults,
existingBackupStatus,
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 3453116c50..e40830afcf 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -64,6 +64,15 @@ interface SharedApiRoutesContext {
apiResultHandler: any;
checkApiAuthOrElectron: any;
checkAppNotInitialized: any;
+ /**
+ * Refuses a setup route where the wizard has a knowledge base behind it and has not been
+ * unlocked with that knowledge base's password.
+ *
+ * Supplied by the platform rather than shared, because what may skip it is: the desktop's own
+ * renderer arrives over a custom protocol and is trusted, an instance configured for no
+ * authentication has nothing to check against, and a browser-only build is served to no one.
+ */
+ checkSetupAuth: any;
loginRateLimiter: any;
checkCredentials: any;
uploadMiddlewareWithErrorHandling: any;
@@ -71,7 +80,7 @@ interface SharedApiRoutesContext {
csrfMiddleware: any;
}
-export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransaction, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, importMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {
+export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransaction, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkSetupAuth, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, importMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {
apiRoute(GET, '/api/tree', treeApiRoute.getTree);
apiRoute(PST, '/api/tree/load', treeApiRoute.load);
@@ -163,24 +172,37 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
// Not transactional: a status read needs no transaction, and one is unopenable during the moment
// a restore has the database detached — which is exactly when the wizard is polling hardest.
asyncRoute(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);
- asyncRoute(PST, "/api/setup/new-document", [checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler);
- asyncRoute(PST, "/api/setup/sync-from-server", [checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler);
+ // The password of the knowledge base the wizard is standing over, which is what unlocks every
+ // route below that could replace it. Rate limited like the application's own login.
+ asyncRoute(PST, "/api/setup/auth", [checkAppNotInitialized, loginRateLimiter], setupApiRoute.authenticate, apiResultHandler);
+ // Both erase the knowledge base the wizard was booted away from before they create anything, so
+ // neither may be wrapped in a transaction: erasing closes the connection such a transaction
+ // would belong to, and the browser then has nothing left to commit it against. Each creates its
+ // database inside transactions of its own, which is what the erasure has to stay outside of.
+ asyncRouteWithoutTransaction(PST, "/api/setup/new-document", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.setupNewDocument, apiResultHandler);
+ asyncRouteWithoutTransaction(PST, "/api/setup/sync-from-server", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.setupSyncFromServer, apiResultHandler);
route(GET, "/api/setup/sync-seed", [loginRateLimiter, checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);
+ // Pushed by the other device rather than asked for here, so it cannot carry a token of ours.
+ // Refused from inside instead, while there is a knowledge base to lose: see `saveSyncSeed`.
asyncRoute(PST, "/api/setup/sync-seed", [checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler);
- // The one setup route that belongs to a running instance rather than to one without a database:
- // it is how the app asks the next start to be the wizard.
+ // The setup routes that belong to a running instance rather than to one without a database:
+ // this is how the app asks the next start to be the wizard, and how it takes the request back.
+ // Authenticated like the rest of the running app, which is what keeps a passer-by from sending
+ // somebody else's instance to a screen that can erase it.
asyncApiRoute(PST, "/api/setup/boot", setupApiRoute.bootToSetup);
+ asyncApiRoute(GET, "/api/setup/boot", setupApiRoute.isBootToSetupRequested);
+ asyncApiRoute(DEL, "/api/setup/boot", setupApiRoute.cancelBootToSetup);
// What becomes of the database the wizard was booted away from. Guarded like the rest of setup,
// and refused again inside on an instance that has no such database. Not transactional: the
// backup runs for minutes, and keeping the database reopens it.
// Without a transaction, on every platform: the backup runs for minutes with the database in
// use, and erasing or keeping it closes the connection any transaction would belong to.
- asyncRouteWithoutTransaction(PST, "/api/setup/existing/backup", [checkAppNotInitialized], setupApiRoute.backUpExisting, apiResultHandler);
- asyncRouteWithoutTransaction(GET, "/api/setup/existing/backup-defaults", [checkAppNotInitialized], setupApiRoute.existingBackupDefaults, apiResultHandler);
- asyncRouteWithoutTransaction(GET, "/api/setup/existing/status", [checkAppNotInitialized], setupApiRoute.existingBackupStatus, apiResultHandler);
- asyncRouteWithoutTransaction(PST, "/api/setup/existing/delete", [checkAppNotInitialized], setupApiRoute.deleteExisting, apiResultHandler);
- asyncRouteWithoutTransaction(PST, "/api/setup/existing/keep", [checkAppNotInitialized], setupApiRoute.keepExisting, apiResultHandler);
+ asyncRouteWithoutTransaction(PST, "/api/setup/existing/backup", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.backUpExisting, apiResultHandler);
+ asyncRouteWithoutTransaction(GET, "/api/setup/existing/backup-defaults", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.existingBackupDefaults, apiResultHandler);
+ asyncRouteWithoutTransaction(GET, "/api/setup/existing/status", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.existingBackupStatus, apiResultHandler);
+ asyncRouteWithoutTransaction(PST, "/api/setup/existing/delete", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.deleteExisting, apiResultHandler);
+ asyncRouteWithoutTransaction(PST, "/api/setup/existing/keep", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.keepExisting, apiResultHandler);
asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);
asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);
diff --git a/packages/trilium-core/src/routes/setup_routes.spec.ts b/packages/trilium-core/src/routes/setup_routes.spec.ts
new file mode 100644
index 0000000000..b031343a1a
--- /dev/null
+++ b/packages/trilium-core/src/routes/setup_routes.spec.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+
+import { buildSharedApiRoutes } from "./index.js";
+
+/**
+ * How the setup routes are registered, rather than what they do.
+ *
+ * One property is worth pinning down here, because nothing else catches it and the failure it
+ * causes is remote from its cause: a handler that erases the knowledge base must not be wrapped in
+ * a transaction. `asyncRoute` opens one in the browser and not on the server, so a route that
+ * erases goes on working on the desktop and dies on the standalone build with "cannot rollback - no
+ * transaction is active" — the transaction belonged to a connection the erasure closed, and the one
+ * opened in its place has nothing to roll back.
+ */
+describe("how the setup routes are registered", () => {
+ /** Every route that erases the knowledge base before it creates one in its place. */
+ const ERASING_ROUTES = [
+ "/api/setup/new-document",
+ "/api/setup/sync-from-server",
+ "/api/setup/existing/delete",
+ // Not an erasure, but it reopens the database it was asked to leave alone, which closes the
+ // connection just the same.
+ "/api/setup/existing/keep"
+ ];
+
+ it("keeps every route that closes the database out of a transaction", () => {
+ const registered = captureRoutes();
+
+ for (const path of ERASING_ROUTES) {
+ expect(registered.get(path), `${path} is not registered at all`).toBe("asyncRouteWithoutTransaction");
+ }
+ });
+});
+
+/**
+ * Runs the route builder against a context that records which builder each path went through, and
+ * does nothing else. Enough for the question above, which is about registration rather than about
+ * anything a handler does.
+ */
+function captureRoutes(): Map<string, string> {
+ const registered = new Map<string, string>();
+ const noop = () => {};
+ const record = (builder: string) => (_method: string, path: string) => {
+ registered.set(path, builder);
+ };
+
+ buildSharedApiRoutes({
+ route: record("route"),
+ asyncRoute: record("asyncRoute"),
+ asyncRouteWithoutTransaction: record("asyncRouteWithoutTransaction"),
+ apiRoute: record("apiRoute"),
+ asyncApiRoute: record("asyncApiRoute"),
+ apiResultHandler: noop,
+ checkApiAuth: noop,
+ checkApiAuthOrElectron: noop,
+ checkAppNotInitialized: noop,
+ checkSetupAuth: noop,
+ checkCredentials: noop,
+ loginRateLimiter: noop,
+ uploadMiddlewareWithErrorHandling: noop,
+ importMiddlewareWithErrorHandling: noop,
+ csrfMiddleware: noop
+ });
+
+ return registered;
+}
diff --git a/packages/trilium-core/src/services/bootstrap_utils.spec.ts b/packages/trilium-core/src/services/bootstrap_utils.spec.ts
index 766254ebc3..0dae2544c3 100644
--- a/packages/trilium-core/src/services/bootstrap_utils.spec.ts
+++ b/packages/trilium-core/src/services/bootstrap_utils.spec.ts
@@ -65,13 +65,13 @@ describe("bootstrap_utils (real DB)", () => {
try {
// A first run: nowhere in particular to go, and nothing behind the wizard.
expect(getSharedBootstrapItems(ASSET_PATH, false)).toMatchObject({
- initialSetup: true, setupTargetScreen: undefined
+ hasExistingData: false, setupTargetScreen: undefined
});
enterSetupMode({ lang: "ro", targetScreen: "restore-backup" });
const items = getSharedBootstrapItems(ASSET_PATH, false);
- expect(items).toMatchObject({ initialSetup: false, setupTargetScreen: "restore-backup" });
+ expect(items).toMatchObject({ hasExistingData: true, setupTargetScreen: "restore-backup" });
// The schema of a finished database says nothing about an interrupted sync, so the
// wizard must not be sent to the sync-progress screen instead of the one asked for.
expect(items.syncInProgress).toBe(false);
diff --git a/packages/trilium-core/src/services/bootstrap_utils.ts b/packages/trilium-core/src/services/bootstrap_utils.ts
index df36be0c30..c474a4b625 100644
--- a/packages/trilium-core/src/services/bootstrap_utils.ts
+++ b/packages/trilium-core/src/services/bootstrap_utils.ts
@@ -8,7 +8,8 @@ import { getCurrentLocale } from "./i18n";
import attributes from "./attributes";
import BNote from "../becca/entities/bnote";
import { getPlatform } from "./platform";
-import { getSetupTargetScreen, isInitialSetup, isSetupRequested } from "./setup_mode";
+import { isSetupAuthRequired } from "./setup_auth";
+import { getSetupTargetScreen, hasExistingData, isSetupRequested } from "./setup_mode";
import sqlInit from "./sql_init";
export default function getSharedBootstrapItems(assetPath: string, dbInitialized: boolean) {
@@ -29,9 +30,11 @@ export default function getSharedBootstrapItems(assetPath: string, dbInitialized
// Kept in the common items so both payload shapes carry the flag uniformly. An instance that
// was asked into setup has a finished database behind it, so its schema says nothing here.
syncInProgress: !dbInitialized && !isSetupRequested() && sqlInit.schemaExists(),
- // Where the wizard should open, and whether it has anywhere to go back to. Only a marker
- // says otherwise; a first run leaves both at their first-run answers.
- initialSetup: isInitialSetup(),
+ // Where the wizard should open, whether it still has anything to lose, and whether it has to
+ // be unlocked before it will act on it. Only a marker says otherwise; a first run leaves all
+ // three at their first-run answers.
+ hasExistingData: hasExistingData(),
+ setupAuthRequired: isSetupAuthRequired(),
setupTargetScreen: getSetupTargetScreen(),
...getIconConfig(assetPath)
};
diff --git a/packages/trilium-core/src/services/hidden_subtree.ts b/packages/trilium-core/src/services/hidden_subtree.ts
index 3369b1049a..c2c4ab224f 100644
--- a/packages/trilium-core/src/services/hidden_subtree.ts
+++ b/packages/trilium-core/src/services/hidden_subtree.ts
@@ -313,6 +313,7 @@ function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenS
{ id: "_optionsMFA", title: t("hidden-subtree.multi-factor-authentication-title"), type: "contentWidget", enforceDeleted: true },
{ id: "_optionsEtapi", title: t("hidden-subtree.etapi-title"), type: "contentWidget", icon: "bx-extension", attributes: [{ type: "label", name: "notInStandalone" }] },
{ id: "_optionsBackup", title: t("hidden-subtree.backup-title"), type: "contentWidget", icon: "bx-data" },
+ { id: "_optionsDatabase", title: t("hidden-subtree.database-title"), type: "contentWidget", icon: "bx-hdd" },
{ id: "_optionsSync", title: t("hidden-subtree.sync-title"), type: "contentWidget", icon: "bx-wifi" },
{ id: "_optionsLlm", title: t("hidden-subtree.llm-title"), type: "contentWidget", icon: "bx-bot" },
{ id: "_optionsAi", title: "AI Chat", type: "contentWidget", enforceDeleted: true },
diff --git a/packages/trilium-core/src/services/scheduler.spec.ts b/packages/trilium-core/src/services/scheduler.spec.ts
index 86fd5e120b..89ad608d11 100644
--- a/packages/trilium-core/src/services/scheduler.spec.ts
+++ b/packages/trilium-core/src/services/scheduler.spec.ts
@@ -29,10 +29,15 @@ const HOUR = 3600 * SECOND;
* startScheduler() registers all its timers inside `sqlInit.dbReady.then(...)`.
* Awaiting the (already-resolved) dbReady promise lets those then-callbacks run
* first, so the timers exist before we advance the fake clock.
+ *
+ * Several microtasks rather than one: the hidden-subtree callback reconciles the
+ * language before it runs, and each `await` inside it costs another turn.
*/
async function settleDbReady() {
await sqlInit.dbReady;
- await Promise.resolve();
+ for (let i = 0; i < 5; i++) {
+ await Promise.resolve();
+ }
}
function buildBackendScript() {
@@ -95,7 +100,7 @@ describe("scheduler", () => {
startScheduler();
await settleDbReady();
- // DB was already initialized → hidden subtree is checked immediately via dbReady.
+ // The hidden subtree is checked as soon as there is a database, via dbReady.
expect(checkHiddenSubtree).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(10 * SECOND);
@@ -111,15 +116,21 @@ describe("scheduler", () => {
expect(getNotesWithLabel).toHaveBeenCalledWith("run", "daily");
});
- it("checks the hidden subtree only via the periodic maintenance interval when the DB is not yet initialized", async () => {
+ it("still checks the hidden subtree where the database was opened after the scheduler started", async () => {
+ // Which is every path through the setup wizard: the instance has nothing to open when this
+ // runs, and the database it goes on to open — restored from a backup, or pulled from a sync
+ // server — was written by an older version that knows nothing of whatever has been added to
+ // the subtree since. Asking whether the database was initialized at the moment the scheduler
+ // started answered for the wrong moment, and left those instances unchecked until a restart.
isDbInitialized.mockReturnValue(false);
startScheduler();
await settleDbReady();
- expect(checkHiddenSubtree).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(7 * HOUR);
expect(checkHiddenSubtree).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(7 * HOUR);
+ expect(checkHiddenSubtree).toHaveBeenCalledTimes(2);
});
it("does not schedule script timers when backend scripting is disabled, but still runs maintenance", async () => {
diff --git a/packages/trilium-core/src/services/scheduler.ts b/packages/trilium-core/src/services/scheduler.ts
index cb59f4befa..3a807d00da 100644
--- a/packages/trilium-core/src/services/scheduler.ts
+++ b/packages/trilium-core/src/services/scheduler.ts
@@ -4,6 +4,7 @@ import config from "./config.js";
import * as cls from "./context.js";
import events from "./events.js";
import hiddenSubtreeService from "./hidden_subtree.js";
+import { reconcileLanguageAfterDbInit } from "./i18n.js";
import { getLog } from "./log.js";
import options from "./options.js";
import protected_session from "./protected_session.js";
@@ -38,12 +39,25 @@ function runNotesWithLabel(runAttrValue: string) {
}
export function startScheduler() {
- // If the database is already initialized, we need to check the hidden subtree. Otherwise, hidden subtree
- // is also checked before importing the demo.zip, so no need to do it again.
- if (sqlInit.isDbInitialized()) {
- console.log("Checking hidden subtree.");
- sqlInit.dbReady.then(() => cls.getContext().init(() => hiddenSubtreeService.checkHiddenSubtree()));
- }
+ // Whenever a database comes up, whichever way it got here. This used to be asked of the instance
+ // at the moment the scheduler started, which is the wrong moment: an instance that starts in the
+ // setup wizard has no database yet and answers no, and the one it goes on to open — restored
+ // from a backup, or pulled from a sync server — then never gets checked at all. A restored
+ // database is exactly the one that needs it, since it was written by an older version and knows
+ // nothing of whatever has been added to the subtree since.
+ //
+ // Creating a new document checks the subtree itself, before importing the demo content, so on
+ // that one path this runs a second time over a subtree that is already whole. It is the same
+ // check that runs every seven hours below, and it finds nothing to do.
+ console.log("Checking hidden subtree.");
+ sqlInit.dbReady.then(async () => {
+ // Reconciled first, because the titles the check may write have to be in the document's own
+ // language: i18next cannot read the stored locale before there is a database to read it
+ // from, so on every path that opens one after start it is still on the fallback "en". A
+ // no-op on an ordinary boot, where this has already been done.
+ await reconcileLanguageAfterDbInit();
+ cls.getContext().init(() => hiddenSubtreeService.checkHiddenSubtree());
+ });
// Periodic checks.
sqlInit.dbReady.then(() => {
diff --git a/packages/trilium-core/src/services/setup_auth.spec.ts b/packages/trilium-core/src/services/setup_auth.spec.ts
new file mode 100644
index 0000000000..76473032ae
--- /dev/null
+++ b/packages/trilium-core/src/services/setup_auth.spec.ts
@@ -0,0 +1,115 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import * as passwordService from "./encryption/password.js";
+import passwordEncryptionService from "./encryption/password_encryption.js";
+import {
+ authenticateSetup,
+ isSetupAuthorized,
+ isSetupAuthRequired,
+ resetSetupAuth
+} from "./setup_auth.js";
+import { enterSetupMode, leaveSetupMode, markExistingDataDiscarded } from "./setup_mode.js";
+
+/** An instance with a password, which is the only kind the gate has anything to check against. */
+function instanceHasPassword(hasOne: boolean) {
+ vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(hasOne);
+}
+
+/** What the password check answers, without going anywhere near a real hash. */
+function passwordIs(correct: string) {
+ vi.spyOn(passwordEncryptionService, "verifyPassword")
+ .mockImplementation(async (given: string) => given === correct);
+}
+
+beforeEach(() => {
+ resetSetupAuth();
+ // An instance the app sent back to setup, with a knowledge base still behind the wizard.
+ enterSetupMode({ lang: "en" });
+ instanceHasPassword(true);
+});
+
+afterEach(() => {
+ leaveSetupMode();
+ resetSetupAuth();
+ vi.restoreAllMocks();
+});
+
+describe("whether the wizard has to be unlocked", () => {
+ it("is asked for where there is a knowledge base behind it and a password that guarded it", () => {
+ expect(isSetupAuthRequired()).toBe(true);
+ });
+
+ it("is not asked for on a first run, which has nothing behind it and nobody to be", () => {
+ leaveSetupMode();
+
+ expect(isSetupAuthRequired()).toBe(false);
+ });
+
+ it("is not asked for where no password was ever set, since there is nothing to ask", () => {
+ instanceHasPassword(false);
+
+ expect(isSetupAuthRequired()).toBe(false);
+ });
+
+ it("stops being asked for once the knowledge base is gone, which is when a first run begins", () => {
+ markExistingDataDiscarded();
+
+ expect(isSetupAuthRequired()).toBe(false);
+ });
+});
+
+describe("unlocking it", () => {
+ it("issues a token for the right password, and the token is what the routes accept", async () => {
+ passwordIs("hunter2");
+
+ const token = await authenticateSetup("hunter2");
+
+ expect(token).toBeTruthy();
+ expect(isSetupAuthorized(token ?? "")).toBe(true);
+ });
+
+ it("says no to the wrong password, and issues nothing", async () => {
+ passwordIs("hunter2");
+
+ expect(await authenticateSetup("hunter3")).toBeNull();
+ expect(isSetupAuthorized("hunter3")).toBe(false);
+ });
+
+ it("accepts nothing before a token has been issued, and nothing that is not one", async () => {
+ expect(isSetupAuthorized("anything")).toBe(false);
+ expect(isSetupAuthorized(undefined)).toBe(false);
+
+ passwordIs("hunter2");
+ await authenticateSetup("hunter2");
+
+ expect(isSetupAuthorized("anything")).toBe(false);
+ expect(isSetupAuthorized("")).toBe(false);
+ });
+
+ it("replaces the last token rather than keeping both current", async () => {
+ passwordIs("hunter2");
+
+ const first = await authenticateSetup("hunter2");
+ const second = await authenticateSetup("hunter2");
+
+ expect(first).not.toBe(second);
+ expect(isSetupAuthorized(first ?? "")).toBe(false);
+ expect(isSetupAuthorized(second ?? "")).toBe(true);
+ });
+
+ it("stops accepting one that has been held too long", async () => {
+ vi.useFakeTimers();
+ try {
+ passwordIs("hunter2");
+ const token = await authenticateSetup("hunter2");
+
+ vi.advanceTimersByTime(12 * 60 * 60 * 1000 - 1000);
+ expect(isSetupAuthorized(token ?? "")).toBe(true);
+
+ vi.advanceTimersByTime(2000);
+ expect(isSetupAuthorized(token ?? "")).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/trilium-core/src/services/setup_auth.ts b/packages/trilium-core/src/services/setup_auth.ts
new file mode 100644
index 0000000000..0182ba9728
--- /dev/null
+++ b/packages/trilium-core/src/services/setup_auth.ts
@@ -0,0 +1,95 @@
+import { getCrypto } from "./encryption/crypto.js";
+import { isPasswordSet } from "./encryption/password.js";
+import passwordEncryptionService from "./encryption/password_encryption.js";
+import { getLog } from "./log.js";
+import { hasExistingData } from "./setup_mode.js";
+import { encodeUtf8 } from "./utils/binary.js";
+import { randomSecureToken } from "./utils/index.js";
+
+/**
+ * Who is allowed to drive the setup wizard when there is a knowledge base behind it.
+ *
+ * Setup is ordinarily unauthenticated, and rightly so: before a database exists there is nobody to
+ * authenticate and nothing to protect. An instance the app sent back to setup is the other case
+ * entirely. Its database is sitting right there, unopened, and every guard that normally protects it
+ * has stood down, because each of them gives way when the instance reports itself uninitialized.
+ * That is exactly what setup mode makes it report.
+ *
+ * On a desktop that matters little. On a server it is the whole thing: the setup screen is served
+ * over the network to whoever asks, and the wizard can erase the knowledge base, replace it from a
+ * backup, or point it at somebody else's sync server. So the password that guarded the instance a
+ * moment ago guards it here too, read straight from the options table, which is legible while the
+ * database is attached but not initialized.
+ *
+ * What is issued in exchange lives in memory for this process only. Sessions cannot serve here: the
+ * session store answers nothing while the database is uninitialized, so a user who was logged in a
+ * minute ago is a stranger to it now.
+ *
+ * @module
+ */
+
+/**
+ * Whether the wizard has to be unlocked before it will do anything.
+ *
+ * Two things have to hold. There has to be something to protect, which stops being true the moment
+ * the user picks a path and the database goes; from then on the instance is as bare as a first run
+ * and is treated as one. And there has to be a password to check against, since an instance that
+ * never had one has nothing to ask for and would otherwise be locked out of its own wizard.
+ */
+export function isSetupAuthRequired(): boolean {
+ return hasExistingData() && isPasswordSet();
+}
+
+/**
+ * Checks the instance's own password and, where it matches, issues the token that unlocks the rest
+ * of the wizard.
+ *
+ * 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.
+ *
+ * @returns the token, or `null` where the password was wrong.
+ */
+export async function authenticateSetup(password: string): Promise<string | null> {
+ if (!await passwordEncryptionService.verifyPassword(password)) {
+ getLog().info("Setup: a wrong password 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.");
+
+ return issued.token;
+}
+
+/** Whether a token presented by a request is the one this process issued, and still current. */
+export function isSetupAuthorized(token: string | undefined): boolean {
+ if (!issued || !token) {
+ return false;
+ }
+ if (Date.now() > issued.expires) {
+ issued = null;
+ return false;
+ }
+
+ // Compared the way the password itself is: the token is a bearer secret, and a comparison that
+ // stops at the first wrong byte says how much of it was right.
+ return getCrypto().constantTimeCompare(encodeUtf8(token), encodeUtf8(issued.token));
+}
+
+/** Forgets it, for the tests that need one process to look like a fresh one. */
+export function resetSetupAuth(): void {
+ issued = null;
+}
+
+/**
+ * How long an unlocked wizard stays unlocked.
+ *
+ * Long enough to cover what the user might do inside it: backing up a large knowledge base runs
+ * into the tens of minutes, and being asked for the password again halfway through would be asking
+ * it of somebody who has already walked away from the screen.
+ */
+const TOKEN_LIFETIME_MS = 12 * 60 * 60 * 1000;
+
+let issued: { token: string; expires: number } | null = null;
diff --git a/packages/trilium-core/src/services/setup_existing.spec.ts b/packages/trilium-core/src/services/setup_existing.spec.ts
index cd2ad9cc1a..0fa26eadbb 100644
--- a/packages/trilium-core/src/services/setup_existing.spec.ts
+++ b/packages/trilium-core/src/services/setup_existing.spec.ts
@@ -6,6 +6,7 @@ import optionService from "./options.js";
import {
backUpExistingData,
deleteExistingData,
+ discardExistingData,
getExistingBackupDefaults,
getExistingBackupProgress,
getExistingBackupStatus,
@@ -17,6 +18,7 @@ import { enterSetupMode, initSetupPlatform, leaveSetupMode } from "./setup_mode.
const platform = {
writeMarker: vi.fn(async () => {}),
+ hasMarker: vi.fn(async () => false),
removeMarker: vi.fn(async () => {}),
removeDatabase: vi.fn(async () => {})
};
@@ -92,6 +94,33 @@ describe("what becomes of the existing database", () => {
expect(platform.removeDatabase).toHaveBeenCalled();
});
+ it("treats it as gone once it is, refusing everything that would act on it again", async () => {
+ await deleteExistingData();
+ platform.removeDatabase.mockClear();
+
+ // Every one of these acts on a file that no longer exists. Keeping it, in particular, would
+ // reopen a database that has been deleted and come up on an empty one.
+ await expect(deleteExistingData()).rejects.toThrow(/already been discarded/);
+ await expect(backUpExistingData(ANY_SETTINGS)).rejects.toThrow(/already been discarded/);
+ await expect(keepExistingData()).rejects.toThrow(/already been discarded/);
+ expect(platform.removeDatabase).not.toHaveBeenCalled();
+ });
+
+ it("erases only where there is something to erase, for the paths that create a database", async () => {
+ // Called by creating a document and by syncing from a server, both of which run identically
+ // on a first run, where there never was anything here.
+ await discardExistingData();
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+
+ // Asked again by a second path taken in the same wizard, which has nothing left to do.
+ await discardExistingData();
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+
+ leaveSetupMode();
+ await expect(discardExistingData()).resolves.toBeUndefined();
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+ });
+
it("puts the instance back as it was when the answer is to keep it", async () => {
await keepExistingData();
diff --git a/packages/trilium-core/src/services/setup_existing.ts b/packages/trilium-core/src/services/setup_existing.ts
index 767f09e801..c213c8efe2 100644
--- a/packages/trilium-core/src/services/setup_existing.ts
+++ b/packages/trilium-core/src/services/setup_existing.ts
@@ -11,7 +11,13 @@ import { getBackup } from "./backup.js";
import eventService from "./events.js";
import { getLog } from "./log.js";
import optionService from "./options.js";
-import { getSetupPlatform, isInitialSetup, leaveSetupMode } from "./setup_mode.js";
+import {
+ getSetupPlatform,
+ hasExistingData,
+ isInitialSetup,
+ leaveSetupMode,
+ markExistingDataDiscarded
+} from "./setup_mode.js";
import sqlInit from "./sql_init.js";
/**
@@ -189,18 +195,35 @@ function reportProgress(fraction: number): void {
/**
* Erases the existing database, which is the point of no return.
*
- * Only ever reached from a screen that has said as much, and only after the user has either taken a
- * backup or refused one. What follows is the rest of the wizard, on an instance that now genuinely
- * has nothing.
+ * Deliberately late: the user answers for a backup on the way into the wizard, but nothing is
+ * touched until they pick a path that replaces the database, and this is what those paths call
+ * first. Up to here every screen can still be left through Cancel with the knowledge base intact.
+ *
+ * The one path that does not call it is restoring a backup, and for a reason worth keeping: a
+ * restore validates the file and only then swaps the database, so a backup that turns out to be
+ * unusable leaves the user with what they already had. Erasing first would throw that away.
*/
export async function deleteExistingData(): Promise<void> {
requireExistingData();
getLog().info("Setup: erasing the existing database at the user's request.");
await getSetupPlatform().removeDatabase();
+ markExistingDataDiscarded();
getLog().info("Setup: the existing database is gone.");
}
+/**
+ * The same, for callers that do not know whether there is anything to erase.
+ *
+ * Which is every path that creates a database: it runs identically on a first run, where there
+ * never was one, and on an instance the app sent here, where there is one right up until this call.
+ */
+export async function discardExistingData(): Promise<void> {
+ if (hasExistingData()) {
+ await deleteExistingData();
+ }
+}
+
/**
* Abandons setup and opens the database that was there all along.
*
@@ -225,11 +248,18 @@ export async function keepExistingData(): Promise<void> {
* These operations only make sense between an app asking for setup and the wizard getting past the
* question, and each of them is destructive or irreversible in its own way. A first run reaching
* them means something is wrong, not that there is an empty database to erase.
+ *
+ * The second case is the same thing later on: once the user has picked a path and the database has
+ * gone, a screen still offering to back it up or to go back to it is a screen acting on something
+ * that is no longer there.
*/
function requireExistingData(): void {
if (isInitialSetup()) {
throw new Error("There is no existing database: this instance is being set up for the first time.");
}
+ if (!hasExistingData()) {
+ throw new Error("The existing database has already been discarded during this setup.");
+ }
}
function messageOf(e: unknown): string {
diff --git a/packages/trilium-core/src/services/setup_mode.spec.ts b/packages/trilium-core/src/services/setup_mode.spec.ts
index 158cc896da..6da842fb01 100644
--- a/packages/trilium-core/src/services/setup_mode.spec.ts
+++ b/packages/trilium-core/src/services/setup_mode.spec.ts
@@ -6,10 +6,12 @@ import {
getSetupLanguage,
getSetupPlatform,
getSetupTargetScreen,
+ hasExistingData,
initSetupPlatform,
isInitialSetup,
isSetupRequested,
leaveSetupMode,
+ markExistingDataDiscarded,
parseSetupMarker
} from "./setup_mode.js";
@@ -79,11 +81,36 @@ describe("being in setup because it was asked for", () => {
});
});
+describe("whether there is still a knowledge base behind the wizard", () => {
+ it("is what a marker means, until the wizard erases what the marker was about", () => {
+ expect(hasExistingData()).toBe(false);
+
+ enterSetupMode({ lang: "de" });
+ expect(hasExistingData()).toBe(true);
+
+ markExistingDataDiscarded();
+ expect(hasExistingData()).toBe(false);
+ // How it was reached does not change, which is a different question and a settled one.
+ expect(isInitialSetup()).toBe(false);
+ expect(isSetupRequested()).toBe(true);
+ });
+
+ it("comes back with the next start, since that one has a database of its own again", () => {
+ enterSetupMode({ lang: "de" });
+ markExistingDataDiscarded();
+ leaveSetupMode();
+
+ enterSetupMode({ lang: "de" });
+ expect(hasExistingData()).toBe(true);
+ });
+});
+
describe("what setup reaches for on its platform", () => {
it("carries what a route writes to whichever platform registered itself", async () => {
const written: unknown[] = [];
initSetupPlatform({
writeMarker: async (marker) => { written.push(marker); },
+ hasMarker: async () => written.length > 0,
removeMarker: async () => {},
removeDatabase: async () => {}
});
diff --git a/packages/trilium-core/src/services/setup_mode.ts b/packages/trilium-core/src/services/setup_mode.ts
index b1b24c62f1..31e03ce071 100644
--- a/packages/trilium-core/src/services/setup_mode.ts
+++ b/packages/trilium-core/src/services/setup_mode.ts
@@ -22,6 +22,7 @@ import { type SetupMarker, type SetupTargetScreen } from "@triliumnext/commons";
const TARGET_SCREENS: readonly SetupTargetScreen[] = [ "restore-backup", "backup-database" ];
let requested: SetupMarker | null = null;
+let dataDiscarded = false;
/**
* Puts the instance into setup for the rest of this process.
@@ -31,6 +32,7 @@ let requested: SetupMarker | null = null;
*/
export function enterSetupMode(marker: SetupMarker | null): void {
requested = marker;
+ dataDiscarded = false;
}
/**
@@ -42,6 +44,23 @@ export function enterSetupMode(marker: SetupMarker | null): void {
*/
export function leaveSetupMode(): void {
requested = null;
+ dataDiscarded = false;
+}
+
+/**
+ * Whether the knowledge base the wizard was booted away from is still there.
+ *
+ * Not the same question as {@link isInitialSetup}, which answers for how the wizard was reached and
+ * never changes. This one stops being true the moment the user picks a path that replaces the
+ * database, which is the point everything offering to back it up, or to go back to it, has to stop.
+ */
+export function hasExistingData(): boolean {
+ return requested !== null && !dataDiscarded;
+}
+
+/** Records that it is gone. Nothing takes this back: the file it refers to no longer exists. */
+export function markExistingDataDiscarded(): void {
+ dataDiscarded = true;
}
/** Whether this instance was asked to be in setup rather than being there for want of a database. */
@@ -123,6 +142,14 @@ export function asSetupTargetScreen(value: unknown): SetupTargetScreen | undefin
export interface SetupPlatform {
/** Leaves the marker that makes the next start the wizard. */
writeMarker(marker: SetupMarker): Promise<void>;
+ /**
+ * Whether one is lying there waiting to be read.
+ *
+ * Asked by an instance that cannot restart itself, where the marker outlives the page that
+ * wrote it: a server is restarted by hand, possibly days later, and until then this is the only
+ * thing that can tell the owner a start-over is pending, or let them call it off.
+ */
+ hasMarker(): Promise<boolean>;
/** Takes it back, for a request that was made and then abandoned. */
removeMarker(): Promise<void>;
/**
diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.ts
index ccbfe5c120..feda46717c 100644
--- a/packages/trilium-core/src/services/sql_init.ts
+++ b/packages/trilium-core/src/services/sql_init.ts
@@ -234,6 +234,12 @@ async function createInitialDatabase(skipDemoDb?: boolean, locale?: string) {
log.info("Schema and initial content generated.");
+ // A database has been brought up, so whatever asked for setup has had its answer. Done here
+ // rather than left to `setDbAsInitialized`, which this path deliberately does not go through
+ // (see below): without it the instance goes on reporting itself uninitialized for the rest of
+ // the process, and the window that opens next comes up as the wizard all over again.
+ leaveSetupMode();
+
initDbConnection();
// `initNotSyncedOptions(true, ...)` above already set the "initialized"
diff --git a/packages/trilium-core/src/services/sql_init_resetup.spec.ts b/packages/trilium-core/src/services/sql_init_resetup.spec.ts
index e4952dcb77..9ff85834b8 100644
--- a/packages/trilium-core/src/services/sql_init_resetup.spec.ts
+++ b/packages/trilium-core/src/services/sql_init_resetup.spec.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
import * as cls from "./context.js";
+import {
+ enterSetupMode,
+ hasExistingData,
+ isSetupRequested,
+ leaveSetupMode
+} from "./setup_mode.js";
import { getSql } from "./sql/index.js";
import sqlInit from "./sql_init.js";
@@ -121,6 +127,34 @@ describe("createDatabaseForSync on a virgin database", () => {
});
});
+/**
+ * The instance that reaches `createInitialDatabase` through the wizard rather than on a first run.
+ *
+ * It was sent there by a `setup.json` marker, and until that is answered it goes on reporting that
+ * it has nothing to open — which is the whole point of setup mode, and is what keeps the database
+ * closed and every uninitialized-only guard in force. This path does not go through
+ * `setDbAsInitialized`, where every other path answers the marker, so it has to answer it itself.
+ * Left standing, the window that opens next comes up as the wizard all over again.
+ */
+describe("creating a document for an instance that was sent to the setup wizard", () => {
+ it("leaves setup mode, so the instance stops answering as one with nothing to open", async () => {
+ wipeToVirginDatabase();
+ enterSetupMode({ lang: "en" });
+
+ try {
+ expect(sqlInit.isDbInitialized()).toBe(false);
+
+ await cls.init(() => sqlInit.createInitialDatabase(true, "en"));
+
+ expect(isSetupRequested()).toBe(false);
+ expect(hasExistingData()).toBe(false);
+ expect(sqlInit.isDbInitialized()).toBe(true);
+ } finally {
+ leaveSetupMode();
+ }
+ });
+});
+
/** Reduces the database to a truly empty file, as on a first-ever run. */
function wipeToVirginDatabase() {
const sql = getSql();
diff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.ts
index d6a0345dac..04556221c3 100644
--- a/packages/trilium-core/src/test/api_tester.ts
+++ b/packages/trilium-core/src/test/api_tester.ts
@@ -271,6 +271,7 @@ export class CoreApiTester {
checkApiAuth: noop,
checkApiAuthOrElectron: noop,
checkAppNotInitialized: noop,
+ checkSetupAuth: noop,
checkCredentials: noop,
loginRateLimiter: noop,
uploadMiddlewareWithErrorHandling: noop,