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): select token-endpoint auth from provider discovery, closes #10585
Elian Doran48609b3cce48
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 991b399bdb..d28a41fde4 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -95,6 +95,7 @@"multer": "2.2.0","normalize-strings": "1.1.1","officeparser": "7.3.0",+ "openid-client": "6.8.4","rand-token": "1.0.1","safe-compare": "1.1.4","serve-favicon": "2.5.1",diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.tsindex 7a16f9e012..9a0d0385d1 100644--- a/apps/server/src/services/open_id.spec.ts+++ b/apps/server/src/services/open_id.spec.ts@@ -1,10 +1,11 @@import { cls, options } from "@triliumnext/core";import type { NextFunction, Request as ExpressRequest, RequestHandler, Response as ExpressResponse } from "express";+import { ClientSecretBasic, ClientSecretPost } from "openid-client";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import config from "./config.js";import openIDEncryption from "./encryption/open_id_encryption.js";-import openID, { createReactiveOidcMiddleware, resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";+import openID, { createReactiveOidcMiddleware, type ProviderCapabilities, resolveClientAuthMethod, resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";import sql from "./sql.js";import sqlInit from "./sql_init.js";@@ -174,24 +175,22 @@ describe("open_id", () => {expect(typeof cfg.afterCallback).toBe("function");});- it("auto-selects the token-endpoint auth method by issuer", () => {+ it("passes the probed provider capabilities through to express-openid-connect", () => {setOauthConfig(true);- // Non-Google issuer (the setOauthConfig default) → spec-default client_secret_basic.- expect(openID.generateOAuthConfig().clientAuthMethod).toBe("client_secret_basic");-- // Google issuer (trailing slash tolerated) → client_secret_post, since Google rejects the- // RFC-encoded Basic credentials (client_ids contain "-"/"." which become %2D/%2E).- mfa.oauthIssuerBaseUrl = "https://accounts.google.com/";- expect(openID.generateOAuthConfig().clientAuthMethod).toBe("client_secret_post");- });+ // Without a probe result, both settings fall back to the conservative spec defaults.+ expect(openID.generateOAuthConfig()).toMatchObject({+ clientAuthMethod: "client_secret_basic",+ idpLogout: false+ });- it("enables RP-Initiated Logout (idpLogout) only when the provider supports it", () => {- setOauthConfig(true);- // Default off, and on only when discovery confirmed an end_session_endpoint at startup.- expect(openID.generateOAuthConfig().idpLogout).toBe(false);- expect(openID.generateOAuthConfig(false).idpLogout).toBe(false);- expect(openID.generateOAuthConfig(true).idpLogout).toBe(true);+ expect(openID.generateOAuthConfig({+ endSessionSupported: true,+ clientAuthMethod: "client_secret_post"+ })).toMatchObject({+ clientAuthMethod: "client_secret_post",+ idpLogout: true+ });});it("returns the session unchanged when the DB is not initialized", async () => {@@ -381,8 +380,85 @@ describe("open_id", () => {});});- describe("isRpInitiatedLogoutSupported", () => {+ /**+ * Regression cover for #10585: OIDC login against GitLab broke in v0.104.0 with+ * `OAUTH_WWW_AUTHENTICATE_CHALLENGE`.+ *+ * The cause is the express-openid-connect 2.20.2 → 3.2.0 bump (openid-client v5 → v6/oauth4webapi).+ * v6's `ClientSecretBasic` applies strict RFC 6749 §2.3.1 form-encoding *inside* the HTTP Basic+ * header, escaping `- _ . ! ~ * ' ( )`; v5 used plain `encodeURIComponent`, which leaves them alone.+ * GitLab's client secrets are prefixed `gloas-`, so the hyphen becomes `%2D` and GitLab's Doorkeeper+ * token endpoint — which base64-decodes the header but does not percent-decode it — sees a wrong+ * secret and answers 401 + `WWW-Authenticate`.+ *+ * The method must therefore be picked from the provider's own discovery document rather than+ * hardcoded per issuer (the previous Google-only special case had the identical root cause).+ */+ describe("resolveClientAuthMethod", () => {+ // Verbatim from https://gitlab.com/.well-known/openid-configuration.+ const GITLAB = { token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"] };+ const GOOGLE = { token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic"] };+ const BASIC_ONLY = { token_endpoint_auth_methods_supported: ["client_secret_basic"] };++ it("prefers client_secret_post whenever the provider advertises it", () => {+ // Body-posted credentials are form-encoded by the transport and arrive intact, so post is+ // the safe choice for any provider that accepts it — regardless of issuer.+ expect(resolveClientAuthMethod(GITLAB)).toBe("client_secret_post");+ expect(resolveClientAuthMethod(GOOGLE)).toBe("client_secret_post");+ });++ it("falls back to client_secret_basic when post is unavailable or discovery is unusable", () => {+ // A provider that registers confidential clients as basic-only must still get basic.+ expect(resolveClientAuthMethod(BASIC_ONLY)).toBe("client_secret_basic");+ // Field absent → the OIDC Core default for the token endpoint is client_secret_basic.+ expect(resolveClientAuthMethod({ issuer: "https://idp.example" })).toBe("client_secret_basic");+ // Malformed / missing metadata (a failed discovery probe) fails safe to the spec default+ // rather than silently switching every provider's authentication method.+ expect(resolveClientAuthMethod({ token_endpoint_auth_methods_supported: "client_secret_post" })).toBe("client_secret_basic");+ expect(resolveClientAuthMethod(null)).toBe("client_secret_basic");+ expect(resolveClientAuthMethod(undefined)).toBe("client_secret_basic");+ });++ /**+ * The end-to-end property the fix actually has to hold: whatever method we select, the+ * credentials must reach the token endpoint byte-identical to what the user configured. This+ * drives the real openid-client encoders, so a future dependency bump that reintroduces the+ * mangling fails here rather than in production.+ */+ it("delivers a GitLab-style secret to the token endpoint intact", () => {+ // GitLab: 64-hex Application ID, `gloas-` prefixed secret (the hyphen is what breaks Basic).+ const clientId = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2";+ const clientSecret = "gloas-4f3a2b1c-9d8e-7f6a-5b4c-3d2e1f0a9b8c";++ const received = credentialsAtTokenEndpoint(resolveClientAuthMethod(GITLAB), clientId, clientSecret);++ expect(received).toEqual({ clientId, clientSecret });+ });++ /**+ * The basic-only fallback has no safer method to fall back *to*, so it stays correct only for a+ * provider that percent-decodes per spec. Both halves are pinned here so the tradeoff is explicit:+ * choosing basic is safe for a compliant provider and lossy for a non-compliant one — which is+ * precisely why post is preferred wherever it's on offer.+ */+ it("relies on the provider decoding per spec when it only offers basic", () => {+ // The credentials from Trilium's own Authelia dev harness; the "_" is what Basic escapes.+ const clientId = "trilium";+ const clientSecret = "insecure_secret";+ const method = resolveClientAuthMethod(BASIC_ONLY);++ expect(credentialsAtTokenEndpoint(method, clientId, clientSecret, { percentDecodes: true }))+ .toEqual({ clientId, clientSecret });++ // A provider that skips the percent-decoding step sees a corrupted secret instead.+ expect(credentialsAtTokenEndpoint(method, clientId, clientSecret))+ .toEqual({ clientId, clientSecret: "insecure%5Fsecret" });+ });+ });++ describe("probeProviderCapabilities", () => {const wellKnownUrl = "https://issuer.example.com/.well-known/openid-configuration";+ const DEFAULTS = { endSessionSupported: false, clientAuthMethod: "client_secret_basic" };function mockFetch(impl: (url: string) => Partial<Response> | Promise<Partial<Response>>) {return vi.spyOn(globalThis, "fetch").mockImplementation(@@ -390,31 +466,40 @@ describe("open_id", () => {);}- it("fetches the issuer's discovery document and reflects end_session_endpoint", async () => {+ // One fetch has to serve both settings — probing the same document twice would double the+ // startup cost and could observe an inconsistent provider between the two reads.+ it("derives every capability from a single discovery fetch", async () => {setOauthConfig(true);const fetchSpy = mockFetch(() => ({ok: true,- json: () => Promise.resolve({ end_session_endpoint: "https://issuer.example.com/logout" })+ json: () => Promise.resolve({+ end_session_endpoint: "https://issuer.example.com/logout",+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"]+ })}));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(true);+ expect(await openID.probeProviderCapabilities()).toEqual({+ endSessionSupported: true,+ clientAuthMethod: "client_secret_post"+ });+ expect(fetchSpy).toHaveBeenCalledOnce();expect(fetchSpy).toHaveBeenCalledWith(wellKnownUrl, expect.anything());});- it("is false when discovery omits end_session_endpoint", async () => {+ it("falls back to the spec defaults when discovery advertises neither capability", async () => {setOauthConfig(true);mockFetch(() => ({ ok: true, json: () => Promise.resolve({}) }));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeProviderCapabilities()).toEqual(DEFAULTS);});- it("fails closed (false) on a non-OK response or a thrown fetch", async () => {+ it("fails safe on a non-OK response or a thrown fetch", async () => {setOauthConfig(true);mockFetch(() => ({ ok: false, status: 404, json: () => Promise.resolve({}) }));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeProviderCapabilities()).toEqual(DEFAULTS);vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network down"));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeProviderCapabilities()).toEqual(DEFAULTS);});it("does not attempt discovery when no issuer is configured", async () => {@@ -422,7 +507,7 @@ describe("open_id", () => {mfa.oauthIssuerBaseUrl = "";const fetchSpy = mockFetch(() => ({ ok: true, json: () => Promise.resolve({}) }));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeProviderCapabilities()).toEqual(DEFAULTS);expect(fetchSpy).not.toHaveBeenCalled();});});@@ -435,18 +520,27 @@ describe("open_id", () => {* every request, and lazily builds (and caches) the underlying handler the first time OAuth is used.*/describe("createReactiveOidcMiddleware", () => {+ const BASIC_CAPABILITIES: ProviderCapabilities = {+ endSessionSupported: false,+ clientAuthMethod: "client_secret_basic"+ };+ const POST_CAPABILITIES: ProviderCapabilities = {+ endSessionSupported: true,+ clientAuthMethod: "client_secret_post"+ };+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 probeProviderCapabilities = vi.fn().mockResolvedValue(BASIC_CAPABILITIES);+ const generateOAuthConfig = vi.fn((capabilities: ProviderCapabilities) => ({ capabilities }) as never);const isConfigured = vi.fn(() => configured);const middleware = createReactiveOidcMiddleware({isConfigured,- isRpInitiatedLogoutSupported,+ probeProviderCapabilities,generateOAuthConfig,buildAuth});@@ -455,7 +549,7 @@ describe("createReactiveOidcMiddleware", () => {middleware,oidcHandler,buildAuth,- isRpInitiatedLogoutSupported,+ probeProviderCapabilities,generateOAuthConfig,isConfigured,setConfigured: (value: boolean) => { configured = value; }@@ -479,7 +573,7 @@ describe("createReactiveOidcMiddleware", () => {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();+ expect(t.probeProviderCapabilities).not.toHaveBeenCalled();});it("builds and delegates to the OIDC handler when OAuth is selected", async () => {@@ -488,8 +582,8 @@ describe("createReactiveOidcMiddleware", () => {const { req, res, next } = await run(t.middleware);- expect(t.isRpInitiatedLogoutSupported).toHaveBeenCalledOnce();- expect(t.generateOAuthConfig).toHaveBeenCalledWith(false);+ expect(t.probeProviderCapabilities).toHaveBeenCalledOnce();+ expect(t.generateOAuthConfig).toHaveBeenCalledWith(BASIC_CAPABILITIES);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@@ -506,18 +600,18 @@ describe("createReactiveOidcMiddleware", () => {await run(t.middleware);expect(t.buildAuth).toHaveBeenCalledOnce();- expect(t.isRpInitiatedLogoutSupported).toHaveBeenCalledOnce();+ expect(t.probeProviderCapabilities).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.probeProviderCapabilities.mockResolvedValue(POST_CAPABILITIES);t.setConfigured(true);await run(t.middleware);- expect(t.generateOAuthConfig).toHaveBeenCalledWith(true);+ expect(t.generateOAuthConfig).toHaveBeenCalledWith(POST_CAPABILITIES);});// This is the regression the whole change exists to fix: with the old startup-only mount, flipping@@ -558,12 +652,12 @@ describe("createReactiveOidcMiddleware", () => {// 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; }));+ let resolveProbe: (value: ProviderCapabilities) => void = () => {};+ t.probeProviderCapabilities.mockReturnValue(new Promise<ProviderCapabilities>((resolve) => { resolveProbe = resolve; }));const first = run(t.middleware);const second = run(t.middleware);- resolveProbe(false);+ resolveProbe(BASIC_CAPABILITIES);await Promise.all([first, second]);expect(t.buildAuth).toHaveBeenCalledOnce();@@ -576,7 +670,7 @@ describe("createReactiveOidcMiddleware", () => {it("retries the build on a subsequent request after a failed init", async () => {const t = setup();t.setConfigured(true);- t.isRpInitiatedLogoutSupported.mockRejectedValueOnce(new Error("transient discovery failure"));+ t.probeProviderCapabilities.mockRejectedValueOnce(new Error("transient discovery failure"));await expect(run(t.middleware)).rejects.toThrow("transient discovery failure");expect(t.oidcHandler).not.toHaveBeenCalled();@@ -587,3 +681,45 @@ describe("createReactiveOidcMiddleware", () => {expect(t.oidcHandler).toHaveBeenCalledWith(req, res, expect.any(Function));});});++/**+ * Replays what a provider's token endpoint actually receives for a given client authentication method,+ * driving the real openid-client encoders rather than re-implementing them.+ *+ * `percentDecodes` models the one behavioural split that matters. oauth4webapi always percent-encodes+ * the Basic credentials per RFC 6749 §2.3.1, so what the provider ends up with depends entirely on+ * whether it decodes them again:+ *+ * - `true` — a spec-compliant provider (Authelia/fosite, Keycloak). Basic round-trips correctly.+ * - `false` — Rack/Doorkeeper, i.e. GitLab: it base64-decodes the header and splits on ":" but never+ * percent-decodes, so it compares against a corrupted secret. That asymmetry is the bug behind #10585.+ *+ * `client_secret_post` is unaffected either way: the credentials ride in the form body, which every+ * provider form-decodes as a matter of course.+ */+function credentialsAtTokenEndpoint(+ method: "client_secret_basic" | "client_secret_post",+ clientId: string,+ clientSecret: string,+ { percentDecodes = false } = {}+) {+ const headers = new Headers();+ const body = new URLSearchParams();+ const applyAuth = method === "client_secret_post"+ ? ClientSecretPost(clientSecret)+ : ClientSecretBasic(clientSecret);+ applyAuth({} as never, { client_id: clientId } as never, body, headers);++ const authorization = headers.get("authorization");+ if (authorization) {+ const decoded = Buffer.from(authorization.replace(/^Basic /, ""), "base64").toString();+ const separator = decoded.indexOf(":");+ const asReceived = (value: string) => (percentDecodes ? decodeURIComponent(value) : value);+ return {+ clientId: asReceived(decoded.slice(0, separator)),+ clientSecret: asReceived(decoded.slice(separator + 1))+ };+ }++ return { clientId: body.get("client_id"), clientSecret: body.get("client_secret") };+}diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.tsindex 7f676aeed6..bdefabbdc3 100644--- a/apps/server/src/services/open_id.ts+++ b/apps/server/src/services/open_id.ts@@ -132,7 +132,7 @@ function deriveFaviconUrl(baseUrl: string) {}}-function generateOAuthConfig(endSessionSupported = false) {+function generateOAuthConfig(capabilities: ProviderCapabilities = DEFAULT_PROVIDER_CAPABILITIES) {const authRoutes = {callback: "/callback",login: "/authenticate",@@ -151,18 +151,18 @@ function generateOAuthConfig(endSessionSupported = false) {issuerBaseURL: config.MultiFactorAuthentication.oauthIssuerBaseUrl,secret: config.MultiFactorAuthentication.oauthClientSecret,clientSecret: config.MultiFactorAuthentication.oauthClientSecret,- clientAuthMethod: resolveClientAuthMethod(),+ clientAuthMethod: capabilities.clientAuthMethod,authorizationParams: {response_type: "code",scope: "openid profile email",},routes: authRoutes,// Only enable RP-Initiated Logout when the provider actually advertises an end_session_endpoint- // (see isRpInitiatedLogoutSupported). With idpLogout on, express-openid-connect unconditionally+ // (see probeProviderCapabilities). 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.- idpLogout: endSessionSupported,+ idpLogout: capabilities.endSessionSupported,logoutParams,afterCallback: async (req: Request, res: Response, session: Session) => {if (!sqlInit.isDbInitialized()) return session;@@ -251,10 +251,10 @@ type AuthBuilder = typeof import("express-openid-connect").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>;+ /** Single discovery probe resolving everything we negotiate with the provider. */+ probeProviderCapabilities: () => Promise<ProviderCapabilities>;/** Builds the express-openid-connect config for the current provider settings. */- generateOAuthConfig: (endSessionSupported: boolean) => Parameters<AuthBuilder>[0];+ generateOAuthConfig: (capabilities: ProviderCapabilities) => Parameters<AuthBuilder>[0];/** The express-openid-connect `auth()` factory (injectable so the middleware is unit-testable). */buildAuth: AuthBuilder;}@@ -269,14 +269,14 @@ interface ReactiveOidcDeps {* 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.+ * (see {@link probeProviderCapabilities}) 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,+ probeProviderCapabilities: probeCapabilities = probeProviderCapabilities,generateOAuthConfig: buildOAuthConfig = generateOAuthConfig,buildAuth} = deps;@@ -297,8 +297,8 @@ export function createReactiveOidcMiddleware(deps: Partial<ReactiveOidcDeps> = {// OAuth unselected. The sole static reference to the package is the erased `Session` type// import, so the bundler keeps it out of the eager-init graph (see scripts/build-utils.ts).const authFactory = buildAuth ?? (await import("express-openid-connect")).auth;- const endSessionSupported = await probeRpLogout();- oidcMiddleware = authFactory(buildOAuthConfig(endSessionSupported));+ const capabilities = await probeCapabilities();+ oidcMiddleware = authFactory(buildOAuthConfig(capabilities));})();try {await oidcInit;@@ -332,25 +332,55 @@ export default {clearSavedUser,isTokenValid,isUserSaved,- isRpInitiatedLogoutSupported,+ probeProviderCapabilities,};-const GOOGLE_ISSUER = "https://accounts.google.com";-// Cap the startup discovery probe so a slow/unreachable provider can't stall server boot.const DISCOVERY_TIMEOUT_MS = 10_000;+/** Everything we negotiate with the provider from its discovery document. */+export interface ProviderCapabilities {+ /** Whether RP-Initiated Logout (`idpLogout`) can be safely enabled. */+ endSessionSupported: boolean;+ /** How to authenticate to the token endpoint. */+ clientAuthMethod: ClientAuthMethod;+}++/**+ * What we assume when discovery is unavailable: no RP-Initiated Logout (so logout degrades to clearing+ * the local session rather than crashing on a missing endpoint), and the OIDC Core default token-endpoint+ * auth method. Both are the conservative, spec-default choices.+ */+const DEFAULT_PROVIDER_CAPABILITIES: ProviderCapabilities = {+ endSessionSupported: false,+ clientAuthMethod: "client_secret_basic"+};+/**- * Probes the configured OIDC issuer's discovery document to decide whether RP-Initiated Logout is- * available, i.e. whether `idpLogout` can be safely enabled in {@link generateOAuthConfig}. The issuer- * is fixed in config.ini/env and only changes on restart, so this is resolved once at startup rather- * than per logout. Any fetch/parse failure is treated as "unsupported" so a transient network blip- * degrades to a working local logout rather than breaking it.+ * Probes the configured OIDC issuer's discovery document once and derives every provider-dependent+ * setting from it. The issuer is fixed in config.ini/env and only changes on restart, so this resolves+ * a single time on first OAuth use rather than per request. Any fetch/parse failure degrades to+ * {@link DEFAULT_PROVIDER_CAPABILITIES} so a transient network blip doesn't break login outright.*/-async function isRpInitiatedLogoutSupported() {+async function probeProviderCapabilities(): Promise<ProviderCapabilities> {+ const metadata = await fetchDiscoveryMetadata();+ if (metadata === undefined) {+ return DEFAULT_PROVIDER_CAPABILITIES;+ }++ return {+ endSessionSupported: supportsRpInitiatedLogout(metadata),+ clientAuthMethod: resolveClientAuthMethod(metadata)+ };+}++/**+ * Fetches the issuer's OIDC discovery document, or `undefined` when it can't be retrieved or parsed.+ */+async function fetchDiscoveryMetadata(): Promise<unknown> {const issuer = config.MultiFactorAuthentication.oauthIssuerBaseUrl.replace(/\/+$/, "");if (!issuer) {- return false;+ return undefined;}// The discovery document lives at `{issuer}/.well-known/openid-configuration` — appended to the full@@ -361,26 +391,26 @@ async function isRpInitiatedLogoutSupported() {try {const response = await fetch(metadataUrl, { signal: controller.signal });if (!response.ok) {- getLog().info(`OAuth: discovery for ${issuer} returned HTTP ${response.status}; treating RP-Initiated Logout as unsupported.`);- return false;+ getLog().info(`OAuth: discovery for ${issuer} returned HTTP ${response.status}; falling back to default provider settings.`);+ return undefined;}- const metadata: unknown = await response.json();- return supportsRpInitiatedLogout(metadata);+ return await response.json();} catch (error) {- getLog().info(`OAuth: discovery fetch for ${issuer} failed, treating RP-Initiated Logout as unsupported. ${error instanceof Error ? error.message : error}`);- return false;+ getLog().info(`OAuth: discovery fetch for ${issuer} failed, falling back to default provider settings. ${error instanceof Error ? error.message : error}`);+ return undefined;} finally {clearTimeout(timeout);}}/**- * The single field of the OIDC discovery document we consume. The full metadata is large and arrives as+ * The fields of the OIDC discovery document we consume. The full metadata is large and arrives as* untrusted network JSON, so rather than pull in (and pin) openid-client's transitive `ServerMetadata`- * type for one property, we mirror just what we read and validate it at runtime.+ * type, we mirror just what we read and validate it at runtime.*/interface OidcDiscoveryMetadata {end_session_endpoint?: string;+ token_endpoint_auth_methods_supported?: string[];}/**@@ -395,22 +425,39 @@ export function supportsRpInitiatedLogout(metadata: unknown) {return typeof end_session_endpoint === "string" && end_session_endpoint.length > 0;}+export type ClientAuthMethod = "client_secret_basic" | "client_secret_post";+/**- * Chooses the token-endpoint client authentication method based on the issuer.+ * Chooses the token-endpoint client authentication method from the provider's own discovery document,+ * preferring `client_secret_post` whenever it is advertised.+ *+ * `client_secret_basic` — the OIDC Core default, and what express-openid-connect picks on its own — is+ * unsafe for credentials containing `- _ . ! ~ * ' ( )`. Its oauth4webapi implementation form-url-encodes+ * the client_id/secret per RFC 6749 §2.3.1 ("-" → %2D, "." → %2E) *inside* the HTTP Basic header, but+ * providers routinely base64-decode that header without percent-decoding it, so the credentials arrive+ * corrupted. This has broken two providers already: Google (whose client_ids always contain "-" and ".";+ * "invalid_client: The OAuth client was not found") and GitLab (whose secrets are `gloas-` prefixed;+ * OAUTH_WWW_AUTHENTICATE_CHALLENGE — see #10585, a regression from the openid-client v5 → v6 upgrade,+ * where v5's plainer `encodeURIComponent` left those characters intact).*- * - **Google** → `client_secret_post`. express-openid-connect defaults to `client_secret_basic`,- * whose oauth4webapi implementation form-url-encodes the client_id/secret per RFC 6749 §2.3.1- * ("-" → %2D, "." → %2E) inside the HTTP Basic header. Google does not decode Basic credentials, so- * a Google client_id (which always contains "-" and ".") arrives corrupted and the token exchange- * fails with "invalid_client: The OAuth client was not found." Posting the credentials in the body- * sidesteps the Basic-auth encoding.- * - **Any other issuer** → `client_secret_basic`, the OIDC default a spec-compliant provider expects- * (e.g. Authelia/Keycloak register confidential clients as `client_secret_basic` and reject a- * mismatched method).+ * Posting the credentials in the request body sidesteps the Basic-auth encoding entirely, so it is the+ * safe choice for *any* provider that accepts it — hence a capability check rather than an issuer+ * allowlist. Providers that only register confidential clients as `client_secret_basic` (Authelia,+ * Keycloak) still get basic, as does a provider whose discovery document is missing or malformed.*/-function resolveClientAuthMethod() {- const issuer = config.MultiFactorAuthentication.oauthIssuerBaseUrl.replace(/\/+$/, "");- return issuer === GOOGLE_ISSUER ? "client_secret_post" : "client_secret_basic";+export function resolveClientAuthMethod(metadata: unknown): ClientAuthMethod {+ if (typeof metadata !== "object" || metadata === null) {+ return DEFAULT_PROVIDER_CAPABILITIES.clientAuthMethod;+ }++ const { token_endpoint_auth_methods_supported } = metadata as OidcDiscoveryMetadata;+ if (!Array.isArray(token_endpoint_auth_methods_supported)) {+ return DEFAULT_PROVIDER_CAPABILITIES.clientAuthMethod;+ }++ return token_endpoint_auth_methods_supported.includes("client_secret_post")+ ? "client_secret_post"+ : "client_secret_basic";}/**diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cecd09b648..c8ee28b972 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -793,6 +793,9 @@ importers:officeparser:specifier: 7.3.0version: 7.3.0([email protected])+ openid-client:+ specifier: 6.8.4+ version: 6.8.4rand-token:specifier: 1.0.1version: 1.0.1