diff --git a/.changeset/33358-local-sign-in-off-floor.md b/.changeset/33358-local-sign-in-off-floor.md new file mode 100644 index 00000000000..3dd0aa9748a --- /dev/null +++ b/.changeset/33358-local-sign-in-off-floor.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(auth)!: under direct sign-in's local sign-in path `off`, the last identity provider is the last way in; the door's landings on the sign-in page keep its `?redirect=` + +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`), `POST /api/v1/auth/sso/delete-provider` on the last identity provider answers `409 DELETE_RESTRICTED` and deletes nothing while email and password is switched on, where it deleted the row; email and password, and phone sign-in, no longer count as a way in there, because the sign-in page does not offer them. Widened: module exports (not on the package entry) `pageOffersLocalSignIn`, `pageOffersEmailPassword` and `carriedRedirect`, an optional `localSignIn` on `SignInMethodConfigView.features`, and an `asThePageOffers` option on `otherSignInMethods`. The refusal under `off` answers with a new message, the copy key `enterpriseSsoLocalOff`, in all 11 locales. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches direct sign-in, the provider delete or the boot report; `content/docs/permissions/sso.mdx` gains the rule in this change. + + + +**BREAKING** for a deployment running direct sign-in with the local sign-in path `off`: Setup's **Delete SSO Provider** on the last identity provider is refused `409 DELETE_RESTRICTED` (nothing deleted) unless another way in the sign-in page offers remains (another identity provider row, a social or OIDC provider with a client ID and secret, or a host sign-in handoff), even with email and password switched on, and even with phone sign-in switched on. Before, the delete went through and the sign-in page then showed "No sign-in method is available". A boot in that state now reports at error under `no_sign_in_method_at_boot`. + +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 server's own password sign-in, which `off` never changed. + +What to do: nothing, unless you delete the last identity provider 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. + +Also fixed: the direct sign-in door hands the identity provider a sign-in page error address that keeps the page's `?redirect=`, and its own landing on the sign-in page (no provider to start, a refused or rate-limited start) keeps it too. A `?redirect=` that is not a same-origin path is dropped, by the return path's own rule. diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index 89fa9bce850..ba6b54b54c8 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -758,6 +758,17 @@ 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 +`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. + **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 started, and only when this server mounted the door: a setting turned on @@ -772,7 +783,10 @@ no session itself. `//host`, a backslash, a control character (a tab or a newline included), or any of these behind percent-encoding is dropped, and the sign-in returns to the Console home page. The query takes `callbackURL` only, once. Anything else -is refused **400 `VALIDATION_ERROR`**. +is refused **400 `VALIDATION_ERROR`**. When the sign-in lands back on the +sign-in page instead (the provider's error, or a start the door could not +make), the page's own `?redirect=` comes with it, under the same same-origin +rule. **No loops.** The page shows itself, with a **Continue with single sign-on** button (and the reason, where there is one), instead of starting again when: 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 7360e32c172..2a7f505a526 100644 --- a/packages/plugins/plugin-auth/src/direct-sign-in.test.ts +++ b/packages/plugins/plugin-auth/src/direct-sign-in.test.ts @@ -276,6 +276,46 @@ describe('runDirectSignIn: the start door', () => { expect((host.logger!.warn as any).mock.calls[0][1]).toMatchObject({ reason: 'rate_limited' }); }); + // The page hands the door its own path and query; its `?redirect=` survives every landing back on `/login`. + const PAGE_WITH_REDIRECT = `?callbackURL=${encodeURIComponent('/_console/login?redirect=%2Fapps%2Fcrm%3Fview%3Dall&direct=returned')}`; + + it('hands the vendor a sign-in page error address that keeps the page\'s ?redirect=', async () => { + const { host, dispatched } = fakeHost(); + await runDirectSignIn(door(PAGE_WITH_REDIRECT), host); + expect(dispatched[0].body.errorCallbackURL).toBe(`${ORIGIN}/_console/login?redirect=%2Fapps%2Fcrm%3Fview%3Dall`); + expect(new URL(dispatched[0].body.errorCallbackURL).searchParams.get('redirect')).toBe('/apps/crm?view=all'); + }); + + it('lands a rate-limited start on the sign-in page with the page\'s ?redirect= kept', async () => { + const { host } = fakeHost({ dispatch: async () => new Response('{"message":"Too many requests"}', { status: 429 }) }); + const res = await runDirectSignIn(door(PAGE_WITH_REDIRECT), host); + expect(res.status).toBe(302); + const location = new URL(res.headers.get('location')!); + expect(`${location.origin}${location.pathname}`).toBe(`${ORIGIN}/_console/login`); + expect(location.searchParams.get('error')).toBe(DIRECT_SIGN_IN_RATE_LIMITED); + expect(location.searchParams.get('redirect')).toBe('/apps/crm?view=all'); + }); + + it('CONTROL: with no ?redirect= on the page, both landings are the bare sign-in page as before', async () => { + const plain = `?callbackURL=${encodeURIComponent('/_console/login?direct=returned')}`; + const { host, dispatched } = fakeHost(); + await runDirectSignIn(door(plain), host); + expect(dispatched[0].body.errorCallbackURL).toBe(`${ORIGIN}/_console/login`); + const limited = fakeHost({ dispatch: async () => new Response('{}', { status: 429 }) }); + const res = await runDirectSignIn(door(plain), limited.host); + expect(res.headers.get('location')).toBe(`${ORIGIN}/_console/login?error=${DIRECT_SIGN_IN_RATE_LIMITED}`); + }); + + it.each(FOREIGN_RETURN_PATHS)('drops the foreign ?redirect= %j, the return path\'s own rule, and still lands on the page', async (foreign) => { + const page = `/_console/login?redirect=${encodeURIComponent(foreign)}&direct=returned`; + const { host, dispatched } = fakeHost(); + await runDirectSignIn(door(`?callbackURL=${encodeURIComponent(page)}`), host); + expect(dispatched[0].body.errorCallbackURL).toBe(`${ORIGIN}/_console/login`); + const limited = fakeHost({ dispatch: async () => new Response('{}', { status: 429 }) }); + const res = await runDirectSignIn(door(`?callbackURL=${encodeURIComponent(page)}`), limited.host); + expect(res.headers.get('location')).toBe(`${ORIGIN}/_console/login?error=${DIRECT_SIGN_IN_RATE_LIMITED}`); + }); + it('lands on the sign-in page with an error, never a retry, when no provider resolves or the start is refused', async () => { const cases: Array> = [ { chooseProvider: async () => ({ miss: 'several_providers' }) }, diff --git a/packages/plugins/plugin-auth/src/direct-sign-in.ts b/packages/plugins/plugin-auth/src/direct-sign-in.ts index c89b565e88c..ee2edffefa8 100644 --- a/packages/plugins/plugin-auth/src/direct-sign-in.ts +++ b/packages/plugins/plugin-auth/src/direct-sign-in.ts @@ -211,6 +211,33 @@ export function keptReturnPath(raw: unknown): string | undefined { return raw; } +/** + * The `redirect` the sign-in page was opened with, read from the kept return + * path (the page hands the door its own path and query), so a landing back on + * the page (the door's own error, or the identity provider's) still knows where + * the person was going. Carried only when it is sent once and is itself a kept + * return path ({@link keptReturnPath}); otherwise none. + */ +export function carriedRedirect(kept: string | undefined): string | undefined { + if (kept === undefined) return undefined; + let values: string[]; + try { + values = new URL(kept, 'https://return-path.invalid').searchParams.getAll('redirect'); + } catch { + return undefined; + } + return values.length === 1 ? keptReturnPath(values[0]) : 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 { + const params = new URLSearchParams(); + if (error !== undefined) params.set('error', error); + if (redirect !== undefined) params.set('redirect', redirect); + const query = params.toString(); + return `${host.consolePageUrl('/login')}${query ? `?${query}` : ''}`; +} + /** Which vendor start a provider takes. */ export type DirectSignInProvider = | { kind: 'oauth'; providerId: string } @@ -343,6 +370,8 @@ function queryOf(url: URL): Record { * Console's `/login?error=direct_sign_in_unavailable`, and one `warn` line; * a start the vendor's rate limit refused (`429`) ⇒ the same, with * `error=direct_sign_in_rate_limited` and the reason `rate_limited`. + * - Every landing on `/login`, the door's and the vendor's error return + * address alike, carries the page's `?redirect=` ({@link carriedRedirect}). * * The caller mounts the door only while the setting is on; a call with it off * answers `404 RESOURCE_NOT_FOUND` like an unmounted route. @@ -369,13 +398,18 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost): }); } + const requested = url.searchParams.get('callbackURL'); + const kept = keptReturnPath(requested); + // Every landing on the sign-in page keeps the page's own `?redirect=`. + const redirectTo = carriedRedirect(kept); + const unavailable = (reason: DirectSignInMiss, providerId?: string): Response => { const text = `[auth] Direct sign-in not started: ${reason}. The sign-in page is shown instead.`; const meta = { entry: 'direct_sign_in', reason, ...(providerId ? { providerId } : {}) }; if (host.logger) host.logger.warn(text, meta); else console.warn(text, meta); const code = reason === 'rate_limited' ? DIRECT_SIGN_IN_RATE_LIMITED : DIRECT_SIGN_IN_UNAVAILABLE; - return redirect(`${host.consolePageUrl('/login')}?error=${code}`); + return redirect(signInPageUrl(host, redirectTo, code)); }; let chosen: DirectSignInProvider | { miss: DirectSignInProviderMiss }; @@ -386,8 +420,6 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost): } if ('miss' in chosen) return unavailable(chosen.miss); - const requested = url.searchParams.get('callbackURL'); - const kept = keptReturnPath(requested); if (requested !== null && kept === undefined) { host.logger?.debug?.('[auth] Direct sign-in: the return path is not a same-origin path and was dropped.', { entry: 'direct_sign_in', @@ -397,7 +429,7 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost): const callbackURL = kept !== undefined ? `${origin}${kept}` : host.consolePageUrl('/'); // Defence in depth: whatever was kept, the sign-in returns to this origin. if (new URL(callbackURL).origin !== new URL(origin).origin) return unavailable('start_refused'); - const errorCallbackURL = host.consolePageUrl('/login'); + const errorCallbackURL = signInPageUrl(host, redirectTo); const body = chosen.kind === 'oauth' ? { provider: chosen.providerId, callbackURL, errorCallbackURL, disableRedirect: true } 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 44f12359cb9..7d221d6568d 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 @@ -470,6 +470,9 @@ const PASSWORD = 'S3cure!Passw0rd-30300'; const SYS = { isSystem: true } as const; const ENV_KEYS_30300 = [ + 'OS_AUTH_DIRECT_SIGN_IN_ENABLED', + 'OS_AUTH_DIRECT_SIGN_IN_PROVIDER', + 'OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_GOOGLE_ENABLED', 'GOOGLE_CLIENT_ID', @@ -550,8 +553,8 @@ describe('the last way to sign in is kept, and a boot without one is said (#3030 // ── Door 1 ───────────────────────────────────────────────────────────────── /** A signed-in administrator who owns `providers`, on a deployment with enterprise SSO switched on. */ - async function adminWithProviders(providers: string[]) { - const env = await boot({ plugins: { sso: true } }); + async function adminWithProviders(providers: string[], authOptions: Record = {}) { + const env = await boot({ plugins: { sso: true }, ...authOptions }); const { ql, manager } = env; const signedUp = await manager.handleRequest( new Request(`${AUTH}/sign-up/email`, { @@ -651,8 +654,55 @@ describe('the last way to sign in is kept, and a boot without one is said (#3030 expect(await providerIds()).toEqual(['okta']); }, 30_000); + // The local sign-in path behind direct sign-in: under `off` the sign-in page + // draws no email and password, so it is no way in there, on or not. + + it('under the local sign-in path off, deleting the last provider is refused with email and password on: 409, nothing deleted', async () => { + const { manager, remove, providerIds } = await adminWithProviders(['okta'], { directSignIn: { localSignIn: 'off' } }); + expect(manager.getPublicConfig().emailPassword.enabled).toBe(true); + expect(manager.getPublicConfig().features.localSignIn).toBe('off'); + + const res = await remove('okta'); + const body = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(409); + expect(body).toMatchObject({ + code: 'DELETE_RESTRICTED', + message: SIGN_IN_FLOOR_COPY.en.enterpriseSsoLocalOff, + lastSignInMethod: 'enterprise_sso', + }); + expect(await providerIds()).toEqual(['okta']); + }, 30_000); + + it('CONTROL: with the local sign-in path hidden (the page offers email and password), deleting the last provider goes through as before', async () => { + const { manager, remove, providerIds } = await adminWithProviders(['okta'], { directSignIn: { localSignIn: 'hidden' } }); + expect(manager.getPublicConfig().features.localSignIn).toBe('hidden'); + + const res = await remove('okta'); + expect(res.status, await res.clone().text()).toBe(200); + expect(await providerIds()).toEqual([]); + }, 30_000); + // ── Door 2 ───────────────────────────────────────────────────────────────── + it('a boot under the local sign-in path off with no provider is said at error, email and password on or not', async () => { + const { manager, reports } = await boot({ directSignIn: { localSignIn: 'off' } }); + expect(manager.getPublicConfig().emailPassword.enabled).toBe(true); + expect(reports()).toHaveLength(1); + expect(reports()[0]).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden'); + }, 30_000); + + it('a boot under the local sign-in path off with email and password off too names both settings to recover', async () => { + const { manager, reports } = await boot({ emailAndPassword: { enabled: false }, directSignIn: { localSignIn: 'off' } }); + expect(manager.getPublicConfig().emailPassword.enabled).toBe(false); + expect(reports()).toHaveLength(1); + expect(reports()[0]).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden and OS_AUTH_EMAIL_PASSWORD_ENABLED=true'); + }, 30_000); + + it('CONTROL: the same boot with the local sign-in path hidden says nothing', async () => { + const { reports } = await boot({ directSignIn: { localSignIn: 'hidden' } }); + expect(reports()).toEqual([]); + }, 30_000); + it('a redeploy that drops the last provider while email and password is off is said at error, and still boots', async () => { const { manager, reports } = await boot({ emailAndPassword: { enabled: false } }); @@ -746,6 +796,43 @@ describe('the floor judges a provider delete and a boot by what it can read (#30 expect(await resolveNoSignInMethodReport(deps({ hostSignInHandoff: true }))).toBeNull(); }); + it('counts the local ways in only as the sign-in page offers them: under localSignIn off, neither email and password nor phone sign-in', async () => { + const LOCAL_OFF: SignInMethodConfigView = { + emailPassword: { enabled: true }, + socialProviders: [], + features: { sso: true, phoneNumber: true, localSignIn: 'off' }, + }; + await expect(ssoProviderDeleteRefusal(deps({ config: LOCAL_OFF, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toEqual({ + status: 'CONFLICT', + code: 'DELETE_RESTRICTED', + message: SIGN_IN_FLOOR_COPY.en.enterpriseSsoLocalOff, + lastSignInMethod: 'enterprise_sso', + }); + expect(await resolveNoSignInMethodReport(deps({ config: LOCAL_OFF, rows: [] }))).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden'); + // CONTROL: the same deployment with the path hidden counts both as before. + const HIDDEN: SignInMethodConfigView = { ...LOCAL_OFF, features: { ...LOCAL_OFF.features, localSignIn: 'hidden' } }; + await expect(ssoProviderDeleteRefusal(deps({ config: HIDDEN, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toBeUndefined(); + expect(await resolveNoSignInMethodReport(deps({ config: HIDDEN, rows: [] }))).toBeNull(); + const PHONE_ONLY: SignInMethodConfigView = { ...HIDDEN, emailPassword: { enabled: false } }; + await expect(ssoProviderDeleteRefusal(deps({ config: PHONE_ONLY, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toBeUndefined(); + // Phone sign-in alone under off, email and password off too: the page draws neither, so the delete is refused, + // and the remedy is the local-path one (turning email and password back on alone draws nothing under off). + const PHONE_ONLY_OFF: SignInMethodConfigView = { ...PHONE_ONLY, features: { ...PHONE_ONLY.features, localSignIn: 'off' } }; + await expect(ssoProviderDeleteRefusal(deps({ config: PHONE_ONLY_OFF, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toMatchObject({ + code: 'DELETE_RESTRICTED', + message: SIGN_IN_FLOOR_COPY.en.enterpriseSsoLocalOff, + }); + const report = await resolveNoSignInMethodReport(deps({ config: PHONE_ONLY_OFF, rows: [] })); + expect(report).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden and OS_AUTH_EMAIL_PASSWORD_ENABLED=true'); + expect(report).not.toContain('no phone-number sign-in'); + // CONTROL: email and password off with the page drawing local sign-in keeps the email-off copy and report. + const EMAIL_OFF_HIDDEN: SignInMethodConfigView = { ...OFF, features: { sso: true, localSignIn: 'hidden' } }; + await expect(ssoProviderDeleteRefusal(deps({ config: EMAIL_OFF_HIDDEN, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toMatchObject({ + message: SIGN_IN_FLOOR_COPY.en.enterpriseSso, + }); + expect(await resolveNoSignInMethodReport(deps({ config: EMAIL_OFF_HIDDEN, rows: [] }))).toContain('OS_AUTH_EMAIL_PASSWORD_ENABLED=true and restart'); + }); + 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 36e18cac061..5f399350d89 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts @@ -38,6 +38,12 @@ * that provider is one of the above or nothing), and magic link and passkeys, * which no login page offers (`PUBLIC_AUTH_FEATURES_NOT_ADVERTISED`). * + * 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. + * * ## The changes refused * * - `email_password_enabled` off when nothing else is in force after the save; @@ -102,6 +108,7 @@ import { type BootStorePresence, } from './boot-sign-in-reachability.js'; import { SSO_PROVIDER_OBJECT } from './sso-client-secret.js'; +import { DIRECT_SIGN_IN_ENV } from './direct-sign-in.js'; /** A way in other than email and password, as {@link otherSignInMethods} names it. */ export type OtherSignInMethod = 'social_provider' | 'enterprise_sso' | 'phone_number' | 'host_handoff'; @@ -110,7 +117,23 @@ export type OtherSignInMethod = 'social_provider' | 'enterprise_sso' | 'phone_nu export interface SignInMethodConfigView { emailPassword?: { enabled?: boolean }; socialProviders?: Array<{ id?: string; type?: string; enabled?: boolean }>; - features?: { sso?: boolean; phoneNumber?: boolean }; + features?: { sso?: boolean; phoneNumber?: boolean; localSignIn?: 'hidden' | 'off' }; +} + +/** + * Whether the sign-in page offers the local ways in (email and password, phone + * sign-in): the page reads `features.localSignIn`, which `getPublicConfig()` + * serves only while direct sign-in is on, and under `'off'` draws none of them. + * The server's own password door is unchanged by it, but the floor counts what + * the page offers, so a way in the page does not draw counts for nothing. + */ +export function pageOffersLocalSignIn(config: SignInMethodConfigView): boolean { + return config.features?.localSignIn !== 'off'; +} + +/** Email and password is on AND the sign-in page offers it ({@link pageOffersLocalSignIn}). */ +export function pageOffersEmailPassword(config: SignInMethodConfigView): boolean { + return config.emailPassword?.enabled !== false && pageOffersLocalSignIn(config); } /** Live readers, asked at save time, never recorded at boot. */ @@ -198,11 +221,13 @@ function providerCounts( * The ways in besides email and password that are in force now. `withoutGoogle` * leaves the settings-managed Google provider out, to judge a save that may * remove or add it; `withoutEnterpriseSso` leaves enterprise SSO out (and reads - * no provider row), for a caller that judges the provider rows itself. + * no provider row), for a caller that judges the provider rows itself; + * `asThePageOffers` counts phone sign-in only when the sign-in page draws it + * ({@link pageOffersLocalSignIn}). */ export async function otherSignInMethods( deps: SignInMethodFloorDeps, - options: { withoutGoogle?: boolean; withoutEnterpriseSso?: boolean } = {}, + options: { withoutGoogle?: boolean; withoutEnterpriseSso?: boolean; asThePageOffers?: boolean } = {}, ): Promise { const config = deps.publicConfig(); const methods: OtherSignInMethod[] = []; @@ -210,7 +235,9 @@ export async function otherSignInMethods( (p) => providerCounts(deps, p) && !(options.withoutGoogle && isSettingsGoogle(p)), ); if (providers.length > 0) methods.push('social_provider'); - if (config.features?.phoneNumber === true) methods.push('phone_number'); + if (config.features?.phoneNumber === true && (!options.asThePageOffers || pageOffersLocalSignIn(config))) { + methods.push('phone_number'); + } if (deps.hostSignInHandoff) methods.push('host_handoff'); if ( !options.withoutEnterpriseSso && @@ -229,6 +256,8 @@ interface SignInFloorCopy { google: 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. */ + enterpriseSsoLocalOff: string; /** The provider list could not be read to judge that delete. */ enterpriseSsoUnverified: string; } @@ -252,6 +281,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { '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 ' + 'sign-in back on, or register another identity provider or set up another sign-in method, then delete this one.', + enterpriseSsoLocalOff: + 'This is the last enterprise SSO identity provider, and the sign-in page offers no local sign-in (the local ' + + 'sign-in path behind direct sign-in is off), so nothing else signs anyone in: deleting it would lock everyone ' + + 'out, administrators included. First register another identity provider, set up another sign-in method, or set ' + + '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 ' + @@ -267,6 +301,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { enterpriseSso: '这是最后一个企业 SSO 身份提供方,邮箱/密码登录又已关闭,没有其他登录方式,删除后所有人(包括管理员)都将无法登录。' + '请先重新开启邮箱/密码登录,或登记另一个身份提供方、配置另一种登录方式,然后再删除它。', + enterpriseSsoLocalOff: + '这是最后一个企业 SSO 身份提供方,而登录页不提供本地登录(直接登录的本地登录路径已关闭),没有其他登录方式,' + + '删除后所有人(包括管理员)都将无法登录。请先登记另一个身份提供方、配置另一种登录方式,或把本地登录路径改回 hidden 并开启邮箱/密码登录,' + + '然后再删除它。', enterpriseSsoUnverified: '身份提供方未删除:无法读取身份提供方列表来确认仍有其他登录方式,而邮箱/密码登录已关闭,它可能是最后一种。' + '请在数据库可以访问时重试。', @@ -285,6 +323,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'これは最後のエンタープライズ SSO の ID プロバイダーで、メール/パスワードログインもオフのため他にログイン方法が' + 'ありません。削除すると管理者を含む全員がログインできなくなります。先にメール/パスワードログインをオンに戻すか、' + '別の ID プロバイダーを登録するか別のログイン方法を設定してから削除してください。', + enterpriseSsoLocalOff: + 'これは最後のエンタープライズ SSO の ID プロバイダーで、ログインページはローカルログインを表示しません(ダイレクト' + + 'サインインのローカルログインパスがオフ)。他にログイン方法がないため、削除すると管理者を含む全員がログインできなく' + + 'なります。先に別の ID プロバイダーを登録するか、別のログイン方法を設定するか、ローカルログインパスを hidden に戻してメール/パスワードログインをオンにしてから' + + '削除してください。', enterpriseSsoUnverified: 'ID プロバイダーは削除されませんでした。ID プロバイダーの一覧を読み取れず、他のログイン方法が残ることを確認できません' + 'でした。メール/パスワードログインがオフのため、これが最後のログイン方法かもしれません。データベースに接続できる' + @@ -306,6 +349,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'nada más permite iniciar sesión, así que eliminarlo dejaría fuera a todo el mundo, incluidos los ' + 'administradores. Vuelva a activar primero el inicio de sesión con correo y contraseña, o registre otro ' + 'proveedor de identidad o configure otro método, y después elimine este.', + enterpriseSsoLocalOff: + 'Este es el último proveedor de identidad de SSO empresarial y 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 nada más permite ' + + 'iniciar sesión: eliminarlo dejaría fuera a todo el mundo, incluidos los administradores. Primero registre otro ' + + 'proveedor de identidad, configure otro método de inicio de sesión o vuelva a poner la ruta local en hidden con el correo y la contraseña activados, y ' + + '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 ' + @@ -321,6 +370,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { enterpriseSso: '這是最後一個企業 SSO 身分提供者,電子郵件/密碼登入又已關閉,沒有其他登入方式,刪除後所有人(包括管理員)都將無法登入。' + '請先重新開啟電子郵件/密碼登入,或登記另一個身分提供者、設定另一種登入方式,然後再刪除它。', + enterpriseSsoLocalOff: + '這是最後一個企業 SSO 身分提供者,而登入頁不提供本機登入(直接登入的本機登入路徑已關閉),沒有其他登入方式,' + + '刪除後所有人(包括管理員)都將無法登入。請先登記另一個身分提供者、設定另一種登入方式,或把本機登入路徑改回 hidden 並開啟電子郵件/密碼登入,' + + '然後再刪除它。', enterpriseSsoUnverified: '身分提供者未刪除:無法讀取身分提供者清單來確認仍有其他登入方式,而電子郵件/密碼登入已關閉,它可能是最後一種。' + '請在資料庫可以存取時重試。', @@ -338,6 +391,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'هذا آخر موفّر هوية SSO مؤسسي، ومع إيقاف البريد الإلكتروني وكلمة المرور لا شيء غيره يتيح لأحد تسجيل الدخول، ' + 'لذا فإن حذفه سيمنع الجميع من الدخول بمن فيهم المسؤولون. أعد أولًا تفعيل تسجيل الدخول بالبريد الإلكتروني ' + 'وكلمة المرور، أو سجّل موفّر هوية آخر أو اضبط طريقة أخرى لتسجيل الدخول، ثم احذف هذا الموفّر.', + enterpriseSsoLocalOff: + 'هذا آخر موفّر هوية للدخول الموحّد المؤسسي، وصفحة تسجيل الدخول لا تعرض تسجيل الدخول المحلي (مسار تسجيل الدخول ' + + 'المحلي خلف تسجيل الدخول المباشر متوقف)، فلا شيء آخر يتيح تسجيل الدخول: حذفه سيمنع الجميع من الدخول، بمن فيهم ' + + 'المسؤولون. سجّل أولًا موفّر هوية آخر، أو أعدّ طريقة تسجيل دخول أخرى، أو أعد مسار تسجيل الدخول المحلي إلى hidden مع تشغيل تسجيل الدخول بالبريد الإلكتروني وكلمة المرور، ' + + 'ثم احذف هذا الموفّر.', enterpriseSsoUnverified: 'لم يُحذف موفّر الهوية: تعذّرت قراءة قائمة موفّري الهوية للتأكد من بقاء طريقة أخرى لتسجيل الدخول، ومع إيقاف ' + 'البريد الإلكتروني وكلمة المرور قد يكون هذا آخرها. أعد المحاولة عندما تصبح قاعدة البيانات متاحة.', @@ -357,6 +415,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'rien d’autre ne permet de se connecter : le supprimer bloquerait tout le monde, administrateurs compris. ' + 'Réactivez d’abord la connexion par e-mail et mot de passe, ou enregistrez un autre fournisseur d’identité ou ' + 'configurez une autre méthode de connexion, puis supprimez celui-ci.', + enterpriseSsoLocalOff: + 'Ceci est le dernier fournisseur d\'identité SSO d\'entreprise, et la page de connexion n\'offre aucune ' + + 'connexion locale (le chemin de connexion locale derrière la connexion directe est désactivé) : rien d\'autre ne ' + + 'permet de se connecter, et le supprimer bloquerait tout le monde, administrateurs compris. Enregistrez d\'abord ' + + 'un autre fournisseur d\'identité, configurez une autre méthode de connexion ou remettez le chemin de connexion ' + + '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, ' + @@ -377,6 +441,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'permite entrar, então excluí-lo bloquearia todos, inclusive os administradores. Primeiro reative o login com ' + 'e-mail e senha, ou cadastre outro provedor de identidade ou configure outro método de login, e depois exclua ' + 'este.', + enterpriseSsoLocalOff: + 'Este é o último provedor de identidade de SSO empresarial, e 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 nada mais permite entrar: excluí-lo ' + + 'deixaria todos de fora, incluindo os administradores. Primeiro registre outro provedor de identidade, configure ' + + '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. ' + @@ -397,6 +466,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'что войти больше нечем: его удаление лишит доступа всех, включая администраторов. Сначала снова включите вход ' + 'по электронной почте и паролю либо зарегистрируйте другого поставщика удостоверений или настройте другой ' + 'способ входа, а затем удалите этого.', + enterpriseSsoLocalOff: + 'Это последний поставщик удостоверений корпоративного SSO, а страница входа не предлагает локальный вход ' + + '(локальный путь входа за прямым входом отключён), поэтому войти иначе невозможно: его удаление заблокирует всех, ' + + 'включая администраторов. Сначала зарегистрируйте другого поставщика удостоверений, настройте другой способ входа ' + + 'или верните локальному пути входа значение hidden с включённым входом по почте и паролю, а затем удалите этого.', enterpriseSsoUnverified: 'Поставщик удостоверений не удалён: не удалось прочитать список поставщиков удостоверений, чтобы убедиться, ' + 'что останется другой способ входа, а при отключённом входе по электронной почте и паролю этот может быть ' + @@ -417,6 +491,12 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Passwort meldet nichts anderes jemanden an. Ihn zu löschen würde daher alle aussperren, Administratoren ' + 'eingeschlossen. Schalten Sie zuerst die Anmeldung mit E-Mail und Passwort wieder ein oder registrieren Sie ' + 'einen anderen Identitätsanbieter bzw. richten Sie eine andere Anmeldemethode ein, und löschen Sie ihn dann.', + enterpriseSsoLocalOff: + 'Dies ist der letzte Identitätsanbieter für Enterprise-SSO, und die Anmeldeseite bietet keine lokale Anmeldung ' + + 'an (der lokale Anmeldepfad hinter der Direktanmeldung ist aus), sodass sich niemand anders anmelden kann: Ihn zu ' + + 'löschen würde alle aussperren, Administratoren eingeschlossen. Registrieren Sie zuerst einen anderen ' + + '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 ' + @@ -435,6 +515,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { '이것은 마지막 엔터프라이즈 SSO ID 공급자이며, 이메일/비밀번호 로그인도 꺼져 있어 다른 로그인 방법이 없습니다. ' + '삭제하면 관리자를 포함한 모든 사람이 로그인할 수 없게 됩니다. 먼저 이메일/비밀번호 로그인을 다시 켜거나, 다른 ID ' + '공급자를 등록하거나 다른 로그인 방법을 설정한 뒤 이 공급자를 삭제하세요.', + enterpriseSsoLocalOff: + '이것은 마지막 엔터프라이즈 SSO ID 공급자이며, 로그인 페이지는 로컬 로그인을 제공하지 않습니다(직접 로그인의 로컬 ' + + '로그인 경로가 꺼져 있음). 다른 로그인 방법이 없으므로 삭제하면 관리자를 포함한 모든 사람이 로그인할 수 없게 ' + + '됩니다. 먼저 다른 ID 공급자를 등록하거나, 다른 로그인 방법을 설정하거나, 로컬 로그인 경로를 hidden으로 되돌리고 이메일/비밀번호 로그인을 켠 ' + + '다음 이 공급자를 삭제하세요.', enterpriseSsoUnverified: 'ID 공급자를 삭제하지 않았습니다. 다른 로그인 방법이 남아 있는지 확인하기 위해 ID 공급자 목록을 읽을 수 없었고, ' + '이메일/비밀번호 로그인이 꺼져 있어 이것이 마지막 방법일 수 있습니다. 데이터베이스에 연결할 수 있게 되면 다시 ' + @@ -646,10 +731,11 @@ export interface SsoProviderDeleteRefusal { /** * Whether deleting the identity provider `providerId` would leave no way to * sign in, asked before the vendor deletes anything. Nothing is refused while - * email and password is on, while enterprise SSO is not switched on (its rows - * then sign nobody in either way), or while another way in counts - * ({@link otherSignInMethods}, enterprise SSO left out) or another provider row - * remains. Otherwise the delete would remove the last way in: `409 + * the sign-in page offers email and password ({@link pageOffersEmailPassword}: + * on, and the local sign-in path behind direct sign-in not `off`), while + * enterprise SSO is not switched on (its rows then sign nobody in either way), + * or while another way in the page offers counts ({@link otherSignInMethods}, + * enterprise SSO left out) or another provider row remains. Otherwise the delete would remove the last way in: `409 * DELETE_RESTRICTED` (the standard code for a delete refused while something * depends on the row; `organization-delete.ts` answers the same), or `503 * SERVICE_UNAVAILABLE` when the provider list cannot be read to tell, because a @@ -661,9 +747,9 @@ export async function ssoProviderDeleteRefusal( locale?: string, ): Promise { const config = deps.publicConfig(); - if (config.emailPassword?.enabled !== false) return undefined; + if (pageOffersEmailPassword(config)) return undefined; if (config.features?.sso !== true) return undefined; - if ((await otherSignInMethods(deps, { withoutEnterpriseSso: true })).length > 0) return undefined; + if ((await otherSignInMethods(deps, { withoutEnterpriseSso: true, asThePageOffers: true })).length > 0) return undefined; const others = await probeOtherSsoProviders(deps.engine(), providerId); if (others === 'present' || others === 'not_found') return undefined; const copy = signInFloorCopy(locale); @@ -673,7 +759,8 @@ export async function ssoProviderDeleteRefusal( return { status: 'CONFLICT', code: 'DELETE_RESTRICTED', - message: copy.enterpriseSso, + // The page draws no local way in: turning email and password "back on" alone is no remedy. + message: pageOffersLocalSignIn(config) ? copy.enterpriseSso : copy.enterpriseSsoLocalOff, lastSignInMethod: 'enterprise_sso', }; } @@ -685,17 +772,34 @@ export const NO_SIGN_IN_METHOD_AT_BOOT = 'no_sign_in_method_at_boot'; /** * The boot report for a deployment that serves no way to sign in, or `null`. - * It makes a positive claim only: email and password is off, no other way in - * counts, and when enterprise SSO is switched on the provider table was READ + * It makes a positive claim only: the sign-in page does not offer email and + * password ({@link pageOffersEmailPassword}: off, or the local sign-in path + * behind direct sign-in is `off`), no other way in the page offers counts, and when enterprise SSO is switched on the provider table was READ * and holds no row. A provider table that cannot be read proves nothing either * way, so it stays silent, as `no_sign_in_account_at_boot` does on an * unanswered probe. */ export async function resolveNoSignInMethodReport(deps: SignInMethodFloorDeps): Promise { const config = deps.publicConfig(); - if (config.emailPassword?.enabled !== false) return null; - if ((await otherSignInMethods(deps, { withoutEnterpriseSso: true })).length > 0) return null; + if (pageOffersEmailPassword(config)) return null; + if ((await otherSignInMethods(deps, { withoutEnterpriseSso: true, asThePageOffers: true })).length > 0) return null; if (config.features?.sso === true && (await probeSsoProvidersPresence(deps.engine())) !== 'absent') return null; + if (!pageOffersLocalSignIn(config)) { + // The sign-in page draws no local way in, whatever email and password says. + return ( + `[auth] ${NO_SIGN_IN_METHOD_AT_BOOT}: this deployment serves NO way to sign in on its sign-in page, so nobody ` + + 'can sign in there, administrators included, while it keeps looking healthy. The local sign-in path behind ' + + `direct sign-in is off (${DIRECT_SIGN_IN_ENV.localSignIn} or directSignIn.localSignIn), so the page offers no ` + + 'email and password and no phone sign-in, and no other sign-in method is in force: no social or OIDC provider ' + + 'with a client ID and secret, no enterprise SSO identity provider and no host sign-in handoff. Recover: set ' + + `${DIRECT_SIGN_IN_ENV.localSignIn}=hidden` + + (config.emailPassword?.enabled === false + ? ' and OS_AUTH_EMAIL_PASSWORD_ENABLED=true (email and password sign-in is off too)' + : '') + + ' and restart (the page then offers email and password at /login?local=1), or restore the identity provider ' + + 'this configuration no longer declares. The boot continues.' + ); + } return ( `[auth] ${NO_SIGN_IN_METHOD_AT_BOOT}: this deployment serves NO way to sign in, so nobody can sign in, ` + 'administrators included, while it keeps looking healthy. Email and password sign-in is off, and no other ' +