@jsb188/auth-web 1.1.11 → 1.1.12

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.
@@ -6,6 +6,7 @@ import {
6
6
  useContinueWithGoogle,
7
7
  useContinueWithMicrosoft,
8
8
  } from '../hooks/use-oauth';
9
+ import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
9
10
 
10
11
  interface OAuthButtonProps {
11
12
  formPublicId?: string | null;
@@ -82,13 +83,14 @@ export const ContinueWithMicrosoft = (p: OAuthButtonProps) => {
82
83
 
83
84
  export const ContinueWithSso = (p: AuthMethodButtonProps) => {
84
85
  const { onClickButton } = p;
85
- return (
86
- <FullWidthButton
87
- onClick={onClickButton}
88
- preset="em"
89
- className="mb_sm"
90
- iconName="buildings-2-color"
91
- iconClassName="ft_md shift_up"
86
+ return (
87
+ <FullWidthButton
88
+ onClick={onClickButton}
89
+ preset="em"
90
+ className="mb_sm"
91
+ iconName={COMMON_ICON_NAMES.enterprise_signin}
92
+ iconClassName="ft_md shift_up"
93
+ tryColor
92
94
  >
93
95
  {i18n.t('auth.continue_with_sso')}
94
96
  </FullWidthButton>
@@ -1,16 +1,11 @@
1
1
  import { runWithAuthSessionBrowserLock } from '@jsb188/app/utils/authSession.ts';
2
+ import { clearGoogleAutoSignInSuppression } from '../utils/googleIdentity';
2
3
 
3
4
  /**
4
5
  * Types
5
6
  */
6
7
 
7
- export type AuthPageName =
8
- | 'signin'
9
- | 'signin_success'
10
- | 'signup'
11
- | 'signup_success'
12
- | 'reset_password'
13
- | 'welcome';
8
+ export type AuthPageName = 'signin' | 'signin_success' | 'signup' | 'signup_success' | 'reset_password' | 'welcome';
14
9
 
15
10
  export type OAuthSessionAuthenticationInput = {
16
11
  provider: 'GOOGLE' | 'MICROSOFT';
@@ -26,36 +21,67 @@ export type OAuthSessionAuthenticationResult = {
26
21
  error: any | null;
27
22
  };
28
23
 
24
+ export type AuthenticationSessionHydrationResult = {
25
+ auth: any | null;
26
+ error: any | null;
27
+ };
28
+
29
+ const DEFAULT_AUTH_ROUTES: Record<AuthPageName, string> = {
30
+ signin: '/auth/signin',
31
+ signin_success: '/auth/success',
32
+ signup: '/auth/signup',
33
+ signup_success: '/auth/signup-finished',
34
+ reset_password: '/auth/reset-password',
35
+ welcome: '/auth/welcome',
36
+ };
37
+
29
38
  /**
30
39
  * Helper; get route path
31
40
  */
32
41
 
33
- export function getAuthRoute(
34
- pageName: AuthPageName,
35
- authRoutesMap?: Record<AuthPageName, string>,
36
- queryStr?: string,
37
- ) {
38
- const defaultAuthRoutesMap: Record<AuthPageName, string> = {
39
- signin: '/auth/signin',
40
- signin_success: '/auth/success',
41
- signup: '/auth/signup',
42
- signup_success: '/auth/signup-finished',
43
- reset_password: '/auth/reset-password',
44
- welcome: '/auth/welcome',
42
+ export function getAuthRoute(pageName: AuthPageName, authRoutesMap?: Record<AuthPageName, string>, queryStr?: string) {
43
+ const pathname = authRoutesMap?.[pageName] || DEFAULT_AUTH_ROUTES[pageName] || 'auth';
44
+ return queryStr ? `${pathname}?${queryStr}` : pathname;
45
+ }
46
+
47
+ /*
48
+ * Encode one validated post-authentication destination for auth route links.
49
+ */
50
+ export function getAuthReturnQuery(returnTo?: string | null) {
51
+ return returnTo ? new URLSearchParams({ returnTo }).toString() : undefined;
52
+ }
53
+
54
+ /*
55
+ * Accept only a same-site public-form destination and extract its campaign id.
56
+ */
57
+ export function getPublicFormReturnContext(value?: string | null) {
58
+ const match = value?.match(/^\/form\/([A-Za-z0-9]+)$/);
59
+ return {
60
+ formPublicId: match?.[1] || null,
61
+ returnTo: match?.[0] || null,
45
62
  };
63
+ }
46
64
 
47
- const pathname =
48
- authRoutesMap?.[pageName] || defaultAuthRoutesMap[pageName] || 'auth';
49
- return queryStr ? `${pathname}?${queryStr}` : pathname;
65
+ /*
66
+ * Preserve only explicitly supported account-auth destinations. MCP consent is
67
+ * account authentication and must never acquire public-form respondent semantics.
68
+ */
69
+ export function getAuthReturnContext(value?: string | null) {
70
+ const publicForm = getPublicFormReturnContext(value);
71
+ if (publicForm.returnTo) return publicForm;
72
+ const consent = value?.match(
73
+ /^\/auth\/mcp-consent\?request=([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$/,
74
+ );
75
+ return {
76
+ formPublicId: null,
77
+ returnTo: consent ? `/auth/mcp-consent?request=${consent[1]}` : value === '/auth/mcp-connections' ? value : null,
78
+ };
50
79
  }
51
80
 
52
81
  /*
53
82
  * Post one login credential to the same-origin HttpOnly-cookie endpoint.
54
83
  */
55
- async function postSignInSessionCredential(
56
- name: 'bootstrapToken' | 'token',
57
- value: string,
58
- ): Promise<boolean> {
84
+ async function postSignInSessionCredential(name: 'bootstrapToken' | 'token', value: string): Promise<boolean> {
59
85
  try {
60
86
  const response = await fetch('/auth/session', {
61
87
  method: 'POST',
@@ -80,6 +106,7 @@ async function postSignInSessionCredential(
80
106
  */
81
107
  export async function authenticateOAuthSignInSession(
82
108
  input: OAuthSessionAuthenticationInput,
109
+ signal?: AbortSignal,
83
110
  ): Promise<OAuthSessionAuthenticationResult> {
84
111
  if (typeof fetch !== 'function') {
85
112
  return { auth: null, error: { errorCode: 'network_error' } };
@@ -87,18 +114,18 @@ export async function authenticateOAuthSignInSession(
87
114
 
88
115
  try {
89
116
  return await runWithAuthSessionBrowserLock(async () => {
117
+ signal?.throwIfAborted();
90
118
  const body = new URLSearchParams({
91
119
  provider: input.provider,
92
120
  managedSessionVersion: '1',
93
121
  ...(input.oauthToken ? { oauthToken: input.oauthToken } : {}),
94
122
  ...(input.idToken ? { idToken: input.idToken } : {}),
95
- ...(input.ssoConnectionId
96
- ? { ssoConnectionId: input.ssoConnectionId }
97
- : {}),
123
+ ...(input.ssoConnectionId ? { ssoConnectionId: input.ssoConnectionId } : {}),
98
124
  ...(input.formPublicId ? { formPublicId: input.formPublicId } : {}),
99
125
  ...(input.authenticateOnly ? { authenticateOnly: '1' } : {}),
100
126
  });
101
127
  const response = await fetch('/auth/session', {
128
+ signal,
102
129
  method: 'POST',
103
130
  credentials: 'same-origin',
104
131
  headers: {
@@ -113,6 +140,9 @@ export async function authenticateOAuthSignInSession(
113
140
  error: result?.error || { errorCode: 'network_error' },
114
141
  };
115
142
  }
143
+ if (input.provider === 'GOOGLE' && (result.auth?.account?.id || result.auth?.respondentToken)) {
144
+ clearGoogleAutoSignInSuppression();
145
+ }
116
146
  return { auth: result.auth || null, error: null };
117
147
  });
118
148
  } catch {
@@ -120,22 +150,49 @@ export async function authenticateOAuthSignInSession(
120
150
  }
121
151
  }
122
152
 
153
+ /*
154
+ * Rehydrate browser authentication from the shared HttpOnly managed-session
155
+ * cookie after a same-origin popup establishes it.
156
+ */
157
+ export async function hydrateAuthenticationSession(): Promise<AuthenticationSessionHydrationResult> {
158
+ if (typeof fetch !== 'function') {
159
+ return { auth: null, error: { errorCode: 'network_error' } };
160
+ }
161
+
162
+ try {
163
+ return await runWithAuthSessionBrowserLock(async () => {
164
+ const response = await fetch('/auth/session', {
165
+ method: 'POST',
166
+ credentials: 'same-origin',
167
+ headers: {
168
+ 'Content-Type': 'application/x-www-form-urlencoded',
169
+ },
170
+ body: new URLSearchParams({ hydrate: '1' }),
171
+ });
172
+ const result = await response.json().catch(() => null);
173
+ if (!response.ok || !result?.ok || !result.auth?.token) {
174
+ return {
175
+ auth: null,
176
+ error: result?.error || { errorCode: 'network_error' },
177
+ };
178
+ }
179
+ return { auth: result.auth, error: null };
180
+ });
181
+ } catch {
182
+ return { auth: null, error: { errorCode: 'network_error' } };
183
+ }
184
+ }
185
+
123
186
  /*
124
187
  * Persist an OAuth or phone login before navigating without a bearer-token query.
125
188
  */
126
- export async function persistSignInSession(
127
- token: string,
128
- bootstrapToken?: string | null,
129
- ): Promise<boolean> {
189
+ export async function persistSignInSession(token: string, bootstrapToken?: string | null): Promise<boolean> {
130
190
  if (typeof fetch !== 'function' || (!token && !bootstrapToken)) {
131
191
  return false;
132
192
  }
133
193
 
134
194
  return await runWithAuthSessionBrowserLock(async () => {
135
- if (
136
- bootstrapToken &&
137
- (await postSignInSessionCredential('bootstrapToken', bootstrapToken))
138
- ) {
195
+ if (bootstrapToken && (await postSignInSessionCredential('bootstrapToken', bootstrapToken))) {
139
196
  return true;
140
197
  }
141
198
  return token ? await postSignInSessionCredential('token', token) : false;
@@ -1,307 +1,177 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
- import {
3
- isPhone,
4
- isEmail,
5
- passwordStrength,
6
- } from '@jsb188/app/utils/string.ts';
2
+ import { defineForm } from '@jsb188/form/libs/defineForm';
3
+ import { rules } from '@jsb188/form/libs/rules';
4
+ import { z } from 'zod';
7
5
 
8
- /**
9
- * Types
10
- */
11
-
12
- interface SignInFormType {
13
- identifier?: string;
14
- password?: string;
15
- }
6
+ export type SignInFormValues = z.input<ReturnType<typeof makeSignInSchema>['schema']>;
16
7
 
17
- interface SignUpFormType {
18
- email: string;
19
- password: string;
20
- passwordRepeat: string;
21
- }
22
-
23
- interface SignInDataForSchema {
8
+ export interface SignInFormContext {
24
9
  hidePassword: boolean;
25
- lastIdentifier: string;
10
+ lastIdentifier?: string;
26
11
  }
27
12
 
28
- /**
29
- * Values for validation
30
- */
31
-
32
- const MIN_LEN_VALUES = {
33
- password: 8,
34
- description: 750,
35
- };
36
-
37
- /**
38
- * Rules for each field
39
- */
40
-
41
- const RULES = (function () {
42
- return {
43
- email: {
44
- for: 'email',
45
- rule: isEmail,
46
- error: (value: string) => ({
47
- message: i18n.t('error.msg_email_invalid', { value }),
48
- }),
49
- },
50
- password: {
51
- for: 'password',
52
- rule: (value: string) =>
53
- passwordStrength(value, MIN_LEN_VALUES.password).valid,
54
- error: (value: string) => {
55
- const {
56
- isLongEnough,
57
- hasLowercase,
58
- hasUppercase,
59
- hasDigit,
60
- hasSpecial,
61
- } = passwordStrength(value, MIN_LEN_VALUES.password);
62
- const errorMessages = [];
63
-
64
- if (!isLongEnough) {
65
- errorMessages.push(
66
- i18n.t('error.msg_password_too_short', {
67
- length: MIN_LEN_VALUES.password,
68
- }),
69
- );
70
- }
71
- if (!hasLowercase) {
72
- errorMessages.push(i18n.t('error.msg_password_lowercase'));
73
- }
74
- if (!hasUppercase) {
75
- errorMessages.push(i18n.t('error.msg_password_uppercase'));
76
- }
77
- if (!hasDigit) {
78
- errorMessages.push(i18n.t('error.msg_password_digit'));
79
- }
80
- if (!hasSpecial) {
81
- errorMessages.push(i18n.t('error.msg_password_special'));
82
- }
83
-
84
- return {
85
- message:
86
- errorMessages.length > 1
87
- ? i18n.t('error.msg_password_insecure')
88
- : errorMessages[0],
89
- };
90
- },
91
- },
92
- passwordRepeat: {
93
- for: 'passwordRepeat',
94
- rule: (value: string, formValues: Partial<SignUpFormType>) =>
95
- value === formValues.password,
96
- error: {
97
- message: i18n.t('error.msg_password_mismatch'),
98
- },
99
- },
100
- phone: {
101
- for: 'phone',
102
- rule: (value: string) => isPhone(value),
103
- error: (value: string) => ({
104
- message: i18n.t('error.msg_phone_invalid', { value }),
105
- }),
106
- },
107
- };
108
- })();
109
-
110
- /**
111
- * Schema; Change password
13
+ /*
14
+ * Define the current password and matching new password fields for account changes and token resets.
112
15
  */
113
-
114
- export const makeChangeAccountPasswordSchema = () => ({
115
- listData: [
116
- {
117
- __type: 'input',
118
- hidden: (dataForSchema?: SignInDataForSchema) =>
119
- !!dataForSchema?.hidePassword,
120
- item: {
121
- autoFocus: true,
122
- name: 'currentPassword',
16
+ export function makeChangeAccountPasswordSchema() {
17
+ return defineForm({
18
+ schema: z
19
+ .object({
20
+ currentPassword: z.string(),
21
+ password: rules.password(),
22
+ passwordRepeat: z.string(),
23
+ })
24
+ .superRefine(rules.matches('passwordRepeat', 'password')),
25
+ defaults: { currentPassword: '', password: '', passwordRepeat: '' },
26
+ fields: {
27
+ currentPassword: {
28
+ kind: 'input',
123
29
  type: 'password',
30
+ autoFocus: true,
124
31
  label: i18n.t('account.currentPassword'),
125
32
  placeholder: i18n.t('account.password_ph'),
126
- // info: 'whatever you want',
33
+ visibleWhen: ({ context }: { context?: Partial<SignInFormContext> }) => !context?.hidePassword,
127
34
  },
128
- },
129
- {
130
- __type: 'password',
131
- item: {
132
- name: 'password',
35
+ password: {
36
+ kind: 'password',
133
37
  type: 'password',
134
38
  label: i18n.t('account.newPassword'),
135
- // placeholder: ''
136
- // info: 'whatever you want',
137
39
  },
138
- },
139
- {
140
- __type: 'password',
141
- item: {
142
- name: 'passwordRepeat',
40
+ passwordRepeat: {
41
+ kind: 'password',
143
42
  type: 'password',
144
43
  label: i18n.t('account.newPasswordRepeat'),
145
44
  },
146
45
  },
147
- ],
148
- rules: [RULES.password],
149
- });
46
+ });
47
+ }
150
48
 
151
- /**
152
- * Schema; Assign a new password
49
+ /*
50
+ * Define a matching password pair when an account does not yet have a password.
153
51
  */
154
-
155
- export const makeAssignPasswordSchema = () => ({
156
- listData: [
157
- {
158
- __type: 'password',
159
- item: {
160
- name: 'password',
52
+ export function makeAssignPasswordSchema() {
53
+ return defineForm({
54
+ schema: z
55
+ .object({
56
+ password: rules.password(),
57
+ passwordRepeat: z.string(),
58
+ })
59
+ .superRefine(rules.matches('passwordRepeat', 'password')),
60
+ defaults: { password: '', passwordRepeat: '' },
61
+ fields: {
62
+ password: {
63
+ kind: 'password',
161
64
  type: 'password',
162
65
  label: i18n.t('account.password'),
163
66
  },
164
- },
165
- {
166
- __type: 'password',
167
- item: {
168
- name: 'passwordRepeat',
67
+ passwordRepeat: {
68
+ kind: 'password',
169
69
  type: 'password',
170
70
  label: i18n.t('account.passwordRepeat'),
171
71
  },
172
72
  },
173
- ],
174
- rules: [RULES.password],
175
- isButtonDisabled: (formValues: any) => {
176
- return !formValues?.password?.trim() || !formValues?.passwordRepeat?.trim();
177
- },
178
- });
73
+ canSubmit: ({ values }) => !!values.password.trim() && !!values.passwordRepeat.trim(),
74
+ });
75
+ }
179
76
 
180
- /**
181
- * Schema; sign in
77
+ /*
78
+ * Define identifier discovery and the password step without applying new-password rules to existing passwords.
182
79
  */
183
-
184
- export const makeSignInSchema = () => ({
185
- listData: [
186
- {
187
- __type: 'input',
188
- // Can't do this because disabling the input will make post form ignore this field
189
- // locked: ({ hidePassword, lastIdentifier }: SignInDataForSchema) => !hidePassword && !!lastIdentifier,
190
- item: {
191
- name: 'identifier',
80
+ export function makeSignInSchema() {
81
+ return defineForm({
82
+ schema: z.object({ identifier: z.string(), password: z.string() }),
83
+ defaults: { identifier: '', password: '' },
84
+ fields: {
85
+ identifier: {
86
+ kind: 'input',
87
+ // Keep the identifier enabled so native form POST includes it.
88
+ suppressHydrationWarning: true,
192
89
  allowClearIfLocked: true,
193
90
  label: i18n.t('auth.login_opts_main'),
194
91
  placeholder: i18n.t('account.email_ph'),
195
92
  },
196
- },
197
- {
198
- __type: 'password',
199
- hidden: (dataForSchema?: SignInDataForSchema) =>
200
- !!dataForSchema?.hidePassword,
201
- autoFocus: true,
202
- item: {
203
- name: 'password',
93
+ password: {
94
+ kind: 'password',
204
95
  type: 'password',
96
+ autoFocus: true,
97
+ suppressHydrationWarning: true,
205
98
  label: i18n.t('account.password'),
206
99
  placeholder: i18n.t('account.password_ph'),
100
+ visibleWhen: ({ context }: { context?: Partial<SignInFormContext> }) => !context?.hidePassword,
207
101
  },
208
102
  },
209
- ],
210
- isButtonDisabled: (formValues: SignInFormType) => {
211
- return !formValues?.identifier?.trim();
212
- },
213
- });
103
+ canSubmit: ({ values }) => !!values.identifier.trim(),
104
+ });
105
+ }
214
106
 
215
- /**
216
- * Schema; Sign up
107
+ /*
108
+ * Define the email sign-up fields and the shared password strength and confirmation rules.
217
109
  */
218
-
219
- export const makeSignUpSchema = () => ({
220
- listData: [
221
- {
222
- __type: 'input',
223
- item: {
224
- name: 'email',
110
+ export function makeSignUpSchema() {
111
+ return defineForm({
112
+ schema: z
113
+ .object({
114
+ email: rules.email(),
115
+ password: rules.password(),
116
+ passwordRepeat: z.string(),
117
+ })
118
+ .superRefine(rules.matches('passwordRepeat', 'password')),
119
+ defaults: { email: '', password: '', passwordRepeat: '' },
120
+ fields: {
121
+ email: {
122
+ kind: 'input',
225
123
  label: i18n.t('account.email'),
226
124
  placeholder: i18n.t('account.email_ph'),
227
125
  },
228
- },
229
- {
230
- __type: 'password',
231
- item: {
232
- name: 'password',
126
+ password: {
127
+ kind: 'password',
233
128
  type: 'password',
234
129
  label: i18n.t('account.password'),
235
130
  placeholder: i18n.t('account.password_ph'),
236
131
  },
237
- },
238
- {
239
- __type: 'password',
240
- item: {
241
- name: 'passwordRepeat',
132
+ passwordRepeat: {
133
+ kind: 'password',
242
134
  type: 'password',
243
135
  label: i18n.t('account.passwordRepeat'),
244
136
  placeholder: i18n.t('account.password_ph'),
245
137
  },
246
138
  },
247
- ],
248
- isButtonDisabled: (formValues: Partial<SignUpFormType>) => {
249
- const fields: (keyof SignUpFormType)[] = [
250
- 'email',
251
- 'password',
252
- 'passwordRepeat',
253
- ];
254
- return fields.some((s) => !formValues[s]?.trim());
255
- },
256
- rules: [RULES.email, RULES.password, RULES.passwordRepeat],
257
- });
258
-
259
- /**
260
- * Schema; Request a link to reset password
261
- */
262
-
263
- interface RequestTokenizedEmailObj {
264
- email: string;
139
+ canSubmit: ({ values }) => !!values.email.trim() && !!values.password.trim() && !!values.passwordRepeat.trim(),
140
+ });
265
141
  }
266
142
 
267
- export const makeRequestTokenizedEmailSchema = () => ({
268
- listData: [
269
- {
270
- __type: 'input',
271
- item: {
272
- name: 'email',
143
+ /*
144
+ * Define the email field shared by verification, recovery, and organization sign-in discovery.
145
+ */
146
+ export function makeRequestTokenizedEmailSchema() {
147
+ return defineForm({
148
+ schema: z.object({ email: rules.email() }),
149
+ defaults: { email: '' },
150
+ fields: {
151
+ email: {
152
+ kind: 'input',
273
153
  label: i18n.t('account.email'),
274
154
  placeholder: i18n.t('account.email_ph'),
275
155
  },
276
156
  },
277
- ],
278
- isButtonDisabled: (formValues: Partial<RequestTokenizedEmailObj>) => {
279
- return !formValues.email?.trim();
280
- },
281
- rules: [RULES.email],
282
- });
283
-
284
- /**
285
- * Schema; Send phone verification code
286
- */
287
-
288
- interface SendPhoneVerificationObj {
289
- phone: string;
157
+ canSubmit: ({ values }) => !!values.email.trim(),
158
+ });
290
159
  }
291
160
 
292
- export const makeSendPhoneVerificationSchema = () => ({
293
- listData: [
294
- {
295
- __type: 'input',
296
- item: {
297
- name: 'phone',
298
- label: i18n.t('form.phone_number'),
161
+ /*
162
+ * Define the phone field used to request a sign-in verification code.
163
+ */
164
+ export function makeSendPhoneVerificationSchema() {
165
+ return defineForm({
166
+ schema: z.object({ phone: rules.phone() }),
167
+ defaults: { phone: '' },
168
+ fields: {
169
+ phone: {
170
+ kind: 'input',
171
+ label: i18n.t('c.phone_number'),
299
172
  placeholder: i18n.t('account.phone_ph'),
300
173
  },
301
174
  },
302
- ],
303
- isButtonDisabled: (formValues: Partial<SendPhoneVerificationObj>) => {
304
- return !formValues.phone?.trim();
305
- },
306
- rules: [RULES.phone],
307
- });
175
+ canSubmit: ({ values }) => !!values.phone.trim(),
176
+ });
177
+ }