Repository navigation
Expand file tree
/
Copy pathtwoFactorSignIn-29105.test.tsx
More file actions
314 lines (258 loc) · 13.3 KB
/
Copy pathtwoFactorSignIn-29105.test.tsx
File metadata and controls
314 lines (258 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* objectstack#29105 — a password sign-in for an account with two-factor
* sign-in on asks for the second factor in place.
*
* The server accepts the password and answers a challenge instead of a
* session. `LoginForm` used to drop that answer: the page stayed as it was,
* with no code field and no message, and the user could not get in at all.
* These run the real `AuthProvider` and `LoginForm` over a stub client whose
* `signIn` answers the challenge, as better-auth's `/sign-in/email` does.
*/
import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { AuthProvider } from '../AuthProvider';
import { LoginForm, type LoginFormProps } from '../LoginForm';
import { useAuth } from '../useAuth';
import type { AuthClient } from '../types';
const USER = { id: 'u1', name: 'Totp User', email: 'totp@example.com' };
function refusal(code: string, message: string) {
return Object.assign(new Error(message), { code });
}
function stubClient(overrides: Partial<AuthClient> = {}): AuthClient {
return {
signIn: vi.fn().mockResolvedValue({ twoFactor: { methods: ['totp'] } }),
verifySignInTwoFactor: vi.fn().mockResolvedValue({ user: USER, session: { token: 'session-token' } }),
signOut: vi.fn().mockResolvedValue(undefined),
getSession: vi.fn().mockResolvedValue(null),
getConfig: vi.fn().mockResolvedValue({}),
...overrides,
} as unknown as AuthClient;
}
/** Shows who the provider says is signed in, next to the form. */
function SignedInAs() {
const { user } = useAuth();
return <output data-testid="signed-in-as">{user?.email ?? ''}</output>;
}
function renderLogin(client: AuthClient, props: LoginFormProps = {}) {
return render(
<AuthProvider authUrl="/api/v1/auth" client={client}>
<LoginForm {...props} />
<SignedInAs />
</AuthProvider>,
);
}
async function submitPassword() {
fireEvent.change(await screen.findByLabelText('Email'), { target: { value: USER.email } });
fireEvent.change(screen.getByLabelText('Password'), { target: { value: 'correct horse' } });
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await screen.findByTestId('two-factor-challenge');
}
function enterCode(label: string, code: string) {
fireEvent.change(screen.getByLabelText(label), { target: { value: code } });
fireEvent.click(screen.getByRole('button', { name: 'Verify' }));
}
describe('LoginForm — two-factor sign-in (objectstack#29105)', () => {
it('asks for the authenticator code after the password, then signs the user in', async () => {
const client = stubClient();
const onSuccess = vi.fn();
renderLogin(client, { onSuccess });
await submitPassword();
// The password step is gone, nobody is signed in yet, and the host was not told it succeeded.
expect(screen.queryByLabelText('Password')).toBeNull();
expect(screen.getByTestId('signed-in-as').textContent).toBe('');
expect(onSuccess).not.toHaveBeenCalled();
// An authenticator shows "123 456"; the space is not part of the code.
enterCode('Authentication code', '123 456');
await waitFor(() => expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email));
expect(client.verifySignInTwoFactor).toHaveBeenCalledWith('123456', 'totp');
expect(onSuccess).toHaveBeenCalledTimes(1);
});
it('says a wrong code is wrong, in place, and lets the user try again', async () => {
const verify = vi
.fn()
.mockRejectedValueOnce(refusal('INVALID_CODE', 'Invalid code'))
.mockResolvedValueOnce({ user: USER, session: { token: 'session-token' } });
renderLogin(stubClient({ verifySignInTwoFactor: verify }), {
errorMessages: { INVALID_CODE: 'That code is not valid.' },
});
await submitPassword();
enterCode('Authentication code', '000000');
expect((await screen.findByRole('alert')).textContent).toContain('That code is not valid.');
expect(screen.getByTestId('two-factor-challenge')).toBeTruthy();
expect(screen.getByTestId('signed-in-as').textContent).toBe('');
enterCode('Authentication code', '654321');
await waitFor(() => expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email));
expect(verify).toHaveBeenLastCalledWith('654321', 'totp');
});
it('accepts a backup code instead of the authenticator code', async () => {
const client = stubClient();
renderLogin(client);
await submitPassword();
fireEvent.click(screen.getByRole('button', { name: 'Use a backup code instead' }));
enterCode('Backup code', ' abcde-fghij ');
await waitFor(() => expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email));
expect(client.verifySignInTwoFactor).toHaveBeenCalledWith('abcde-fghij', 'backup-code');
});
it('goes back to the password step on "Back to sign in"', async () => {
const client = stubClient();
renderLogin(client);
await submitPassword();
fireEvent.click(screen.getByRole('button', { name: 'Back to sign in' }));
expect(await screen.findByLabelText('Password')).toBeTruthy();
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
expect(client.verifySignInTwoFactor).not.toHaveBeenCalled();
});
it('returns to the password step with the reason when the server has dropped the challenge', async () => {
renderLogin(
stubClient({
verifySignInTwoFactor: vi
.fn()
.mockRejectedValue(refusal('TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE', 'Too many attempts.')),
}),
{ errorMessages: { TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: 'Sign in with your password again.' } },
);
await submitPassword();
enterCode('Authentication code', '111111');
expect(await screen.findByLabelText('Password')).toBeTruthy();
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
expect(screen.getByRole('alert').textContent).toContain('Sign in with your password again.');
});
it('offers only backup codes when the server lists no authenticator method', async () => {
renderLogin(stubClient({ signIn: vi.fn().mockResolvedValue({ twoFactor: { methods: [] } }) }));
await submitPassword();
expect(screen.getByLabelText('Backup code')).toBeTruthy();
expect(screen.queryByRole('button', { name: 'Use your authenticator app instead' })).toBeNull();
});
it('signs a user without two-factor sign-in straight in, as before', async () => {
const client = stubClient({
signIn: vi.fn().mockResolvedValue({ user: USER, session: { token: 'plain-token' } }),
});
const onSuccess = vi.fn();
renderLogin(client, { onSuccess });
fireEvent.change(await screen.findByLabelText('Email'), { target: { value: USER.email } });
fireEvent.change(screen.getByLabelText('Password'), { target: { value: 'pw' } });
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email);
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
expect(client.verifySignInTwoFactor).not.toHaveBeenCalled();
});
});
describe('LoginForm — two-factor sign-in by phone number and password (objectstack#32107)', () => {
const PHONE_ON = { features: { phoneNumber: true } };
async function submitPhonePassword(password = 'correct horse') {
fireEvent.change(await screen.findByLabelText('Email or phone number'), {
target: { value: '138 0013 8000' },
});
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));
}
it('asks for the code after the phone password, as on the email path, then signs the user in', async () => {
const client = stubClient({
getConfig: vi.fn().mockResolvedValue(PHONE_ON),
signInWithPhonePassword: vi.fn().mockResolvedValue({ twoFactor: { methods: ['totp'] } }),
});
const onSuccess = vi.fn();
renderLogin(client, { onSuccess });
await submitPhonePassword();
await screen.findByTestId('two-factor-challenge');
expect(client.signInWithPhonePassword).toHaveBeenCalledWith('13800138000', 'correct horse');
expect(client.signIn).not.toHaveBeenCalled();
expect(screen.queryByRole('alert')).toBeNull();
expect(screen.getByTestId('signed-in-as').textContent).toBe('');
expect(onSuccess).not.toHaveBeenCalled();
enterCode('Authentication code', '123456');
await waitFor(() => expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email));
expect(client.verifySignInTwoFactor).toHaveBeenCalledWith('123456', 'totp');
expect(onSuccess).toHaveBeenCalledTimes(1);
});
it('signs a phone account without two-factor sign-in straight in, as before', async () => {
const client = stubClient({
getConfig: vi.fn().mockResolvedValue(PHONE_ON),
signInWithPhonePassword: vi.fn().mockResolvedValue({ user: USER, session: { token: 'phone-token' } }),
});
const onSuccess = vi.fn();
renderLogin(client, { onSuccess });
await submitPhonePassword('pw');
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email);
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
});
it('still says a wrong phone password is wrong, and asks for no code', async () => {
const client = stubClient({
getConfig: vi.fn().mockResolvedValue(PHONE_ON),
signInWithPhonePassword: vi
.fn()
.mockRejectedValue(refusal('INVALID_PHONE_NUMBER_OR_PASSWORD', 'Invalid phone number or password.')),
});
renderLogin(client);
await submitPhonePassword('wrong');
expect((await screen.findByRole('alert')).textContent).toContain('Invalid phone number or password.');
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
expect(screen.getByLabelText('Password')).toBeTruthy();
});
});
describe('LoginForm — the phone-code sign-in continues to the two-factor prompt when the account has an enrolled second factor', () => {
const OTP_ON = { features: { phoneNumber: true, phoneNumberOtp: true } };
async function submitPhoneCode(code: string) {
fireEvent.click(await screen.findByRole('button', { name: 'Sign in with verification code' }));
fireEvent.change(await screen.findByLabelText('Phone number'), { target: { value: '+8613800138000' } });
fireEvent.click(screen.getByRole('button', { name: 'Get code' }));
await screen.findByRole('button', { name: /Resend in \d+s/ });
fireEvent.change(screen.getByLabelText('Verification code'), { target: { value: code } });
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));
}
it('shows the two-factor prompt after an accepted phone code, with no error, then signs the user in', async () => {
const client = stubClient({
getConfig: vi.fn().mockResolvedValue(OTP_ON),
sendPhoneOtp: vi.fn().mockResolvedValue(undefined),
signInWithPhoneOtp: vi.fn().mockResolvedValue({ twoFactor: { methods: ['totp'] } }),
});
const onSuccess = vi.fn();
renderLogin(client, { onSuccess });
await submitPhoneCode('123456');
await screen.findByTestId('two-factor-challenge');
expect(client.signInWithPhoneOtp).toHaveBeenCalledWith('+8613800138000', '123456');
expect(screen.queryByRole('alert')).toBeNull();
expect(screen.queryByLabelText('Verification code')).toBeNull();
expect(screen.getByTestId('signed-in-as').textContent).toBe('');
expect(onSuccess).not.toHaveBeenCalled();
enterCode('Authentication code', '654321');
await waitFor(() => expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email));
expect(client.verifySignInTwoFactor).toHaveBeenCalledWith('654321', 'totp');
expect(onSuccess).toHaveBeenCalledTimes(1);
});
it('CONTROL: signs a phone account with no enrolled second factor straight in, as before', async () => {
const client = stubClient({
getConfig: vi.fn().mockResolvedValue(OTP_ON),
sendPhoneOtp: vi.fn().mockResolvedValue(undefined),
signInWithPhoneOtp: vi.fn().mockResolvedValue({ user: USER, session: { token: 'otp-token' } }),
});
const onSuccess = vi.fn();
renderLogin(client, { onSuccess });
await submitPhoneCode('123456');
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
expect(screen.getByTestId('signed-in-as').textContent).toBe(USER.email);
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
});
it('CONTROL: a wrong phone code still shows the existing error, and asks for no second factor', async () => {
const client = stubClient({
getConfig: vi.fn().mockResolvedValue(OTP_ON),
sendPhoneOtp: vi.fn().mockResolvedValue(undefined),
signInWithPhoneOtp: vi.fn().mockRejectedValue(refusal('INVALID_OTP', 'Invalid OTP')),
});
renderLogin(client);
await submitPhoneCode('000000');
expect((await screen.findByRole('alert')).textContent).toContain('Invalid OTP');
expect(screen.queryByTestId('two-factor-challenge')).toBeNull();
expect(screen.getByLabelText('Verification code')).toBeTruthy();
});
});