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 ").
+ *
+ * The endpoints come from the issuer's discovery document
+ * (`/.well-known/openid-configuration`). The redirect URI the
+ * provider must allow is `/api/auth/oauth2/callback/oidc`.
+ */
+export interface OidcAuthConfig {
+ readonly discoveryUrl: string;
+ readonly clientId: string;
+ readonly clientSecret: string;
+ readonly label: string;
+}
+
+export function oidcAuthConfig(
+ source: Record = process.env,
+): OidcAuthConfig | null {
+ const issuer = source.OIDC_ISSUER?.trim();
+ const clientId = source.OIDC_CLIENT_ID?.trim();
+ const clientSecret = source.OIDC_CLIENT_SECRET?.trim();
+ if (!issuer && !clientId && !clientSecret) return null; // unset → silently off
+ if (!issuer || !clientId || !clientSecret) {
+ console.warn(
+ "[auth] OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are only partially set: " +
+ "OpenID Connect sign-in disabled. Set all three or none.",
+ );
+ return null;
+ }
+ const url = URL.canParse(issuer) ? new URL(issuer) : null;
+ if (!url || (url.protocol !== "https:" && url.protocol !== "http:") || url.search || url.hash) {
+ console.warn("[auth] OIDC_ISSUER is not an http(s) URL without a query: OpenID Connect sign-in disabled.");
+ return null;
+ }
+ return {
+ // OpenID Connect Discovery 1.0, section 4: drop a trailing slash, then
+ // append the well-known path, so an issuer with a path keeps it.
+ discoveryUrl: `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`,
+ clientId,
+ clientSecret,
+ label: source.OIDC_BUTTON_LABEL?.trim() || DEFAULT_OIDC_BUTTON_LABEL,
+ };
+}
+
+/** True when OpenID Connect sign-in is fully configured. */
+export function oidcAuthEnabled(): boolean {
+ return oidcAuthConfig() !== null;
+}
+
+/** True when a provider that vouches for an email address (Google or OpenID
+ * Connect) can sign people in: such a sign-in links an existing account with
+ * that verified address, so an account without a password still has a way in. */
+export function providerSignInEnabled(): boolean {
+ return googleAuthEnabled() || oidcAuthEnabled();
+}
+
/**
* GitHub config for real repository selection (src/github/*). Backend-only: the
* token NEVER reaches React — it authenticates the repo listing here and rides
diff --git a/backend/src/slack/access-requests.ts b/backend/src/slack/access-requests.ts
index e49a6cded..0fd51dedc 100644
--- a/backend/src/slack/access-requests.ts
+++ b/backend/src/slack/access-requests.ts
@@ -18,7 +18,7 @@ import { sendSmtp } from "../connectors/email/smtp";
import { db, type Executor } from "../db/client";
import { invitation, member, organization, user } from "../db/auth-schema";
import { slackAccessRequests, slackUsers, slackWorkspaces } from "../db/schema";
-import { env, googleAuthEnabled, invitationMailConfig } from "../env";
+import { env, invitationMailConfig, providerSignInEnabled } from "../env";
import { withOrgLock } from "../org-lock";
import type { SlackClient } from "./client";
import { kickSlackOutbox } from "./outbox/delivery";
@@ -582,12 +582,13 @@ async function provenIdentity(tx: Executor, row: Request): Promise {
const config = invitationMailConfig();
- if (!config || !googleAuthEnabled()) return;
+ if (!config || !providerSignInEnabled()) return;
const [row] = await db
.select({ email: slackAccessRequests.email, userId: slackUsers.userId })
.from(slackAccessRequests)
diff --git a/backend/test/oidc-auth.test.ts b/backend/test/oidc-auth.test.ts
new file mode 100644
index 000000000..e361a5075
--- /dev/null
+++ b/backend/test/oidc-auth.test.ts
@@ -0,0 +1,342 @@
+import { afterAll, afterEach, describe, expect, test } from "bun:test";
+import { eq, like } from "drizzle-orm";
+
+// OpenID Connect sign-in through the real better-auth routes and database: the
+// sign-in request, the provider's redirect back to the callback, the session.
+// Only the identity provider is fake, stubbed at `fetch` (discovery and token
+// endpoints), so no test reaches the network.
+const OIDC = {
+ OIDC_ISSUER: "https://idp.example.test/realms/acme",
+ OIDC_CLIENT_ID: "useagent-test",
+ OIDC_CLIENT_SECRET: "oidc-test-secret",
+ OIDC_BUTTON_LABEL: "Acme SSO",
+};
+const NAMES = [...Object.keys(OIDC), "NODE_ENV", "BETTER_AUTH_SECRET", "SIGNUP_OPEN", "CONNECTOR_EMAIL_HOST", "CONNECTOR_EMAIL_FROM", "SIGNUP_ALLOWED_DOMAINS"];
+const prior = Object.fromEntries(NAMES.map((name) => [name, process.env[name]]));
+function restore(names: readonly string[]): void {
+ for (const name of names) {
+ if (prior[name] === undefined) delete process.env[name];
+ else process.env[name] = prior[name];
+ }
+}
+
+await import("./helpers");
+const { createAuthServer, oidcDisplayName } = await import("../src/auth");
+const { db } = await import("../src/db/client");
+const { account, invitation, member, organization, session, user } = await import("../src/db/auth-schema");
+const { env, oidcAuthConfig, providerSignInEnabled } = await import("../src/env");
+const { canSignIn } = await import("../src/auth-invitations");
+
+Object.assign(process.env, OIDC);
+// Built outside production so the library's own rate limiter (on in production)
+// lets this file sign in many times; the sign-up policy reads NODE_ENV per
+// request, and each sign-in below runs in production.
+process.env.BETTER_AUTH_SECRET = "oidc-auth-test-secret-0123456789abcdef";
+const auth = createAuthServer();
+restore(["BETTER_AUTH_SECRET"]);
+
+const prefix = `oidc-auth-${crypto.randomUUID().slice(0, 8)}`;
+const address = (label: string, domain = "example.test") => `${prefix}-${label}@${domain}`;
+/** Where the library sends a browser whose new account the sign-up policy refused. */
+const REFUSED = "/api/auth/error?error=Account_creation_is_disabled";
+const DISCOVERY = `${OIDC.OIDC_ISSUER}/.well-known/openid-configuration`;
+const TOKEN_ENDPOINT = `${OIDC.OIDC_ISSUER}/protocol/openid-connect/token`;
+
+/** What the fake provider says about the person who signs in next. */
+let claims: Record = {};
+const tokenRequests: URLSearchParams[] = [];
+const realFetch = globalThis.fetch;
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url === DISCOVERY) {
+ return Response.json({
+ issuer: OIDC.OIDC_ISSUER,
+ authorization_endpoint: `${OIDC.OIDC_ISSUER}/protocol/openid-connect/auth`,
+ token_endpoint: TOKEN_ENDPOINT,
+ userinfo_endpoint: `${OIDC.OIDC_ISSUER}/protocol/openid-connect/userinfo`,
+ });
+ }
+ if (url === TOKEN_ENDPOINT) {
+ tokenRequests.push(new URLSearchParams(String(init?.body ?? "")));
+ return Response.json({ access_token: "access", token_type: "Bearer", expires_in: 300, id_token: idToken(claims) });
+ }
+ return realFetch(input, init);
+}) as typeof fetch;
+
+/** An ID token as the token endpoint returns it over TLS. The library reads its
+ * claims without checking the signature, so this one carries none. */
+function idToken(payload: Record): string {
+ const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
+ return `${part({ alg: "none", typ: "JWT" })}.${part({ iss: OIDC.OIDC_ISSUER, aud: OIDC.OIDC_CLIENT_ID, ...payload })}.`;
+}
+
+function cookieHeader(response: Response, previous = ""): string {
+ const jar = new Map(previous.split("; ").filter(Boolean).map((pair) => [pair.split("=")[0], pair] as const));
+ for (const line of response.headers.getSetCookie()) {
+ const pair = line.split(";")[0];
+ jar.set(pair.split("=")[0], pair);
+ }
+ return [...jar.values()].join("; ");
+}
+
+/** The whole browser round trip: ask to sign in, follow the provider back to
+ * the callback with a code, and report where the callback sends the browser. */
+async function signInAs(
+ person: Record,
+ extra: Record = {},
+): Promise<{ status: number; location: string; cookies: string }> {
+ claims = person;
+ const started = await auth.handler(
+ new Request(`${env.BETTER_AUTH_URL}/api/auth/sign-in/oauth2`, {
+ method: "POST",
+ headers: { "content-type": "application/json", origin: env.FRONTEND_ORIGIN },
+ body: JSON.stringify({ providerId: "oidc", callbackURL: "/", ...extra }),
+ }),
+ );
+ expect(started.status).toBe(200);
+ const { url } = (await started.json()) as { url: string };
+ const authorize = new URL(url);
+ expect(authorize.origin + authorize.pathname).toBe(`${OIDC.OIDC_ISSUER}/protocol/openid-connect/auth`);
+ expect(authorize.searchParams.get("client_id")).toBe(OIDC.OIDC_CLIENT_ID);
+ expect(authorize.searchParams.get("scope")).toBe("openid email profile");
+ expect(authorize.searchParams.get("code_challenge_method")).toBe("S256");
+ expect(authorize.searchParams.get("redirect_uri")).toBe(`${env.BETTER_AUTH_URL}/api/auth/oauth2/callback/oidc`);
+ const state = authorize.searchParams.get("state") ?? "";
+ const cookies = cookieHeader(started);
+ const back = await auth.handler(
+ new Request(`${env.BETTER_AUTH_URL}/api/auth/oauth2/callback/oidc?code=provider-code&state=${encodeURIComponent(state)}`, {
+ headers: { cookie: cookies },
+ }),
+ );
+ return { status: back.status, location: back.headers.get("location") ?? "", cookies: cookieHeader(back, cookies) };
+}
+
+async function inProduction(work: () => Promise, extra: Record = {}): Promise {
+ process.env.NODE_ENV = "production";
+ Object.assign(process.env, extra);
+ try {
+ return await work();
+ } finally {
+ restore(["NODE_ENV", ...Object.keys(extra)]);
+ }
+}
+
+async function usersWith(email: string) {
+ return db.select().from(user).where(eq(user.email, email));
+}
+
+const inviterId = `user_${crypto.randomUUID()}`;
+const orgId = `org_${crypto.randomUUID()}`;
+await db.insert(user).values({ id: inviterId, name: prefix, email: address("inviter"), emailVerified: true });
+await db.insert(organization).values({ id: orgId, name: prefix, slug: `${prefix}-org`, createdAt: new Date() });
+await db.insert(member).values({ id: `member_${crypto.randomUUID()}`, organizationId: orgId, userId: inviterId, role: "owner", createdAt: new Date() });
+
+async function invite(email: string): Promise {
+ await db.insert(invitation).values({
+ id: `inv_${crypto.randomUUID()}`,
+ organizationId: orgId,
+ email,
+ role: "member",
+ status: "pending",
+ expiresAt: new Date(Date.now() + 86_400_000),
+ inviterId,
+ });
+}
+
+afterEach(() => {
+ tokenRequests.length = 0;
+});
+
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ restore(NAMES);
+ await db.delete(user).where(like(user.email, `${prefix}%`));
+ await db.delete(organization).where(like(organization.slug, `${prefix}%`));
+});
+
+describe("OpenID Connect settings", () => {
+ test("all three settings turn it on, with the discovery URL under the issuer and a default label", () => {
+ expect(oidcAuthConfig({ OIDC_ISSUER: "https://idp.example.test/realms/acme/", OIDC_CLIENT_ID: "id", OIDC_CLIENT_SECRET: "secret" })).toEqual({
+ discoveryUrl: "https://idp.example.test/realms/acme/.well-known/openid-configuration",
+ clientId: "id",
+ clientSecret: "secret",
+ label: "SSO",
+ });
+ expect(oidcAuthConfig({ OIDC_ISSUER: "http://localhost:8080", OIDC_CLIENT_ID: "id", OIDC_CLIENT_SECRET: "secret", OIDC_BUTTON_LABEL: " Okta " })).toMatchObject({
+ discoveryUrl: "http://localhost:8080/.well-known/openid-configuration",
+ label: "Okta",
+ });
+ });
+
+ test("absent, partial or malformed settings leave it off", () => {
+ expect(oidcAuthConfig({})).toBeNull();
+ expect(oidcAuthConfig({ OIDC_ISSUER: "https://idp.example.test", OIDC_CLIENT_ID: "id" })).toBeNull();
+ expect(oidcAuthConfig({ OIDC_CLIENT_ID: "id", OIDC_CLIENT_SECRET: "secret" })).toBeNull();
+ expect(oidcAuthConfig({ OIDC_ISSUER: " ", OIDC_CLIENT_ID: "id", OIDC_CLIENT_SECRET: "secret" })).toBeNull();
+ for (const issuer of ["idp.example.test", "ftp://idp.example.test", "https://idp.example.test/?realm=a", "https://idp.example.test/#a"]) {
+ expect(oidcAuthConfig({ OIDC_ISSUER: issuer, OIDC_CLIENT_ID: "id", OIDC_CLIENT_SECRET: "secret" })).toBeNull();
+ }
+ });
+
+ test("the display name falls back from name to given and family names, the username, then the address", () => {
+ expect(oidcDisplayName({ name: "Ada Lovelace", preferred_username: "ada" })).toBe("Ada Lovelace");
+ expect(oidcDisplayName({ given_name: "Ada", family_name: "Lovelace", preferred_username: "ada" })).toBe("Ada Lovelace");
+ expect(oidcDisplayName({ name: " ", preferred_username: "ada", email: "ada@example.test" })).toBe("ada");
+ expect(oidcDisplayName({ email: "ada@example.test" })).toBe("ada@example.test");
+ expect(oidcDisplayName({})).toBeUndefined();
+ });
+});
+
+describe("the sign-in card", () => {
+ test("provider-config names the button only when OpenID Connect is set up", async () => {
+ const { handleAuthRequest } = await import("../src/auth/routes");
+ const read = async () => (await (await handleAuthRequest(new Request("http://localhost:3211/api/auth/provider-config"))).json()) as Record;
+ const on = await read();
+ expect(on.oidc).toEqual({ label: "Acme SSO" });
+ expect(JSON.stringify(on)).not.toContain(OIDC.OIDC_CLIENT_SECRET);
+ expect(JSON.stringify(on)).not.toContain(OIDC.OIDC_ISSUER);
+ expect(providerSignInEnabled()).toBe(true);
+
+ for (const name of Object.keys(OIDC)) delete process.env[name];
+ try {
+ expect((await read()).oidc).toBeNull();
+ } finally {
+ Object.assign(process.env, OIDC);
+ }
+ });
+
+ test("a server built without the settings has no OpenID Connect routes", async () => {
+ for (const name of Object.keys(OIDC)) delete process.env[name];
+ let plain: ReturnType;
+ try {
+ plain = createAuthServer();
+ } finally {
+ Object.assign(process.env, OIDC);
+ }
+ const response = await plain.handler(
+ new Request(`${env.BETTER_AUTH_URL}/api/auth/sign-in/oauth2`, {
+ method: "POST",
+ headers: { "content-type": "application/json", origin: env.FRONTEND_ORIGIN },
+ body: JSON.stringify({ providerId: "oidc", callbackURL: "/" }),
+ }),
+ );
+ expect(response.status).toBe(404);
+ });
+});
+
+describe("new accounts follow the Google rules", () => {
+ test("a closed deployment refuses an identity nobody invited, and creates nothing", async () => {
+ const email = address("stranger");
+ const result = await inProduction(() => signInAs({ sub: "stranger", email, email_verified: true, name: "Stranger" }));
+ expect(result.status).toBe(302);
+ expect(result.location).toContain(REFUSED);
+ expect(result.cookies).not.toContain("session_token");
+ expect(await usersWith(email)).toEqual([]);
+ // The code was exchanged with the client's own secret and the PKCE verifier.
+ expect(tokenRequests).toHaveLength(1);
+ expect(tokenRequests[0]?.get("code")).toBe("provider-code");
+ expect(tokenRequests[0]?.get("code_verifier")?.length).toBeGreaterThan(0);
+ });
+
+ test("the web card's error URL brings a refused person back to the login card with the reason", async () => {
+ const email = address("refused-to-card");
+ const result = await inProduction(() =>
+ signInAs({ sub: "refused-to-card", email, email_verified: true, name: "Refused" }, { errorCallbackURL: "/login?via=provider" }),
+ );
+ expect(result.location).toBe("/login?via=provider&error=Account_creation_is_disabled");
+ expect(await usersWith(email)).toEqual([]);
+ });
+
+ test("a pending invitation lets a verified identity create its account and sign in", async () => {
+ const email = address("invited");
+ await invite(email);
+ const result = await inProduction(() =>
+ signInAs({ sub: "invited", email: email.toUpperCase(), email_verified: true, preferred_username: "invited-person" }),
+ );
+ expect(result.status).toBe(302);
+ expect(result.location).toBe("/");
+ expect(result.cookies).toContain("session_token");
+ const [created] = await usersWith(email);
+ expect(created).toMatchObject({ email, emailVerified: true, name: "invited-person" });
+ expect(await db.select({ providerId: account.providerId, accountId: account.accountId }).from(account).where(eq(account.userId, created!.id))).toEqual([
+ { providerId: "oidc", accountId: "invited" },
+ ]);
+ expect(await db.select().from(session).where(eq(session.userId, created!.id))).toHaveLength(1);
+ // Every account lands in a workspace of its own.
+ expect(await db.select().from(member).where(eq(member.userId, created!.id))).toHaveLength(1);
+ });
+
+ test("an invitation does not admit an address the provider did not verify", async () => {
+ for (const [label, verified] of [["unverified", false], ["string-verified", "true"], ["missing-verified", undefined]] as const) {
+ const email = address(label);
+ await invite(email);
+ const result = await inProduction(() => signInAs({ sub: label, email, email_verified: verified, name: label }));
+ expect(result.location).toContain(REFUSED);
+ expect(await usersWith(email)).toEqual([]);
+ }
+ });
+
+ test("open sign-up admits only its domains, like a Google identity", async () => {
+ const open = { SIGNUP_OPEN: "1", CONNECTOR_EMAIL_HOST: "127.0.0.1", CONNECTOR_EMAIL_FROM: "hello@example.test", SIGNUP_ALLOWED_DOMAINS: "example.test" };
+ const outside = address("outside", "elsewhere.test");
+ const refused = await inProduction(() => signInAs({ sub: "outside", email: outside, email_verified: true, name: "Outside" }), open);
+ expect(refused.location).toContain("/api/auth/error?error=Sign-up_is_limited_to_%40example.test_addresses");
+ expect(await usersWith(outside)).toEqual([]);
+
+ const inside = address("inside");
+ const admitted = await inProduction(() => signInAs({ sub: "inside", email: inside, email_verified: true, name: "Inside" }), open);
+ expect(admitted.location).toBe("/");
+ expect(await usersWith(inside)).toHaveLength(1);
+ });
+
+ test("open sign-up refuses an address the provider did not verify, and creates nothing", async () => {
+ const open = { SIGNUP_OPEN: "1", CONNECTOR_EMAIL_HOST: "127.0.0.1", CONNECTOR_EMAIL_FROM: "hello@example.test", SIGNUP_ALLOWED_DOMAINS: "example.test" };
+ const email = address("open-unverified");
+ const refused = await inProduction(() => signInAs({ sub: "open-unverified", email, email_verified: false, name: "Claimer" }), open);
+ expect(refused.location).toContain("/api/auth/error?error=Sign-up_needs_an_address_your_provider_has_verified");
+ expect(refused.cookies).not.toContain("session_token");
+ expect(await usersWith(email)).toEqual([]);
+ expect(await db.select().from(account).where(eq(account.accountId, "open-unverified"))).toEqual([]);
+ });
+});
+
+describe("existing accounts", () => {
+ test("a verified identity links an existing account and signs it in; an unverified one does not", async () => {
+ const email = address("existing");
+ const id = `user_${crypto.randomUUID()}`;
+ await db.insert(user).values({ id, name: "Existing", email, emailVerified: true });
+
+ const refused = await inProduction(() => signInAs({ sub: "existing-unverified", email, email_verified: false, name: "Existing" }));
+ expect(refused.location).toContain("error=account_not_linked");
+ expect(await db.select().from(account).where(eq(account.userId, id))).toEqual([]);
+ expect(await db.select().from(session).where(eq(session.userId, id))).toEqual([]);
+
+ const linked = await inProduction(() => signInAs({ sub: "existing", email, email_verified: true, name: "Existing" }));
+ expect(linked.location).toBe("/");
+ expect(await db.select({ providerId: account.providerId }).from(account).where(eq(account.userId, id))).toEqual([{ providerId: "oidc" }]);
+ expect(await db.select().from(session).where(eq(session.userId, id))).toHaveLength(1);
+ });
+
+ test("a verified identity taking over an unconfirmed account drops every sign-in attached before", async () => {
+ const email = address("claimed");
+ const id = `user_${crypto.randomUUID()}`;
+ await db.insert(user).values({ id, name: "Claimed", email, emailVerified: false });
+ await db.insert(account).values({ id: `acct_${crypto.randomUUID()}`, userId: id, providerId: "oidc", accountId: "claimer", createdAt: new Date(), updatedAt: new Date() });
+
+ const owner = await inProduction(() => signInAs({ sub: "claimed-owner", email, email_verified: true, name: "Owner" }));
+ expect(owner.location).toBe("/");
+ expect(await db.select({ accountId: account.accountId }).from(account).where(eq(account.userId, id))).toEqual([{ accountId: "claimed-owner" }]);
+ });
+
+ test("an invitation to an address without a password can be used once OpenID Connect is on", async () => {
+ await inProduction(async () => {
+ expect(await canSignIn(address("nobody-yet"))).toBe(true);
+ for (const name of Object.keys(OIDC)) delete process.env[name];
+ try {
+ expect(await canSignIn(address("nobody-yet"))).toBe(false);
+ } finally {
+ Object.assign(process.env, OIDC);
+ }
+ });
+ });
+});
diff --git a/compose.local.yaml b/compose.local.yaml
index f906d72c0..c9f7870e6 100644
--- a/compose.local.yaml
+++ b/compose.local.yaml
@@ -44,6 +44,10 @@ services:
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:?set BETTER_AUTH_SECRET in .env.compose}
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
+ OIDC_ISSUER: ${OIDC_ISSUER:-}
+ OIDC_CLIENT_ID: ${OIDC_CLIENT_ID:-}
+ OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET:-}
+ OIDC_BUTTON_LABEL: ${OIDC_BUTTON_LABEL:-}
SIGNUP_OPEN: ${SIGNUP_OPEN:-}
SIGNUP_ALLOWED_DOMAINS: ${SIGNUP_ALLOWED_DOMAINS:-}
SIGNUP_INVITE_CODE: ${SIGNUP_INVITE_CODE:-}
diff --git a/deploy/compose/env.example b/deploy/compose/env.example
index f8cf23be6..8cfc5d6b7 100644
--- a/deploy/compose/env.example
+++ b/deploy/compose/env.example
@@ -4,6 +4,14 @@ BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters
# Google sign-in for existing users; public sign-up is closed unless opened below.
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
+# Sign-in through your own OpenID Connect provider (Okta, Microsoft Entra ID,
+# Keycloak, Authentik), with the same new-account rules as Google. Set all three
+# or none; the provider must allow /api/auth/oauth2/callback/oidc
+# as a redirect URI. The button reads "Sign in with ".
+# OIDC_ISSUER=
+# OIDC_CLIENT_ID=
+# OIDC_CLIENT_SECRET=
+# OIDC_BUTTON_LABEL=
# Open sign-up: anyone with an email address and a password, confirmed by a
# mailed link before the first sign-in. Needs CONNECTOR_EMAIL_HOST and
# CONNECTOR_EMAIL_FROM (the settings invitations use); without them the switch
diff --git a/docs-site/docs/platform/auth-and-orgs.mdx b/docs-site/docs/platform/auth-and-orgs.mdx
index ccfdd9664..c699cb3c1 100644
--- a/docs-site/docs/platform/auth-and-orgs.mdx
+++ b/docs-site/docs/platform/auth-and-orgs.mdx
@@ -14,15 +14,17 @@ backend, not trusted from the client.
`/login` and `/signup` go through the better-auth surface mounted at
`/api/auth/*` (`GET` and `POST`), which owns sessions, email/password sign-in,
and the organization plugin. Google social sign-in is env-gated: it is offered
-only when both `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set.
-`GET /api/config` advertises which methods are enabled
-(`auth: { google, emailPassword }`), so the UI renders the right affordances
-without probing.
-
-Self-service account creation is closed by default. Signup is refused for both
-email/password and Google whenever verified dev mode is off, and the check
-always fails closed when `NODE_ENV=production`, even if a dev-mode flag was
-accidentally left on. Production users are administratively provisioned or
+only when both `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set. Sign-in
+through your own OpenID Connect provider is gated the same way (see
+[Single sign-on with OpenID Connect](#single-sign-on-with-openid-connect)).
+`GET /api/auth/provider-config` advertises which methods are enabled
+(`google`, `oidc: { label }` or `null`, `emailPassword`), so the UI renders the
+right affordances without probing.
+
+Self-service account creation is closed by default. Signup is refused for
+email/password, Google and OpenID Connect whenever verified dev mode is off,
+and the check always fails closed when `NODE_ENV=production`, even if a
+dev-mode flag was accidentally left on. Production users are administratively provisioned or
invited.
A deployment opens sign-up with `SIGNUP_OPEN=1`. Anyone can then create an
@@ -58,6 +60,96 @@ invited one from creation, an open sign-up once its address is confirmed, a
taken-over claim once the identity links, whether or not another organisation
(a Slack workspace, say) admitted it first.
+## Single sign-on with OpenID Connect
+
+A self-hosted install can let people sign in with the identity provider they
+already use (Okta, Microsoft Entra ID, Keycloak, Authentik or any other
+OpenID Connect provider) instead of a separate password. Set these on the
+backend:
+
+| Variable | Value |
+|---|---|
+| `OIDC_ISSUER` | The provider's issuer URL. Its endpoints are read from `/.well-known/openid-configuration`. |
+| `OIDC_CLIENT_ID` | The client id the provider gave UseAgent. |
+| `OIDC_CLIENT_SECRET` | That client's secret. |
+| `OIDC_BUTTON_LABEL` | Optional. The button reads "Sign in with ``"; the default is "SSO". |
+
+All three of the first settings must be set, or none: anything in between, or
+an issuer that is not an http(s) URL, leaves OpenID Connect off with a warning
+at boot. When none is set nothing changes. The settings are read when the
+backend starts.
+
+In the provider, create a confidential client that uses the authorization code
+flow, and allow this redirect URI:
+
+```text
+/api/auth/oauth2/callback/oidc
+```
+
+UseAgent asks for the `openid`, `email` and `profile` scopes and uses PKCE. The
+sign-in button shows on the web sign-in card and on the desktop app's browser
+sign-in.
+
+New people follow the same rules as Google sign-in, so OpenID Connect never
+opens a way around invitations:
+
+- An address with a pending invitation gets an account, but only when the
+ provider says the address is verified (the `email_verified` claim is `true`).
+- Anyone else gets an account only when `SIGNUP_OPEN` admits them, narrowed by
+ `SIGNUP_ALLOWED_DOMAINS`. A provider sign-in carries no invite code, so with
+ `SIGNUP_INVITE_CODE` set only invited addresses get in this way.
+- An existing account with the same address is linked on the first sign-in
+ when the provider says the address is verified, so a person who used a
+ password before keeps their account and workspaces.
+
+A refused sign-in in the browser returns to the sign-in card, which says why.
+The account's name comes from the `name` claim, else the given and family
+names, else the username, else the address.
+
+### Try it with Keycloak
+
+This sets up a local Keycloak in Docker for a backend reached at
+`http://localhost:3400` (`BETTER_AUTH_URL`):
+
+```bash
+docker run -d --name keycloak -p 8080:8080 \
+ -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
+ quay.io/keycloak/keycloak:26.4 start-dev
+
+# Once http://localhost:8080 answers:
+kc() { docker exec keycloak /opt/keycloak/bin/kcadm.sh "$@"; }
+kc config credentials --server http://localhost:8080 --realm master --user admin --password admin
+kc create realms -s realm=acme -s enabled=true
+kc create clients -r acme -s clientId=useagent -s publicClient=false \
+ -s secret=change-me -s standardFlowEnabled=true \
+ -s 'redirectUris=["http://localhost:3400/api/auth/oauth2/callback/oidc"]'
+kc create users -r acme -s username=grace -s email=grace@acme.test \
+ -s emailVerified=true -s firstName=Grace -s lastName=Hopper -s enabled=true
+kc set-password -r acme --username grace --new-password change-me-too
+```
+
+Then start the backend with:
+
+```bash
+OIDC_ISSUER=http://localhost:8080/realms/acme
+OIDC_CLIENT_ID=useagent
+OIDC_CLIENT_SECRET=change-me
+OIDC_BUTTON_LABEL="Acme Keycloak"
+```
+
+`/login` now shows **Sign in with Acme Keycloak**. Invite `grace@acme.test` to
+a workspace (or open sign-up) and sign in as `grace`: the account is created as
+Grace Hopper and lands in the app. Without an invitation on a closed
+deployment, the card says the server did not create an account for that
+address.
+
+:::note
+The backend and the browser must both reach the issuer at the same URL, since
+the issuer the provider reports is checked on the way back. With Keycloak in
+Docker next to a containerized backend, set Keycloak's hostname (`KC_HOSTNAME`)
+to an address both can use.
+:::
+
## Organization scoping
The organization is the tenant boundary, and scope is resolved server-side on
diff --git a/frontend/app/desktop-auth/page.test.ts b/frontend/app/desktop-auth/page.test.ts
index e7b311370..bb9d0c540 100644
--- a/frontend/app/desktop-auth/page.test.ts
+++ b/frontend/app/desktop-auth/page.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test";
-import { desktopAuthRequest, restartElectronRedirect, startDesktopGoogleSignIn } from "./request";
+import { desktopAuthRequest, restartElectronRedirect, startDesktopGoogleSignIn, startDesktopOidcSignIn } from "./request";
import { desktopAuthClient } from "@/lib/desktop-auth-client";
const valid = `https://plane.example/desktop-auth?client_id=electron&state=${"A".repeat(16)}&code_challenge=${"B".repeat(43)}&code_challenge_method=S256`;
@@ -35,3 +35,14 @@ test("desktop Google sign-in returns OAuth to the desktop-auth page that polls f
await expect(startDesktopGoogleSignIn(request, async () => ({ error: { message: "denied" } })))
.rejects.toThrow("Could not start Google sign-in.");
});
+
+test("desktop OpenID Connect sign-in returns to the same desktop-auth page", async () => {
+ expect(typeof desktopAuthClient.signIn.oauth2).toBe("function");
+ const request = desktopAuthRequest(valid);
+ if (!request) throw new Error("the valid desktop request was refused");
+ const calls: unknown[] = [];
+ await startDesktopOidcSignIn(request, async (input) => { calls.push(input); return { error: null }; });
+ expect(calls).toEqual([{ providerId: "oidc", callbackURL: request.url, fetchOptions: { query: request.query } }]);
+ await expect(startDesktopOidcSignIn(request, async () => ({ error: { message: "denied" } })))
+ .rejects.toThrow("Could not start single sign-on.");
+});
diff --git a/frontend/app/desktop-auth/page.tsx b/frontend/app/desktop-auth/page.tsx
index df2c892a6..7c07cb547 100644
--- a/frontend/app/desktop-auth/page.tsx
+++ b/frontend/app/desktop-auth/page.tsx
@@ -7,7 +7,13 @@ import { Button } from "@/components/base/buttons/button";
import { useSession } from "@/lib/auth";
import { desktopAuthClient } from "@/lib/desktop-auth-client";
-import { desktopAuthRequest, restartElectronRedirect, startDesktopGoogleSignIn, type DesktopAuthRequest } from "./request";
+import {
+ desktopAuthRequest,
+ restartElectronRedirect,
+ startDesktopGoogleSignIn,
+ startDesktopOidcSignIn,
+ type DesktopAuthRequest,
+} from "./request";
export default function DesktopAuthPage() {
const { session, loading } = useSession();
@@ -49,7 +55,11 @@ export default function DesktopAuthPage() {
);
if (!loading && !session) return (
- startDesktopGoogleSignIn(request)} />
+ startDesktopGoogleSignIn(request)}
+ oidcAction={() => startDesktopOidcSignIn(request)}
+ />
);
return (
diff --git a/frontend/app/desktop-auth/request.ts b/frontend/app/desktop-auth/request.ts
index edf080f9d..6b25db582 100644
--- a/frontend/app/desktop-auth/request.ts
+++ b/frontend/app/desktop-auth/request.ts
@@ -1,3 +1,4 @@
+import { OIDC_PROVIDER_ID } from "@/lib/auth";
import { desktopAuthClient } from "@/lib/desktop-auth-client";
export type DesktopAuthRequest = {
@@ -26,6 +27,16 @@ export async function startDesktopGoogleSignIn(
if (result.error) throw new Error("Could not start Google sign-in.");
}
+/** The same hand-off through the deployment's OpenID Connect provider. */
+export async function startDesktopOidcSignIn(
+ request: DesktopAuthRequest,
+ oauth2: (input: { providerId: string; callbackURL: string; fetchOptions: { query: Record } }) => Promise<{ error: unknown }>
+ = (input) => desktopAuthClient.signIn.oauth2(input),
+): Promise {
+ const result = await oauth2({ providerId: OIDC_PROVIDER_ID, callbackURL: request.url, fetchOptions: { query: request.query } });
+ if (result.error) throw new Error("Could not start single sign-on.");
+}
+
export function restartElectronRedirect(
previous: ReturnType | null,
start: () => ReturnType = () => desktopAuthClient.ensureElectronRedirect(),
diff --git a/frontend/app/login/[[...login]]/page.tsx b/frontend/app/login/[[...login]]/page.tsx
index 722faec79..98ee61b69 100644
--- a/frontend/app/login/[[...login]]/page.tsx
+++ b/frontend/app/login/[[...login]]/page.tsx
@@ -17,14 +17,15 @@ export default async function LoginPage({
verified?: string | string[];
declined?: string | string[];
error?: string | string[];
+ via?: string | string[];
}>;
}) {
- const { redirect_url, mode, verified, declined, error } = await searchParams;
+ const { redirect_url, mode, verified, declined, error, via } = await searchParams;
return (
);
}
diff --git a/frontend/app/login/auth-form.tsx b/frontend/app/login/auth-form.tsx
index d03c7f750..77779bc4c 100644
--- a/frontend/app/login/auth-form.tsx
+++ b/frontend/app/login/auth-form.tsx
@@ -7,6 +7,7 @@ import { AuthScreen } from "@/components/auth/auth-screen";
import { CheckYourEmail, type MailStatus } from "@/components/auth/check-your-email";
import { DesktopSignIn } from "@/components/auth/desktop-sign-in";
import { GoogleSignInButton } from "@/components/auth/google-sign-in-button";
+import { OidcSignInButton } from "@/components/auth/oidc-sign-in-button";
import type { VerificationNotice } from "@/components/auth/verification-notice";
import { Button } from "@/components/base/buttons/button";
import { Divider } from "@/components/base/divider/divider";
@@ -46,6 +47,7 @@ const COPY = {
export function AuthForm({
callbackURL = "/",
googleAction,
+ oidcAction,
initialDesktopBridge,
initialAuthConfig,
initialMode = "signin",
@@ -53,6 +55,7 @@ export function AuthForm({
}: {
callbackURL?: string;
googleAction?: () => Promise;
+ oidcAction?: () => Promise;
initialDesktopBridge?: DesktopBridge | null;
/** The server's answer when already known (tests); otherwise fetched on mount. */
initialAuthConfig?: AuthConfig | null;
@@ -84,6 +87,8 @@ export function AuthForm({
const signup = authConfig?.emailPassword ? authConfig.signup : null;
const kind: AuthMode = signup && mode === "signup" ? "signup" : "signin";
const copy = COPY[kind];
+ // The identity providers this deployment offers, shown above the password form.
+ const providers = kind === "signin" && Boolean(authConfig?.google || authConfig?.oidc);
/** One attempt of either kind: the card is now waiting for mail (and what
* the server said about it), or a problem to show, or null once signed in. */
@@ -163,13 +168,16 @@ export function AuthForm({
)}
- {authConfig?.google && kind === "signin" && (
-
-
+ {providers && (
+
+ {authConfig?.oidc && (
+
+ )}
+ {authConfig?.google && }
)}
- {authConfig?.google && authConfig.emailPassword && kind === "signin" && (
+ {providers && authConfig?.emailPassword && (
@@ -266,7 +274,7 @@ export function AuthForm({
)}
- {authConfig && !authConfig.google && !authConfig.emailPassword && (
+ {authConfig && !authConfig.google && !authConfig.oidc && !authConfig.emailPassword && (
Sign-in is unavailable on this server.
diff --git a/frontend/components/auth/google-sign-in-button.tsx b/frontend/components/auth/google-sign-in-button.tsx
index 70eed4050..3d9b22167 100644
--- a/frontend/components/auth/google-sign-in-button.tsx
+++ b/frontend/components/auth/google-sign-in-button.tsx
@@ -1,9 +1,8 @@
"use client";
import { RiGoogleFill } from "@remixicon/react";
-import { useState } from "react";
import { signInWithGoogle } from "@/lib/auth";
-import { cx } from "@/utils/cx";
+import { ProviderSignInButton } from "./provider-sign-in-button";
/**
* "Continue with Google" — the primary sign-in affordance. Hands off to
@@ -21,45 +20,14 @@ export function GoogleSignInButton({
callbackURL?: string;
action?: () => Promise;
}) {
- const [pending, setPending] = useState(false);
- const [error, setError] = useState(null);
-
if (!enabled) return null;
-
- async function handleClick() {
- if (pending || disabled || !enabled) return;
- setError(null);
- setPending(true);
- try {
- await (action ? action() : signInWithGoogle(callbackURL));
- // On success the browser navigates to Google; nothing renders after.
- } catch {
- setError("Couldn't start Google sign-in. Please try again.");
- setPending(false);
- }
- }
-
return (
-
-
-
- {pending ? "Redirecting…" : "Continue with Google"}
-
- {error && (
-
- {error}
-
- )}
-
+ signInWithGoogle(callbackURL))}
+ disabled={disabled}
+ />
);
}
diff --git a/frontend/components/auth/oidc-sign-in-button.test.tsx b/frontend/components/auth/oidc-sign-in-button.test.tsx
new file mode 100644
index 000000000..15f04d6d8
--- /dev/null
+++ b/frontend/components/auth/oidc-sign-in-button.test.tsx
@@ -0,0 +1,10 @@
+import { expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import { OidcSignInButton } from "./oidc-sign-in-button";
+
+test("names the deployment's identity provider on the button", () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain("Sign in with Acme SSO");
+ expect(html).toContain('aria-label="Sign in with Acme SSO"');
+});
diff --git a/frontend/components/auth/oidc-sign-in-button.tsx b/frontend/components/auth/oidc-sign-in-button.tsx
new file mode 100644
index 000000000..ce66c9235
--- /dev/null
+++ b/frontend/components/auth/oidc-sign-in-button.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { RiShieldUserLine } from "@remixicon/react";
+import { signInWithOidc } from "@/lib/auth";
+import { ProviderSignInButton } from "./provider-sign-in-button";
+
+/**
+ * "Sign in with ": the deployment's own OpenID Connect provider (Okta,
+ * Microsoft Entra ID, Keycloak and the like), named by the backend's
+ * OIDC_BUTTON_LABEL. Hands off to better-auth's OAuth 2 flow (lib/auth.ts).
+ */
+export function OidcSignInButton({
+ label,
+ disabled = false,
+ callbackURL = "/",
+ action,
+}: {
+ label: string;
+ disabled?: boolean;
+ callbackURL?: string;
+ action?: () => Promise;
+}) {
+ return (
+ signInWithOidc(callbackURL))}
+ disabled={disabled}
+ />
+ );
+}
diff --git a/frontend/components/auth/provider-sign-in-button.tsx b/frontend/components/auth/provider-sign-in-button.tsx
new file mode 100644
index 000000000..d10c379d0
--- /dev/null
+++ b/frontend/components/auth/provider-sign-in-button.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import type { RemixiconComponentType } from "@remixicon/react";
+import { useState } from "react";
+import { cx } from "@/utils/cx";
+
+/**
+ * A full-width button that hands sign-in off to an identity provider (Google,
+ * or the deployment's own OpenID Connect provider). `start` sends the browser
+ * away; when it throws, the button says so and can be pressed again.
+ */
+export function ProviderSignInButton({
+ label,
+ icon: Icon,
+ failure,
+ start,
+ disabled = false,
+}: {
+ /** The button's text, such as "Continue with Google". */
+ label: string;
+ icon: RemixiconComponentType;
+ /** What to say when the hand-off could not start. */
+ failure: string;
+ start: () => Promise;
+ disabled?: boolean;
+}) {
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState(null);
+
+ async function handleClick() {
+ if (pending || disabled) return;
+ setError(null);
+ setPending(true);
+ try {
+ await start();
+ // On success the browser navigates to the provider; nothing renders after.
+ } catch {
+ setError(failure);
+ setPending(false);
+ }
+ }
+
+ return (
+
+
+
+ {pending ? "Redirecting…" : label}
+
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+}
diff --git a/frontend/components/auth/signup-policy.test.ts b/frontend/components/auth/signup-policy.test.ts
index 689a0a19c..56b8e389d 100644
--- a/frontend/components/auth/signup-policy.test.ts
+++ b/frontend/components/auth/signup-policy.test.ts
@@ -13,7 +13,7 @@ const router = { push() {}, replace() {}, refresh() {}, back() {}, forward() {},
const renderToStaticMarkup = (node: ReactElement) =>
renderMarkup(createElement(AppRouterContext.Provider, { value: router }, node));
-const CLOSED: AuthConfig = { google: false, emailPassword: true, allowDevOrg: false, invitationEmail: null, signup: null };
+const CLOSED: AuthConfig = { google: false, oidc: null, emailPassword: true, allowDevOrg: false, invitationEmail: null, signup: null };
const OPEN: AuthConfig = { ...CLOSED, signup: { inviteCode: true, domains: ["acme.com"] } };
const card = (config: AuthConfig, initialMode?: AuthMode) =>
renderToStaticMarkup(createElement(AuthForm, { initialDesktopBridge: null, initialAuthConfig: config, initialMode }));
@@ -85,6 +85,29 @@ describe("self-service signup UI policy", () => {
expect(plain).not.toContain("addresses can sign up");
});
+ test("the card offers each identity provider the server names, above the password form", () => {
+ const sso = card({ ...CLOSED, oidc: { label: "Acme SSO" } });
+ expect(sso).toContain("Sign in with Acme SSO");
+ expect(sso).not.toContain("Continue with Google");
+ expect(sso.indexOf("Sign in with Acme SSO")).toBeLessThan(sso.indexOf('type="password"'));
+ expect(sso).toContain(">or<");
+
+ const both = card({ ...CLOSED, google: true, oidc: { label: "Acme SSO" } });
+ expect(both).toContain("Sign in with Acme SSO");
+ expect(both).toContain("Continue with Google");
+
+ const only = card({ ...CLOSED, emailPassword: false, oidc: { label: "Acme SSO" } });
+ expect(only).toContain("Sign in with Acme SSO");
+ expect(only).not.toContain('type="password"');
+ expect(only).not.toContain(">or<");
+ expect(only).not.toContain("Sign-in is unavailable on this server.");
+
+ expect(card(CLOSED)).not.toContain("Sign in with");
+ expect(card({ ...CLOSED, emailPassword: false })).toContain("Sign-in is unavailable on this server.");
+ // The sign-up card is for a password: the providers stay on the sign-in card.
+ expect(card({ ...OPEN, oidc: { label: "Acme SSO" } }, "signup")).not.toContain("Sign in with Acme SSO");
+ });
+
test("the login page turns the confirmation landing into a notice on the card", async () => {
const confirmed = (await LoginPage({ searchParams: Promise.resolve({ verified: "1" }) })) as ReactElement<{
notice: VerificationNotice | null;
diff --git a/frontend/components/auth/verification-notice.test.ts b/frontend/components/auth/verification-notice.test.ts
index a10190d3e..608a6c27b 100644
--- a/frontend/components/auth/verification-notice.test.ts
+++ b/frontend/components/auth/verification-notice.test.ts
@@ -14,3 +14,17 @@ test("a confirmation landing is explained in plain words, problems before succes
expect(verificationNotice({ declined: "nothing" })?.text).toContain("Nothing was cancelled");
expect(verificationNotice({ error: ["a", "b"] })).toBeNull();
});
+
+test("a failed provider sign-in is explained by its code, never by echoing the query", () => {
+ expect(verificationNotice({ via: "provider", error: "Account_creation_is_disabled" })?.text).toBe(
+ "This server did not create an account for that address. Ask a workspace admin to invite it. An invitation needs an address your sign-in provider has confirmed.",
+ );
+ expect(verificationNotice({ via: "provider", error: "Sign-up_is_limited_to_@acme.com_addresses" })?.text).toContain("did not create an account");
+ expect(verificationNotice({ via: "provider", error: "That_invite_code_is_not_valid" })?.text).toContain("did not create an account");
+ expect(verificationNotice({ via: "provider", error: "account_not_linked" })?.text).toContain("Sign in with your password instead.");
+ const other = verificationNotice({ via: "provider", error: "Call_555_0100_to_restore_access" });
+ expect(other).toEqual({ tone: "problem", text: "That sign-in did not work. Please try again." });
+ // Without the marker, an error is still about a confirmation link.
+ expect(verificationNotice({ error: "Account_creation_is_disabled" })?.text).toContain("confirmation link is not valid");
+ expect(verificationNotice({ via: "provider" })).toBeNull();
+});
diff --git a/frontend/components/auth/verification-notice.ts b/frontend/components/auth/verification-notice.ts
index 0577fc02f..cc465edb0 100644
--- a/frontend/components/auth/verification-notice.ts
+++ b/frontend/components/auth/verification-notice.ts
@@ -1,19 +1,44 @@
/**
* What the login card says about a confirmation link that landed here. The
* backend sends every confirming click to `/login?verified=1`, or to
- * `/login?error=` when the link was not good.
+ * `/login?error=` when the link was not good. A Google or OpenID Connect
+ * sign-in that failed lands on `/login?via=provider&error=`
+ * (`providerErrorURL` in lib/auth.ts).
*/
export interface VerificationNotice {
readonly tone: "ok" | "problem";
readonly text: string;
}
+/** The codes better-auth sends back when the sign-up policy refused to create
+ * an account (`signupRefusal` in the backend): its message, spaces made `_`. */
+const REFUSED_ACCOUNT = /^(Account_creation_is_disabled|Sign-up_is_limited_to_|That_invite_code_is_not_valid)/;
+
+/** A failed provider sign-in, by code only: the query string is never echoed. */
+function providerNotice(error: string): VerificationNotice {
+ if (error === "account_not_linked") {
+ return {
+ tone: "problem",
+ text: "An account with that address already exists, and your sign-in provider has not confirmed the address. Sign in with your password instead.",
+ };
+ }
+ if (REFUSED_ACCOUNT.test(error)) {
+ return {
+ tone: "problem",
+ text: "This server did not create an account for that address. Ask a workspace admin to invite it. An invitation needs an address your sign-in provider has confirmed.",
+ };
+ }
+ return { tone: "problem", text: "That sign-in did not work. Please try again." };
+}
+
export function verificationNotice(params: {
verified?: string | string[];
declined?: string | string[];
error?: string | string[];
+ via?: string | string[];
}): VerificationNotice | null {
const error = typeof params.error === "string" ? params.error : null;
+ if (error && params.via === "provider") return providerNotice(error);
if (error === "signup_replaced") {
return {
tone: "problem",
diff --git a/frontend/lib/auth.test.ts b/frontend/lib/auth.test.ts
index 4d413cfdb..897b39aa6 100644
--- a/frontend/lib/auth.test.ts
+++ b/frontend/lib/auth.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test";
-import { createSessionRequest, getAuthConfig, listWorkspaces, switchOrganization } from "./auth";
+import { createSessionRequest, getAuthConfig, listWorkspaces, providerErrorURL, switchOrganization } from "./auth";
function countingFetcher(responses: (() => Response)[] = []) {
const seen: string[] = [];
@@ -64,6 +64,7 @@ test("provider config uses the dedicated route and fails closed", async () => {
seen.push(path);
return Response.json({
google: true,
+ oidc: { label: " Acme SSO " },
emailPassword: false,
allowDevOrg: false,
signup: { inviteCode: true, domains: ["acme.com", 3] },
@@ -72,6 +73,7 @@ test("provider config uses the dedicated route and fails closed", async () => {
expect(await getAuthConfig(fetcher)).toEqual({
google: true,
+ oidc: { label: "Acme SSO" },
emailPassword: false,
allowDevOrg: false,
invitationEmail: null, // the server did not say
@@ -84,6 +86,7 @@ test("provider config uses the dedicated route and fails closed", async () => {
>[0];
expect(await getAuthConfig(unavailable)).toEqual({
google: false,
+ oidc: null,
emailPassword: false,
allowDevOrg: false,
invitationEmail: null,
@@ -91,6 +94,11 @@ test("provider config uses the dedicated route and fails closed", async () => {
});
});
+test("a failed provider sign-in returns to the login card, still headed for the page asked for", () => {
+ expect(providerErrorURL("/")).toBe("/login?via=provider");
+ expect(providerErrorURL("/agent/new?desktop=1")).toBe("/login?via=provider&redirect_url=%2Fagent%2Fnew%3Fdesktop%3D1");
+});
+
test("a workspace row without an id or a name fails validation instead of becoming a blank selected workspace", async () => {
const fetcher = (async () => Response.json({ activeOrganizationId: undefined, workspaces: [{}] })) as unknown as Parameters[0];
await expect(listWorkspaces(fetcher)).rejects.toThrow("invalid response");
diff --git a/frontend/lib/auth.ts b/frontend/lib/auth.ts
index e1c3735e0..cf2c1d050 100644
--- a/frontend/lib/auth.ts
+++ b/frontend/lib/auth.ts
@@ -79,13 +79,22 @@ export function invalidateSession(): void {
for (const listener of sessionListeners) listener();
}
+/** Where a provider sign-in that failed lands: the login card, which says why
+ * (`via=provider`; better-auth appends `error`), still headed for the page
+ * the person asked for. Without it the library shows its own error page. */
+export function providerErrorURL(callbackURL: string): string {
+ const params = new URLSearchParams({ via: "provider" });
+ if (callbackURL !== "/") params.set("redirect_url", callbackURL);
+ return `/login?${params}`;
+}
+
/** Begin the Google OAuth flow: better-auth returns the provider URL to visit,
* and we hand the browser off to it. Throws if Google isn't configured. */
export async function signInWithGoogle(callbackURL = "/"): Promise {
const res = await backendFetch("/api/auth/sign-in/social", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider: "google", callbackURL }),
+ body: JSON.stringify({ provider: "google", callbackURL, errorCallbackURL: providerErrorURL(callbackURL) }),
});
if (!res.ok) throw new Error(`Google sign-in unavailable (${res.status})`);
const data = (await res.json()) as { url?: string };
@@ -93,6 +102,23 @@ export async function signInWithGoogle(callbackURL = "/"): Promise {
window.location.href = data.url;
}
+/** The provider id the backend registers for OpenID Connect sign-in. */
+export const OIDC_PROVIDER_ID = "oidc";
+
+/** Begin the OpenID Connect flow (the deployment's own identity provider), the
+ * same way: better-auth answers the provider URL. Throws if it isn't set up. */
+export async function signInWithOidc(callbackURL = "/"): Promise {
+ const res = await backendFetch("/api/auth/sign-in/oauth2", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ providerId: OIDC_PROVIDER_ID, callbackURL, errorCallbackURL: providerErrorURL(callbackURL) }),
+ });
+ if (!res.ok) throw new Error(`Single sign-on unavailable (${res.status})`);
+ const data = (await res.json()) as { url?: string };
+ if (!data.url) throw new Error("No redirect URL returned");
+ window.location.href = data.url;
+}
+
/** End the session (clears the cookie server-side). */
export async function signOut(): Promise {
const res = await backendFetch("/api/auth/sign-out", {
@@ -165,6 +191,9 @@ export async function switchOrganization(
export interface AuthConfig {
/** Google provider configured (GOOGLE_CLIENT_ID/SECRET both present). */
google: boolean;
+ /** OpenID Connect sign-in (OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET
+ * set): the name the button shows. Null when it is off. */
+ oidc: { label: string } | null;
emailPassword: boolean;
/** Unauthenticated dev-org access currently open (ALLOW_DEV_ORG). */
allowDevOrg: boolean;
@@ -178,6 +207,7 @@ export interface AuthConfig {
const FALLBACK_CONFIG: AuthConfig = {
google: false,
+ oidc: null,
emailPassword: false,
allowDevOrg: false,
invitationEmail: null,
@@ -193,8 +223,10 @@ export async function getAuthConfig(
if (!res.ok) return FALLBACK_CONFIG;
const data = (await res.json()) as Partial;
const signup = data.signup && typeof data.signup === "object" ? data.signup : null;
+ const oidcLabel = data.oidc && typeof data.oidc === "object" ? data.oidc.label : null;
return {
google: Boolean(data.google),
+ oidc: typeof oidcLabel === "string" && oidcLabel.trim() ? { label: oidcLabel.trim() } : null,
emailPassword: data.emailPassword === true,
allowDevOrg: Boolean(data.allowDevOrg),
invitationEmail: typeof data.invitationEmail === "boolean" ? data.invitationEmail : null,
diff --git a/frontend/lib/desktop-auth-client.ts b/frontend/lib/desktop-auth-client.ts
index 8e4b7146f..330bd43c0 100644
--- a/frontend/lib/desktop-auth-client.ts
+++ b/frontend/lib/desktop-auth-client.ts
@@ -1,9 +1,10 @@
import { electronProxyClient } from "@better-auth/electron/proxy";
import { createAuthClient } from "better-auth/client";
+import { genericOAuthClient } from "better-auth/client/plugins";
export const desktopAuthClient = createAuthClient({
plugins: [electronProxyClient({
protocol: { scheme: "useagent" },
callbackPath: "/auth/callback",
- })],
+ }), genericOAuthClient()],
});