Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

fix(settings): explain identity-provider two-step sign-in for SSO-only accounts (#243)

Kevin Rose45d5dc057c54
diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx
index 4235966..4ea6a78 100644
--- a/src/app/(app)/settings/page.tsx
+++ b/src/app/(app)/settings/page.tsx
@@ -4,22 +4,26 @@ import { UpdatesPanel } from "@/components/settings/updates-panel";
import { isAdminUser } from "@/lib/auth/admin";
import { accountClosureBlock } from "@/lib/account";
import { getAuthSession } from "@/lib/auth/server";
+import { readSsoConfig } from "@/lib/auth/sso";
import { toOrganizationSettingsView } from "@/lib/organization-settings";
import {
getSettings,
readStoredSettings,
resolveSettings,
} from "@/lib/settings";
-import { usesTwoFactor } from "@/lib/sign-in-security";
+import { userHasPassword, usesTwoFactor } from "@/lib/sign-in-security";
import { getUpdateStatus } from "@/lib/software-update";
export default async function SettingsPage() {
const session = await getAuthSession();
- const isAdmin = session ? await isAdminUser(session.user.id) : false;
- const settings = await getSettings();
- const closureBlockedReason = session
- ? await accountClosureBlock(session.user).catch(() => null)
- : null;
+ const [isAdmin, settings, closureBlockedReason, hasPassword] =
+ await Promise.all([
+ session ? isAdminUser(session.user.id) : false,
+ getSettings(),
+ session ? accountClosureBlock(session.user).catch(() => null) : null,
+ session ? userHasPassword(session.user.id) : false,
+ ]);
+ const sso = readSsoConfig();
return (
<div className="space-y-8">
@@ -31,7 +35,9 @@ export default async function SettingsPage() {
}}
twoFactor={{
enabled: session ? usesTwoFactor(session.user) : false,
+ hasPassword,
required: settings.requireTwoFactor,
+ ssoProviderName: sso?.name ?? null,
}}
/>
{isAdmin ? (
diff --git a/src/components/auth/two-step-setup-required.tsx b/src/components/auth/two-step-setup-required.tsx
index ef8987d..24010bf 100644
--- a/src/components/auth/two-step-setup-required.tsx
+++ b/src/components/auth/two-step-setup-required.tsx
@@ -38,7 +38,7 @@ export function TwoStepSetupRequired({ email }: { email: string }) {
</p>
</section>
- <TwoFactorPanel enabled={false} required />
+ <TwoFactorPanel enabled={false} hasPassword required />
<ShellButton
className="w-fit"
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index 4dc8842..769209e 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -346,10 +346,11 @@ export function SecurityPanel({
<p className="max-w-2xl text-sm leading-6 text-(--secondary)">
Two-step sign-in asks for a code from an authenticator app (such as
1Password, Google Authenticator or Microsoft Authenticator) after the
- password. When you require it, anyone who has not set it up is asked
- to do so the next time they open the app, and can do nothing else
- until they have. Ten wrong passwords for one email address stop
- sign-in for it for 15 minutes either way.
+ password. When you require it, anyone with a password who has not set
+ it up is asked to do so the next time they open the app, and can do
+ nothing else until they have. Accounts that only use single sign-on
+ are managed by their identity provider instead. Ten wrong passwords
+ for one email address stop sign-in for it for 15 minutes either way.
</p>
</div>
diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsx
index ffdb66f..394ab97 100644
--- a/src/components/settings/settings-shell.tsx
+++ b/src/components/settings/settings-shell.tsx
@@ -24,7 +24,12 @@ type SettingsShellProps = {
/** Why this account cannot be closed; shown in place of the button. */
closureBlockedReason?: string | null;
initialProfile?: ProfileValues;
- twoFactor?: { enabled: boolean; required: boolean };
+ twoFactor?: {
+ enabled: boolean;
+ hasPassword?: boolean;
+ required: boolean;
+ ssoProviderName?: string | null;
+ };
};
type FeedbackTone = "error" | "success";
@@ -166,7 +171,12 @@ function isNoOpEmailChangeMessage(message: string) {
export function SettingsShell({
closureBlockedReason = null,
initialProfile = defaultProfileValues,
- twoFactor = { enabled: false, required: false },
+ twoFactor = {
+ enabled: false,
+ hasPassword: true,
+ required: false,
+ ssoProviderName: null,
+ },
}: SettingsShellProps) {
const closureCopy = useClosureCopy();
const [profileValues, setProfileValues] = useState(initialProfile);
@@ -665,7 +675,9 @@ export function SettingsShell({
<TwoFactorPanel
enabled={twoFactor.enabled}
+ hasPassword={twoFactor.hasPassword ?? true}
required={twoFactor.required}
+ ssoProviderName={twoFactor.ssoProviderName ?? null}
/>
<SessionsPanel />
diff --git a/src/components/settings/two-factor-panel.tsx b/src/components/settings/two-factor-panel.tsx
index fee6e37..5b2de0c 100644
--- a/src/components/settings/two-factor-panel.tsx
+++ b/src/components/settings/two-factor-panel.tsx
@@ -5,6 +5,7 @@ import { encode } from "uqr";
import { useBranding } from "@/components/layout/branding-provider";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+import { describeTwoFactorPanel } from "@/lib/two-factor-view";
// Two-step sign-in for the signed-in person: set it up with an
// authenticator app, make new backup codes, or turn it off. The work is
@@ -44,6 +45,7 @@ function describeAuthError(payload: ApiPayload): string {
return "That password is not right.";
case "INVALID_CODE":
return "That code is not right. Check the time on your phone and try the newest code.";
+ case "PASSWORD_REQUIRED_FOR_TWO_FACTOR":
case "TWO_FACTOR_REQUIRED_BY_ADMINISTRATOR":
return payload.message ?? GENERIC_ERROR_MESSAGE;
default:
@@ -138,12 +140,23 @@ function BackupCodes({
export function TwoFactorPanel({
enabled,
+ hasPassword = true,
required,
+ ssoProviderName = null,
}: {
enabled: boolean;
+ hasPassword?: boolean;
required: boolean;
+ ssoProviderName?: string | null;
}) {
const { productName } = useBranding();
+ const view = describeTwoFactorPanel({
+ enabled,
+ hasPassword,
+ productName,
+ required,
+ ssoProviderName,
+ });
const [step, setStep] = useState<Step>({ kind: "idle" });
const [password, setPassword] = useState("");
const [code, setCode] = useState("");
@@ -151,6 +164,10 @@ export function TwoFactorPanel({
const [isBusy, setIsBusy] = useState(false);
function start(purpose: "disable" | "enable" | "codes") {
+ if (!view.canManage) {
+ return;
+ }
+
setPassword("");
setFeedback(null);
setStep({ kind: "confirm-password", purpose });
@@ -166,7 +183,7 @@ export function TwoFactorPanel({
async function handlePassword(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
- if (isBusy || step.kind !== "confirm-password") {
+ if (!view.canManage || isBusy || step.kind !== "confirm-password") {
return;
}
@@ -237,7 +254,7 @@ export function TwoFactorPanel({
async function handleCode(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
- if (isBusy || step.kind !== "scan") {
+ if (!view.canManage || isBusy || step.kind !== "scan") {
return;
}
@@ -279,154 +296,175 @@ export function TwoFactorPanel({
<h2 className="text-xl font-extrabold tracking-[-0.02em] text-(--fg)">
Two-step sign-in
</h2>
- <span className={`pill ${enabled ? "pill-success" : "pill-neutral"}`}>
- {enabled ? "On" : "Off"}
+ <span
+ className={`pill ${view.statusTone === "success" ? "pill-success" : "pill-neutral"}`}
+ >
+ {view.statusLabel}
</span>
</div>
<p className="max-w-2xl text-sm leading-6 text-(--secondary)">
- After your password, {productName} asks for a 6-digit code from an
- authenticator app on your phone, such as 1Password, Google
- Authenticator or Microsoft Authenticator. Someone who learns your
- password still cannot sign in.
- {required ? " Your organization requires it." : ""}
+ {view.description}
</p>
- {feedback ? (
- <p
- className={`notice ${feedback.tone === "success" ? "notice-success" : "notice-danger"}`}
- role={feedback.tone === "error" ? "alert" : "status"}
- >
- {feedback.message}
- </p>
- ) : null}
-
- {step.kind === "idle" ? (
- <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
- {enabled ? (
- <>
- <ShellButton onClick={() => start("codes")} variant="secondary">
- Make new backup codes
- </ShellButton>
- {required ? null : (
+ {view.canManage ? (
+ <>
+ {feedback ? (
+ <p
+ className={`notice ${feedback.tone === "success" ? "notice-success" : "notice-danger"}`}
+ role={feedback.tone === "error" ? "alert" : "status"}
+ >
+ {feedback.message}
+ </p>
+ ) : null}
+
+ {step.kind === "idle" ? (
+ <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
+ {enabled ? (
+ <>
+ <ShellButton
+ onClick={() => start("codes")}
+ variant="secondary"
+ >
+ Make new backup codes
+ </ShellButton>
+ {view.canDisable ? (
+ <ShellButton
+ onClick={() => start("disable")}
+ variant="secondary"
+ >
+ Turn off two-step sign-in
+ </ShellButton>
+ ) : null}
+ </>
+ ) : (
<ShellButton
- onClick={() => start("disable")}
- variant="secondary"
+ className="w-fit"
+ onClick={() => start("enable")}
>
- Turn off two-step sign-in
+ Set up two-step sign-in
</ShellButton>
)}
- </>
- ) : (
- <ShellButton className="w-fit" onClick={() => start("enable")}>
- Set up two-step sign-in
- </ShellButton>
- )}
- </div>
- ) : null}
-
- {step.kind === "confirm-password" ? (
- <form className="space-y-4" noValidate onSubmit={handlePassword}>
- <div className="max-w-sm">
- <FieldShell
- autoComplete="current-password"
- disabled={isBusy}
- label="Your password"
- name="two-factor-password"
- onChange={(event) => {
- setPassword(event.target.value);
- setFeedback(null);
- }}
- readOnly={false}
- type="password"
- value={password}
- />
- </div>
- <div className="flex flex-col gap-3 sm:flex-row">
- <ShellButton loading={isBusy} type="submit">
- {step.purpose === "enable"
- ? "Continue"
- : step.purpose === "codes"
- ? "Make new codes"
- : "Turn off"}
- </ShellButton>
- <ShellButton
- disabled={isBusy}
- onClick={cancel}
- variant="secondary"
- >
- Cancel
- </ShellButton>
- </div>
- </form>
- ) : null}
-
- {step.kind === "scan" ? (
- <div className="space-y-6">
- <div className="flex flex-col gap-5 sm:flex-row sm:items-start">
- <QrCode value={step.totpURI} />
- <div className="space-y-2 text-sm leading-6 text-(--secondary)">
- <p>
- <span className="font-semibold text-(--fg)">1.</span> Scan
- this code with your authenticator app.
- </p>
- <p>Or type in this key:</p>
- <p className="font-mono text-(--fg)" data-testid="totp-secret">
- {groupSecret(readSecret(step.totpURI))}
- </p>
</div>
- </div>
-
- <div className="space-y-2">
- <p className="text-sm font-semibold text-(--fg)">
- 2. Save your backup codes
- </p>
- <BackupCodes codes={step.backupCodes} productName={productName} />
- </div>
+ ) : null}
+
+ {step.kind === "confirm-password" ? (
+ <form className="space-y-4" noValidate onSubmit={handlePassword}>
+ <div className="max-w-sm">
+ <FieldShell
+ autoComplete="current-password"
+ disabled={isBusy}
+ label="Your password"
+ name="two-factor-password"
+ onChange={(event) => {
+ setPassword(event.target.value);
+ setFeedback(null);
+ }}
+ readOnly={false}
+ type="password"
+ value={password}
+ />
+ </div>
+ <div className="flex flex-col gap-3 sm:flex-row">
+ <ShellButton loading={isBusy} type="submit">
+ {step.purpose === "enable"
+ ? "Continue"
+ : step.purpose === "codes"
+ ? "Make new codes"
+ : "Turn off"}
+ </ShellButton>
+ <ShellButton
+ disabled={isBusy}
+ onClick={cancel}
+ variant="secondary"
+ >
+ Cancel
+ </ShellButton>
+ </div>
+ </form>
+ ) : null}
+
+ {step.kind === "scan" ? (
+ <div className="space-y-6">
+ <div className="flex flex-col gap-5 sm:flex-row sm:items-start">
+ <QrCode value={step.totpURI} />
+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">
+ <p>
+ <span className="font-semibold text-(--fg)">1.</span> Scan
+ this code with your authenticator app.
+ </p>
+ <p>Or type in this key:</p>
+ <p
+ className="font-mono text-(--fg)"
+ data-testid="totp-secret"
+ >
+ {groupSecret(readSecret(step.totpURI))}
+ </p>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-sm font-semibold text-(--fg)">
+ 2. Save your backup codes
+ </p>
+ <BackupCodes
+ codes={step.backupCodes}
+ productName={productName}
+ />
+ </div>
+
+ <form className="space-y-4" noValidate onSubmit={handleCode}>
+ <p className="text-sm font-semibold text-(--fg)">
+ 3. Enter the code your app shows
+ </p>
+ <div className="max-w-xs">
+ <FieldShell
+ autoComplete="one-time-code"
+ disabled={isBusy}
+ label="6-digit code"
+ name="two-factor-setup-code"
+ onChange={(event) => {
+ setCode(event.target.value);
+ setFeedback(null);
+ }}
+ readOnly={false}
+ value={code}
+ />
+ </div>
+ <div className="flex flex-col gap-3 sm:flex-row">
+ <ShellButton loading={isBusy} type="submit">
+ Turn on two-step sign-in
+ </ShellButton>
+ <ShellButton
+ disabled={isBusy}
+ onClick={cancel}
+ variant="secondary"
+ >
+ Cancel
+ </ShellButton>
+ </div>
+ </form>
+ </div>
+ ) : null}
- <form className="space-y-4" noValidate onSubmit={handleCode}>
- <p className="text-sm font-semibold text-(--fg)">
- 3. Enter the code your app shows
- </p>
- <div className="max-w-xs">
- <FieldShell
- autoComplete="one-time-code"
- disabled={isBusy}
- label="6-digit code"
- name="two-factor-setup-code"
- onChange={(event) => {
- setCode(event.target.value);
- setFeedback(null);
- }}
- readOnly={false}
- value={code}
+ {step.kind === "new-codes" ? (
+ <div className="space-y-4">
+ <p className="notice notice-success" role="status">
+ New backup codes made. The old ones no longer work.
+ </p>
+ <BackupCodes
+ codes={step.backupCodes}
+ productName={productName}
/>
- </div>
- <div className="flex flex-col gap-3 sm:flex-row">
- <ShellButton loading={isBusy} type="submit">
- Turn on two-step sign-in
- </ShellButton>
<ShellButton
- disabled={isBusy}
+ className="w-fit"
onClick={cancel}
variant="secondary"
>
- Cancel
+ Done
</ShellButton>
</div>
- </form>
- </div>
- ) : null}
-
- {step.kind === "new-codes" ? (
- <div className="space-y-4">
- <p className="notice notice-success" role="status">
- New backup codes made. The old ones no longer work.
- </p>
- <BackupCodes codes={step.backupCodes} productName={productName} />
- <ShellButton className="w-fit" onClick={cancel} variant="secondary">
- Done
- </ShellButton>
- </div>
+ ) : null}
+ </>
) : null}
</div>
</div>
diff --git a/src/lib/auth/sign-in-events.ts b/src/lib/auth/sign-in-events.ts
index 64b7f7a..7dd30dd 100644
--- a/src/lib/auth/sign-in-events.ts
+++ b/src/lib/auth/sign-in-events.ts
@@ -26,6 +26,7 @@ import {
getSignInLockState,
MAX_FAILED_SIGN_INS,
SIGN_IN_LOCKED_MESSAGE,
+ userHasPassword,
} from "../sign-in-security.ts";
// Puts sign-ins and changes to how people sign in into the install's audit
@@ -45,6 +46,14 @@ const SECOND_STEP_PATHS = new Set([
"/two-factor/verify-totp",
]);
+// Two-step management endpoints that verify the account's password.
+const PASSWORD_TWO_FACTOR_PATHS = new Set([
+ "/two-factor/disable",
+ "/two-factor/enable",
+ "/two-factor/generate-backup-codes",
+ "/two-factor/get-totp-uri",
+]);
+
// Paths whose actor is only known before the endpoint runs: each replaces
// or ends the session it was called with.
const SESSION_FIRST_PATHS = new Set([
@@ -302,6 +311,28 @@ export function signInEvents() {
}
}),
},
+ {
+ // Two-step sign-in here protects password sign-in and verifies the
+ // account's password before changing settings. Someone who only signs
+ // in through an identity provider has no password here; refusing
+ // early avoids a misleading "Invalid password" error.
+ matcher: (ctx) => PASSWORD_TWO_FACTOR_PATHS.has(ctx.path ?? ""),
+ handler: createAuthMiddleware(async (ctx) => {
+ const session = await getSessionFromCtx(ctx).catch(() => null);
+
+ if (!session) {
+ return;
+ }
+
+ if (!(await userHasPassword(session.user.id))) {
+ throw new APIError("BAD_REQUEST", {
+ code: "PASSWORD_REQUIRED_FOR_TWO_FACTOR",
+ message:
+ "This account signs in with single sign-on and has no password here. Two-step sign-in is managed by your identity provider.",
+ });
+ }
+ }),
+ },
{
// An install that requires two-step sign-in does not let anyone
// turn theirs off. An administrator can still reset it for
diff --git a/src/lib/auth/sso.dbtest.ts b/src/lib/auth/sso.dbtest.ts
index ebf5500..16ed257 100644
--- a/src/lib/auth/sso.dbtest.ts
+++ b/src/lib/auth/sso.dbtest.ts
@@ -14,7 +14,11 @@ 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";
+import {
+ needsTwoFactorSetup,
+ setTwoFactorRequirement,
+ userHasPassword,
+} 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
@@ -590,22 +594,96 @@ test("requiring two-step sign-in does not hold up someone who only uses single s
const user = await sessionUser(auth, cookies);
assert.ok(user);
+ assert.equal(await userHasPassword(user.id, { database }), false);
assert.equal(
await needsTwoFactorSetup({ requireTwoFactor: true }, user, { database }),
false,
);
- // Someone with a password still has to set it up.
+ // Calling the password-based two-step endpoints directly explains why
+ // instead of returning a misleading INVALID_PASSWORD error.
+ const enableAttempt = await post(
+ auth,
+ "/two-factor/enable",
+ { issuer: "Acme Sign", password: PASSWORD },
+ cookies,
+ );
+
+ assert.equal(enableAttempt.status, 400);
+ assert.equal(enableAttempt.payload?.code, "PASSWORD_REQUIRED_FOR_TWO_FACTOR");
+
+ const codesAttempt = await post(
+ auth,
+ "/two-factor/generate-backup-codes",
+ { password: PASSWORD },
+ cookies,
+ );
+
+ assert.equal(codesAttempt.status, 400);
+ assert.equal(codesAttempt.payload?.code, "PASSWORD_REQUIRED_FOR_TWO_FACTOR");
+
+ // An SSO-only administrator can require two-step sign-in for password
+ // accounts without being told to set it up on their own passwordless account.
+ await database.query(`update "user" set role = 'admin' where id = $1`, [
+ user.id,
+ ]);
+ await setTwoFactorRequirement(
+ { email: user.email, userId: user.id },
+ true,
+ database,
+ );
+ invalidateSettingsCache();
+
+ const disableAttempt = await post(
+ auth,
+ "/two-factor/disable",
+ { password: PASSWORD },
+ cookies,
+ );
+
+ assert.equal(disableAttempt.status, 400);
+ assert.equal(
+ disableAttempt.payload?.code,
+ "PASSWORD_REQUIRED_FOR_TWO_FACTOR",
+ );
+
+ // A credential row with a NULL password does not count as having a password.
+ const emptyCredId = randomUUID();
+
+ await database.query(
+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, $2, 'credential', $2, null)`,
+ [emptyCredId, user.id],
+ );
+ assert.equal(await userHasPassword(user.id, { database }), false);
+ assert.equal(
+ await needsTwoFactorSetup({ requireTwoFactor: true }, user, { database }),
+ false,
+ );
+ await database.query(`delete from account where id = $1`, [emptyCredId]);
+
+ // Someone with BOTH SSO and a password still has to set it up, and can.
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 userHasPassword(user.id, { database }), true);
assert.equal(
await needsTwoFactorSetup({ requireTwoFactor: true }, user, { database }),
true,
);
+
+ const hybridEnable = await post(
+ auth,
+ "/two-factor/enable",
+ { issuer: "Acme Sign", password: PASSWORD },
+ cookies,
+ );
+
+ assert.equal(hybridEnable.status, 200, JSON.stringify(hybridEnable.payload));
+ assert.ok(typeof hybridEnable.payload?.totpURI === "string");
+ assert.equal((hybridEnable.payload?.backupCodes as string[])?.length, 10);
});
test("an ID token posted straight to the sign-in route is refused, not signed in unaudited", async () => {
diff --git a/src/lib/sign-in-security.dbtest.ts b/src/lib/sign-in-security.dbtest.ts
index 12e2955..b11a5b4 100644
--- a/src/lib/sign-in-security.dbtest.ts
+++ b/src/lib/sign-in-security.dbtest.ts
@@ -21,6 +21,7 @@ import {
resetTwoFactor,
setTwoFactorRequirement,
SignInSecurityError,
+ userHasPassword,
} from "./sign-in-security.ts";
// Sign-in security against a real Postgres and the real Better Auth
@@ -706,3 +707,31 @@ test("confirming an authenticator with a leftover challenge cookie is recorded a
assert.equal((await events("two_factor_enabled"))[0]?.actorUserId, userId);
assert.equal((await events("sign_in_succeeded")).length, before);
});
+
+test("userHasPassword checks for a non-empty credential hash, and an SSO-only admin can require two-step sign-in", async () => {
+ const passwordUserId = await createVerifiedUser("[email protected]");
+ const ssoAdminId = randomUUID();
+
+ await database.query(
+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Sso Admin', '[email protected]', true, 'admin')`,
+ [ssoAdminId],
+ );
+ await database.query(
+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, 'oidc-sub', 'sso', $2, null)`,
+ [randomUUID(), ssoAdminId],
+ );
+
+ assert.equal(await userHasPassword(passwordUserId, { database }), true);
+ assert.equal(await userHasPassword(ssoAdminId, { database }), false);
+
+ await setTwoFactorRequirement(
+ { email: "[email protected]", userId: ssoAdminId },
+ true,
+ database,
+ );
+
+ const [changed] = await events("two_factor_requirement_changed");
+
+ assert.equal(changed?.actorUserId, ssoAdminId);
+ assert.deepEqual(changed?.metadata, { from: false, to: true });
+});
diff --git a/src/lib/sign-in-security.test.ts b/src/lib/sign-in-security.test.ts
new file mode 100644
index 0000000..401d57f
--- /dev/null
+++ b/src/lib/sign-in-security.test.ts
@@ -0,0 +1,376 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { isAPIError } from "better-auth/api";
+
+import { signInEvents } from "./auth/sign-in-events.ts";
+import {
+ replaceDbPoolForTests,
+ type DbExecutor,
+ type DbPool,
+} from "./db/connection.ts";
+import {
+ needsTwoFactorSetup,
+ userHasPassword,
+ usesTwoFactor,
+} from "./sign-in-security.ts";
+import { describeTwoFactorPanel } from "./two-factor-view.ts";
+
+type AccountRow = {
+ password: string | null;
+ providerId: string;
+ userId: string;
+};
+
+/**
+ * Minimal DbExecutor stub that emulates the `account` password lookup SQL
+ * used by `userHasPassword` and `needsTwoFactorSetup`.
+ */
+function mockAccountDb(accounts: readonly AccountRow[]) {
+ const queries: Array<{ text: string; values: unknown[] }> = [];
+
+ const database = {
+ async query(text: string, values: unknown[] = []) {
+ queries.push({ text, values });
+
+ const userId = typeof values[0] === "string" ? values[0] : "";
+ const requiresNonNullPassword = /password\s+is\s+not\s+null/i.test(text);
+ const requiresNonEmptyPassword = /password\s*<>\s*''/i.test(text);
+
+ const found = accounts.some((row) => {
+ if (row.userId !== userId || row.providerId !== "credential") {
+ return false;
+ }
+
+ if (requiresNonNullPassword && row.password === null) {
+ return false;
+ }
+
+ if (requiresNonEmptyPassword && row.password === "") {
+ return false;
+ }
+
+ return true;
+ });
+
+ return {
+ command: "SELECT",
+ fields: [],
+ oid: 0,
+ rowCount: found ? 1 : 0,
+ rows: found ? [{ found: 1 }] : [],
+ };
+ },
+ } as unknown as DbExecutor;
+
+ return { database, queries };
+}
+
+test("usesTwoFactor recognizes only an explicit boolean true", () => {
+ assert.equal(usesTwoFactor({ twoFactorEnabled: true }), true);
+ assert.equal(usesTwoFactor({ twoFactorEnabled: false }), false);
+ assert.equal(usesTwoFactor({ twoFactorEnabled: "true" }), false);
+ assert.equal(usesTwoFactor({}), false);
+});
+
+test("userHasPassword distinguishes password-only, SSO-only, hybrid and null-password accounts", async () => {
+ const { database } = mockAccountDb([
+ { password: "hashed-password", providerId: "credential", userId: "pwd" },
+ { password: null, providerId: "sso", userId: "sso-only" },
+ { password: null, providerId: "sso", userId: "hybrid" },
+ { password: "hashed-password", providerId: "credential", userId: "hybrid" },
+ { password: null, providerId: "credential", userId: "null-pwd" },
+ { password: "", providerId: "credential", userId: "empty-pwd" },
+ ]);
+
+ assert.equal(await userHasPassword("pwd", { database }), true);
+ assert.equal(await userHasPassword("sso-only", { database }), false);
+ assert.equal(await userHasPassword("hybrid", { database }), true);
+ assert.equal(await userHasPassword("null-pwd", { database }), false);
+ assert.equal(await userHasPassword("empty-pwd", { database }), false);
+ assert.equal(await userHasPassword("missing", { database }), false);
+});
+
+test("needsTwoFactorSetup exempts SSO-only accounts but enforces on password and hybrid accounts", async () => {
+ const { database, queries } = mockAccountDb([
+ { password: "hashed-password", providerId: "credential", userId: "pwd" },
+ { password: null, providerId: "sso", userId: "sso-only" },
+ { password: null, providerId: "sso", userId: "hybrid" },
+ { password: "hashed-password", providerId: "credential", userId: "hybrid" },
+ { password: null, providerId: "credential", userId: "null-pwd" },
+ ]);
+
+ // Short-circuits without querying when requirement is off or 2FA is already on.
+ assert.equal(
+ await needsTwoFactorSetup(
+ { requireTwoFactor: false },
+ { id: "pwd", twoFactorEnabled: false },
+ { database },
+ ),
+ false,
+ );
+ assert.equal(
+ await needsTwoFactorSetup(
+ { requireTwoFactor: true },
+ { id: "pwd", twoFactorEnabled: true },
+ { database },
+ ),
+ false,
+ );
+ assert.equal(queries.length, 0);
+
+ // Requirement on, 2FA off: depends on whether a non-empty credential password exists.
+ assert.equal(
+ await needsTwoFactorSetup(
+ { requireTwoFactor: true },
+ { id: "sso-only", twoFactorEnabled: false },
+ { database },
+ ),
+ false,
+ );
+ assert.equal(
+ await needsTwoFactorSetup(
+ { requireTwoFactor: true },
+ { id: "null-pwd", twoFactorEnabled: false },
+ { database },
+ ),
+ false,
+ );
+ assert.equal(
+ await needsTwoFactorSetup(
+ { requireTwoFactor: true },
+ { id: "pwd", twoFactorEnabled: false },
+ { database },
+ ),
+ true,
+ );
+ assert.equal(
+ await needsTwoFactorSetup(
+ { requireTwoFactor: true },
+ { id: "hybrid", twoFactorEnabled: false },
+ { database },
+ ),
+ true,
+ );
+ // Missing user id fails closed.
+ assert.equal(
+ await needsTwoFactorSetup({ requireTwoFactor: true }, {}, { database }),
+ true,
+ );
+});
+
+test("TwoFactorPanel view for SSO-only accounts hides password setup and org requirement notice", () => {
+ const optionalDefault = describeTwoFactorPanel({
+ enabled: false,
+ hasPassword: false,
+ productName: "SignuDoc",
+ required: false,
+ ssoProviderName: "single sign-on",
+ });
+
+ assert.equal(optionalDefault.mode, "sso-only");
+ assert.equal(optionalDefault.canManage, false);
+ assert.equal(optionalDefault.canDisable, false);
+ assert.equal(optionalDefault.statusLabel, "Managed by identity provider");
+ assert.equal(optionalDefault.statusTone, "neutral");
+ assert.match(optionalDefault.description, /signs in with single sign-on and/);
+ assert.match(optionalDefault.description, /no SignuDoc password/);
+ assert.match(
+ optionalDefault.description,
+ /managed by your identity provider/,
+ );
+ assert.doesNotMatch(optionalDefault.description, /After your password/);
+ assert.doesNotMatch(
+ optionalDefault.description,
+ /Your organization requires/,
+ );
+ assert.doesNotMatch(optionalDefault.description, /\(single sign-on\)/i);
+
+ const requiredNamed = describeTwoFactorPanel({
+ enabled: false,
+ hasPassword: false,
+ productName: "Acme Corp",
+ required: true,
+ ssoProviderName: "Okta",
+ });
+
+ assert.equal(requiredNamed.mode, "sso-only");
+ assert.equal(requiredNamed.canManage, false);
+ assert.equal(requiredNamed.statusLabel, "Managed by identity provider");
+ assert.match(requiredNamed.description, /single sign-on \(Okta\)/);
+ assert.match(requiredNamed.description, /no Acme Corp password/);
+ assert.match(
+ requiredNamed.description,
+ /applies only to accounts with a password, so it does not apply to this account/,
+ );
+ assert.doesNotMatch(requiredNamed.description, /After your password/);
+ assert.doesNotMatch(requiredNamed.description, /Your organization requires/);
+
+ const noConfiguredProvider = describeTwoFactorPanel({
+ enabled: false,
+ hasPassword: false,
+ productName: "SignuDoc",
+ required: true,
+ ssoProviderName: null,
+ });
+
+ assert.equal(noConfiguredProvider.mode, "sso-only");
+ assert.equal(noConfiguredProvider.canManage, false);
+ assert.match(
+ noConfiguredProvider.description,
+ /signs in with single sign-on and has no SignuDoc password/,
+ );
+
+ // Even in a degenerate state where twoFactorEnabled was true without a
+ // credential password, password-gated actions stay hidden.
+ const degenerate = describeTwoFactorPanel({
+ enabled: true,
+ hasPassword: false,
+ productName: "SignuDoc",
+ required: false,
+ ssoProviderName: "Okta",
+ });
+
+ assert.equal(degenerate.mode, "sso-only");
+ assert.equal(degenerate.canManage, false);
+ assert.equal(degenerate.canDisable, false);
+});
+
+test("TwoFactorPanel view for password and hybrid SSO+password accounts keeps normal setup and org requirement", () => {
+ const passwordOptional = describeTwoFactorPanel({
+ enabled: false,
+ hasPassword: true,
+ productName: "SignuDoc",
+ required: false,
+ ssoProviderName: null,
+ });
+
+ assert.equal(passwordOptional.mode, "password");
+ assert.equal(passwordOptional.canManage, true);
+ assert.equal(passwordOptional.canDisable, false);
+ assert.equal(passwordOptional.statusLabel, "Off");
+ assert.equal(passwordOptional.statusTone, "neutral");
+ assert.match(passwordOptional.description, /^After your password, SignuDoc/);
+ assert.doesNotMatch(
+ passwordOptional.description,
+ /Your organization requires it\./,
+ );
+
+ const hybridRequired = describeTwoFactorPanel({
+ enabled: false,
+ hasPassword: true,
+ productName: "SignuDoc",
+ required: true,
+ ssoProviderName: "Okta",
+ });
+
+ assert.equal(hybridRequired.mode, "password");
+ assert.equal(hybridRequired.canManage, true);
+ assert.equal(hybridRequired.statusLabel, "Off");
+ assert.match(hybridRequired.description, /^After your password, SignuDoc/);
+ assert.match(hybridRequired.description, /Your organization requires it\.$/);
+
+ const enabledOptional = describeTwoFactorPanel({
+ enabled: true,
+ hasPassword: true,
+ productName: "Acme Corp",
+ required: false,
+ });
+
+ assert.equal(enabledOptional.mode, "password");
+ assert.equal(enabledOptional.canManage, true);
+ assert.equal(enabledOptional.canDisable, true);
+ assert.equal(enabledOptional.statusLabel, "On");
+ assert.equal(enabledOptional.statusTone, "success");
+
+ const enabledRequired = describeTwoFactorPanel({
+ enabled: true,
+ hasPassword: true,
+ productName: "Acme Corp",
+ required: true,
+ });
+
+ assert.equal(enabledRequired.mode, "password");
+ assert.equal(enabledRequired.canManage, true);
+ assert.equal(enabledRequired.canDisable, false);
+ assert.equal(enabledRequired.statusLabel, "On");
+ assert.equal(enabledRequired.statusTone, "success");
+ assert.match(enabledRequired.description, /Your organization requires it\.$/);
+});
+
+test("signInEvents refuses password-based two-factor routes for SSO-only accounts with a clear error", async () => {
+ const plugin = signInEvents();
+ const guard = plugin.hooks.before.find(
+ (hook) =>
+ hook.matcher({ path: "/two-factor/enable" } as never) &&
+ !hook.matcher({ path: "/change-password" } as never),
+ );
+
+ assert.ok(guard, "expected password-required two-factor guard hook");
+
+ for (const path of [
+ "/two-factor/enable",
+ "/two-factor/disable",
+ "/two-factor/generate-backup-codes",
+ "/two-factor/get-totp-uri",
+ ]) {
+ assert.equal(guard.matcher({ path } as never), true, path);
+ }
+
+ assert.equal(
+ guard.matcher({ path: "/two-factor/verify-totp" } as never),
+ false,
+ );
+
+ const { database } = mockAccountDb([
+ { password: "hashed-password", providerId: "credential", userId: "pwd" },
+ { password: null, providerId: "sso", userId: "sso-only" },
+ { password: null, providerId: "sso", userId: "hybrid" },
+ { password: "hashed-password", providerId: "credential", userId: "hybrid" },
+ { password: null, providerId: "credential", userId: "null-pwd" },
+ ]);
+ const previous = replaceDbPoolForTests(database as unknown as DbPool);
+
+ try {
+ for (const userId of ["sso-only", "null-pwd"]) {
+ await assert.rejects(
+ () =>
+ guard.handler({
+ context: {
+ session: {
+ session: { token: "tok" },
+ user: { email: `${userId}@acme.com`, id: userId },
+ },
+ },
+ path: "/two-factor/enable",
+ } as never),
+ (error: unknown) =>
+ isAPIError(error) &&
+ error.statusCode === 400 &&
+ (error.body as { code?: string } | null)?.code ===
+ "PASSWORD_REQUIRED_FOR_TWO_FACTOR",
+ );
+ }
+
+ // Password-only and hybrid accounts pass through to Better Auth.
+ for (const userId of ["pwd", "hybrid"]) {
+ await guard.handler({
+ context: {
+ session: {
+ session: { token: "tok" },
+ user: { email: `${userId}@acme.com`, id: userId },
+ },
+ },
+ path: "/two-factor/enable",
+ } as never);
+ }
+
+ // Unauthenticated callers pass through so Better Auth returns 401.
+ await guard.handler({
+ context: {},
+ path: "/two-factor/enable",
+ } as never);
+ } finally {
+ replaceDbPoolForTests(previous as DbPool);
+ }
+});
diff --git a/src/lib/sign-in-security.ts b/src/lib/sign-in-security.ts
index fbd425b..23bae7e 100644
--- a/src/lib/sign-in-security.ts
+++ b/src/lib/sign-in-security.ts
@@ -102,6 +102,24 @@ export async function clearFailedSignIns(
await clearRateLimit(failedSignInKey(email), options);
}
+/**
+ * Whether this account has a password stored here (a Better Auth credential
+ * account with a non-empty password hash), as opposed to signing in only
+ * through an identity provider.
+ */
+export async function userHasPassword(
+ userId: string,
+ options: { database?: DbExecutor } = {},
+): Promise<boolean> {
+ const password = await queryOne<{ found: number }>(
+ options.database ?? getDb(),
+ `SELECT 1 AS found FROM account WHERE "userId" = $1 AND "providerId" = 'credential' AND password IS NOT NULL AND password <> '' LIMIT 1`,
+ [userId],
+ );
+
+ return password !== null;
+}
+
/**
* 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
@@ -126,13 +144,7 @@ export async function needsTwoFactorSetup(
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;
+ return userHasPassword(userId, options);
}
/**
diff --git a/src/lib/two-factor-view.ts b/src/lib/two-factor-view.ts
new file mode 100644
index 0000000..9aab6f3
--- /dev/null
+++ b/src/lib/two-factor-view.ts
@@ -0,0 +1,86 @@
+// What the Two-step sign-in panel in Settings shows for an account. Kept
+// apart from the React component so every account kind (password-only,
+// SSO-only, and accounts with both) can be tested without a browser.
+
+export type TwoFactorPanelInput = {
+ enabled: boolean;
+ /** Whether the account has a password stored here (credential account). */
+ hasPassword: boolean;
+ productName: string;
+ /** Whether the organization requires two-step sign-in for password accounts. */
+ required: boolean;
+ /** Configured identity provider name (SSO_NAME), if any. */
+ ssoProviderName?: string | null;
+};
+
+export type TwoFactorPanelView =
+ | {
+ canDisable: false;
+ canManage: false;
+ description: string;
+ mode: "sso-only";
+ statusLabel: "Managed by identity provider";
+ statusTone: "neutral";
+ }
+ | {
+ canDisable: boolean;
+ canManage: true;
+ description: string;
+ mode: "password";
+ statusLabel: "Off" | "On";
+ statusTone: "neutral" | "success";
+ };
+
+function formatSsoProviderQualifier(
+ ssoProviderName: string | null | undefined,
+): string {
+ const trimmed = ssoProviderName?.trim() ?? "";
+
+ if (trimmed.length === 0 || trimmed.toLowerCase() === "single sign-on") {
+ return "";
+ }
+
+ return ` (${trimmed})`;
+}
+
+/**
+ * Decides the badge, copy and controls for the Two-step sign-in panel.
+ *
+ * Two-step sign-in here protects password sign-in and requires the account's
+ * password to turn on, change or turn off. An account with no password here
+ * signs in through the organization's identity provider, which handles its
+ * own second step and is exempt from the organization's password two-step
+ * sign-in requirement.
+ */
+export function describeTwoFactorPanel({
+ enabled,
+ hasPassword,
+ productName,
+ required,
+ ssoProviderName,
+}: TwoFactorPanelInput): TwoFactorPanelView {
+ if (!hasPassword) {
+ const providerQualifier = formatSsoProviderQualifier(ssoProviderName);
+ const requirementNote = required
+ ? " The organization's two-step sign-in requirement applies only to accounts with a password, so it does not apply to this account."
+ : "";
+
+ return {
+ canDisable: false,
+ canManage: false,
+ description: `This account signs in with single sign-on${providerQualifier} and has no ${productName} password. Two-step sign-in is managed by your identity provider instead of here.${requirementNote}`,
+ mode: "sso-only",
+ statusLabel: "Managed by identity provider",
+ statusTone: "neutral",
+ };
+ }
+
+ return {
+ canDisable: enabled && !required,
+ canManage: true,
+ description: `After your password, ${productName} asks for a 6-digit code from an authenticator app on your phone, such as 1Password, Google Authenticator or Microsoft Authenticator. Someone who learns your password still cannot sign in.${required ? " Your organization requires it." : ""}`,
+ mode: "password",
+ statusLabel: enabled ? "On" : "Off",
+ statusTone: enabled ? "success" : "neutral",
+ };
+}