Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): don't redirect explicit login navigation to the share page, closes #10552

Elian Doran910bfb158e5e
diff --git a/apps/server/src/routes/login.spec.ts b/apps/server/src/routes/login.spec.ts
index 3aa8fdfd75..7f67a26c9c 100644
--- a/apps/server/src/routes/login.spec.ts
+++ b/apps/server/src/routes/login.spec.ts
@@ -4,7 +4,9 @@ import { SessionData } from "express-session";
import supertest, { type Response } from "supertest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-import { cls } from "@triliumnext/core";
+import { cls, options } from "@triliumnext/core";
+import { refreshAuth } from "../services/auth.js";
+import config from "../services/config.js";
import { type SQLiteSessionStore } from "./session_parser.js";
let app: Application;
@@ -24,12 +26,12 @@ describe("Login Route test", () => {
vi.useRealTimers();
});
- it("redirects GET /login to the SPA root, since login is served client-side", async () => {
+ it("redirects GET /login to the SPA root with the login marker, since login is served client-side", async () => {
const res = await supertest(app)
.get("/login")
.expect(302);
- expect(res.headers.location).toBe(".");
+ expect(res.headers.location).toBe("./?login");
});
it("returns a 401 status, when login fails with wrong password", async () => {
@@ -41,6 +43,58 @@ describe("Login Route test", () => {
});
+ describe("login stays reachable with redirectBareDomain enabled (#10552)", () => {
+ // The fixture DB contains a #shareRoot note (y0AFOwgOgkWO), so enabling
+ // redirectBareDomain arms the bare-domain → share redirect in checkAuth.
+ // The login screen is served by the SPA at the root, so an explicit login
+ // request must still be able to reach it — otherwise the share redirect
+ // locks the owner out of their own instance.
+ let originalNoAuthentication: boolean;
+
+ beforeAll(() => {
+ // The spec data dir's config.ini enables noAuthentication, which makes
+ // checkAuth wave every request through and would mask the redirect
+ // behavior under test.
+ originalNoAuthentication = config.General.noAuthentication;
+ config.General.noAuthentication = false;
+ refreshAuth();
+ cls.init(() => options.setOption("redirectBareDomain", "true"));
+ });
+
+ afterAll(() => {
+ config.General.noAuthentication = originalNoAuthentication;
+ refreshAuth();
+ cls.init(() => options.setOption("redirectBareDomain", "false"));
+ });
+
+ it("still redirects the bare domain itself to the share page", async () => {
+ const res = await supertest(app).get("/").expect(302);
+ expect(res.headers.location).toBe("share");
+ });
+
+ it("GET /login ends on the login screen, not the share page", async () => {
+ const { res, path } = await followRedirects(app, "/login");
+
+ expect(path).not.toMatch(/^\/share/);
+ expect(res.status).toBe(200);
+ });
+
+ it("GET /login/ (trailing slash) ends on the login screen, not a redirect loop", async () => {
+ const { res, path } = await followRedirects(app, "/login/");
+
+ expect(path).not.toMatch(/^\/share/);
+ expect(res.status).toBe(200);
+ });
+
+ it("serves the bootstrap payload to a logged-out client instead of redirecting it to share", async () => {
+ // The SPA's login screen is driven by the bootstrap `loggedIn: false`
+ // payload; if /bootstrap gets bounced to the share page, the login
+ // screen can never render even when the SPA itself is served.
+ const res = await supertest(app).get("/bootstrap").expect(200);
+ expect(res.body.loggedIn).toBe(false);
+ });
+ });
+
describe("Login when 'Remember Me' is ticked", async () => {
// TriliumNextTODO: make setting cookieMaxAge via env variable work
// => process.env.TRILIUM_SESSION_COOKIEMAXAGE
@@ -185,6 +239,31 @@ describe("Login Route test", () => {
});
}, 100_000);
+const MAX_REDIRECT_HOPS = 5;
+
+/**
+ * Follows 3xx redirects the way a browser would, resolving relative `Location`
+ * headers (".", "share", …) against the current URL. Stops after
+ * {@link MAX_REDIRECT_HOPS} hops so redirect loops surface as a final 3xx
+ * response instead of hanging the test.
+ */
+async function followRedirects(app: Application, startPath: string) {
+ let url = new URL(startPath, "http://localhost");
+ let res = await supertest(app).get(url.pathname + url.search);
+
+ for (let hop = 0; hop < MAX_REDIRECT_HOPS && res.status >= 300 && res.status < 400; hop++) {
+ const location = res.headers.location;
+ if (!location) {
+ break;
+ }
+
+ url = new URL(location, url);
+ res = await supertest(app).get(url.pathname + url.search);
+ }
+
+ return { res, path: url.pathname };
+}
+
async function getSessionFromCookie(setCookieHeader: string) {
// Extract the session ID from the cookie.
const sessionIdMatch = setCookieHeader.match(/trilium.sid=(?<sessionId>[^;]+)/)?.[1];
diff --git a/apps/server/src/routes/login.ts b/apps/server/src/routes/login.ts
index 024fe4c253..8cd026085b 100644
--- a/apps/server/src/routes/login.ts
+++ b/apps/server/src/routes/login.ts
@@ -10,8 +10,11 @@ import totp from '../services/totp.js';
function loginPage(req: Request, res: Response) {
// The login screen is served by the SPA at the root now (driven by the bootstrap
// `loggedIn: false` payload, which also surfaces any one-shot SSO error left by a
- // failed OIDC round-trip); redirect any direct hits there.
- res.redirect(".");
+ // failed OIDC round-trip); redirect any direct hits there. The `?login` marker
+ // tells checkAuth this is an explicit login navigation, so it isn't mistaken for
+ // a bare-domain hit and bounced to the share page (#10552). A direct hit on
+ // "/login/" (trailing slash) needs ".." — "." would resolve onto itself and loop.
+ res.redirect(req.path.endsWith("/") ? "../?login" : "./?login");
}
function setPasswordPage(req: Request, res: Response) {
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index c7a1247d44..803bd7ac7d 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -108,6 +108,7 @@ describe("Auth", () => {
return {
method: "GET",
path: "/test",
+ query: {},
ip: "127.0.0.1",
sessionID: "sid",
headers: {},
@@ -165,18 +166,43 @@ describe("Auth", () => {
const labelSpy = vi.spyOn(attributes, "getNotesWithLabel").mockReturnValue([]);
const resLogin = makeRes();
const nextLogin = vi.fn();
- auth.checkAuth(makeReq({ session: { loggedIn: false } }), resLogin as never, nextLogin);
+ auth.checkAuth(makeReq({ path: "/", session: { loggedIn: false } }), resLogin as never, nextLogin);
expect(nextLogin).toHaveBeenCalled();
expect(resLogin.statusCode).not.toBe(404);
labelSpy.mockReturnValue([{ noteId: "x" } as never]);
const resShare = makeRes();
- auth.checkAuth(makeReq({ session: { loggedIn: false } }), resShare as never, vi.fn());
+ auth.checkAuth(makeReq({ path: "/", session: { loggedIn: false } }), resShare as never, vi.fn());
expect(resShare.redirectedTo).toBe("share");
cls.init(() => options.setOption("redirectBareDomain", "false"));
});
+ it("checkAuth limits the bare-domain redirect to bare root requests (#10552)", () => {
+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
+ vi.spyOn(attributes, "getNotesWithLabel").mockReturnValue([{ noteId: "x" } as never]);
+ cls.init(() => options.setOption("redirectBareDomain", "true"));
+
+ // An explicit login navigation (GET /login redirects to the root with the
+ // `?login` marker) must reach the SPA login screen, not the share page.
+ const resLogin = makeRes();
+ const nextLogin = vi.fn();
+ auth.checkAuth(makeReq({ path: "/", query: { login: "" }, session: { loggedIn: false } }), resLogin as never, nextLogin);
+ expect(nextLogin).toHaveBeenCalled();
+ expect(resLogin.redirectedTo).toBeUndefined();
+
+ // SPA sub-requests such as /bootstrap must fall through too, or the login
+ // screen can never render its `loggedIn: false` payload.
+ const resBootstrap = makeRes();
+ const nextBootstrap = vi.fn();
+ auth.checkAuth(makeReq({ path: "/bootstrap", session: { loggedIn: false } }), resBootstrap as never, nextBootstrap);
+ expect(nextBootstrap).toHaveBeenCalled();
+ expect(resBootstrap.redirectedTo).toBeUndefined();
+
+ cls.init(() => options.setOption("redirectBareDomain", "false"));
+ });
+
it("checkAuth destroys the session and redirects when auth state changed", () => {
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);
diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.ts
index 5cd4d8333a..95b1178595 100644
--- a/apps/server/src/services/auth.ts
+++ b/apps/server/src/services/auth.ts
@@ -44,7 +44,14 @@ function checkAuth(req: Request, res: Response, next: NextFunction) {
// TriliumNextTODO: look into potentially creating an getOptionBoolOrNull instead
const hasRedirectBareDomain = options.getOptionOrNull("redirectBareDomain") === "true";
- if (hasRedirectBareDomain) {
+ // The redirect targets only a bare document request for the root. The login
+ // screen is served by the SPA at the root too, so an explicit login navigation
+ // (GET /login redirects here with a `?login` marker) and SPA sub-requests such
+ // as /bootstrap must fall through to it — otherwise enabling the option locks
+ // the owner out of the instance entirely (#10552).
+ const isBareRootRequest = req.path === "/" && req.query.login === undefined;
+
+ if (hasRedirectBareDomain && isBareRootRequest) {
// Only redirect to the share page when a share root is actually configured.
// Otherwise (e.g. the owner's session expired before they set one up) fall back
// to the login screen rather than stranding the user on a 404. See #7869.