Skip to content

Commit 004729a

Browse files
committed
wip(plugin-auth): refuse an organization's require_mfa while two-factor is off; the MFA gate holds only enrollable users
Claude-Session: https://claude.ai/code/session_01Utp6CYRZxPEjGeTbGfW4YC Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5fa9375 commit 004729a

5 files changed

Lines changed: 219 additions & 7 deletions

File tree

‎packages/plugins/plugin-auth/src/auth-manager-password-session-policy.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ export interface PasswordSessionPolicyHost {
6262
_orgMfaCache: AuthManager['_orgMfaCache'];
6363
_orgMfaRefreshing: AuthManager['_orgMfaRefreshing'];
6464
getDataEngine: AuthManager['getDataEngine'];
65+
isTwoFactorEnabled: AuthManager['isTwoFactorEnabled'];
6566
logDurabilityDegradation: AuthManager['logDurabilityDegradation'];
67+
noteMfaRequirementWithoutEnrollment: AuthManager['noteMfaRequirementWithoutEnrollment'];
6668
parseHashes: AuthManager['parseHashes'];
6769
refreshMustChangeCacheIfStale: AuthManager['refreshMustChangeCacheIfStale'];
6870
refreshOrgMfaCacheIfStale: AuthManager['refreshOrgMfaCacheIfStale'];
@@ -136,7 +138,7 @@ export function refreshOrgMfaCacheIfStale(this: Pick<PasswordSessionPolicyHost,
136138

137139
/** The body of `AuthManager#resolveUserAuthGates`; the method's docblock there is its contract. */
138140
export async function resolveUserAuthGates(
139-
this: Pick<PasswordSessionPolicyHost, '_mustChangeCache' | '_orgMfaCache' | 'config' | 'getDataEngine' | 'refreshMustChangeCacheIfStale' | 'refreshOrgMfaCacheIfStale'>,
141+
this: Pick<PasswordSessionPolicyHost, '_mustChangeCache' | '_orgMfaCache' | 'config' | 'getDataEngine' | 'isTwoFactorEnabled' | 'noteMfaRequirementWithoutEnrollment' | 'refreshMustChangeCacheIfStale' | 'refreshOrgMfaCacheIfStale'>,
140142
userId: string,
141143
options: { organizationId?: string } = {},
142144
): Promise<AuthGate[]> {
@@ -205,7 +207,21 @@ export async function resolveUserAuthGates(
205207
// A user without TOTP enrolled is blocked once their grace window
206208
// elapses. The clock (`mfa_required_at`) starts the first time we see
207209
// them required-but-unenrolled (stamped lazily, best-effort).
208-
if (mfaRequired && !(u?.two_factor_enabled === true || u?.two_factor_enabled === 1)) {
210+
//
211+
// [#30201] Only while they CAN enroll. The twoFactor plugin's
212+
// `/two-factor/*` endpoints are the one enrollment path; with the plugin
213+
// off, a hold here answers `MFA_REQUIRED` to a user whose remediation
214+
// endpoint does not exist, which locks every member of the organization
215+
// out, the owner included, behind the very gate that guards Setup. So an
216+
// unenrollable requirement is not enforced (no hold, and no grace clock
217+
// started: the window opens when enrollment does) and is reported once.
218+
// The `require_mfa` write guard refuses a new requirement in that state
219+
// (`organization-mfa-enrollment-guard.ts`); this covers rows stored before
220+
// it, and an `OS_AUTH_TWO_FACTOR=false` pin under the global setting.
221+
const unenrolled = !(u?.two_factor_enabled === true || u?.two_factor_enabled === 1);
222+
if (mfaRequired && unenrolled && !this.isTwoFactorEnabled()) {
223+
this.noteMfaRequirementWithoutEnrollment();
224+
} else if (mfaRequired && unenrolled) {
209225
const graceDays = Math.max(0, Math.floor(Number(this.config.mfaGracePeriodDays ?? 7)));
210226
let requiredAt = u?.mfa_required_at;
211227
if (!requiredAt) {

‎packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ import {
7171
resolveDcrEnabled,
7272
resolveOidcProviderEnabled,
7373
resolveScimEnabled,
74+
resolveTwoFactorEnabled,
7475
type AuthManager,
7576
} from './auth-manager.js';
7677
import {
@@ -188,11 +189,13 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
188189
// better-auth build would otherwise mount SCIM with its ADR-0134
189190
// deprovisioning path silently declined.
190191
assertScimAdminCoherence(pluginConfig);
191-
const twoFactorFromEnv = readBooleanEnv('OS_AUTH_TWO_FACTOR');
192192
const hibpFromEnv = readBooleanEnv('OS_AUTH_PASSWORD_REJECT_BREACHED');
193193
const enabled = {
194194
organization: pluginConfig.organization ?? true,
195-
twoFactor: twoFactorFromEnv ?? pluginConfig.twoFactor ?? false,
195+
// [#30201] Shared decision point (env → config), see
196+
// resolveTwoFactorEnabled — the MFA gate and the require_mfa write guard
197+
// ask the same question, so a requirement is never enforced unenrollable.
198+
twoFactor: resolveTwoFactorEnabled(pluginConfig),
196199
passwordRejectBreached: hibpFromEnv ?? pluginConfig.passwordRejectBreached ?? false,
197200
passkeys: pluginConfig.passkeys ?? false,
198201
magicLink: pluginConfig.magicLink ?? false,

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,23 @@ export function resolveScimEnabled(pluginConfig?: Partial<AuthPluginConfig>): bo
432432
return pluginConfig?.scim ?? readBooleanEnv('OS_SCIM_ENABLED') ?? false;
433433
}
434434

435+
/**
436+
* [#30201] SINGLE decision point for "can a user enroll a second factor
437+
* here?" — whether better-auth's `twoFactor` plugin is wired, whose
438+
* `/two-factor/*` endpoints are the only enrollment path. Shared by
439+
* `buildPluginList()` (what is wired), the `/auth/config` features block (what
440+
* is advertised), the per-user MFA gate (ADR-0069 D3 holds a user only while
441+
* they can enroll) and the `sys_organization.require_mfa` write guard
442+
* (`organization-mfa-enrollment-guard.ts`), so the four can never disagree.
443+
*
444+
* Resolution order: `OS_AUTH_TWO_FACTOR` env (operator override, wins) →
445+
* config (`plugins.twoFactor`, which the `auth.mfa_required` setting turns on
446+
* together with the requirement) → off.
447+
*/
448+
export function resolveTwoFactorEnabled(pluginConfig?: Partial<AuthPluginConfig>): boolean {
449+
return readBooleanEnv('OS_AUTH_TWO_FACTOR') ?? pluginConfig?.twoFactor ?? false;
450+
}
451+
435452
/**
436453
* Entry validation (#13816, maintainer ruling 2026-09-01) — REFUSES the one
437454
* incoherent corner of the `admin` tri-state at the point the config enters
@@ -1547,6 +1564,10 @@ export class AuthManager {
15471564
// the node that issues a flag (other nodes catch up within the TTL).
15481565
private _mustChangeCache: { value: boolean; at: number } = { value: false, at: 0 };
15491566
private _mustChangeRefreshing = false;
1567+
// [#30201] Set the first time the MFA gate meets a requirement it does not
1568+
// enforce because no one can enroll (see `noteMfaRequirementWithoutEnrollment`),
1569+
// so the warning is said once per manager, not once per request.
1570+
private _mfaWithoutEnrollmentNoted = false;
15501571
// Optional auth features whose better-auth plugin failed to initialize and
15511572
// was skipped so core auth stays up (feature key → error message). Rebuilt
15521573
// by every buildPluginList() run; see addOptionalPlugin().
@@ -4584,7 +4605,6 @@ export class AuthManager {
45844605
const termsUrl = resolveLegalUrl(rawTermsUrl, DEFAULT_TERMS_URL);
45854606
const privacyUrl = resolveLegalUrl(rawPrivacyUrl, DEFAULT_PRIVACY_URL);
45864607

4587-
const twoFactorFromEnv = readBooleanEnv('OS_AUTH_TWO_FACTOR');
45884608
const turnstileKeys = resolveTurnstileKeys();
45894609

45904610
// [#7481, maintainer ruling 2026-08-11] `passkeys` / `magicLink` are
@@ -4595,7 +4615,7 @@ export class AuthManager {
45954615
// `magicLink`'s server endpoints are unaffected: `plugins.magicLink` still
45964616
// wires better-auth's magic-link plugin in buildPluginList().
45974617
const features = {
4598-
twoFactor: twoFactorFromEnv ?? pluginConfig.twoFactor ?? false,
4618+
twoFactor: resolveTwoFactorEnabled(pluginConfig),
45994619
organization: pluginConfig.organization ?? true,
46004620
multiOrgEnabled,
46014621
// ADR-0105 D1 — WHICH posture is in force. `multiOrgEnabled` stays the
@@ -5233,6 +5253,37 @@ export class AuthManager {
52335253
return ((this.config.plugins ?? {}) as any).phoneNumber === true;
52345254
}
52355255

5256+
/**
5257+
* [#30201] Can a user enroll a second factor on this deployment right now —
5258+
* is the twoFactor plugin wired? {@link resolveTwoFactorEnabled} over the
5259+
* live config, the one answer `buildPluginList()` and `features.twoFactor`
5260+
* give too. Read per call, so a settings pass that turns the plugin on is
5261+
* seen at once.
5262+
*/
5263+
public isTwoFactorEnabled(): boolean {
5264+
return resolveTwoFactorEnabled(this.config.plugins);
5265+
}
5266+
5267+
/**
5268+
* [#30201] Called by the MFA gate when a user is under an MFA requirement
5269+
* (the global `mfaRequired` or their organization's `require_mfa`) that it
5270+
* does not enforce, because the twoFactor plugin is off and the user has no
5271+
* way to enroll. A functional degradation (AGENTS.md, degradation log
5272+
* levels): the requirement is visibly not in force, nothing stored is lost.
5273+
* Said once per manager, with the remedy.
5274+
*/
5275+
private noteMfaRequirementWithoutEnrollment(): void {
5276+
if (this._mfaWithoutEnrollmentNoted) return;
5277+
this._mfaWithoutEnrollmentNoted = true;
5278+
this.config.logger?.warn(
5279+
'[auth] multi-factor authentication is required (the auth.mfa_required setting, or an organization\'s ' +
5280+
'require_mfa) but is NOT enforced: the two-factor feature is off, so nobody can enroll an authenticator ' +
5281+
'app, and holding them would lock every affected member out, the owner included. Remedy: turn two-factor ' +
5282+
'on (OS_AUTH_TWO_FACTOR=true, or the auth.mfa_required setting, which turns it on with the requirement); ' +
5283+
'or clear require_mfa on the organization.',
5284+
);
5285+
}
5286+
52365287
/**
52375288
* #2766 V2 — is an email transport wired? The identity import endpoint
52385289
* rejects the invite password policy up front when it isn't, instead of
@@ -5441,11 +5492,13 @@ export class AuthManager {
54415492
const readMustChangeCache = () => this._mustChangeCache;
54425493
const readOrgMfaCache = () => this._orgMfaCache;
54435494
const readConfig = () => this.config;
5444-
const host: Pick<PasswordSessionPolicyHost, '_mustChangeCache' | '_orgMfaCache' | 'config' | 'getDataEngine' | 'refreshMustChangeCacheIfStale' | 'refreshOrgMfaCacheIfStale'> = {
5495+
const host: Pick<PasswordSessionPolicyHost, '_mustChangeCache' | '_orgMfaCache' | 'config' | 'getDataEngine' | 'isTwoFactorEnabled' | 'noteMfaRequirementWithoutEnrollment' | 'refreshMustChangeCacheIfStale' | 'refreshOrgMfaCacheIfStale'> = {
54455496
get _mustChangeCache() { return readMustChangeCache(); },
54465497
get _orgMfaCache() { return readOrgMfaCache(); },
54475498
get config() { return readConfig(); },
54485499
getDataEngine: (...a) => this.getDataEngine(...a),
5500+
isTwoFactorEnabled: (...a) => this.isTwoFactorEnabled(...a),
5501+
noteMfaRequirementWithoutEnrollment: (...a) => this.noteMfaRequirementWithoutEnrollment(...a),
54495502
refreshMustChangeCacheIfStale: (...a) => this.refreshMustChangeCacheIfStale(...a),
54505503
refreshOrgMfaCacheIfStale: (...a) => this.refreshOrgMfaCacheIfStale(...a),
54515504
};

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ import {
6868
} from './identity-write-guard.js';
6969
import { registerLastAdminGuard } from './last-admin-guard.js';
7070
import { registerApiKeyRestoreGuard } from './api-key-restore-guard.js';
71+
import { registerOrganizationMfaEnrollmentGuard } from './organization-mfa-enrollment-guard.js';
7172
import { registerPersonalViewHooks } from './personal-view-hooks.js';
7273
import { registerUserPreferenceHooks } from './user-preference-hooks.js';
7374
import { personalViewCallerResolver, registerPersonalViewRoutes, PERSONAL_VIEW_REMOVE_ROUTE, type PersonalViewEngine } from './personal-view-routes.js';
@@ -1878,6 +1879,14 @@ export class AuthPlugin implements Plugin {
18781879
packageId: 'com.objectstack.plugin-auth.api-key-restore-guard',
18791880
logger: ctx.logger,
18801881
});
1882+
// [#30201] ADR-0069 D3 — an organization's `require_mfa` is refused
1883+
// while nobody can enroll a second factor, the pairing the global
1884+
// `auth.mfa_required` switch gets from its settings piece below. Asks
1885+
// the live manager per write. See organization-mfa-enrollment-guard.ts.
1886+
registerOrganizationMfaEnrollmentGuard(engine, {
1887+
packageId: 'com.objectstack.plugin-auth.organization-mfa-enrollment-guard',
1888+
isTwoFactorEnabled: () => this.authManager?.isTwoFactorEnabled() ?? false,
1889+
});
18811890
// A reader's own named list views: the body is judged on every save as
18821891
// a ListView for the row's own object. See personal-view-hooks.ts.
18831892
registerPersonalViewHooks(engine, {
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#30201] An organization cannot require multi-factor authentication while
5+
* nobody can enroll a second factor (ADR-0069 D3).
6+
*
7+
* ## The dead end this closes
8+
*
9+
* `sys_organization.require_mfa` is a generically editable extension column
10+
* (`MANAGED_EXTENSION_EDITABLE_FIELDS`): an administrator ticks it on the
11+
* organization's edit form and it saves. The per-user MFA gate then holds every
12+
* unenrolled member once their grace period ends (`resolveUserAuthGates`,
13+
* `MFA_REQUIRED`). The only way to enroll is better-auth's `twoFactor` plugin
14+
* (`/two-factor/*`), which is off by default; on such a deployment the held
15+
* member was sent to enroll and the enrollment endpoint answered 404. Every
16+
* member, the owner included, was locked out, and nobody could undo it from
17+
* inside the product, because Setup sits behind the same gate.
18+
*
19+
* The global switch never had this hole: the `auth.mfa_required` setting
20+
* applies the requirement and the plugin as ONE piece (`auth-plugin.ts`, the
21+
* settings binding), so the requirement is never in force without its
22+
* enrollment path. The organization column had no such pairing.
23+
*
24+
* ## Why the write is refused rather than paired
25+
*
26+
* The plugin's switch is process configuration — the settings pass and the
27+
* `OS_AUTH_TWO_FACTOR` env var, re-applied at every boot — and an organization
28+
* row is data. Turning the plugin on from an organization write would hold in
29+
* the process that took the write only: it would not survive a restart or
30+
* reach another node, because nothing that builds the plugin list reads
31+
* organization rows. And turning it off again when the last organization
32+
* clears the column would silently drop the second factor of every member who
33+
* enrolled. So the card's own fallback is taken: the save is refused, and says
34+
* why and what to do.
35+
*
36+
* ## The rule
37+
*
38+
* A write to `sys_organization` whose payload sets `require_mfa` to anything
39+
* but an explicit off value is refused while {@link
40+
* OrganizationMfaEnrollmentGuardOptions.isTwoFactorEnabled} answers false —
41+
* `400 VALIDATION_FAILED` with one `fields[]` entry, `require_mfa` /
42+
* `invalid_value` (the closed ADR-0114 catalog), built by `validationFailure`.
43+
* Clearing the column, writing other columns, and every write while two-factor
44+
* is on pass untouched.
45+
*
46+
* Judged for EVERY write context, the system's included, like the last-admin
47+
* guard: the lockout does not depend on who wrote the row. And judged on the
48+
* payload, not on the stored row, so it covers the by-id path, a multi-row
49+
* update (whose per-row contexts share one payload) and an insert alike; a
50+
* form that re-sends `require_mfa: true` for a row stored before this guard is
51+
* told the requirement is not enforceable, which is true.
52+
*
53+
* Rows stored before this guard are not touched. The gate itself does not
54+
* enforce a requirement nobody can comply with (`resolveUserAuthGates`), so
55+
* such a row locks no one out; it starts holding members, with a fresh grace
56+
* window, once two-factor is turned on.
57+
*/
58+
59+
import { SystemObjectName } from '@objectstack/spec/system';
60+
import { validationFailure } from '@objectstack/types';
61+
62+
/** After the ADR-0092 D2 identity write guard (10), before default-priority hooks (100). */
63+
export const ORGANIZATION_MFA_ENROLLMENT_GUARD_PRIORITY = 15;
64+
65+
export const REQUIRE_MFA_FIELD = 'require_mfa';
66+
67+
export interface OrganizationMfaEnrollmentGuardOptions {
68+
packageId: string;
69+
/**
70+
* Can a user enroll a second factor right now — is the twoFactor plugin
71+
* wired? Read per write (`AuthManager.isTwoFactorEnabled`, the same answer
72+
* the plugin list and `features.twoFactor` give), so a settings pass that
73+
* turns the plugin on admits the next write.
74+
*/
75+
isTwoFactorEnabled: () => boolean;
76+
}
77+
78+
/** The engine surface this guard uses. */
79+
export interface OrganizationMfaEnrollmentGuardEngine {
80+
registerHook(
81+
event: string,
82+
handler: (ctx: any) => Promise<void>,
83+
options?: { object?: string; priority?: number; packageId?: string },
84+
): void;
85+
}
86+
87+
/**
88+
* The values that leave the requirement off. Anything else a payload carries
89+
* for the column — `true`, `1`, `'true'`, or a value the engine would refuse
90+
* later anyway — is judged as turning it on, so the guard never admits a value
91+
* the gate could read as a requirement.
92+
*/
93+
const OFF_VALUES: ReadonlySet<unknown> = new Set([false, 0, '0', 'false', null, undefined]);
94+
95+
/** True when `value`, written to `require_mfa`, turns the requirement on. */
96+
export function turnsMfaRequirementOn(value: unknown): boolean {
97+
if (typeof value === 'string') return !OFF_VALUES.has(value.trim().toLowerCase());
98+
return !OFF_VALUES.has(value);
99+
}
100+
101+
/** The refusal: what was refused, why, who it would have locked out, and the two ways forward. */
102+
export function organizationMfaWithoutEnrollmentRefusal(): Error {
103+
const message =
104+
'This organization cannot require multi-factor authentication yet: two-factor enrollment is off on this ' +
105+
'deployment, so once the grace period ended every member, the owner included, would be blocked with no way ' +
106+
'to enroll an authenticator app. Turn two-factor on first, then require it here: set OS_AUTH_TWO_FACTOR=true ' +
107+
'on the deployment, or turn on the auth.mfa_required setting, which requires multi-factor authentication for ' +
108+
'every organization and turns enrollment on with it.';
109+
return validationFailure(message, [{ field: REQUIRE_MFA_FIELD, code: 'invalid_value', message }]);
110+
}
111+
112+
/** Register the guard's insert and update hooks on `sys_organization`. */
113+
export function registerOrganizationMfaEnrollmentGuard(
114+
engine: OrganizationMfaEnrollmentGuardEngine,
115+
opts: OrganizationMfaEnrollmentGuardOptions,
116+
): void {
117+
const judge = async (ctx: any): Promise<void> => {
118+
const data = ctx?.input?.data as Record<string, unknown> | undefined;
119+
if (!data || typeof data !== 'object' || !(REQUIRE_MFA_FIELD in data)) return;
120+
if (!turnsMfaRequirementOn(data[REQUIRE_MFA_FIELD])) return;
121+
if (opts.isTwoFactorEnabled()) return;
122+
throw organizationMfaWithoutEnrollmentRefusal();
123+
};
124+
const options = {
125+
object: SystemObjectName.ORGANIZATION,
126+
priority: ORGANIZATION_MFA_ENROLLMENT_GUARD_PRIORITY,
127+
packageId: opts.packageId,
128+
};
129+
engine.registerHook('beforeInsert', judge, options);
130+
engine.registerHook('beforeUpdate', judge, options);
131+
}

0 commit comments

Comments
 (0)