From b5ecfafb2b16d9eb6aab887651a1595cc8c220f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:09:20 +0000 Subject: [PATCH 1/6] fix(plugin-auth): the auth settings save judges the sign-in floor by what the page offers under the local sign-in path off Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSSVaNcDs8HPSoGV6V --- .../src/sign-in-method-floor.test.ts | 128 ++++++++++++++ .../plugin-auth/src/sign-in-method-floor.ts | 157 +++++++++++++----- 2 files changed, 245 insertions(+), 40 deletions(-) diff --git a/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts b/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts index 7d221d6568d..3ca5a2864b8 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts @@ -47,6 +47,16 @@ * declares the provider, and the recovery `OS_AUTH_EMAIL_PASSWORD_ENABLED=true`; * 10. the judge and the report against a fault the composition cannot make: * an unreadable provider list is 503 on the delete and silence at boot. + * + * Under the local sign-in path behind direct sign-in `'off'` (the page draws no + * email and password and no phone sign-in, on or not): + * 11. the settings save refuses removing Google when it is the last way in + * with email and password ON, with its own copy (`googleLocalOff`), and + * never refuses the `email_password_enabled` key; CONTROL: the path + * `hidden` accepts the same Google change; + * 12. the exits still count under `'off'`, on the save, the delete and the + * boot report: another provider row, a social or OIDC provider with + * credentials, a host handoff. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -78,6 +88,7 @@ import { providerCredentialsFrom, reportIfNoSignInMethodAtBoot, resolveNoSignInMethodReport, + signInMethodFloorPredicate, ssoProviderDeleteRefusal, type SignInMethodConfigView, type SignInMethodFloorDeps, @@ -445,6 +456,60 @@ describe('the auth settings save keeps a way to sign in', () => { expect(has({ id: 'keycloak', type: 'oidc' })).toBe(false); }); + // ── 11. The local sign-in path behind direct sign-in is off ────────────── + + it('under the local sign-in path off, removing the last Google is refused with email and password on, in its own copy', async () => { + const { settings, manager } = await boot({ pluginOptions: { directSignIn: { localSignIn: 'off' } } }); + expect(manager.getPublicConfig().features.localSignIn).toBe('off'); + expect(passwordOn(manager)).toBe(true); + await saveGoogle(settings, manager); + + for (const [patch, field] of [ + [{ google_enabled: false }, 'google_enabled'], + [{ google_client_secret: null }, 'google_client_secret'], + // Turning email and password on in the same save does not help: the page draws it neither way. + [{ google_enabled: false, email_password_enabled: true }, 'google_enabled'], + ] as const) { + const refusal = await refusalOf(settings.setMany('auth', patch)); + expect(refusal.fields).toEqual([ + expect.objectContaining({ + field, + code: 'invalid_value', + message: SIGN_IN_FLOOR_COPY.en.googleLocalOff, + constraint: { lastSignInMethod: 'google' }, + }), + ]); + } + expect(googleOn(manager)).toBe(true); + + // The email and password key itself removes nothing the page offers, so it is never refused under off. + await settings.setMany('auth', { email_password_enabled: false }); + await vi.waitFor(() => expect(passwordOn(manager)).toBe(false)); + await settings.setMany('auth', { email_password_enabled: true }); + await vi.waitFor(() => expect(passwordOn(manager)).toBe(true)); + expect(googleOn(manager)).toBe(true); + }); + + it('CONTROL: with the local sign-in path hidden, the same Google change goes through while email and password is on', async () => { + const { settings, manager } = await boot({ pluginOptions: { directSignIn: { localSignIn: 'hidden' } } }); + expect(manager.getPublicConfig().features.localSignIn).toBe('hidden'); + await saveGoogle(settings, manager); + await settings.setMany('auth', { google_enabled: false }); + await vi.waitFor(() => expect(googleOn(manager)).toBe(false)); + }); + + it('under the local sign-in path off, another social provider keeps the way in, so removing Google goes through', async () => { + const { settings, manager } = await boot({ + pluginOptions: { + directSignIn: { localSignIn: 'off' }, + socialProviders: { github: { clientId: 'gh-id', clientSecret: 'gh-secret' } }, + }, + }); + await saveGoogle(settings, manager); + await settings.setMany('auth', { google_enabled: false }); + await vi.waitFor(() => expect(googleOn(manager)).toBe(false)); + }); + // ── 5. Recovery for a deployment that already stored the dead end ───────── it('OS_AUTH_EMAIL_PASSWORD_ENABLED=true overrides a stored false (control: without it, the stored false rules)', async () => { @@ -833,6 +898,69 @@ describe('the floor judges a provider delete and a boot by what it can read (#30 expect(await resolveNoSignInMethodReport(deps({ config: EMAIL_OFF_HIDDEN, rows: [] }))).toContain('OS_AUTH_EMAIL_PASSWORD_ENABLED=true and restart'); }); + // ── 12. The exits that still count under the local sign-in path off ────── + + const LOCAL_OFF_SSO: SignInMethodConfigView = { + emailPassword: { enabled: true }, + socialProviders: [], + features: { sso: true, phoneNumber: true, localSignIn: 'off' }, + }; + + it.each([ + { name: 'another provider row', over: { rows: [{ provider_id: 'okta' }, { provider_id: 'entra' }] } }, + { name: 'a social provider with credentials', over: { config: { ...LOCAL_OFF_SSO, socialProviders: [{ id: 'github', type: 'social' }] } } }, + { name: 'an OIDC provider with credentials', over: { config: { ...LOCAL_OFF_SSO, socialProviders: [{ id: 'keycloak', type: 'oidc' }] } } }, + { name: 'a host sign-in handoff', over: { hostSignInHandoff: true } }, + ])('under the local sign-in path off, the delete of a provider passes with $name', async ({ over }) => { + const d = deps({ config: LOCAL_OFF_SSO, rows: [{ provider_id: 'okta' }], ...over }); + await expect(ssoProviderDeleteRefusal(d, 'okta')).resolves.toBeUndefined(); + }); + + it.each([ + { name: 'a social provider with credentials', over: { config: { ...LOCAL_OFF_SSO, socialProviders: [{ id: 'github', type: 'social' }] } } }, + { name: 'an OIDC provider with credentials', over: { config: { ...LOCAL_OFF_SSO, socialProviders: [{ id: 'keycloak', type: 'oidc' }] } } }, + { name: 'a host sign-in handoff', over: { hostSignInHandoff: true } }, + { name: 'an identity provider row', over: { rows: [{ provider_id: 'okta' }] } }, + ])('under the local sign-in path off, a boot with $name says nothing', async ({ over }) => { + expect(await resolveNoSignInMethodReport(deps({ config: LOCAL_OFF_SSO, rows: [], ...over }))).toBeNull(); + }); + + it('the settings save under the local sign-in path off: email and password and phone count for nothing, the exits still do', async () => { + const GOOGLE_ONLY_OFF: SignInMethodConfigView = { + emailPassword: { enabled: true }, + socialProviders: [{ id: 'google', type: 'social' }], + features: { sso: false, phoneNumber: true, localSignIn: 'off' }, + }; + const save = (d: SignInMethodFloorDeps, batch: Record, locale?: string) => { + const [key] = Object.keys(batch); + return signInMethodFloorPredicate(d, async () => undefined)({ key, next: batch[key], batch, locale }); + }; + // Google is the last way in the page draws: refused in the off copy, in the caller's language. + await expect(save(deps({ config: GOOGLE_ONLY_OFF }), { google_enabled: false }, 'de')).resolves.toEqual({ + message: SIGN_IN_FLOOR_COPY.de.googleLocalOff, + constraint: { lastSignInMethod: 'google' }, + }); + // The email and password key is never refused under off, on or off. + await expect(save(deps({ config: GOOGLE_ONLY_OFF }), { email_password_enabled: false })).resolves.toBeUndefined(); + // The exits under off. + for (const d of [ + deps({ config: { ...GOOGLE_ONLY_OFF, socialProviders: [...GOOGLE_ONLY_OFF.socialProviders!, { id: 'github', type: 'social' }] } }), + deps({ config: { ...GOOGLE_ONLY_OFF, socialProviders: [...GOOGLE_ONLY_OFF.socialProviders!, { id: 'keycloak', type: 'oidc' }] } }), + deps({ config: GOOGLE_ONLY_OFF, hostSignInHandoff: true }), + deps({ config: { ...GOOGLE_ONLY_OFF, features: { ...GOOGLE_ONLY_OFF.features, sso: true } }, rows: [{ provider_id: 'okta' }] }), + ]) { + await expect(save(d, { google_enabled: false })).resolves.toBeUndefined(); + } + // CONTROL: the path hidden counts email and password (and phone) again. + const HIDDEN = { ...GOOGLE_ONLY_OFF, features: { ...GOOGLE_ONLY_OFF.features, localSignIn: 'hidden' as const } }; + await expect(save(deps({ config: HIDDEN }), { google_enabled: false })).resolves.toBeUndefined(); + // CONTROL: email and password off with the path hidden keeps the email-off copy. + const EMAIL_OFF_HIDDEN = { ...HIDDEN, emailPassword: { enabled: false }, features: { localSignIn: 'hidden' as const } }; + await expect(save(deps({ config: EMAIL_OFF_HIDDEN }), { google_enabled: false })).resolves.toMatchObject({ + message: SIGN_IN_FLOOR_COPY.en.google, + }); + }); + it('says it once at error (warn on a sink without error), and never throws', async () => { const error = vi.fn(); const warn = vi.fn(); diff --git a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts index 5f399350d89..de318e83dfb 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts @@ -40,17 +40,23 @@ * * The local sign-in path behind direct sign-in (`features.localSignIn`, served * only while direct sign-in is on): under `'off'` the page draws no local way - * in, so the provider delete and the boot report count neither email and - * password nor phone sign-in there, on or not ({@link pageOffersLocalSignIn}, - * the page's own predicate). The settings save is not judged that way yet. + * in, so the settings save, the provider delete and the boot report count + * neither email and password nor phone sign-in there, on or not + * ({@link pageOffersLocalSignIn}, the page's own predicate). * * ## The changes refused * * - `email_password_enabled` off when nothing else is in force after the save; - * - with email and password off after the save, the Google change that - * removes a Google provider in force and leaves nothing else: - * `google_enabled` off, or clearing a client credential that no environment - * variable and no stack config backs. + * - with email and password off after the save, or not offered by the page + * (the local sign-in path `'off'`), the Google change that removes a Google + * provider in force and leaves nothing else: `google_enabled` off, or + * clearing a client credential that no environment variable and no stack + * config backs. Under `'off'` the refusal says so (`googleLocalOff`): the + * email-off copy's remedy, keep email and password on, does nothing there. + * + * Under `'off'` the `email_password_enabled` key itself is never refused: + * the page draws email and password neither way, so the save removes no way + * in the page offers. * * Each is judged on the state AFTER the whole save (`batch`, every key the save * sets), not on one key against the rest as they stand: asked one key at a @@ -254,6 +260,8 @@ export async function otherSignInMethods( interface SignInFloorCopy { emailPassword: string; google: string; + /** The same Google change, while the sign-in page does not offer local sign-in. */ + googleLocalOff: string; /** Deleting the last identity provider ({@link ssoProviderDeleteRefusal}). */ enterpriseSso: string; /** The same, while email and password is on but the sign-in page does not offer local sign-in. */ @@ -277,6 +285,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'With email and password off, this change to Google would leave no way to sign in, so everyone would be ' + 'locked out, administrators included. Keep email and password sign-in on, or set up another sign-in method, ' + 'before or in this save.', + googleLocalOff: + 'The sign-in page offers no local sign-in (the local sign-in path behind direct sign-in is off), so email and ' + + 'password does not count, and this change to Google would leave no way to sign in: everyone would be locked ' + + 'out, administrators included. Keep Google sign-in, set up another sign-in method before or in this save, or ' + + 'first set the local sign-in path back to hidden with email and password sign-in on.', enterpriseSso: 'This is the last enterprise SSO identity provider, and with email and password off nothing else signs ' + 'anyone in, so deleting it would lock everyone out, administrators included. First turn email and password ' + @@ -288,8 +301,8 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'the local sign-in path back to hidden with email and password sign-in on, then delete this one.', enterpriseSsoUnverified: 'The identity provider was not deleted: the list of identity providers could not be read to confirm that ' + - 'another way to sign in remains, and with email and password off this one may be the last. Try again once ' + - 'the database is reachable.', + 'another way to sign in remains, and the sign-in page offers no email and password sign-in, so this one may be ' + + 'the last. Try again once the database is reachable.', }, 'zh-CN': { emailPassword: @@ -298,6 +311,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { google: '邮箱/密码登录关闭时,这项 Google 修改会导致没有任何登录方式,所有人(包括管理员)都将无法登录。' + '请保持邮箱/密码登录开启,或在本次保存之前或同时配置另一种登录方式。', + googleLocalOff: + '登录页不提供本地登录(直接登录的本地登录路径已关闭),邮箱/密码登录不算一种登录方式,这项 Google ' + + '修改会导致没有任何登录方式,所有人(包括管理员)都将无法登录。请保留 Google ' + + '登录、在本次保存之前或同时配置另一种登录方式,或先把本地登录路径改回 hidden 并开启邮箱/密码登录。', enterpriseSso: '这是最后一个企业 SSO 身份提供方,邮箱/密码登录又已关闭,没有其他登录方式,删除后所有人(包括管理员)都将无法登录。' + '请先重新开启邮箱/密码登录,或登记另一个身份提供方、配置另一种登录方式,然后再删除它。', @@ -306,8 +323,7 @@ export const SIGN_IN_FLOOR_COPY: Record = { '删除后所有人(包括管理员)都将无法登录。请先登记另一个身份提供方、配置另一种登录方式,或把本地登录路径改回 hidden 并开启邮箱/密码登录,' + '然后再删除它。', enterpriseSsoUnverified: - '身份提供方未删除:无法读取身份提供方列表来确认仍有其他登录方式,而邮箱/密码登录已关闭,它可能是最后一种。' + - '请在数据库可以访问时重试。', + '身份提供方未删除:无法读取身份提供方列表来确认仍有其他登录方式,而登录页不提供邮箱/密码登录,它可能是最后一种。请在数据库可以访问时重试。', }, 'ja-JP': { emailPassword: @@ -319,6 +335,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'メール/パスワードログインがオフの状態でこの Google の変更を行うとログイン方法がなくなり、管理者を含む全員が' + 'ログインできなくなります。メール/パスワードログインをオンのままにするか、この保存の前か同じ保存で別のログイン' + '方法を設定してください。', + googleLocalOff: + 'ログインページはローカルログインを表示しません(ダイレクトサインインのローカルログインパスがオフ)。そのためメール/パスワードはログイン方法に数えられず、この ' + + 'Google の変更を行うとログイン方法がなくなり、管理者を含む全員がログインできなくなります。Google ' + + 'ログインを残すか、この保存の前か同じ保存で別のログイン方法を設定するか、先にローカルログインパスを hidden ' + + 'に戻してメール/パスワードログインをオンにしてください。', enterpriseSso: 'これは最後のエンタープライズ SSO の ID プロバイダーで、メール/パスワードログインもオフのため他にログイン方法が' + 'ありません。削除すると管理者を含む全員がログインできなくなります。先にメール/パスワードログインをオンに戻すか、' + @@ -329,9 +350,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'なります。先に別の ID プロバイダーを登録するか、別のログイン方法を設定するか、ローカルログインパスを hidden に戻してメール/パスワードログインをオンにしてから' + '削除してください。', enterpriseSsoUnverified: - 'ID プロバイダーは削除されませんでした。ID プロバイダーの一覧を読み取れず、他のログイン方法が残ることを確認できません' + - 'でした。メール/パスワードログインがオフのため、これが最後のログイン方法かもしれません。データベースに接続できる' + - 'ようになってから再試行してください。', + 'ID プロバイダーは削除されませんでした。ID ' + + 'プロバイダーの一覧を読み取れず、他のログイン方法が残ることを確認できませんでした。ログインページはメール/パスワードログ' + + 'インを表示しないため、これが最後のログイン方法かもしれません。データベースに接続できるようになってから再試行してください。', }, 'es-ES': { emailPassword: @@ -344,6 +365,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Con el correo y la contraseña desactivados, este cambio en Google dejaría sin ninguna forma de iniciar ' + 'sesión, así que todo el mundo quedaría fuera, incluidos los administradores. Mantenga activado el inicio de ' + 'sesión con correo y contraseña o configure otro método, antes o en este mismo guardado.', + googleLocalOff: + 'La página de inicio de sesión no ofrece el inicio de sesión local (la ruta local del inicio de sesión directo ' + + 'está desactivada), así que el correo y la contraseña no cuentan, y este cambio en Google dejaría sin ninguna ' + + 'forma de iniciar sesión: todo el mundo quedaría fuera, incluidos los administradores. Mantenga el inicio de ' + + 'sesión con Google, configure otro método antes o en este mismo guardado, o vuelva primero a poner la ruta ' + + 'local en hidden con el inicio de sesión con correo y contraseña activado.', enterpriseSso: 'Este es el último proveedor de identidad de SSO empresarial y, con el correo y la contraseña desactivados, ' + 'nada más permite iniciar sesión, así que eliminarlo dejaría fuera a todo el mundo, incluidos los ' + @@ -357,8 +384,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'después elimine este.', enterpriseSsoUnverified: 'El proveedor de identidad no se ha eliminado: no se pudo leer la lista de proveedores de identidad para ' + - 'confirmar que queda otra forma de iniciar sesión y, con el correo y la contraseña desactivados, este podría ' + - 'ser el último. Vuelva a intentarlo cuando la base de datos esté disponible.', + 'confirmar que queda otra forma de iniciar sesión y, como la página de inicio de sesión no ofrece el inicio de ' + + 'sesión con correo y contraseña, este podría ser el último. Vuelva a intentarlo cuando la base de datos esté ' + + 'disponible.', }, 'zh-Hant': { emailPassword: @@ -367,6 +395,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { google: '電子郵件/密碼登入關閉時,這項 Google 變更會導致沒有任何登入方式,所有人(包括管理員)都將無法登入。' + '請保持電子郵件/密碼登入開啟,或在本次儲存之前或同時設定另一種登入方式。', + googleLocalOff: + '登入頁不提供本機登入(直接登入的本機登入路徑已關閉),電子郵件/密碼登入不算一種登入方式,這項 Google ' + + '變更會導致沒有任何登入方式,所有人(包括管理員)都將無法登入。請保留 Google ' + + '登入、在本次儲存之前或同時設定另一種登入方式,或先把本機登入路徑改回 hidden 並開啟電子郵件/密碼登入。', enterpriseSso: '這是最後一個企業 SSO 身分提供者,電子郵件/密碼登入又已關閉,沒有其他登入方式,刪除後所有人(包括管理員)都將無法登入。' + '請先重新開啟電子郵件/密碼登入,或登記另一個身分提供者、設定另一種登入方式,然後再刪除它。', @@ -375,8 +407,7 @@ export const SIGN_IN_FLOOR_COPY: Record = { '刪除後所有人(包括管理員)都將無法登入。請先登記另一個身分提供者、設定另一種登入方式,或把本機登入路徑改回 hidden 並開啟電子郵件/密碼登入,' + '然後再刪除它。', enterpriseSsoUnverified: - '身分提供者未刪除:無法讀取身分提供者清單來確認仍有其他登入方式,而電子郵件/密碼登入已關閉,它可能是最後一種。' + - '請在資料庫可以存取時重試。', + '身分提供者未刪除:無法讀取身分提供者清單來確認仍有其他登入方式,而登入頁不提供電子郵件/密碼登入,它可能是最後一種。請在資料庫可以存取時重試。', }, ar: { emailPassword: @@ -387,6 +418,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'مع إيقاف البريد الإلكتروني وكلمة المرور، لن يترك هذا التغيير على Google أي طريقة لتسجيل الدخول، فيُمنع الجميع ' + 'من الدخول بمن فيهم المسؤولون. أبقِ تسجيل الدخول بالبريد الإلكتروني وكلمة المرور مفعّلًا، أو اضبط طريقة أخرى ' + 'لتسجيل الدخول قبل هذا الحفظ أو ضمنه.', + googleLocalOff: + 'صفحة تسجيل الدخول لا تعرض تسجيل الدخول المحلي (مسار تسجيل الدخول المحلي خلف تسجيل الدخول المباشر متوقف)، فلا ' + + 'يُحتسب البريد الإلكتروني وكلمة المرور، ولن يترك هذا التغيير على Google أي طريقة لتسجيل الدخول، فيُمنع الجميع ' + + 'من الدخول بمن فيهم المسؤولون. أبقِ تسجيل الدخول عبر Google، أو اضبط طريقة أخرى لتسجيل الدخول قبل هذا الحفظ أو ' + + 'ضمنه، أو أعد أولًا مسار تسجيل الدخول المحلي إلى hidden مع تشغيل تسجيل الدخول بالبريد الإلكتروني وكلمة المرور.', enterpriseSso: 'هذا آخر موفّر هوية SSO مؤسسي، ومع إيقاف البريد الإلكتروني وكلمة المرور لا شيء غيره يتيح لأحد تسجيل الدخول، ' + 'لذا فإن حذفه سيمنع الجميع من الدخول بمن فيهم المسؤولون. أعد أولًا تفعيل تسجيل الدخول بالبريد الإلكتروني ' + @@ -397,8 +433,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'المسؤولون. سجّل أولًا موفّر هوية آخر، أو أعدّ طريقة تسجيل دخول أخرى، أو أعد مسار تسجيل الدخول المحلي إلى hidden مع تشغيل تسجيل الدخول بالبريد الإلكتروني وكلمة المرور، ' + 'ثم احذف هذا الموفّر.', enterpriseSsoUnverified: - 'لم يُحذف موفّر الهوية: تعذّرت قراءة قائمة موفّري الهوية للتأكد من بقاء طريقة أخرى لتسجيل الدخول، ومع إيقاف ' + - 'البريد الإلكتروني وكلمة المرور قد يكون هذا آخرها. أعد المحاولة عندما تصبح قاعدة البيانات متاحة.', + 'لم يُحذف موفّر الهوية: تعذّرت قراءة قائمة موفّري الهوية للتأكد من بقاء طريقة أخرى لتسجيل الدخول، ولأن صفحة ' + + 'تسجيل الدخول لا تعرض تسجيل الدخول بالبريد الإلكتروني وكلمة المرور قد يكون هذا آخرها. أعد المحاولة عندما تصبح ' + + 'قاعدة البيانات متاحة.', }, fr: { emailPassword: @@ -410,6 +447,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Avec l’e-mail et le mot de passe désactivés, cette modification de Google ne laisserait aucun moyen de se ' + 'connecter : tout le monde serait bloqué, administrateurs compris. Laissez la connexion par e-mail et mot de ' + 'passe activée, ou configurez une autre méthode de connexion, avant ou dans cet enregistrement.', + googleLocalOff: + 'La page de connexion n’offre aucune connexion locale (le chemin de connexion locale derrière la connexion ' + + 'directe est désactivé) : l’e-mail et le mot de passe ne comptent donc pas, et cette modification de Google ne ' + + 'laisserait aucun moyen de se connecter : tout le monde serait bloqué, administrateurs compris. Conservez la ' + + 'connexion Google, configurez une autre méthode de connexion avant ou dans cet enregistrement, ou remettez ' + + 'd’abord le chemin de connexion locale à hidden avec la connexion par e-mail et mot de passe activée.', enterpriseSso: 'C’est le dernier fournisseur d’identité SSO d’entreprise et, avec l’e-mail et le mot de passe désactivés, ' + 'rien d’autre ne permet de se connecter : le supprimer bloquerait tout le monde, administrateurs compris. ' + @@ -423,8 +466,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'locale à hidden avec la connexion par e-mail et mot de passe activée, puis supprimez celui-ci.', enterpriseSsoUnverified: 'Le fournisseur d’identité n’a pas été supprimé : la liste des fournisseurs d’identité n’a pas pu être lue ' + - 'pour vérifier qu’un autre moyen de connexion subsiste et, avec l’e-mail et le mot de passe désactivés, ' + - 'celui-ci est peut-être le dernier. Réessayez quand la base de données sera accessible.', + 'pour vérifier qu’un autre moyen de connexion subsiste et, comme la page de connexion n’offre pas la connexion ' + + 'par e-mail et mot de passe, celui-ci est peut-être le dernier. Réessayez quand la base de données sera ' + + 'accessible.', }, 'pt-BR': { emailPassword: @@ -436,6 +480,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Com o e-mail e a senha desativados, esta alteração no Google deixaria sem nenhuma forma de entrar, então todos ' + 'ficariam bloqueados, inclusive os administradores. Mantenha o login com e-mail e senha ativado ou configure ' + 'outro método de login, antes ou neste mesmo salvamento.', + googleLocalOff: + 'A página de login não oferece login local (o caminho de login local por trás do login direto está ' + + 'desativado), então o e-mail e a senha não contam, e esta alteração no Google deixaria sem nenhuma forma de ' + + 'entrar: todos ficariam bloqueados, inclusive os administradores. Mantenha o login com Google, configure outro ' + + 'método de login antes ou neste mesmo salvamento, ou volte primeiro o caminho de login local para hidden com o ' + + 'login por e-mail e senha ativado.', enterpriseSso: 'Este é o último provedor de identidade de SSO corporativo e, com o e-mail e a senha desativados, nada mais ' + 'permite entrar, então excluí-lo bloquearia todos, inclusive os administradores. Primeiro reative o login com ' + @@ -448,8 +498,8 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'outro método de login ou volte o caminho de login local para hidden com o login por e-mail e senha ativado, e depois exclua este.', enterpriseSsoUnverified: 'O provedor de identidade não foi excluído: não foi possível ler a lista de provedores de identidade para ' + - 'confirmar que resta outra forma de entrar e, com o e-mail e a senha desativados, este pode ser o último. ' + - 'Tente novamente quando o banco de dados estiver acessível.', + 'confirmar que resta outra forma de entrar e, como a página de login não oferece login com e-mail e senha, ' + + 'este pode ser o último. Tente novamente quando o banco de dados estiver acessível.', }, ru: { emailPassword: @@ -461,6 +511,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'При отключённом входе по электронной почте и паролю это изменение Google не оставит ни одного способа входа, ' + 'и доступ потеряют все, включая администраторов. Оставьте вход по электронной почте и паролю включённым или ' + 'настройте другой способ входа до этого сохранения или в нём же.', + googleLocalOff: + 'Страница входа не предлагает локальный вход (локальный путь входа за прямым входом отключён), поэтому вход по ' + + 'электронной почте и паролю не учитывается, и это изменение Google не оставит ни одного способа входа: доступ ' + + 'потеряют все, включая администраторов. Оставьте вход через Google, настройте другой способ входа до этого ' + + 'сохранения или в нём же либо сначала верните локальному пути входа значение hidden с включённым входом по ' + + 'почте и паролю.', enterpriseSso: 'Это последний корпоративный поставщик удостоверений SSO, а вход по электронной почте и паролю отключён, так ' + 'что войти больше нечем: его удаление лишит доступа всех, включая администраторов. Сначала снова включите вход ' + @@ -473,8 +529,8 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'или верните локальному пути входа значение hidden с включённым входом по почте и паролю, а затем удалите этого.', enterpriseSsoUnverified: 'Поставщик удостоверений не удалён: не удалось прочитать список поставщиков удостоверений, чтобы убедиться, ' + - 'что останется другой способ входа, а при отключённом входе по электронной почте и паролю этот может быть ' + - 'последним. Повторите попытку, когда база данных станет доступна.', + 'что останется другой способ входа, а страница входа не предлагает вход по электронной почте и паролю, поэтому ' + + 'этот может быть последним. Повторите попытку, когда база данных станет доступна.', }, de: { emailPassword: @@ -486,6 +542,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Bei ausgeschalteter Anmeldung mit E-Mail und Passwort ließe diese Änderung an Google keine Möglichkeit zur ' + 'Anmeldung, und alle wären ausgesperrt, Administratoren eingeschlossen. Lassen Sie die Anmeldung mit E-Mail ' + 'und Passwort eingeschaltet oder richten Sie vor oder in diesem Speichervorgang eine andere Anmeldemethode ein.', + googleLocalOff: + 'Die Anmeldeseite bietet keine lokale Anmeldung an (der lokale Anmeldepfad hinter der Direktanmeldung ist ' + + 'aus), daher zählen E-Mail und Passwort nicht, und diese Änderung an Google ließe keine Möglichkeit zur ' + + 'Anmeldung: Alle wären ausgesperrt, Administratoren eingeschlossen. Behalten Sie die Google-Anmeldung, richten ' + + 'Sie vor oder in diesem Speichervorgang eine andere Anmeldemethode ein, oder setzen Sie zuerst den lokalen ' + + 'Anmeldepfad wieder auf hidden mit eingeschalteter Anmeldung per E-Mail und Passwort.', enterpriseSso: 'Dies ist der letzte Enterprise-SSO-Identitätsanbieter, und bei ausgeschalteter Anmeldung mit E-Mail und ' + 'Passwort meldet nichts anderes jemanden an. Ihn zu löschen würde daher alle aussperren, Administratoren ' + @@ -498,9 +560,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Identitätsanbieter, richten Sie eine andere Anmeldemethode ein oder setzen Sie den lokalen Anmeldepfad wieder ' + 'auf hidden mit eingeschalteter Anmeldung per E-Mail und Passwort, und löschen Sie diesen dann.', enterpriseSsoUnverified: - 'Der Identitätsanbieter wurde nicht gelöscht: Die Liste der Identitätsanbieter konnte nicht gelesen werden, ' + - 'um zu bestätigen, dass eine andere Anmeldemöglichkeit bleibt, und bei ausgeschalteter Anmeldung mit E-Mail ' + - 'und Passwort ist dieser vielleicht der letzte. Versuchen Sie es erneut, sobald die Datenbank erreichbar ist.', + 'Der Identitätsanbieter wurde nicht gelöscht: Die Liste der Identitätsanbieter konnte nicht gelesen werden, um ' + + 'zu bestätigen, dass eine andere Anmeldemöglichkeit bleibt, und da die Anmeldeseite keine Anmeldung mit E-Mail ' + + 'und Passwort anbietet, ist dieser vielleicht der letzte. Versuchen Sie es erneut, sobald die Datenbank ' + + 'erreichbar ist.', }, ko: { emailPassword: @@ -511,6 +574,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { '이메일/비밀번호 로그인이 꺼진 상태에서 이 Google 변경을 저장하면 로그인할 방법이 전혀 남지 않아 관리자를 포함한 ' + '모든 사람이 로그인할 수 없게 됩니다. 이메일/비밀번호 로그인을 켜 두거나, 이번 저장 전이나 이번 저장에서 다른 ' + '로그인 방법을 설정하세요.', + googleLocalOff: + '로그인 페이지는 로컬 로그인을 제공하지 않습니다(직접 로그인의 로컬 로그인 경로가 꺼져 있음). 따라서 ' + + '이메일/비밀번호는 로그인 방법으로 계산되지 않으며, 이 Google 변경을 저장하면 로그인할 방법이 전혀 ' + + '남지 않아 관리자를 포함한 모든 사람이 로그인할 수 없게 됩니다. Google 로그인을 유지하거나, 이번 ' + + '저장 전이나 이번 저장에서 다른 로그인 방법을 설정하거나, 먼저 로컬 로그인 경로를 hidden으로 ' + + '되돌리고 이메일/비밀번호 로그인을 켜세요.', enterpriseSso: '이것은 마지막 엔터프라이즈 SSO ID 공급자이며, 이메일/비밀번호 로그인도 꺼져 있어 다른 로그인 방법이 없습니다. ' + '삭제하면 관리자를 포함한 모든 사람이 로그인할 수 없게 됩니다. 먼저 이메일/비밀번호 로그인을 다시 켜거나, 다른 ID ' + @@ -521,9 +590,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { '됩니다. 먼저 다른 ID 공급자를 등록하거나, 다른 로그인 방법을 설정하거나, 로컬 로그인 경로를 hidden으로 되돌리고 이메일/비밀번호 로그인을 켠 ' + '다음 이 공급자를 삭제하세요.', enterpriseSsoUnverified: - 'ID 공급자를 삭제하지 않았습니다. 다른 로그인 방법이 남아 있는지 확인하기 위해 ID 공급자 목록을 읽을 수 없었고, ' + - '이메일/비밀번호 로그인이 꺼져 있어 이것이 마지막 방법일 수 있습니다. 데이터베이스에 연결할 수 있게 되면 다시 ' + - '시도하세요.', + 'ID 공급자를 삭제하지 않았습니다. 다른 로그인 방법이 남아 있는지 확인하기 위해 ID 공급자 목록을 읽을 ' + + '수 없었고, 로그인 페이지가 이메일/비밀번호 로그인을 제공하지 않으므로 이것이 마지막 방법일 수 있습니다. ' + + '데이터베이스에 연결할 수 있게 되면 다시 시도하세요.', }, }; @@ -624,29 +693,37 @@ async function googleAfter( /** * The write predicate shared by {@link SIGN_IN_FLOOR_KEYS}. It refuses when the - * state after the whole save leaves email and password off and no other way in: - * at `email_password_enabled` when the save turns it off, and at a `google_*` - * key when the save removes a Google provider that was in force. + * state after the whole save leaves the sign-in page no email and password + * ({@link pageOffersEmailPassword}: off, or the local sign-in path `'off'`) and + * no other way in the page offers: at `email_password_enabled` when the save + * turns it off (never under `'off'`, where that key changes nothing the page + * draws), and at a `google_*` key when the save removes a Google provider that + * was in force. */ export function signInMethodFloorPredicate(deps: SignInMethodFloorDeps, read: AuthSettingReader) { return async (input: SignInFloorWriteInput): Promise => { const { key, next, locale } = input; const batch = input.batch ?? { [key]: next }; const config = deps.publicConfig(); - const emailPasswordAfter = Object.prototype.hasOwnProperty.call(batch, 'email_password_enabled') + // The page draws no local way in under the local sign-in path `'off'`, so + // email and password counts for nothing there, whatever this save sets it to. + const localOffered = pageOffersLocalSignIn(config); + if (!localOffered && key === 'email_password_enabled') return undefined; + const emailPasswordAfter = localOffered && (Object.prototype.hasOwnProperty.call(batch, 'email_password_enabled') ? readToggle( await valueAfter(read, input, batch, 'email_password_enabled'), deps.declaredEmailPasswordEnabled?.() ?? true, ) - : config.emailPassword?.enabled !== false; + : config.emailPassword?.enabled !== false); if (emailPasswordAfter) return undefined; const googleNow = (config.socialProviders ?? []).some((p) => isSettingsGoogle(p) && providerCounts(deps, p)); if (key !== 'email_password_enabled' && !googleNow) return undefined; - if ((await otherSignInMethods(deps, { withoutGoogle: true })).length > 0) return undefined; + if ((await otherSignInMethods(deps, { withoutGoogle: true, asThePageOffers: true })).length > 0) return undefined; if (await googleAfter(deps, read, input, batch, googleNow)) return undefined; + const copy = signInFloorCopy(locale); return key === 'email_password_enabled' - ? { message: signInFloorCopy(locale).emailPassword, constraint: { lastSignInMethod: 'email_password' } } - : { message: signInFloorCopy(locale).google, constraint: { lastSignInMethod: 'google' } }; + ? { message: copy.emailPassword, constraint: { lastSignInMethod: 'email_password' } } + : { message: localOffered ? copy.google : copy.googleLocalOff, constraint: { lastSignInMethod: 'google' } }; }; } From 0e4d653b675f7e9f62639d0ae02d950372ecb421 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:16:49 +0000 Subject: [PATCH 2/6] fix(plugin-auth): a client the IP allow-list refuses at the direct sign-in door lands on the sign-in page with the refusal code Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSSVaNcDs8HPSoGV6V --- content/docs/permissions/sso.mdx | 23 ++++--- .../plugins/plugin-auth/src/auth-plugin.ts | 16 ++++- .../plugin-auth/src/auth-route-ledger.ts | 2 +- .../plugin-auth/src/direct-sign-in.test.ts | 67 ++++++++++++++++++- .../plugins/plugin-auth/src/direct-sign-in.ts | 47 ++++++++++++- 5 files changed, 142 insertions(+), 13 deletions(-) diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index 0e95930c278..95990755579 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -777,16 +777,21 @@ OAuth client's hand-off and when no provider can be started. It changes the form only: `POST /api/v1/auth/sign-in/email` still accepts a password, and the `/register` and `/forgot-password` pages are not changed by it. -Because the form then offers no email and password and no phone sign-in, two -checks that keep a way to sign in do not count them under `off`, even while -they are switched on: Setup's **Delete SSO Provider** on the last identity -provider is refused `409 DELETE_RESTRICTED` with nothing deleted, and a boot -with no identity provider reports at **error** under the grep token -`no_sign_in_method_at_boot`. Recover by setting -`OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden`, and +Because the form then offers no email and password and no phone sign-in, the +three checks that keep a way to sign in do not count them under `off`, even +while they are switched on. Saving the auth settings refuses a Google change +that removes the last way in (Google switched off, or a client credential +cleared that no environment variable backs) with `400 SETTINGS_VALIDATION`, +and turning email and password on in that save does not help. The email and +password switch itself is never refused under `off`, because the form draws it +neither way. Setup's **Delete SSO Provider** on the last identity provider is +refused `409 DELETE_RESTRICTED` with nothing deleted. A boot with no identity +provider reports at **error** under the grep token +`no_sign_in_method_at_boot`. Another identity provider, a social or OIDC +provider with a client ID and secret, or a host sign-in handoff still counts. +Recover by setting `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden`, and `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` too when email and password sign-in is -off, then restarting. The auth settings save still counts email and password -under `off`; that check is still open. +off, then restarting. **What a visit does.** The Console sign-in page reads `features.directSignIn` from `GET /api/v1/auth/config`. That is `true` only while a provider can be diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 9658e0c011d..1db23f80a26 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -128,7 +128,11 @@ import { resolveKernelCache } from './kernel-cache.js'; import { authIdentityManifest } from './manifest.js'; import { scheduleLegacySsoSecretMigration } from './sso-client-secret.js'; import { reportSsoProvidersWithNonBareDomainEntries } from './sso-stored-domain-entries.js'; -import type { DirectSignInOptions } from './direct-sign-in.js'; +import { + directSignInNetworkRefusal, + isDirectSignInDoorNavigation, + type DirectSignInOptions, +} from './direct-sign-in.js'; import { devSeedAdminEmail, devSeedAdminPassword, @@ -3880,6 +3884,9 @@ export class AuthPlugin implements Plugin { // of the routes below. The public render helpers (/config, // /bootstrap-status) are exempt so a blocked client still gets a clean // login page + error. Nothing is judged when no ranges are configured. + // Direct sign-in's start door is NOT exempt: a blocked browser that + // navigated to it is refused with a landing on the sign-in page that names + // the refusal (`directSignInNetworkRefusal`), never by reaching the door. // // The address judged is the one the server ESTABLISHED, by the platform's // client-address trust rule (`AuthManager.resolveClientAddress`, shared @@ -3905,6 +3912,13 @@ export class AuthPlugin implements Plugin { if (!mgr.isClientIpAllowed(ip)) { this.explainAllowListRefusal(ctx, mgr, ip, headers); this.auditAllowListRefusal(ctx, mgr, c, path.startsWith(basePath) ? path.slice(basePath.length) : path, ip); + if ( + this.directSignInDoorMounted && + typeof mgr.getConsoleUrl === 'function' && + isDirectSignInDoorNavigation(c.req.method, path, basePath) + ) { + return directSignInNetworkRefusal(c.req.url, (page) => mgr.getConsoleUrl(page)); + } return c.json( { success: false, error: { code: 'IP_NOT_ALLOWED', message: 'Sign-in is not allowed from your network.' } }, 403, diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 47ee1c7e57e..3e1d13fe2b4 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -186,7 +186,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ // Direct sign-in's start door (`direct-sign-in.ts`): mounted only while the // setting is on (the `directSignIn` option or OS_AUTH_DIRECT_SIGN_IN_ENABLED), // so `requires` names that setting rather than a better-auth plugin. - { route: 'GET /api/v1/auth/sign-in/direct', family: 'objectstack-mount', source: 'objectstack', disposition: 'public', requires: 'directSignIn', note: 'no SDK method builds this URL — the Console sign-in page navigates the browser here with ?callbackURL= and no session; it starts the configured identity provider through the vendor start (/sign-in/social or /sign-in/sso) and answers 302 to it with the vendor state cookie, minting nothing; a return path that is not a same-origin path is dropped, and a start that cannot happen redirects to the sign-in page with error=direct_sign_in_unavailable (error=direct_sign_in_rate_limited when the vendor sign-in rate limit refused it)' }, + { route: 'GET /api/v1/auth/sign-in/direct', family: 'objectstack-mount', source: 'objectstack', disposition: 'public', requires: 'directSignIn', note: 'no SDK method builds this URL — the Console sign-in page navigates the browser here with ?callbackURL= and no session; it starts the configured identity provider through the vendor start (/sign-in/social or /sign-in/sso) and answers 302 to it with the vendor state cookie, minting nothing; a return path that is not a same-origin path is dropped, and a start that cannot happen redirects to the sign-in page with error=direct_sign_in_unavailable (error=direct_sign_in_rate_limited when the vendor sign-in rate limit refused it); a client the IP allow-list refuses never reaches it and is redirected to the sign-in page with error=IP_NOT_ALLOWED instead of the 403 body' }, // #10974 / #10975 — the ninth ObjectStack mount from the #10534 census, // ledgered `sdk` on the maintainer's option-C ruling (2026-08-22) rather // than on either word that was available before it. The two halves landed diff --git a/packages/plugins/plugin-auth/src/direct-sign-in.test.ts b/packages/plugins/plugin-auth/src/direct-sign-in.test.ts index 2a7f505a526..1c92e47c824 100644 --- a/packages/plugins/plugin-auth/src/direct-sign-in.test.ts +++ b/packages/plugins/plugin-auth/src/direct-sign-in.test.ts @@ -30,6 +30,7 @@ import { repeatedQueryParamMessage, unknownQueryParamRefusalMessage } from '@obj import { createMemoryEngine } from './impersonation-bearer-rotation.test'; import { DIRECT_SIGN_IN_ENV, + DIRECT_SIGN_IN_NETWORK_REFUSED, DIRECT_SIGN_IN_QUERY_PARAMS, DIRECT_SIGN_IN_RATE_LIMITED, DIRECT_SIGN_IN_UNAVAILABLE, @@ -358,7 +359,7 @@ afterEach(() => { } }); -function mount(directSignIn?: { provider?: string; localSignIn?: 'hidden' | 'off' }) { +function mount(directSignIn?: { provider?: string; localSignIn?: 'hidden' | 'off' }, extra: Record = {}) { const app = new Hono(); const ctx = { registerService: vi.fn(), @@ -384,6 +385,7 @@ function mount(directSignIn?: { provider?: string; localSignIn?: 'hidden' | 'off }, ], ...(directSignIn ? { directSignIn } : {}), + ...extra, }; const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const plugin = new AuthPlugin(options as any); @@ -452,6 +454,69 @@ describe('the mounted start door (setting on)', () => { }); }); +// ── The IP allow-list in front of the door (ADR-0069 D5) ───────────────────── + +describe('a client the IP allow-list refuses lands on the sign-in page, and the door still starts nothing for it', () => { + /** Documentation ranges (RFC 5737): one allowed, one not. */ + const RANGE = '203.0.113.0/24'; + const INSIDE = '203.0.113.7'; + const OUTSIDE = '198.51.100.9'; + const fromPeer = (app: Hono, path: string, peer: string, init: RequestInit = {}) => + app.request(`${ORIGIN}${path}`, init, { incoming: { socket: { remoteAddress: peer } } }); + const DOOR = '/api/v1/auth/sign-in/direct'; + const RETURN = `?callbackURL=${encodeURIComponent('/_console/login?redirect=%2Fapps%2Fcrm&direct=returned')}`; + + it('a blocked navigation to the door answers 302 to /login?error=IP_NOT_ALLOWED with the page\'s ?redirect= kept, and no vendor state', async () => { + const { app } = mount({ provider: PLATFORM_IDP }, { allowedIpRanges: [RANGE] }); + const res = await fromPeer(app, `${DOOR}${RETURN}`, OUTSIDE); + expect(res.status).toBe(302); + expect(res.headers.get('location')).toBe( + `${ORIGIN}/_console/login?error=${DIRECT_SIGN_IN_NETWORK_REFUSED}&redirect=%2Fapps%2Fcrm`, + ); + expect(res.headers.getSetCookie()).toEqual([]); + + // No ?redirect= on the page, or a foreign one: the bare landing with the code. + for (const query of ['', `?callbackURL=${encodeURIComponent('/_console/login?redirect=https%3A%2F%2Fevil.test')}`]) { + const bare = await fromPeer(app, `${DOOR}${query}`, OUTSIDE); + expect(bare.status).toBe(302); + expect(bare.headers.get('location')).toBe(`${ORIGIN}/_console/login?error=${DIRECT_SIGN_IN_NETWORK_REFUSED}`); + } + }); + + it('the page it lands on can still read /auth/config, which says direct sign-in is on, while every sign-in door stays refused 403', async () => { + const { app } = mount({ provider: PLATFORM_IDP }, { allowedIpRanges: [RANGE] }); + const cfg = await fromPeer(app, '/api/v1/auth/config', OUTSIDE); + expect(cfg.status).toBe(200); + expect((await cfg.json()).data.features.directSignIn).toBe(true); + for (const [path, init] of [ + ['/api/v1/auth/get-session', {}], + ['/api/v1/auth/sign-in/social', { method: 'POST', headers: { 'content-type': 'application/json', origin: ORIGIN }, body: JSON.stringify({ provider: PLATFORM_IDP }) }], + [DOOR, { method: 'POST' }], + ] as const) { + const res = await fromPeer(app, path, OUTSIDE, init as RequestInit); + expect(res.status, path).toBe(403); + expect((await res.json()).error.code, path).toBe('IP_NOT_ALLOWED'); + } + }); + + it('CONTROL: an allowed client still starts the identity provider through the door', async () => { + const { app } = mount({ provider: PLATFORM_IDP }, { allowedIpRanges: [RANGE] }); + const res = await fromPeer(app, `${DOOR}${RETURN}`, INSIDE); + expect(res.status).toBe(302); + const location = new URL(res.headers.get('location')!); + expect(`${location.origin}${location.pathname}`).toBe(`${IDP}/${PLATFORM_IDP}/authorize`); + expect(res.headers.getSetCookie().length).toBeGreaterThan(0); + }); + + it('CONTROL: with direct sign-in off (no door), the same blocked request is the 403 body as before', async () => { + const { app } = mount(undefined, { allowedIpRanges: [RANGE] }); + const res = await fromPeer(app, `${DOOR}${RETURN}`, OUTSIDE); + expect(res.status).toBe(403); + expect((await res.json()).error.code).toBe('IP_NOT_ALLOWED'); + expect(res.headers.get('location')).toBeNull(); + }); +}); + describe('CONTROL: with the setting off, the door and /auth/config are what they are on main', () => { it('does not mount the door: the path answers what an unclaimed auth path answers', async () => { const off = mount(); diff --git a/packages/plugins/plugin-auth/src/direct-sign-in.ts b/packages/plugins/plugin-auth/src/direct-sign-in.ts index ee2edffefa8..02dcc6974db 100644 --- a/packages/plugins/plugin-auth/src/direct-sign-in.ts +++ b/packages/plugins/plugin-auth/src/direct-sign-in.ts @@ -108,6 +108,14 @@ export const DIRECT_SIGN_IN_UNAVAILABLE = 'direct_sign_in_unavailable'; */ export const DIRECT_SIGN_IN_RATE_LIMITED = 'direct_sign_in_rate_limited'; +/** + * The `error` code the sign-in page is sent to when the deployment's IP + * allow-list (ADR-0069 D5) refused the client at the start door: the + * refusal's own code, so the page names it as the network refusal it is and + * does not navigate again ({@link directSignInNetworkRefusal}). + */ +export const DIRECT_SIGN_IN_NETWORK_REFUSED = 'IP_NOT_ALLOWED'; + /** The longest return path kept; a longer one is dropped. */ export const RETURN_PATH_MAX = 2048; @@ -230,7 +238,11 @@ export function carriedRedirect(kept: string | undefined): string | undefined { } /** The Console's `/login`, with the carried `redirect` and the `error` code, when there are any. */ -function signInPageUrl(host: DirectSignInHost, redirect: string | undefined, error?: string): string { +function signInPageUrl( + host: Pick, + redirect: string | undefined, + error?: string, +): string { const params = new URLSearchParams(); if (error !== undefined) params.set('error', error); if (redirect !== undefined) params.set('redirect', redirect); @@ -453,3 +465,36 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost): if (!location) return unavailable('start_refused', chosen.providerId); return redirect(location, started.headers.getSetCookie?.() ?? []); } + +/** + * Whether a request is a browser's navigation to the start door + * (`GET {basePath}/sign-in/direct`), the one auth request the IP allow-list + * answers with a landing instead of a JSON body ({@link directSignInNetworkRefusal}). + */ +export function isDirectSignInDoorNavigation(method: string, path: string, basePath: string): boolean { + return method.toUpperCase() === 'GET' && path === `${basePath}${DIRECT_SIGN_IN_PATH}`; +} + +/** + * The answer the IP allow-list gives a client it refused at the start door: + * `302` to the Console's `/login?error=IP_NOT_ALLOWED`, carrying the page's + * `?redirect=` like every other landing ({@link carriedRedirect}), instead of + * the raw `403 IP_NOT_ALLOWED` body a top-level navigation would show. + * + * The refusal stands: nothing is started, no provider is read and nothing + * reaches the door. The page reads the code, holds (an `error` on the URL), + * and says the network is not allowed; every sign-in door it offers is judged + * by the allow-list as before. Only the query's `callbackURL` is read, and a + * query the door would refuse `400` still lands here: the client is refused + * either way, and the network refusal is the one that tells it why. + */ +export function directSignInNetworkRefusal(requestUrl: string, consolePageUrl: (path: string) => string): Response { + let redirectTo: string | undefined; + try { + const values = new URL(requestUrl).searchParams.getAll('callbackURL'); + redirectTo = values.length === 1 ? carriedRedirect(keptReturnPath(values[0])) : undefined; + } catch { + redirectTo = undefined; + } + return redirect(signInPageUrl({ consolePageUrl }, redirectTo, DIRECT_SIGN_IN_NETWORK_REFUSED)); +} From f917e6ef0c6980035483ff411c70479e38663b28 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:19:14 +0000 Subject: [PATCH 3/6] fix(auth): the page names an IP allow-list refusal at the direct sign-in door, and the sign-out note is read only on the provider's return Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSSVaNcDs8HPSoGV6V --- .../LoginPage.direct-sign-in.test.tsx | 8 +++ .../src/pages/auth/ssoCallbackRefusal.ts | 13 ++++ .../__tests__/signOutRoundTrip-33183.test.tsx | 67 +++++++++++++++++-- ui/packages/auth/src/createAuthClient.ts | 2 +- ui/packages/auth/src/signOutRoundTrip.ts | 60 +++++++++++++---- ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + 16 files changed, 142 insertions(+), 19 deletions(-) diff --git a/ui/apps/console/src/pages/auth/__tests__/LoginPage.direct-sign-in.test.tsx b/ui/apps/console/src/pages/auth/__tests__/LoginPage.direct-sign-in.test.tsx index 4fc718e9a52..8badbca3e5e 100644 --- a/ui/apps/console/src/pages/auth/__tests__/LoginPage.direct-sign-in.test.tsx +++ b/ui/apps/console/src/pages/auth/__tests__/LoginPage.direct-sign-in.test.tsx @@ -196,6 +196,14 @@ describe('LoginPage — direct sign-in', () => { expect(screen.getByTestId('direct-sign-in-retry-button')).toBeTruthy(); expect(window.location.replace).not.toHaveBeenCalled(); }); + + it('names a start the IP allow-list refused (the door\'s IP_NOT_ALLOWED landing) as the network, without starting again', async () => { + renderLogin('?error=IP_NOT_ALLOWED&redirect=%2Fapps%2Fcrm', ON); + const alert = await screen.findByTestId('sso-callback-refusal'); + expect(alert.textContent).toContain('This system does not allow sign-in from your network.'); + expect(alert.textContent).not.toContain('expired or was already used'); + expect(window.location.replace).not.toHaveBeenCalled(); + }); }); /** diff --git a/ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts b/ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts index 1fe174a0503..df7d5b76a7f 100644 --- a/ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts +++ b/ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts @@ -58,6 +58,12 @@ const DIRECT_SIGN_IN_RATE_LIMITED: RefusalCopy = { defaultValue: 'Too many sign-ins were started from this network just now. Wait a few seconds, then try again.', }; +const NETWORK_NOT_ALLOWED: RefusalCopy = { + key: 'auth.login.errors.networkNotAllowed', + defaultValue: + "This system does not allow sign-in from your network. Connect from an allowed network (for example your organization's office network or VPN), or ask your administrator.", +}; + const ACCESS_DENIED: RefusalCopy = { key: 'auth.login.errors.ssoAccessDenied', defaultValue: @@ -101,6 +107,12 @@ const GENERIC: RefusalCopy = { * - `direct_sign_in_unavailable`: the direct sign-in door found no single * identity provider to start, or the provider's start was refused * (`./directSignIn`); + * - `IP_NOT_ALLOWED`: the deployment's IP allow-list refused this client at + * the direct sign-in door, which sends a browser here instead of answering + * the raw `403` body (plugin-auth `direct-sign-in.ts` + * `directSignInNetworkRefusal`). Nothing was started, and every sign-in + * this page offers is refused the same way from this network, so the + * sentence names the network and the administrator, not a retry; * - `access_denied` (RFC 6749 §4.1.2.1): the identity provider refused the * signed-in account for this relying party. The ObjectStack provider sends * it when its environment-access gate refuses an account that is not a @@ -134,6 +146,7 @@ const SSO_CALLBACK_REFUSALS: Readonly> = { state_not_found: START_FROM_LOGIN_PAGE, direct_sign_in_unavailable: DIRECT_SIGN_IN_UNAVAILABLE, direct_sign_in_rate_limited: DIRECT_SIGN_IN_RATE_LIMITED, + IP_NOT_ALLOWED: NETWORK_NOT_ALLOWED, access_denied: ACCESS_DENIED, EMAIL_DOMAIN_NOT_ALLOWED: EMAIL_DOMAIN_NOT_ALLOWED, INVALID_EMAIL: EMAIL_NOT_AN_ADDRESS, diff --git a/ui/packages/auth/src/__tests__/signOutRoundTrip-33183.test.tsx b/ui/packages/auth/src/__tests__/signOutRoundTrip-33183.test.tsx index 52ba87ff7d1..279a7268e11 100644 --- a/ui/packages/auth/src/__tests__/signOutRoundTrip-33183.test.tsx +++ b/ui/packages/auth/src/__tests__/signOutRoundTrip-33183.test.tsx @@ -11,7 +11,11 @@ * - the sign-out purge that runs before the page unloads keeps it; * - the first `AuthProvider` mount after the round trip starts with * `sessionEndedBySignOut: true`, and drops the note, so it is read once; - * - a note older than the round trip's window is a fresh visit. + * - a note older than the round trip's window is a fresh visit; + * - the note names the sign-in page the provider returns to, and only a load + * of that page reads it: a provider that never sends the browser back + * leaves it behind, and the next load of another page in the tab (a deep + * link) is a fresh visit, so `LoginRedirect` keeps its `?redirect=`. */ import React, { useEffect } from 'react'; @@ -29,6 +33,17 @@ import { readSignOutRoundTrip, } from '../signOutRoundTrip'; +/** The sign-in page the sign-out returns to (`resolveSpaRoute('/login')` with no base element). */ +const SIGN_IN_PAGE = '/login'; + +/** Load `pathname` in this tab, as a full page load lands on it. */ +function loadAt(pathname: string) { + Object.defineProperty(window, 'location', { + writable: true, + value: { ...window.location, pathname } as unknown as Location, + }); +} + const END_SESSION_URL = 'https://idp.example.com/end-session?post_logout_redirect_uri=https%3A%2F%2Fenv.example.com%2Flogin'; @@ -61,7 +76,12 @@ beforeEach(() => { }); Object.defineProperty(window, 'location', { writable: true, - value: { ...originalLocation, origin: 'https://env.example.com', assign: assignSpy } as unknown as Location, + value: { + ...originalLocation, + origin: 'https://env.example.com', + pathname: SIGN_IN_PAGE, + assign: assignSpy, + } as unknown as Location, }); }); @@ -100,6 +120,9 @@ describe('createAuthClient.signOut writes the note only for a provider logout', expect(noteAtAssign).toHaveLength(1); expect(noteAtAssign[0]).not.toBeNull(); expect(readSignOutRoundTrip()).toBe(true); + // The note names the sign-in page the provider returns to, and only a load of it reads the note. + expect(readSignOutRoundTrip(Date.now(), SIGN_IN_PAGE)).toBe(true); + expect(readSignOutRoundTrip(Date.now(), '/apps/crm/crm_account')).toBe(false); }); it('CONTROL: writes nothing when the sign-out stays in the page', async () => { @@ -152,7 +175,7 @@ describe('createAuthClient.signOut writes the note only for a provider logout', describe('AuthProvider reads the note once, on the mount after the round trip', () => { it('starts with sessionEndedBySignOut raised, and drops the note', async () => { - markSignOutRoundTrip(); + markSignOutRoundTrip(SIGN_IN_PAGE); const view = render( @@ -164,7 +187,7 @@ describe('AuthProvider reads the note once, on the mount after the round trip', }); it('a second load (a reload) is a fresh visit', async () => { - markSignOutRoundTrip(); + markSignOutRoundTrip(SIGN_IN_PAGE); const first = render( @@ -190,7 +213,7 @@ describe('AuthProvider reads the note once, on the mount after the round trip', }); it('a note older than the round trip window is a fresh visit', () => { - markSignOutRoundTrip(Date.now() - SIGN_OUT_ROUND_TRIP_MAX_AGE_MS - 1000); + markSignOutRoundTrip(SIGN_IN_PAGE, Date.now() - SIGN_OUT_ROUND_TRIP_MAX_AGE_MS - 1000); const view = render( @@ -199,8 +222,40 @@ describe('AuthProvider reads the note once, on the mount after the round trip', expect(view.getByTestId('ended').textContent).toBe('false'); }); + it('a load of another page in the tab (the provider never sent the browser back) is a fresh visit, and drops the note', async () => { + markSignOutRoundTrip(SIGN_IN_PAGE); + loadAt('/apps/crm/crm_account'); + const deepLink = render( + + + , + ); + expect(deepLink.getByTestId('ended').textContent).toBe('false'); + await waitFor(() => expect(sessionStorage.getItem(SIGN_OUT_ROUND_TRIP_KEY)).toBeNull()); + deepLink.unmount(); + // The provider's late return to the sign-in page then finds no note either. + loadAt(SIGN_IN_PAGE); + const late = render( + + + , + ); + expect(late.getByTestId('ended').textContent).toBe('false'); + }); + + it('reads the return path without its query or a trailing slash, under a Console base path too', () => { + markSignOutRoundTrip('/_console/login'); + expect(readSignOutRoundTrip(Date.now(), '/_console/login')).toBe(true); + expect(readSignOutRoundTrip(Date.now(), '/_console/login/')).toBe(true); + expect(readSignOutRoundTrip(Date.now(), '/_console/apps/crm')).toBe(false); + expect(readSignOutRoundTrip(Date.now(), '/login')).toBe(false); + // A note that does not parse, or names no path, is no note. + sessionStorage.setItem(SIGN_OUT_ROUND_TRIP_KEY, String(Date.now())); + expect(readSignOutRoundTrip(Date.now(), '/_console/login')).toBe(false); + }); + it('a session on return lowers it, whoever it belongs to', async () => { - markSignOutRoundTrip(); + markSignOutRoundTrip(SIGN_IN_PAGE); const client = { ...signedOutClient(), getSession: vi.fn().mockResolvedValue({ diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts index 0a7015632f3..ab510ed0c01 100644 --- a/ui/packages/auth/src/createAuthClient.ts +++ b/ui/packages/auth/src/createAuthClient.ts @@ -802,7 +802,7 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { // page holds instead of starting a direct sign-in (objectstack#33183). const url = providerLogoutURL(data); if (url && typeof window !== 'undefined') { - markSignOutRoundTrip(); + markSignOutRoundTrip(resolveSpaRoute('/login')); window.location.assign(url); } }, diff --git a/ui/packages/auth/src/signOutRoundTrip.ts b/ui/packages/auth/src/signOutRoundTrip.ts index 1482af78e10..969dbd5a802 100644 --- a/ui/packages/auth/src/signOutRoundTrip.ts +++ b/ui/packages/auth/src/signOutRoundTrip.ts @@ -20,10 +20,16 @@ * TAB's `sessionStorage` (the provider brings the browser back to the same * tab), and `AuthProvider` reads it once when it mounts. * - * It holds a time and nothing else, and it is honoured for - * {@link SIGN_OUT_ROUND_TRIP_MAX_AGE_MS} only: a tab that never came back from - * the provider and is reused later is a fresh visit. Never throws: storage - * that is absent or blocked reads as "no note", which is today's behaviour. + * It holds a time and the path the provider returns the browser to (the + * sign-out's `callbackURL`, the sign-in page) and nothing else, and it is + * honoured only on THAT return: a load of the same path within + * {@link SIGN_OUT_ROUND_TRIP_MAX_AGE_MS}. A provider that never sends the + * browser back leaves the note behind, and the next load of the app in the tab + * is some other page (a deep link, say): that load drops the note unread, so + * it is a fresh visit and `LoginRedirect` keeps the deep link's `?redirect=`. + * A tab reused after the window is a fresh visit too. Never throws: storage + * that is absent or blocked, or a note that does not parse, reads as "no + * note", which is today's behaviour. */ /** The `sessionStorage` key. Kept across the sign-out purge (`ActiveOrganizationStorage`). */ @@ -40,28 +46,58 @@ function tabStore(): Storage | undefined { } } -/** Write the note, just before the browser leaves for the provider's logout. */ -export function markSignOutRoundTrip(now: number = Date.now()): void { +/** A path without its query or fragment, and without a trailing slash (`/` stays `/`). */ +function barepath(path: string): string { + const bare = path.split(/[?#]/)[0] || '/'; + return bare.length > 1 ? bare.replace(/\/+$/, '') || '/' : bare; +} + +function loadedPath(): string | undefined { + try { + return typeof window !== 'undefined' ? window.location.pathname : undefined; + } catch { + return undefined; + } +} + +/** + * Write the note, just before the browser leaves for the provider's logout. + * `returnPath` is where the provider sends the browser back: the sign-out's + * `callbackURL`, the sign-in page. + */ +export function markSignOutRoundTrip(returnPath: string, now: number = Date.now()): void { try { - tabStore()?.setItem(SIGN_OUT_ROUND_TRIP_KEY, String(now)); + tabStore()?.setItem(SIGN_OUT_ROUND_TRIP_KEY, JSON.stringify({ at: now, path: barepath(returnPath) })); } catch { /* storage unavailable: the page starts as for a fresh visit */ } } -/** Whether this tab is coming back from its own sign-out's provider logout. Reads, never clears. */ -export function readSignOutRoundTrip(now: number = Date.now()): boolean { +/** + * Whether this load is the tab coming back from its own sign-out's provider + * logout: a note within the window whose return path is the path loaded now + * (`pathname`, the current location's by default). Reads, never clears. + */ +export function readSignOutRoundTrip(now: number = Date.now(), pathname: string | undefined = loadedPath()): boolean { let raw: string | null | undefined; try { raw = tabStore()?.getItem(SIGN_OUT_ROUND_TRIP_KEY); } catch { return false; } - if (!raw) return false; - const at = Number(raw); + if (!raw || pathname === undefined) return false; + let note: { at?: unknown; path?: unknown }; + try { + note = JSON.parse(raw) as { at?: unknown; path?: unknown }; + } catch { + return false; + } + if (!note || typeof note !== 'object' || typeof note.path !== 'string') return false; + const at = typeof note.at === 'number' ? note.at : Number.NaN; if (!Number.isFinite(at)) return false; const age = now - at; - return age >= 0 && age <= SIGN_OUT_ROUND_TRIP_MAX_AGE_MS; + if (age < 0 || age > SIGN_OUT_ROUND_TRIP_MAX_AGE_MS) return false; + return barepath(note.path) === barepath(pathname); } /** Drop the note: it is read once, by the first `AuthProvider` mount after the round trip. */ diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 69866a5d609..d1161ca7af4 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3005,6 +3005,7 @@ const ar = { directSignInIncomplete: "لم يكتمل تسجيل الدخول: عدت من تسجيل الدخول الموحّد دون أن يتم تسجيل دخولك. تحقّق من أن هذا المتصفح يسمح بملفات تعريف الارتباط لهذا الموقع، ثم حاول مرة أخرى.", directSignInUnavailable: "تعذّر بدء تسجيل الدخول الموحّد لهذا النظام. اطلب من المسؤول التحقق من خدمة تسجيل الدخول التي يستخدمها.", directSignInRateLimited: "بدأ عدد كبير جدًا من عمليات تسجيل الدخول من هذه الشبكة للتو. انتظر بضع ثوانٍ ثم حاول مرة أخرى.", + networkNotAllowed: "لا يسمح هذا النظام بتسجيل الدخول من شبكتك. اتصل من شبكة مسموح بها (مثل شبكة مكتب مؤسستك أو شبكة VPN الخاصة بها)، أو تواصل مع المسؤول.", ssoAccessDenied: "الحساب الذي سجّلت الدخول به ليس لديه صلاحية الوصول إلى هذه البيئة. سجّل الدخول بحساب لديه صلاحية الوصول، أو اطلب من مسؤول مؤسسة هذه البيئة إضافتك عضوًا.", ssoSwitchAccount: "تبديل الحساب", ssoBackToConsole: "العودة إلى وحدة التحكم", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index d7e9301757b..a6c8e4cfd6e 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2731,6 +2731,7 @@ const de = { directSignInIncomplete: "Die Anmeldung wurde nicht abgeschlossen: Sie sind vom Single Sign-on zurückgekehrt, ohne angemeldet zu sein. Prüfen Sie, ob dieser Browser Cookies für diese Website zulässt, und versuchen Sie es erneut.", directSignInUnavailable: "Das Single Sign-on für dieses System konnte nicht gestartet werden. Bitten Sie Ihren Administrator, den verwendeten Anmeldedienst zu prüfen.", directSignInRateLimited: "Von diesem Netzwerk wurden gerade zu viele Anmeldungen gestartet. Warten Sie ein paar Sekunden und versuchen Sie es dann erneut.", + networkNotAllowed: "Dieses System erlaubt keine Anmeldung aus Ihrem Netzwerk. Verbinden Sie sich über ein zugelassenes Netzwerk (zum Beispiel das Büronetz oder VPN Ihrer Organisation), oder wenden Sie sich an Ihren Administrator.", ssoAccessDenied: "Das Konto, mit dem Sie sich angemeldet haben, hat keinen Zugriff auf diese Umgebung. Melden Sie sich mit einem Konto an, das Zugriff hat, oder bitten Sie einen Administrator der Organisation dieser Umgebung, Sie als Mitglied hinzuzufügen.", ssoSwitchAccount: "Konto wechseln", ssoBackToConsole: "Zurück zur Konsole", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 44a37492d3b..eaa98c50e84 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3391,6 +3391,7 @@ const en = { directSignInIncomplete: "Sign-in did not complete: you came back from single sign-on without being signed in. Check that this browser allows cookies for this site, then try again.", directSignInUnavailable: "Single sign-on could not be started for this system. Ask your administrator to check which sign-in service it uses.", directSignInRateLimited: "Too many sign-ins were started from this network just now. Wait a few seconds, then try again.", + networkNotAllowed: "This system does not allow sign-in from your network. Connect from an allowed network (for example your organization's office network or VPN), or ask your administrator.", // objectstack#32992 — `access_denied`: the identity provider refused the // signed-in account for this environment, with its two ways on. ssoAccessDenied: "The account you signed in with does not have access to this environment. Sign in with an account that has access, or ask an administrator of this environment's organization to add you as a member.", diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 3e314ac017a..a9a1692ab49 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2801,6 +2801,7 @@ const es = { directSignInIncomplete: "No se completó el inicio de sesión: volviste del inicio de sesión único sin haber iniciado sesión. Comprueba que este navegador permite cookies para este sitio y vuelve a intentarlo.", directSignInUnavailable: "No se pudo iniciar el inicio de sesión único para este sistema. Pide a tu administrador que revise qué servicio de inicio de sesión usa.", directSignInRateLimited: "Se iniciaron demasiados inicios de sesión desde esta red hace un momento. Espera unos segundos y vuelve a intentarlo.", + networkNotAllowed: "Este sistema no permite iniciar sesión desde tu red. Conéctate desde una red permitida (por ejemplo, la red de la oficina o la VPN de tu organización) o pide ayuda a tu administrador.", ssoAccessDenied: "La cuenta con la que iniciaste sesión no tiene acceso a este entorno. Inicia sesión con una cuenta que tenga acceso o pide a un administrador de la organización de este entorno que te añada como miembro.", ssoSwitchAccount: "Cambiar de cuenta", ssoBackToConsole: "Volver a la consola", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 4f69562ddaf..cd3dc6d868e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2797,6 +2797,7 @@ const fr = { directSignInIncomplete: "La connexion n'a pas abouti : vous êtes revenu de l'authentification unique sans être connecté. Vérifiez que ce navigateur autorise les cookies pour ce site, puis réessayez.", directSignInUnavailable: "L'authentification unique n'a pas pu être lancée pour ce système. Demandez à votre administrateur de vérifier le service de connexion utilisé.", directSignInRateLimited: "Trop de connexions ont été lancées depuis ce réseau à l'instant. Patientez quelques secondes, puis réessayez.", + networkNotAllowed: "Ce système n'autorise pas la connexion depuis votre réseau. Connectez-vous depuis un réseau autorisé (par exemple le réseau du bureau ou le VPN de votre organisation), ou contactez votre administrateur.", ssoAccessDenied: "Le compte avec lequel vous vous êtes connecté n'a pas accès à cet environnement. Connectez-vous avec un compte qui y a accès, ou demandez à un administrateur de l'organisation de cet environnement de vous ajouter comme membre.", ssoSwitchAccount: "Changer de compte", ssoBackToConsole: "Retour à la console", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index c6eec3e9aff..1ee97bc75f9 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2733,6 +2733,7 @@ const ja = { directSignInIncomplete: "サインインが完了しませんでした。シングルサインオンから戻りましたが、サインインされていません。このブラウザーでこのサイトの Cookie が許可されているか確認して、もう一度お試しください。", directSignInUnavailable: "このシステムのシングルサインオンを開始できませんでした。使用しているサインインサービスの確認を管理者に依頼してください。", directSignInRateLimited: "このネットワークから短時間に多くのサインインが開始されました。数秒待ってから、もう一度お試しください。", + networkNotAllowed: "このシステムは、現在のネットワークからのサインインを許可していません。許可されたネットワーク(組織のオフィスネットワークや VPN など)から接続するか、管理者に問い合わせてください。", ssoAccessDenied: "サインインしたアカウントには、この環境へのアクセス権がありません。アクセス権のあるアカウントでサインインするか、この環境の組織の管理者にメンバーとして追加するよう依頼してください。", ssoSwitchAccount: "アカウントを切り替える", ssoBackToConsole: "コンソールに戻る", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 748816a60c1..a6a42874950 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2731,6 +2731,7 @@ const ko = { directSignInIncomplete: "로그인이 완료되지 않았습니다. 싱글 사인온에서 돌아왔지만 로그인되지 않았습니다. 이 브라우저에서 이 사이트의 쿠키가 허용되어 있는지 확인한 후 다시 시도하세요.", directSignInUnavailable: "이 시스템의 싱글 사인온을 시작할 수 없습니다. 관리자에게 사용하는 로그인 서비스를 확인해 달라고 요청하세요.", directSignInRateLimited: "방금 이 네트워크에서 너무 많은 로그인이 시작되었습니다. 몇 초 기다린 후 다시 시도하세요.", + networkNotAllowed: "이 시스템은 현재 네트워크에서의 로그인을 허용하지 않습니다. 허용된 네트워크(예: 조직의 사무실 네트워크나 VPN)에서 접속하거나 관리자에게 문의하세요.", ssoAccessDenied: "로그인한 계정에는 이 환경에 대한 액세스 권한이 없습니다. 액세스 권한이 있는 계정으로 로그인하거나, 이 환경 조직의 관리자에게 멤버로 추가해 달라고 요청하세요.", ssoSwitchAccount: "계정 전환", ssoBackToConsole: "콘솔로 돌아가기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index c6d03ea6e72..5e398880f77 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2796,6 +2796,7 @@ const pt = { directSignInIncomplete: "O login não foi concluído: você voltou do login único sem estar conectado. Verifique se este navegador permite cookies para este site e tente novamente.", directSignInUnavailable: "Não foi possível iniciar o login único para este sistema. Peça ao seu administrador para verificar qual serviço de login ele usa.", directSignInRateLimited: "Muitos logins foram iniciados a partir desta rede agora há pouco. Aguarde alguns segundos e tente novamente.", + networkNotAllowed: "Este sistema não permite entrar a partir da sua rede. Conecte-se de uma rede permitida (por exemplo, a rede do escritório ou a VPN da sua organização) ou fale com o administrador.", ssoAccessDenied: "A conta com a qual você entrou não tem acesso a este ambiente. Entre com uma conta que tenha acesso ou peça a um administrador da organização deste ambiente para adicionar você como membro.", ssoSwitchAccount: "Trocar de conta", ssoBackToConsole: "Voltar ao console", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index be1fc286152..58615308a07 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2876,6 +2876,7 @@ const ru = { directSignInIncomplete: "Вход не завершён: вы вернулись после единого входа, но не вошли в систему. Убедитесь, что этот браузер разрешает файлы cookie для этого сайта, и повторите попытку.", directSignInUnavailable: "Не удалось начать единый вход в эту систему. Попросите администратора проверить, какую службу входа она использует.", directSignInRateLimited: "Только что из этой сети было начато слишком много входов. Подождите несколько секунд и повторите попытку.", + networkNotAllowed: "Эта система не разрешает вход из вашей сети. Подключитесь из разрешённой сети (например, офисной сети или VPN вашей организации) или обратитесь к администратору.", ssoAccessDenied: "У учётной записи, с которой вы вошли, нет доступа к этой среде. Войдите с учётной записью, у которой есть доступ, или попросите администратора организации этой среды добавить вас в участники.", ssoSwitchAccount: "Сменить учётную запись", ssoBackToConsole: "Вернуться в консоль", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c614d0f6411..1488953b31e 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2803,6 +2803,7 @@ const zh = { directSignInIncomplete: "登录没有完成:你从单点登录返回时仍未登录。请确认浏览器允许本站点的 Cookie,然后重试。", directSignInUnavailable: "无法为本系统发起单点登录。请联系管理员检查本系统使用的登录服务。", directSignInRateLimited: "刚刚从此网络发起的登录过多。请等待几秒后再试。", + networkNotAllowed: "本系统不允许从你当前的网络登录。请从允许的网络(例如组织的办公网络或 VPN)连接,或联系管理员。", ssoAccessDenied: "你登录所用的账号无权访问本系统。请使用有权访问的账号登录,或请本系统所属组织的管理员将你添加为成员。", ssoSwitchAccount: "切换账号", ssoBackToConsole: "返回控制台", diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 5549f146f1f..0c19aa02fa7 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2803,6 +2803,7 @@ const zhHant = { directSignInIncomplete: "登入沒有完成:你從單點登入返回時仍未登入。請確認瀏覽器允許本站點的 Cookie,然後重試。", directSignInUnavailable: "無法為本系統發起單點登入。請聯絡管理員檢查本系統使用的登入服務。", directSignInRateLimited: "剛剛從此網路發起的登入過多。請等待幾秒後再試。", + networkNotAllowed: "本系統不允許從你當前的網路登入。請從允許的網路(例如組織的辦公網路或 VPN)連線,或聯絡管理員。", ssoAccessDenied: "你登入所用的賬號無權訪問本系統。請使用有權訪問的賬號登入,或請本系統所屬組織的管理員將你新增為成員。", ssoSwitchAccount: "切換賬號", ssoBackToConsole: "返回控制台", From f76f585695c59083d6ebb6a7db097662c37fd120 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:32:48 +0000 Subject: [PATCH 4/6] chore: changeset for the sign-in floor and direct sign-in door fixes Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSSVaNcDs8HPSoGV6V --- ...-sign-in-floor-local-off-and-blocked-door.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/33358-sign-in-floor-local-off-and-blocked-door.md diff --git a/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md b/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md new file mode 100644 index 00000000000..1ed1b48f52f --- /dev/null +++ b/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-auth': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +'@object-ui/auth': patch +--- + +fix(plugin-auth): the auth settings save keeps a way to sign in under the local sign-in path off, and a client the IP allow-list refuses at the direct sign-in door lands on the sign-in page + +Clause-②: yes (widening) +Metadata-protocol: none + +Three fixes next to direct sign-in. + +- **The auth settings save under `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=off`.** With the local sign-in path behind direct sign-in `off`, the sign-in page offers no email and password and no phone sign-in, but saving the auth settings still counted them as a way in. So with Google as the last provider, saving Google off (or clearing a client credential no environment variable backs) went through, and the page then showed "No sign-in method is available". The save now judges by what the page offers, as the provider delete and the boot report already do: that change is refused `400 SETTINGS_VALIDATION` with its own sentence in all eleven languages (keep Google, set up another sign-in method, or set the local sign-in path back to `hidden` with email and password on), and turning email and password on in the same save does not help. The `email_password_enabled` switch itself is never refused under `off`, because the page draws it neither way. Another identity provider, a social or OIDC provider with a client ID and secret, or a host sign-in handoff still counts. The `503` sentence for a provider delete whose provider list could not be read now says the sign-in page offers no email and password, which is true under both reasons the check runs. +- **A client the IP allow-list refuses at `GET /api/v1/auth/sign-in/direct`.** A blocked browser that navigated to the direct sign-in door got the raw `403 IP_NOT_ALLOWED` JSON. It now gets `302` to the Console's `/login?error=IP_NOT_ALLOWED`, with the page's `?redirect=` kept, and the page says the system does not allow sign-in from this network. The door is not exempt from the allow-list: nothing is started and no provider is read, every other auth request from that client is refused `403` as before, and the refusal is still audited and logged. The `@object-ui/i18n` locale packs gain one key, `auth.login.errors.networkNotAllowed`, in all eleven shipped locales; no key is renamed or removed. +- **The sign-out note after a provider logout.** The note a provider-logout sign-out leaves in the tab now records the sign-in page the provider returns to, and only a load of that page reads it. A provider that never sends the browser back no longer makes the next deep link opened in that tab drop its `?redirect=`. From 7c6c999ce249c9cc9604082fddc10366db8a3528 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 10:58:02 +0000 Subject: [PATCH 5/6] fix(plugin-auth)!: pin the email key under off with nothing else in force, door path check, docs 302 Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSSVaNcDs8HPSoGV6V --- ...ign-in-floor-local-off-and-blocked-door.md | 17 ++++++++----- content/docs/permissions/sso.mdx | 7 ++++++ .../plugin-auth/src/direct-sign-in.test.ts | 2 ++ .../src/sign-in-method-floor.test.ts | 25 +++++++++++++++++++ 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md b/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md index 1ed1b48f52f..7ea3dcd9185 100644 --- a/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md +++ b/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md @@ -5,13 +5,18 @@ '@object-ui/auth': patch --- -fix(plugin-auth): the auth settings save keeps a way to sign in under the local sign-in path off, and a client the IP allow-list refuses at the direct sign-in door lands on the sign-in page +fix(plugin-auth)!: under the local sign-in path `off`, the auth settings save keeps a way to sign in, and a client the IP allow-list refuses at the direct sign-in door lands on the sign-in page -Clause-②: yes (widening) +Clause-②: yes (narrowing) — narrowed: with direct sign-in on and its local sign-in path `off` (`directSignIn.localSignIn: 'off'`, or `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=off`), an auth settings save (`PUT /api/settings/auth`) that turns Google off, or clears a Google client credential no environment variable backs, while Google is the last way in the sign-in page offers answers `400 SETTINGS_VALIDATION` with the new copy `googleLocalOff` and saves nothing, where it saved, even with email and password (or phone sign-in) switched on; and a `GET /api/v1/auth/sign-in/direct` from a client the IP allow-list refuses answers `302` to the Console's `/login?error=IP_NOT_ALLOWED` (keeping a same-origin `?redirect=`), where it answered the `403 IP_NOT_ALLOWED` JSON body. Widened: module exports (not on the package entry) `DIRECT_SIGN_IN_NETWORK_REFUSED`, `isDirectSignInDoorNavigation` and `directSignInNetworkRefusal`; a `googleLocalOff` key on the sign-in floor copy, in all 11 locales; the `@object-ui/i18n` key `auth.login.errors.networkNotAllowed`, in all 11 shipped locales (no key renamed or removed); the Console sign-in page explains `?error=IP_NOT_ALLOWED`; `markSignOutRoundTrip` in `@object-ui/auth` takes the sign-in page path it records. Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches direct sign-in, the auth settings save, the IP allow-list or the sign-out note; `content/docs/permissions/sso.mdx` gains the rules in this change. -Three fixes next to direct sign-in. + -- **The auth settings save under `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=off`.** With the local sign-in path behind direct sign-in `off`, the sign-in page offers no email and password and no phone sign-in, but saving the auth settings still counted them as a way in. So with Google as the last provider, saving Google off (or clearing a client credential no environment variable backs) went through, and the page then showed "No sign-in method is available". The save now judges by what the page offers, as the provider delete and the boot report already do: that change is refused `400 SETTINGS_VALIDATION` with its own sentence in all eleven languages (keep Google, set up another sign-in method, or set the local sign-in path back to `hidden` with email and password on), and turning email and password on in the same save does not help. The `email_password_enabled` switch itself is never refused under `off`, because the page draws it neither way. Another identity provider, a social or OIDC provider with a client ID and secret, or a host sign-in handoff still counts. The `503` sentence for a provider delete whose provider list could not be read now says the sign-in page offers no email and password, which is true under both reasons the check runs. -- **A client the IP allow-list refuses at `GET /api/v1/auth/sign-in/direct`.** A blocked browser that navigated to the direct sign-in door got the raw `403 IP_NOT_ALLOWED` JSON. It now gets `302` to the Console's `/login?error=IP_NOT_ALLOWED`, with the page's `?redirect=` kept, and the page says the system does not allow sign-in from this network. The door is not exempt from the allow-list: nothing is started and no provider is read, every other auth request from that client is refused `403` as before, and the refusal is still audited and logged. The `@object-ui/i18n` locale packs gain one key, `auth.login.errors.networkNotAllowed`, in all eleven shipped locales; no key is renamed or removed. -- **The sign-out note after a provider logout.** The note a provider-logout sign-out leaves in the tab now records the sign-in page the provider returns to, and only a load of that page reads it. A provider that never sends the browser back no longer makes the next deep link opened in that tab drop its `?redirect=`. +**BREAKING** for a deployment running direct sign-in with the local sign-in path `off`: saving the auth settings with Google off (or with an unbacked Google client credential cleared) while Google is the last way in the sign-in page offers is refused `400 SETTINGS_VALIDATION` and nothing is saved, unless another way in the page offers remains (another identity provider row, a social or OIDC provider with a client ID and secret, or a host sign-in handoff). Email and password and phone sign-in do not count there, because the page does not offer them; turning email and password on in the same save does not help. Before, the save went through and the sign-in page then showed "No sign-in method is available". Also **BREAKING** for anything that reads the status of `GET /api/v1/auth/sign-in/direct` from a client outside the IP allow-list: it is now `302` to `/login?error=IP_NOT_ALLOWED` with no cookie set, instead of the `403` JSON body. + +Unchanged: the local sign-in path `hidden` (the default) and direct sign-in off, where email and password and phone sign-in count as before; the `email_password_enabled` switch, which is never refused under `off` because the page draws it neither way; the IP allow-list itself, which does not exempt the door: nothing is started and no provider is read for a refused client, every other auth request from it (including a `POST` to the door and the door path with a trailing slash) is still refused `403 IP_NOT_ALLOWED`, and the refusal is still audited and logged. + +What to do: nothing, unless you turn Google off as the last way in under `off`. Register another identity provider first, or set `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden` (with email and password sign-in on) and restart. A client that checked the door's `403` status should check for the `302` to `/login?error=IP_NOT_ALLOWED` instead. + +Also fixed: the `503` sentence for a provider delete whose provider list could not be read now says the sign-in page offers no email and password, which is true under both reasons the check runs; and the note a provider-logout sign-out leaves in the tab now records the sign-in page the provider returns to, and only a load of that page reads it, so a provider that never sends the browser back no longer makes the next deep link opened in that tab drop its `?redirect=`. diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index 95990755579..43fb53b4a06 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -826,6 +826,13 @@ button (and the reason, where there is one), instead of starting again when: starts from one address in a few seconds). It redirects to `/login?error=direct_sign_in_rate_limited`, the page asks the visitor to wait a few seconds and try again, and the `warn` line names `rate_limited`; +- the [IP allow-list](/docs/permissions/authentication) refuses the + visitor's network. The door is not exempt from the allow-list: a browser + `GET` of the door from a refused address starts nothing and is redirected + to `/login?error=IP_NOT_ALLOWED` (keeping a same-origin `?redirect=`) + instead of the `403` body, the page says sign-in is not allowed from this + network, and every other auth request from that address is still refused + `403 IP_NOT_ALLOWED`; - the person just signed out in that tab. Often the identity provider's session outlives the platform's, so starting again would sign them straight back in. When the provider ends its own session too (an OIDC provider whose diff --git a/packages/plugins/plugin-auth/src/direct-sign-in.test.ts b/packages/plugins/plugin-auth/src/direct-sign-in.test.ts index 1c92e47c824..debc2413fd1 100644 --- a/packages/plugins/plugin-auth/src/direct-sign-in.test.ts +++ b/packages/plugins/plugin-auth/src/direct-sign-in.test.ts @@ -492,6 +492,8 @@ describe('a client the IP allow-list refuses lands on the sign-in page, and the ['/api/v1/auth/get-session', {}], ['/api/v1/auth/sign-in/social', { method: 'POST', headers: { 'content-type': 'application/json', origin: ORIGIN }, body: JSON.stringify({ provider: PLATFORM_IDP }) }], [DOOR, { method: 'POST' }], + // Only the door's exact path is the navigation that lands on the page: a trailing slash is not it. + [`${DOOR}/${RETURN}`, {}], ] as const) { const res = await fromPeer(app, path, OUTSIDE, init as RequestInit); expect(res.status, path).toBe(403); diff --git a/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts b/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts index 3ca5a2864b8..0b0932c9b6b 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts @@ -490,6 +490,18 @@ describe('the auth settings save keeps a way to sign in', () => { expect(googleOn(manager)).toBe(true); }); + it('under the local sign-in path off, the email and password key is never refused, even with no other way in configured', async () => { + // Nothing else is in force: no Google, no identity provider, no social or OIDC provider, no handoff. + const { settings, manager } = await boot({ pluginOptions: { directSignIn: { localSignIn: 'off' } } }); + expect(manager.getPublicConfig().features.localSignIn).toBe('off'); + expect(googleOn(manager)).toBe(false); + expect(passwordOn(manager)).toBe(true); + await settings.setMany('auth', { email_password_enabled: false }); + await vi.waitFor(() => expect(passwordOn(manager)).toBe(false)); + await settings.setMany('auth', { email_password_enabled: true }); + await vi.waitFor(() => expect(passwordOn(manager)).toBe(true)); + }); + it('CONTROL: with the local sign-in path hidden, the same Google change goes through while email and password is on', async () => { const { settings, manager } = await boot({ pluginOptions: { directSignIn: { localSignIn: 'hidden' } } }); expect(manager.getPublicConfig().features.localSignIn).toBe('hidden'); @@ -942,6 +954,19 @@ describe('the floor judges a provider delete and a boot by what it can read (#30 }); // The email and password key is never refused under off, on or off. await expect(save(deps({ config: GOOGLE_ONLY_OFF }), { email_password_enabled: false })).resolves.toBeUndefined(); + // ...also with nothing else in force (no Google, no row, no social or OIDC provider, no handoff). + const NOTHING_ELSE_OFF: SignInMethodConfigView = { + emailPassword: { enabled: true }, + socialProviders: [], + features: { sso: false, phoneNumber: true, localSignIn: 'off' }, + }; + await expect(save(deps({ config: NOTHING_ELSE_OFF }), { email_password_enabled: false })).resolves.toBeUndefined(); + // CONTROL: with the path hidden (and phone off), the same save is refused in the email copy. + await expect( + save(deps({ config: { ...NOTHING_ELSE_OFF, features: { sso: false, phoneNumber: false, localSignIn: 'hidden' } } }), { + email_password_enabled: false, + }), + ).resolves.toMatchObject({ constraint: { lastSignInMethod: 'email_password' } }); // The exits under off. for (const d of [ deps({ config: { ...GOOGLE_ONLY_OFF, socialProviders: [...GOOGLE_ONLY_OFF.socialProviders!, { id: 'github', type: 'social' }] } }), From e25b4e31a6be0e0cc5aca0fcae4a0779a678dd84 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:07:55 +0000 Subject: [PATCH 6/6] docs(changeset): declare the email-off save under off with nothing else in force as widened Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSSVaNcDs8HPSoGV6V --- .../33358-sign-in-floor-local-off-and-blocked-door.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md b/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md index 7ea3dcd9185..017217dde33 100644 --- a/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md +++ b/.changeset/33358-sign-in-floor-local-off-and-blocked-door.md @@ -7,7 +7,7 @@ fix(plugin-auth)!: under the local sign-in path `off`, the auth settings save keeps a way to sign in, and a client the IP allow-list refuses at the direct sign-in door lands on the sign-in page -Clause-②: yes (narrowing) — narrowed: with direct sign-in on and its local sign-in path `off` (`directSignIn.localSignIn: 'off'`, or `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=off`), an auth settings save (`PUT /api/settings/auth`) that turns Google off, or clears a Google client credential no environment variable backs, while Google is the last way in the sign-in page offers answers `400 SETTINGS_VALIDATION` with the new copy `googleLocalOff` and saves nothing, where it saved, even with email and password (or phone sign-in) switched on; and a `GET /api/v1/auth/sign-in/direct` from a client the IP allow-list refuses answers `302` to the Console's `/login?error=IP_NOT_ALLOWED` (keeping a same-origin `?redirect=`), where it answered the `403 IP_NOT_ALLOWED` JSON body. Widened: module exports (not on the package entry) `DIRECT_SIGN_IN_NETWORK_REFUSED`, `isDirectSignInDoorNavigation` and `directSignInNetworkRefusal`; a `googleLocalOff` key on the sign-in floor copy, in all 11 locales; the `@object-ui/i18n` key `auth.login.errors.networkNotAllowed`, in all 11 shipped locales (no key renamed or removed); the Console sign-in page explains `?error=IP_NOT_ALLOWED`; `markSignOutRoundTrip` in `@object-ui/auth` takes the sign-in page path it records. +Clause-②: yes (narrowing) — narrowed: with direct sign-in on and its local sign-in path `off` (`directSignIn.localSignIn: 'off'`, or `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=off`), an auth settings save (`PUT /api/settings/auth`) that turns Google off, or clears a Google client credential no environment variable backs, while Google is the last way in the sign-in page offers answers `400 SETTINGS_VALIDATION` with the new copy `googleLocalOff` and saves nothing, where it saved, even with email and password (or phone sign-in) switched on; and a `GET /api/v1/auth/sign-in/direct` from a client the IP allow-list refuses answers `302` to the Console's `/login?error=IP_NOT_ALLOWED` (keeping a same-origin `?redirect=`), where it answered the `403 IP_NOT_ALLOWED` JSON body. Widened: under `off` with nothing else in force (no Google, no identity provider row, no social or OIDC provider with credentials, no host sign-in handoff), a save of `email_password_enabled: false` answers `200` and saves, where it answered `400 SETTINGS_VALIDATION`, because the sign-in page offers no email and password there either way; module exports (not on the package entry) `DIRECT_SIGN_IN_NETWORK_REFUSED`, `isDirectSignInDoorNavigation` and `directSignInNetworkRefusal`; a `googleLocalOff` key on the sign-in floor copy, in all 11 locales; the `@object-ui/i18n` key `auth.login.errors.networkNotAllowed`, in all 11 shipped locales (no key renamed or removed); the Console sign-in page explains `?error=IP_NOT_ALLOWED`; `markSignOutRoundTrip` in `@object-ui/auth` takes the sign-in page path it records. Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches direct sign-in, the auth settings save, the IP allow-list or the sign-out note; `content/docs/permissions/sso.mdx` gains the rules in this change. @@ -15,8 +15,8 @@ Skills-docs: none — no skill under `skills/**` teaches direct sign-in, the aut **BREAKING** for a deployment running direct sign-in with the local sign-in path `off`: saving the auth settings with Google off (or with an unbacked Google client credential cleared) while Google is the last way in the sign-in page offers is refused `400 SETTINGS_VALIDATION` and nothing is saved, unless another way in the page offers remains (another identity provider row, a social or OIDC provider with a client ID and secret, or a host sign-in handoff). Email and password and phone sign-in do not count there, because the page does not offer them; turning email and password on in the same save does not help. Before, the save went through and the sign-in page then showed "No sign-in method is available". Also **BREAKING** for anything that reads the status of `GET /api/v1/auth/sign-in/direct` from a client outside the IP allow-list: it is now `302` to `/login?error=IP_NOT_ALLOWED` with no cookie set, instead of the `403` JSON body. -Unchanged: the local sign-in path `hidden` (the default) and direct sign-in off, where email and password and phone sign-in count as before; the `email_password_enabled` switch, which is never refused under `off` because the page draws it neither way; the IP allow-list itself, which does not exempt the door: nothing is started and no provider is read for a refused client, every other auth request from it (including a `POST` to the door and the door path with a trailing slash) is still refused `403 IP_NOT_ALLOWED`, and the refusal is still audited and logged. +Unchanged: the local sign-in path `hidden` (the default) and direct sign-in off, where email and password and phone sign-in count as before; the IP allow-list itself, which does not exempt the door: nothing is started and no provider is read for a refused client, every other auth request from it (including a `POST` to the door and the door path with a trailing slash) is still refused `403 IP_NOT_ALLOWED`, and the refusal is still audited and logged. -What to do: nothing, unless you turn Google off as the last way in under `off`. Register another identity provider first, or set `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden` (with email and password sign-in on) and restart. A client that checked the door's `403` status should check for the `302` to `/login?error=IP_NOT_ALLOWED` instead. +What to do: nothing, unless you turn Google off as the last way in under `off`, or switch email and password off there. Register another identity provider first, or set `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden` (with email and password sign-in on) and restart. If email and password sign-in was switched off under `off` (that save is no longer refused), setting the local path back to `hidden` is not enough: set `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` as well, then restart. A client that checked the door's `403` status should check for the `302` to `/login?error=IP_NOT_ALLOWED` instead. Also fixed: the `503` sentence for a provider delete whose provider list could not be read now says the sign-in page offers no email and password, which is true under both reasons the check runs; and the note a provider-logout sign-out leaves in the tab now records the sign-in page the provider returns to, and only a load of that page reads it, so a provider that never sends the browser back no longer makes the next deep link opened in that tab drop its `?redirect=`.