diff --git a/backend/README.md b/backend/README.md index c34fc9241..9ce2a6f4a 100644 --- a/backend/README.md +++ b/backend/README.md @@ -217,9 +217,12 @@ The important variables are: - `FRONTEND_ORIGIN=http://localhost:3400` for local browser auth and CORS. - `BETTER_AUTH_URL=http://localhost:3201` for auth redirects and `BETTER_AUTH_SECRET` for session signing. Set `GOOGLE_CLIENT_ID` and - `GOOGLE_CLIENT_SECRET` for Google sign-in. Without `SIGNUP_OPEN` (below) - production accepts existing users only; their email/password sign-in remains - available while Google is optional. + `GOOGLE_CLIENT_SECRET` for Google sign-in, and `OIDC_ISSUER`, + `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` (with `OIDC_BUTTON_LABEL` for the + button) for sign-in through your own OpenID Connect provider. Without + `SIGNUP_OPEN` (below) production accepts existing and invited users only; + their email/password sign-in remains available while both providers are + optional. - `SIGNUP_OPEN=1` opens email/password sign-up behind a mailed confirmation (needs `CONNECTOR_EMAIL_HOST` and `CONNECTOR_EMAIL_FROM`); `SIGNUP_ALLOWED_DOMAINS` and `SIGNUP_INVITE_CODE` narrow it. diff --git a/backend/src/auth-invitations.ts b/backend/src/auth-invitations.ts index 1b4002407..aa5f9d702 100644 --- a/backend/src/auth-invitations.ts +++ b/backend/src/auth-invitations.ts @@ -3,7 +3,7 @@ import { and, eq, gt, isNotNull } from "drizzle-orm"; import { sendSmtp } from "./connectors/email/smtp"; import { db, type Executor } from "./db/client"; import { account, invitation, user } from "./db/auth-schema"; -import { env, googleAuthEnabled, type InvitationMailConfig, invitationMailConfig, sameSecret, selfSignupEnabled } from "./env"; +import { env, type InvitationMailConfig, invitationMailConfig, providerSignInEnabled, sameSecret, selfSignupEnabled } from "./env"; /** * Organisation invitations, and the sign-up verification mail that shares @@ -296,13 +296,14 @@ export async function deliverVerification( } export const NO_WAY_IN = - "That address has no account with a password here, and this deployment cannot create one. Set up Google sign-in, or invite an address that already signs in with a password."; + "That address has no account with a password here, and this deployment cannot create one. Set up Google or OpenID Connect sign-in, or invite an address that already signs in with a password."; /** Whether an invitation to this address can ever be used. Any deployment that * creates accounts says yes; a closed one needs an account with a password, - * since a Google-only account from a time when Google was on has no way in. */ + * since an account a provider created (Google or OpenID Connect) from a time + * when that provider was on has no way in. */ export async function canSignIn(email: string): Promise { - if (selfSignupEnabled() || googleAuthEnabled()) return true; + if (selfSignupEnabled() || providerSignInEnabled()) return true; const [known] = await db .select({ id: user.id }) .from(user) diff --git a/backend/src/auth.ts b/backend/src/auth.ts index 1e35930f8..f862240b2 100644 --- a/backend/src/auth.ts +++ b/backend/src/auth.ts @@ -2,8 +2,8 @@ import { electron } from "@better-auth/electron"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { APIError } from "better-auth/api"; -import { organization } from "better-auth/plugins"; -import { and, eq } from "drizzle-orm"; +import { genericOAuth, organization } from "better-auth/plugins"; +import { eq } from "drizzle-orm"; import { ensurePersonalOrgForUser, hasCredential, unverifiedClaim } from "./auth-hooks"; import { organizationLimitReached } from "./auth/organization-limit"; import { @@ -20,6 +20,8 @@ import { betterAuthTrustedOrigins, env, googleAuthConfig, + OIDC_PROVIDER_ID, + oidcAuthConfig, openSignupConfig, selfSignupEnabled, signupRefusal, @@ -31,15 +33,27 @@ import { * limiter and the sign-up limiter then both see the address the edge saw. */ const TRUSTED_PROXIES = ["127.0.0.0/8", "::1/128", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; +/** The display name an OpenID Connect identity gets: the `name` claim, else the + * given and family names, else the username, else the address. Many providers + * send `name` only once a person has filled in their names, and the library + * refuses a sign-in without one. */ +export function oidcDisplayName(profile: Record): string | undefined { + const text = (value: unknown) => (typeof value === "string" ? value.trim() : ""); + const given = [text(profile.given_name), text(profile.family_name)].filter(Boolean).join(" "); + return text(profile.name) || given || text(profile.preferred_username) || text(profile.email) || undefined; +} + /** - * Better Auth server with Google, existing-account password sign-in, and - * organizations. A closed deployment creates no accounts on its own: a verified - * Google identity links to an existing local user, or creates one only when a - * pending organisation invitation names that email. SIGNUP_OPEN (env.ts) opens - * email-and-password sign-up behind mail verification. + * Better Auth server with Google, OpenID Connect, existing-account password + * sign-in, and organizations. A closed deployment creates no accounts on its + * own: a verified Google or OpenID Connect identity links to an existing local + * user, or creates one only when a pending organisation invitation names that + * email. SIGNUP_OPEN (env.ts) opens email-and-password sign-up behind mail + * verification. */ export function createAuthServer() { const google = googleAuthConfig(); + const oidc = oidcAuthConfig(); const allowSignup = selfSignupEnabled(); const open = openSignupConfig(); if (signupSwitchOn() && !open) { @@ -110,6 +124,30 @@ export function createAuthServer() { }, }), electron(), + // Each new identity answers to the same user-create hook as Google below: + // invited with a verified address, or admitted by the sign-up policy. + ...(oidc + ? [ + genericOAuth({ + config: [ + { + providerId: OIDC_PROVIDER_ID, + discoveryUrl: oidc.discoveryUrl, + clientId: oidc.clientId, + clientSecret: oidc.clientSecret, + scopes: ["openid", "email", "profile"], + pkce: true, + mapProfileToUser: (profile) => ({ + name: oidcDisplayName(profile), + // Only a literal `email_verified: true` vouches for the + // address; a missing claim or a string does not. + emailVerified: profile.email_verified === true, + }), + }, + ], + }), + ] + : []), ], trustedOrigins: betterAuthTrustedOrigins(), databaseHooks: { @@ -130,6 +168,13 @@ export function createAuthServer() { // body; a Google identity presents none. const refusal = signupRefusal(user.email, context?.body?.inviteCode, process.env, pending); if (refusal) throw APIError.from("FORBIDDEN", { code: "SIGNUP_DISABLED", message: refusal }); + // A provider identity creates an account only for an address the + // provider verified: an unverified claim could name anyone's address, + // and its account row would outlive the real owner's takeover. Email + // sign-up confirms the address by mail instead. + if (context?.path !== "/sign-up/email" && user.emailVerified !== true) { + throw APIError.from("FORBIDDEN", { code: "SIGNUP_DISABLED", message: "Sign-up needs an address your provider has verified" }); + } }, after: async (user) => { // An open sign-up gets its organisation once the address is confirmed @@ -168,13 +213,14 @@ export function createAuthServer() { create: { before: async (account) => { // A provider identity that verified the address (the library links no - // other) outranks a password nobody confirmed: linking to a claim (an - // account that never confirmed its address and belongs nowhere) drops - // the claim's password, and the account is that person's; the library + // other) outranks everything attached to an account nobody confirmed: + // linking to a claim (an account that never confirmed its address and + // belongs nowhere) drops the claim's password and any other sign-in + // attached before, and the account is that person's; the library // marks the address confirmed right after the link. Invited or not, // open or closed: the account already exists, no door is opened. if (account.providerId !== "credential" && (await unverifiedClaim(account.userId))) { - await db.delete(schema.account).where(and(eq(schema.account.userId, account.userId), eq(schema.account.providerId, "credential"))); + await db.delete(schema.account).where(eq(schema.account.userId, account.userId)); } }, after: async (account) => { diff --git a/backend/src/auth/routes.ts b/backend/src/auth/routes.ts index 9d679189e..6d843518b 100644 --- a/backend/src/auth/routes.ts +++ b/backend/src/auth/routes.ts @@ -5,7 +5,7 @@ import { INVITATION_EXPIRES_IN_SECONDS, NO_WAY_IN, canSignIn, deliverInvitation import { acceptLinkedInvitationAsMember, bindInvitedSlackSender, linkedSlackSenders, reopenInvitedRequest } from "../slack/access-requests"; import { db } from "../db/client"; import { invitation, member, organization, user } from "../db/auth-schema"; -import { allowDevOrg, betterAuthTrustedOrigins, googleAuthEnabled, invitationMailEnabled, openSignupConfig } from "../env"; +import { allowDevOrg, betterAuthTrustedOrigins, googleAuthEnabled, invitationMailEnabled, oidcAuthConfig, openSignupConfig } from "../env"; import type { AppEnv } from "../http"; import { operatorAccessAllowed } from "../operator/access"; import { withOrgLock } from "../org-lock"; @@ -33,8 +33,12 @@ async function redactSessionTokens(response: Response): Promise { const routes = new Hono(); routes.get("/api/auth/provider-config", (c) => { const open = openSignupConfig(); + const oidc = oidcAuthConfig(); return c.json({ google: googleAuthEnabled(), + // OpenID Connect sign-in: only the button's label; the issuer and client + // stay on the server. + oidc: oidc ? { label: oidc.label } : null, emailPassword: true, allowDevOrg: allowDevOrg(), invitationEmail: invitationMailEnabled(), diff --git a/backend/src/env.ts b/backend/src/env.ts index 266ee7e41..49a687c54 100644 --- a/backend/src/env.ts +++ b/backend/src/env.ts @@ -321,6 +321,73 @@ export function googleAuthEnabled(): boolean { return googleAuthConfig() !== null; } +/** The provider id better-auth registers for OpenID Connect sign-in. It names + * the callback path the identity provider must allow and the `providerId` of + * every account the provider vouches for, so it never changes. */ +export const OIDC_PROVIDER_ID = "oidc"; + +const DEFAULT_OIDC_BUTTON_LABEL = "SSO"; + +/** + * OpenID Connect sign-in for a self-hosted install (src/auth.ts), set up like + * {@link googleAuthConfig}: read per call, and `OIDC_ISSUER`, `OIDC_CLIENT_ID` + * and `OIDC_CLIENT_SECRET` must all be set or the provider is off. Anything in + * between, or an issuer that is not an http(s) URL, is a misconfiguration: + * warn and stay off rather than half-enable. `OIDC_BUTTON_LABEL` names the + * provider on the sign-in button ("Sign in with