@jsb188/auth-web 1.1.3 → 1.1.11

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.
@@ -0,0 +1,143 @@
1
+ import { runWithAuthSessionBrowserLock } from '@jsb188/app/utils/authSession.ts';
2
+
3
+ /**
4
+ * Types
5
+ */
6
+
7
+ export type AuthPageName =
8
+ | 'signin'
9
+ | 'signin_success'
10
+ | 'signup'
11
+ | 'signup_success'
12
+ | 'reset_password'
13
+ | 'welcome';
14
+
15
+ export type OAuthSessionAuthenticationInput = {
16
+ provider: 'GOOGLE' | 'MICROSOFT';
17
+ oauthToken?: string | null;
18
+ idToken?: string | null;
19
+ ssoConnectionId?: string | null;
20
+ formPublicId?: string | null;
21
+ authenticateOnly?: boolean;
22
+ };
23
+
24
+ export type OAuthSessionAuthenticationResult = {
25
+ auth: any | null;
26
+ error: any | null;
27
+ };
28
+
29
+ /**
30
+ * Helper; get route path
31
+ */
32
+
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',
45
+ };
46
+
47
+ const pathname =
48
+ authRoutesMap?.[pageName] || defaultAuthRoutesMap[pageName] || 'auth';
49
+ return queryStr ? `${pathname}?${queryStr}` : pathname;
50
+ }
51
+
52
+ /*
53
+ * Post one login credential to the same-origin HttpOnly-cookie endpoint.
54
+ */
55
+ async function postSignInSessionCredential(
56
+ name: 'bootstrapToken' | 'token',
57
+ value: string,
58
+ ): Promise<boolean> {
59
+ try {
60
+ const response = await fetch('/auth/session', {
61
+ method: 'POST',
62
+ credentials: 'same-origin',
63
+ headers: {
64
+ 'Content-Type': 'application/x-www-form-urlencoded',
65
+ },
66
+ body: new URLSearchParams({
67
+ [name]: value,
68
+ managedSessionVersion: '1',
69
+ }),
70
+ });
71
+ return response.ok;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ /*
78
+ * Authenticate one OAuth provider credential through the same-origin BFF and
79
+ * atomically persist the resulting HttpOnly managed-session cookie.
80
+ */
81
+ export async function authenticateOAuthSignInSession(
82
+ input: OAuthSessionAuthenticationInput,
83
+ ): Promise<OAuthSessionAuthenticationResult> {
84
+ if (typeof fetch !== 'function') {
85
+ return { auth: null, error: { errorCode: 'network_error' } };
86
+ }
87
+
88
+ try {
89
+ return await runWithAuthSessionBrowserLock(async () => {
90
+ const body = new URLSearchParams({
91
+ provider: input.provider,
92
+ managedSessionVersion: '1',
93
+ ...(input.oauthToken ? { oauthToken: input.oauthToken } : {}),
94
+ ...(input.idToken ? { idToken: input.idToken } : {}),
95
+ ...(input.ssoConnectionId
96
+ ? { ssoConnectionId: input.ssoConnectionId }
97
+ : {}),
98
+ ...(input.formPublicId ? { formPublicId: input.formPublicId } : {}),
99
+ ...(input.authenticateOnly ? { authenticateOnly: '1' } : {}),
100
+ });
101
+ const response = await fetch('/auth/session', {
102
+ method: 'POST',
103
+ credentials: 'same-origin',
104
+ headers: {
105
+ 'Content-Type': 'application/x-www-form-urlencoded',
106
+ },
107
+ body,
108
+ });
109
+ const result = await response.json().catch(() => null);
110
+ if (!response.ok || !result?.ok) {
111
+ return {
112
+ auth: null,
113
+ error: result?.error || { errorCode: 'network_error' },
114
+ };
115
+ }
116
+ return { auth: result.auth || null, error: null };
117
+ });
118
+ } catch {
119
+ return { auth: null, error: { errorCode: 'network_error' } };
120
+ }
121
+ }
122
+
123
+ /*
124
+ * Persist an OAuth or phone login before navigating without a bearer-token query.
125
+ */
126
+ export async function persistSignInSession(
127
+ token: string,
128
+ bootstrapToken?: string | null,
129
+ ): Promise<boolean> {
130
+ if (typeof fetch !== 'function' || (!token && !bootstrapToken)) {
131
+ return false;
132
+ }
133
+
134
+ return await runWithAuthSessionBrowserLock(async () => {
135
+ if (
136
+ bootstrapToken &&
137
+ (await postSignInSessionCredential('bootstrapToken', bootstrapToken))
138
+ ) {
139
+ return true;
140
+ }
141
+ return token ? await postSignInSessionCredential('token', token) : false;
142
+ });
143
+ }
@@ -1,28 +1,28 @@
1
- import i18n from '@jsb188/app/i18n';
2
- import { isEmail, passwordStrength } from '@jsb188/app/utils/string';
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import {
3
+ isPhone,
4
+ isEmail,
5
+ passwordStrength,
6
+ } from '@jsb188/app/utils/string.ts';
3
7
 
4
8
  /**
5
9
  * Types
6
10
  */
7
11
 
8
12
  interface SignInFormType {
9
- identifier?: string;
10
- password?: string;
13
+ identifier?: string;
14
+ password?: string;
11
15
  }
12
16
 
13
17
  interface SignUpFormType {
14
- email: string;
15
- password: string;
16
- passwordRepeat: string;
17
- }
18
-
19
- interface ForgotPasswordFormType {
20
- email: string;
18
+ email: string;
19
+ password: string;
20
+ passwordRepeat: string;
21
21
  }
22
22
 
23
23
  interface SignInDataForSchema {
24
- hidePassword: boolean;
25
- lastIdentifier: string;
24
+ hidePassword: boolean;
25
+ lastIdentifier: string;
26
26
  }
27
27
 
28
28
  /**
@@ -30,143 +30,151 @@ interface SignInDataForSchema {
30
30
  */
31
31
 
32
32
  const MIN_LEN_VALUES = {
33
- password: 8,
34
- pronouns: 20,
35
- description: 750,
33
+ password: 8,
34
+ description: 750,
36
35
  };
37
36
 
38
37
  /**
39
38
  * Rules for each field
40
39
  */
41
40
 
42
- const makeRules = () => ({
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) => passwordStrength(value, MIN_LEN_VALUES.password).valid,
53
- error: (value: string) => {
54
- const { isLongEnough, hasLowercase, hasUppercase, hasDigit, hasSpecial } = passwordStrength(value, MIN_LEN_VALUES.password);
55
- const errorMessages = [];
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 = [];
56
63
 
57
- if (!isLongEnough) {
58
- errorMessages.push(
59
- i18n.t('error.msg_password_too_short', { length: MIN_LEN_VALUES.password }),
60
- );
61
- }
62
- if (!hasLowercase) {
63
- errorMessages.push(i18n.t('error.msg_password_lowercase'));
64
- }
65
- if (!hasUppercase) {
66
- errorMessages.push(i18n.t('error.msg_password_uppercase'));
67
- }
68
- if (!hasDigit) {
69
- errorMessages.push(i18n.t('error.msg_password_digit'));
70
- }
71
- if (!hasSpecial) {
72
- errorMessages.push(i18n.t('error.msg_password_special'));
73
- }
74
-
75
- return {
76
- message: errorMessages.length > 1 ? i18n.t('error.msg_password_insecure') : errorMessages[0],
77
- };
78
- },
79
- },
80
- passwordRepeat: {
81
- for: 'passwordRepeat',
82
- rule: (value: string, formValues: Partial<SignUpFormType>) => value === formValues.password,
83
- error: {
84
- message: i18n.t('error.msg_password_mismatch'),
85
- },
86
- },
87
- });
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
+ }
88
83
 
89
- const RULES = makeRules();
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
+ })();
90
109
 
91
110
  /**
92
111
  * Schema; Change password
93
112
  */
94
113
 
95
- export const makeChangePasswordSchema = () => ({
96
- listData: [{
97
- __type: 'input',
98
- hidden: (dataForSchema?: SignInDataForSchema) => !!dataForSchema?.hidePassword,
99
- item: {
100
- autoFocus: true,
101
- name: 'currentPassword',
102
- type: 'password',
103
- label: i18n.t('user.currentPassword'),
104
- placeholder: i18n.t('user.password_ph'),
105
- // info: 'whatever you want',
106
- },
107
- }, {
108
- __type: 'password',
109
- item: {
110
- name: 'password',
111
- type: 'password',
112
- label: i18n.t('user.newPassword'),
113
- // placeholder: ''
114
- // info: 'whatever you want',
115
- },
116
- }, {
117
- __type: 'password',
118
- item: {
119
- name: 'passwordRepeat',
120
- type: 'password',
121
- label: i18n.t('user.newPasswordRepeat'),
122
- },
123
- }],
124
- rules: [
125
- RULES.password,
126
- ],
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',
123
+ type: 'password',
124
+ label: i18n.t('account.currentPassword'),
125
+ placeholder: i18n.t('account.password_ph'),
126
+ // info: 'whatever you want',
127
+ },
128
+ },
129
+ {
130
+ __type: 'password',
131
+ item: {
132
+ name: 'password',
133
+ type: 'password',
134
+ label: i18n.t('account.newPassword'),
135
+ // placeholder: ''
136
+ // info: 'whatever you want',
137
+ },
138
+ },
139
+ {
140
+ __type: 'password',
141
+ item: {
142
+ name: 'passwordRepeat',
143
+ type: 'password',
144
+ label: i18n.t('account.newPasswordRepeat'),
145
+ },
146
+ },
147
+ ],
148
+ rules: [RULES.password],
127
149
  });
128
150
 
129
151
  /**
130
- * Schema; Edit profile
152
+ * Schema; Assign a new password
131
153
  */
132
154
 
133
- export const makeEditProfileSchema = () => ({
134
- listData: [{
135
- // __type: 'input',
136
- // item: {
137
- // autoFocus: true,
138
- // maxLength: MIN_LEN_VALUES.displayName,
139
- // name: 'displayName',
140
- // label: i18n.t('user.displayName'),
141
- // placeholder: i18n.t('user.displayName_ph'),
142
- // info: i18n.t('user.displayName_info'),
143
- // autoComplete: 'off',
144
- // },
145
- // }, {
146
- __type: 'input',
147
- item: {
148
- name: 'pronouns',
149
- maxLength: MIN_LEN_VALUES.pronouns,
150
- setter: (data: any) => data?.profile?.pronouns,
151
- label: i18n.t('user.pronouns'),
152
- placeholder: i18n.t('user.pronouns_ph'),
153
- autoComplete: 'off',
154
- },
155
- }, {
156
- __type: 'textarea',
157
- item: {
158
- name: 'description',
159
- maxLength: MIN_LEN_VALUES.description,
160
- setter: (data: any) => data?.profile?.description,
161
- label: i18n.t('user.about'),
162
- placeholder: i18n.t('user.about_ph'),
163
- preset: 'in_modal',
164
- autoComplete: 'off',
165
- },
166
- }],
167
- rules: [
168
- // RULES.displayName,
169
- ],
155
+ export const makeAssignPasswordSchema = () => ({
156
+ listData: [
157
+ {
158
+ __type: 'password',
159
+ item: {
160
+ name: 'password',
161
+ type: 'password',
162
+ label: i18n.t('account.password'),
163
+ },
164
+ },
165
+ {
166
+ __type: 'password',
167
+ item: {
168
+ name: 'passwordRepeat',
169
+ type: 'password',
170
+ label: i18n.t('account.passwordRepeat'),
171
+ },
172
+ },
173
+ ],
174
+ rules: [RULES.password],
175
+ isButtonDisabled: (formValues: any) => {
176
+ return !formValues?.password?.trim() || !formValues?.passwordRepeat?.trim();
177
+ },
170
178
  });
171
179
 
172
180
  /**
@@ -174,30 +182,34 @@ export const makeEditProfileSchema = () => ({
174
182
  */
175
183
 
176
184
  export const makeSignInSchema = () => ({
177
- listData: [{
178
- __type: 'input',
179
- // Can't do this because disabling the input will make post form ignore this field
180
- // locked: ({ hidePassword, lastIdentifier }: SignInDataForSchema) => !hidePassword && !!lastIdentifier,
181
- item: {
182
- name: 'identifier',
183
- allowClearIfLocked: true,
184
- label: i18n.t('auth.login_opts_phone_email'),
185
- placeholder: i18n.t('user.phone_ph'),
186
- },
187
- }, {
188
- __type: 'password',
189
- hidden: (dataForSchema?: SignInDataForSchema) => !!dataForSchema?.hidePassword,
190
- autoFocus: true,
191
- item: {
192
- name: 'password',
193
- type: 'password',
194
- label: i18n.t('user.password'),
195
- placeholder: i18n.t('user.password_ph'),
196
- },
197
- }],
198
- isButtonDisabled: (formValues: SignInFormType) => {
199
- return !formValues?.identifier?.trim();
200
- },
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',
192
+ allowClearIfLocked: true,
193
+ label: i18n.t('auth.login_opts_main'),
194
+ placeholder: i18n.t('account.email_ph'),
195
+ },
196
+ },
197
+ {
198
+ __type: 'password',
199
+ hidden: (dataForSchema?: SignInDataForSchema) =>
200
+ !!dataForSchema?.hidePassword,
201
+ autoFocus: true,
202
+ item: {
203
+ name: 'password',
204
+ type: 'password',
205
+ label: i18n.t('account.password'),
206
+ placeholder: i18n.t('account.password_ph'),
207
+ },
208
+ },
209
+ ],
210
+ isButtonDisabled: (formValues: SignInFormType) => {
211
+ return !formValues?.identifier?.trim();
212
+ },
201
213
  });
202
214
 
203
215
  /**
@@ -205,58 +217,91 @@ export const makeSignInSchema = () => ({
205
217
  */
206
218
 
207
219
  export const makeSignUpSchema = () => ({
208
- listData: [{
209
- __type: 'input',
210
- item: {
211
- name: 'email',
212
- label: i18n.t('user.email'),
213
- placeholder: i18n.t('user.email_ph'),
214
- },
215
- }, {
216
- __type: 'password',
217
- item: {
218
- name: 'password',
219
- type: 'password',
220
- label: i18n.t('user.password'),
221
- placeholder: i18n.t('user.password_ph'),
222
- },
223
- }, {
224
- __type: 'password',
225
- item: {
226
- name: 'passwordRepeat',
227
- type: 'password',
228
- label: i18n.t('user.passwordRepeat'),
229
- placeholder: i18n.t('user.password_ph'),
230
- },
231
- }],
232
- isButtonDisabled: (formValues: Partial<SignUpFormType>) => {
233
- return ['email', 'password', 'passwordRepeat']
234
- .some((s) => !formValues[s]?.trim());
235
- },
236
- rules: [
237
- RULES.email,
238
- RULES.password,
239
- RULES.passwordRepeat,
240
- ],
220
+ listData: [
221
+ {
222
+ __type: 'input',
223
+ item: {
224
+ name: 'email',
225
+ label: i18n.t('account.email'),
226
+ placeholder: i18n.t('account.email_ph'),
227
+ },
228
+ },
229
+ {
230
+ __type: 'password',
231
+ item: {
232
+ name: 'password',
233
+ type: 'password',
234
+ label: i18n.t('account.password'),
235
+ placeholder: i18n.t('account.password_ph'),
236
+ },
237
+ },
238
+ {
239
+ __type: 'password',
240
+ item: {
241
+ name: 'passwordRepeat',
242
+ type: 'password',
243
+ label: i18n.t('account.passwordRepeat'),
244
+ placeholder: i18n.t('account.password_ph'),
245
+ },
246
+ },
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],
241
257
  });
242
258
 
243
259
  /**
244
260
  * Schema; Request a link to reset password
245
261
  */
246
262
 
263
+ interface RequestTokenizedEmailObj {
264
+ email: string;
265
+ }
266
+
247
267
  export const makeRequestTokenizedEmailSchema = () => ({
248
- listData: [{
249
- __type: 'input',
250
- item: {
251
- name: 'email',
252
- label: i18n.t('user.email'),
253
- placeholder: i18n.t('user.email_ph'),
254
- },
255
- }],
256
- isButtonDisabled: (formValues: Partial<ForgotPasswordFormType>) => {
257
- return !formValues.email?.trim();
258
- },
259
- rules: [
260
- RULES.email,
261
- ],
268
+ listData: [
269
+ {
270
+ __type: 'input',
271
+ item: {
272
+ name: 'email',
273
+ label: i18n.t('account.email'),
274
+ placeholder: i18n.t('account.email_ph'),
275
+ },
276
+ },
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;
290
+ }
291
+
292
+ export const makeSendPhoneVerificationSchema = () => ({
293
+ listData: [
294
+ {
295
+ __type: 'input',
296
+ item: {
297
+ name: 'phone',
298
+ label: i18n.t('form.phone_number'),
299
+ placeholder: i18n.t('account.phone_ph'),
300
+ },
301
+ },
302
+ ],
303
+ isButtonDisabled: (formValues: Partial<SendPhoneVerificationObj>) => {
304
+ return !formValues.phone?.trim();
305
+ },
306
+ rules: [RULES.phone],
262
307
  });