Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into feat/fix-oidc-take1

Elian Doran97a48a880f12
diff --cc apps/server/src/assets/config-sample.ini
index 99629fc91e,30895ccbab..7fafd847e5
--- a/apps/server/src/assets/config-sample.ini
+++ b/apps/server/src/assets/config-sample.ini
@@@ -68,16 -68,19 +68,29 @@@ oauthIssuerName
# This is the icon of the service that will be used to verify the user's identity
oauthIssuerIcon=
+# 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
+
+ # How Trilium authenticates to the provider's token endpoint: client_secret_basic or
+ # client_secret_post. Leave empty to auto-detect (client_secret_post for GitLab and Google,
+ # client_secret_basic otherwise). Set client_secret_post if login fails with a
+ # WWW-Authenticate / invalid_client error and your credentials contain any of - _ . ! ~ * ' ( ),
+ # e.g. on a self-hosted GitLab. Must match the method your client is registered with.
+ oauthClientAuthMethod=
+
+ # The algorithm the provider signs ID tokens with, e.g. RS256, EdDSA or ES256. Leave empty to
+ # detect it from the provider's discovery document (RS256 is used whenever the provider offers it).
+ # Set this only if sign-in fails with "unexpected JWT alg received", which means the provider signs
+ # with an algorithm other than the one it advertises first.
+ oauthIdTokenSigningAlg=
+
[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 trust
diff --cc apps/server/src/services/config.ts
index 76983d5d59,5808838825..e72d9f73df
--- a/apps/server/src/services/config.ts
+++ b/apps/server/src/services/config.ts
@@@ -134,10 -134,16 +134,20 @@@ 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;
+ /**
+ * How to authenticate to the provider's token endpoint: 'client_secret_basic' or
+ * 'client_secret_post'. Leave empty to auto-detect from the issuer.
+ */
+ oauthClientAuthMethod: string;
+ /**
+ * The JWS algorithm the provider signs ID tokens with (e.g. 'RS256', 'EdDSA', 'ES256').
+ * Leave empty to auto-detect from the issuer's discovery document.
+ */
+ oauthIdTokenSigningAlg: string;
};
/** Logging configuration */
Logging: {
@@@ -477,29 -494,19 +498,43 @@@ const configMapping =
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), 10);
+ // 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';
+ // Normalize internal whitespace, and prepend the spec-required 'openid' if the user forgot it.
+ const tokens = trimmed.split(/\s+/);
+ return tokens.includes('openid') ? tokens.join(' ') : `openid ${tokens.join(' ')}`;
+ }
++ },
+ oauthClientAuthMethod: {
+ standardEnvVar: 'TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTAUTHMETHOD',
+ // alternative format
+ aliasEnvVars: ['TRILIUM_OAUTH_CLIENT_AUTH_METHOD'],
+ iniGetter: () => getIniSection("MultiFactorAuthentication")?.oauthClientAuthMethod,
+ defaultValue: ''
+ },
+ oauthIdTokenSigningAlg: {
+ standardEnvVar: 'TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHIDTOKENSIGNINGALG',
+ // alternative format
+ aliasEnvVars: ['TRILIUM_OAUTH_ID_TOKEN_SIGNING_ALG'],
+ iniGetter: () => getIniSection("MultiFactorAuthentication")?.oauthIdTokenSigningAlg,
+ defaultValue: ''
}
},
Logging: {
@@@ -584,8 -591,8 +619,10 @@@ const config: TriliumConfig =
oauthIssuerBaseUrl: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerBaseUrl),
oauthIssuerName: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerName),
oauthIssuerIcon: getConfigValue(configMapping.MultiFactorAuthentication.oauthIssuerIcon),
+ oauthHttpTimeout: getConfigValue(configMapping.MultiFactorAuthentication.oauthHttpTimeout),
- oauthScope: getConfigValue(configMapping.MultiFactorAuthentication.oauthScope)
++ oauthScope: getConfigValue(configMapping.MultiFactorAuthentication.oauthScope),
+ oauthClientAuthMethod: getConfigValue(configMapping.MultiFactorAuthentication.oauthClientAuthMethod),
+ oauthIdTokenSigningAlg: getConfigValue(configMapping.MultiFactorAuthentication.oauthIdTokenSigningAlg)
},
Logging: {
retentionDays: getConfigValue(configMapping.Logging.retentionDays)
@@@ -649,8 -656,7 +686,10 @@@
* - 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')
+ * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTAUTHMETHOD : Token-endpoint auth method
++ * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHIDTOKENSIGNINGALG : ID token signing algorithm
*
* Logging Section:
* - TRILIUM_LOGGING_RETENTIONDAYS : Log retention period in days
diff --cc apps/server/src/services/open_id.ts
index 005bf44903,81b0ae6e01..90198af51e
--- a/apps/server/src/services/open_id.ts
+++ b/apps/server/src/services/open_id.ts
@@@ -153,27 -164,17 +165,31 @@@ function generateOAuthConfig
secret: config.MultiFactorAuthentication.oauthClientSecret,
clientSecret: config.MultiFactorAuthentication.oauthClientSecret,
clientAuthMethod: resolveClientAuthMethod(),
+ // Also not read straight from config: express-openid-connect hardcodes RS256 unless told
+ // otherwise, so this comes from the discovery probe via resolveIdTokenSigningAlg. Defaulted for
+ // callers that don't probe.
+ idTokenSigningAlg,
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,
+ routes: { ...OIDC_ROUTES },
// Only enable RP-Initiated Logout when the provider actually advertises an end_session_endpoint
- // (see isRpInitiatedLogoutSupported). With idpLogout on, express-openid-connect unconditionally
+ // (see supportsRpInitiatedLogout). With idpLogout on, express-openid-connect unconditionally
// builds a redirect to that endpoint at logout; providers without one (e.g. Google, Authelia)
// would otherwise crash POST /logout with a 500. When false, logout falls back to clearing the
// local session and redirecting to postLogoutRedirect.
diff --cc docs/User Guide/User Guide/Installation & Setup/Server Installation/Signing in with OpenID Connect.md
index 6eed00f884,69e38bea2b..d002c0cf94
--- 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,18 -36,10 +36,18 @@@ Setting up authentication with OpenID c
| 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`, `TRILIUM_OAUTH_HTTP_TIMEOUT`, `TRILIUM_OAUTH_SCOPE`
-> 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_CLIENT_AUTH_METHOD`, `TRILIUM_OAUTH_ID_TOKEN_SIGNING_ALG` .
++> 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`, `TRILIUM_OAUTH_CLIENT_AUTH_METHOD`, `TRILIUM_OAUTH_ID_TOKEN_SIGNING_ALG`.
## Connecting to the authentication provider