Skip to content

Commit a27d88d

Browse files
fix(plugin-auth)!: under local sign-in off, the last identity provider is the last way in; the direct sign-in door keeps ?redirect= (#33623)
Part of #33358 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. ## 维护者速读 - **改了什么**:直接登录把本地登录路径设为 `off` 时,登录页不再显示邮箱/密码和手机登录;现在"保留最后一种登录方式"的检查也不再把它们算作登录方式,所以删除最后一个身份提供方会被拒绝(409),启动时也会报错提示。另外,直接登录入口把人送回登录页时(身份提供方报错、被限流、无法发起)会带上原来的 `?redirect=`。 - **为什么改**:之前在 `off` 下删掉最后一个身份提供方会成功,随后登录页只显示"没有可用的登录方式",所有人(包括管理员)被锁在外面;深链接用户在出错后重试会落到首页而不是原来要去的页面。 - **风险与回滚**:只影响开启直接登录且本地登录路径为 `off` 的自托管部署(之前允许的删除现在被拒,属于收窄,已标 BREAKING);`hidden`(默认)和未开启直接登录的部署行为不变。回滚即 revert 本 PR。 - **先看**:`packages/plugins/plugin-auth/src/sign-in-method-floor.ts`(`ssoProviderDeleteRefusal` 与 `resolveNoSignInMethodReport` 两处判断)、`packages/plugins/plugin-auth/src/direct-sign-in.ts`(`carriedRedirect` 与两个落地地址)、`.changeset/33358-local-sign-in-off-floor.md`。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run src/sign-in-method-floor.test.ts src/direct-sign-in.test.ts`,预期全部通过,其中包含 `under the local sign-in path off, deleting the last provider is refused` 与 `keeps the page's ?redirect=` 几条。 - **需要你做的**:无,席位落地。 ## What changes Items covered from #33358: **1** (N7, the sign-in method floor and the boot report), **3** (the provider-error return address keeps `?redirect=`) and **4** (the rate-limited landing keeps `?redirect=`). Items **2** (the IP allow-list landing on the direct sign-in door) and **5** (the N13 sign-out note) remain on the card for a later round. **Item 1 — the floor counts what the sign-in page offers.** The page decides what it draws from `features.localSignIn`, which `getPublicConfig()` serves only while direct sign-in is on: under `'off'` `LoginForm` draws no email and password and no phone sign-in. The floor now reads the same served value with the same predicate (`pageOffersLocalSignIn(config)` is `config.features?.localSignIn !== 'off'`, exactly the page's test), so: - `ssoProviderDeleteRefusal` (the `/sso/delete-provider` door) and `resolveNoSignInMethodReport` (the boot report) count email and password only when it is on **and** the page offers it (`pageOffersEmailPassword`), and count phone sign-in only when the page offers it (`otherSignInMethods(..., { asThePageOffers: true })`). - The 409 under `off` carries a new localized copy, `enterpriseSsoLocalOff` (11 locales), chosen by `!pageOffersLocalSignIn(config)` whatever email and password says, because the existing copy's remedy, "turn email and password sign-in back on", draws nothing under `off`. Its remedy: 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. - The boot report under `off` (chosen the same way) names `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden` as the recovery, plus `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` when email and password is off too; it no longer says "no phone-number sign-in" there. Phone sign-in is included as a bounded in-place fix: it is the same defect class (a local way in the page does not draw under `off`, counted anyway), a mechanical change in the same file, held by this claim, in the same gate family. Without it a deployment with phone sign-in on and `off` would pass the same delete and reach the same "No sign-in method is available" page. **Items 3 and 4 — the door's landings keep `?redirect=`.** The Console hands the door its own path and query as `callbackURL` (for example `/_console/login?redirect=%2Fapps%2Fcrm&direct=returned`). `carriedRedirect(kept)` reads `redirect` from the already-kept return path, carries it only when it is sent once and is itself a kept return path (`keptReturnPath`, the door's existing same-origin rule), and both landings now use it: the `errorCallbackURL` handed to the vendor (`/login?redirect=...`; better-auth appends its `error` to it) and the door's own landing (`/login?error=...&redirect=...`, the rate-limited one and the unavailable one alike). With no `?redirect=`, or a foreign one, both are the bare page exactly as before. Docs: `content/docs/permissions/sso.mdx` says both rules, names the two checks this PR changes (the provider delete and the boot report, email and password and phone sign-in alike), and says the settings save is still open on #33358. ## Tests - `src/sign-in-method-floor.test.ts`, the composition (real kernel, sqlite, AuthPlugin and settings): under `directSignIn: { localSignIn: 'off' }` with email and password on, deleting the last provider answers 409 `DELETE_RESTRICTED` with `enterpriseSsoLocalOff` and the row stays; CONTROL: under `hidden` the same delete is 200 and the row is gone; a boot under `off` with no provider reports `no_sign_in_method_at_boot` naming `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden`; CONTROL: the same boot under `hidden` says nothing. - Same file, the judge over a fake: under `off`, neither email and password nor phone sign-in counts (delete refused, boot report said); CONTROL under `hidden`: both count as before; phone alone under `off` with email and password off is refused with `enterpriseSsoLocalOff` and its boot report names both settings without "no phone-number sign-in"; CONTROL: email and password off under `hidden` keeps the `enterpriseSso` copy and the `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` report. Composition: a boot under `off` with email and password off names `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden and OS_AUTH_EMAIL_PASSWORD_ENABLED=true`. - `src/direct-sign-in.test.ts`: the vendor's `errorCallbackURL` keeps `?redirect=`; the rate-limited landing keeps it; CONTROL: with no `?redirect=` both landings are the bare page, as before; a foreign `?redirect=` is dropped and the landings are the bare page, pinned over every spelling in `FOREIGN_RETURN_PATHS` (24: absolute, protocol-relative, backslash, `javascript:`, control characters, percent-encoded forms, `/..//`, empty, over-long). ## Acceptance notes - The card names the setting `OS_AUTH_LOCAL_SIGN_IN=off`; the variable in the code is `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH` (`directSignIn.localSignIn`). The premise holds otherwise. - Not changed here, same family: the auth **settings save** door (`signInMethodFloorPredicate`) still counts email and password on under `off`, so under `off` a save that switches off Google as the last social provider passes. Its refusal copy speaks of turning email and password back on, so a fix there needs its own copy. Reported to the seat for the card rather than widened here. - Not changed here: the 503 copy (`enterpriseSsoUnverified`) still says "with email and password off"; under `off` with email and password on it is slightly inaccurate, but it is still the right refusal. ## Verification Review#3 delta: head `cc741c8ef3` answers M1 and N1 to N4 of contract record 6888499485; the runs below the dogfood paragraph were taken at `2a03b651b6` and the delta's runs are in the first fold. Earlier head `2a03b651b6` (merge base `c32bb6ccb` = `origin/main` at the time; `origin/main` had not moved when re-fetched before opening). **Dogfood battery** (the title carries `!`): `pnpm --filter @objectstack/dogfood test` under the verify lock, dependency closure built first, on head `2a03b651b6`. It was still running when this PR opened; its verdict (Test Files, Tests, every failure named) goes into the `os-dev-report` comment on #33358, and the PR's own `Dogfood Regression Gate` runs it in the queue. <details><summary>Review#3 delta, local runs on head cc741c8</summary> - `pnpm --filter @objectstack/plugin-auth test` (verify lock): `Test Files 274 passed (274)`, `Tests 5336 passed | 10 skipped (5346)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/plugin-auth typecheck`: `VERDICT command-exit 0`, `check:test-typecheck: OK` (ledger unchanged). eslint `--no-inline-config` on the three changed `.ts` files: exit 0. `check-nul-bytes`: OK. - M1 ablations (scripts/ablation-replace.mjs, landed and restored, blob equal to HEAD): delete copy chosen by email and password again: 1 failed / 41; boot report branched by email and password again: 2 failed / 41. - Narrowed gate re-run (declared): `check-adr-0087-registration`, `check-empty-changeset`, `check-changeset-no-major`, `check:doc-authoring`, `check:issue-citations`, `check-closing-keyword-parity`, `check:doc-anchors`, `check-affected-docs`: all exit 0. The full derived set was not re-run for the delta; CI runs it. - Dogfood battery not re-run: the delta changes copy and report-text selection and test pins only; the runtime decision (refuse or allow, report or not) is unchanged from `2a03b651b6`, where the battery was green. </details> <details><summary>Local runs on head 2a03b65</summary> - `pnpm --filter @objectstack/plugin-auth test` (verify lock): `Test Files 274 passed (274)`, `Tests 5312 passed | 10 skipped (5322)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/plugin-auth build && pnpm --filter @objectstack/plugin-auth typecheck`: `VERDICT command-exit 0`; `check:test-typecheck: OK` (10 files / 72 errors / 23 pinned signatures held in the existing ledger, unchanged). - `eslint --no-inline-config` on the four changed source files: exit 0. `node scripts/check-nul-bytes.mjs`: OK. - Single files: `src/sign-in-method-floor.test.ts` 40/40, `src/direct-sign-in.test.ts` 87/87. </details> <details><summary>Ablations (one per fix; each mutation landed on disk via scripts/ablation-replace.mjs and was restored, blob equal to HEAD and git diff HEAD empty)</summary> - Delete door back to `config.emailPassword?.enabled !== false`: 2 failed / 38 (the composition delete under `off`, the judge case). - Boot report back to `config.emailPassword?.enabled !== false`: 2 failed / 38 (the composition boot under `off`, the judge case). - `errorCallbackURL` back to the bare `/login`: 1 failed / 87 (keeps the page's `?redirect=`). - The door's landing without the carried redirect: 1 failed / 87 (the rate-limited landing). The tests import `src/` directly (no `dist/` in the path), so no rebuild leg was needed. </details> <details><summary>Derived gate families (dispatch-gates --commands, 97 families)</summary> 97 run: 94 exit 0; 3 exit 3 `PREREQUISITE NOT MET`, read as NOT MEASURED and left to CI: `check:skill-examples` (no `packages/client-react/dist` in this worktree), `check:dual-build-cjs-loads` (several packages unbuilt), `check:type-check-debt` (its re-measure prerequisite). `dispatch-gates --ran`: 97 derived, 97 run, 0 UNRUN. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d1NJYFGVi2FRztyBNo)_ <!-- signed: domain:server#5 · os-elon-musk · session_016WV4d1NJYFGVi2FRztyBNo --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8d523b5 commit a27d88d

6 files changed

Lines changed: 318 additions & 22 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
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=`
6+
7+
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.
8+
Metadata-protocol: none
9+
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.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped. The moved answer is a runtime refusal at one auth door under a deployment switch, so there is nothing stored for a migration to rewrite and no tombstone. -->
12+
13+
**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`.
14+
15+
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.
16+
17+
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.
18+
19+
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.

‎content/docs/permissions/sso.mdx‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,17 @@ OAuth client's hand-off and when no provider can be started. It changes the
758758
form only: `POST /api/v1/auth/sign-in/email` still accepts a password, and the
759759
`/register` and `/forgot-password` pages are not changed by it.
760760

761+
Because the form then offers no email and password and no phone sign-in, two
762+
checks that keep a way to sign in do not count them under `off`, even while
763+
they are switched on: Setup's **Delete SSO Provider** on the last identity
764+
provider is refused `409 DELETE_RESTRICTED` with nothing deleted, and a boot
765+
with no identity provider reports at **error** under the grep token
766+
`no_sign_in_method_at_boot`. Recover by setting
767+
`OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden`, and
768+
`OS_AUTH_EMAIL_PASSWORD_ENABLED=true` too when email and password sign-in is
769+
off, then restarting. The auth settings save still counts email and password
770+
under `off`; that check is still open.
771+
761772
**What a visit does.** The Console sign-in page reads `features.directSignIn`
762773
from `GET /api/v1/auth/config`. That is `true` only while a provider can be
763774
started, and only when this server mounted the door: a setting turned on
@@ -772,7 +783,10 @@ no session itself.
772783
`//host`, a backslash, a control character (a tab or a newline included), or
773784
any of these behind percent-encoding is dropped, and the sign-in returns to
774785
the Console home page. The query takes `callbackURL` only, once. Anything else
775-
is refused **400 `VALIDATION_ERROR`**.
786+
is refused **400 `VALIDATION_ERROR`**. When the sign-in lands back on the
787+
sign-in page instead (the provider's error, or a start the door could not
788+
make), the page's own `?redirect=` comes with it, under the same same-origin
789+
rule.
776790

777791
**No loops.** The page shows itself, with a **Continue with single sign-on**
778792
button (and the reason, where there is one), instead of starting again when:

‎packages/plugins/plugin-auth/src/direct-sign-in.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,46 @@ describe('runDirectSignIn: the start door', () => {
276276
expect((host.logger!.warn as any).mock.calls[0][1]).toMatchObject({ reason: 'rate_limited' });
277277
});
278278

279+
// The page hands the door its own path and query; its `?redirect=` survives every landing back on `/login`.
280+
const PAGE_WITH_REDIRECT = `?callbackURL=${encodeURIComponent('/_console/login?redirect=%2Fapps%2Fcrm%3Fview%3Dall&direct=returned')}`;
281+
282+
it('hands the vendor a sign-in page error address that keeps the page\'s ?redirect=', async () => {
283+
const { host, dispatched } = fakeHost();
284+
await runDirectSignIn(door(PAGE_WITH_REDIRECT), host);
285+
expect(dispatched[0].body.errorCallbackURL).toBe(`${ORIGIN}/_console/login?redirect=%2Fapps%2Fcrm%3Fview%3Dall`);
286+
expect(new URL(dispatched[0].body.errorCallbackURL).searchParams.get('redirect')).toBe('/apps/crm?view=all');
287+
});
288+
289+
it('lands a rate-limited start on the sign-in page with the page\'s ?redirect= kept', async () => {
290+
const { host } = fakeHost({ dispatch: async () => new Response('{"message":"Too many requests"}', { status: 429 }) });
291+
const res = await runDirectSignIn(door(PAGE_WITH_REDIRECT), host);
292+
expect(res.status).toBe(302);
293+
const location = new URL(res.headers.get('location')!);
294+
expect(`${location.origin}${location.pathname}`).toBe(`${ORIGIN}/_console/login`);
295+
expect(location.searchParams.get('error')).toBe(DIRECT_SIGN_IN_RATE_LIMITED);
296+
expect(location.searchParams.get('redirect')).toBe('/apps/crm?view=all');
297+
});
298+
299+
it('CONTROL: with no ?redirect= on the page, both landings are the bare sign-in page as before', async () => {
300+
const plain = `?callbackURL=${encodeURIComponent('/_console/login?direct=returned')}`;
301+
const { host, dispatched } = fakeHost();
302+
await runDirectSignIn(door(plain), host);
303+
expect(dispatched[0].body.errorCallbackURL).toBe(`${ORIGIN}/_console/login`);
304+
const limited = fakeHost({ dispatch: async () => new Response('{}', { status: 429 }) });
305+
const res = await runDirectSignIn(door(plain), limited.host);
306+
expect(res.headers.get('location')).toBe(`${ORIGIN}/_console/login?error=${DIRECT_SIGN_IN_RATE_LIMITED}`);
307+
});
308+
309+
it.each(FOREIGN_RETURN_PATHS)('drops the foreign ?redirect= %j, the return path\'s own rule, and still lands on the page', async (foreign) => {
310+
const page = `/_console/login?redirect=${encodeURIComponent(foreign)}&direct=returned`;
311+
const { host, dispatched } = fakeHost();
312+
await runDirectSignIn(door(`?callbackURL=${encodeURIComponent(page)}`), host);
313+
expect(dispatched[0].body.errorCallbackURL).toBe(`${ORIGIN}/_console/login`);
314+
const limited = fakeHost({ dispatch: async () => new Response('{}', { status: 429 }) });
315+
const res = await runDirectSignIn(door(`?callbackURL=${encodeURIComponent(page)}`), limited.host);
316+
expect(res.headers.get('location')).toBe(`${ORIGIN}/_console/login?error=${DIRECT_SIGN_IN_RATE_LIMITED}`);
317+
});
318+
279319
it('lands on the sign-in page with an error, never a retry, when no provider resolves or the start is refused', async () => {
280320
const cases: Array<Partial<DirectSignInHost>> = [
281321
{ chooseProvider: async () => ({ miss: 'several_providers' }) },

‎packages/plugins/plugin-auth/src/direct-sign-in.ts‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,33 @@ export function keptReturnPath(raw: unknown): string | undefined {
211211
return raw;
212212
}
213213

214+
/**
215+
* The `redirect` the sign-in page was opened with, read from the kept return
216+
* path (the page hands the door its own path and query), so a landing back on
217+
* the page (the door's own error, or the identity provider's) still knows where
218+
* the person was going. Carried only when it is sent once and is itself a kept
219+
* return path ({@link keptReturnPath}); otherwise none.
220+
*/
221+
export function carriedRedirect(kept: string | undefined): string | undefined {
222+
if (kept === undefined) return undefined;
223+
let values: string[];
224+
try {
225+
values = new URL(kept, 'https://return-path.invalid').searchParams.getAll('redirect');
226+
} catch {
227+
return undefined;
228+
}
229+
return values.length === 1 ? keptReturnPath(values[0]) : undefined;
230+
}
231+
232+
/** The Console's `/login`, with the carried `redirect` and the `error` code, when there are any. */
233+
function signInPageUrl(host: DirectSignInHost, redirect: string | undefined, error?: string): string {
234+
const params = new URLSearchParams();
235+
if (error !== undefined) params.set('error', error);
236+
if (redirect !== undefined) params.set('redirect', redirect);
237+
const query = params.toString();
238+
return `${host.consolePageUrl('/login')}${query ? `?${query}` : ''}`;
239+
}
240+
214241
/** Which vendor start a provider takes. */
215242
export type DirectSignInProvider =
216243
| { kind: 'oauth'; providerId: string }
@@ -343,6 +370,8 @@ function queryOf(url: URL): Record<string, string[]> {
343370
* Console's `/login?error=direct_sign_in_unavailable`, and one `warn` line;
344371
* a start the vendor's rate limit refused (`429`) ⇒ the same, with
345372
* `error=direct_sign_in_rate_limited` and the reason `rate_limited`.
373+
* - Every landing on `/login`, the door's and the vendor's error return
374+
* address alike, carries the page's `?redirect=` ({@link carriedRedirect}).
346375
*
347376
* The caller mounts the door only while the setting is on; a call with it off
348377
* answers `404 RESOURCE_NOT_FOUND` like an unmounted route.
@@ -369,13 +398,18 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost):
369398
});
370399
}
371400

401+
const requested = url.searchParams.get('callbackURL');
402+
const kept = keptReturnPath(requested);
403+
// Every landing on the sign-in page keeps the page's own `?redirect=`.
404+
const redirectTo = carriedRedirect(kept);
405+
372406
const unavailable = (reason: DirectSignInMiss, providerId?: string): Response => {
373407
const text = `[auth] Direct sign-in not started: ${reason}. The sign-in page is shown instead.`;
374408
const meta = { entry: 'direct_sign_in', reason, ...(providerId ? { providerId } : {}) };
375409
if (host.logger) host.logger.warn(text, meta);
376410
else console.warn(text, meta);
377411
const code = reason === 'rate_limited' ? DIRECT_SIGN_IN_RATE_LIMITED : DIRECT_SIGN_IN_UNAVAILABLE;
378-
return redirect(`${host.consolePageUrl('/login')}?error=${code}`);
412+
return redirect(signInPageUrl(host, redirectTo, code));
379413
};
380414

381415
let chosen: DirectSignInProvider | { miss: DirectSignInProviderMiss };
@@ -386,8 +420,6 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost):
386420
}
387421
if ('miss' in chosen) return unavailable(chosen.miss);
388422

389-
const requested = url.searchParams.get('callbackURL');
390-
const kept = keptReturnPath(requested);
391423
if (requested !== null && kept === undefined) {
392424
host.logger?.debug?.('[auth] Direct sign-in: the return path is not a same-origin path and was dropped.', {
393425
entry: 'direct_sign_in',
@@ -397,7 +429,7 @@ export async function runDirectSignIn(request: Request, host: DirectSignInHost):
397429
const callbackURL = kept !== undefined ? `${origin}${kept}` : host.consolePageUrl('/');
398430
// Defence in depth: whatever was kept, the sign-in returns to this origin.
399431
if (new URL(callbackURL).origin !== new URL(origin).origin) return unavailable('start_refused');
400-
const errorCallbackURL = host.consolePageUrl('/login');
432+
const errorCallbackURL = signInPageUrl(host, redirectTo);
401433

402434
const body = chosen.kind === 'oauth'
403435
? { provider: chosen.providerId, callbackURL, errorCallbackURL, disableRedirect: true }

‎packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,9 @@ const PASSWORD = 'S3cure!Passw0rd-30300';
470470
const SYS = { isSystem: true } as const;
471471

472472
const ENV_KEYS_30300 = [
473+
'OS_AUTH_DIRECT_SIGN_IN_ENABLED',
474+
'OS_AUTH_DIRECT_SIGN_IN_PROVIDER',
475+
'OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH',
473476
'OS_AUTH_EMAIL_PASSWORD_ENABLED',
474477
'OS_AUTH_GOOGLE_ENABLED',
475478
'GOOGLE_CLIENT_ID',
@@ -550,8 +553,8 @@ describe('the last way to sign in is kept, and a boot without one is said (#3030
550553
// ── Door 1 ─────────────────────────────────────────────────────────────────
551554

552555
/** A signed-in administrator who owns `providers`, on a deployment with enterprise SSO switched on. */
553-
async function adminWithProviders(providers: string[]) {
554-
const env = await boot({ plugins: { sso: true } });
556+
async function adminWithProviders(providers: string[], authOptions: Record<string, unknown> = {}) {
557+
const env = await boot({ plugins: { sso: true }, ...authOptions });
555558
const { ql, manager } = env;
556559
const signedUp = await manager.handleRequest(
557560
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
651654
expect(await providerIds()).toEqual(['okta']);
652655
}, 30_000);
653656

657+
// The local sign-in path behind direct sign-in: under `off` the sign-in page
658+
// draws no email and password, so it is no way in there, on or not.
659+
660+
it('under the local sign-in path off, deleting the last provider is refused with email and password on: 409, nothing deleted', async () => {
661+
const { manager, remove, providerIds } = await adminWithProviders(['okta'], { directSignIn: { localSignIn: 'off' } });
662+
expect(manager.getPublicConfig().emailPassword.enabled).toBe(true);
663+
expect(manager.getPublicConfig().features.localSignIn).toBe('off');
664+
665+
const res = await remove('okta');
666+
const body = await res.json();
667+
expect(res.status, JSON.stringify(body)).toBe(409);
668+
expect(body).toMatchObject({
669+
code: 'DELETE_RESTRICTED',
670+
message: SIGN_IN_FLOOR_COPY.en.enterpriseSsoLocalOff,
671+
lastSignInMethod: 'enterprise_sso',
672+
});
673+
expect(await providerIds()).toEqual(['okta']);
674+
}, 30_000);
675+
676+
it('CONTROL: with the local sign-in path hidden (the page offers email and password), deleting the last provider goes through as before', async () => {
677+
const { manager, remove, providerIds } = await adminWithProviders(['okta'], { directSignIn: { localSignIn: 'hidden' } });
678+
expect(manager.getPublicConfig().features.localSignIn).toBe('hidden');
679+
680+
const res = await remove('okta');
681+
expect(res.status, await res.clone().text()).toBe(200);
682+
expect(await providerIds()).toEqual([]);
683+
}, 30_000);
684+
654685
// ── Door 2 ─────────────────────────────────────────────────────────────────
655686

687+
it('a boot under the local sign-in path off with no provider is said at error, email and password on or not', async () => {
688+
const { manager, reports } = await boot({ directSignIn: { localSignIn: 'off' } });
689+
expect(manager.getPublicConfig().emailPassword.enabled).toBe(true);
690+
expect(reports()).toHaveLength(1);
691+
expect(reports()[0]).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden');
692+
}, 30_000);
693+
694+
it('a boot under the local sign-in path off with email and password off too names both settings to recover', async () => {
695+
const { manager, reports } = await boot({ emailAndPassword: { enabled: false }, directSignIn: { localSignIn: 'off' } });
696+
expect(manager.getPublicConfig().emailPassword.enabled).toBe(false);
697+
expect(reports()).toHaveLength(1);
698+
expect(reports()[0]).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden and OS_AUTH_EMAIL_PASSWORD_ENABLED=true');
699+
}, 30_000);
700+
701+
it('CONTROL: the same boot with the local sign-in path hidden says nothing', async () => {
702+
const { reports } = await boot({ directSignIn: { localSignIn: 'hidden' } });
703+
expect(reports()).toEqual([]);
704+
}, 30_000);
705+
656706
it('a redeploy that drops the last provider while email and password is off is said at error, and still boots', async () => {
657707
const { manager, reports } = await boot({ emailAndPassword: { enabled: false } });
658708

@@ -746,6 +796,43 @@ describe('the floor judges a provider delete and a boot by what it can read (#30
746796
expect(await resolveNoSignInMethodReport(deps({ hostSignInHandoff: true }))).toBeNull();
747797
});
748798

799+
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 () => {
800+
const LOCAL_OFF: SignInMethodConfigView = {
801+
emailPassword: { enabled: true },
802+
socialProviders: [],
803+
features: { sso: true, phoneNumber: true, localSignIn: 'off' },
804+
};
805+
await expect(ssoProviderDeleteRefusal(deps({ config: LOCAL_OFF, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toEqual({
806+
status: 'CONFLICT',
807+
code: 'DELETE_RESTRICTED',
808+
message: SIGN_IN_FLOOR_COPY.en.enterpriseSsoLocalOff,
809+
lastSignInMethod: 'enterprise_sso',
810+
});
811+
expect(await resolveNoSignInMethodReport(deps({ config: LOCAL_OFF, rows: [] }))).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden');
812+
// CONTROL: the same deployment with the path hidden counts both as before.
813+
const HIDDEN: SignInMethodConfigView = { ...LOCAL_OFF, features: { ...LOCAL_OFF.features, localSignIn: 'hidden' } };
814+
await expect(ssoProviderDeleteRefusal(deps({ config: HIDDEN, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toBeUndefined();
815+
expect(await resolveNoSignInMethodReport(deps({ config: HIDDEN, rows: [] }))).toBeNull();
816+
const PHONE_ONLY: SignInMethodConfigView = { ...HIDDEN, emailPassword: { enabled: false } };
817+
await expect(ssoProviderDeleteRefusal(deps({ config: PHONE_ONLY, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toBeUndefined();
818+
// Phone sign-in alone under off, email and password off too: the page draws neither, so the delete is refused,
819+
// and the remedy is the local-path one (turning email and password back on alone draws nothing under off).
820+
const PHONE_ONLY_OFF: SignInMethodConfigView = { ...PHONE_ONLY, features: { ...PHONE_ONLY.features, localSignIn: 'off' } };
821+
await expect(ssoProviderDeleteRefusal(deps({ config: PHONE_ONLY_OFF, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toMatchObject({
822+
code: 'DELETE_RESTRICTED',
823+
message: SIGN_IN_FLOOR_COPY.en.enterpriseSsoLocalOff,
824+
});
825+
const report = await resolveNoSignInMethodReport(deps({ config: PHONE_ONLY_OFF, rows: [] }));
826+
expect(report).toContain('OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden and OS_AUTH_EMAIL_PASSWORD_ENABLED=true');
827+
expect(report).not.toContain('no phone-number sign-in');
828+
// CONTROL: email and password off with the page drawing local sign-in keeps the email-off copy and report.
829+
const EMAIL_OFF_HIDDEN: SignInMethodConfigView = { ...OFF, features: { sso: true, localSignIn: 'hidden' } };
830+
await expect(ssoProviderDeleteRefusal(deps({ config: EMAIL_OFF_HIDDEN, rows: [{ provider_id: 'okta' }] }), 'okta')).resolves.toMatchObject({
831+
message: SIGN_IN_FLOOR_COPY.en.enterpriseSso,
832+
});
833+
expect(await resolveNoSignInMethodReport(deps({ config: EMAIL_OFF_HIDDEN, rows: [] }))).toContain('OS_AUTH_EMAIL_PASSWORD_ENABLED=true and restart');
834+
});
835+
749836
it('says it once at error (warn on a sink without error), and never throws', async () => {
750837
const error = vi.fn();
751838
const warn = vi.fn();

0 commit comments

Comments
 (0)