|
| 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