From ee52361589bfdca0b430df1c320ace153c077c79 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:17:55 +0000 Subject: [PATCH 1/2] fix(plugin-auth): Setup > Authentication states email and password sign-in as it runs Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../plugins/plugin-auth/src/auth-plugin.ts | 45 +++- .../src/auth-settings-live-status.test.ts | 240 +++++++++++++++++ .../src/auth-settings-live-status.ts | 241 ++++++++++++++++++ 3 files changed, 524 insertions(+), 2 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts create mode 100644 packages/plugins/plugin-auth/src/auth-settings-live-status.ts diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 37cb30ada34..2fb46e897c5 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -159,6 +159,7 @@ import { ssoProviderDeleteRefusal, type SignInMethodFloorDeps, } from './sign-in-method-floor.js'; +import { describeEmailPasswordLiveStatus, type AuthLiveStatus } from './auth-settings-live-status.js'; import { judgePlatformAdmin, judgeHeldSession, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js'; import { decideDemoStaffEnvironmentGate, @@ -255,6 +256,15 @@ interface SettingsReadSurface { predicate: (input: unknown) => unknown, options?: { requestHeaders?: readonly string[] }, ): void; + /** + * State what runs at the top of the namespace's page, read on each page + * request (`SettingsService.registerLiveStatus`). Optional, like `subscribe`. + * See auth-settings-live-status.ts. + */ + registerLiveStatus?( + namespace: string, + provider: (input: { ctx: Record; locale?: string }) => Promise, + ): void; } /** [#23367] The auth setting that records when the API-key lifecycle policy took effect. */ @@ -3159,10 +3169,41 @@ export class AuthPlugin implements Plugin { // the one-off moves of the toggle-era values onto the levels. await this.bindOrganizationAccessPolicy(ctx, settings); - await applySettings(); + // The pass a change event started, so the page's statement below reads the + // running config after it, not mid-way. + let pass: Promise = Promise.resolve(); + const runPass = (): Promise => (pass = applySettings()); + + // Setup → Authentication states what runs when the switch says otherwise: + // with nothing stored the switch shows the manifest default while the + // running config takes the deployment's declaration. See auth-settings-live-status.ts. + if (typeof settings.registerLiveStatus === 'function') { + const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager); + try { + settings.registerLiveStatus('auth', async ({ ctx: pageCtx, locale }) => { + 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, + }); + }); + } catch (err: any) { + ctx.logger.warn( + '[auth] Setup → Authentication: the live status was NOT registered ' + + `(${String(err?.message ?? err)}), so where the deployment declares email and password sign-in off ` + + 'with nothing saved, the page shows the switch on with nothing saying it is off.', + ); + } + } + + await runPass(); if (typeof settings.subscribe === 'function') { settings.subscribe('auth', () => { - void applySettings(); + void runPass(); }); ctx.logger.info('Auth: bound to settings namespace=auth'); } 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 new file mode 100644 index 00000000000..ddc39b34678 --- /dev/null +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts @@ -0,0 +1,240 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup → Authentication says what runs when the email and password switch + * says otherwise (`auth-settings-live-status.ts`). + * + * Through the REAL settings service (`@objectstack/service-settings`, aliased + * to its source) and its real `GET /api/settings/:namespace` route, the one + * the settings page reads, over the real `AuthPlugin` / `AuthManager`. + * + * Pinned: + * 1. a deployment that declares email and password off, with nothing stored: + * the switch still resolves to the manifest default (`true`, `source: + * 'default'`) while the runtime runs it off, and the page is headed by a + * live-status banner saying it is off on this deployment, in the caller's + * language (measured before the change: no banner); + * 2. CONTROL: email and password declared on (the default), nothing stored: + * no banner; + * 3. a stored value still wins where it is applied: saved on over a declared + * off, or saved off over a declared on, and the page states nothing; + * 4. on a cloud-managed runtime that holds it off: the banner says so, `info` + * with nothing stored, `warning` over a stored on that is not applied. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// Paid during collection, not inside a clocked case: the auth manager loads it lazily. +import '@objectstack/core/egress'; +import { resetCloudManagedForTesting, type PluginContext } from '@objectstack/core'; +import type { IHttpRequest, IHttpResponse, IHttpServer, RouteHandler } from '@objectstack/spec/contracts'; +import { + SETTINGS_LIVE_STATUS_BANNER_ID, + SettingsService, + builtinSettingsManifests, + registerSettingsRoutes, +} 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'; + +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'] as const; + +describe('Setup → Authentication states email and password sign-in as it runs', () => { + const savedEnv: Partial> = {}; + + 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(); + }; + + beforeEach(() => { + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } + setManaged(false); + }); + + afterEach(() => { + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } + resetCloudManagedForTesting(); + vi.restoreAllMocks(); + }); + + /** Boot as a host does (init → start → kernel:ready), with email and password declared as given. */ + const boot = async (opts: { emailPassword?: boolean; hostSignInHandoff?: boolean } = {}) => { + const settings = new SettingsService({ env: {} }); + 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 ? {} : { emailAndPassword: { enabled: opts.emailPassword } }), + ...(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 }; + }; + + /** `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 }; + }; + + 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)); + + it('declared off with nothing stored: the switch reads the default, and the page says it is off', async () => { + const { settings, manager } = await boot({ emailPassword: false }); + expect(passwordOn(manager)).toBe(false); + // The stored-value read is unchanged: nothing is stored, so the manifest default. + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'default' }); + + const { page, banner } = await readPage(settings); + expect(page.values.email_password_enabled).toMatchObject({ value: true, source: 'default' }); + expect(banner).toMatchObject({ + type: 'info_banner', + label: AUTH_LIVE_STATUS_COPY.en.declaredOffLabel, + bannerText: AUTH_LIVE_STATUS_COPY.en.declaredOffText, + bannerSeverity: 'info', + }); + // It heads the page. + expect(page.manifest.specifiers[0].id).toBe(SETTINGS_LIVE_STATUS_BANNER_ID); + + // In the caller's language. + const zh = await readPage(settings, { 'accept-language': 'zh-CN' }); + expect(zh.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY['zh-CN'].declaredOffLabel }); + }); + + it('CONTROL: declared on with nothing stored, the page states nothing', async () => { + const { settings, manager } = await boot(); + expect(passwordOn(manager)).toBe(true); + const { page, banner } = await readPage(settings); + expect(page.values.email_password_enabled).toMatchObject({ value: true, source: 'default' }); + expect(banner).toBeUndefined(); + }); + + it('a stored value still wins where it is applied, and the page states nothing', async () => { + const off = await boot({ emailPassword: false }); + await off.settings.setMany('auth', { email_password_enabled: true }); + await vi.waitFor(() => expect(passwordOn(off.manager)).toBe(true)); + const savedOn = await readPage(off.settings); + expect(savedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' }); + expect(savedOn.banner).toBeUndefined(); + + // Saved off over a declared on; the host's sign-in handoff keeps a way in, so the sign-in floor lets it through. + const on = await boot({ hostSignInHandoff: true }); + expect(passwordOn(on.manager)).toBe(true); + await on.settings.setMany('auth', { email_password_enabled: false }); + await vi.waitFor(() => expect(passwordOn(on.manager)).toBe(false)); + const savedOff = await readPage(on.settings); + expect(savedOff.page.values.email_password_enabled).toMatchObject({ value: false, source: 'global' }); + expect(savedOff.banner).toBeUndefined(); + }); + + it('a cloud-managed runtime that holds it off says so: info with nothing stored, warning over a stored on', async () => { + setManaged(true); + const { settings, manager } = await boot({ emailPassword: false }); + const nothingStored = await readPage(settings); + expect(nothingStored.banner).toMatchObject({ + label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel, + bannerText: AUTH_LIVE_STATUS_COPY.en.managedOffText, + bannerSeverity: 'info', + }); + + // A re-save of the default is stored and not applied (the settings pass's managed hold). + await settings.setMany('auth', { email_password_enabled: true }); + await settle(); + expect(passwordOn(manager)).toBe(false); + const storedOn = await readPage(settings); + expect(storedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' }); + expect(storedOn.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel, bannerSeverity: 'warning' }); + }); +}); + +describe('describeEmailPasswordLiveStatus', () => { + it('states nothing while the switch and the running value agree', () => { + for (const running of [true, false]) { + expect(describeEmailPasswordLiveStatus({ + running, shown: { value: running, source: 'global' }, heldOffByHost: false, + })).toBeUndefined(); + } + expect(describeEmailPasswordLiveStatus({ running: true, shown: undefined, heldOffByHost: false })).toBeUndefined(); + }); + + it('any other disagreement is stated as a warning naming what runs', () => { + expect(describeEmailPasswordLiveStatus({ + running: true, shown: { value: false, source: 'global' }, heldOffByHost: false, + })).toEqual({ + label: AUTH_LIVE_STATUS_COPY.en.differsLabel(true), + bannerText: AUTH_LIVE_STATUS_COPY.en.differsText, + bannerSeverity: 'warning', + }); + // Off by something other than the declaration (stored on, not applied, self-hosted). + expect(describeEmailPasswordLiveStatus({ + running: false, shown: { value: true, source: 'global' }, heldOffByHost: false, + })).toMatchObject({ label: AUTH_LIVE_STATUS_COPY.en.differsLabel(false), bannerSeverity: 'warning' }); + }); + + it('every language on the copy table carries every sentence', () => { + const keys = Object.keys(AUTH_LIVE_STATUS_COPY.en).sort(); + for (const [locale, copy] of Object.entries(AUTH_LIVE_STATUS_COPY)) { + expect(Object.keys(copy).sort(), locale).toEqual(keys); + for (const [key, value] of Object.entries(copy)) { + const text = typeof value === 'function' ? value(false) : value; + expect(typeof text === 'string' && text.length > 0, `${locale}.${key}`).toBe(true); + } + } + }); +}); diff --git a/packages/plugins/plugin-auth/src/auth-settings-live-status.ts b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts new file mode 100644 index 00000000000..0b9f17ae54a --- /dev/null +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts @@ -0,0 +1,241 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { resolveLocale } from '@objectstack/core'; +import type { SettingsCopyLocale } from './settings-copy-locale.js'; + +/** + * What Setup → Authentication states about email and password sign-in as it + * RUNS, when that differs from the switch on the page. + * + * The switch shows what `auth.email_password_enabled` resolves to. With nothing + * stored that is the manifest default (on), while the running config takes + * the deployment's own declaration (`emailAndPassword.enabled`): the settings + * pass applies only stored or `OS_*` values, and the manifest default is a + * console default that never rules (`auth-settings-declared.ts`). So a + * deployment that declares email and password off, with nothing stored, shows + * the switch on for a sign-in method that is off. A cloud-managed runtime that + * holds it off (`emailPasswordHeldOffByHost`) shows a stored on that is not + * applied the same way. + * + * 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 + * only, so a toggle is stated in the banner that heads the page. Read at + * request time, never recorded at boot; nothing is stated while the switch + * and the running value agree. + * + * Same shape as service-settings' `SettingsLiveStatus`, restated because this + * plugin reaches the settings service through a structural surface and takes + * no package dependency on it. + */ +export interface AuthLiveStatus { + label: string; + bannerText: string; + bannerSeverity: 'info' | 'warning'; +} + +/** What the statement is judged from, all read on the page request. */ +export interface EmailPasswordLiveInput { + /** Whether email and password sign-in runs: `getPublicConfig().emailPassword.enabled`. */ + running: boolean; + /** `auth.email_password_enabled` as the page reads it (`SettingsService.get`). */ + shown: { value?: unknown; source?: string } | undefined; + /** A cloud-managed runtime whose deployment declared it off (`emailPasswordHeldOffByHost`). */ + heldOffByHost: boolean; + /** The caller's display language; a language with no entry is answered in English. */ + locale?: string; +} + +/** The words of the statement, one entry per language on the platform locale table. */ +export interface AuthLiveStatusCopy { + /** Declared off by the deployment, nothing stored. */ + declaredOffLabel: string; + declaredOffText: string; + /** Held off by the host on a cloud-managed runtime. */ + managedOffLabel: string; + managedOffText: string; + /** Any other disagreement between the switch and what runs. */ + differsLabel(running: boolean): string; + differsText: string; +} + +export const AUTH_LIVE_STATUS_COPY: Record = { + en: { + declaredOffLabel: 'Email and password sign-in is off on this deployment', + declaredOffText: 'This deployment\'s own configuration turns email and password sign-in off, and nothing is ' + + 'saved here, so the switch below shows the console default (on), not what runs. The sign-in page offers ' + + 'no email and password form. A value saved here takes precedence over that configuration.', + managedOffLabel: 'Email and password sign-in is off on this environment', + managedOffText: 'This environment is cloud-managed and its deployment turns email and password sign-in off: ' + + 'people sign in through the identity provider of the organisation that hosts it, and the sign-in page ' + + 'offers no email and password form. The switch below does not change that, and a value saved on is not ' + + 'applied.', + differsLabel: (running) => `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.', + }, + 'zh-CN': { + declaredOffLabel: '本部署已关闭邮箱/密码登录', + declaredOffText: '本部署自身的配置关闭了邮箱/密码登录,而这里没有保存任何值,所以下方开关显示的是控制台默认值(开),' + + '并非实际运行的状态。登录页不提供邮箱/密码表单。在这里保存的值优先于该配置。', + managedOffLabel: '本环境已关闭邮箱/密码登录', + managedOffText: '本环境由云端托管,其部署关闭了邮箱/密码登录:用户通过托管本环境的组织的身份提供方登录,' + + '登录页不提供邮箱/密码表单。下方开关无法改变这一点,保存为开的值不会生效。', + differsLabel: (running) => `实际运行中邮箱/密码登录为${running ? '开' : '关'}`, + differsText: '下方开关显示的是已保存的设置,并非当前实际运行的状态。', + }, + 'zh-Hant': { + declaredOffLabel: '本部署已關閉電子郵件/密碼登入', + declaredOffText: '本部署自身的設定關閉了電子郵件/密碼登入,而這裡沒有儲存任何值,所以下方開關顯示的是主控台預設值(開),' + + '並非實際執行的狀態。登入頁不提供電子郵件/密碼表單。在這裡儲存的值優先於該設定。', + managedOffLabel: '本環境已關閉電子郵件/密碼登入', + managedOffText: '本環境由雲端代管,其部署關閉了電子郵件/密碼登入:使用者透過代管本環境之組織的身分識別提供者登入,' + + '登入頁不提供電子郵件/密碼表單。下方開關無法改變這一點,儲存為開的值不會生效。', + differsLabel: (running) => `實際執行中電子郵件/密碼登入為${running ? '開' : '關'}`, + differsText: '下方開關顯示的是已儲存的設定,並非目前實際執行的狀態。', + }, + 'ja-JP': { + declaredOffLabel: 'このデプロイではメール/パスワードによるサインインはオフです', + declaredOffText: 'このデプロイ自身の構成でメール/パスワードによるサインインがオフになっており、ここには何も保存されていないため、' + + '下のスイッチは実際の動作ではなくコンソールの既定値(オン)を表示しています。サインインページにメール/パスワードのフォームは' + + '表示されません。ここで保存した値はその構成より優先されます。', + managedOffLabel: 'この環境ではメール/パスワードによるサインインはオフです', + managedOffText: 'この環境はクラウドで管理されており、そのデプロイでメール/パスワードによるサインインがオフになっています。' + + 'ユーザーはこの環境をホストする組織の ID プロバイダーでサインインし、サインインページにメール/パスワードのフォームは' + + '表示されません。下のスイッチではこれを変更できず、オンで保存された値は適用されません。', + differsLabel: (running) => `実行中のシステムではメール/パスワードによるサインインは${running ? 'オン' : 'オフ'}です`, + differsText: '下のスイッチは保存済みの設定を表示しており、現在の実際の動作とは異なります。', + }, + 'es-ES': { + declaredOffLabel: 'El inicio de sesión con correo y contraseña está desactivado en esta implementación', + declaredOffText: 'La propia configuración de esta implementación desactiva el inicio de sesión con correo y ' + + 'contraseña y aquí no hay nada guardado, así que el interruptor de abajo muestra el valor predeterminado de la ' + + 'consola (activado), no lo que se ejecuta. La página de inicio de sesión no ofrece formulario de correo y ' + + 'contraseña. Un valor guardado aquí prevalece sobre esa configuración.', + managedOffLabel: 'El inicio de sesión con correo y contraseña está desactivado en este entorno', + managedOffText: 'Este entorno está gestionado en la nube y su implementación desactiva el inicio de sesión con ' + + 'correo y contraseña: las personas inician sesión mediante el proveedor de identidad de la organización que lo ' + + 'aloja, y la página de inicio de sesión no ofrece formulario de correo y contraseña. El interruptor de abajo no ' + + 'cambia eso, y un valor guardado como activado no se aplica.', + differsLabel: (running) => + `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.', + }, + ar: { + declaredOffLabel: 'تسجيل الدخول بالبريد الإلكتروني وكلمة المرور متوقف في هذا النشر', + declaredOffText: 'تُوقف إعدادات هذا النشر نفسها تسجيل الدخول بالبريد الإلكتروني وكلمة المرور، ولا يوجد شيء محفوظ هنا، ' + + 'لذا يعرض المفتاح أدناه القيمة الافتراضية لوحدة التحكم (مُفعّل) وليس ما يعمل فعلًا. لا تعرض صفحة تسجيل الدخول نموذج ' + + 'البريد الإلكتروني وكلمة المرور. القيمة المحفوظة هنا لها الأسبقية على تلك الإعدادات.', + managedOffLabel: 'تسجيل الدخول بالبريد الإلكتروني وكلمة المرور متوقف في هذه البيئة', + managedOffText: 'هذه البيئة مُدارة سحابيًا ويُوقف نشرها تسجيل الدخول بالبريد الإلكتروني وكلمة المرور: يسجّل الأشخاص ' + + 'الدخول عبر موفّر الهوية للمؤسسة التي تستضيفها، ولا تعرض صفحة تسجيل الدخول نموذج البريد الإلكتروني وكلمة المرور. ' + + 'لا يغيّر المفتاح أدناه ذلك، ولا تُطبَّق القيمة المحفوظة مُفعّلة.', + differsLabel: (running) => + `تسجيل الدخول بالبريد الإلكتروني وكلمة المرور ${running ? 'مُفعّل' : 'متوقف'} في النظام قيد التشغيل`, + differsText: 'يعرض المفتاح أدناه الإعداد المحفوظ، وهو ليس ما يعمل الآن.', + }, + fr: { + declaredOffLabel: 'La connexion par e-mail et mot de passe est désactivée sur ce déploiement', + declaredOffText: 'La configuration propre à ce déploiement désactive la connexion par e-mail et mot de passe, et ' + + 'rien n\'est enregistré ici : l\'interrupteur ci-dessous affiche donc la valeur par défaut de la console ' + + '(activé), pas ce qui s\'exécute. La page de connexion ne propose aucun formulaire e-mail et mot de passe. ' + + 'Une valeur enregistrée ici l\'emporte sur cette configuration.', + managedOffLabel: 'La connexion par e-mail et mot de passe est désactivée sur cet environnement', + managedOffText: 'Cet environnement est géré dans le cloud et son déploiement désactive la connexion par e-mail et ' + + 'mot de passe : on se connecte via le fournisseur d\'identité de l\'organisation qui l\'héberge, et la page de ' + + 'connexion ne propose aucun formulaire e-mail et mot de passe. L\'interrupteur ci-dessous n\'y change rien, et ' + + 'une valeur enregistrée activée n\'est pas appliquée.', + differsLabel: (running) => + `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.', + }, + 'pt-BR': { + declaredOffLabel: 'O login com e-mail e senha está desativado nesta implantação', + declaredOffText: 'A própria configuração desta implantação desativa o login com e-mail e senha, e nada está salvo ' + + 'aqui, então o interruptor abaixo mostra o padrão do console (ativado), não o que está em execução. A página de ' + + 'login não oferece formulário de e-mail e senha. Um valor salvo aqui prevalece sobre essa configuração.', + managedOffLabel: 'O login com e-mail e senha está desativado neste ambiente', + managedOffText: 'Este ambiente é gerenciado na nuvem e sua implantação desativa o login com e-mail e senha: as ' + + 'pessoas entram pelo provedor de identidade da organização que o hospeda, e a página de login não oferece ' + + 'formulário de e-mail e senha. O interruptor abaixo não muda isso, e um valor salvo como ativado não é aplicado.', + differsLabel: (running) => `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.', + }, + ru: { + declaredOffLabel: 'Вход по электронной почте и паролю отключён в этом развёртывании', + declaredOffText: 'Собственная конфигурация этого развёртывания отключает вход по электронной почте и паролю, а здесь ' + + 'ничего не сохранено, поэтому переключатель ниже показывает значение консоли по умолчанию (включено), а не то, ' + + 'что работает. Страница входа не предлагает форму электронной почты и пароля. Значение, сохранённое здесь, ' + + 'имеет приоритет над этой конфигурацией.', + managedOffLabel: 'Вход по электронной почте и паролю отключён в этой среде', + managedOffText: 'Эта среда управляется в облаке, и её развёртывание отключает вход по электронной почте и паролю: ' + + 'пользователи входят через поставщика удостоверений организации, которая её размещает, а страница входа не ' + + 'предлагает форму электронной почты и пароля. Переключатель ниже этого не меняет, а сохранённое значение ' + + '«включено» не применяется.', + differsLabel: (running) => `В работающей системе вход по электронной почте и паролю ${running ? 'включён' : 'отключён'}`, + differsText: 'Переключатель ниже показывает сохранённую настройку, а не то, что работает сейчас.', + }, + de: { + declaredOffLabel: 'Die Anmeldung mit E-Mail und Passwort ist in dieser Bereitstellung aus', + declaredOffText: 'Die eigene Konfiguration dieser Bereitstellung schaltet die Anmeldung mit E-Mail und Passwort aus, ' + + 'und hier ist nichts gespeichert. Der Schalter unten zeigt daher den Konsolen-Standard (an), nicht das, was ' + + 'läuft. Die Anmeldeseite bietet kein Formular für E-Mail und Passwort. Ein hier gespeicherter Wert hat ' + + 'Vorrang vor dieser Konfiguration.', + managedOffLabel: 'Die Anmeldung mit E-Mail und Passwort ist in dieser Umgebung aus', + managedOffText: 'Diese Umgebung wird in der Cloud verwaltet, und ihre Bereitstellung schaltet die Anmeldung mit ' + + 'E-Mail und Passwort aus: Man meldet sich über den Identitätsanbieter der Organisation an, die sie hostet, und ' + + 'die Anmeldeseite bietet kein Formular für E-Mail und Passwort. Der Schalter unten ändert daran nichts, und ein ' + + 'auf an gespeicherter Wert wird nicht angewendet.', + differsLabel: (running) => `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.', + }, + ko: { + declaredOffLabel: '이 배포에서는 이메일/비밀번호 로그인이 꺼져 있습니다', + declaredOffText: '이 배포 자체의 구성에서 이메일/비밀번호 로그인이 꺼져 있고 여기에 저장된 값이 없으므로, 아래 스위치는 ' + + '실제 동작이 아니라 콘솔 기본값(켜짐)을 표시합니다. 로그인 페이지에는 이메일/비밀번호 양식이 표시되지 않습니다. ' + + '여기에 저장한 값은 해당 구성보다 우선합니다.', + managedOffLabel: '이 환경에서는 이메일/비밀번호 로그인이 꺼져 있습니다', + managedOffText: '이 환경은 클라우드에서 관리되며, 배포에서 이메일/비밀번호 로그인이 꺼져 있습니다. 사용자는 이 환경을 ' + + '호스팅하는 조직의 ID 공급자를 통해 로그인하며, 로그인 페이지에는 이메일/비밀번호 양식이 표시되지 않습니다. 아래 ' + + '스위치로는 이를 바꿀 수 없으며, 켜짐으로 저장된 값은 적용되지 않습니다.', + differsLabel: (running) => `실행 중인 시스템에서 이메일/비밀번호 로그인이 ${running ? '켜져' : '꺼져'} 있습니다`, + differsText: '아래 스위치는 저장된 설정을 표시하며, 현재 실제로 동작하는 상태와 다릅니다.', + }, +}; + +const COPY_LOCALES = Object.keys(AUTH_LIVE_STATUS_COPY); + +/** The copy for a caller's locale: exact, then by language, else English. */ +export function authLiveStatusCopy(locale: string | undefined): AuthLiveStatusCopy { + const picked = locale ? resolveLocale(locale, COPY_LOCALES) : undefined; + return AUTH_LIVE_STATUS_COPY[(picked ?? 'en') as SettingsCopyLocale]; +} + +/** The reading `bindAuthSettings` gives a resolved toggle: absent or unreadable is the manifest default, on. */ +function shownToggle(value: unknown): boolean { + if (typeof value === 'boolean') return value; + if (typeof value === 'string') return value.toLowerCase() !== 'false'; + if (typeof value === 'number') return value !== 0; + return true; +} + +/** + * The statement, or `undefined` when the switch and the running value agree + * (nothing to state: the page already says what runs). + */ +export function describeEmailPasswordLiveStatus(input: EmailPasswordLiveInput): AuthLiveStatus | undefined { + const shown = shownToggle(input.shown?.value); + if (shown === input.running) return undefined; + const copy = authLiveStatusCopy(input.locale); + const nothingStored = (input.shown?.source ?? 'default') === 'default'; + if (!input.running && input.heldOffByHost) { + // A value stored on that is not applied is the operator's to clear: warn. + return { + label: copy.managedOffLabel, + bannerText: copy.managedOffText, + bannerSeverity: nothingStored ? 'info' : 'warning', + }; + } + if (!input.running && nothingStored) { + return { label: copy.declaredOffLabel, bannerText: copy.declaredOffText, bannerSeverity: 'info' }; + } + return { label: copy.differsLabel(input.running), bannerText: copy.differsText, bannerSeverity: 'warning' }; +} From 022ffdfd80121895dba020055859236842bfc094 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:18:18 +0000 Subject: [PATCH 2/2] chore: changeset for the auth live status Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .changeset/auth-email-password-live-status.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/auth-email-password-live-status.md diff --git a/.changeset/auth-email-password-live-status.md b/.changeset/auth-email-password-live-status.md new file mode 100644 index 00000000000..a1370256ff6 --- /dev/null +++ b/.changeset/auth-email-password-live-status.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth): Setup → Authentication says when email and password sign-in runs other than the switch shows + +Clause-②: no +Metadata-protocol: none + +With nothing stored, `auth.email_password_enabled` resolves to the manifest default (on), while the running config takes the deployment's own `emailAndPassword.enabled`. A deployment that declares it off therefore showed the switch on for a sign-in method that is off. The auth plugin now registers a live-status provider for the `auth` namespace: whenever the switch and the running value disagree, `GET /api/settings/auth` heads the page with the `live_status` banner saying what runs (off by the deployment's configuration; off on a cloud-managed environment that holds it off, `warning` when a stored on is not applied; or, for any other disagreement, what runs), in the caller's language across the 11 platform locales. Nothing is stated while they agree. The resolved `values` and every save are unchanged: a stored value still wins where it is applied.