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): fetch UserInfo at enrollment so name/email work with spec-compliant providers
Elian Doran0e53d004c2e4
diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.tsindex 6c9a99788f..2a55b8389e 100644--- a/apps/server/src/services/open_id.spec.ts+++ b/apps/server/src/services/open_id.spec.ts@@ -3,7 +3,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import config from "./config.js";import openIDEncryption from "./encryption/open_id_encryption.js";-import openID from "./open_id.js";+import openID, { resolveOAuthIdentity } from "./open_id.js";import sql from "./sql.js";import sqlInit from "./sql_init.js";@@ -172,7 +172,10 @@ describe("open_id", () => {vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);const saveSpy = vi.spyOn(openIDEncryption, "saveUser").mockReturnValue(true);const req = {- oidc: { user: { sub: "sub-1", name: "Alice", email: "[email protected]" } },+ oidc: {+ user: { sub: "sub-1", name: "Alice", email: "[email protected]" },+ fetchUserInfo: vi.fn().mockResolvedValue({})+ },session: { loggedIn: true } as Record<string, unknown>} as never;const session = { marker: 3 } as never;@@ -184,6 +187,40 @@ describe("open_id", () => {expect(result).toBe(session);});+ it("enrolls with name/email from UserInfo when the ID token omits them (Authelia case)", async () => {+ const cfg = buildConfig();+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);+ const saveSpy = vi.spyOn(openIDEncryption, "saveUser").mockReturnValue(true);+ // ID token carries only `sub`; the profile claims arrive from the UserInfo endpoint.+ const fetchUserInfo = vi.fn().mockResolvedValue({ name: "Alice", email: "[email protected]" });+ const req = {+ oidc: { user: { sub: "sub-1" }, fetchUserInfo },+ session: { loggedIn: true } as Record<string, unknown>+ } as never;++ await cfg.afterCallback(req, {} as never, { marker: 7 } as never);++ expect(fetchUserInfo).toHaveBeenCalled();+ expect(saveSpy).toHaveBeenCalledWith("sub-1", "Alice", "[email protected]");+ });++ it("falls back to ID token claims when the UserInfo fetch fails", async () => {+ const cfg = buildConfig();+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);+ const saveSpy = vi.spyOn(openIDEncryption, "saveUser").mockReturnValue(true);+ const req = {+ oidc: {+ user: { sub: "sub-1", name: "Alice", email: "[email protected]" },+ fetchUserInfo: vi.fn().mockRejectedValue(new Error("network down"))+ },+ session: { loggedIn: true } as Record<string, unknown>+ } as never;++ await cfg.afterCallback(req, {} as never, { marker: 8 } as never);++ expect(saveSpy).toHaveBeenCalledWith("sub-1", "Alice", "[email protected]");+ });+it("refuses enrollment from an unauthenticated session (no first-login claim)", async () => {const cfg = buildConfig();vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);@@ -235,4 +272,29 @@ describe("open_id", () => {expect(result).toBe(session);});});++ describe("resolveOAuthIdentity", () => {+ it("prefers the ID token claims when present", () => {+ const identity = resolveOAuthIdentity(+ { name: "Alice", email: "[email protected]" },+ { name: "Other", email: "[email protected]" }+ );+ expect(identity).toEqual({ name: "Alice", email: "[email protected]" });+ });++ it("falls back to UserInfo per-field when the ID token omits or blanks a claim", () => {+ expect(resolveOAuthIdentity({ sub: "x" }, { name: "Alice", email: "[email protected]" }))+ .toEqual({ name: "Alice", email: "[email protected]" });+ // Empty strings in the ID token are treated as missing.+ expect(resolveOAuthIdentity({ name: "", email: "[email protected]" }, { name: "Alice" }))+ .toEqual({ name: "Alice", email: "[email protected]" });+ });++ it("yields empty strings when a claim is on neither source", () => {+ expect(resolveOAuthIdentity({ sub: "x" }, undefined)).toEqual({ name: "", email: "" });+ expect(resolveOAuthIdentity(undefined, undefined)).toEqual({ name: "", email: "" });+ // Non-string claim values are ignored rather than coerced.+ expect(resolveOAuthIdentity({ name: 42, email: null }, undefined)).toEqual({ name: "", email: "" });+ });+ });});diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.tsindex 6f42971d35..68cfdd754c 100644--- a/apps/server/src/services/open_id.ts+++ b/apps/server/src/services/open_id.ts@@ -168,11 +168,20 @@ function generateOAuthConfig() {return session;}- openIDEncryption.saveUser(- incomingSubject,- user.name?.toString() ?? "",- user.email?.toString() ?? ""- );+ // The profile claims (name/email) aren't guaranteed to be in the ID token under the+ // authorization-code flow — spec-compliant providers (Authelia, Zitadel, Keycloak) only+ // return them from the UserInfo endpoint. Fetch it and merge so enrollment records a real+ // name/email regardless of provider; on failure we fall back to whatever the ID token+ // carried (e.g. Google, which does include them).+ let userInfo: Record<string, unknown> | undefined;+ try {+ userInfo = await req.oidc.fetchUserInfo();+ } catch (error) {+ getLog().info(`OAuth enrollment: UserInfo fetch failed, using ID token claims only. ${error instanceof Error ? error.message : error}`);+ }++ const { name, email } = resolveOAuthIdentity(user, userInfo);+ openIDEncryption.saveUser(incomingSubject, name, email);}req.session.loggedIn = true;@@ -218,3 +227,28 @@ function resolveClientAuthMethod() {const issuer = config.MultiFactorAuthentication.oauthIssuerBaseUrl.replace(/\/+$/, "");return issuer === GOOGLE_ISSUER ? "client_secret_post" : "client_secret_basic";}++/**+ * Resolves the display name and email to enroll for an OAuth account. These profile claims may live in+ * the ID token (e.g. Google) or only be available from the UserInfo endpoint (e.g. Authelia, Zitadel,+ * Keycloak), so each field is taken from the ID token when present and falls back to UserInfo. A field+ * absent from both yields an empty string, matching the previous behaviour.+ */+export function resolveOAuthIdentity(+ idTokenClaims: Record<string, unknown> | undefined,+ userInfo: Record<string, unknown> | undefined+) {+ return {+ name: firstNonEmptyString(idTokenClaims?.name, userInfo?.name) ?? "",+ email: firstNonEmptyString(idTokenClaims?.email, userInfo?.email) ?? ""+ };+}++function firstNonEmptyString(...values: unknown[]) {+ for (const value of values) {+ if (typeof value === "string" && value.length > 0) {+ return value;+ }+ }+ return undefined;+}