Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add single sign-on over OpenID Connect, with password sign-in optional
Claude5588cb5f69b1
diff --git a/.env.example b/.env.exampleindex ab22874..d8ab9a6 100644--- a/.env.example+++ b/.env.example@@ -112,3 +112,19 @@ EMAIL_DRIVER=capture## With both set: eideasy (the default) or csc.# SIGNING_PROVIDER=++# Single sign-on with your organization's identity provider over OpenID+# Connect (Okta, Microsoft Entra ID, Google Workspace, and others). Unset,+# people sign in with a password. Register this redirect URI with the+# provider: <your site>/api/auth/callback/sso. See "Single sign-on" in+# docs/self-hosting.md.+# SSO_ISSUER=https://acme.okta.com+# SSO_CLIENT_ID=+# SSO_CLIENT_SECRET=+# What the button says after "Continue with".+# SSO_NAME=Okta+#+# off: only single sign-on, once it is set up. The listed addresses keep a+# password, for when the identity provider is down.+# PASSWORD_SIGN_IN=offdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 403719e..0d0eadf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,11 @@ release says when it does.changes and the email domain being added. It moved from the Part 11 panelto the new Sign-in security panel, and is there whether or not Part 11mode is on.+- Single sign-on over OpenID Connect (Okta, Microsoft Entra ID, Google+ Workspace and others), set up with `SSO_ISSUER`, `SSO_CLIENT_ID` and+ `SSO_CLIENT_SECRET`. New people get an account under the install's+ sign-up rule. `PASSWORD_SIGN_IN=off` then turns password sign-in off,+ except for the addresses in `PASSWORD_SIGN_IN_ALLOWED_EMAILS`.This release changes the database (`20261117090000_sign_in_security.sql`,`20261117100000_session_controls.sql`), which the production build applies.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 3295d19..6d5f9d4 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -141,6 +141,7 @@ A deployment made with the button needs no environment variables. These are ther| `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal, and long-term validation. See [Long-term validation](#long-term-validation). || `EIDEASY_CLIENT_ID`, `EIDEASY_SECRET` | Let senders ask for advanced or qualified signatures in the signers' own names, through eID Easy. See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). || `CSC_API_URL`, `CSC_CLIENT_ID`, `CSC_CLIENT_SECRET` | The same through a trust service provider's remote signing service (CSC API v2). See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). |+| `SSO_ISSUER`, `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` | Sign in through your organization's identity provider (Okta, Entra ID, Google Workspace). `PASSWORD_SIGN_IN=off` then turns passwords off. See [Single sign-on](#single-sign-on). |## Set the site up@@ -165,6 +166,28 @@ These cover the people with an account (senders and administrators). Signers who- **Wrong passwords.** Ten wrong passwords for one email address within 15 minutes stop sign-in for that address until the 15 minutes are up. This happens whether or not the address has an account, so it says nothing about which ones do. Ten wrong codes at the second step lock that step for 15 minutes in the same way.- **The site audit trail** (Settings, Organization, Sign-in security) records each sign-in and failed sign-in with the address it came from, lockouts, sign-outs, password changes and resets, two-step sign-in being turned on, off or reset, new backup codes, and changes to settings, roles, the logo, the email domain, identity confirmations and signing locks. The rows form one hash chain, so a changed or removed row shows, and the trail downloads as CSV.+### Single sign-on++People can sign in through your organization's identity provider instead of with a password, over OpenID Connect. That puts your provider's own rules in charge: its MFA, its conditional access, and removing someone there removes them here at their next sign-in. It works with any provider that publishes `/.well-known/openid-configuration`, which includes Okta, Microsoft Entra ID, Google Workspace, OneLogin, JumpCloud, Keycloak and Auth0. It is optional and set up by hand, because the provider is outside Vercel.++1. In your provider, make a web application (OIDC, authorization code flow). Give it the redirect URI `https://<your site>/api/auth/callback/sso` and the scopes `openid email profile`.+2. In the Vercel project, under Settings, Environment Variables, set:+ - `SSO_ISSUER`: the provider's issuer URL. For Okta, `https://<your org>.okta.com` (or your custom authorization server's URL). For Entra ID, `https://login.microsoftonline.com/<tenant id>/v2.0`. For Google, `https://accounts.google.com`.+ - `SSO_CLIENT_ID` and `SSO_CLIENT_SECRET`: from the application you made.+ - `SSO_NAME` (optional): what the button says after "Continue with", such as `Okta`.+3. Deploy again. The sign-in and sign-up pages show "Continue with …".++How it behaves:++- **New people** get an account the first time they sign in, under the same sign-up rule as a password sign-up (Settings, Organization, Who can sign up). So the email domain limit holds for single sign-on too. With Google this matters: any Google account can use the button, and the rule decides who gets an account. To let only your directory in, set the rule to your domains, or to nobody and add people some other way first.+- **People who already have an account** with the same email address are signed in to it, if their address here is confirmed and the provider does not say theirs is unverified. Microsoft Entra ID does not say either way, and its addresses are trusted.+- **Two-step sign-in** is not asked for after single sign-on: the provider's sign-in, with its own MFA, is the check. When an administrator requires two-step sign-in, it applies to people who have a password; someone who only uses single sign-on is not held up.+- **Turning passwords off.** With single sign-on set up, `PASSWORD_SIGN_IN=off` stops password sign-in, password sign-up and password reset links. Put one or two administrator addresses in `PASSWORD_SIGN_IN_ALLOWED_EMAILS` (comma-separated) so there is a way in if the provider is down; their sign-in page shows "Sign in with a password instead". Without single sign-on set up, `PASSWORD_SIGN_IN=off` does nothing, so nobody is locked out by a half-finished setup.+- **The site audit trail** records single sign-on sign-ins, and refused ones with the reason (for example, an address the sign-up rule turned away).+- A missing or broken setting (one of the three left out, an issuer that is not `https://`) turns single sign-on off and leaves a warning in the function logs, so password sign-in keeps working.++SAML is not supported. Okta, Entra ID and Google all offer OIDC for the same application.+## Your responsibilitiesYour install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsxindex 0f84ee3..a024f1c 100644--- a/src/app/(app)/layout.tsx+++ b/src/app/(app)/layout.tsx@@ -34,7 +34,7 @@ export default async function AuthenticatedAppLayout({// The install requires two-step sign-in and this person has not set it// up: nothing else until they have.- if (needsTwoFactorSetup(settings, session.user)) {+ if (await needsTwoFactorSetup(settings, session.user)) {redirect("/two-step-setup");}diff --git a/src/app/(auth)/login/page.tsx b/src/app/(auth)/login/page.tsxindex 95447d7..9be2062 100644--- a/src/app/(auth)/login/page.tsx+++ b/src/app/(auth)/login/page.tsx@@ -1,5 +1,6 @@import { LoginShell } from "@/components/auth/login-shell";import { redirectIfSignedIn } from "@/lib/auth/server";+import { readPasswordSignInPolicy, readSsoConfig } from "@/lib/auth/sso";type LoginPageProps = {searchParams?: Promise<{@@ -17,14 +18,24 @@ export default async function LoginPage({ searchParams }: LoginPageProps) {await redirectIfSignedIn();}+ const error = resolvedSearchParams?.error ?? null;+ const sso = readSsoConfig();+ const passwordPolicy = readPasswordSignInPolicy();+return (<LoginShell- resetError={- resolvedSearchParams?.error === "INVALID_TOKEN"- ? resolvedSearchParams.error- : null+ passwordSignIn={+ passwordPolicy.enabled+ ? "on"+ : passwordPolicy.allowedEmails.length > 0+ ? "fallback"+ : "off"}+ resetError={error === "INVALID_TOKEN" ? error : null}resetToken={resolvedSearchParams?.token ?? null}+ sso={sso ? { name: sso.name } : null}+ // Anything else is single sign-on coming back without a session.+ ssoError={error && error !== "INVALID_TOKEN" ? error.slice(0, 80) : null}/>);}diff --git a/src/app/(auth)/signup/page.tsx b/src/app/(auth)/signup/page.tsxindex 08d5d7e..cd480a6 100644--- a/src/app/(auth)/signup/page.tsx+++ b/src/app/(auth)/signup/page.tsx@@ -1,5 +1,6 @@import { SignupShell } from "@/components/auth/signup-shell";import { redirectIfSignedIn } from "@/lib/auth/server";+import { readPasswordSignInPolicy, readSsoConfig } from "@/lib/auth/sso";import { buildBranding } from "@/lib/branding";import { getSettings } from "@/lib/settings";import { describeSignupPolicy } from "@/lib/signup-policy";@@ -8,9 +9,12 @@ export default async function SignupPage() {await redirectIfSignedIn();const settings = await getSettings();+ const sso = readSsoConfig();return (<SignupShell+ passwordSignIn={readPasswordSignInPolicy().enabled}+ sso={sso ? { name: sso.name } : null}signupAvailable={buildBranding(settings).signupAvailable}// Says who can sign up before anyone fills the form in. Nothing to// say when anyone can.diff --git a/src/app/(auth)/two-step-setup/page.tsx b/src/app/(auth)/two-step-setup/page.tsxindex deb6215..2956cc3 100644--- a/src/app/(auth)/two-step-setup/page.tsx+++ b/src/app/(auth)/two-step-setup/page.tsx@@ -14,7 +14,7 @@ export default async function TwoStepSetupPage() {redirect("/login");}- if (!needsTwoFactorSetup(await getSettings(), session.user)) {+ if (!(await needsTwoFactorSetup(await getSettings(), session.user))) {redirect("/dashboard");}diff --git a/src/app/(canvas)/layout.tsx b/src/app/(canvas)/layout.tsxindex 9d3b664..d4d2341 100644--- a/src/app/(canvas)/layout.tsx+++ b/src/app/(canvas)/layout.tsx@@ -23,7 +23,7 @@ export default async function CanvasLayout({redirect("/login");}- if (needsTwoFactorSetup(await getSettings(), session.user)) {+ if (await needsTwoFactorSetup(await getSettings(), session.user)) {redirect("/two-step-setup");}diff --git a/src/components/auth/login-shell.tsx b/src/components/auth/login-shell.tsxindex 20d4e5e..14d5923 100644--- a/src/components/auth/login-shell.tsx+++ b/src/components/auth/login-shell.tsx@@ -5,6 +5,11 @@ import { useRouter } from "next/navigation";import { useState, type ChangeEvent, type FormEvent } from "react";import { useBranding } from "@/components/layout/branding-provider";+import {+ describeSsoError,+ SsoButton,+ type SsoOption,+} from "@/components/auth/sso-button";import { FieldShell, ShellButton } from "@/components/shared/form-shell";import { authClient } from "@/lib/auth/client";import { forgotPasswordSchema, loginSchema } from "@/lib/schemas/auth";@@ -39,8 +44,13 @@ type ForgotPasswordFormErrors = Partial<>;type LoginShellProps = {+ /** "on", "off", or "fallback": off, but a few addresses may still use one. */+ passwordSignIn?: "fallback" | "off" | "on";resetError?: string | null;resetToken?: string | null;+ sso?: SsoOption | null;+ /** The ?error= single sign-on came back with. */+ ssoError?: string | null;};type ForgotPasswordModel = {@@ -102,16 +112,16 @@ function normalizeAuthErrorMessage(return error?.message?.trim().toLowerCase() ?? "";}-export function LoginShell({- resetError = null,- resetToken = null,-}: LoginShellProps) {- return <LiveLoginShell resetError={resetError} resetToken={resetToken} />;+export function LoginShell(props: LoginShellProps) {+ return <LiveLoginShell {...props} />;}function LiveLoginShell({+ passwordSignIn = "on",resetError = null,resetToken = null,+ sso = null,+ ssoError = null,}: LoginShellProps) {const router = useRouter();const { signupAvailable } = useBranding();@@ -122,7 +132,14 @@ function LiveLoginShell({const [bannerMessage, setBannerMessage] = useState<string | null>(resetError === "INVALID_TOKEN"? "This reset link is invalid or has expired."- : null,+ : ssoError+ ? describeSsoError(ssoError)+ : null,+ );+ // With password sign-in off, the form is only shown on request, for the+ // few addresses that keep a password for when single sign-on is down.+ const [showPasswordForm, setShowPasswordForm] = useState(+ passwordSignIn === "on",);const [isSubmitting, setIsSubmitting] = useState(false);const [forgotPassword, setForgotPassword] = useState<ForgotPasswordModel>(@@ -228,7 +245,12 @@ function LiveLoginShell({if (result.error) {const normalizedErrorMessage = normalizeAuthErrorMessage(result.error);- if ((result.error as AuthErrorLike).code === "SIGN_IN_LOCKED") {+ const errorCode = (result.error as AuthErrorLike).code;++ if (+ errorCode === "SIGN_IN_LOCKED" ||+ errorCode === "PASSWORD_SIGN_IN_OFF"+ ) {setBannerMessage(result.error.message ??"Too many wrong passwords. Try again in 15 minutes.",@@ -386,62 +408,90 @@ function LiveLoginShell({</p>) : null}- <form className="space-y-5" noValidate onSubmit={handleSubmit}>- <FieldShell- autoComplete="email"- disabled={formLocked}- error={errors.email}- label="Email"- name="login-email"- onChange={handleChange("email")}- placeholder="[email protected]"- readOnly={formLocked}- type="email"- value={values.email}- />- <FieldShell- autoComplete="current-password"- disabled={formLocked}- error={errors.password}- label="Password"- name="login-password"- onChange={handleChange("password")}- readOnly={formLocked}- type="password"- value={values.password}+ {sso ? (+ <SsoButton+ onError={setBannerMessage}+ sso={sso}+ variant={showPasswordForm ? "secondary" : "primary"}/>- <ShellButton- className="w-full"- disabled={formLocked}- loading={isSubmitting}- type="submit"- >- {isSubmitting ? "Logging in..." : "Log in"}- </ShellButton>- {showResendVerification ? (- <ShellButton- className="w-full"- disabled={formLocked}- loading={isResendingVerification}- onClick={handleResendVerification}- type="button"- variant="secondary"- >- {isResendingVerification- ? "Sending..."- : "Resend verification email"}- </ShellButton>- ) : null}- </form>+ ) : null}- <div className="flex flex-col gap-3 border-t border-(--border) pt-5 text-sm text-(--secondary)">+ {sso && showPasswordForm ? (+ <p className="text-center text-xs font-semibold uppercase tracking-[0.12em] text-(--secondary)">+ or+ </p>+ ) : null}++ {showPasswordForm ? (+ <>+ <form className="space-y-5" noValidate onSubmit={handleSubmit}>+ <FieldShell+ autoComplete="email"+ disabled={formLocked}+ error={errors.email}+ label="Email"+ name="login-email"+ onChange={handleChange("email")}+ placeholder="[email protected]"+ readOnly={formLocked}+ type="email"+ value={values.email}+ />+ <FieldShell+ autoComplete="current-password"+ disabled={formLocked}+ error={errors.password}+ label="Password"+ name="login-password"+ onChange={handleChange("password")}+ readOnly={formLocked}+ type="password"+ value={values.password}+ />+ <ShellButton+ className="w-full"+ disabled={formLocked}+ loading={isSubmitting}+ type="submit"+ >+ {isSubmitting ? "Logging in..." : "Log in"}+ </ShellButton>+ {showResendVerification ? (+ <ShellButton+ className="w-full"+ disabled={formLocked}+ loading={isResendingVerification}+ onClick={handleResendVerification}+ type="button"+ variant="secondary"+ >+ {isResendingVerification+ ? "Sending..."+ : "Resend verification email"}+ </ShellButton>+ ) : null}+ </form>+ </>+ ) : passwordSignIn === "fallback" ? (<button- className="w-fit p-0 text-left font-bold text-(--accent-ink) underline-offset-4 hover:underline"- onClick={openForgotPasswordModal}+ className="w-fit p-0 text-left text-sm font-bold text-(--accent-ink) underline-offset-4 hover:underline"+ onClick={() => setShowPasswordForm(true)}type="button">- Forgot your password?+ Sign in with a password instead</button>+ ) : null}++ <div className="flex flex-col gap-3 border-t border-(--border) pt-5 text-sm text-(--secondary)">+ {showPasswordForm ? (+ <button+ className="w-fit p-0 text-left font-bold text-(--accent-ink) underline-offset-4 hover:underline"+ onClick={openForgotPasswordModal}+ type="button"+ >+ Forgot your password?+ </button>+ ) : null}{signupAvailable ? (<p>Don't have an account?{" "}diff --git a/src/components/auth/signup-shell.tsx b/src/components/auth/signup-shell.tsxindex cf55d26..3dc81c4 100644--- a/src/components/auth/signup-shell.tsx+++ b/src/components/auth/signup-shell.tsx@@ -8,6 +8,7 @@ import {type FormEvent,} from "react";+import { SsoButton, type SsoOption } from "@/components/auth/sso-button";import { FieldShell, ShellButton } from "@/components/shared/form-shell";import { authClient } from "@/lib/auth/client";import { signUpSchema } from "@/lib/schemas/auth";@@ -28,6 +29,10 @@ const SIGNUP_RULE_ERROR_CODES = new Set([]);type SignupShellProps = {+ /** False when password sign-in is turned off, so accounts come from SSO. */+ passwordSignIn?: boolean;+ /** Single sign-on, when the install has it (lib/auth/sso.ts). */+ sso?: SsoOption | null;/** False when this install is not taking new accounts at all. */signupAvailable?: boolean;/** One sentence on who can create an account, or null when anyone can. */@@ -74,9 +79,12 @@ type SignupFormCardProps = {onFullNameChange: ChangeEventHandler<HTMLInputElement>;onPasswordChange: ChangeEventHandler<HTMLInputElement>;onResendVerification?: () => void | Promise<void>;+ onSsoError: (message: string) => void;onSubmit: (event: FormEvent<HTMLFormElement>) => void | Promise<void>;+ passwordSignIn: boolean;showSuccess: boolean;signupRule: string | null;+ sso: SsoOption | null;successMessage: string | null;values: SignupFormValues;};@@ -91,9 +99,12 @@ function SignupFormCard({onFullNameChange,onPasswordChange,onResendVerification,+ onSsoError,onSubmit,+ passwordSignIn,showSuccess,signupRule,+ sso,successMessage,values,}: SignupFormCardProps) {@@ -119,86 +130,97 @@ function SignupFormCard({) : null}{showSuccess ? (- <div- aria-live="polite"- className="notice notice-success"- >- <p>- {successMessage ?? defaultSuccessMessage}- </p>+ <div aria-live="polite" className="notice notice-success">+ <p>{successMessage ?? defaultSuccessMessage}</p></div>) : null}- <form className="space-y-5" noValidate onSubmit={onSubmit}>- <FieldShell- autoComplete="name"- disabled={formLocked}- error={errors.fullName}- label="Full name"- name="signup-full-name"- onChange={onFullNameChange}- placeholder="Jane Smith"- readOnly={formLocked}- value={values.fullName}- />- <FieldShell- autoComplete="email"- disabled={formLocked}- error={errors.email}- label="Email"- name="signup-email"- onChange={onEmailChange}- placeholder="[email protected]"- readOnly={formLocked}- type="email"- value={values.email}- />- <FieldShell- autoComplete="new-password"- disabled={formLocked}- error={errors.password}- helper="Must be at least 15 characters"- label="Password"- name="signup-password"- onChange={onPasswordChange}- placeholder="Enter a password"- readOnly={formLocked}- type="password"- value={values.password}+ {sso ? (+ <SsoButton+ onError={onSsoError}+ sso={sso}+ variant={passwordSignIn ? "secondary" : "primary"}/>+ ) : null}- {showSuccess ? (- <div className="flex flex-col gap-3">- <ShellButton className="w-full" href="/login" variant="primary">- Go to log in- </ShellButton>- {onResendVerification ? (- <ShellButton- className="w-full"- disabled={formLocked}- loading={isResendingVerification}- onClick={onResendVerification}- type="button"- variant="secondary"- >- {isResendingVerification- ? "Sending..."- : "Resend verification email"}- </ShellButton>- ) : null}- </div>- ) : (- <ShellButton- className="w-full"+ {sso && passwordSignIn ? (+ <p className="text-center text-xs font-semibold uppercase tracking-[0.12em] text-(--secondary)">+ or+ </p>+ ) : null}++ {passwordSignIn ? (+ <form className="space-y-5" noValidate onSubmit={onSubmit}>+ <FieldShell+ autoComplete="name"+ disabled={formLocked}+ error={errors.fullName}+ label="Full name"+ name="signup-full-name"+ onChange={onFullNameChange}+ placeholder="Jane Smith"+ readOnly={formLocked}+ value={values.fullName}+ />+ <FieldShell+ autoComplete="email"disabled={formLocked}- loading={isSubmitting}- type="submit"- variant="primary"- >- {isSubmitting ? "Creating account..." : "Sign up"}- </ShellButton>- )}- </form>+ error={errors.email}+ label="Email"+ name="signup-email"+ onChange={onEmailChange}+ placeholder="[email protected]"+ readOnly={formLocked}+ type="email"+ value={values.email}+ />+ <FieldShell+ autoComplete="new-password"+ disabled={formLocked}+ error={errors.password}+ helper="Must be at least 15 characters"+ label="Password"+ name="signup-password"+ onChange={onPasswordChange}+ placeholder="Enter a password"+ readOnly={formLocked}+ type="password"+ value={values.password}+ />++ {showSuccess ? (+ <div className="flex flex-col gap-3">+ <ShellButton className="w-full" href="/login" variant="primary">+ Go to log in+ </ShellButton>+ {onResendVerification ? (+ <ShellButton+ className="w-full"+ disabled={formLocked}+ loading={isResendingVerification}+ onClick={onResendVerification}+ type="button"+ variant="secondary"+ >+ {isResendingVerification+ ? "Sending..."+ : "Resend verification email"}+ </ShellButton>+ ) : null}+ </div>+ ) : (+ <ShellButton+ className="w-full"+ disabled={formLocked}+ loading={isSubmitting}+ type="submit"+ variant="primary"+ >+ {isSubmitting ? "Creating account..." : "Sign up"}+ </ShellButton>+ )}+ </form>+ ) : null}<div className="border-t border-(--border) pt-5 text-sm text-(--secondary)">Already have an account?{" "}@@ -215,14 +237,22 @@ function SignupFormCard({}export function SignupShell({+ passwordSignIn = true,signupAvailable = true,signupRule = null,+ sso = null,}: SignupShellProps) {if (!signupAvailable) {return <SignupClosedCard />;}- return <LiveSignupShell signupRule={signupRule} />;+ return (+ <LiveSignupShell+ passwordSignIn={passwordSignIn || !sso}+ signupRule={signupRule}+ sso={sso}+ />+ );}function SignupClosedCard() {@@ -235,8 +265,8 @@ function SignupClosedCard() {Sign-up is closed</h1><p className="pt-1 text-sm leading-6 text-muted-foreground">- New accounts are not being accepted on this site. If you were sent- a document to sign, use the link in that email. You do not need an+ New accounts are not being accepted on this site. If you were sent a+ document to sign, use the link in that email. You do not need anaccount.</p></div>@@ -248,7 +278,15 @@ function SignupClosedCard() {);}-function LiveSignupShell({ signupRule }: { signupRule: string | null }) {+function LiveSignupShell({+ passwordSignIn,+ signupRule,+ sso,+}: {+ passwordSignIn: boolean;+ signupRule: string | null;+ sso: SsoOption | null;+}) {const [values, setValues] = useState<SignupFormValues>(createSignupFormValues(),);@@ -415,9 +453,12 @@ function LiveSignupShell({ signupRule }: { signupRule: string | null }) {onFullNameChange={handleChange("fullName")}onPasswordChange={handleChange("password")}onResendVerification={handleResendVerification}+ onSsoError={setBannerMessage}onSubmit={handleSubmit}+ passwordSignIn={passwordSignIn}showSuccess={showSuccess}signupRule={signupRule}+ sso={sso}successMessage={successMessage}values={values}/>diff --git a/src/components/auth/sso-button.tsx b/src/components/auth/sso-button.tsxnew file mode 100644index 0000000..a008d2a--- /dev/null+++ b/src/components/auth/sso-button.tsx@@ -0,0 +1,94 @@+"use client";++import { useState } from "react";++import { ShellButton } from "@/components/shared/form-shell";++// "Continue with <provider>": hands the visitor to the organization's+// identity provider (lib/auth/sso.ts). Better Auth sends them back to+// /api/auth/callback/sso, and from there to the dashboard, or to the sign-in+// page with ?error= when it did not work.++export type SsoOption = { name: string };++/** What the sign-in page says for an ?error= the provider callback sent. */+export function describeSsoError(code: string): string {+ switch (code) {+ case "signup_closed":+ case "signup_domain_not_allowed":+ return "That address does not have an account here, and this site's sign-up rule does not let it make one. Ask an administrator.";+ case "access_denied":+ return "Sign-in was cancelled.";+ case "email_not_found":+ return "Your identity provider did not share an email address, so you could not be signed in. Ask your IT team to include the email claim.";+ case "unable_to_link_account":+ case "email_not_verified":+ return "An account with this address already exists and its address is not confirmed yet. Sign in with your password once, or ask an administrator.";+ case "account_already_linked_to_different_user":+ return "This sign-in is already tied to a different account here. Ask an administrator.";+ default:+ return "Single sign-on did not finish. Please try again.";+ }+}++export function SsoButton({+ label,+ onError,+ sso,+ variant = "primary",+}: {+ label?: string;+ onError: (message: string) => void;+ sso: SsoOption;+ variant?: "primary" | "secondary";+}) {+ const [isBusy, setIsBusy] = useState(false);++ async function start() {+ if (isBusy) {+ return;+ }++ setIsBusy(true);++ try {+ const origin = window.location.origin;+ const response = await fetch("/api/auth/sign-in/social", {+ body: JSON.stringify({+ callbackURL: `${origin}/dashboard`,+ errorCallbackURL: `${origin}/login`,+ newUserCallbackURL: `${origin}/dashboard`,+ provider: "sso",+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const payload = (await response.json().catch(() => null)) as {+ url?: string;+ } | null;++ if (!response.ok || !payload?.url) {+ onError(describeSsoError(""));+ setIsBusy(false);+ return;+ }++ window.location.assign(payload.url);+ } catch {+ onError(describeSsoError(""));+ setIsBusy(false);+ }+ }++ return (+ <ShellButton+ className="w-full"+ loading={isBusy}+ onClick={() => void start()}+ type="button"+ variant={variant}+ >+ {label ?? `Continue with ${sso.name}`}+ </ShellButton>+ );+}diff --git a/src/lib/auth/route-session.ts b/src/lib/auth/route-session.tsindex ccdfc41..6abf16a 100644--- a/src/lib/auth/route-session.ts+++ b/src/lib/auth/route-session.ts@@ -14,7 +14,7 @@ export async function requireVerifiedSenderSession(request: Request) {}if (session.user.emailVerified === true) {- if (needsTwoFactorSetup(await getSettings(), session.user)) {+ if (await needsTwoFactorSetup(await getSettings(), session.user)) {return NextResponse.json({ error: "Set up two-step sign-in before continuing." },{ status: 403 },diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.tsindex c55811f..ea10922 100644--- a/src/lib/auth/server.ts+++ b/src/lib/auth/server.ts@@ -1,7 +1,7 @@import { APIError, betterAuth } from "better-auth";import { createAuthMiddleware } from "better-auth/api";import { nextCookies } from "better-auth/next-js";-import { haveIBeenPwned, twoFactor } from "better-auth/plugins";+import { genericOAuth, haveIBeenPwned, twoFactor } from "better-auth/plugins";import { headers } from "next/headers";import { redirect, unstable_rethrow } from "next/navigation";import { after } from "next/server";@@ -38,6 +38,12 @@ import {import { escapeHtml } from "../utils/html.ts";import { isRunningSetup } from "./setup-context.ts";import { signInEvents } from "./sign-in-events.ts";+import {+ mayUsePassword,+ readPasswordSignInPolicy,+ readSsoConfig,+ SSO_PROVIDER_ID,+} from "./sso.ts";import { recordSystemAuditEvent } from "../services/system-audit.ts";type CreateAppAuthOptions = {@@ -251,6 +257,15 @@ function isPasswordBreachCheckEnabled(env: EnvSource): boolean {);}+// Where a password is used or handed out. A reset link is only sent where+// a password may be used, so turning password sign-in off cannot be undone+// with "Forgot your password?".+const PASSWORD_PATHS = new Set([+ "/request-password-reset",+ "/sign-in/email",+ "/sign-up/email",+]);+export function createAppAuth({database = getDb(),env = process.env,@@ -274,7 +289,40 @@ export function createAppAuth({return cachedEmailService;};+ const sso = readSsoConfig(env);+ const passwordPolicy = readPasswordSignInPolicy(env);const plugins = [+ // Single sign-on with the organization's identity provider (sso.ts).+ // Its sign-ins do not ask for this app's second step: the provider's+ // own sign-in, with its own MFA, is the check.+ ...(sso+ ? [+ genericOAuth({+ config: [+ {+ clientId: sso.clientId,+ clientSecret: sso.clientSecret,+ discoveryUrl: sso.discoveryUrl,+ // A provider whose discovery cannot vouch for its ID tokens+ // is left out rather than trusted unchecked.+ requireIdTokenVerification: true,+ // Microsoft Entra ID leaves email_verified out of its+ // tokens. The organization's own directory is trusted for+ // its addresses unless it says one is not verified.+ mapProfileToUser: (profile) => ({+ emailVerified:+ profile.email_verified !== false &&+ profile.email_verified !== "false",+ }),+ name: sso.name,+ pkce: true,+ providerId: SSO_PROVIDER_ID,+ scopes: ["openid", "email", "profile"],+ },+ ],+ }),+ ]+ : []),...(isPasswordBreachCheckEnabled(env)? [haveIBeenPwned({@@ -399,7 +447,7 @@ export function createAppAuth({// address's domain and is printed on the sign-up page, so saying it// here gives nothing away.before: createAuthMiddleware(async (ctx) => {- if (ctx.path !== "/sign-up/email" || isRunningSetup()) {+ if (isRunningSetup()) {return;}@@ -411,6 +459,24 @@ export function createAppAuth({typeof body.email === "string"? body.email: "";++ // With password sign-in turned off, only the addresses kept for+ // when the identity provider is down may use one (sso.ts).+ if (+ sso &&+ PASSWORD_PATHS.has(ctx.path ?? "") &&+ !mayUsePassword(passwordPolicy, email)+ ) {+ throw new APIError("FORBIDDEN", {+ code: "PASSWORD_SIGN_IN_OFF",+ message: `Password sign-in is turned off here. Continue with ${sso.name} instead.`,+ });+ }++ if (ctx.path !== "/sign-up/email") {+ return;+ }+const decision = await evaluateSignupRequest(email, env);if (!decision.allowed) {diff --git a/src/lib/auth/sign-in-events.ts b/src/lib/auth/sign-in-events.tsindex d729fbb..a9d2216 100644--- a/src/lib/auth/sign-in-events.ts+++ b/src/lib/auth/sign-in-events.ts@@ -218,6 +218,7 @@ export function signInEvents() {after: [{matcher: (ctx) =>+ isProviderCallback(ctx.path) ||ctx.path === "/sign-in/email" ||ctx.path === "/change-password" ||SECOND_STEP_PATHS.has(ctx.path ?? "") ||@@ -232,6 +233,11 @@ export function signInEvents() {return;}+ if (isProviderCallback(path)) {+ await afterProviderSignIn(ctx, returned);+ return;+ }+if (SECOND_STEP_PATHS.has(path)) {await afterSecondStep(ctx, returned, failed);return;@@ -346,6 +352,60 @@ async function afterPasswordSignIn(}}+/** The identity provider sending someone back (auth/sso.ts). */+function isProviderCallback(path: string | undefined): boolean {+ return path === "/callback/:id" || (path?.startsWith("/callback/") ?? false);+}++/**+ * The callback ends in a redirect either way: on to the app with a new+ * session, or back to the sign-in page with ?error= saying why not.+ */+async function afterProviderSignIn(ctx: HookContext, returned: unknown) {+ const session = ctx.context.newSession;+ const provider =+ typeof ctx.params?.id === "string" ? ctx.params.id : "unknown";++ if (session) {+ await record(ctx, {+ actorEmail: session.user.email,+ actorUserId: session.user.id,+ event: "sign_in_succeeded",+ metadata: { method: "sso", provider },+ targetUserId: session.user.id,+ });+ return;+ }++ const location =+ isAPIError(returned) && returned.headers instanceof Headers+ ? returned.headers.get("location")+ : null;+ let reason: string | null = null;++ try {+ reason = location+ ? new URL(location, "http://local").searchParams.get("error")+ : null;+ } catch {+ reason = null;+ }++ // A redirect with no error is the hand-over to the provider, or a POST+ // turned into a GET: nothing happened yet.+ if (!reason) {+ return;+ }++ await record(ctx, {+ actorEmail: null,+ actorUserId: null,+ event: "sign_in_failed",+ metadata: { method: "sso", provider, reason },+ targetUserId: null,+ });+}+function hasSessionToken(returned: unknown): boolean {return (typeof returned === "object" &&diff --git a/src/lib/auth/sso.dbtest.ts b/src/lib/auth/sso.dbtest.tsnew file mode 100644index 0000000..3d6588c--- /dev/null+++ b/src/lib/auth/sso.dbtest.ts@@ -0,0 +1,543 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { registerHooks } from "node:module";+import { after, before, beforeEach, test } from "node:test";++import { exportJWK, generateKeyPair, SignJWT, type JWK } from "jose";+import type pg from "pg";++import type { createAppAuth as CreateAppAuth } from "./server.ts";+import { replaceDbPoolForTests } from "../db/connection.ts";+import { openTestDatabase } from "../db/test-database.ts";+import { clearRateLimitStoreForTests } from "../security/rate-limit.ts";+import { listSystemAuditEvents } from "../services/system-audit.ts";+import { invalidateSettingsCache, saveSettings } from "../settings.ts";+import { needsTwoFactorSetup } from "../sign-in-security.ts";++// Single sign-on against a real Postgres, the real Better Auth endpoints and+// a small OpenID Connect provider run here: discovery, signed ID tokens and+// nonce checks are all the real thing. Run with `npm run test:db`.++const BASE_URL = "http://localhost:3998";+const CLIENT_ID = "signudoc-test";+const PASSWORD = "a long enough passphrase";++registerHooks({+ resolve(specifier, context, nextResolve) {+ if (/^next\/[a-z-]+$/.test(specifier)) {+ return nextResolve(`${specifier}.js`, context);+ }++ return nextResolve(specifier, context);+ },+});++type Profile = {+ email?: string;+ email_verified?: boolean;+ name: string;+ sub: string;+};++let database: pg.Pool;+let replaced: pg.Pool | null = null;+let provider: Server;+let issuer = "";+let privateKey: CryptoKey;+let publicJwk: JWK;+let nextProfile: Profile;+const codes = new Map<string, { nonce: string | null; profile: Profile }>();++async function signIdToken(profile: Profile, nonce: string | null) {+ return new SignJWT({ ...profile, ...(nonce ? { nonce } : {}) })+ .setProtectedHeader({ alg: "RS256", kid: "test" })+ .setIssuer(issuer)+ .setAudience(CLIENT_ID)+ .setIssuedAt()+ .setExpirationTime("5m")+ .sign(privateKey);+}++function startProvider(): Promise<void> {+ provider = createServer((request, response) => {+ const url = new URL(request.url ?? "/", issuer || "http://127.0.0.1");+ const json = (body: unknown) => {+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify(body));+ };++ if (url.pathname === "/.well-known/openid-configuration") {+ json({+ authorization_endpoint: `${issuer}/authorize`,+ id_token_signing_alg_values_supported: ["RS256"],+ issuer,+ jwks_uri: `${issuer}/jwks`,+ response_types_supported: ["code"],+ subject_types_supported: ["public"],+ token_endpoint: `${issuer}/token`,+ userinfo_endpoint: `${issuer}/userinfo`,+ });+ return;+ }++ if (url.pathname === "/jwks") {+ json({ keys: [{ ...publicJwk, alg: "RS256", kid: "test", use: "sig" }] });+ return;+ }++ if (url.pathname === "/token") {+ let body = "";++ request.on("data", (chunk: Buffer) => {+ body += chunk.toString();+ });+ request.on("end", () => {+ const code = new URLSearchParams(body).get("code") ?? "";+ const pending = codes.get(code);++ if (!pending) {+ response.writeHead(400, { "content-type": "application/json" });+ response.end(JSON.stringify({ error: "invalid_grant" }));+ return;+ }++ void signIdToken(pending.profile, pending.nonce).then((idToken) => {+ json({+ access_token: `access-${code}`,+ expires_in: 300,+ id_token: idToken,+ token_type: "Bearer",+ });+ });+ });+ return;+ }++ if (url.pathname === "/userinfo") {+ const code = (request.headers.authorization ?? "").replace(+ /^Bearer access-/,+ "",+ );+ const pending = codes.get(code);++ json(pending?.profile ?? {});+ return;+ }++ response.writeHead(404);+ response.end();+ });++ return new Promise((resolve) => {+ provider.listen(0, "127.0.0.1", () => {+ const { port } = provider.address() as AddressInfo;++ issuer = `http://127.0.0.1:${String(port)}`;+ resolve();+ });+ });+}++type Cookies = Map<string, string>;++function cookieHeader(cookies: Cookies): string {+ return [...cookies].map(([name, value]) => `${name}=${value}`).join("; ");+}++function absorbCookies(response: Response, cookies: Cookies) {+ for (const line of response.headers.getSetCookie()) {+ const [pair] = line.split(";");+ const index = pair?.indexOf("=") ?? -1;++ if (!pair || index < 0) {+ continue;+ }++ const name = pair.slice(0, index).trim();+ const value = pair.slice(index + 1).trim();++ if (value === "" || /max-age=0/i.test(line)) {+ cookies.delete(name);+ } else {+ cookies.set(name, value);+ }+ }+}++function makeAuth(extraEnv: Record<string, string> = {}) {+ return import("./server.ts").then(({ createAppAuth }) =>+ createAppAuth({+ database,+ env: {+ APP_URL: BASE_URL,+ BETTER_AUTH_SECRET:+ "test-secret-that-is-long-enough-for-better-auth-0123",+ BETTER_AUTH_URL: BASE_URL,+ EMAIL_DRIVER: "capture",+ NODE_ENV: "test",+ SSO_CLIENT_ID: CLIENT_ID,+ SSO_CLIENT_SECRET: "client-secret",+ SSO_ISSUER: issuer,+ SSO_NAME: "Acme Okta",+ ...extraEnv,+ },+ includeNextCookies: false,+ }),+ );+}++async function post(+ auth: ReturnType<typeof CreateAppAuth>,+ path: string,+ body: unknown,+ cookies: Cookies = new Map(),+) {+ const response = await auth.handler(+ new Request(`${BASE_URL}/api/auth${path}`, {+ body: JSON.stringify(body),+ headers: {+ "content-type": "application/json",+ cookie: cookieHeader(cookies),+ origin: BASE_URL,+ "x-forwarded-for": "203.0.113.9",+ },+ method: "POST",+ }),+ );++ absorbCookies(response, cookies);++ return {+ payload: (await response.json().catch(() => null)) as Record<+ string,+ unknown+ > | null,+ status: response.status,+ };+}++/**+ * The whole round trip: ask for the provider's sign-in page, have the+ * provider "sign in" `profile`, and follow the callback. Returns where the+ * callback sent the browser, and its cookies.+ */+async function signInWithSso(+ auth: ReturnType<typeof CreateAppAuth>,+ profile: Profile,+) {+ const cookies: Cookies = new Map();+ const started = await post(+ auth,+ "/sign-in/social",+ {+ callbackURL: `${BASE_URL}/dashboard`,+ errorCallbackURL: `${BASE_URL}/login`,+ provider: "sso",+ },+ cookies,+ );++ assert.equal(started.status, 200, JSON.stringify(started.payload));++ const authorizeUrl = new URL(String(started.payload?.url));++ assert.equal(authorizeUrl.origin, issuer);+ assert.ok(authorizeUrl.searchParams.get("code_challenge"), "PKCE is used");++ const code = randomUUID();++ nextProfile = profile;+ codes.set(code, {+ nonce: authorizeUrl.searchParams.get("nonce"),+ profile: nextProfile,+ });++ const callback = await auth.handler(+ new Request(+ `${BASE_URL}/api/auth/callback/sso?code=${code}&state=${encodeURIComponent(authorizeUrl.searchParams.get("state") ?? "")}`,+ {+ headers: {+ cookie: cookieHeader(cookies),+ "x-forwarded-for": "203.0.113.9",+ },+ method: "GET",+ },+ ),+ );++ absorbCookies(callback, cookies);++ return {+ cookies,+ location: new URL(callback.headers.get("location") ?? "", BASE_URL),+ };+}++async function sessionUser(+ auth: ReturnType<typeof CreateAppAuth>,+ cookies: Cookies,+) {+ const session = await auth.api.getSession({+ headers: new Headers({ cookie: cookieHeader(cookies) }),+ });++ return session?.user ?? null;+}++before(async () => {+ const keys = await generateKeyPair("RS256");++ privateKey = keys.privateKey;+ publicJwk = await exportJWK(keys.publicKey);+ await startProvider();+ database = await openTestDatabase();+ replaced = replaceDbPoolForTests(database);+});++beforeEach(async () => {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.system_audit_events");+ await database.query("delete from public.app_settings");+ await database.query("delete from public.rate_limits");+ await database.query("delete from public.verification");+ clearRateLimitStoreForTests();+ invalidateSettingsCache();+ await saveSettings({ signupMode: "open" }, database);+ // An install that has been set up has an administrator.+ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Owner', '[email protected]', true, 'admin')`,+ [randomUUID()],+ );+});++after(async () => {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.system_audit_events");+ await database.query("delete from public.app_settings");+ replaceDbPoolForTests(replaced ?? database);+ await database.end();+ provider.close();+});++test("a first sign-in through the identity provider makes a verified account and is audited", async () => {+ const auth = await makeAuth();+ const { cookies, location } = await signInWithSso(auth, {+ email: "[email protected]",+ name: "Pat Person",+ sub: "okta-pat",+ });++ assert.equal(location.pathname, "/dashboard");++ const user = await sessionUser(auth, cookies);++ assert.equal(user?.email, "[email protected]");+ // Entra ID leaves email_verified out; the organization's directory is+ // trusted for its own addresses.+ assert.equal(user?.emailVerified, true);++ const events = await listSystemAuditEvents({ limit: 100 }, database);+ const signedIn = events.find((event) => event.event === "sign_in_succeeded");++ assert.equal(signedIn?.actorUserId, user?.id);+ assert.deepEqual(signedIn?.metadata, { method: "sso", provider: "sso" });+});++test("someone with a password account is signed in to it, not given a second one", async () => {+ const auth = await makeAuth();+ const context = await auth.$context;+ const id = randomUUID();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Pat', '[email protected]', true, 'admin')`,+ [id],+ );+ await database.query(+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, $2, 'credential', $2, $3)`,+ [randomUUID(), id, await context.password.hash(PASSWORD)],+ );++ const { cookies, location } = await signInWithSso(auth, {+ email: "[email protected]",+ email_verified: true,+ name: "Pat",+ sub: "okta-pat",+ });++ assert.equal(location.pathname, "/dashboard");+ assert.equal((await sessionUser(auth, cookies))?.id, id);++ const { rows } = await database.query<{ count: string }>(+ `select count(*)::text as count from "user" where email = '[email protected]'`,+ );++ assert.equal(rows[0]?.count, "1");+});++test("the sign-up rule holds for single sign-on too", async () => {+ await saveSettings(+ { allowedEmailDomains: ["acme.com"], signupMode: "domains" },+ database,+ );+ invalidateSettingsCache();++ const auth = await makeAuth();+ const refused = await signInWithSso(auth, {+ email: "[email protected]",+ name: "Pat",+ sub: "google-pat",+ });++ assert.equal(refused.location.pathname, "/login");+ assert.equal(+ refused.location.searchParams.get("error"),+ "signup_domain_not_allowed",+ );+ assert.equal(await sessionUser(auth, refused.cookies), null);++ const failed = (await listSystemAuditEvents({ limit: 100 }, database)).find(+ (event) => event.event === "sign_in_failed",+ );++ assert.deepEqual(failed?.metadata, {+ method: "sso",+ provider: "sso",+ reason: "signup_domain_not_allowed",+ });++ const allowed = await signInWithSso(auth, {+ email: "[email protected]",+ name: "Sam",+ sub: "google-sam",+ });++ assert.equal(allowed.location.pathname, "/dashboard");+});++test("an address the provider says is unverified is not tied to an existing account", async () => {+ const auth = await makeAuth();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Pat', '[email protected]', true, 'user')`,+ [randomUUID()],+ );++ const { cookies, location } = await signInWithSso(auth, {+ email: "[email protected]",+ email_verified: false,+ name: "Pat",+ sub: "okta-intruder",+ });++ assert.equal(location.pathname, "/login");+ assert.ok(location.searchParams.get("error"));+ assert.equal(await sessionUser(auth, cookies), null);+});++test("with password sign-in off, only the listed addresses may use a password", async () => {+ const auth = await makeAuth({+ PASSWORD_SIGN_IN: "off",+ PASSWORD_SIGN_IN_ALLOWED_EMAILS: "[email protected]",+ });+ const context = await auth.$context;++ for (const email of ["[email protected]", "[email protected]"]) {+ const id = randomUUID();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Someone', $2, true, 'user') on conflict do nothing`,+ [id, email],+ );+ await database.query(+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, $2, 'credential', $2, $3)`,+ [randomUUID(), id, await context.password.hash(PASSWORD)],+ );+ }++ const refused = await post(auth, "/sign-in/email", {+ email: "[email protected]",+ password: PASSWORD,+ });++ assert.equal(refused.status, 403);+ assert.equal(refused.payload?.code, "PASSWORD_SIGN_IN_OFF");++ const reset = await post(auth, "/request-password-reset", {+ email: "[email protected]",+ redirectTo: `${BASE_URL}/login`,+ });++ assert.equal(reset.status, 403);++ const signUp = await post(auth, "/sign-up/email", {+ email: "[email protected]",+ name: "New",+ password: PASSWORD,+ });++ assert.equal(signUp.status, 403);++ const breakGlass = await post(auth, "/sign-in/email", {+ email: "[email protected]",+ password: PASSWORD,+ });++ assert.equal(breakGlass.status, 200);+});++test("PASSWORD_SIGN_IN=off does nothing without single sign-on set up", async () => {+ const auth = await makeAuth({+ PASSWORD_SIGN_IN: "off",+ SSO_CLIENT_ID: "",+ SSO_CLIENT_SECRET: "",+ SSO_ISSUER: "",+ });+ const context = await auth.$context;+ const id = randomUUID();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Pat', '[email protected]', true, 'user')`,+ [id],+ );+ await database.query(+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, $2, 'credential', $2, $3)`,+ [randomUUID(), id, await context.password.hash(PASSWORD)],+ );++ const result = await post(auth, "/sign-in/email", {+ email: "[email protected]",+ password: PASSWORD,+ });++ assert.equal(result.status, 200);+});++test("requiring two-step sign-in does not hold up someone who only uses single sign-on", async () => {+ const auth = await makeAuth();+ const { cookies } = await signInWithSso(auth, {+ email: "[email protected]",+ name: "Pat",+ sub: "okta-pat",+ });+ const user = await sessionUser(auth, cookies);++ assert.ok(user);+ assert.equal(+ await needsTwoFactorSetup({ requireTwoFactor: true }, user, { database }),+ false,+ );++ // Someone with a password still has to set it up.+ const context = await auth.$context;++ await database.query(+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, $2, 'credential', $2, $3)`,+ [randomUUID(), user.id, await context.password.hash(PASSWORD)],+ );+ assert.equal(+ await needsTwoFactorSetup({ requireTwoFactor: true }, user, { database }),+ true,+ );+});diff --git a/src/lib/auth/sso.test.ts b/src/lib/auth/sso.test.tsnew file mode 100644index 0000000..51698c1--- /dev/null+++ b/src/lib/auth/sso.test.ts@@ -0,0 +1,65 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ mayUsePassword,+ readPasswordSignInPolicy,+ readSsoConfig,+} from "./sso.ts";++const sso = {+ SSO_CLIENT_ID: "client",+ SSO_CLIENT_SECRET: "secret",+ SSO_ISSUER: "https://acme.okta.com/",+};++test("single sign-on is off unless all three settings are given", () => {+ assert.equal(readSsoConfig({}), null);+ assert.equal(readSsoConfig({ ...sso, SSO_CLIENT_SECRET: "" }), null);+ assert.equal(+ readSsoConfig({ ...sso, SSO_ISSUER: "http://acme.okta.com" }),+ null,+ );+ assert.equal(readSsoConfig({ ...sso, SSO_ISSUER: "not a url" }), null);+});++test("the issuer may be given with its discovery path or a trailing slash", () => {+ for (const issuer of [+ "https://acme.okta.com",+ "https://acme.okta.com/",+ "https://acme.okta.com/.well-known/openid-configuration",+ ]) {+ const config = readSsoConfig({ ...sso, SSO_ISSUER: issuer });++ assert.equal(config?.issuer, "https://acme.okta.com");+ assert.equal(+ config?.discoveryUrl,+ "https://acme.okta.com/.well-known/openid-configuration",+ );+ }++ assert.equal(readSsoConfig(sso)?.name, "single sign-on");+ assert.equal(readSsoConfig({ ...sso, SSO_NAME: "Okta" })?.name, "Okta");+});++test("password sign-in can only be turned off while single sign-on is set up", () => {+ assert.equal(+ readPasswordSignInPolicy({ PASSWORD_SIGN_IN: "off" }).enabled,+ true,+ );++ const policy = readPasswordSignInPolicy({+ ...sso,+ PASSWORD_SIGN_IN: "OFF",+ PASSWORD_SIGN_IN_ALLOWED_EMAILS: " [email protected] , [email protected],",+ });++ assert.equal(policy.enabled, false);+ assert.deepEqual(policy.allowedEmails, ["[email protected]", "[email protected]"]);+ assert.equal(mayUsePassword(policy, "[email protected] "), true);+ assert.equal(mayUsePassword(policy, "[email protected]"), false);+ assert.equal(+ mayUsePassword(readPasswordSignInPolicy(sso), "[email protected]"),+ true,+ );+});diff --git a/src/lib/auth/sso.ts b/src/lib/auth/sso.tsnew file mode 100644index 0000000..cd33155--- /dev/null+++ b/src/lib/auth/sso.ts@@ -0,0 +1,135 @@+import { readEnv, type EnvSource } from "../utils/env.ts";++// Single sign-on with the organization's own identity provider, over OpenID+// Connect: Okta, Microsoft Entra ID, Google Workspace, or any other provider+// that publishes /.well-known/openid-configuration. It is off unless the+// deployer sets all three of SSO_ISSUER, SSO_CLIENT_ID and SSO_CLIENT_SECRET.+//+// People who sign in this way for the first time get an account under the+// install's sign-up rule (Settings, Organization), the same as a sign-up with+// a password, so the email domain limit holds for both. Someone who already+// has an account with that email address is signed in to it.+//+// PASSWORD_SIGN_IN=off then turns password sign-in off, so the identity+// provider decides who gets in, and its own rules (MFA, offboarding) apply.+// The addresses in PASSWORD_SIGN_IN_ALLOWED_EMAILS keep their password, as a+// way in for an administrator when the provider is down.++/** The provider id in Better Auth: its routes end in /oauth2/callback/sso. */+export const SSO_PROVIDER_ID = "sso";++export type SsoConfig = {+ clientId: string;+ clientSecret: string;+ /** The provider's discovery document. */+ discoveryUrl: string;+ issuer: string;+ /** What the button says after "Continue with". */+ name: string;+};++export type PasswordSignInPolicy = {+ /** Lowercased addresses that may still use a password when it is off. */+ allowedEmails: string[];+ enabled: boolean;+};++function normalizeIssuer(value: string): string | null {+ let url: URL;++ try {+ url = new URL(value);+ } catch {+ return null;+ }++ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";++ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) {+ return null;+ }++ // The issuer may be given with its discovery path, or with a trailing slash.+ return url+ .toString()+ .replace(/\/\.well-known\/openid-configuration\/?$/, "")+ .replace(/\/+$/, "");+}++/**+ * The install's single sign-on settings, or null when it is not set up.+ * A partial or broken setting is reported once and treated as not set up,+ * so a typo cannot stop password sign-in from working.+ */+export function readSsoConfig(env: EnvSource = process.env): SsoConfig | null {+ const rawIssuer = readEnv(env, "SSO_ISSUER");+ const clientId = readEnv(env, "SSO_CLIENT_ID");+ const clientSecret = readEnv(env, "SSO_CLIENT_SECRET");++ if (!rawIssuer && !clientId && !clientSecret) {+ return null;+ }++ if (!rawIssuer || !clientId || !clientSecret) {+ warnOnce(+ "SSO is turned off: set all three of SSO_ISSUER, SSO_CLIENT_ID and SSO_CLIENT_SECRET.",+ );+ return null;+ }++ const issuer = normalizeIssuer(rawIssuer);++ if (!issuer) {+ warnOnce("SSO is turned off: SSO_ISSUER must be an https:// URL.");+ return null;+ }++ return {+ clientId,+ clientSecret,+ discoveryUrl: `${issuer}/.well-known/openid-configuration`,+ issuer,+ name: readEnv(env, "SSO_NAME") ?? "single sign-on",+ };+}++/**+ * Whether password sign-in is on. It can only be turned off while single+ * sign-on is set up, so nobody can be left with no way in at all.+ */+export function readPasswordSignInPolicy(+ env: EnvSource = process.env,+): PasswordSignInPolicy {+ const off =+ readEnv(env, "PASSWORD_SIGN_IN")?.toLowerCase() === "off" &&+ readSsoConfig(env) !== null;++ return {+ allowedEmails: off+ ? (readEnv(env, "PASSWORD_SIGN_IN_ALLOWED_EMAILS") ?? "")+ .split(",")+ .map((email) => email.trim().toLowerCase())+ .filter(Boolean)+ : [],+ enabled: !off,+ };+}++/** Whether this address may sign in, sign up or reset with a password. */+export function mayUsePassword(+ policy: PasswordSignInPolicy,+ email: string,+): boolean {+ return (+ policy.enabled || policy.allowedEmails.includes(email.trim().toLowerCase())+ );+}++const warned = new Set<string>();++function warnOnce(message: string) {+ if (!warned.has(message)) {+ warned.add(message);+ console.warn(`[auth] ${message}`);+ }+}diff --git a/src/lib/sign-in-security.ts b/src/lib/sign-in-security.tsindex 712b379..fbd425b 100644--- a/src/lib/sign-in-security.ts+++ b/src/lib/sign-in-security.ts@@ -106,12 +106,33 @@ export async function clearFailedSignIns(* Whether this person must set up two-step sign-in before using the app.* `twoFactorEnabled` comes from the session, which is at most a few minutes* old; the setup itself replaces the session, so it is current right after.+ *+ * It applies to password sign-in. Someone with no password, who only signs+ * in through the organization's identity provider (auth/sso.ts), has the+ * provider's own MFA as their second step, and could not set one up here.*/-export function needsTwoFactorSetup(+export async function needsTwoFactorSetup(settings: { requireTwoFactor: boolean },user: object,-): boolean {- return settings.requireTwoFactor && !usesTwoFactor(user);+ options: { database?: DbExecutor } = {},+): Promise<boolean> {+ if (!settings.requireTwoFactor || usesTwoFactor(user)) {+ return false;+ }++ const userId = "id" in user && typeof user.id === "string" ? user.id : null;++ if (!userId) {+ return true;+ }++ const password = await queryOne<{ found: number }>(+ options.database ?? getDb(),+ `SELECT 1 AS found FROM account WHERE "userId" = $1 AND "providerId" = 'credential' LIMIT 1`,+ [userId],+ );++ return password !== null;}/**@@ -172,7 +193,15 @@ export async function setTwoFactorRequirement(return;}- if (required && !actorRow.twoFactorEnabled) {+ if (+ required &&+ !actorRow.twoFactorEnabled &&+ (await needsTwoFactorSetup(+ { requireTwoFactor: true },+ { id: actor.userId },+ { database: tx },+ ))+ ) {throw new SignInSecurityError("Set up two-step sign-in for your own account first, under Settings, Two-step sign-in.",409,