@proteinjs/user-ui 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/src/auth/AuthApi.d.ts +19 -2
  3. package/dist/src/auth/AuthApi.d.ts.map +1 -1
  4. package/dist/src/auth/AuthApi.js +51 -3
  5. package/dist/src/auth/AuthApi.js.map +1 -1
  6. package/dist/src/auth/AuthTextField.d.ts +9 -2
  7. package/dist/src/auth/AuthTextField.d.ts.map +1 -1
  8. package/dist/src/auth/AuthTextField.js +7 -4
  9. package/dist/src/auth/AuthTextField.js.map +1 -1
  10. package/dist/src/pages/ForgotPassword.d.ts.map +1 -1
  11. package/dist/src/pages/ForgotPassword.js +1 -1
  12. package/dist/src/pages/ForgotPassword.js.map +1 -1
  13. package/dist/src/pages/Login.d.ts.map +1 -1
  14. package/dist/src/pages/Login.js +1 -1
  15. package/dist/src/pages/Login.js.map +1 -1
  16. package/dist/src/pages/PasswordReset.d.ts.map +1 -1
  17. package/dist/src/pages/PasswordReset.js +15 -7
  18. package/dist/src/pages/PasswordReset.js.map +1 -1
  19. package/dist/src/pages/Signup.d.ts.map +1 -1
  20. package/dist/src/pages/Signup.js +37 -20
  21. package/dist/src/pages/Signup.js.map +1 -1
  22. package/dist/test/authApi.test.js +26 -5
  23. package/dist/test/authApi.test.js.map +1 -1
  24. package/dist/test/authPages.test.js +7 -2
  25. package/dist/test/authPages.test.js.map +1 -1
  26. package/dist/test/passwordResetAutofill.test.d.ts +5 -0
  27. package/dist/test/passwordResetAutofill.test.d.ts.map +1 -0
  28. package/dist/test/passwordResetAutofill.test.js +168 -0
  29. package/dist/test/passwordResetAutofill.test.js.map +1 -0
  30. package/dist/test/signupAutofill.test.d.ts +5 -0
  31. package/dist/test/signupAutofill.test.d.ts.map +1 -0
  32. package/dist/test/signupAutofill.test.js +196 -0
  33. package/dist/test/signupAutofill.test.js.map +1 -0
  34. package/package.json +4 -3
  35. package/src/auth/AuthApi.ts +33 -4
  36. package/src/auth/AuthTextField.tsx +16 -6
  37. package/src/pages/ForgotPassword.tsx +3 -1
  38. package/src/pages/Login.tsx +3 -1
  39. package/src/pages/PasswordReset.tsx +12 -2
  40. package/src/pages/Signup.tsx +25 -10
  41. package/test/authApi.test.ts +19 -5
  42. package/test/authPages.test.tsx +7 -2
  43. package/test/passwordResetAutofill.test.tsx +92 -0
  44. package/test/signupAutofill.test.tsx +115 -0
@@ -3,13 +3,13 @@ import { Skeleton, Stack } from '@mui/material';
3
3
  import { Page } from '@proteinjs/ui';
4
4
  import { getSignupService, uiRoutes } from '@proteinjs/user';
5
5
  import { Helmet } from 'react-helmet';
6
- import { useNavigate } from 'react-router-dom';
7
6
  import { AuthLayout } from '../auth/AuthLayout';
8
7
  import { AuthTextField } from '../auth/AuthTextField';
9
8
  import { AuthButton } from '../auth/AuthButton';
10
9
  import { AuthFormError } from '../auth/AuthFormError';
11
10
  import { AuthMessagePanel } from '../auth/AuthMessagePanel';
12
11
  import { AuthValidation } from '../auth/AuthValidation';
12
+ import { AuthApi } from '../auth/AuthApi';
13
13
 
14
14
  function inviteTokenFromUrl(): string {
15
15
  if (typeof window === 'undefined') {
@@ -20,12 +20,12 @@ function inviteTokenFromUrl(): string {
20
20
  }
21
21
 
22
22
  const SignupComponent: React.FC = () => {
23
- const navigate = useNavigate();
24
23
  const [token] = useState(inviteTokenFromUrl);
25
24
  const [initializing, setInitializing] = useState(true);
26
25
  const [initializationError, setInitializationError] = useState<string | null>(null);
27
26
  const [name, setName] = useState('');
28
27
  const [email, setEmail] = useState('');
28
+ const [inviteEmail, setInviteEmail] = useState('');
29
29
  const [password, setPassword] = useState('');
30
30
  const [confirmPassword, setConfirmPassword] = useState('');
31
31
  const [error, setError] = useState<string | undefined>();
@@ -36,8 +36,13 @@ const SignupComponent: React.FC = () => {
36
36
  getSignupService()
37
37
  .initializeSignup(token || undefined)
38
38
  .then((response) => {
39
- if (active && !response.isReady && response.error) {
39
+ if (!active) {
40
+ return;
41
+ }
42
+ if (!response.isReady && response.error) {
40
43
  setInitializationError(response.error);
44
+ } else if (response.invite) {
45
+ setInviteEmail(response.invite.email);
41
46
  }
42
47
  })
43
48
  .catch(() => {
@@ -66,15 +71,18 @@ const SignupComponent: React.FC = () => {
66
71
  setError(undefined);
67
72
  setBusy(true);
68
73
  try {
69
- // invited users don't enter an email (the invite token carries it)
70
- await getSignupService().createUser({ name, email: token ? undefined : email.trim(), password }, token);
71
- } catch {
72
- setError('Sign up failed.');
74
+ // invited users don't enter an email (the invite token carries it); the request also
75
+ // establishes the session (auto-login)
76
+ await new AuthApi().signup({ name, email: token ? undefined : email.trim(), password }, token || undefined);
77
+ } catch (error: any) {
78
+ setError(error.message);
73
79
  setBusy(false);
74
80
  return;
75
81
  }
76
82
 
77
- navigate(uiRoutes.auth.login.startsWith('/') ? uiRoutes.auth.login : '/' + uiRoutes.auth.login);
83
+ // Full navigation, not a router transition: the fresh page load renders under the
84
+ // just-established session, landing the new user in the app — never on the login form.
85
+ window.location.href = '/';
78
86
  };
79
87
 
80
88
  if (initializing) {
@@ -109,13 +117,20 @@ const SignupComponent: React.FC = () => {
109
117
  <AuthLayout title='Create your account'>
110
118
  <form onSubmit={onSubmit} noValidate>
111
119
  <AuthTextField label='Name' value={name} onChange={setName} autoComplete='name' disabled={busy} />
112
- {!token && (
120
+ {token ? (
121
+ // The invite fixes the email; render it read-only, tagged as the username. Without
122
+ // an email field here, password managers captured the NAME field as the saved
123
+ // credential's username — which then autofilled the login email field and failed.
124
+ <AuthTextField label='Email' value={inviteEmail} type='email' autoComplete='username' readOnly />
125
+ ) : (
126
+ // 'username' (not 'email'): this is the credential identifier password managers
127
+ // save and fill; type='email' still gives the email keyboard.
113
128
  <AuthTextField
114
129
  label='Email'
115
130
  value={email}
116
131
  onChange={setEmail}
117
132
  type='email'
118
- autoComplete='email'
133
+ autoComplete='username'
119
134
  disabled={busy}
120
135
  />
121
136
  )}
@@ -61,14 +61,28 @@ describe('AuthApi.initiatePasswordReset', () => {
61
61
  });
62
62
 
63
63
  describe('AuthApi.validateResetToken', () => {
64
- it('returns undefined for a valid token', async () => {
65
- mockFetch({ body: { isValid: true } });
66
- await expect(new AuthApi().validateResetToken('tok')).resolves.toBeUndefined();
64
+ it('resolves valid WITH the account email the reset is for (the form renders it as the identifier)', async () => {
65
+ mockFetch({ body: { isValid: true, email: 'ada@example.com' } });
66
+ await expect(new AuthApi().validateResetToken('tok')).resolves.toEqual({
67
+ valid: true,
68
+ email: 'ada@example.com',
69
+ });
67
70
  });
68
71
 
69
- it('returns the server message for an invalid token', async () => {
72
+ it('resolves invalid with the server message', async () => {
70
73
  mockFetch({ body: { isValid: false, message: 'Token expired' } });
71
- await expect(new AuthApi().validateResetToken('tok')).resolves.toBe('Token expired');
74
+ await expect(new AuthApi().validateResetToken('tok')).resolves.toEqual({
75
+ valid: false,
76
+ message: 'Token expired',
77
+ });
78
+ });
79
+
80
+ it('falls back to a generic message when the server sends none', async () => {
81
+ mockFetch({ body: { isValid: false } });
82
+ await expect(new AuthApi().validateResetToken('tok')).resolves.toEqual({
83
+ valid: false,
84
+ message: 'Invalid or expired token',
85
+ });
72
86
  });
73
87
  });
74
88
 
@@ -21,8 +21,11 @@ describe('auth pages', () => {
21
21
  // Real submit semantics: Enter submits the form.
22
22
  expect(html).toContain('type="submit"');
23
23
  // Mobile keyboards + autofill: proper autocomplete tokens (HTML attribute names are
24
- // case-insensitive; SSR emits the camelCase form).
25
- expect(html.toLowerCase()).toContain('autocomplete="email"');
24
+ // case-insensitive; SSR emits the camelCase form). The identifier field is tagged
25
+ // `username` — the token password managers fill from the stored credential — while
26
+ // type="email" keeps the email keyboard.
27
+ expect(html.toLowerCase()).toContain('autocomplete="username"');
28
+ expect(html.toLowerCase()).toContain('type="email"');
26
29
  expect(html.toLowerCase()).toContain('autocomplete="current-password"');
27
30
  });
28
31
 
@@ -32,6 +35,8 @@ describe('auth pages', () => {
32
35
  expect(html).toContain('Reset your password');
33
36
  expect(html).toContain('Send reset link');
34
37
  expect(html).toContain('href="/login"');
38
+ // Same identifier token as login, so the password manager fills the stored username here.
39
+ expect(html.toLowerCase()).toContain('autocomplete="username"');
35
40
  });
36
41
 
37
42
  it('password reset without a token renders the invalid-link state, never the form', () => {
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ * @jest-environment-options {"customExportConditions": ["node", "node-addons"]}
4
+ *
5
+ * Password-manager capture semantics on the password-reset form, through the real page
6
+ * component (token-validation effect included — global `fetch` is the only mock).
7
+ *
8
+ * The bug these tests pin down: the reset form rendered only the two password fields — no
9
+ * identifier at all — so password managers had nothing to associate the updated password
10
+ * with. The stored credential kept its OLD password while the account moved to the new one.
11
+ * The fix renders the account email (returned by token validation; the server knows it from
12
+ * the token's user row) as a read-only field tagged `autocomplete="username"` — read-only
13
+ * rather than disabled because password managers ignore disabled inputs.
14
+ */
15
+ import React from 'react';
16
+ import { createRoot, Root } from 'react-dom/client';
17
+ import { act } from 'react-dom/test-utils';
18
+ import { passwordResetPage } from '../src/pages/PasswordReset';
19
+
20
+ declare global {
21
+ // eslint-disable-next-line no-var
22
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
23
+ }
24
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
25
+
26
+ const ACCOUNT_EMAIL = 'ada@example.com';
27
+
28
+ let container: HTMLDivElement;
29
+ let root: Root;
30
+
31
+ beforeEach(() => {
32
+ container = document.createElement('div');
33
+ document.body.appendChild(container);
34
+ root = createRoot(container);
35
+ });
36
+
37
+ afterEach(async () => {
38
+ await act(async () => root.unmount());
39
+ container.remove();
40
+ delete (global as any).fetch;
41
+ });
42
+
43
+ function mockValidateResponse(body: unknown) {
44
+ (global as any).fetch = jest.fn().mockResolvedValue({
45
+ status: 200,
46
+ statusText: 'OK',
47
+ json: async () => body,
48
+ });
49
+ }
50
+
51
+ async function renderPasswordReset(url: string) {
52
+ window.history.replaceState({}, '', url);
53
+ const PasswordReset = passwordResetPage.component;
54
+ await act(async () => {
55
+ root.render(<PasswordReset urlParams={{}} />);
56
+ });
57
+ }
58
+
59
+ function field(label: string): HTMLInputElement {
60
+ const input = document.getElementById(`auth-field-${label}`);
61
+ expect(input).not.toBeNull();
62
+ return input as HTMLInputElement;
63
+ }
64
+
65
+ describe('password reset form', () => {
66
+ it('renders the account email as a read-only username field (password-manager capture target)', async () => {
67
+ mockValidateResponse({ isValid: true, email: ACCOUNT_EMAIL });
68
+ await renderPasswordReset('/login/reset-password?token=reset-token-1');
69
+
70
+ const email = field('Email');
71
+ expect(email.value).toBe(ACCOUNT_EMAIL);
72
+ expect(email.readOnly).toBe(true);
73
+ expect(email.getAttribute('autocomplete')).toBe('username');
74
+ });
75
+
76
+ it('tags both password fields new-password so managers offer to update the credential', async () => {
77
+ mockValidateResponse({ isValid: true, email: ACCOUNT_EMAIL });
78
+ await renderPasswordReset('/login/reset-password?token=reset-token-1');
79
+
80
+ expect(field('New password').getAttribute('autocomplete')).toBe('new-password');
81
+ expect(field('Confirm new password').getAttribute('autocomplete')).toBe('new-password');
82
+ });
83
+
84
+ it('an invalid token renders the invalid-link state — no form, no email field', async () => {
85
+ mockValidateResponse({ isValid: false, message: 'Token has expired' });
86
+ await renderPasswordReset('/login/reset-password?token=dead-token');
87
+
88
+ expect(document.body.textContent).toContain('This reset link is invalid');
89
+ expect(document.getElementById('auth-field-Email')).toBeNull();
90
+ expect(document.getElementById('auth-field-New password')).toBeNull();
91
+ });
92
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ * @jest-environment-options {"customExportConditions": ["node", "node-addons"]}
4
+ *
5
+ * Password-manager capture semantics on the signup form, through the real page component
6
+ * (initialization effect included — `getSignupService` is the only mock).
7
+ *
8
+ * The bug these tests pin down: the invite path rendered NO email field, so browser password
9
+ * managers captured the closest text input — the NAME field — as the credential's username.
10
+ * The stored "Brent Test" credential then autofilled the login email field, producing
11
+ * "User name or password incorrect" against a perfectly valid password. The fix renders the
12
+ * invite's email (returned by `initializeSignup`, previously discarded) as a read-only field
13
+ * tagged `autocomplete="username"` — read-only rather than disabled because password managers
14
+ * ignore disabled inputs, which would recreate the bug.
15
+ */
16
+ import React from 'react';
17
+ import { createRoot, Root } from 'react-dom/client';
18
+ import { act } from 'react-dom/test-utils';
19
+ import type { InitializeSignupResponse } from '@proteinjs/user';
20
+ import { signupPage } from '../src/pages/Signup';
21
+
22
+ declare global {
23
+ // eslint-disable-next-line no-var
24
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
25
+ }
26
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
27
+
28
+ const initializeSignup = jest.fn<Promise<InitializeSignupResponse>, [string | undefined]>();
29
+
30
+ jest.mock('@proteinjs/user', () => ({
31
+ ...jest.requireActual('@proteinjs/user'),
32
+ getSignupService: () => ({ initializeSignup }),
33
+ }));
34
+
35
+ const INVITE_EMAIL = 'ada@example.com';
36
+
37
+ let container: HTMLDivElement;
38
+ let root: Root;
39
+
40
+ beforeEach(() => {
41
+ initializeSignup.mockReset();
42
+ container = document.createElement('div');
43
+ document.body.appendChild(container);
44
+ root = createRoot(container);
45
+ });
46
+
47
+ afterEach(async () => {
48
+ await act(async () => root.unmount());
49
+ container.remove();
50
+ });
51
+
52
+ async function renderSignup(url: string) {
53
+ window.history.replaceState({}, '', url);
54
+ const Signup = signupPage.component;
55
+ await act(async () => {
56
+ root.render(<Signup urlParams={{}} />);
57
+ });
58
+ }
59
+
60
+ function field(label: string): HTMLInputElement {
61
+ const input = document.getElementById(`auth-field-${label}`);
62
+ expect(input).not.toBeNull();
63
+ return input as HTMLInputElement;
64
+ }
65
+
66
+ describe('invited signup', () => {
67
+ beforeEach(() => {
68
+ initializeSignup.mockResolvedValue({
69
+ isReady: true,
70
+ isInviteOnly: true,
71
+ invite: { email: INVITE_EMAIL } as InitializeSignupResponse['invite'],
72
+ });
73
+ });
74
+
75
+ it('renders the invite email as a read-only username field (password-manager capture target)', async () => {
76
+ await renderSignup('/signup?token=invite-token-1');
77
+ expect(initializeSignup).toHaveBeenCalledWith('invite-token-1');
78
+
79
+ const email = field('Email');
80
+ expect(email.value).toBe(INVITE_EMAIL);
81
+ expect(email.readOnly).toBe(true);
82
+ expect(email.getAttribute('autocomplete')).toBe('username');
83
+ });
84
+
85
+ it('keeps the name field out of credential capture (autocomplete name, never username)', async () => {
86
+ await renderSignup('/signup?token=invite-token-1');
87
+
88
+ const name = field('Name');
89
+ expect(name.readOnly).toBe(false);
90
+ expect(name.getAttribute('autocomplete')).toBe('name');
91
+ });
92
+
93
+ it('tags both password fields new-password so managers offer to save the credential', async () => {
94
+ await renderSignup('/signup?token=invite-token-1');
95
+
96
+ expect(field('Password').getAttribute('autocomplete')).toBe('new-password');
97
+ expect(field('Confirm password').getAttribute('autocomplete')).toBe('new-password');
98
+ });
99
+ });
100
+
101
+ describe('plain signup', () => {
102
+ beforeEach(() => {
103
+ initializeSignup.mockResolvedValue({ isReady: true, isInviteOnly: false });
104
+ });
105
+
106
+ it('renders an editable email field tagged as the username', async () => {
107
+ await renderSignup('/signup');
108
+ expect(initializeSignup).toHaveBeenCalledWith(undefined);
109
+
110
+ const email = field('Email');
111
+ expect(email.readOnly).toBe(false);
112
+ expect(email.getAttribute('autocomplete')).toBe('username');
113
+ expect(field('Name').getAttribute('autocomplete')).toBe('name');
114
+ });
115
+ });