Skip to content

Commit 79a355b

Browse files
fix(auth): SSO sign-in keeps the safe pre-login redirect (#36778)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8VwKpuGTiLu4nqkGWLoyEMK)_ Fixes #36754 Clause-②: no Metadata-protocol: none ## 维护者速读 - 未登录的人打开一条记录链接,用工作邮箱走 SSO 登录后,现在回到那条记录;以前落到上次用的应用。 - 补齐登录体验:密码登录和第三方账号按钮早就会带人回原链接,只有邮箱 SSO 漏了。 - 只认本站内的链接,外站地址一律丢弃、照常落到默认应用;出错最多是落回默认应用,可直接撤回。 - 无。 ## What changes `LoginForm`'s "Sign in with SSO" (email-domain SSO, `POST /api/v1/auth/sign-in/sso`) built its `callbackURL` from the console base plus a fixed `/`, so the `?redirect=` the sign-in page carries was lost. It now: - with a **safe** `?redirect=` on the sign-in page, sends `callbackURL` = the sign-in page's own path with only that redirect (`/login?redirect=ENCODED`, or `/_console/login?redirect=ENCODED` under a mount). The identity provider returns the browser to the sign-in page, which finishes sign-in its own way (org auto-select, the mobile hand-off, the OAuth-provider replay) and then lands on the link through its own `isSafeRedirect`. This is the same return the provider buttons (`SocialSignInButtons`, default callback = the current page) and direct sign-in (`directSignInStartUrl`) already use; - with **no** redirect or an **unsafe** one, keeps `callbackURL` = base + `/` exactly as before (#36732). "Safe" is the console `LoginPage`'s own rule, byte for byte: starts with `/` and not `//`. It is not loosened, and the console page applies it again on the final hop. The predicate stays module-private (no new export). Only `redirect` travels, never the rest of the query (a previous attempt's `error` would otherwise come back with a successful sign-in). Why back to the sign-in page rather than straight to `base + redirect`: the mobile hand-off rules (`handoffRedirect.ts`, rule 2) say the hand-off route is never handed to a provider as its `callbackURL`; going through the sign-in page keeps that, and keeps the org auto-select step a direct landing would skip. ## Tests New `ui/packages/auth/src/__tests__/ssoCallbackRedirect-36754.test.tsx` (8 tests) drives the real form: sets the page URL, presses "Sign in with SSO", reads the request body. - safe redirect at `/login` returns to `/login?redirect=ENCODED`, and the redirect decodes back to the record path; - under `/_console/login` with `error` / `error_description` beside it: returns to `/_console/login?redirect=ENCODED`, nothing else carried; - dropped, callback `/`: absolute URL, protocol-relative `//host`, a non-root-relative path, an empty value; - unsafe redirect under the mount: callback `/_console/`; - CONTROL: no redirect gives `/` and `/_console/`, as before. <details><summary>Readings (head dcd0d78)</summary> - `pnpm exec vitest run packages/auth/src/__tests__/ssoCallbackRedirect-36754.test.tsx packages/auth/src/__tests__/LoginForm.test.tsx` (from `ui/`): Test Files 2 passed (2), Tests 46 passed (46). - `pnpm --filter @object-ui/auth type-check` then `pnpm exec vitest run packages/auth/`: exit 0, Test Files 49 passed (49), Tests 502 passed (502). - Ablation (fix committed first, `LoginForm.tsx` taken from `origin/main`, `ssoCallbackURL` count 0 on disk): the two carry tests turn red (`2 failed | 6 passed (8)`); the drop and control tests stay green, as expected, since main always drops. Restored with `git checkout HEAD --`, blob hash equal to HEAD's (`eaba863d`). - Local gates: `check-changeset-no-major`, `check-empty-changeset`, `check-adr-0087-registration` (all `--base origin/main`), `check:nul-bytes`, `check-sdui-manifest`: exit 0. `overlap-check`: VERDICT clean. Every other derived family is left to this PR's CI. </details> ## Acceptance notes - **Browser check: NOT MEASURED, no SSO provider locally.** Email-domain SSO needs a registered identity provider (`@better-auth/sso`), which a local dev stack does not have, so the browser leg is pinned by the test above, as the card allows. - better-auth accepts the new callback: its relative-path check (`isSafeRelativeURL`, better-auth 1.7.12) refuses protocol-relative values and encoded separators in the path; the redirect rides the query, percent-encoded by `encodeURIComponent`. - The package's other sign-in page, app-shell's exported `DefaultLoginPage`, has no in-repo user and does not honour `?redirect=` for any sign-in (its password success navigates to `/`). Through it, SSO now returns to that page like its provider buttons already do. Noted, not changed. ## Verification Read first: `ui/packages/auth/src/LoginForm.tsx` `ssoCallbackURL` (the only behaviour change), then the new test file. Two-minute check: from `ui/`, `pnpm exec vitest run packages/auth/src/__tests__/ssoCallbackRedirect-36754.test.tsx`: expect 8 passed. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbWcpizQKnJmTb6cTpa)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 38a0081 commit 79a355b

3 files changed

Lines changed: 145 additions & 5 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/auth': patch
3+
---
4+
5+
fix(auth): "Sign in with SSO" brings a signed-out person back to the link they opened
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A person who opened a record link while signed out is sent to the sign-in page, which remembers the link. Password and provider-button sign-in took them to it afterwards; signing in with SSO by work email took them to their last app instead. The SSO sign-in now comes back to the sign-in page with that link, the same way the provider buttons do, and the page then takes the person to it. Only a link inside this site is kept: a full web address or one pointing at another host is dropped, and the person lands where any sign-in does. With no link, nothing changes.

‎ui/packages/auth/src/LoginForm.tsx‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,33 @@ function refusalText(error: Error, errorMessages: Record<string, string> | undef
195195
const SSO_SIGN_IN_TIMEOUT_MS = 20_000;
196196
const SSO_SIGN_IN_TIMEOUT_TEXT = 'Sign-in timed out — the server did not respond. Please try again.';
197197

198+
/**
199+
* Where the identity provider sends the browser back after "Sign in with SSO".
200+
*
201+
* A sign-in page that carries a safe `?redirect=` (the link a signed-out
202+
* person opened) gets the browser back on itself with that redirect, the
203+
* return the provider buttons and direct sign-in already use: the host page
204+
* then finishes sign-in its own way and lands the person on the link
205+
* (objectstack#36754). Only the redirect travels, never the rest of the query
206+
* (a previous attempt's `error`, for one).
207+
*
208+
* Without one, or with an unsafe one, it is the console root, which lands the
209+
* person where any sign-in does: the last-used app, the declared default, the
210+
* first app (objectstack#36732).
211+
*
212+
* "Safe" is the console sign-in page's own post-login rule, unchanged: a
213+
* same-origin path, never an absolute or protocol-relative (`//host`) URL.
214+
* That page applies it again on the final hop.
215+
*/
216+
function ssoCallbackURL(): string {
217+
const { pathname, search } = window.location;
218+
const redirect = new URLSearchParams(search).get('redirect');
219+
if (redirect && redirect.startsWith('/') && !redirect.startsWith('//')) {
220+
return `${pathname}?redirect=${encodeURIComponent(redirect)}`;
221+
}
222+
return pathname.replace(/\/login(?:\/.*)?$/, '') + '/';
223+
}
224+
198225
const DefaultLink = ({ href, className, children }: AuthLinkComponentProps) => (
199226
<a href={href} className={className}>{children}</a>
200227
);
@@ -554,14 +581,10 @@ export function LoginForm({
554581
controller.abort();
555582
}, SSO_SIGN_IN_TIMEOUT_MS);
556583
try {
557-
const base = window.location.pathname.replace(/\/login(?:\/.*)?$/, '');
558-
// Back at the console root, which lands the person where any sign-in
559-
// does: the last-used app, the declared default, the first app
560-
// (objectstack#36732). The platform home page it named is retired.
561584
const res = await fetch('/api/v1/auth/sign-in/sso', {
562585
method: 'POST',
563586
headers: { 'content-type': 'application/json' },
564-
body: JSON.stringify({ email: identifier, callbackURL: base + '/' }),
587+
body: JSON.stringify({ email: identifier, callbackURL: ssoCallbackURL() }),
565588
credentials: 'include',
566589
signal: controller.signal,
567590
});
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#36754 — a signed-out person who opens a record link is sent to
11+
* the sign-in page with `?redirect=<record>`. Password and provider-button
12+
* sign-in brought them to the record; "Sign in with SSO" (by email domain)
13+
* sent the identity provider back to the console root, so they landed in
14+
* their last app instead.
15+
*
16+
* The SSO request's `callbackURL` now returns to the sign-in page itself with
17+
* that redirect when it is safe (a same-origin path, never an absolute or
18+
* protocol-relative URL: the console sign-in page's own rule), the return the
19+
* provider buttons already use; the page then finishes sign-in and lands the
20+
* person on the link. An unsafe redirect is dropped, and with none the
21+
* callback is the console root exactly as before.
22+
*/
23+
24+
import React from 'react';
25+
import { afterEach, describe, it, expect, vi } from 'vitest';
26+
import { cleanup, render, screen, waitFor, fireEvent } from '@testing-library/react';
27+
import { AuthProvider } from '../AuthProvider';
28+
import { LoginForm } from '../LoginForm';
29+
import type { AuthClient } from '../types';
30+
31+
const RECORD = '/apps/crm/account/acc_1?tab=contacts';
32+
33+
afterEach(() => {
34+
cleanup();
35+
vi.restoreAllMocks();
36+
window.history.replaceState(null, '', '/');
37+
});
38+
39+
function client(): AuthClient {
40+
return {
41+
signIn: vi.fn(),
42+
getSession: vi.fn().mockResolvedValue(null),
43+
getConfig: vi.fn().mockResolvedValue({ features: { sso: true } }),
44+
} as unknown as AuthClient;
45+
}
46+
47+
/** Open the sign-in page at `url`, press "Sign in with SSO", and read the request's callbackURL. */
48+
async function ssoCallbackFrom(url: string): Promise<string> {
49+
window.history.replaceState(null, '', url);
50+
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
51+
new Response(JSON.stringify({ message: 'No SSO provider is configured for this email domain.' }), {
52+
status: 404,
53+
headers: { 'content-type': 'application/json' },
54+
}),
55+
);
56+
render(
57+
<AuthProvider authUrl="/api/auth" client={client()}>
58+
<LoginForm />
59+
</AuthProvider>,
60+
);
61+
const button = await screen.findByRole('button', { name: 'Sign in with SSO' });
62+
fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'a@corp.example' } });
63+
fireEvent.click(button);
64+
await waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(1));
65+
expect(String(fetchSpy.mock.calls[0][0])).toBe('/api/v1/auth/sign-in/sso');
66+
return (JSON.parse(String(fetchSpy.mock.calls[0][1]?.body)) as { callbackURL: string }).callbackURL;
67+
}
68+
69+
describe('LoginForm — SSO keeps the pre-login link (objectstack#36754)', () => {
70+
it('returns to the sign-in page with a safe redirect', async () => {
71+
const callbackURL = await ssoCallbackFrom(`/login?redirect=${encodeURIComponent(RECORD)}`);
72+
expect(callbackURL).toBe(`/login?redirect=${encodeURIComponent(RECORD)}`);
73+
expect(new URL(callbackURL, 'https://host.example').searchParams.get('redirect')).toBe(RECORD);
74+
});
75+
76+
it('keeps the console mount and carries only the redirect, not the rest of the query', async () => {
77+
const callbackURL = await ssoCallbackFrom(
78+
`/_console/login?redirect=${encodeURIComponent(RECORD)}&error=state_mismatch&error_description=x`,
79+
);
80+
expect(callbackURL).toBe(`/_console/login?redirect=${encodeURIComponent(RECORD)}`);
81+
});
82+
83+
it.each([
84+
['an absolute URL', 'https://evil.example/phish'],
85+
['a protocol-relative URL', '//evil.example/phish'],
86+
['a relative path that is not root-relative', 'evil.example/phish'],
87+
['an empty value', ''],
88+
])('drops %s and returns to the console root', async (_label, redirect) => {
89+
const callbackURL = await ssoCallbackFrom(`/login?redirect=${encodeURIComponent(redirect)}`);
90+
expect(callbackURL).toBe('/');
91+
expect(callbackURL).not.toContain('evil.example');
92+
});
93+
94+
it('drops an unsafe redirect under the console mount, keeping the mount root', async () => {
95+
const callbackURL = await ssoCallbackFrom(
96+
`/_console/login?redirect=${encodeURIComponent('//evil.example/phish')}`,
97+
);
98+
expect(callbackURL).toBe('/_console/');
99+
});
100+
101+
it('CONTROL: with no redirect the callback is the console root, as before', async () => {
102+
expect(await ssoCallbackFrom('/login')).toBe('/');
103+
cleanup();
104+
vi.restoreAllMocks();
105+
expect(await ssoCallbackFrom('/_console/login')).toBe('/_console/');
106+
});
107+
});

0 commit comments

Comments
 (0)