From e003c2244de94d0477fab2118da0c68e101ec912 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:17:51 +0000 Subject: [PATCH 1/4] fix(plugin-auth): auth settings read the deployment's declaration for every key it states; sign-up forced off is stated Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../plugins/plugin-auth/src/auth-plugin.ts | 42 +++++-- .../src/auth-settings-declared-defaults.ts | 118 ++++++++++++++++-- .../src/auth-settings-live-status.ts | 108 +++++++++++++++- 3 files changed, 247 insertions(+), 21 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 05a83a06bd9..d3b607246aa 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -159,7 +159,12 @@ import { ssoProviderDeleteRefusal, type SignInMethodFloorDeps, } from './sign-in-method-floor.js'; -import { describeEmailPasswordLiveStatus, type AuthLiveStatus } from './auth-settings-live-status.js'; +import { + combineAuthLiveStatus, + describeEmailPasswordLiveStatus, + describeSignUpLiveStatus, + type AuthLiveStatus, +} from './auth-settings-live-status.js'; import { registerAuthDeclaredDefaults } from './auth-settings-declared-defaults.js'; import { judgePlatformAdmin, judgeHeldSession, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js'; import { @@ -3192,9 +3197,10 @@ export class AuthPlugin implements Plugin { let pass: Promise = Promise.resolve(); const runPass = (): Promise => (pass = applySettings()); - // Setup → Authentication states what runs when the switch says otherwise: - // a value stored on that a cloud-managed runtime does not apply, or any - // other disagreement. See auth-settings-live-status.ts. + // Setup → Authentication states what runs when a switch says otherwise: + // email and password stored on that a cloud-managed runtime does not + // apply, or any other disagreement; sign-up stored on where the + // deployment forces it off. See auth-settings-live-status.ts. if (typeof settings.registerLiveStatus === 'function') { const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager); try { @@ -3202,18 +3208,30 @@ export class AuthPlugin implements Plugin { await pass; const manager = this.authManager; if (!manager) return undefined; - return describeEmailPasswordLiveStatus({ - running: manager.getPublicConfig().emailPassword.enabled, - shown: await settings.get('auth', 'email_password_enabled', pageCtx), - heldOffByHost: emailPasswordHeldOffByHost(floorDeps), - locale, - }); + const running = manager.getPublicConfig().emailPassword; + const emailPasswordShown = await settings.get('auth', 'email_password_enabled', pageCtx); + return combineAuthLiveStatus([ + describeEmailPasswordLiveStatus({ + running: running.enabled, + shown: emailPasswordShown, + heldOffByHost: emailPasswordHeldOffByHost(floorDeps), + locale, + }), + describeSignUpLiveStatus({ + running: !running.disableSignUp, + shown: await settings.get('auth', 'signup_enabled', pageCtx), + forcedOff: manager.resolveDisableSignUp(false), + emailPasswordShown, + locale, + }), + ]); }); } catch (err: any) { ctx.logger.warn( '[auth] Setup → Authentication: the live status was NOT registered ' - + `(${String(err?.message ?? err)}), so where a saved email and password value is not what runs ` - + '(a cloud-managed environment holding it off), the page shows the switch on with nothing saying it is off.', + + `(${String(err?.message ?? err)}), so where a saved email and password or sign-up value is not what ` + + 'runs (a cloud-managed or single-sign-on-only environment holding it off), the page shows the switch on ' + + 'with nothing saying it is off.', ); } } diff --git a/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts b/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts index e6649831ba0..09c0513b2e9 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts @@ -16,9 +16,12 @@ * service answers it at the bottom of the cascade, still `source: 'default'` * (nothing is stored), and a stored value or an `OS_*` override still wins. * - * Only the keys whose declaration can differ from their manifest default - * through a value the deployment itself states, each computed through the - * formula the running config answers with, so the two cannot disagree: + * Every key whose running value is taken from a value the deployment itself + * states, each computed through the formula the running config answers with, + * so the two cannot disagree. Measured key by key on a real `AuthPlugin`: + * with nothing declared each formula answers the manifest default (or nothing, + * for a key with no manifest default), so a deployment that declares nothing + * reads as before; with a declaration, the switch reads it. * * - `email_password_enabled` (manifest `true`): `emailAndPassword.enabled`, * on unless declared `false` (`getPublicConfig().emailPassword.enabled`). @@ -30,14 +33,48 @@ * `emailAndPassword.requireEmailVerification` under the audience posture in * force (`resolveEmailVerificationRequirement`) — on under `email_domain`, * on under `open` unless declared `false`. + * - The password, MFA, API-key, session, network and lockout keys, the + * membership policy and the audience trio: the declared option the manager + * reads, through the manager's own default and clamp where it has one + * ({@link AUTH_DECLARED_DEFAULTS} names the reader each mirrors). + * + * Each answer is in the shape the key's specifier takes: days for a session + * lifetime the manager holds in seconds, one entry per line for a list the + * console edits as a textarea, and a select's value only when it is one of + * the select's options (an off-vocabulary declaration answers nothing, so the + * manifest default stands, rather than serving a value the page cannot offer). + * + * Not declared here, by design: + * + * - `rate_limit_max` / `rate_limit_window_seconds`: with nothing stored the + * sign-in, sign-up and password-reset endpoints run on the auth library's + * own per-path rules (and its production-only switch), or a declared + * `rateLimit` that is not the per-endpoint cap the setting writes, so no + * one number states what runs. + * - `api_key_policy_started_at`: recorded into the store by the first boot + * that runs the policy, so it is not left unstored. + * - `google_enabled`: an intent toggle whose runtime default is the manifest + * default (on); a Google button needs it and both credentials. + * - `google_client_id` / `google_client_secret`: a credential declared in the + * server configuration outranks a saved one, so it is not the value a + * clear returns to, and a secret is never served as a default. * * Asked by the settings service on each read, never recorded here, so a * posture change or a host flag is followed at once. */ +import { + API_KEY_DEFAULT_EXPIRY_DAYS, + API_KEY_INACTIVITY_DAYS, + API_KEY_MAX_EXPIRY_DAYS, +} from '@objectstack/core'; import type { AudiencePosture } from '@objectstack/spec/system'; -import { resolveEmailVerificationRequirement } from './audience-posture.js'; +import { resolveAudience, resolveEmailVerificationRequirement } from './audience-posture.js'; +import { readBooleanEnv } from './auth-manager.js'; +import { resolveMfaGracePeriodDays } from './auth-manager-password-session-policy.js'; import type { DeclaredAuthOptions } from './auth-settings-declared.js'; +import { isMfaRequirementLevel } from './organization-access-policy.js'; +import { isMembershipPolicy } from './reconcile-membership.js'; /** What a declared default is computed from, all read when asked. */ export interface AuthDeclaredDefaultFacts { @@ -49,8 +86,23 @@ export interface AuthDeclaredDefaultFacts { audiencePosture(): AudiencePosture; } -/** Each key's declared default, by key. */ -export const AUTH_DECLARED_DEFAULTS: Readonly boolean>> = { +/** A non-empty list as the console's textarea holds it (one entry per line), else nothing declared. */ +function asLines(list: readonly string[] | undefined): string | undefined { + return Array.isArray(list) && list.length > 0 ? list.join('\n') : undefined; +} + +/** `AuthManager#resolveApiKeyLifecyclePolicy`'s reading of one window. */ +function apiKeyDays(value: unknown, fallback: number, min: number): number { + const n = Math.floor(Number(value)); + return Number.isFinite(n) && n >= min ? n : fallback; +} + +/** + * Each key's declared default, by key: what the running config takes for it + * while nothing is stored. `undefined` means the deployment declared nothing + * the specifier can show, and the manifest default stands. + */ +export const AUTH_DECLARED_DEFAULTS: Readonly unknown>> = { email_password_enabled: (facts) => facts.declared().emailAndPassword?.enabled !== false, signup_enabled: (facts) => !facts.resolveDisableSignUp(facts.declared().emailAndPassword?.disableSignUp), require_email_verification: (facts) => @@ -58,8 +110,60 @@ export const AUTH_DECLARED_DEFAULTS: Readonly numberOrUndefined(facts.declared().emailAndPassword?.minPasswordLength), + password_max_length: (facts) => numberOrUndefined(facts.declared().emailAndPassword?.maxPasswordLength), + // `AuthManager#getMembershipPolicy`. + membership_policy: (facts) => { + const declared = facts.declared().membershipPolicy ?? 'auto'; + return isMembershipPolicy(declared) ? declared : undefined; + }, + // `buildPluginList`: the deployment env, else the declared flag, else off. + password_reject_breached: (facts) => + readBooleanEnv('OS_AUTH_PASSWORD_REJECT_BREACHED') ?? facts.declared().plugins?.passwordRejectBreached ?? false, + // `assertPasswordComplexity`. + password_require_complexity: (facts) => Boolean(facts.declared().passwordRequireComplexity), + password_min_classes: (facts) => + Math.min(4, Math.max(1, Math.floor(Number(facts.declared().passwordMinClasses) || 3))), + // The password history and expiry policy bodies. + password_history_count: (facts) => Math.floor(Number(facts.declared().passwordHistoryCount) || 0), + password_expiry_days: (facts) => Math.floor(Number(facts.declared().passwordExpiryDays) || 0), + // `AuthManager#getDeploymentAccessFloor`. + mfa_required: (facts) => { + const declared = facts.declared().mfaRequirement ?? 'off'; + return isMfaRequirementLevel(declared) ? declared : undefined; + }, + mfa_grace_period_days: (facts) => resolveMfaGracePeriodDays(facts.declared()), + // `AuthManager#resolveApiKeyLifecyclePolicy` (the ceiling rules the default too). + api_key_default_expiry_days: (facts) => { + const declared = facts.declared(); + const max = apiKeyDays(declared.apiKeyMaxExpiryDays, API_KEY_MAX_EXPIRY_DAYS, 1); + return Math.min(max, apiKeyDays(declared.apiKeyDefaultExpiryDays, API_KEY_DEFAULT_EXPIRY_DAYS, 1)); + }, + api_key_max_expiry_days: (facts) => apiKeyDays(facts.declared().apiKeyMaxExpiryDays, API_KEY_MAX_EXPIRY_DAYS, 1), + api_key_inactivity_days: (facts) => apiKeyDays(facts.declared().apiKeyInactivityDays, API_KEY_INACTIVITY_DAYS, 0), + // The auth instance's `session` block, seconds as days. + session_expiry_days: (facts) => (facts.declared().session?.expiresIn || 60 * 60 * 24 * 7) / 86_400, + session_refresh_days: (facts) => (facts.declared().session?.updateAge || 60 * 60 * 24) / 86_400, + // `AuthManager#getDeploymentAccessFloor`. + session_idle_timeout_minutes: (facts) => facts.declared().sessionIdleTimeoutMinutes ?? 0, + session_absolute_max_hours: (facts) => facts.declared().sessionAbsoluteMaxHours ?? 0, + max_concurrent_sessions_per_user: (facts) => facts.declared().maxConcurrentSessions ?? 0, + allowed_ip_ranges: (facts) => asLines(facts.declared().allowedIpRanges), + // The sign-in lockout bodies. + lockout_threshold: (facts) => Number(facts.declared().lockoutThreshold) || 0, + lockout_duration_minutes: (facts) => Number(facts.declared().lockoutDurationMinutes) || 15, + // `AuthManager#getAudience` (`resolveAudience`): undeclared or off-vocabulary is `invite_only`. + audience_posture: (facts) => resolveAudience(facts.declared().audience).posture, + audience_allowed_email_domains: (facts) => asLines(resolveAudience(facts.declared().audience).allowedEmailDomains), + audience_self_registration_permission_set: (facts) => + resolveAudience(facts.declared().audience).selfRegistrationPermissionSet, }; +function numberOrUndefined(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} + /** The slice of the settings service this needs (structural: no package dependency). */ export interface DeclaredDefaultHost { registerDeclaredDefault?(namespace: string, key: string, provider: () => unknown): void; @@ -85,7 +189,7 @@ export function registerAuthDeclaredDefaults( } catch (err: any) { logger.warn( `[auth] Setup → Authentication: the declared default of auth.${key} was NOT registered ` - + `(${String(err?.message ?? err)}), so with nothing saved that switch shows the console default rather ` + + `(${String(err?.message ?? err)}), so with nothing saved that setting shows the console default rather ` + 'than what this deployment runs.', ); } diff --git a/packages/plugins/plugin-auth/src/auth-settings-live-status.ts b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts index 11d7a879a23..b0e71dff439 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-live-status.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts @@ -14,8 +14,11 @@ import type { SettingsCopyLocale } from './settings-copy-locale.js'; * stored value the runtime does not apply: on a cloud-managed runtime that * holds email and password off (`emailPasswordHeldOffByHost`), a value stored * on shows the switch on for a sign-in method that is off; and any other - * disagreement between the switch and what runs. Those head the page as a - * `warning`. + * disagreement between the switch and what runs. Likewise for + * self-registration: a `signup_enabled` stored on, where the deployment forces + * sign-up off (SSO-only, cloud-managed, `OS_DISABLE_SIGNUP`), shows the switch + * on for a sign-up the runtime does not offer + * ({@link describeSignUpLiveStatus}). Those head the page as a `warning`. * * The settings service's live-status seam (`registerLiveStatus`) is how a page * says what runs beside what is stored; its `values` serve option-bearing keys @@ -52,6 +55,9 @@ export interface AuthLiveStatusCopy { /** Any other disagreement between the switch and what runs. */ differsLabel(running: boolean): string; differsText: string; + /** Self-registration forced off by the deployment, over `signup_enabled` stored on. */ + signupForcedOffLabel: string; + signupForcedOffText: string; } export const AUTH_LIVE_STATUS_COPY: Record = { @@ -63,6 +69,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `Email and password sign-in is ${running ? 'on' : 'off'} in the running system`, differsText: 'The switch below shows the saved setting, which is not what runs right now.', + signupForcedOffLabel: 'Self-registration is off on this environment', + signupForcedOffText: 'This environment\'s deployment turns self-registration off (single sign-on only, a cloud-managed ' + + 'environment, or the server configuration): people join only by invitation or through the identity ' + + 'provider, and the sign-in page offers no sign-up. The switch below does not change that, and a ' + + 'value saved on is not applied.', }, 'zh-CN': { managedOffLabel: '本环境已关闭邮箱/密码登录', @@ -70,6 +81,8 @@ export const AUTH_LIVE_STATUS_COPY: Record `实际运行中邮箱/密码登录为${running ? '开' : '关'}`, differsText: '下方开关显示的是已保存的设置,并非当前实际运行的状态。', + signupForcedOffLabel: '本环境已关闭自助注册', + signupForcedOffText: '本环境的部署关闭了自助注册(仅单点登录、云端托管环境或服务器配置):用户只能通过邀请或身份提供方加入,登录页不提供注册入口。下方开关无法改变这一点,保存为开的值不会生效。', }, 'zh-Hant': { managedOffLabel: '本環境已關閉電子郵件/密碼登入', @@ -77,6 +90,8 @@ export const AUTH_LIVE_STATUS_COPY: Record `實際執行中電子郵件/密碼登入為${running ? '開' : '關'}`, differsText: '下方開關顯示的是已儲存的設定,並非目前實際執行的狀態。', + signupForcedOffLabel: '本環境已關閉自助註冊', + signupForcedOffText: '本環境的部署關閉了自助註冊(僅單一登入、雲端代管環境或伺服器設定):使用者只能透過邀請或身分識別提供者加入,登入頁不提供註冊入口。下方開關無法改變這一點,儲存為開的值不會生效。', }, 'ja-JP': { managedOffLabel: 'この環境ではメール/パスワードによるサインインはオフです', @@ -85,6 +100,10 @@ export const AUTH_LIVE_STATUS_COPY: Record `実行中のシステムではメール/パスワードによるサインインは${running ? 'オン' : 'オフ'}です`, differsText: '下のスイッチは保存済みの設定を表示しており、現在の実際の動作とは異なります。', + signupForcedOffLabel: 'この環境ではセルフ登録はオフです', + signupForcedOffText: 'この環境のデプロイでセルフ登録がオフになっています(シングルサインオンのみ、クラウド管理環境、または' + + 'サーバー構成)。ユーザーは招待または ID プロバイダー経由でのみ参加でき、サインインページに登録の' + + '入口は表示されません。下のスイッチではこれを変更できず、オンで保存された値は適用されません。', }, 'es-ES': { managedOffLabel: 'El inicio de sesión con correo y contraseña está desactivado en este entorno', @@ -95,6 +114,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `El inicio de sesión con correo y contraseña está ${running ? 'activado' : 'desactivado'} en el sistema en ejecución`, differsText: 'El interruptor de abajo muestra el ajuste guardado, que no es lo que se ejecuta ahora mismo.', + signupForcedOffLabel: 'El autorregistro está desactivado en este entorno', + signupForcedOffText: 'La implementación de este entorno desactiva el autorregistro (solo inicio de sesión único, un ' + + 'entorno gestionado en la nube o la configuración del servidor): las personas se unen solo por ' + + 'invitación o mediante el proveedor de identidad, y la página de inicio de sesión no ofrece ' + + 'registro. El interruptor de abajo no cambia eso, y un valor guardado como activado no se aplica.', }, ar: { managedOffLabel: 'تسجيل الدخول بالبريد الإلكتروني وكلمة المرور متوقف في هذه البيئة', @@ -104,6 +128,10 @@ export const AUTH_LIVE_STATUS_COPY: Record `تسجيل الدخول بالبريد الإلكتروني وكلمة المرور ${running ? 'مُفعّل' : 'متوقف'} في النظام قيد التشغيل`, differsText: 'يعرض المفتاح أدناه الإعداد المحفوظ، وهو ليس ما يعمل الآن.', + signupForcedOffLabel: 'التسجيل الذاتي متوقف في هذه البيئة', + signupForcedOffText: 'يُوقف نشر هذه البيئة التسجيل الذاتي (تسجيل الدخول الموحّد فقط، أو بيئة مُدارة سحابيًا، أو إعدادات ' + + 'الخادم): ينضم الأشخاص بدعوة فقط أو عبر موفّر الهوية، ولا تعرض صفحة تسجيل الدخول خيار التسجيل. لا ' + + 'يغيّر المفتاح أدناه ذلك، ولا تُطبَّق القيمة المحفوظة مُفعّلة.', }, fr: { managedOffLabel: 'La connexion par e-mail et mot de passe est désactivée sur cet environnement', @@ -114,6 +142,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `La connexion par e-mail et mot de passe est ${running ? 'activée' : 'désactivée'} dans le système en cours d'exécution`, differsText: 'L\'interrupteur ci-dessous affiche le paramètre enregistré, qui n\'est pas ce qui s\'exécute en ce moment.', + signupForcedOffLabel: 'L\'inscription libre est désactivée sur cet environnement', + signupForcedOffText: 'Le déploiement de cet environnement désactive l\'inscription libre (authentification unique seule, ' + + 'environnement géré dans le cloud ou configuration du serveur) : on ne rejoint que sur invitation ou ' + + 'via le fournisseur d\'identité, et la page de connexion ne propose pas d\'inscription. ' + + 'L\'interrupteur ci-dessous n\'y change rien, et une valeur enregistrée activée n\'est pas appliquée.', }, 'pt-BR': { managedOffLabel: 'O login com e-mail e senha está desativado neste ambiente', @@ -122,6 +155,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `O login com e-mail e senha está ${running ? 'ativado' : 'desativado'} no sistema em execução`, differsText: 'O interruptor abaixo mostra a configuração salva, que não é o que está em execução agora.', + signupForcedOffLabel: 'O autocadastro está desativado neste ambiente', + signupForcedOffText: 'A implantação deste ambiente desativa o autocadastro (somente login único, um ambiente gerenciado ' + + 'na nuvem ou a configuração do servidor): as pessoas entram apenas por convite ou pelo provedor de ' + + 'identidade, e a página de login não oferece cadastro. O interruptor abaixo não muda isso, e um ' + + 'valor salvo como ativado não é aplicado.', }, ru: { managedOffLabel: 'Вход по электронной почте и паролю отключён в этой среде', @@ -131,6 +169,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `В работающей системе вход по электронной почте и паролю ${running ? 'включён' : 'отключён'}`, differsText: 'Переключатель ниже показывает сохранённую настройку, а не то, что работает сейчас.', + signupForcedOffLabel: 'Самостоятельная регистрация отключена в этой среде', + signupForcedOffText: 'Развёртывание этой среды отключает самостоятельную регистрацию (только единый вход, облачная ' + + 'управляемая среда или конфигурация сервера): пользователи присоединяются только по приглашению или ' + + 'через поставщика удостоверений, а страница входа не предлагает регистрацию. Переключатель ниже ' + + 'этого не меняет, а сохранённое значение «включено» не применяется.', }, de: { managedOffLabel: 'Die Anmeldung mit E-Mail und Passwort ist in dieser Umgebung aus', @@ -140,6 +183,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `Die Anmeldung mit E-Mail und Passwort ist im laufenden System ${running ? 'an' : 'aus'}`, differsText: 'Der Schalter unten zeigt die gespeicherte Einstellung, nicht das, was gerade läuft.', + signupForcedOffLabel: 'Die Selbstregistrierung ist in dieser Umgebung aus', + signupForcedOffText: 'Die Bereitstellung dieser Umgebung schaltet die Selbstregistrierung aus (nur Single Sign-on, eine ' + + 'in der Cloud verwaltete Umgebung oder die Serverkonfiguration): Man tritt nur auf Einladung oder ' + + 'über den Identitätsanbieter bei, und die Anmeldeseite bietet keine Registrierung. Der Schalter ' + + 'unten ändert daran nichts, und ein auf an gespeicherter Wert wird nicht angewendet.', }, ko: { managedOffLabel: '이 환경에서는 이메일/비밀번호 로그인이 꺼져 있습니다', @@ -148,6 +196,11 @@ export const AUTH_LIVE_STATUS_COPY: Record `실행 중인 시스템에서 이메일/비밀번호 로그인이 ${running ? '켜져' : '꺼져'} 있습니다`, differsText: '아래 스위치는 저장된 설정을 표시하며, 현재 실제로 동작하는 상태와 다릅니다.', + signupForcedOffLabel: '이 환경에서는 자체 가입이 꺼져 있습니다', + signupForcedOffText: '이 환경의 배포에서 자체 가입이 꺼져 있습니다(싱글 사인온 전용, 클라우드 관리 환경 또는' + + ' 서버 구성). 사용자는 초대 또는 ID 공급자를 통해서만 참여할 수 있으며, 로그인 페이' + + '지에는 가입 입구가 표시되지 않습니다. 아래 스위치로는 이를 바꿀 수 없으며, 켜짐으로 저' + + '장된 값은 적용되지 않습니다.', }, }; @@ -181,3 +234,54 @@ export function describeEmailPasswordLiveStatus(input: EmailPasswordLiveInput): } return { label: copy.differsLabel(input.running), bannerText: copy.differsText, bannerSeverity: 'warning' }; } + +/** What the self-registration statement is judged from, all read on the page request. */ +export interface SignUpLiveInput { + /** Whether self-registration runs: `!getPublicConfig().emailPassword.disableSignUp`. */ + running: boolean; + /** `auth.signup_enabled` as the page reads it (`SettingsService.get`). */ + shown: { value?: unknown; source?: string } | undefined; + /** + * Whether the deployment turns self-registration off whatever is saved + * (`AuthManager.resolveDisableSignUp(false)`: SSO-only, cloud-managed, or + * `OS_DISABLE_SIGNUP`). + */ + forcedOff: boolean; + /** `auth.email_password_enabled` as the page reads it: the switch is shown only while it is not off. */ + emailPasswordShown: { value?: unknown } | undefined; + /** The caller's display language; a language with no entry is answered in English. */ + locale?: string; +} + +/** + * The self-registration statement, or `undefined` when there is nothing the + * switch does not already say. With nothing stored the switch reads the + * declaration, which already folds in a forced off + * (`auth-settings-declared-defaults.ts`); what it cannot say is a value + * stored on that the deployment overrides: the settings pass applies it and + * the runtime still forces sign-up off. Stated only while the switch is on + * the page (it is hidden while email and password is off). + */ +export function describeSignUpLiveStatus(input: SignUpLiveInput): AuthLiveStatus | undefined { + if (shownToggle(input.emailPasswordShown?.value) === false) return undefined; + if (!input.forcedOff || input.running || !shownToggle(input.shown?.value)) return undefined; + const copy = authLiveStatusCopy(input.locale); + return { label: copy.signupForcedOffLabel, bannerText: copy.signupForcedOffText, bannerSeverity: 'warning' }; +} + +/** + * One banner heads the page (the settings service takes one statement per + * namespace): the first statement's title, every statement's body in order. + * `undefined` when there is nothing to state. + */ +export function combineAuthLiveStatus( + statements: ReadonlyArray, +): AuthLiveStatus | undefined { + const present = statements.filter((statement): statement is AuthLiveStatus => statement !== undefined); + if (present.length <= 1) return present[0]; + return { + label: present[0].label, + bannerText: present.map((statement) => `**${statement.label}.** ${statement.bannerText}`).join('\n\n'), + bannerSeverity: present.some((statement) => statement.bannerSeverity === 'warning') ? 'warning' : 'info', + }; +} From db53f2a2d74830552affabcc93364022b7a00c57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:20:34 +0000 Subject: [PATCH 2/4] test(plugin-auth): pin every declared auth key against the running config, and the forced-off sign-up statement Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../src/auth-settings-live-status.test.ts | 476 ++++++++++++++---- 1 file changed, 376 insertions(+), 100 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts index a92c7be2186..59aeea17129 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts @@ -38,118 +38,131 @@ import { } from '@objectstack/service-settings'; import { AuthPlugin } from './auth-plugin.js'; import type { AuthManager } from './auth-manager.js'; -import { AUTH_LIVE_STATUS_COPY, describeEmailPasswordLiveStatus } from './auth-settings-live-status.js'; +import { + AUTH_LIVE_STATUS_COPY, + combineAuthLiveStatus, + describeEmailPasswordLiveStatus, + describeSignUpLiveStatus, +} from './auth-settings-live-status.js'; +import { AUTH_SETTING_RESTORE } from './auth-settings-declared.js'; const SECRET = 'test-secret-at-least-32-chars-long'; const ADMIN = { enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }; -const ENV_KEYS = ['OS_CLOUD_MANAGED', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_SSO_ONLY', 'OS_DISABLE_SIGNUP'] as const; +const ENV_KEYS = [ + 'OS_CLOUD_MANAGED', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_SSO_ONLY', 'OS_DISABLE_SIGNUP', + 'OS_AUTH_SIGNUP_ENABLED', 'OS_AUTH_PASSWORD_REJECT_BREACHED', +] as const; -describe('Setup → Authentication shows the auth switches as they run', () => { - const savedEnv: Partial> = {}; +/** Boot as a host does (init → start → kernel:ready), with email and password declared as given. */ +const boot = async (opts: { + emailPassword?: boolean; + emailAndPassword?: Record; + audience?: Record; + hostSignInHandoff?: boolean; + settings?: SettingsService; + /** Further plugin options, as a deployment declares them. */ + declare?: Record; +} = {}) => { + const settings = opts.settings ?? new SettingsService({ env: {} }); + if (!opts.settings) settings.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); + const hooks = new Map Promise>>(); + const ctx = { + registerService: vi.fn(), + getService: vi.fn((name: string) => { + if (name === 'manifest') return { register: vi.fn() }; + if (name === 'settings') return settings; + return undefined; + }), + getServices: vi.fn(() => new Map()), + hook: vi.fn((name: string, handler: () => Promise) => { + hooks.set(name, [...(hooks.get(name) ?? []), handler]); + }), + trigger: vi.fn(), + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(), + } as unknown as PluginContext; + const plugin = new AuthPlugin({ + secret: SECRET, + baseUrl: 'http://localhost:3000', + ...(opts.emailPassword === undefined && !opts.emailAndPassword ? {} : { + emailAndPassword: { + ...(opts.emailPassword === undefined ? {} : { enabled: opts.emailPassword }), + ...opts.emailAndPassword, + }, + }), + ...(opts.audience ? { audience: opts.audience } : {}), + ...(opts.hostSignInHandoff ? { hostSignInHandoff: true } : {}), + ...opts.declare, + } as ConstructorParameters[0]); + await plugin.init(ctx); + const manager = (ctx.registerService as any).mock.calls.find(([name]: [string]) => name === 'auth')?.[1] as AuthManager; + await plugin.start(ctx); + for (const handler of hooks.get('kernel:ready') ?? []) await handler(); + return { settings, manager }; +}; - const setManaged = (on: boolean) => { - if (on) process.env.OS_CLOUD_MANAGED = '1'; - else delete process.env.OS_CLOUD_MANAGED; - // `isCloudManaged()` memoizes its first read. - resetCloudManagedForTesting(); +/** `GET /api/settings/auth` through the real settings route: the page's own read. */ +const readPage = async (settings: SettingsService, headers: Record = {}) => { + const routes = new Map(); + const add = (method: string) => (path: string, handler: RouteHandler) => { + routes.set(`${method} ${path}`, handler); + return http; }; + const http = { + get: add('GET'), post: add('POST'), put: add('PUT'), delete: add('DELETE'), patch: add('PATCH'), + use: () => http, listen: async () => {}, close: async () => {}, getInstance: () => null, + } as unknown as IHttpServer; + registerSettingsRoutes(http, settings, { contextFromRequest: () => ({ ...ADMIN }) }); + const state: { status: number; body?: any } = { status: 200 }; + const res = { + json: vi.fn((data: unknown) => { state.body = data; }), + send: vi.fn(), + status: vi.fn((code: number) => { state.status = code; return res; }), + header: vi.fn(() => res), + } as unknown as IHttpResponse; + const req = { + params: { namespace: 'auth' }, query: {}, headers, method: 'GET', path: '/api/settings/auth', + } as unknown as IHttpRequest; + await routes.get('GET /api/settings/:namespace')!(req, res); + expect(state.status).toBe(200); + const page = state.body?.data ?? state.body; + const banner = (page.manifest.specifiers as Array>) + .find((spec) => spec.id === SETTINGS_LIVE_STATUS_BANNER_ID); + return { page, banner }; +}; - beforeEach(() => { - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key]; - delete process.env[key]; - } - setManaged(false); - }); +const passwordOn = (manager: AuthManager) => manager.getPublicConfig().emailPassword.enabled; +/** Let the settings pass a write's change event started run to its end. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); - afterEach(() => { - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) delete process.env[key]; - else process.env[key] = savedEnv[key]; - } - resetCloudManagedForTesting(); - vi.restoreAllMocks(); - }); +// Every case in this file starts from a clean auth env and a fresh cloud-managed read. +const savedEnv: Partial> = {}; - /** Boot as a host does (init → start → kernel:ready), with email and password declared as given. */ - const boot = async (opts: { - emailPassword?: boolean; - emailAndPassword?: Record; - audience?: Record; - hostSignInHandoff?: boolean; - settings?: SettingsService; - } = {}) => { - const settings = opts.settings ?? new SettingsService({ env: {} }); - if (!opts.settings) settings.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); - const hooks = new Map Promise>>(); - const ctx = { - registerService: vi.fn(), - getService: vi.fn((name: string) => { - if (name === 'manifest') return { register: vi.fn() }; - if (name === 'settings') return settings; - return undefined; - }), - getServices: vi.fn(() => new Map()), - hook: vi.fn((name: string, handler: () => Promise) => { - hooks.set(name, [...(hooks.get(name) ?? []), handler]); - }), - trigger: vi.fn(), - logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, - getKernel: vi.fn(), - } as unknown as PluginContext; - const plugin = new AuthPlugin({ - secret: SECRET, - baseUrl: 'http://localhost:3000', - ...(opts.emailPassword === undefined && !opts.emailAndPassword ? {} : { - emailAndPassword: { - ...(opts.emailPassword === undefined ? {} : { enabled: opts.emailPassword }), - ...opts.emailAndPassword, - }, - }), - ...(opts.audience ? { audience: opts.audience } : {}), - ...(opts.hostSignInHandoff ? { hostSignInHandoff: true } : {}), - }); - await plugin.init(ctx); - const manager = (ctx.registerService as any).mock.calls.find(([name]: [string]) => name === 'auth')?.[1] as AuthManager; - await plugin.start(ctx); - for (const handler of hooks.get('kernel:ready') ?? []) await handler(); - return { settings, manager }; - }; +const setManaged = (on: boolean) => { + if (on) process.env.OS_CLOUD_MANAGED = '1'; + else delete process.env.OS_CLOUD_MANAGED; + // `isCloudManaged()` memoizes its first read. + resetCloudManagedForTesting(); +}; - /** `GET /api/settings/auth` through the real settings route: the page's own read. */ - const readPage = async (settings: SettingsService, headers: Record = {}) => { - const routes = new Map(); - const add = (method: string) => (path: string, handler: RouteHandler) => { - routes.set(`${method} ${path}`, handler); - return http; - }; - const http = { - get: add('GET'), post: add('POST'), put: add('PUT'), delete: add('DELETE'), patch: add('PATCH'), - use: () => http, listen: async () => {}, close: async () => {}, getInstance: () => null, - } as unknown as IHttpServer; - registerSettingsRoutes(http, settings, { contextFromRequest: () => ({ ...ADMIN }) }); - const state: { status: number; body?: any } = { status: 200 }; - const res = { - json: vi.fn((data: unknown) => { state.body = data; }), - send: vi.fn(), - status: vi.fn((code: number) => { state.status = code; return res; }), - header: vi.fn(() => res), - } as unknown as IHttpResponse; - const req = { - params: { namespace: 'auth' }, query: {}, headers, method: 'GET', path: '/api/settings/auth', - } as unknown as IHttpRequest; - await routes.get('GET /api/settings/:namespace')!(req, res); - expect(state.status).toBe(200); - const page = state.body?.data ?? state.body; - const banner = (page.manifest.specifiers as Array>) - .find((spec) => spec.id === SETTINGS_LIVE_STATUS_BANNER_ID); - return { page, banner }; - }; +beforeEach(() => { + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } + setManaged(false); +}); - const passwordOn = (manager: AuthManager) => manager.getPublicConfig().emailPassword.enabled; - /** Let the settings pass a write's change event started run to its end. */ - const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); +afterEach(() => { + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } + resetCloudManagedForTesting(); + vi.restoreAllMocks(); +}); +describe('Setup → Authentication shows the auth switches as they run', () => { it('declared off with nothing stored: the switch reads the declaration, and the page states nothing', async () => { const { settings, manager } = await boot({ emailPassword: false }); expect(passwordOn(manager)).toBe(false); @@ -290,6 +303,237 @@ describe('Setup → Authentication shows the auth switches as they run', () => { }); }); +/** + * Every other key the settings pass applies, measured against the running + * config: a deployment that declares a value reads it with nothing stored + * (`AUTH_DECLARED_DEFAULTS`), and one that declares nothing reads the manifest + * default as before. + */ +describe('Setup → Authentication reads every declared auth key as it runs', () => { + /** One deployment declaring a non-default value for every key the module states. */ + const DECLARED = { + emailAndPassword: { minPasswordLength: 12, maxPasswordLength: 64 }, + membershipPolicy: 'invite-only', + plugins: { passwordRejectBreached: true }, + passwordRequireComplexity: true, + passwordMinClasses: 2, + passwordHistoryCount: 5, + passwordExpiryDays: 90, + mfaRequirement: 'administrators', + mfaGracePeriodDays: 3, + apiKeyDefaultExpiryDays: 30, + apiKeyMaxExpiryDays: 180, + apiKeyInactivityDays: 0, + session: { expiresIn: 30 * 86_400, updateAge: 2 * 86_400 }, + sessionIdleTimeoutMinutes: 30, + sessionAbsoluteMaxHours: 12, + maxConcurrentSessions: 3, + allowedIpRanges: ['10.0.0.0/8', '192.168.1.1'], + lockoutThreshold: 5, + lockoutDurationMinutes: 30, + audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com', 'b.io'], selfRegistrationPermissionSet: 'member_default' }, + // Declared too, and deliberately NOT stated (see the module): the settings keep the manifest default. + rateLimit: { enabled: true, window: 120, max: 5 }, + socialProviders: { google: { clientId: 'declared-client', clientSecret: 'declared-secret' } }, + }; + + /** What each key reads with nothing stored on that deployment. */ + const EXPECTED: Record = { + password_min_length: 12, + password_max_length: 64, + membership_policy: 'invite-only', + password_reject_breached: true, + password_require_complexity: true, + password_min_classes: 2, + password_history_count: 5, + password_expiry_days: 90, + mfa_required: 'administrators', + mfa_grace_period_days: 3, + api_key_default_expiry_days: 30, + api_key_max_expiry_days: 180, + api_key_inactivity_days: 0, + session_expiry_days: 30, + session_refresh_days: 2, + session_idle_timeout_minutes: 30, + session_absolute_max_hours: 12, + max_concurrent_sessions_per_user: 3, + allowed_ip_ranges: '10.0.0.0/8\n192.168.1.1', + lockout_threshold: 5, + lockout_duration_minutes: 30, + audience_posture: 'email_domain', + audience_allowed_email_domains: 'acme.com\nb.io', + audience_self_registration_permission_set: 'member_default', + }; + + /** The value the running config takes for each key, read off the manager as the enforcement reads it. */ + const running = (manager: AuthManager): Record => { + const config = (manager as any).config; + const floor = manager.getDeploymentAccessFloor(); + const apiKeys = manager.resolveApiKeyLifecyclePolicy(); + const audience = manager.getAudience(); + return { + password_min_length: config.emailAndPassword?.minPasswordLength, + password_max_length: config.emailAndPassword?.maxPasswordLength, + membership_policy: manager.getMembershipPolicy(), + password_reject_breached: config.plugins?.passwordRejectBreached, + password_require_complexity: config.passwordRequireComplexity, + password_min_classes: config.passwordMinClasses, + password_history_count: config.passwordHistoryCount, + password_expiry_days: config.passwordExpiryDays, + mfa_required: floor.mfaRequirement, + mfa_grace_period_days: manager.getMfaGracePeriodDays(), + api_key_default_expiry_days: apiKeys.defaultExpiryDays, + api_key_max_expiry_days: apiKeys.maxExpiryDays, + api_key_inactivity_days: apiKeys.inactivityDays, + session_expiry_days: config.session.expiresIn / 86_400, + session_refresh_days: config.session.updateAge / 86_400, + session_idle_timeout_minutes: floor.sessionIdleTimeoutMinutes, + session_absolute_max_hours: floor.sessionAbsoluteMaxHours, + max_concurrent_sessions_per_user: floor.maxConcurrentSessions, + allowed_ip_ranges: floor.allowedIpRanges.join('\n'), + lockout_threshold: config.lockoutThreshold, + lockout_duration_minutes: config.lockoutDurationMinutes, + audience_posture: audience.posture, + audience_allowed_email_domains: audience.allowedEmailDomains.join('\n'), + audience_self_registration_permission_set: audience.selfRegistrationPermissionSet, + }; + }; + + const manifestDefault = (key: string): unknown => { + const spec = builtinSettingsManifests.find((m) => m.namespace === 'auth')!.specifiers + .find((candidate) => (candidate as { key?: string }).key === key) as { default?: unknown } | undefined; + return spec?.default ?? null; + }; + + it('declared: each key reads what runs, as source default, through get and the page route', async () => { + const { settings, manager } = await boot({ declare: DECLARED }); + const runs = running(manager); + const { page, banner } = await readPage(settings); + for (const [key, expected] of Object.entries(EXPECTED)) { + expect(runs[key], `running ${key}`).toEqual(expected); + expect(expected, `${key} differs from its manifest default`).not.toEqual(manifestDefault(key)); + expect(await settings.get('auth', key), key).toMatchObject({ value: expected, source: 'default' }); + expect(page.values[key], `page ${key}`).toMatchObject({ value: expected, source: 'default' }); + } + expect(banner).toBeUndefined(); + }); + + it('CONTROL: the keys not stated keep the manifest default, declared or not', async () => { + const { settings, manager } = await boot({ declare: DECLARED }); + expect((manager as any).config.rateLimit).toMatchObject({ window: 120, max: 5 }); + for (const key of ['rate_limit_max', 'rate_limit_window_seconds', 'google_enabled', 'google_client_id', 'google_client_secret']) { + expect((await settings.get('auth', key)).value ?? null, key).toEqual(manifestDefault(key)); + } + }); + + it('CONTROL: nothing declared, every auth key reads its manifest default', async () => { + const { settings } = await boot(); + const keys = Object.keys(AUTH_SETTING_RESTORE).filter((key) => key !== 'api_key_policy_started_at'); + for (const key of keys) { + const resolved = await settings.get('auth', key); + expect(resolved.source, key).toBe('default'); + expect(resolved.value ?? null, key).toEqual(manifestDefault(key)); + } + }); + + it('CONTROL: a declaration equal to the manifest default reads the same value', async () => { + const { settings } = await boot({ + declare: { membershipPolicy: 'auto', lockoutDurationMinutes: 15, session: { expiresIn: 7 * 86_400 } }, + }); + expect(await settings.get('auth', 'membership_policy')).toMatchObject({ value: 'auto', source: 'default' }); + expect(await settings.get('auth', 'lockout_duration_minutes')).toMatchObject({ value: 15, source: 'default' }); + expect(await settings.get('auth', 'session_expiry_days')).toMatchObject({ value: 7, source: 'default' }); + }); + + it('a declaration the select cannot offer answers nothing, so the manifest default stands', async () => { + const { settings, manager } = await boot({ declare: { membershipPolicy: 'everyone' } }); + expect(manager.getMembershipPolicy()).toBe('everyone'); + expect(await settings.get('auth', 'membership_policy')).toMatchObject({ value: 'auto', source: 'default' }); + }); + + it('a stored value still wins, and a clear returns to the declaration', async () => { + const { settings, manager } = await boot({ declare: { lockoutThreshold: 5 } }); + await settings.setMany('auth', { lockout_threshold: 2 }); + await vi.waitFor(() => expect((manager as any).config.lockoutThreshold).toBe(2)); + expect(await settings.get('auth', 'lockout_threshold')).toMatchObject({ value: 2, source: 'global' }); + await settings.setMany('auth', { lockout_threshold: null }); + await vi.waitFor(() => expect((manager as any).config.lockoutThreshold).toBe(5)); + expect(await settings.get('auth', 'lockout_threshold')).toMatchObject({ value: 5, source: 'default' }); + }); + + it('a key a declaration makes visible is judged on save; CONTROL undeclared, it is hidden and not judged', async () => { + // lockout_duration_minutes (1..1440) is visible only while lockout_threshold > 0. + const declared = await boot({ declare: { lockoutThreshold: 5 } }); + await expect(declared.settings.setMany('auth', { lockout_duration_minutes: 5000 })).rejects.toMatchObject({ + code: 'SETTINGS_VALIDATION', + fields: [expect.objectContaining({ field: 'lockout_duration_minutes' })], + }); + expect(await declared.settings.get('auth', 'lockout_duration_minutes')).toMatchObject({ source: 'default' }); + + const control = await boot(); + await expect(control.settings.setMany('auth', { lockout_duration_minutes: 5000 })).resolves.toBeDefined(); + expect(await control.settings.get('auth', 'lockout_duration_minutes')).toMatchObject({ value: 5000, source: 'global' }); + }); +}); + +describe('Setup → Authentication states a sign-up the deployment forces off over a value saved on', () => { + const signUpRuns = (manager: AuthManager) => !manager.getPublicConfig().emailPassword.disableSignUp; + + it('SSO-only: nothing stored reads off with no banner; a value saved on is stated as a warning', async () => { + process.env.OS_AUTH_SSO_ONLY = 'true'; + const { settings, manager } = await boot(); + const nothingStored = await readPage(settings); + expect(nothingStored.page.values.signup_enabled).toMatchObject({ value: false, source: 'default' }); + expect(nothingStored.banner).toBeUndefined(); + + await settings.setMany('auth', { signup_enabled: true }); + await settle(); + expect(signUpRuns(manager)).toBe(false); + const storedOn = await readPage(settings); + expect(storedOn.page.values.signup_enabled).toMatchObject({ value: true, source: 'global' }); + expect(storedOn.banner).toMatchObject({ + type: 'info_banner', + label: AUTH_LIVE_STATUS_COPY.en.signupForcedOffLabel, + bannerText: AUTH_LIVE_STATUS_COPY.en.signupForcedOffText, + bannerSeverity: 'warning', + }); + const zh = await readPage(settings, { 'accept-language': 'zh-CN' }); + expect(zh.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY['zh-CN'].signupForcedOffLabel }); + }); + + it('CONTROL: self-hosted, a value saved on over a declared off is applied, and nothing is stated', async () => { + const { settings, manager } = await boot({ emailAndPassword: { disableSignUp: true } }); + await settings.setMany('auth', { signup_enabled: true }); + await vi.waitFor(() => expect(signUpRuns(manager)).toBe(true)); + expect((await readPage(settings)).banner).toBeUndefined(); + }); + + it('cloud-managed: a value stored on is stated; with email and password held off too, both are stated', async () => { + setManaged(true); + const seeded = new SettingsService({ env: {} }); + seeded.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); + await seeded.set('auth', 'signup_enabled', true, {}); + const signUpOnly = await boot({ settings: seeded }); + await settle(); + expect(signUpRuns(signUpOnly.manager)).toBe(false); + expect((await readPage(signUpOnly.settings)).banner).toMatchObject({ + label: AUTH_LIVE_STATUS_COPY.en.signupForcedOffLabel, + bannerSeverity: 'warning', + }); + + const both = new SettingsService({ env: {} }); + both.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); + await both.set('auth', 'email_password_enabled', true, {}); + await both.set('auth', 'signup_enabled', true, {}); + const held = await boot({ emailPassword: false, settings: both }); + await settle(); + const { banner } = await readPage(held.settings); + expect(banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel, bannerSeverity: 'warning' }); + expect(String((banner as { bannerText?: unknown }).bannerText)).toContain(AUTH_LIVE_STATUS_COPY.en.managedOffText); + expect(String((banner as { bannerText?: unknown }).bannerText)).toContain(AUTH_LIVE_STATUS_COPY.en.signupForcedOffText); + }); +}); + describe('describeEmailPasswordLiveStatus', () => { it('states nothing while the switch and the running value agree', () => { for (const running of [true, false]) { @@ -325,3 +569,35 @@ describe('describeEmailPasswordLiveStatus', () => { } }); }); + +describe('describeSignUpLiveStatus', () => { + const on = { value: true, source: 'global' }; + it('states a value shown on that the deployment forces off', () => { + expect(describeSignUpLiveStatus({ running: false, shown: on, forcedOff: true, emailPasswordShown: { value: true } })) + .toEqual({ + label: AUTH_LIVE_STATUS_COPY.en.signupForcedOffLabel, + bannerText: AUTH_LIVE_STATUS_COPY.en.signupForcedOffText, + bannerSeverity: 'warning', + }); + }); + + it('states nothing when the switch already says it, sign-up runs, nothing forces it, or the switch is hidden', () => { + const base = { running: false, shown: on, forcedOff: true, emailPasswordShown: { value: true } }; + expect(describeSignUpLiveStatus({ ...base, shown: { value: false, source: 'default' } })).toBeUndefined(); + expect(describeSignUpLiveStatus({ ...base, running: true })).toBeUndefined(); + expect(describeSignUpLiveStatus({ ...base, forcedOff: false })).toBeUndefined(); + expect(describeSignUpLiveStatus({ ...base, emailPasswordShown: { value: false } })).toBeUndefined(); + }); +}); + +describe('combineAuthLiveStatus', () => { + const a = { label: 'A', bannerText: 'a.', bannerSeverity: 'warning' as const }; + const b = { label: 'B', bannerText: 'b.', bannerSeverity: 'info' as const }; + it('answers nothing, the one statement, or one banner carrying every statement in order', () => { + expect(combineAuthLiveStatus([undefined, undefined])).toBeUndefined(); + expect(combineAuthLiveStatus([undefined, b])).toBe(b); + expect(combineAuthLiveStatus([a, b])).toEqual({ + label: 'A', bannerText: '**A.** a.\n\n**B.** b.', bannerSeverity: 'warning', + }); + }); +}); From ad28f6e00b623422c82d11bf6d22a773b43cb3f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:21:45 +0000 Subject: [PATCH 3/4] chore(changeset): plugin-auth declared defaults for every stated auth key Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .changeset/auth-declared-defaults-every-key.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/auth-declared-defaults-every-key.md diff --git a/.changeset/auth-declared-defaults-every-key.md b/.changeset/auth-declared-defaults-every-key.md new file mode 100644 index 00000000000..20007cb1608 --- /dev/null +++ b/.changeset/auth-declared-defaults-every-key.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: Setup → Authentication shows what the deployment runs for every auth setting it declares, and says when sign-up is forced off over a value saved on + +Clause-②: yes (narrowing) — narrowed: with nothing stored, `SettingsService.get('auth', …)` and `GET /api/settings/auth` answer 24 more `auth` keys with the deployment's declaration (still `source: 'default'`) where they answered the manifest default: `password_min_length`, `password_max_length`, `membership_policy`, `password_reject_breached`, `password_require_complexity`, `password_min_classes`, `password_history_count`, `password_expiry_days`, `mfa_required`, `mfa_grace_period_days`, `api_key_default_expiry_days`, `api_key_max_expiry_days`, `api_key_inactivity_days`, `session_expiry_days`, `session_refresh_days`, `session_idle_timeout_minutes`, `session_absolute_max_hours`, `max_concurrent_sessions_per_user`, `allowed_ip_ranges`, `lockout_threshold`, `lockout_duration_minutes`, `audience_posture`, `audience_allowed_email_domains`, `audience_self_registration_permission_set`; so a published response's value changes for an existing reader on any deployment whose own configuration differs from the manifest default for one of them. Four keys gate another key's visibility, so with nothing stored a declaration now shows a key that was hidden, and a save that touches it or its gate is judged for its options and bounds where it was not: `lockout_duration_minutes` under a declared `lockoutThreshold` above 0 (for example `lockout_duration_minutes: 5000` is now refused `400 SETTINGS_VALIDATION` where it was stored), `mfa_grace_period_days` under a declared `mfaRequirement` other than `off`, `password_min_classes` under a declared `passwordRequireComplexity: true`, and `audience_allowed_email_domains` / `audience_self_registration_permission_set` under a declared `audience.posture` of `email_domain` or `open`. A save that sets one of these keys to its manifest default where the declaration differs now asks the key's write predicates. Widened: a save that sets one of these keys to the declaration with nothing stored is no change and asks no predicate. The Setup → Authentication live-status banner adds a `warning` for `signup_enabled` stored on where the deployment forces sign-up off (SSO-only, cloud-managed, `OS_DISABLE_SIGNUP`), in all 11 languages; where both that and the cloud-managed email-and-password hold apply, one banner carries both statements. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the auth settings page, these keys or the settings cascade's bottom rung. + + + +**BREAKING** for a reader of `GET /api/settings/auth` or `SettingsService.get('auth', …)` on a deployment whose own configuration differs from the manifest default for one of these keys, with nothing saved: the value answered is now what runs (for example `lockout_threshold: { value: 5, source: 'default' }` where the deployment declares `lockoutThreshold: 5`), not the manifest default. A saved value and an `OS_AUTH_*` override still win, and a clear returns to the declaration. A deployment that declares none of these reads exactly as before. + +Each answer takes the key's own shape: session lifetimes in days (the declared seconds divided by 86 400), allowed IP ranges and email domains one per line, and a select's value only when it is one of its options (an off-vocabulary `membershipPolicy` or `mfaRequirement` leaves the manifest default). Not stated, by design: `rate_limit_max` and `rate_limit_window_seconds` (the auth library's per-path rules run with nothing stored, which no one number states), `api_key_policy_started_at` (recorded into the store at first boot), and the Google keys (the toggle's runtime default is the manifest default, and a declared credential outranks a saved one). + +What to do: nothing to migrate. A client that read `source: 'default'` as "the manifest default" should read it as "nothing is saved; this is the deployment's default". From 53c02901f87dc30eae502ae2649f1a5250de41e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:25:40 +0000 Subject: [PATCH 4/4] test(plugin-auth): allowed IP ranges reader handles an absent list Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../plugins/plugin-auth/src/auth-settings-live-status.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts index 59aeea17129..d98d9b07174 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts @@ -390,7 +390,7 @@ describe('Setup → Authentication reads every declared auth key as it runs', () session_idle_timeout_minutes: floor.sessionIdleTimeoutMinutes, session_absolute_max_hours: floor.sessionAbsoluteMaxHours, max_concurrent_sessions_per_user: floor.maxConcurrentSessions, - allowed_ip_ranges: floor.allowedIpRanges.join('\n'), + allowed_ip_ranges: (floor.allowedIpRanges ?? []).join('\n'), lockout_threshold: config.lockoutThreshold, lockout_duration_minutes: config.lockoutDurationMinutes, audience_posture: audience.posture,