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
fix(oauth): apply MFA-method switch to OpenID without a server restart
Elian Dorandc7ffbbb9f73
diff --git a/apps/server/src/app.ts b/apps/server/src/app.tsindex 4800c8176f..b2d96fabe5 100644--- a/apps/server/src/app.ts+++ b/apps/server/src/app.ts@@ -5,7 +5,6 @@ import compression from "compression";import cookieParser from "cookie-parser";import ejs from "ejs";import express from "express";-import { auth } from "express-openid-connect";import helmet from "helmet";import { t } from "i18next";import path from "path";@@ -19,7 +18,7 @@ import mcpRoutes from "./routes/mcp.js";import routes from "./routes/routes.js";import config from "./services/config.js";import { getLog } from "@triliumnext/core";-import openID from "./services/open_id.js";+import { createReactiveOidcMiddleware } from "./services/open_id.js";import { RESOURCE_DIR } from "./services/resource_dir.js";import utils, { getResourceDir, isDev } from "./services/utils.js";@@ -111,14 +110,11 @@ export default async function buildApp() {startSessionCleanup();app.use(favicon(path.join(assetsDir, isDev ? "icon-dev.ico" : "icon.ico")));- // Mount the OIDC middleware whenever OAuth is configured — not only once an account is enrolled —- // so the provider round-trip is available for the owner's first (enrollment) sign-in too.- if (openID.isOpenIDConfigured()) {- // Probe the provider's discovery document once here so RP-Initiated Logout is only enabled when- // the provider supports it (otherwise POST /logout 500s); see isRpInitiatedLogoutSupported.- const endSessionSupported = await openID.isRpInitiatedLogoutSupported();- app.use(auth(openID.generateOAuthConfig(endSessionSupported)));- }+ // Always mount the OIDC middleware, but have it activate reactively from the current `mfaMethod`+ // option rather than from a one-time startup check. This lets a switch to (or away from) OpenID take+ // effect without a server restart; the underlying express-openid-connect handler is built lazily on+ // first use, so it costs nothing while OAuth is unselected. See createReactiveOidcMiddleware.+ app.use(createReactiveOidcMiddleware());await assets.register(app);routes.register(app);diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.tsindex 9d626fe80e..2d66fa5dc6 100644--- a/apps/server/src/services/open_id.spec.ts+++ b/apps/server/src/services/open_id.spec.ts@@ -1,9 +1,10 @@import { cls, options } from "@triliumnext/core";+import type { NextFunction, Request as ExpressRequest, RequestHandler, Response as ExpressResponse } from "express";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import config from "./config.js";import openIDEncryption from "./encryption/open_id_encryption.js";-import openID, { resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";+import openID, { createReactiveOidcMiddleware, resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";import sql from "./sql.js";import sqlInit from "./sql_init.js";@@ -426,3 +427,146 @@ describe("open_id", () => {});});});++/**+ * The reactive OIDC middleware is the fix for "switching the MFA method to OpenID requires a server+ * restart". The old code decided *once at startup* whether to mount express-openid-connect; these tests+ * pin down the new contract: the middleware is always mounted, re-evaluates `isOpenIDConfigured()` on+ * every request, and lazily builds (and caches) the underlying handler the first time OAuth is used.+ */+describe("createReactiveOidcMiddleware", () => {+ function setup() {+ let configured = false;++ const oidcHandler = vi.fn(((_req, _res, next) => next()) as RequestHandler);+ const buildAuth = vi.fn(() => oidcHandler);+ const isRpInitiatedLogoutSupported = vi.fn().mockResolvedValue(false);+ const generateOAuthConfig = vi.fn((endSessionSupported: boolean) => ({ endSessionSupported }) as never);+ const isConfigured = vi.fn(() => configured);++ const middleware = createReactiveOidcMiddleware({+ isConfigured,+ isRpInitiatedLogoutSupported,+ generateOAuthConfig,+ buildAuth+ });++ return {+ middleware,+ oidcHandler,+ buildAuth,+ isRpInitiatedLogoutSupported,+ generateOAuthConfig,+ isConfigured,+ setConfigured: (value: boolean) => { configured = value; }+ };+ }++ async function run(middleware: RequestHandler) {+ const next = vi.fn() as unknown as NextFunction;+ const req = {} as ExpressRequest;+ const res = {} as ExpressResponse;+ await middleware(req, res, next);+ return { next, req, res };+ }++ it("passes through without building the OIDC handler when OAuth is not selected", async () => {+ const t = setup(); // starts unconfigured++ const { next } = await run(t.middleware);++ expect(next).toHaveBeenCalledOnce();+ expect(t.buildAuth).not.toHaveBeenCalled();+ expect(t.oidcHandler).not.toHaveBeenCalled();+ // No work is done while OAuth is unselected — not even the discovery probe.+ expect(t.isRpInitiatedLogoutSupported).not.toHaveBeenCalled();+ });++ it("builds and delegates to the OIDC handler when OAuth is selected", async () => {+ const t = setup();+ t.setConfigured(true);++ const { req, res, next } = await run(t.middleware);++ expect(t.isRpInitiatedLogoutSupported).toHaveBeenCalledOnce();+ expect(t.generateOAuthConfig).toHaveBeenCalledWith(false);+ expect(t.buildAuth).toHaveBeenCalledOnce();+ expect(t.oidcHandler).toHaveBeenCalledWith(req, res, expect.any(Function));+ // The wrapper must hand off to the OIDC handler and NOT call next() itself — calling it again+ // after the handler already drove the request double-invokes the pipeline ("Cannot set headers+ // after they are sent"). Exactly one next() (the one the handler makes) must reach the chain.+ expect(next).toHaveBeenCalledOnce();+ });++ it("builds the underlying handler only once across requests (cached)", async () => {+ const t = setup();+ t.setConfigured(true);++ await run(t.middleware);+ await run(t.middleware);++ expect(t.buildAuth).toHaveBeenCalledOnce();+ expect(t.isRpInitiatedLogoutSupported).toHaveBeenCalledOnce();+ expect(t.oidcHandler).toHaveBeenCalledTimes(2);+ });++ it("passes the discovery-probe result into the OAuth config", async () => {+ const t = setup();+ t.isRpInitiatedLogoutSupported.mockResolvedValue(true);+ t.setConfigured(true);++ await run(t.middleware);++ expect(t.generateOAuthConfig).toHaveBeenCalledWith(true);+ });++ // This is the regression the whole change exists to fix: with the old startup-only mount, flipping+ // mfaMethod to "oauth" at runtime did nothing until a restart. Here the same instance starts+ // unselected (passes through) and then activates on the next request after the option flips.+ it("activates without a restart when the sign-in method switches to OAuth at runtime", async () => {+ const t = setup(); // unconfigured at "boot"++ await run(t.middleware);+ expect(t.buildAuth).not.toHaveBeenCalled();+ expect(t.oidcHandler).not.toHaveBeenCalled();++ // User switches the MFA method to OpenID in Settings — no restart.+ t.setConfigured(true);++ const { req, res } = await run(t.middleware);+ expect(t.buildAuth).toHaveBeenCalledOnce();+ expect(t.oidcHandler).toHaveBeenCalledWith(req, res, expect.any(Function));+ });++ it("stops delegating when OAuth is deselected at runtime", async () => {+ const t = setup();+ t.setConfigured(true);+ await run(t.middleware); // builds + delegates+ expect(t.oidcHandler).toHaveBeenCalledOnce();++ // Switch back to local/TOTP — the request should pass straight through again.+ t.setConfigured(false);+ const { next } = await run(t.middleware);++ expect(next).toHaveBeenCalledOnce();+ expect(t.oidcHandler).toHaveBeenCalledOnce(); // not invoked a second time+ });++ it("builds the handler only once even under concurrent first requests", async () => {+ const t = setup();+ t.setConfigured(true);++ // A deferred discovery probe keeps the first build in flight while a second request arrives,+ // exercising the in-flight-init guard (otherwise both requests would each build a handler).+ let resolveProbe: (value: boolean) => void = () => {};+ t.isRpInitiatedLogoutSupported.mockReturnValue(new Promise<boolean>((resolve) => { resolveProbe = resolve; }));++ const first = run(t.middleware);+ const second = run(t.middleware);+ resolveProbe(false);+ await Promise.all([first, second]);++ expect(t.buildAuth).toHaveBeenCalledOnce();+ expect(t.oidcHandler).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.tsindex 7e5da44926..80621413bb 100644--- a/apps/server/src/services/open_id.ts+++ b/apps/server/src/services/open_id.ts@@ -1,6 +1,6 @@import { getLog, options } from "@triliumnext/core";-import type { NextFunction, Request, Response } from "express";-import type { Session } from "express-openid-connect";+import type { NextFunction, Request, RequestHandler, Response } from "express";+import { auth, type Session } from "express-openid-connect";import config from "./config.js";import openIDEncryption from "./encryption/open_id_encryption.js";@@ -246,6 +246,69 @@ function generateOAuthConfig(endSessionSupported = false) {return authConfig;}+type AuthBuilder = typeof auth;++interface ReactiveOidcDeps {+ /** Whether OAuth is currently configured and selected as the sign-in method. Re-checked per request. */+ isConfigured: () => boolean;+ /** Discovery probe deciding whether RP-Initiated Logout (idpLogout) can be safely enabled. */+ isRpInitiatedLogoutSupported: () => Promise<boolean>;+ /** Builds the express-openid-connect config for the current provider settings. */+ generateOAuthConfig: (endSessionSupported: boolean) => Parameters<AuthBuilder>[0];+ /** The express-openid-connect `auth()` factory (injectable so the middleware is unit-testable). */+ buildAuth: AuthBuilder;+}++/**+ * Builds the always-mounted OIDC middleware.+ *+ * The provider round-trip used to be mounted only once, at server startup, gated on whether OAuth was+ * the selected sign-in method at that moment. That coupled a *permanent* mounting decision to the+ * *runtime-mutable* `mfaMethod` option, so switching to OpenID in Settings did nothing until a restart.+ *+ * This middleware is mounted unconditionally and instead re-evaluates `isOpenIDConfigured()` on every+ * request: while OAuth is unselected it simply passes through, and the first time OAuth is actually in+ * use it lazily builds the underlying express-openid-connect handler and caches it. The discovery probe+ * (endSessionSupported) only depends on the issuer — which is fixed in config and changes solely on+ * restart — so it is resolved once on that first use. An in-flight guard ensures concurrent first+ * requests build the handler exactly once.+ */+export function createReactiveOidcMiddleware(deps: Partial<ReactiveOidcDeps> = {}): RequestHandler {+ const {+ isConfigured = isOpenIDConfigured,+ isRpInitiatedLogoutSupported: probeRpLogout = isRpInitiatedLogoutSupported,+ generateOAuthConfig: buildOAuthConfig = generateOAuthConfig,+ buildAuth = auth+ } = deps;++ let oidcMiddleware: RequestHandler | null = null;+ let oidcInit: Promise<void> | null = null;++ return async (req: Request, res: Response, next: NextFunction) => {+ // OAuth not selected as the sign-in method → behave as if the middleware were never mounted.+ if (!isConfigured()) {+ return next();+ }++ if (!oidcMiddleware) {+ oidcInit ??= (async () => {+ const endSessionSupported = await probeRpLogout();+ oidcMiddleware = buildAuth(buildOAuthConfig(endSessionSupported));+ })();+ await oidcInit;+ }++ // Hand off entirely to the express-openid-connect handler: it drives the request by side effect+ // (sends a response/redirect or calls next() itself) and returns undefined. We must NOT call+ // next() ourselves afterwards — doing so double-invokes the downstream pipeline and triggers+ // "Cannot set headers after they are sent". The guard only covers a failed build.+ if (!oidcMiddleware) {+ return next();+ }+ return oidcMiddleware(req, res, next);+ };+}+export default {generateOAuthConfig,getOAuthStatus,