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): tolerate a trailing-slash issuer mismatch, closes #10695
Elian Doran7c6a54511ff7
diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.tsindex 20639ebfab..96eb1ef1e2 100644--- a/apps/server/src/services/open_id.spec.ts+++ b/apps/server/src/services/open_id.spec.ts@@ -1,11 +1,11 @@import { cls, getLog, options } from "@triliumnext/core";import type { NextFunction, Request as ExpressRequest, RequestHandler, Response as ExpressResponse } from "express";-import { ClientSecretBasic, ClientSecretPost } from "openid-client";+import { ClientSecretBasic, ClientSecretPost, type CustomFetch, customFetch, discovery } 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, resolveClientAuthMethod, resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";+import openID, { createReactiveOidcMiddleware, reconcileIssuerBaseUrl, resolveClientAuthMethod, resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";import sql from "./sql.js";import sqlInit from "./sql_init.js";@@ -467,7 +467,7 @@ describe("open_id", () => {});});- describe("isRpInitiatedLogoutSupported", () => {+ describe("probeDiscovery", () => {const wellKnownUrl = "https://issuer.example.com/.well-known/openid-configuration";function mockFetch(impl: (url: string) => Partial<Response> | Promise<Partial<Response>>) {@@ -480,27 +480,54 @@ describe("open_id", () => {setOauthConfig(true);const fetchSpy = mockFetch(() => ({ok: true,- json: () => Promise.resolve({ end_session_endpoint: "https://issuer.example.com/logout" })+ json: () => Promise.resolve({+ issuer: "https://issuer.example.com",+ end_session_endpoint: "https://issuer.example.com/logout"+ })}));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(true);+ expect(await openID.probeDiscovery()).toEqual({+ endSessionSupported: true,+ issuerBaseUrl: "https://issuer.example.com"+ });expect(fetchSpy).toHaveBeenCalledWith(wellKnownUrl, expect.anything());});it("is false when discovery omits end_session_endpoint", async () => {setOauthConfig(true);mockFetch(() => ({ ok: true, json: () => Promise.resolve({}) }));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect((await openID.probeDiscovery()).endSessionSupported).toBe(false);});- it("fails closed (false) on a non-OK response or a thrown fetch", async () => {+ it("adopts the advertised issuer when it differs only by a trailing slash", async () => {+ // The Authentik shape from #10695: the document is served for the slashless URL, but the+ // issuer it advertises carries the slash, and that is what express-openid-connect must be+ // handed for openid-client's equality check to pass.+ setOauthConfig(true);+ mfa.oauthIssuerBaseUrl = "https://sso.example.com/application/o/trilium-app";+ mockFetch(() => ({+ ok: true,+ json: () => Promise.resolve({ issuer: "https://sso.example.com/application/o/trilium-app/" })+ }));++ expect((await openID.probeDiscovery()).issuerBaseUrl)+ .toBe("https://sso.example.com/application/o/trilium-app/");+ });++ it("fails closed on a non-OK response or a thrown fetch, keeping the configured issuer", async () => {setOauthConfig(true);mockFetch(() => ({ ok: false, status: 404, json: () => Promise.resolve({}) }));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeDiscovery()).toEqual({+ endSessionSupported: false,+ issuerBaseUrl: "https://issuer.example.com"+ });vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network down"));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeDiscovery()).toEqual({+ endSessionSupported: false,+ issuerBaseUrl: "https://issuer.example.com"+ });});it("does not attempt discovery when no issuer is configured", async () => {@@ -508,10 +535,129 @@ describe("open_id", () => {mfa.oauthIssuerBaseUrl = "";const fetchSpy = mockFetch(() => ({ ok: true, json: () => Promise.resolve({}) }));- expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);+ expect(await openID.probeDiscovery()).toEqual({ endSessionSupported: false, issuerBaseUrl: "" });expect(fetchSpy).not.toHaveBeenCalled();});});++ /**+ * Cover for #10695: OIDC login against Authentik broke in v0.104.0 with+ * `OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED`, caused by the same express-openid-connect 2.20.2 → 3.2.0+ * bump behind #10585. v6's `discovery()` asserts that the discovery document's `issuer` equals the+ * issuer URL it was handed; v5's `Issuer.discover()` performed no such comparison, so any mismatch+ * was silently tolerated before the upgrade.+ *+ * The comparison is `new URL(advertised).href !== new URL(configured).href`, and that normalisation+ * is what makes the failure provider-shaped rather than universal — see {@link discoveryOutcome}.+ */+ describe("issuer identifier matching", () => {+ it("tolerates a trailing slash either way on an origin-only issuer", async () => {+ // Authelia's issuer carries no path, so `href` normalisation supplies the trailing slash on+ // both sides and the two spellings collapse onto each other. This is why Trilium's Authelia+ // dev harness (apps/server/docker/authelia) cannot reproduce #10695 at all.+ const authelia = "https://auth.example.com:9091";+ expect(await discoveryOutcome(authelia, authelia)).toBe("accepted");+ expect(await discoveryOutcome(`${authelia}/`, authelia)).toBe("accepted");+ });++ it("rejects a path-bearing issuer spelled with the wrong trailing slash", async () => {+ // `href` neither adds nor strips a trailing slash on a *non-empty* path, so once the issuer+ // carries one the user has to match the provider's spelling exactly. Both orientations occur+ // in the wild, which is why normalising in a single direction cannot be the fix.++ // Authentik advertises the trailing slash; #10695's reporter configured it without one.+ const authentik = "https://sso.example.com/application/o/trilium-app/";+ expect(await discoveryOutcome(authentik, authentik)).toBe("accepted");+ expect(await discoveryOutcome(authentik.replace(/\/$/, ""), authentik))+ .toBe("OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED");++ // Keycloak is the mirror image: it advertises no trailing slash, so adding one breaks it.+ const keycloak = "https://sso.example.com/realms/trilium";+ expect(await discoveryOutcome(keycloak, keycloak)).toBe("accepted");+ expect(await discoveryOutcome(`${keycloak}/`, keycloak))+ .toBe("OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED");+ });++ it("still rejects an issuer that differs by more than a trailing slash", async () => {+ // The bound on any tolerance Trilium adds: the comparison is a genuine security check, so a+ // document claiming a different host or realm must keep failing.+ const keycloak = "https://sso.example.com/realms/trilium";+ expect(await discoveryOutcome(keycloak, "https://evil.example.com/realms/trilium"))+ .toBe("OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED");+ expect(await discoveryOutcome(keycloak, "https://sso.example.com/realms/other"))+ .toBe("OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED");++ // Authentik's "global" issuer mode, where every provider reports the instance root while the+ // document is still only served under the per-application path. Out of reach of trailing-slash+ // tolerance — it needs the issuer configured as an explicit `.well-known` URL instead.+ expect(await discoveryOutcome("https://sso.example.com/application/o/trilium-app/", "https://sso.example.com/"))+ .toBe("OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED");+ });++ /**+ * The fix: since only the provider knows which spelling it advertises, the trailing slash is+ * reconciled against the discovery document rather than normalised in either direction.+ */+ describe("reconcileIssuerBaseUrl", () => {+ it("adopts the advertised spelling when it differs only by a trailing slash", () => {+ // Authentik: user omitted the slash the provider advertises.+ expect(reconcileIssuerBaseUrl(+ "https://sso.example.com/application/o/trilium-app",+ "https://sso.example.com/application/o/trilium-app/"+ )).toBe("https://sso.example.com/application/o/trilium-app/");++ // Keycloak: the mirror image, user added a slash the provider does not advertise.+ expect(reconcileIssuerBaseUrl(+ "https://sso.example.com/realms/trilium/",+ "https://sso.example.com/realms/trilium"+ )).toBe("https://sso.example.com/realms/trilium");+ });++ it("leaves an already-matching issuer untouched", () => {+ // Including the origin-only case, where both spellings already normalise to the same href.+ expect(reconcileIssuerBaseUrl("https://auth.example.com:9091", "https://auth.example.com:9091/"))+ .toBe("https://auth.example.com:9091");+ expect(reconcileIssuerBaseUrl("https://sso.example.com/realms/trilium", "https://sso.example.com/realms/trilium"))+ .toBe("https://sso.example.com/realms/trilium");+ });++ it("keeps the configured issuer when the difference is more than a trailing slash", () => {+ // A document claiming a different host/path must not be able to move the expected issuer;+ // returning the configured value leaves openid-client's check to reject the round-trip.+ const configured = "https://sso.example.com/realms/trilium";+ expect(reconcileIssuerBaseUrl(configured, "https://evil.example.com/realms/trilium")).toBe(configured);+ expect(reconcileIssuerBaseUrl(configured, "https://sso.example.com/realms/other")).toBe(configured);+ expect(reconcileIssuerBaseUrl(configured, "http://sso.example.com/realms/trilium")).toBe(configured);+ // Authentik's "global" issuer mode — a real difference, so still out of scope here.+ expect(reconcileIssuerBaseUrl("https://sso.example.com/application/o/trilium-app/", "https://sso.example.com/"))+ .toBe("https://sso.example.com/application/o/trilium-app/");+ });++ it("keeps the configured issuer when the document carries no usable issuer", () => {+ const configured = "https://sso.example.com/realms/trilium";+ expect(reconcileIssuerBaseUrl(configured, undefined)).toBe(configured);+ expect(reconcileIssuerBaseUrl(configured, "")).toBe(configured);+ expect(reconcileIssuerBaseUrl(configured, 42)).toBe(configured);+ // Unparseable on either side falls back rather than substituting a guess.+ expect(reconcileIssuerBaseUrl(configured, "not a url")).toBe(configured);+ expect(reconcileIssuerBaseUrl("not a url", "https://sso.example.com/")).toBe("not a url");+ });++ it("closes the loop: the reconciled issuer is what reaches express-openid-connect", async () => {+ setOauthConfig(true);+ mfa.oauthIssuerBaseUrl = "https://sso.example.com/application/o/trilium-app";+ const advertised = "https://sso.example.com/application/o/trilium-app/";++ const reconciled = reconcileIssuerBaseUrl(mfa.oauthIssuerBaseUrl, advertised);+ const { issuerBaseURL } = openID.generateOAuthConfig(false, reconciled);++ expect(issuerBaseURL).toBe(advertised);+ // ...and that value is one openid-client accepts, which is the whole point: the raw+ // config value fails the very same check (see the sibling cases above).+ expect(await discoveryOutcome(issuerBaseURL, advertised)).toBe("accepted");+ });+ });+ });});/**@@ -521,18 +667,24 @@ describe("open_id", () => {* every request, and lazily builds (and caches) the underlying handler the first time OAuth is used.*/describe("createReactiveOidcMiddleware", () => {+ /** Stands in for the issuer the discovery probe settled on, distinct from any configured value. */+ const PROBED_ISSUER = "https://issuer.example.com/probed/";+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 probeDiscovery = vi.fn().mockResolvedValue({+ endSessionSupported: false,+ issuerBaseUrl: PROBED_ISSUER+ });const generateOAuthConfig = vi.fn((endSessionSupported: boolean) => ({ endSessionSupported }) as never);const isConfigured = vi.fn(() => configured);const middleware = createReactiveOidcMiddleware({isConfigured,- isRpInitiatedLogoutSupported,+ probeDiscovery,generateOAuthConfig,buildAuth});@@ -541,7 +693,7 @@ describe("createReactiveOidcMiddleware", () => {middleware,oidcHandler,buildAuth,- isRpInitiatedLogoutSupported,+ probeDiscovery,generateOAuthConfig,isConfigured,setConfigured: (value: boolean) => { configured = value; }@@ -569,7 +721,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.probeDiscovery).not.toHaveBeenCalled();});it("builds and delegates to the OIDC handler when OAuth is selected", async () => {@@ -578,8 +730,8 @@ describe("createReactiveOidcMiddleware", () => {const { req, res, next } = await run(t.middleware);- expect(t.isRpInitiatedLogoutSupported).toHaveBeenCalledOnce();- expect(t.generateOAuthConfig).toHaveBeenCalledWith(false);+ expect(t.probeDiscovery).toHaveBeenCalledOnce();+ expect(t.generateOAuthConfig).toHaveBeenCalledWith(false, PROBED_ISSUER);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@@ -596,18 +748,23 @@ describe("createReactiveOidcMiddleware", () => {await run(t.middleware);expect(t.buildAuth).toHaveBeenCalledOnce();- expect(t.isRpInitiatedLogoutSupported).toHaveBeenCalledOnce();+ expect(t.probeDiscovery).toHaveBeenCalledOnce();expect(t.oidcHandler).toHaveBeenCalledTimes(2);});- it("passes the discovery-probe result into the OAuth config", async () => {+ it("passes both discovery-probe results into the OAuth config", async () => {const t = setup();- t.isRpInitiatedLogoutSupported.mockResolvedValue(true);+ // The issuer reaching express-openid-connect is the probe's, not whatever sits in config — that+ // indirection is what lets a trailing-slash difference be reconciled (#10695).+ t.probeDiscovery.mockResolvedValue({+ endSessionSupported: true,+ issuerBaseUrl: "https://sso.example.com/application/o/trilium-app/"+ });t.setConfigured(true);await run(t.middleware);- expect(t.generateOAuthConfig).toHaveBeenCalledWith(true);+ expect(t.generateOAuthConfig).toHaveBeenCalledWith(true, "https://sso.example.com/application/o/trilium-app/");});// This is the regression the whole change exists to fix: with the old startup-only mount, flipping@@ -648,12 +805,13 @@ 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; }));+ type Probe = { endSessionSupported: boolean; issuerBaseUrl: string };+ let resolveProbe: (value: Probe) => void = () => {};+ t.probeDiscovery.mockReturnValue(new Promise<Probe>((resolve) => { resolveProbe = resolve; }));const first = run(t.middleware);const second = run(t.middleware);- resolveProbe(false);+ resolveProbe({ endSessionSupported: false, issuerBaseUrl: PROBED_ISSUER });await Promise.all([first, second]);expect(t.buildAuth).toHaveBeenCalledOnce();@@ -666,7 +824,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.probeDiscovery.mockRejectedValueOnce(new Error("transient discovery failure"));// The failure is reported to the user via the redirect-and-flag path rather than thrown at the// generic error handler, which would answer this full-page navigation with raw JSON.@@ -725,7 +883,7 @@ describe("createReactiveOidcMiddleware", () => {// treats falsy as "no error"). describeError yields null and String() yields "" for it, so// only the final fallback keeps the session marker non-empty — and its presence is what marks// the failure downstream.- t.isRpInitiatedLogoutSupported.mockRejectedValueOnce("");+ t.probeDiscovery.mockRejectedValueOnce("");const { req, redirect } = await run(t.middleware);@@ -757,7 +915,7 @@ describe("createReactiveOidcMiddleware", () => {const t = setup();t.setConfigured(true);const failure = new Error("invalid config");- t.isRpInitiatedLogoutSupported.mockRejectedValue(failure);+ t.probeDiscovery.mockRejectedValue(failure);const { redirect, next } = await run(t.middleware, "/");@@ -837,3 +995,40 @@ function credentialsAtTokenEndpoint(return { clientId: body.get("client_id"), clientSecret: body.get("client_secret") };}++/**+ * Replays express-openid-connect's discovery step for a given (configured issuer, advertised issuer)+ * pair, driving the real openid-client rather than re-implementing its comparison — the same approach+ * {@link credentialsAtTokenEndpoint} takes for the token endpoint.+ *+ * The provider is stubbed at the transport layer via openid-client's `customFetch`, so no network and no+ * container is involved: every request is answered with a discovery document advertising+ * `advertisedIssuer`. That is enough, because the failure in #10695 is a pure string comparison the+ * library performs *after* the document is fetched, not a routing or connectivity problem. The document+ * is served for whatever URL is requested, matching how Authentik answers the `.well-known` path+ * regardless of whether the caller included a trailing slash.+ *+ * Returns `"accepted"` or the thrown error's code, so a test reads as the outcome a user would get.+ */+async function discoveryOutcome(configuredIssuer: string, advertisedIssuer: string) {+ const base = advertisedIssuer.replace(/\/$/, "");+ const serveMetadata: CustomFetch = async () => new Response(+ JSON.stringify({+ issuer: advertisedIssuer,+ authorization_endpoint: `${base}/authorize`,+ token_endpoint: `${base}/token`,+ jwks_uri: `${base}/jwks`,+ response_types_supported: ["code"]+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );++ try {+ await discovery(new URL(configuredIssuer), "client-id", {}, undefined, {+ [customFetch]: serveMetadata+ });+ return "accepted";+ } catch (error) {+ return (error as { code?: string })?.code ?? String(error);+ }+}diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.tsindex 0101fa7ccc..e78f9bb0e7 100644--- a/apps/server/src/services/open_id.ts+++ b/apps/server/src/services/open_id.ts@@ -144,7 +144,10 @@ const OIDC_ROUTES = {logout: "/logout",} as const;-function generateOAuthConfig(endSessionSupported = false) {+function generateOAuthConfig(+ endSessionSupported = false,+ issuerBaseUrl = config.MultiFactorAuthentication.oauthIssuerBaseUrl+) {const logoutParams = {};@@ -153,7 +156,10 @@ function generateOAuthConfig(endSessionSupported = false) {auth0Logout: false,baseURL: config.MultiFactorAuthentication.oauthBaseUrl,clientID: config.MultiFactorAuthentication.oauthClientId,- issuerBaseURL: config.MultiFactorAuthentication.oauthIssuerBaseUrl,+ // Not read straight from config: openid-client v6 requires this to match the issuer the provider+ // advertises character for character, so it comes from the discovery probe via+ // reconcileIssuerBaseUrl. Defaulted to the raw config value for callers that don't probe.+ issuerBaseURL: issuerBaseUrl,secret: config.MultiFactorAuthentication.oauthClientSecret,clientSecret: config.MultiFactorAuthentication.oauthClientSecret,clientAuthMethod: resolveClientAuthMethod(),@@ -163,7 +169,7 @@ function generateOAuthConfig(endSessionSupported = false) {},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.@@ -256,10 +262,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>;+ /** Discovery probe supplying the issuer identifier and RP-Initiated Logout support. */+ probeDiscovery: () => Promise<DiscoveryProbe>;/** Builds the express-openid-connect config for the current provider settings. */- generateOAuthConfig: (endSessionSupported: boolean) => Parameters<AuthBuilder>[0];+ generateOAuthConfig: (endSessionSupported: boolean, issuerBaseUrl: string) => Parameters<AuthBuilder>[0];/** The express-openid-connect `auth()` factory (injectable so the middleware is unit-testable). */buildAuth: AuthBuilder;}@@ -274,14 +280,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+ * ({@link probeDiscovery}) 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,+ probeDiscovery: probe = probeDiscovery,generateOAuthConfig: buildOAuthConfig = generateOAuthConfig,buildAuth} = deps;@@ -302,8 +308,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 { endSessionSupported, issuerBaseUrl } = await probe();+ oidcMiddleware = authFactory(buildOAuthConfig(endSessionSupported, issuerBaseUrl));})();try {await oidcInit;@@ -403,53 +409,131 @@ export default {clearSavedUser,isTokenValid,isUserSaved,- isRpInitiatedLogoutSupported,+ probeDiscovery,};// Cap the startup discovery probe so a slow/unreachable provider can't stall server boot.const DISCOVERY_TIMEOUT_MS = 10_000;+/** What {@link probeDiscovery} extracts from the provider's discovery document. */+interface DiscoveryProbe {+ /** Whether `idpLogout` can be safely enabled — see {@link supportsRpInitiatedLogout}. */+ endSessionSupported: boolean;+ /** The issuer to hand express-openid-connect — see {@link reconcileIssuerBaseUrl}. */+ issuerBaseUrl: string;+}+/**- * 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 for the two facts that must be settled before+ * express-openid-connect can be built: whether RP-Initiated Logout is available, and which spelling of+ * the issuer identifier the provider actually advertises. The issuer is fixed in config.ini/env and only+ * changes on restart, so this is resolved once at first use rather than per request.+ *+ * Any fetch/parse failure degrades to the configured issuer with logout support off, leaving a transient+ * network blip to break neither sign-in (express-openid-connect runs its own discovery, which either+ * succeeds or reports the real error) nor logout (which falls back to clearing the local session).*/-async function isRpInitiatedLogoutSupported() {- const issuer = config.MultiFactorAuthentication.oauthIssuerBaseUrl.replace(/\/+$/, "");+async function probeDiscovery(): Promise<DiscoveryProbe> {+ const configuredIssuer = config.MultiFactorAuthentication.oauthIssuerBaseUrl;+ const metadata = await fetchDiscoveryMetadata(configuredIssuer);++ return {+ endSessionSupported: supportsRpInitiatedLogout(metadata),+ issuerBaseUrl: reconcileIssuerBaseUrl(configuredIssuer, readAdvertisedIssuer(metadata))+ };+}++/** Fetches the issuer's discovery document, or null if it can't be retrieved or parsed. */+async function fetchDiscoveryMetadata(configuredIssuer: string): Promise<unknown> {+ const issuer = configuredIssuer.replace(/\/+$/, "");if (!issuer) {- return false;+ return null;}// The discovery document lives at `{issuer}/.well-known/openid-configuration` — appended to the full// issuer (which may carry a path, e.g. Keycloak realms) rather than resolved against the origin root.+ // Trailing slashes are stripped first so both spellings of a path-bearing issuer reach the same URL.const metadataUrl = `${issuer}/.well-known/openid-configuration`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS);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}; using the configured issuer and treating RP-Initiated Logout as unsupported.`);+ return null;}- 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, using the configured issuer and treating RP-Initiated Logout as unsupported. ${error instanceof Error ? error.message : error}`);+ return null;} 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 for two properties, we mirror just what we read and validate it at runtime.*/interface OidcDiscoveryMetadata {end_session_endpoint?: string;+ issuer?: string;+}++function readAdvertisedIssuer(metadata: unknown) {+ if (typeof metadata !== "object" || metadata === null) {+ return undefined;+ }+ return (metadata as OidcDiscoveryMetadata).issuer;+}++/**+ * Picks the issuer identifier to hand express-openid-connect, reconciling what the user configured with+ * what the provider advertises when the two differ only by a trailing slash.+ *+ * openid-client v6 asserts `new URL(advertised).href === new URL(configured).href` after fetching the+ * discovery document, and fails the whole round-trip with `OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED`+ * otherwise (#10695). v5 never compared them, so 0.104.0 turned a harmless spelling difference into a+ * hard sign-in failure. `href` supplies a trailing slash for an *empty* path but neither adds nor strips+ * one on a non-empty path, so the mismatch only bites issuers carrying a path — and it bites in both+ * directions: Authentik advertises `…/application/o/<slug>/` while Keycloak advertises `…/realms/<name>`.+ * Normalising in either single direction would therefore fix one provider by breaking the other.+ *+ * Adopting the advertised spelling costs nothing in security: it is only taken when it is identical to+ * the configured issuer up to trailing slashes, so a document claiming a different host, path or scheme+ * still falls through to the configured value and still fails the library's check. That deliberately+ * leaves Authentik's "global" issuer mode (every provider reports the instance root, while the document+ * is served under the per-application path) failing — the difference there is a real one, and the way+ * out is to configure the issuer as an explicit `.well-known` URL.+ */+export function reconcileIssuerBaseUrl(configuredIssuer: string, advertisedIssuer: unknown) {+ if (typeof advertisedIssuer !== "string" || !advertisedIssuer) {+ return configuredIssuer;+ }++ let configuredHref: string;+ let advertisedHref: string;+ try {+ configuredHref = new URL(configuredIssuer).href;+ advertisedHref = new URL(advertisedIssuer).href;+ } catch {+ // A malformed issuer on either side: leave the configured value alone and let+ // express-openid-connect report it, rather than silently substituting a guess.+ return configuredIssuer;+ }++ if (configuredHref === advertisedHref) {+ return configuredIssuer;+ }++ const withoutTrailingSlashes = (url: string) => url.replace(/\/+$/, "");+ if (withoutTrailingSlashes(configuredHref) !== withoutTrailingSlashes(advertisedHref)) {+ return configuredIssuer;+ }++ getLog().info(`OAuth: issuer '${configuredIssuer}' differs from the advertised '${advertisedIssuer}' only by a trailing slash; using the advertised spelling.`);+ return advertisedIssuer;}/**