Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(setup): render set-password screen client-side via bootstrap
Elian Dorancbfba2ca6524
diff --git a/apps/client/src/index.ts b/apps/client/src/index.tsindex 9f7ef0aafd..2de268b354 100644--- a/apps/client/src/index.ts+++ b/apps/client/src/index.ts@@ -137,6 +137,11 @@ async function loadScripts() {return;}+ if (glob.passwordSet === false) {+ await import("./set_password_page.js");+ return;+ }+switch (glob.device) {case "mobile":await import("./mobile.js");diff --git a/apps/client/src/set_password.css b/apps/client/src/set_password.cssnew file mode 100644index 0000000000..4eb4c53648--- /dev/null+++ b/apps/client/src/set_password.css@@ -0,0 +1,25 @@+/* Keep the set-password page on the same fixed wizard frame as setup. The form+ wraps the whole page here (so the footer's submit button stays inside the form+ for native submission), but setup.css styles every form under `body.setup` at+ 80% width — `display: contents` makes the form layout-transparent so the page+ and its full-bleed footer fill the card edge to edge instead of being squeezed. */+body.setup .setup-container.set-password-container > form {+ display: contents;+}++/* The setup wizard wraps its page in an absolutely-positioned `.slide-page`+ (inset: 0) that covers the container's padding box, so `.setup-container`'s own+ 2em padding is never visible there — only `.page`'s padding shows. This page has+ no slide-page, so that container padding would double up with `.page`'s own.+ Drop it and let `.page` provide the spacing. */+body.setup .setup-container.set-password-container {+ padding: 0;+}++/* The form is short, so centre it within the tall card while the footer stays+ pinned at the bottom. */+body.setup .page.set-password > main {+ justify-content: center;+ width: 75%;+ margin: auto;+}diff --git a/apps/client/src/set_password.ts b/apps/client/src/set_password.tsdeleted file mode 100644index 13be761ec0..0000000000--- a/apps/client/src/set_password.ts+++ /dev/null@@ -1,6 +0,0 @@-import "./stylesheets/auth.css";--// @TriliumNextTODO: is this even needed anymore?-// @ts-ignore - module = undefined-// Required for correct loading of scripts in Electron-if (typeof module === 'object') {window.module = module; module = undefined;}diff --git a/apps/client/src/set_password_page.tsx b/apps/client/src/set_password_page.tsxnew file mode 100644index 0000000000..1c18213f83--- /dev/null+++ b/apps/client/src/set_password_page.tsx@@ -0,0 +1,85 @@+import "./setup.css";+import "./set_password.css";++import { LOCALE_IDS } from "@triliumnext/commons";+import { render } from "preact";+import { useRef, useState } from "preact/hooks";++import { initLocale, t } from "./services/i18n";+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";++const MIN_PASSWORD_LENGTH = 4;++async function main() {+ await initLocale((window.glob.currentLocale?.id ?? "en") as LOCALE_IDS);++ const bodyWrapper = document.createElement("div");+ bodyWrapper.classList.add("setup-outer-wrapper");+ // The device/theme body classes are already applied by index.ts (this page is+ // loaded through the regular bootstrap); we only add the setup styling hook.+ document.body.classList.add("setup");+ render(<App />, bodyWrapper);+ document.body.replaceChildren(bodyWrapper);+}++function App() {+ const password1Ref = useRef<HTMLInputElement>(null);+ const [ password1, setPassword1 ] = useState("");+ const [ password2, setPassword2 ] = useState("");++ // Mirror the server-side validation so the form can't be submitted into an error.+ const tooShort = password1 !== "" && password1.length < MIN_PASSWORD_LENGTH;+ const mismatch = password2 !== "" && password1 !== password2;+ const isValid = password1.length >= MIN_PASSWORD_LENGTH && password1 === password2;++ return (+ <div class="setup-container set-password-container">+ {/* On success the server sets the password and redirects to the login page. */}+ <form method="POST" action="set-password" onSubmit={(e) => { if (!isValid) e.preventDefault(); }}>+ <SetupPage+ className="set-password"+ title={t("set_password.heading")}+ description={t("set_password.description")}+ illustration={<Icon icon="bx bx-lock-alt" className="illustration-icon" />}+ footer={<Button text={t("set_password.button")} kind="primary" disabled={!isValid} />}+ >+ <Card>+ <CardSection>+ <FormGroup+ label={t("set_password.password")} name="password1"+ error={tooShort ? t("set_password.password-too-short", { length: MIN_PASSWORD_LENGTH }) : undefined}+ >+ <FormTextBox+ inputRef={password1Ref} autoFocus+ type="password" name="password1"+ currentValue={password1} onChange={setPassword1}+ autocomplete="new-password" required+ />+ </FormGroup>+ </CardSection>++ <CardSection>+ <FormGroup+ label={t("set_password.password-confirmation")} name="password2"+ error={mismatch ? t("set_password.passwords-dont-match") : undefined}+ >+ <FormTextBox+ type="password" name="password2"+ currentValue={password2} onChange={setPassword2}+ autocomplete="new-password" required+ />+ </FormGroup>+ </CardSection>+ </Card>+ </SetupPage>+ </form>+ </div>+ );+}++main();diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex e917da6b59..7edd531ec1 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -2,15 +2,14 @@ import "./setup.css";import { LOCALES, NetworkAddressesResponse, SetupSyncFromServerResponse } from "@triliumnext/commons";import clsx from "clsx";-import { ComponentChildren, render } from "preact";+import { render } from "preact";import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { useTranslation } from "react-i18next";import logo from "./assets/icon-color.svg?url";import { getCurrentLanguage, initLocale, t } from "./services/i18n";import server from "./services/server";-import { isElectron, isMobileApp, replaceHtmlEscapedSlashes } from "./services/utils";-import ActionButton from "./widgets/react/ActionButton";+import { isElectron, isMobileApp } from "./services/utils";import Admonition, { ExtendedAdmonition } from "./widgets/react/Admonition";import Button from "./widgets/react/Button";import { Card, CardFrame, CardSection } from "./widgets/react/Card";@@ -18,6 +17,7 @@ import FormGroup from "./widgets/react/FormGroup";import { FormListItem } from "./widgets/react/FormList";import FormTextBox from "./widgets/react/FormTextBox";import Icon from "./widgets/react/Icon";+import SetupPage from "./widgets/react/SetupPage";async function main() {await initLocale();@@ -530,53 +530,6 @@ function SetupOptionCard({ title, description, icon, onClick, disabled }: { titl);}-function SetupPage({ title, description, className, illustration, children, footer, error, errorId, onBack }: {- title: string;- description?: string;- error?: string | null;- errorId?: number;- className?: string;- illustration?: ComponentChildren;- children?: ComponentChildren;- footer?: ComponentChildren;- onBack?: () => void;-}) {- const [ showError, setShowError ] = useState(!!error);- useEffect(() => {- if (error) {- setShowError(true);- }- }, [ error, errorId ]);-- return (- <div className={clsx("page", className, { "contentless": !children })}>- {onBack && (- <Button- className="back-button"- icon="bx bx-arrow-back"- text={t("setup.button-back")}- onClick={onBack}- kind="lowProfile"- />- )}- {error && showError && (- <Admonition className="page-error" type="caution">- <ActionButton icon="bx bx-x" text={t("setup.dismiss-error")} onClick={() => setShowError(false)} />- {replaceHtmlEscapedSlashes(error)}- </Admonition>- )}-- {illustration}- <h1>{title}</h1>- {description && <p class="page-description">{description}</p>}- {children && <main>- {children}- </main>}- {footer && <footer>{footer}</footer>}- </div>- );-}-async function getNetworkAddresses(): Promise<NetworkAddressesResponse> {if (!isElectron()) {// The browser already reached this server over the network, so thediff --git a/apps/client/src/stylesheets/auth.css b/apps/client/src/stylesheets/auth.cssdeleted file mode 100644index 6235164393..0000000000--- a/apps/client/src/stylesheets/auth.css+++ /dev/null@@ -1,3 +0,0 @@-.set-password .form-group {- margin-bottom: 1rem;-}\ No newline at end of filediff --git a/apps/client/src/widgets/react/SetupPage.tsx b/apps/client/src/widgets/react/SetupPage.tsxnew file mode 100644index 0000000000..ca48465178--- /dev/null+++ b/apps/client/src/widgets/react/SetupPage.tsx@@ -0,0 +1,63 @@+import clsx from "clsx";+import { ComponentChildren } from "preact";+import { useEffect, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import { replaceHtmlEscapedSlashes } from "../../services/utils";+import ActionButton from "./ActionButton";+import Admonition from "./Admonition";+import Button from "./Button";++/**+ * Shared full-height page shell used by the setup wizard and the set-password page.+ *+ * Renders the rounded card layout (illustration, heading, scrollable content and a+ * sticky footer) on top of the gradient background defined by `body.setup` in+ * `setup.css`. Consumers are expected to mount this inside a `.setup-container`.+ */+export default function SetupPage({ title, description, className, illustration, children, footer, error, errorId, onBack }: {+ title: string;+ description?: string;+ error?: string | null;+ errorId?: number;+ className?: string;+ illustration?: ComponentChildren;+ children?: ComponentChildren;+ footer?: ComponentChildren;+ onBack?: () => void;+}) {+ const [ showError, setShowError ] = useState(!!error);+ useEffect(() => {+ if (error) {+ setShowError(true);+ }+ }, [ error, errorId ]);++ return (+ <div className={clsx("page", className, { "contentless": !children })}>+ {onBack && (+ <Button+ className="back-button"+ icon="bx bx-arrow-back"+ text={t("setup.button-back")}+ onClick={onBack}+ kind="lowProfile"+ />+ )}+ {error && showError && (+ <Admonition className="page-error" type="caution">+ <ActionButton icon="bx bx-x" text={t("setup.dismiss-error")} onClick={() => setShowError(false)} />+ {replaceHtmlEscapedSlashes(error)}+ </Admonition>+ )}++ {illustration}+ <h1>{title}</h1>+ {description && <p class="page-description">{description}</p>}+ {children && <main>+ {children}+ </main>}+ {footer && <footer>{footer}</footer>}+ </div>+ );+}diff --git a/apps/client/vite.config.mts b/apps/client/vite.config.mtsindex 3b7dabd9e8..885ad96c20 100644--- a/apps/client/vite.config.mts+++ b/apps/client/vite.config.mts@@ -98,7 +98,6 @@ export default defineConfig(() => ({input: {index: join(__dirname, "index.html"),login: join(__dirname, "src", "login.ts"),- set_password: join(__dirname, "src", "set_password.ts"),runtime: join(__dirname, "src", "runtime.ts"),print: join(__dirname, "src", "print.tsx")},diff --git a/apps/server/src/assets/views/set_password.ejs b/apps/server/src/assets/views/set_password.ejsdeleted file mode 100644index 10bef8af10..0000000000--- a/apps/server/src/assets/views/set_password.ejs+++ /dev/null@@ -1,57 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">- <title><%= t("set_password.title") %></title>- <link rel="apple-touch-icon" sizes="180x180" href="<%= assetPath %>/images/app-icons/ios/apple-touch-icon.png">- <link rel="shortcut icon" href="favicon.ico">- <link rel="stylesheet" href="<%= assetPath %>/stylesheets/theme-next-light.css" media="(prefers-color-scheme: light)">- <link rel="stylesheet" href="<%= assetPath %>/stylesheets/theme-next-dark.css" media="(prefers-color-scheme: dark)">- <link rel="stylesheet" href="<%= assetPath %>/stylesheets/style.css">- <script src="<%= appPath %>/runtime.js" crossorigin type="module"></script>- <style>- body {- /* Prevent the content from being rendered before the main stylesheet loads */- display: none;- }- </style>-</head>-<body lang="<%= currentLocale.id %>" dir="<%= currentLocale.rtl ? 'rtl' : 'ltr' %>">-<div class="container set-password">- <div class="col-xs-12 col-sm-10 col-md-6 col-lg-4 col-xl-4 mx-auto pt-4">- <h1><%= t("set_password.heading") %></h1>-- <% if (error) { %>- <div class="alert alert-warning">- <%= error %>- </div>- <% } %>-- <p><%= t("set_password.description") %></p>-- <form action="set-password" method="POST">- <div class="form-group">- <label for="password1"><%= t("set_password.password") %></label>- <div class="controls">- <input id="password1" name="password1" placeholder="" class="form-control" type="password" autocomplete="new-password">- </div>- </div>- <div class="form-group">- <label for="password2"><%= t("set_password.password-confirmation") %></label>- <div class="controls">- <input id="password2" name="password2" placeholder="" class="form-control" type="password" autocomplete="new-password">- </div>- </div>-- <div class="form-group">- <button class="btn btn-success"><%= t("set_password.button") %></button>- </div>- </form>- </div>-</div>--<script src="<%= appPath %>/set_password.js" crossorigin type="module"></script>--</body>-</html>diff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.tsindex b51ec15d3e..8719083ae2 100644--- a/apps/server/src/routes/index.ts+++ b/apps/server/src/routes/index.ts@@ -1,5 +1,5 @@import { BootstrapDefinition } from "@triliumnext/commons";-import { attributes, BNote, getSharedBootstrapItems, icon_packs as iconPackService, options as optionService, sql_init, task_states } from "@triliumnext/core";+import { attributes, BNote, getSharedBootstrapItems, icon_packs as iconPackService, options as optionService, password as passwordService, sql_init, task_states } from "@triliumnext/core";import type { Request, Response } from "express";import packageJson from "../../package.json" with { type: "json" };@@ -56,6 +56,25 @@ export function bootstrap(req: Request, res: Response) {return;}+ if (!isElectron && !passwordService.isPasswordSet()) {+ // Pre-auth window: the DB is initialized but no password has been set yet.+ // This screen is web/server-only — the desktop app manages its protected-notes+ // password through the options UI and never gates the app on it — so we exclude+ // Electron here, which also means the Electron-only title-bar / background-effect+ // flags are unconditionally false. We serve a minimal payload (no CSRF token /+ // session data) carrying `passwordSet: false`; theme and icon-pack CSS still come+ // from commonItems so the screen matches the rest of the app.+ res.send({+ ...commonItems,+ passwordSet: false,+ platform: process.platform,+ hasNativeTitleBar: false,+ hasBackgroundEffects: false,+ isMainWindow: true+ } satisfies BootstrapDefinition);+ return;+ }+const csrfToken = generateCsrfToken(req, res, {overwrite: false,@@ -77,6 +96,7 @@ export function bootstrap(req: Request, res: Response) {res.send({...commonItems,dbInitialized: true,+ passwordSet: true,csrfToken,oauthJustEnrolled,platform: process.platform,diff --git a/apps/server/src/routes/login.ts b/apps/server/src/routes/login.tsindex e3c23a74f6..f57e0e1574 100644--- a/apps/server/src/routes/login.ts+++ b/apps/server/src/routes/login.ts@@ -34,12 +34,9 @@ function loginPage(req: Request, res: Response) {}function setPasswordPage(req: Request, res: Response) {- res.render("set_password", {- error: false,- assetPath,- appPath,- currentLocale: i18n.getCurrentLocale()- });+ // The set-password screen is served by the SPA at the root now (driven by the+ // bootstrap `passwordSet: false` flag); redirect any direct hits there.+ res.redirect(".");}async function setPassword(req: Request, res: Response) {@@ -51,22 +48,12 @@ async function setPassword(req: Request, res: Response) {password1 = password1.trim();password2 = password2.trim();- let error;-+ // The client validates these before submitting; the server checks are a safety+ // net, so a violation here is an exceptional case rather than normal flow.if (password1 !== password2) {- error = "Entered passwords don't match.";+ throw new ValidationError("Entered passwords don't match.");} else if (password1.length < 4) {- error = "Password must be at least 4 characters long.";- }-- if (error) {- res.render("set_password", {- error,- assetPath,- appPath,- currentLocale: i18n.getCurrentLocale()- });- return;+ throw new ValidationError("Password must be at least 4 characters long.");}await passwordService.setPassword(password1);diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.tsindex 347d9e65c9..035ad0f802 100644--- a/apps/server/src/services/auth.ts+++ b/apps/server/src/services/auth.ts@@ -21,6 +21,15 @@ function checkAuth(req: Request, res: Response, next: NextFunction) {return next();}+ if (!isElectron && !passwordService.isPasswordSet()) {+ // DB initialized but no password set yet — on the web/server the instance is+ // unprotected until the user sets one, so let the request through for the client+ // to fetch its bootstrap and render the set-password screen. Desktop never shows+ // this screen (it's handled by the internal-electron / session checks below), and+ // the API stays protected separately via checkApiAuth (which still requires a session).+ return next();+ }+const currentTotpStatus = totp.isTotpEnabled();const currentSsoStatus = openID.isOpenIDEnabled();const lastAuthState = req.session.lastAuthState || { totpEnabled: false, ssoEnabled: false };@@ -119,7 +128,9 @@ function checkAppInitialized(_req: Request, _res: Response, next: NextFunction)function checkPasswordSet(req: Request, res: Response, next: NextFunction) {if (!isElectron && !passwordService.isPasswordSet()) {- res.redirect("set-password");+ // The set-password screen is now served by the SPA at the root, driven by+ // the bootstrap `passwordSet: false` flag.+ res.redirect(".");} else {next();}diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 3a72e9bfdd..786e0805ab 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -386,6 +386,13 @@ export interface DefinitionObject {*/export type BootstrapDefinition = {dbInitialized: boolean;+ /**+ * Whether a password has been set yet. `false` only in the pre-auth window+ * after the database is initialized but before the user has set a password,+ * which the client uses to render the set-password screen. Omitted (treated+ * as set) for the regular authenticated payload.+ */+ passwordSet?: boolean;baseApiUrl: string;assetPath: string;theme: string;