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(oidc): configurable HTTP timeout, session lifetime, scopes, and error logging
perfectra1nda86a4baee61
diff --git a/apps/server/src/assets/config-sample.ini b/apps/server/src/assets/config-sample.iniindex 1e89aa8d9c..99629fc91e 100644--- a/apps/server/src/assets/config-sample.ini+++ b/apps/server/src/assets/config-sample.ini@@ -68,6 +68,16 @@ oauthIssuerName=# This is the icon of the service that will be used to verify the user's identityoauthIssuerIcon=+# Timeout in milliseconds for OAuth/OpenID HTTP requests (discovery, token exchange, userinfo).+# The library default is 5000ms, which cold-start identity providers can exceed and cause a+# spurious "have to log in twice" experience. Raised here to 30000ms. Minimum accepted value is 500.+oauthHttpTimeout=30000++# Space-separated list of OIDC scopes requested at login. 'openid' is required and prepended+# automatically if omitted. Add 'offline_access' here if your provider needs it to issue a+# refresh token. Default: openid profile email+oauthScope=openid profile email+[Security]# Enable backend script execution. WARNING: Backend scripts have full server access including# filesystem, network, and OS commands via require('child_process'). Only enable if you trustdiff --git a/apps/server/src/services/config.spec.ts b/apps/server/src/services/config.spec.tsindex f5022e80f0..c3e62d03a9 100644--- a/apps/server/src/services/config.spec.ts+++ b/apps/server/src/services/config.spec.ts@@ -140,6 +140,8 @@ describe("Config Service", () => {process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL = "https://issuer.standard.com";process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME = "Standard Auth";process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON = "standard-icon.png";+ process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT = "45000";+ process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE = "openid profile email offline_access";let { default: config } = await import("./config.js");@@ -149,6 +151,8 @@ describe("Config Service", () => {expect(config.MultiFactorAuthentication.oauthIssuerBaseUrl).toBe("https://issuer.standard.com");expect(config.MultiFactorAuthentication.oauthIssuerName).toBe("Standard Auth");expect(config.MultiFactorAuthentication.oauthIssuerIcon).toBe("standard-icon.png");+ expect(config.MultiFactorAuthentication.oauthHttpTimeout).toBe(45000);+ expect(config.MultiFactorAuthentication.oauthScope).toBe("openid profile email offline_access");// Clear and test with alias namingObject.keys(process.env).forEach(key => {@@ -163,7 +167,9 @@ describe("Config Service", () => {process.env.TRILIUM_OAUTH_ISSUER_BASE_URL = "https://issuer.alias.com";process.env.TRILIUM_OAUTH_ISSUER_NAME = "Alias Auth";process.env.TRILIUM_OAUTH_ISSUER_ICON = "alias-icon.png";-+ process.env.TRILIUM_OAUTH_HTTP_TIMEOUT = "15000";+ process.env.TRILIUM_OAUTH_SCOPE = "openid email";+vi.resetModules();config = (await import("./config.js")).default;@@ -173,6 +179,27 @@ describe("Config Service", () => {expect(config.MultiFactorAuthentication.oauthIssuerBaseUrl).toBe("https://issuer.alias.com");expect(config.MultiFactorAuthentication.oauthIssuerName).toBe("Alias Auth");expect(config.MultiFactorAuthentication.oauthIssuerIcon).toBe("alias-icon.png");+ expect(config.MultiFactorAuthentication.oauthHttpTimeout).toBe(15000);+ expect(config.MultiFactorAuthentication.oauthScope).toBe("openid email");+ });++ it("should apply oauthHttpTimeout and oauthScope transformers (defaults, bounds, openid prefix)", async () => {+ // Timeout below the express-openid-connect minimum (500) falls back to the 30000 default.+ process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT = "100";+ // Scope missing the mandatory 'openid' token gets it prepended.+ process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE = "profile email offline_access";++ let { default: config } = await import("./config.js");+ expect(config.MultiFactorAuthentication.oauthHttpTimeout).toBe(30000);+ expect(config.MultiFactorAuthentication.oauthScope).toBe("openid profile email offline_access");++ // Non-numeric timeout and blank scope both fall back to their defaults.+ process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT = "not-a-number";+ process.env.TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE = " ";+ vi.resetModules();+ config = (await import("./config.js")).default;+ expect(config.MultiFactorAuthentication.oauthHttpTimeout).toBe(30000);+ expect(config.MultiFactorAuthentication.oauthScope).toBe("openid profile email");});it("should handle all Sync environment variables correctly", async () => {diff --git a/apps/server/src/services/config.ts b/apps/server/src/services/config.tsindex a8975e26e0..67b0f66ead 100644--- a/apps/server/src/services/config.ts+++ b/apps/server/src/services/config.ts@@ -134,6 +134,10 @@ export interface TriliumConfig {oauthIssuerName: string;/** URL to the OAuth provider's icon/logo */oauthIssuerIcon: string;+ /** Timeout in milliseconds for OAuth/OIDC HTTP requests (discovery, token exchange, userinfo). Default: 30000 */+ oauthHttpTimeout: number;+ /** Space-separated OIDC scopes requested at login. Default: 'openid profile email' */+ oauthScope: string;};/** Logging configuration */Logging: {@@ -472,6 +476,30 @@ const configMapping = {aliasEnvVars: ['TRILIUM_OAUTH_ISSUER_ICON'],iniGetter: () => getIniSection("MultiFactorAuthentication")?.oauthIssuerIcon,defaultValue: ''+ },+ oauthHttpTimeout: {+ standardEnvVar: 'TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT',+ aliasEnvVars: ['TRILIUM_OAUTH_HTTP_TIMEOUT'],+ iniGetter: () => getIniSection("MultiFactorAuthentication")?.oauthHttpTimeout,+ defaultValue: 30000,+ transformer: (value: unknown) => {+ const parsed = parseInt(String(value));+ // express-openid-connect requires httpTimeout >= 500; fall back to the default otherwise.+ return Number.isFinite(parsed) && parsed >= 500 ? parsed : 30000;+ }+ },+ oauthScope: {+ standardEnvVar: 'TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE',+ aliasEnvVars: ['TRILIUM_OAUTH_SCOPE'],+ iniGetter: () => getIniSection("MultiFactorAuthentication")?.oauthScope,+ defaultValue: 'openid profile email',+ transformer: (value: unknown) => {+ const trimmed = String(value).trim();+ if (!trimmed) return 'openid profile email';+ // 'openid' is required by the OIDC spec; silently prepend it if the user forgot.+ const tokens = trimmed.split(/\s+/);+ return tokens.includes('openid') ? trimmed : `openid ${trimmed}`;+ }}},Logging: {@@ -555,7 +583,9 @@ const config: TriliumConfig = {oauthClientSecret: getConfigValue(configMapping.MultiFactorAuthentication.oauthClientSecret),oauthIssuerBaseUrl: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerBaseUrl),oauthIssuerName: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerName),- oauthIssuerIcon: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerIcon)+ oauthIssuerIcon: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerIcon),+ oauthHttpTimeout: getConfigValue(configMapping.MultiFactorAuthentication.oauthHttpTimeout),+ oauthScope: getConfigValue(configMapping.MultiFactorAuthentication.oauthScope)},Logging: {retentionDays: getConfigValue(configMapping.Logging.retentionDays)@@ -619,6 +649,8 @@ const config: TriliumConfig = {* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL : OAuth issuer URL* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME : OAuth provider name* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON : OAuth provider icon+ * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT : OAuth HTTP timeout in ms (default 30000)+ * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE : Space-separated OIDC scopes (default 'openid profile email')** Logging Section:* - TRILIUM_LOGGING_RETENTIONDAYS : Log retention period in days@@ -644,6 +676,8 @@ const config: TriliumConfig = {* - TRILIUM_OAUTH_ISSUER_BASE_URL : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL* - TRILIUM_OAUTH_ISSUER_NAME : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME* - TRILIUM_OAUTH_ISSUER_ICON : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON+ * - TRILIUM_OAUTH_HTTP_TIMEOUT : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT+ * - TRILIUM_OAUTH_SCOPE : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE** Logging (with underscore):* - TRILIUM_LOGGING_RETENTION_DAYS : Same as TRILIUM_LOGGING_RETENTIONDAYSdiff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.tsindex 7a16f9e012..d5ead36d8c 100644--- a/apps/server/src/services/open_id.spec.ts+++ b/apps/server/src/services/open_id.spec.ts@@ -194,6 +194,26 @@ describe("open_id", () => {expect(openID.generateOAuthConfig(true).idpLogout).toBe(true);});+ it("requests the scope configured via oauthScope", () => {+ setOauthConfig(true);+ mfa.oauthScope = "openid profile email offline_access";+ expect(openID.generateOAuthConfig().authorizationParams.scope).toBe("openid profile email offline_access");+ });++ it("passes the configured oauthHttpTimeout through to the library", () => {+ setOauthConfig(true);+ mfa.oauthHttpTimeout = 45000;+ expect(openID.generateOAuthConfig().httpTimeout).toBe(45000);+ });++ it("bounds the OIDC appSession lifetime to cookieMaxAge (rolling + absolute)", () => {+ setOauthConfig(true);+ const cfg = openID.generateOAuthConfig();+ expect(cfg.session?.rolling).toBe(true);+ expect(cfg.session?.rollingDuration).toBe(config.Session.cookieMaxAge);+ expect(cfg.session?.absoluteDuration).toBe(config.Session.cookieMaxAge);+ });+it("returns the session unchanged when the DB is not initialized", async () => {const cfg = buildConfig();const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.tsindex 7f676aeed6..005bf44903 100644--- a/apps/server/src/services/open_id.ts+++ b/apps/server/src/services/open_id.ts@@ -89,7 +89,8 @@ async function isTokenValid(req: Request, res: Response, next: NextFunction) {message: "Token is valid",user: userStatus,};- } catch {+ } catch (err) {+ getLog().info(`OIDC token validation failed: ${err instanceof Error ? err.message : String(err)}`);return {success: false,message: "Token is not valid",@@ -154,7 +155,21 @@ function generateOAuthConfig(endSessionSupported = false) {clientAuthMethod: resolveClientAuthMethod(),authorizationParams: {response_type: "code",- scope: "openid profile email",+ scope: config.MultiFactorAuthentication.oauthScope,+ },+ // Override the library's default 5000 ms timeout for discovery / token-exchange / userinfo requests.+ // Cold-start IdP responses (e.g. a scaled-to-zero provider) routinely exceed 5s and manifest as a+ // spurious "login twice" failure; the default is raised to 30s and is configurable via oauthHttpTimeout.+ httpTimeout: config.MultiFactorAuthentication.oauthHttpTimeout,+ // Match the OIDC appSession cookie lifetime to Trilium's own trilium.sid cookie. The library defaults+ // (24h rolling, 7d absolute) silently capped the effective Trilium session at 7 days when SSO was on.+ // Both bounds are set to cookieMaxAge (seconds; default 21d): rollingDuration is required when+ // rolling: true, and keeping absoluteDuration as a hard cap follows OWASP / Auth0 guidance that every+ // session should have an upper bound regardless of activity.+ session: {+ rolling: true,+ rollingDuration: config.Session.cookieMaxAge,+ absoluteDuration: config.Session.cookieMaxAge,},routes: authRoutes,// Only enable RP-Initiated Logout when the provider actually advertises an end_session_endpointdiff --git a/docs/User Guide/User Guide/Advanced Usage/Configuration (config.ini or environment variables).md b/docs/User Guide/User Guide/Advanced Usage/Configuration (config.ini or environment variables).mdindex bf2e51eabd..827c94f576 100644--- a/docs/User Guide/User Guide/Advanced Usage/Configuration (config.ini or environment variables).md+++ b/docs/User Guide/User Guide/Advanced Usage/Configuration (config.ini or environment variables).md@@ -75,6 +75,8 @@ Additionally, shorter aliases are available for common configurations (see Alter| `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL` | string | "[https://accounts.google.com](https://accounts.google.com)" | OAuth issuer base URL || `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME` | string | "Google" | OAuth issuer display name || `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON` | string | "" | OAuth issuer icon URL |+| `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT` | integer | 30000 | Timeout in milliseconds for OAuth/OpenID HTTP requests (discovery, token exchange, userinfo). Minimum 500 |+| `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE` | string | "openid profile email" | Space-separated OIDC scopes requested at login (`openid` is prepended automatically if omitted) |### Logging Section@@ -113,6 +115,8 @@ The following alternative environment variable names are also supported and work* `TRILIUM_OAUTH_ISSUER_BASE_URL` (alternative to `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL`)* `TRILIUM_OAUTH_ISSUER_NAME` (alternative to `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME`)* `TRILIUM_OAUTH_ISSUER_ICON` (alternative to `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON`)+* `TRILIUM_OAUTH_HTTP_TIMEOUT` (alternative to `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT`)+* `TRILIUM_OAUTH_SCOPE` (alternative to `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE`)### Logging Variablesdiff --git a/docs/User Guide/User Guide/Installation & Setup/Server Installation/Signing in with OpenID Connect.md b/docs/User Guide/User Guide/Installation & Setup/Server Installation/Signing in with OpenID Connect.mdindex 79bf17755b..6eed00f884 100644--- a/docs/User Guide/User Guide/Installation & Setup/Server Installation/Signing in with OpenID Connect.md+++ b/docs/User Guide/User Guide/Installation & Setup/Server Installation/Signing in with OpenID Connect.md@@ -34,10 +34,18 @@ Setting up authentication with OpenID connect is a two-step process:| Issuer icon | `oauthIssuerIcon` | `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON` | Optionally, the URL to a logo of the provider. By default it will try to obtain the favicon from the website, so it's optional. |All the fields here are optional, since the default OAuth issuer is Google.-4. Restart the server so that the changes are applied.+4. Optionally, tune the following advanced settings. All are optional and have sensible defaults:++ | Configuration | `config.ini` in `[MultiFactorAuthentication]` section | Environment variable | Description |+ | --- | --- | --- | --- |+ | HTTP timeout | `oauthHttpTimeout` | `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT` | Timeout in milliseconds for the provider HTTP requests (discovery, token exchange, userinfo). Defaults to `30000` (30s). Raise this if your provider cold-starts slowly and you are occasionally asked to sign in twice. Minimum accepted value is `500`. |+ | Scopes | `oauthScope` | `TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE` | Space-separated list of OIDC scopes requested at login. Defaults to `openid profile email`. `openid` is required and is prepended automatically if you omit it. |++ The OIDC session lifetime is automatically bound to Trilium's own session cookie lifetime (the `cookieMaxAge` setting in the `[Session]` section, 21 days by default), so a single sign-in stays valid for as long as your Trilium session does rather than expiring early on the OIDC library's shorter internal defaults.+5. Restart the server so that the changes are applied.> [!NOTE]-> Legacy environment variables are also supported: `TRILIUM_OAUTH_BASE_URL`, `TRILIUM_OAUTH_CLIENT_ID`, `TRILIUM_OAUTH_CLIENT_SECRET`, and for customizing the provider: `TRILIUM_OAUTH_ISSUER_BASE_URL`, `TRILIUM_OAUTH_ISSUER_NAME`, `TRILIUM_OAUTH_ISSUER_ICON`+> Legacy environment variables are also supported: `TRILIUM_OAUTH_BASE_URL`, `TRILIUM_OAUTH_CLIENT_ID`, `TRILIUM_OAUTH_CLIENT_SECRET`, and for customizing the provider: `TRILIUM_OAUTH_ISSUER_BASE_URL`, `TRILIUM_OAUTH_ISSUER_NAME`, `TRILIUM_OAUTH_ISSUER_ICON`, `TRILIUM_OAUTH_HTTP_TIMEOUT`, `TRILIUM_OAUTH_SCOPE`## Connecting to the authentication provider