From e003c2244de94d0477fab2118da0c68e101ec912 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:17:51 +0000 Subject: [PATCH 1/8] 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/8] 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/8] 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/8] 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, From 61dab921f8987639239b9a8d39669d76a13964ac Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:55:05 +0000 Subject: [PATCH 5/8] fix(plugin-auth): a declared audience applies key by key, as the page reads it The settings pass composed the audience from stored keys only, so a sibling saved under a declared posture, or a posture saved beside a declared sibling the console did not resend, was stored and did not run. The pass now reads each audience key as stored, else as declared, the way the page does. Also: the API-key default reads under the ceiling in force, every restored auth key is pinned as stated or named as not stated, and the combined banner puts each title on its own line. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSo8YrNtRUFhn8aWNc --- .../plugins/plugin-auth/src/auth-plugin.ts | 71 +++++++----- .../src/auth-settings-declared-defaults.ts | 41 +++++-- .../src/auth-settings-live-status.test.ts | 101 +++++++++++++++++- .../src/auth-settings-live-status.ts | 3 +- 4 files changed, 180 insertions(+), 36 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index d3b607246aa..4ee052f5e49 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -33,7 +33,7 @@ import { // same question. [#14157] The dev-admin seed no longer GATES on it (a // directory row is not a login); it still reads it to find the seed account // among existing users when re-arming the credential hint. -import { isHumanUserRow, OPEN_POSTURE_VERIFICATION_OFF_WARNING } from './audience-posture.js'; +import { isHumanUserRow, OPEN_POSTURE_VERIFICATION_OFF_WARNING, resolveAudience } from './audience-posture.js'; // [#14157] The dev-admin seed's own precondition — "does a login exist?". import { decideDevAdminSeedGate } from './dev-admin-seed-gate.js'; import { localizationMailCurrencyResolver, withMailTenantCurrency } from './mail-tenant-currency.js'; @@ -2544,6 +2544,7 @@ export class AuthPlugin implements Plugin { declared: () => this.declaredAuthOptions, resolveDisableSignUp: (declared) => declaringManager.resolveDisableSignUp(declared), audiencePosture: () => declaringManager.getAudience().posture, + apiKeyMaxExpiryDays: () => declaringManager.resolveApiKeyLifecyclePolicy().maxExpiryDays, }, ctx.logger); const applySettings = async (): Promise => { @@ -3062,19 +3063,22 @@ export class AuthPlugin implements Plugin { // ride whatever posture the coercion picked). // // Composition rule: the declaration carries only the keys the - // explicitly selected posture READS (the spec marks the siblings + // selected posture (stored, else declared) READS (the spec marks the siblings // "only read under" their postures). In particular, switching BACK to // `invite_only` sends `{ posture: 'invite_only' }` alone — leftover // text in the (hidden) domain-list field must never make CLOSING the // wall refusable, because that refusal would leave the previous, more // open posture ruling: the one direction that must not fail. - // Missing required siblings are NOT guessed: the patch goes out - // without them and `applyConfigPatch` refuses the merged result - // (standing config keeps ruling — refusing to OPEN fails closed). + // A required sibling neither stored nor declared is NOT guessed: the + // patch goes out without it and `applyConfigPatch` refuses the merged + // result (standing config keeps ruling — refusing to OPEN fails + // closed). One the deployment declares is what the page shows for it, + // so it rides the patch (below). // [#30312] No posture stored any more (cleared, or the namespace // restored) while an audience key had been: the declared audience comes // back whole, judged by the same merged-result validation. A sibling - // still stored without a posture is then IGNORED as below. + // still stored without a posture is then composed under the declared + // posture as below, or IGNORED where the deployment declares none. if (!isExplicit('audience_posture')) { const audienceRestoring = audienceKeys.filter(restoring); if (audienceRestoring.length > 0) { @@ -3089,11 +3093,23 @@ export class AuthPlugin implements Plugin { } } } + // Composed as the page reads the trio: each key as stored, else as the + // deployment declares it (the declared defaults of + // auth-settings-declared-defaults.ts, through the same + // `resolveAudience`). Once one key is stored, the patch carries the + // other two as the page shows them, so a sibling saved under a + // declared posture, or a posture saved beside a declared sibling the + // console did not resend (it posts only the keys edited), runs as + // shown, or is refused by the merged-result validation, never stored + // without effect. A sibling stored where the deployment declares no + // audience has no posture to read it under and is IGNORED, as before: + // the manifest's `invite_only` is a console default, never guessed. if (audienceKeys.some((key) => isExplicit(key))) { - const rawPosture = values.audience_posture; - if (!isExplicit('audience_posture')) { + const declaredAudience = declared.audience === undefined ? undefined : resolveAudience(declared.audience); + const rawPosture = isExplicit('audience_posture') ? values.audience_posture : declaredAudience?.posture; + if (rawPosture === undefined) { ctx.logger.error( - '[auth] audience settings IGNORED — a domain list or permission set is declared without a posture. ' + + '[auth] audience settings IGNORED — a domain list or permission set is stored without a posture, and the deployment declares no audience. ' + `The standing posture ('${this.authManager.getAudience().posture}') keeps ruling. ` + `Set auth.audience_posture (or OS_AUTH_AUDIENCE_POSTURE) to one of: ${AUDIENCE_POSTURES.join(', ')}.`, ); @@ -3105,24 +3121,27 @@ export class AuthPlugin implements Plugin { ); } else { const audience: AudienceConfig = { posture: rawPosture }; - if (rawPosture === 'email_domain' && isExplicit('audience_allowed_email_domains')) { - const rawDomains = typeof values.audience_allowed_email_domains === 'string' - ? values.audience_allowed_email_domains - : ''; - // Same textarea convention as `allowed_ip_ranges`: newline- or - // comma-separated. Entries are NOT filtered for shape here — - // a malformed domain must be refused loudly by the validator, - // never silently dropped from the allowlist it was typed into. - audience.allowedEmailDomains = rawDomains - .split(/[\n,]+/) - .map((d) => d.trim()) - .filter(Boolean); + if (rawPosture === 'email_domain') { + if (isExplicit('audience_allowed_email_domains')) { + const rawDomains = typeof values.audience_allowed_email_domains === 'string' + ? values.audience_allowed_email_domains + : ''; + // Same textarea convention as `allowed_ip_ranges`: newline- or + // comma-separated. Entries are NOT filtered for shape here — + // a malformed domain must be refused loudly by the validator, + // never silently dropped from the allowlist it was typed into. + audience.allowedEmailDomains = rawDomains + .split(/[\n,]+/) + .map((d) => d.trim()) + .filter(Boolean); + } else if (declaredAudience && declaredAudience.allowedEmailDomains.length > 0) { + audience.allowedEmailDomains = [...declaredAudience.allowedEmailDomains]; + } } - if ( - audiencePermitsSelfRegistration(rawPosture) && - isExplicit('audience_self_registration_permission_set') - ) { - const set = asTrimmedString(values.audience_self_registration_permission_set); + if (audiencePermitsSelfRegistration(rawPosture)) { + const set = isExplicit('audience_self_registration_permission_set') + ? asTrimmedString(values.audience_self_registration_permission_set) + : declaredAudience?.selfRegistrationPermissionSet; if (set !== undefined) audience.selfRegistrationPermissionSet = set; } try { 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 09c0513b2e9..79a94bacfac 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts @@ -18,7 +18,13 @@ * * 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`: + * so the two cannot disagree. The audience trio is one declaration the + * manager replaces whole: once any of the three is stored, the settings pass + * composes the patch from the three as the page reads them (stored, else + * this declared default, through the same `resolveAudience`), so a sibling + * saved alone under a declared posture, or a posture saved beside a declared + * sibling the console did not resend, runs as the page shows it or is + * refused (`auth-plugin.ts`, the audience block of the settings pass). 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. @@ -33,6 +39,9 @@ * `emailAndPassword.requireEmailVerification` under the audience posture in * force (`resolveEmailVerificationRequirement`) — on under `email_domain`, * on under `open` unless declared `false`. + * - `api_key_default_expiry_days`: the declared default under the ceiling in + * force (a stored `api_key_max_expiry_days` included), as the signing door + * clamps it (`AuthManager#resolveApiKeyLifecyclePolicy`). * - 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 @@ -84,6 +93,8 @@ export interface AuthDeclaredDefaultFacts { resolveDisableSignUp(declared: boolean | undefined): boolean; /** The audience posture in force (`AuthManager.getAudience().posture`). */ audiencePosture(): AudiencePosture; + /** The API-key ceiling in force (`AuthManager#resolveApiKeyLifecyclePolicy().maxExpiryDays`). */ + apiKeyMaxExpiryDays(): number; } /** A non-empty list as the console's textarea holds it (one entry per line), else nothing declared. */ @@ -134,12 +145,12 @@ export const AUTH_DECLARED_DEFAULTS: Readonly 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)); - }, + // `AuthManager#resolveApiKeyLifecyclePolicy`: the ceiling in force rules the default too. + api_key_default_expiry_days: (facts) => + Math.min( + facts.apiKeyMaxExpiryDays(), + apiKeyDays(facts.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. @@ -160,6 +171,22 @@ export const AUTH_DECLARED_DEFAULTS: Readonly> = { + rate_limit_max: 'the auth library\'s per-path rules run, not one number', + rate_limit_window_seconds: 'the auth library\'s per-path rules run, not one number', + api_key_policy_started_at: 'recorded into the store by the first boot', + google_enabled: 'an intent toggle whose runtime default is the manifest default', + google_client_id: 'a declared credential outranks a saved one', + google_client_secret: 'a declared credential outranks a saved one, and a secret is never served', +}; + function numberOrUndefined(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? value : undefined; } 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 d98d9b07174..8f224913e27 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 @@ -45,6 +45,7 @@ import { describeSignUpLiveStatus, } from './auth-settings-live-status.js'; import { AUTH_SETTING_RESTORE } from './auth-settings-declared.js'; +import { AUTH_DECLARED_DEFAULTS, AUTH_KEYS_NOT_DECLARED } from './auth-settings-declared-defaults.js'; const SECRET = 'test-secret-at-least-32-chars-long'; const ADMIN = { enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }; @@ -98,7 +99,9 @@ const boot = async (opts: { 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 }; + /** The `error` lines the plugin logged so far. */ + const errors = () => ((ctx.logger as any).error.mock.calls as unknown[][]).map((call) => String(call[0])); + return { settings, manager, errors }; }; /** `GET /api/settings/auth` through the real settings route: the page's own read. */ @@ -461,6 +464,22 @@ describe('Setup → Authentication reads every declared auth key as it runs', () expect(await settings.get('auth', 'lockout_threshold')).toMatchObject({ value: 5, source: 'default' }); }); + it('every auth key the settings pass restores is either stated or named as not stated, never both', () => { + const stated = Object.keys(AUTH_DECLARED_DEFAULTS); + const notStated = Object.keys(AUTH_KEYS_NOT_DECLARED); + expect(stated.filter((key) => notStated.includes(key))).toEqual([]); + expect([...stated, ...notStated].sort()).toEqual(Object.keys(AUTH_SETTING_RESTORE).sort()); + }); + + it('the API-key default reads under the ceiling in force, a stored ceiling included', async () => { + const { settings, manager } = await boot({ declare: { apiKeyDefaultExpiryDays: 30 } }); + expect(await settings.get('auth', 'api_key_default_expiry_days')).toMatchObject({ value: 30, source: 'default' }); + await settings.setMany('auth', { api_key_max_expiry_days: 10 }); + await vi.waitFor(() => expect(manager.resolveApiKeyLifecyclePolicy().maxExpiryDays).toBe(10)); + expect(manager.resolveApiKeyLifecyclePolicy().defaultExpiryDays).toBe(10); + expect(await settings.get('auth', 'api_key_default_expiry_days')).toMatchObject({ value: 10, 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 } }); @@ -476,6 +495,84 @@ describe('Setup → Authentication reads every declared auth key as it runs', () }); }); +/** + * The audience trio is one declaration the manager replaces whole. The page + * reads each key as stored, else as declared, and the console posts only the + * keys an admin edited; the settings pass composes the audience from the + * three as the page reads them, so what the page then reads is what runs. + */ +describe('Setup → Authentication: an audience key saved under a declared audience runs as the page reads it', () => { + /** The trio as the page reads it, beside what the manager runs. */ + const audienceRead = async (settings: SettingsService, manager: AuthManager) => { + const { page } = await readPage(settings); + const runs = manager.getAudience(); + return { + page: { + posture: page.values.audience_posture?.value, + domains: page.values.audience_allowed_email_domains?.value ?? '', + set: page.values.audience_self_registration_permission_set?.value, + }, + runs: { posture: runs.posture, domains: runs.allowedEmailDomains.join('\n'), set: runs.selfRegistrationPermissionSet }, + }; + }; + + it('(a) a shortened domain list saved alone under a declared email_domain takes effect', async () => { + const { settings, manager, errors } = await boot({ + declare: { + audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com', 'b.io'], selfRegistrationPermissionSet: 'member_default' }, + }, + }); + // The console's patch: only the field edited. + await settings.setMany('auth', { audience_allowed_email_domains: 'acme.com' }); + await vi.waitFor(() => expect(manager.getAudience().allowedEmailDomains).toEqual(['acme.com'])); + const read = await audienceRead(settings, manager); + expect(read.page).toEqual({ posture: 'email_domain', domains: 'acme.com', set: 'member_default' }); + expect(read.runs).toEqual(read.page); + expect(errors().filter((line) => line.includes('audience settings'))).toEqual([]); + }); + + it('(b) a switch to email_domain under a declared open, with the shown permission set unsent, takes effect', async () => { + const { settings, manager, errors } = await boot({ + declare: { audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }, + }); + expect((await readPage(settings)).page.values.audience_self_registration_permission_set) + .toMatchObject({ value: 'member_default', source: 'default' }); + await settings.setMany('auth', { audience_posture: 'email_domain', audience_allowed_email_domains: 'acme.com' }); + await vi.waitFor(() => expect(manager.getAudience().posture).toBe('email_domain')); + const read = await audienceRead(settings, manager); + expect(read.page).toEqual({ posture: 'email_domain', domains: 'acme.com', set: 'member_default' }); + expect(read.runs).toEqual(read.page); + expect(errors().filter((line) => line.includes('audience settings'))).toEqual([]); + }); + + it('the permission set saved alone under a declared open takes effect', async () => { + const { settings, manager } = await boot({ + declare: { audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }, + }); + await settings.setMany('auth', { audience_self_registration_permission_set: 'member_extended' }); + await vi.waitFor(() => expect(manager.getAudience().selfRegistrationPermissionSet).toBe('member_extended')); + const read = await audienceRead(settings, manager); + expect(read.runs).toEqual({ ...read.page, domains: '' }); + }); + + it('CONTROL: nothing declared, a domain list saved alone is still ignored with no posture to read it under', async () => { + const { settings, manager, errors } = await boot(); + await settings.setMany('auth', { audience_allowed_email_domains: 'acme.com' }); + await vi.waitFor(() => expect(errors().some((line) => line.includes('without a posture'))).toBe(true)); + expect(manager.getAudience().posture).toBe('invite_only'); + expect((await readPage(settings)).page.values.audience_posture).toMatchObject({ value: 'invite_only', source: 'default' }); + }); + + it('CONTROL: a posture saved under a declared open, with no domain list stored or declared, is refused and open keeps ruling', async () => { + const { settings, manager, errors } = await boot({ + declare: { audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }, + }); + await settings.setMany('auth', { audience_posture: 'email_domain' }); + await vi.waitFor(() => expect(errors().some((line) => line.includes('audience settings REFUSED'))).toBe(true)); + expect(manager.getAudience().posture).toBe('open'); + }); +}); + describe('Setup → Authentication states a sign-up the deployment forces off over a value saved on', () => { const signUpRuns = (manager: AuthManager) => !manager.getPublicConfig().emailPassword.disableSignUp; @@ -597,7 +694,7 @@ describe('combineAuthLiveStatus', () => { 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', + label: 'A', bannerText: '**A**\n\na.\n\n**B**\n\nb.', bannerSeverity: 'warning', }); }); }); 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 b0e71dff439..9e021f17f0c 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-live-status.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts @@ -281,7 +281,8 @@ export function combineAuthLiveStatus( if (present.length <= 1) return present[0]; return { label: present[0].label, - bannerText: present.map((statement) => `**${statement.label}.** ${statement.bannerText}`).join('\n\n'), + // The title on a line of its own: no stop to write after it, in any language. + bannerText: present.map((statement) => `**${statement.label}**\n\n${statement.bannerText}`).join('\n\n'), bannerSeverity: present.some((statement) => statement.bannerSeverity === 'warning') ? 'warning' : 'info', }; } From 00f32844090fafdcc52b261d16fd0f18f52751df Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 13:02:27 +0000 Subject: [PATCH 6/8] test(plugin-auth): the switch to email_domain case waits out the batch's in-between pass Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSo8YrNtRUFhn8aWNc --- .../plugin-auth/src/auth-settings-live-status.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 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 8f224913e27..f6d5e293d51 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 @@ -539,10 +539,18 @@ describe('Setup → Authentication: an audience key saved under a declared audie .toMatchObject({ value: 'member_default', source: 'default' }); await settings.setMany('auth', { audience_posture: 'email_domain', audience_allowed_email_domains: 'acme.com' }); await vi.waitFor(() => expect(manager.getAudience().posture).toBe('email_domain')); + await settle(); const read = await audienceRead(settings, manager); expect(read.page).toEqual({ posture: 'email_domain', domains: 'acme.com', set: 'member_default' }); expect(read.runs).toEqual(read.page); - expect(errors().filter((line) => line.includes('audience settings'))).toEqual([]); + // The batch's rows land one by one, and a pass may run between the two + // (posture stored, list not yet): that pass is refused, and the next one + // applies. What matters is that nothing is refused once both are stored. + const lines = errors().filter((line) => line.includes('audience settings')); + await settings.setMany('auth', { lockout_threshold: 3 }); + await vi.waitFor(() => expect((manager as any).config.lockoutThreshold).toBe(3)); + expect(errors().filter((line) => line.includes('audience settings'))).toEqual(lines); + expect(manager.getAudience().posture).toBe('email_domain'); }); it('the permission set saved alone under a declared open takes effect', async () => { From 55bf5d85679404c9acac862fdae8ee93f0c67d0f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 13:03:36 +0000 Subject: [PATCH 7/8] docs(plugin-auth): changeset and the config-resolution page name what the declared auth defaults now cover Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSo8YrNtRUFhn8aWNc --- .changeset/auth-declared-defaults-every-key.md | 8 +++++++- content/docs/protocol/kernel/config-resolution.mdx | 11 ++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.changeset/auth-declared-defaults-every-key.md b/.changeset/auth-declared-defaults-every-key.md index 20007cb1608..6a6dd45a608 100644 --- a/.changeset/auth-declared-defaults-every-key.md +++ b/.changeset/auth-declared-defaults-every-key.md @@ -4,12 +4,18 @@ 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. +Clause-②: yes (narrowing) — a declared audience now applies key by key, so two saves that were stored without effect now take effect or are refused, as the L2 record states Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches the auth settings page, these keys or the settings cascade's bottom rung. +What narrows: 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. + +A declared value outside its specifier's own bounds or options is answered as declared, because it is what runs, and is then judged whenever the key is touched without a value of its own: a clear of that key beside any other key in one patch, or a save of `email_password_enabled`, which gates the visibility of eight of these keys (the password keys and `mfa_required`). For example a declared `session.expiresIn` under one day reads below `session_expiry_days`'s minimum of 1, and a declared `minPasswordLength` under 6 below `password_min_length`'s; such a save is refused `400 SETTINGS_VALIDATION` at that key, where the manifest default sat in the slot and passed. Save the key within its bounds in the same patch, or clear it alone. + +The audience trio is one declaration the auth manager replaces whole. Once any of the three is stored, the settings pass now composes the audience from the three as the page reads them: each as stored, else as the deployment declares it. A domain list or permission set saved alone under a declared posture now runs, where it was stored and ignored; a posture saved beside a declared permission set the console did not resend now runs with that set, where it was refused. A saved audience the merged-result validation refuses is still refused, and the standing audience keeps ruling. A sibling saved where the deployment declares no audience is still ignored, with no posture to read it under. + **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). diff --git a/content/docs/protocol/kernel/config-resolution.mdx b/content/docs/protocol/kernel/config-resolution.mdx index 8afaa31275b..377661642bc 100644 --- a/content/docs/protocol/kernel/config-resolution.mdx +++ b/content/docs/protocol/kernel/config-resolution.mdx @@ -76,9 +76,14 @@ configuration when nothing is stored (plugin options, a host declaration) states that value with `registerDeclaredDefault(namespace, key, provider)`; otherwise the manifest `default` answers. Either way the answer reports `source: 'default'`: nothing is stored, and a clear returns to it. The auth -plugin states `email_password_enabled`, `signup_enabled` and -`require_email_verification` this way, so Setup → Authentication shows what -the deployment runs, not a console default it never applies. +plugin states every `auth` key its runtime takes from the deployment's own +configuration this way (the sign-in switches, password, MFA, API-key, +session, network, lockout, membership and audience settings), so +Setup → Authentication shows what the deployment runs, not a console default +it never applies. It leaves on the manifest default the keys no one declared +value describes: the rate-limit pair (the auth library's own per-path rules +run while nothing is stored), the Google sign-in keys, and the API-key policy +start date the first boot records. Two rules follow from the walk, and both are enforced in `SettingsService`: From a13241a81dc8bc9e2c026f61883f8474a55c56bb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:06:20 +0000 Subject: [PATCH 8/8] docs(plugin-auth): the changeset names the stored audience case an upgrade reads differently, and both rate-limit halves Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSo8YrNtRUFhn8aWNc --- .changeset/auth-declared-defaults-every-key.md | 10 ++++++---- content/docs/protocol/kernel/config-resolution.mdx | 11 +++++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/.changeset/auth-declared-defaults-every-key.md b/.changeset/auth-declared-defaults-every-key.md index 6a6dd45a608..ca61d79d7b9 100644 --- a/.changeset/auth-declared-defaults-every-key.md +++ b/.changeset/auth-declared-defaults-every-key.md @@ -4,11 +4,11 @@ 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) — a declared audience now applies key by key, so two saves that were stored without effect now take effect or are refused, as the L2 record states +Clause-②: yes (narrowing) — with nothing stored, 24 more `auth` keys answer the deployment's declaration where they answered the manifest default, so a published response changes for an existing reader, and a save of a key a declaration now shows or bounds can be refused where it was stored Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches the auth settings page, these keys or the settings cascade's bottom rung. - + What narrows: 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. @@ -18,6 +18,8 @@ The audience trio is one declaration the auth manager replaces whole. Once any o **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). +**BREAKING** also for a deployment that declares an audience (`audience` in its auth configuration) and holds a stored `audience_allowed_email_domains` or `audience_self_registration_permission_set` with no stored `audience_posture` (left by clearing the posture alone, or set through that key's `OS_AUTH_*` override alone). Every earlier release ignored such a value with an `error` line; from this release it takes effect under the declared posture, so it can change which email domains may self-register, or which permission set a self-registered user receives. -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". +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` (with nothing stored, the auth library's own per-path rules run, or, under a declared `rateLimit`, that declared global pair; neither is the per-endpoint cap the setting writes, so no one number states what runs), `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: before upgrading a deployment that declares an audience, look for `audience_allowed_email_domains` or `audience_self_registration_permission_set` stored while `audience_posture` is not (on `GET /api/settings/auth`, either key with a `source` other than `default` while `audience_posture` reads `source: 'default'`), including one set through its `OS_AUTH_*` override alone; clear it, or confirm it is the value to enforce. Nothing else 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". diff --git a/content/docs/protocol/kernel/config-resolution.mdx b/content/docs/protocol/kernel/config-resolution.mdx index 377661642bc..67fa1709566 100644 --- a/content/docs/protocol/kernel/config-resolution.mdx +++ b/content/docs/protocol/kernel/config-resolution.mdx @@ -80,10 +80,13 @@ plugin states every `auth` key its runtime takes from the deployment's own configuration this way (the sign-in switches, password, MFA, API-key, session, network, lockout, membership and audience settings), so Setup → Authentication shows what the deployment runs, not a console default -it never applies. It leaves on the manifest default the keys no one declared -value describes: the rate-limit pair (the auth library's own per-path rules -run while nothing is stored), the Google sign-in keys, and the API-key policy -start date the first boot records. +it never applies. It leaves three groups on the manifest default. The +rate-limit pair: with nothing stored the auth library's own per-path rules +run, or a declared `rateLimit` global pair, and neither is the per-endpoint +cap the setting writes. The Google sign-in keys: the toggle's runtime default +is the manifest's, and a declared credential outranks a saved one, so it is +not what a clear returns to. And the API-key policy start date, which the +first boot records into the store. Two rules follow from the walk, and both are enforced in `SettingsService`: