|
| 1 | +/** |
| 2 | + * objectui#10893 — an invitee who registers from an invitation link must be |
| 3 | + * brought back to the invitation by the verification mail. |
| 4 | + * |
| 5 | + * The console kept `?redirect=/accept-invitation/ID` from the login page through |
| 6 | + * `/register` to `/verify-email-prompt`, but the verification mail is built |
| 7 | + * server-side from the sign-up request's `callbackURL`, which nothing sent: the |
| 8 | + * link read `callbackURL=/` and the invitee verified onto the workspace picker. |
| 9 | + * |
| 10 | + * Two console seams feed that value: |
| 11 | + * |
| 12 | + * - `RegisterPage` → `RegisterForm.verificationCallbackURL` → `signUp`'s 4th |
| 13 | + * argument (the first mail); |
| 14 | + * - `VerifyEmailPromptPage` → `sendVerificationEmail`'s 2nd argument (the |
| 15 | + * "Resend" mail), which forwarded the bare router path and so pointed at the |
| 16 | + * ORIGIN root, outside the console mount. |
| 17 | + * |
| 18 | + * Both must hand the server a ROOT-relative url inside the mount. The server |
| 19 | + * never sees `<base href>`; better-auth refuses a document-relative `./…` with |
| 20 | + * `403 INVALID_CALLBACK_URL`, failing the whole sign-up. So the embedded mount |
| 21 | + * (whose `withConsoleBase` answer is `./…`) is the case that matters most. |
| 22 | + * |
| 23 | + * Nothing in `@object-ui/auth` is replaced: a real `AuthProvider` over a real |
| 24 | + * `createAuthClient` runs against a stub server, and every assertion reads the |
| 25 | + * REQUEST BODY the server would receive — the value better-auth writes into the |
| 26 | + * mail's link. So the page, the shipped `RegisterForm`, `useAuth`, the provider |
| 27 | + * and the client are all on the path; dropping the value at any hop turns these |
| 28 | + * red. |
| 29 | + */ |
| 30 | + |
| 31 | +import '@testing-library/jest-dom/vitest'; |
| 32 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 33 | +import { render, screen, cleanup, waitFor } from '@testing-library/react'; |
| 34 | +import userEvent from '@testing-library/user-event'; |
| 35 | +import { BrowserRouter } from 'react-router-dom'; |
| 36 | +import { I18nProvider } from '@object-ui/i18n'; |
| 37 | +import { AuthProvider, createAuthClient } from '@object-ui/auth'; |
| 38 | + |
| 39 | +vi.mock('sonner', async (importOriginal) => { |
| 40 | + const actual = await importOriginal<Record<string, unknown>>(); |
| 41 | + return { ...actual, toast: { success: vi.fn(), error: vi.fn() } }; |
| 42 | +}); |
| 43 | + |
| 44 | +const { RegisterPage } = await import('../RegisterPage'); |
| 45 | +const { VerifyEmailPromptPage } = await import('../VerifyEmailPromptPage'); |
| 46 | + |
| 47 | +/** The three configurations the console ships in (see authExitBasename.test). */ |
| 48 | +const MOUNTS = { |
| 49 | + standalone: { href: null, baseUrl: '/', basename: '/', prefix: '' }, |
| 50 | + embedded: { href: '/_console/', baseUrl: './', basename: '/_console', prefix: '/_console' }, |
| 51 | + pinned: { href: '/_console/', baseUrl: '/_console/', basename: '/_console', prefix: '/_console' }, |
| 52 | +} as const; |
| 53 | +type MountName = keyof typeof MOUNTS; |
| 54 | + |
| 55 | +let baseEl: HTMLBaseElement | null = null; |
| 56 | + |
| 57 | +function mountConsole(name: MountName, at: string) { |
| 58 | + const mount = MOUNTS[name]; |
| 59 | + baseEl?.remove(); |
| 60 | + baseEl = null; |
| 61 | + if (mount.href) { |
| 62 | + baseEl = document.createElement('base'); |
| 63 | + baseEl.setAttribute('href', mount.href); |
| 64 | + document.head.appendChild(baseEl); |
| 65 | + } |
| 66 | + vi.stubEnv('BASE_URL', mount.baseUrl); |
| 67 | + window.history.replaceState({}, '', `${mount.prefix}${at}`); |
| 68 | + return mount; |
| 69 | +} |
| 70 | + |
| 71 | +const AUTH_URL = 'http://localhost/api/v1/auth'; |
| 72 | +type WireBodies = Record<'signUp' | 'resend', Array<Record<string, unknown>>>; |
| 73 | +let wire: WireBodies; |
| 74 | + |
| 75 | +/** |
| 76 | + * A signed-out visitor on a server that gates sign-in on email verification: |
| 77 | + * no session, `/sign-up/email` answers with a null token. |
| 78 | + */ |
| 79 | +function verificationGatedServer(): typeof fetch { |
| 80 | + wire = { signUp: [], resend: [] }; |
| 81 | + const json = (body: unknown) => |
| 82 | + new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }); |
| 83 | + return (async (input: string | URL | Request, init?: RequestInit) => { |
| 84 | + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; |
| 85 | + if (url.includes('/sign-up/email')) { |
| 86 | + wire.signUp.push(JSON.parse(String(init?.body))); |
| 87 | + return json({ user: { id: 'u_new', name: 'Wang Wei', email: 'wangwei@example.com' }, token: null }); |
| 88 | + } |
| 89 | + if (url.includes('/send-verification-email')) { |
| 90 | + wire.resend.push(JSON.parse(String(init?.body))); |
| 91 | + return json({ status: true }); |
| 92 | + } |
| 93 | + if (url.endsWith('/config')) return json({}); |
| 94 | + return json(null); |
| 95 | + }) as typeof fetch; |
| 96 | +} |
| 97 | + |
| 98 | +function renderAt(basename: string, ui: React.ReactElement) { |
| 99 | + const client = createAuthClient({ baseURL: AUTH_URL, fetchFn: verificationGatedServer() }); |
| 100 | + return render( |
| 101 | + <I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}> |
| 102 | + <AuthProvider authUrl={AUTH_URL} client={client}> |
| 103 | + <BrowserRouter basename={basename}>{ui}</BrowserRouter> |
| 104 | + </AuthProvider> |
| 105 | + </I18nProvider>, |
| 106 | + ); |
| 107 | +} |
| 108 | + |
| 109 | +/** What the server would be asked to redirect to after verification. */ |
| 110 | +async function signUpCallback(name: MountName, search: string): Promise<unknown> { |
| 111 | + const mount = mountConsole(name, `/register${search}`); |
| 112 | + renderAt(mount.basename, <RegisterPage />); |
| 113 | + |
| 114 | + await userEvent.type(await screen.findByLabelText('Name'), 'Wang Wei'); |
| 115 | + await userEvent.type(screen.getByLabelText('Email'), 'wangwei@example.com'); |
| 116 | + await userEvent.type(screen.getByLabelText('Password'), 'hunter2hunter2'); |
| 117 | + await userEvent.type(screen.getByLabelText('Confirm Password'), 'hunter2hunter2'); |
| 118 | + await userEvent.click(screen.getByRole('button', { name: 'Create Account' })); |
| 119 | + |
| 120 | + await waitFor(() => expect(wire.signUp).toHaveLength(1)); |
| 121 | + expect(wire.signUp[0]).toMatchObject({ name: 'Wang Wei', email: 'wangwei@example.com' }); |
| 122 | + return wire.signUp[0].callbackURL; |
| 123 | +} |
| 124 | + |
| 125 | +/** A url better-auth accepts as a callbackURL without a trusted-origin list. */ |
| 126 | +function isRootRelative(value: unknown): boolean { |
| 127 | + return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//'); |
| 128 | +} |
| 129 | + |
| 130 | +const INVITE = '?redirect=%2Faccept-invitation%2Finv_1'; |
| 131 | + |
| 132 | +beforeEach(() => { |
| 133 | + vi.spyOn(window.location, 'assign').mockImplementation(() => undefined); |
| 134 | + vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 135 | +}); |
| 136 | + |
| 137 | +afterEach(() => { |
| 138 | + cleanup(); |
| 139 | + baseEl?.remove(); |
| 140 | + baseEl = null; |
| 141 | + vi.unstubAllEnvs(); |
| 142 | + vi.restoreAllMocks(); |
| 143 | +}); |
| 144 | + |
| 145 | +describe('RegisterPage — the verification mail carries ?redirect= (objectui#10893)', () => { |
| 146 | + it('embedded console: the invitation, root-relative inside the mount', async () => { |
| 147 | + const callback = await signUpCallback('embedded', INVITE); |
| 148 | + expect(callback).toBe('/_console/accept-invitation/inv_1'); |
| 149 | + expect(isRootRelative(callback)).toBe(true); |
| 150 | + }); |
| 151 | + |
| 152 | + it('pinned-base console: the invitation, inside the mount', async () => { |
| 153 | + expect(await signUpCallback('pinned', INVITE)).toBe('/_console/accept-invitation/inv_1'); |
| 154 | + }); |
| 155 | + |
| 156 | + it('default `/` mount: the invitation route as-is', async () => { |
| 157 | + expect(await signUpCallback('standalone', INVITE)).toBe('/accept-invitation/inv_1'); |
| 158 | + }); |
| 159 | + |
| 160 | + it('no ?redirect=: no callbackURL on the wire, so the server default is untouched', async () => { |
| 161 | + expect(await signUpCallback('embedded', '')).toBeUndefined(); |
| 162 | + expect(Object.keys(wire.signUp[0])).not.toContain('callbackURL'); |
| 163 | + }); |
| 164 | + |
| 165 | + it('an off-site ?redirect= is not forwarded (the server would refuse it and fail sign-up)', async () => { |
| 166 | + expect(await signUpCallback('embedded', '?redirect=%2F%2Fevil.example%2Fx')).toBeUndefined(); |
| 167 | + }); |
| 168 | + |
| 169 | + it('still routes to the inbox prompt with the redirect kept', async () => { |
| 170 | + await signUpCallback('embedded', INVITE); |
| 171 | + await waitFor(() => expect(window.location.pathname).toBe('/_console/verify-email-prompt')); |
| 172 | + const sp = new URLSearchParams(window.location.search); |
| 173 | + expect(sp.get('email')).toBe('wangwei@example.com'); |
| 174 | + expect(sp.get('redirect')).toBe('/accept-invitation/inv_1'); |
| 175 | + }); |
| 176 | +}); |
| 177 | + |
| 178 | +describe('VerifyEmailPromptPage — the resent mail carries ?redirect= too (objectui#10893)', () => { |
| 179 | + async function resendCallback(name: MountName, search: string): Promise<[unknown, unknown]> { |
| 180 | + const mount = mountConsole(name, `/verify-email-prompt${search}`); |
| 181 | + renderAt(mount.basename, <VerifyEmailPromptPage />); |
| 182 | + await userEvent.click(await screen.findByRole('button', { name: /Resend verification email/ })); |
| 183 | + await waitFor(() => expect(wire.resend).toHaveLength(1)); |
| 184 | + return [wire.resend[0].email, wire.resend[0].callbackURL]; |
| 185 | + } |
| 186 | + |
| 187 | + it('embedded console: resolves the router path into the mount', async () => { |
| 188 | + const [email, callback] = await resendCallback('embedded', `?email=wangwei%40example.com&${INVITE.slice(1)}`); |
| 189 | + expect(email).toBe('wangwei@example.com'); |
| 190 | + // The pre-fix value was the bare router path '/accept-invitation/inv_1', |
| 191 | + // which the server redirected to at the ORIGIN root, outside `/_console`. |
| 192 | + expect(callback).toBe('/_console/accept-invitation/inv_1'); |
| 193 | + }); |
| 194 | + |
| 195 | + it('default `/` mount: the invitation route as-is', async () => { |
| 196 | + const [, callback] = await resendCallback('standalone', `?email=wangwei%40example.com&${INVITE.slice(1)}`); |
| 197 | + expect(callback).toBe('/accept-invitation/inv_1'); |
| 198 | + }); |
| 199 | + |
| 200 | + it('no ?redirect=: no callbackURL on the wire, so the server default applies', async () => { |
| 201 | + const [, callback] = await resendCallback('embedded', '?email=wangwei%40example.com'); |
| 202 | + expect(callback).toBeUndefined(); |
| 203 | + expect(Object.keys(wire.resend[0])).not.toContain('callbackURL'); |
| 204 | + }); |
| 205 | +}); |
0 commit comments