Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 5 additions & 4 deletions backend/src/auth-invitations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<boolean> {
if (selfSignupEnabled() || googleAuthEnabled()) return true;
if (selfSignupEnabled() || providerSignInEnabled()) return true;
const [known] = await db
.select({ id: user.id })
.from(user)
Expand Down
68 changes: 57 additions & 11 deletions backend/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -20,6 +20,8 @@ import {
betterAuthTrustedOrigins,
env,
googleAuthConfig,
OIDC_PROVIDER_ID,
oidcAuthConfig,
openSignupConfig,
selfSignupEnabled,
signupRefusal,
Expand All @@ -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, unknown>): 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) {
Expand Down Expand Up @@ -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: {
Expand All @@ -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
Expand Down Expand Up @@ -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) => {
Expand Down
6 changes: 5 additions & 1 deletion backend/src/auth/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -33,8 +33,12 @@ async function redactSessionTokens(response: Response): Promise<Response> {
const routes = new Hono<AppEnv>();
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(),
Expand Down
67 changes: 67 additions & 0 deletions backend/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <label>").
*
* The endpoints come from the issuer's discovery document
* (`<OIDC_ISSUER>/.well-known/openid-configuration`). The redirect URI the
* provider must allow is `<BETTER_AUTH_URL>/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<string, string | undefined> = 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
Expand Down
11 changes: 6 additions & 5 deletions backend/src/slack/access-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -582,12 +582,13 @@ async function provenIdentity(tx: Executor, row: Request): Promise<string | null
return null; // lost every turn to creations landing in between; the admin can decide again
}

/** Best effort, and only when the web has a way for them in: a Google sign-in
* with this address links the account. Self sign-up cannot, the address is
* taken. The person can already work from Slack either way. */
/** Best effort, and only when the web has a way for them in: a Google or
* OpenID Connect sign-in with this address links the account. Self sign-up
* cannot, the address is taken. The person can already work from Slack
* either way. */
async function welcome(orgId: string, requestId: string): Promise<void> {
const config = invitationMailConfig();
if (!config || !googleAuthEnabled()) return;
if (!config || !providerSignInEnabled()) return;
const [row] = await db
.select({ email: slackAccessRequests.email, userId: slackUsers.userId })
.from(slackAccessRequests)
Expand Down
Loading
Loading