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): surface the underlying cause of opaque OIDC "fetch failed" errors
Elian Doranf055824322e3
diff --git a/apps/server/src/routes/error_handlers.spec.ts b/apps/server/src/routes/error_handlers.spec.tsindex f527aea39a..271f4d5a58 100644--- a/apps/server/src/routes/error_handlers.spec.ts+++ b/apps/server/src/routes/error_handlers.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { extractOAuthErrorDetail } from "./error_handlers.js";+import { describeError, extractOAuthErrorDetail } from "./error_handlers.js";describe("extractOAuthErrorDetail", () => {it("combines OAuth error code and description", () => {@@ -21,3 +21,56 @@ describe("extractOAuthErrorDetail", () => {expect(extractOAuthErrorDetail(undefined)).toBeNull();});});++describe("describeError", () => {+ it("unwraps undici's opaque 'fetch failed' to its underlying cause and code", () => {+ const cause = Object.assign(new Error("self-signed certificate in certificate chain"), {+ code: "DEPTH_ZERO_SELF_SIGNED_CERT"+ });+ const err = Object.assign(new TypeError("fetch failed"), { cause });++ expect(describeError(err)).toBe(+ "fetch failed ← caused by: self-signed certificate in certificate chain [DEPTH_ZERO_SELF_SIGNED_CERT]"+ );+ });++ it("surfaces Node system-error fields for connection failures", () => {+ const cause = Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:9091"), {+ code: "ECONNREFUSED",+ syscall: "connect",+ address: "127.0.0.1",+ port: 9091+ });+ const err = Object.assign(new TypeError("fetch failed"), { cause });++ expect(describeError(err)).toBe(+ "fetch failed ← caused by: connect ECONNREFUSED 127.0.0.1:9091 [ECONNREFUSED connect 127.0.0.1 9091]"+ );+ });++ it("includes OAuth error/description detail alongside the message", () => {+ const err = Object.assign(new Error("server responded with an error in the response body"), {+ error: "invalid_client",+ error_description: "Client authentication failed"+ });++ expect(describeError(err)).toBe(+ "server responded with an error in the response body invalid_client: Client authentication failed"+ );+ });++ it("stops walking a cyclic cause chain", () => {+ const a: { message: string; cause?: unknown } = { message: "a" };+ const b = { message: "b", cause: a };+ a.cause = b;++ expect(describeError(a)).toBe("a ← caused by: b");+ });++ it("returns null when there is no extractable detail", () => {+ expect(describeError("just a string")).toBeNull();+ expect(describeError(null)).toBeNull();+ expect(describeError(undefined)).toBeNull();+ expect(describeError({})).toBeNull();+ });+});diff --git a/apps/server/src/routes/error_handlers.ts b/apps/server/src/routes/error_handlers.tsindex 2ab4759cce..8f21a3c47e 100644--- a/apps/server/src/routes/error_handlers.ts+++ b/apps/server/src/routes/error_handlers.ts@@ -39,14 +39,15 @@ function register(app: Application) {getLog().info(errMessage);- // Some upstream errors carry their real cause in OAuth/OIDC-style `error` /- // `error_description` properties rather than the generic `.message`. The express-openid-connect- // callback is the prime example: a failed token exchange surfaces only "server responded with an- // error in the response body" as the message, while the actual reason (e.g. redirect_uri_mismatch,- // invalid_client) lives in these fields. Log them so such failures are diagnosable.- const oauthDetail = extractOAuthErrorDetail(err);- if (oauthDetail) {- getLog().error(`OAuth/OpenID error on ${req.method} ${req.url}: ${oauthDetail}`);+ // Many upstream failures hide their real reason below the surface `.message`: OAuth/OIDC errors+ // stash it in `error` / `error_description`, while undici's opaque `TypeError: fetch failed`+ // (thrown e.g. when the OIDC discovery/token request can't reach the provider — TLS rejection,+ // DNS failure, refused connection) keeps it in the nested `.cause` chain. Surface both so these+ // are diagnosable instead of a bare "fetch failed".+ const detail = describeError(err);+ const plainMessage = err instanceof Error ? err.message : undefined;+ if (detail && detail !== plainMessage) {+ getLog().error(`Error on ${req.method} ${req.url}: ${detail}`);}res.status(statusCode).send({@@ -76,6 +77,54 @@ export function extractOAuthErrorDetail(err: unknown) {return [ code, description ].filter(Boolean).join(": ");}+/**+ * Builds a single-line, diagnosable description of an error for logging. Beyond the top-level+ * `.message` it surfaces:+ * - OAuth/OIDC `error` / `error_description` fields (see {@link extractOAuthErrorDetail}),+ * - Node system-error fields (`code`, `syscall`, `hostname`, `address`, `port`), and+ * - the nested `.cause` chain — crucial for undici's opaque `TypeError: fetch failed`, whose real+ * reason (e.g. `DEPTH_ZERO_SELF_SIGNED_CERT`, `ENOTFOUND`, `ECONNREFUSED`) only lives in `cause`.+ *+ * Returns `null` for non-object errors (e.g. a thrown string) that carry no extractable detail.+ */+export function describeError(err: unknown) {+ const segments: string[] = [];+ const seen = new Set<unknown>();+ let current: unknown = err;++ // Bounded walk down the cause chain, guarding against cycles and pathologically deep nesting.+ while (current && typeof current === "object" && !seen.has(current) && seen.size < 8) {+ seen.add(current);++ const candidate = current as { message?: unknown; cause?: unknown } & Record<string, unknown>;+ const parts: string[] = [];++ if (typeof candidate.message === "string" && candidate.message) {+ parts.push(candidate.message);+ }++ const oauthDetail = extractOAuthErrorDetail(current);+ if (oauthDetail) {+ parts.push(oauthDetail);+ }++ const systemFields = [ candidate.code, candidate.syscall, candidate.hostname, candidate.address, candidate.port ]+ .filter((value): value is string | number => typeof value === "string" || typeof value === "number")+ .map(String);+ if (systemFields.length) {+ parts.push(`[${systemFields.join(" ")}]`);+ }++ if (parts.length) {+ segments.push(parts.join(" "));+ }++ current = candidate.cause;+ }++ return segments.length ? segments.join(" ← caused by: ") : null;+}+export default {register};