@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.
package/package.json CHANGED
@@ -1,20 +1,27 @@
1
1
  {
2
- "name": "@jsb188/auth-web",
3
- "version": "1.1.3",
4
- "description": "Authentication module for web.",
5
- "license": "ISC",
6
- "author": "jsb188",
7
- "type": "module",
8
- "main": "src/main.ts",
9
- "peerDependencies": {
10
- "@jsb188/app": "1.1.3",
11
- "@jsb188/react-web": "1.1.3",
12
- "react-router": "^7.6.2",
13
- "jotai": "^2.12.5",
14
- "react": "^19.1.0"
15
- },
16
- "scripts": {
17
- "test": "echo \"Error: no test specified\" && exit 1",
18
- "build": "tsc"
19
- }
2
+ "name": "@jsb188/auth-web",
3
+ "version": "1.1.11",
4
+ "description": "Authentication module for web.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./src/main.ts",
10
+ "./schemas": "./src/schemas/index.ts",
11
+ "./schemas/address": "./src/schemas/address.ts"
12
+ },
13
+ "peerDependencies": {
14
+ "@azure/msal-browser": "^4.30.0",
15
+ "@jsb188/app": "1.1.11",
16
+ "@jsb188/graphql": "1.1.11",
17
+ "@jsb188/react": "1.1.11",
18
+ "@jsb188/react-web": "1.1.11",
19
+ "jotai": "^2.20.2",
20
+ "react": "^19.2.8",
21
+ "react-router": "^8.3.0"
22
+ },
23
+ "scripts": {
24
+ "test": "echo \"Error: no test specified\" && exit 1",
25
+ "build": "tsc"
26
+ }
20
27
  }
@@ -1,27 +1,79 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import { getTimeBasedUnique } from '@jsb188/app/utils/string';
3
- import { useMutation } from '@jsb188/graphql/client';
4
- import { signInWithGoogleMtn } from '@jsb188/graphql/mutations/accountAuth';
5
2
  import type { OnErrorGQLFn } from '@jsb188/graphql/types.d';
6
- import { AppContext, onAccountLogin, useOpenModalPopUp } from '@jsb188/react/states';
3
+ import {
4
+ AppContext,
5
+ onAccountLogin,
6
+ useOpenModalPopUp,
7
+ } from '@jsb188/react/states';
7
8
  import { useCallback, useContext, useEffect, useRef, useState } from 'react';
9
+ import { authenticateOAuthSignInSession } from '../modules/_helpers';
8
10
 
9
11
  /**
10
12
  * Types
11
13
  */
12
14
 
15
+ // SSO sign-in option resolved by the getSsoLoginOptions mutation
16
+ export interface SsoLoginOptionData {
17
+ id: string;
18
+ provider: 'GOOGLE' | 'MICROSOFT';
19
+ organizationId: string;
20
+ organizationName: string;
21
+ microsoftTenantId?: string | null;
22
+ googleHostedDomain?: string | null;
23
+ }
24
+
25
+ // Called when an "authenticateOnly" sign-in verified an email with no account
26
+ // and the server returned a temporary form respondent token instead
27
+ type OnRespondentTokenFn = (token: string, email: string | null) => void;
28
+
29
+ export type OnFinishSignInFn = (
30
+ token: string,
31
+ sessionBootstrapToken?: string | null,
32
+ sessionPersisted?: boolean,
33
+ ) => boolean | Promise<boolean>;
34
+
13
35
  interface ContinueWithGoogleParams {
14
- doNotAlertErrors?: boolean;
15
- onFinishSignIn: (token: string) => void;
36
+ doNotAlertErrors?: boolean;
37
+ onFinishSignIn: OnFinishSignInFn;
38
+ onRespondentToken?: OnRespondentTokenFn;
39
+ }
40
+
41
+ interface ContinueWithMicrosoftParams {
42
+ doNotAlertErrors?: boolean;
43
+ onFinishSignIn: OnFinishSignInFn;
44
+ onRespondentToken?: OnRespondentTokenFn;
45
+ onError?: OnErrorGQLFn;
16
46
  }
17
47
 
18
48
  interface GoogleLoginHookParams extends ContinueWithGoogleParams {
19
- scriptLoaded: boolean;
20
- scope?: string;
21
- onError?: OnErrorGQLFn;
22
- onNonOAuthError?: (err: any) => void;
23
- overrideScope?: boolean;
24
- state?: string;
49
+ scriptLoaded: boolean;
50
+ scope?: string;
51
+ onError?: OnErrorGQLFn;
52
+ onNonOAuthError?: (err: any) => void;
53
+ overrideScope?: boolean;
54
+ state?: string;
55
+ }
56
+
57
+ /*
58
+ * Apply a BFF-authenticated provider result to the caller and shared app state.
59
+ */
60
+ async function applyOAuthAuthenticationResult(
61
+ auth: any,
62
+ onFinishSignIn: OnFinishSignInFn,
63
+ onRespondentToken: OnRespondentTokenFn | undefined,
64
+ dispatchApp: any,
65
+ ): Promise<boolean> {
66
+ if (auth?.token && auth.account?.id) {
67
+ const persisted = await onFinishSignIn(auth.token, null, true);
68
+ if (persisted) {
69
+ onAccountLogin({ ...auth, sessionBootstrapToken: null }, dispatchApp);
70
+ return true;
71
+ }
72
+ } else if (auth?.respondentToken) {
73
+ onRespondentToken?.(auth.respondentToken, auth.respondentEmail || null);
74
+ }
75
+
76
+ return false;
25
77
  }
26
78
 
27
79
  /**
@@ -29,80 +81,147 @@ interface GoogleLoginHookParams extends ContinueWithGoogleParams {
29
81
  */
30
82
 
31
83
  function useGoogleLogin(p: GoogleLoginHookParams) {
32
- const {
33
- scriptLoaded,
34
- scope = '',
35
- onError,
36
- onNonOAuthError,
37
- onFinishSignIn,
38
- overrideScope,
39
- state,
40
- doNotAlertErrors,
41
- ...props
42
- } = p;
43
-
44
- const { dispatchApp } = useContext(AppContext);
45
- const openModalPopUp = useOpenModalPopUp();
46
- const [signInWithGoogle, { saving }] = useMutation(
47
- signInWithGoogleMtn,
48
- {
49
- openModalPopUp: doNotAlertErrors ? null : openModalPopUp,
50
- onError,
51
- onCompleted: (data) => {
52
- const result = data?.signInWithGoogle;
53
- if (result?.token && result.user?.id) {
54
- onAccountLogin(result, dispatchApp);
55
- onFinishSignIn(result?.token);
56
- }
57
- },
58
- },
59
- );
60
-
61
- const clientRef = useRef<any>();
62
-
63
- const onErrorRef = useRef(onError);
64
- onErrorRef.current = onError;
65
-
66
- const onNonOAuthErrorRef = useRef(onNonOAuthError);
67
- onNonOAuthErrorRef.current = onNonOAuthError;
68
-
69
- useEffect(() => {
70
- if (scriptLoaded) {
71
- // @ts-expect-error - If using this package, it is expected that you install your own Google OAuth script
72
- const client = globalThis.google?.accounts?.oauth2.initTokenClient({
73
- client_id: getENVVariable('GOOGLE_OAUTH'),
74
- scope: overrideScope ? scope : `openid profile email ${scope}`,
75
- callback: (response: any) => {
76
- if (response.error) {
77
- return onErrorRef.current?.(response, null);
78
- }
79
-
80
- const { access_token: oauthToken } = response;
81
- signInWithGoogle({
82
- variables: {
83
- oauthToken,
84
- },
85
- });
86
- },
87
- error_callback: (nonOAuthError: any) => {
88
- onNonOAuthErrorRef.current?.(nonOAuthError);
89
- },
90
- state,
91
- ...props,
92
- });
93
-
94
- clientRef.current = client;
95
- }
96
- }, [scriptLoaded, scope, state]);
97
-
98
- const onInitiateGoogleSignIn = useCallback((overrideConfig?: object) => {
99
- clientRef.current?.requestAccessToken(overrideConfig);
100
- }, []);
101
-
102
- return {
103
- onInitiateGoogleSignIn,
104
- waitingForOAuth: saving,
105
- };
84
+ const {
85
+ scriptLoaded,
86
+ scope = '',
87
+ onError,
88
+ onNonOAuthError,
89
+ onFinishSignIn,
90
+ onRespondentToken,
91
+ overrideScope,
92
+ state,
93
+ doNotAlertErrors,
94
+ ...props
95
+ } = p;
96
+
97
+ const { dispatchApp } = useContext(AppContext);
98
+ const openModalPopUp = useOpenModalPopUp();
99
+ const [waitingForProvider, setWaitingForProvider] = useState(false);
100
+ const [waitingForOAuth, setWaitingForOAuth] = useState(false);
101
+
102
+ const clientRef = useRef<any>(null);
103
+ const onErrorRef = useRef(onError);
104
+
105
+ onErrorRef.current = onError;
106
+
107
+ const onNonOAuthErrorRef = useRef(onNonOAuthError);
108
+ onNonOAuthErrorRef.current = onNonOAuthError;
109
+
110
+ const onRespondentTokenRef = useRef(onRespondentToken);
111
+ onRespondentTokenRef.current = onRespondentToken;
112
+
113
+ const onFinishSignInRef = useRef(onFinishSignIn);
114
+ onFinishSignInRef.current = onFinishSignIn;
115
+
116
+ const openModalPopUpRef = useRef(openModalPopUp);
117
+ openModalPopUpRef.current = openModalPopUp;
118
+
119
+ const doNotAlertErrorsRef = useRef(doNotAlertErrors);
120
+ doNotAlertErrorsRef.current = doNotAlertErrors;
121
+
122
+ const dispatchAppRef = useRef(dispatchApp);
123
+ dispatchAppRef.current = dispatchApp;
124
+
125
+ // Org SSO connection to sign in through; read by the token callback below
126
+ const ssoConnectionIdRef = useRef<string | null>(null);
127
+ // Public web form context; allows contact-gated account creation (CHILD_ORGS forms)
128
+ const formPublicIdRef = useRef<string | null>(null);
129
+ // When true, a verified email with no account returns a temporary respondent
130
+ // token instead of erroring (ANYONE web forms)
131
+ const authenticateOnlyRef = useRef<boolean>(false);
132
+
133
+ useEffect(() => {
134
+ if (scriptLoaded) {
135
+ // If using this package, it is expected that you install your own Google OAuth script
136
+ const client = (
137
+ globalThis as any
138
+ ).google?.accounts?.oauth2.initTokenClient({
139
+ client_id: getENVVariable('GOOGLE_OAUTH'),
140
+ scope: overrideScope ? scope : `openid profile email ${scope}`,
141
+ callback: async (response: any) => {
142
+ if (response.error) {
143
+ setWaitingForProvider(false);
144
+ setWaitingForOAuth(false);
145
+ return onErrorRef.current?.(response, null);
146
+ }
147
+
148
+ const { access_token: oauthToken } = response;
149
+ setWaitingForProvider(false);
150
+ setWaitingForOAuth(true);
151
+ const variables = {
152
+ provider: 'GOOGLE' as const,
153
+ oauthToken,
154
+ ssoConnectionId: ssoConnectionIdRef.current,
155
+ formPublicId: formPublicIdRef.current,
156
+ authenticateOnly: authenticateOnlyRef.current,
157
+ };
158
+ const { auth, error } =
159
+ await authenticateOAuthSignInSession(variables);
160
+ if (error) {
161
+ setWaitingForOAuth(false);
162
+ if (!doNotAlertErrorsRef.current) {
163
+ openModalPopUpRef.current(null, error);
164
+ }
165
+ onErrorRef.current?.(error, variables);
166
+ return;
167
+ }
168
+
169
+ try {
170
+ const authenticated = await applyOAuthAuthenticationResult(
171
+ auth,
172
+ onFinishSignInRef.current,
173
+ onRespondentTokenRef.current,
174
+ dispatchAppRef.current,
175
+ );
176
+ if (!authenticated) {
177
+ setWaitingForOAuth(false);
178
+ }
179
+ } catch (error) {
180
+ setWaitingForOAuth(false);
181
+ throw error;
182
+ }
183
+ },
184
+ error_callback: (nonOAuthError: any) => {
185
+ setWaitingForProvider(false);
186
+ setWaitingForOAuth(false);
187
+ onNonOAuthErrorRef.current?.(nonOAuthError);
188
+ },
189
+ state,
190
+ ...props,
191
+ });
192
+
193
+ clientRef.current = client;
194
+ }
195
+ }, [scriptLoaded, scope, state]);
196
+
197
+ const onInitiateGoogleSignIn = useCallback(
198
+ (
199
+ overrideConfig?: object,
200
+ ssoConnectionId?: string | null,
201
+ formPublicId?: string | null,
202
+ authenticateOnly?: boolean,
203
+ ) => {
204
+ ssoConnectionIdRef.current = ssoConnectionId || null;
205
+ formPublicIdRef.current = formPublicId || null;
206
+ authenticateOnlyRef.current = !!authenticateOnly;
207
+ if (clientRef.current) {
208
+ setWaitingForProvider(true);
209
+ try {
210
+ clientRef.current.requestAccessToken(overrideConfig);
211
+ } catch (error) {
212
+ setWaitingForProvider(false);
213
+ throw error;
214
+ }
215
+ }
216
+ },
217
+ [],
218
+ );
219
+
220
+ return {
221
+ onInitiateGoogleSignIn,
222
+ oauthButtonDisabled: waitingForProvider,
223
+ waitingForOAuth,
224
+ };
106
225
  }
107
226
 
108
227
  /**
@@ -110,65 +229,179 @@ function useGoogleLogin(p: GoogleLoginHookParams) {
110
229
  */
111
230
 
112
231
  export function useContinueWithGoogle(params: ContinueWithGoogleParams) {
113
- const { doNotAlertErrors, onFinishSignIn } = params;
114
- const [scriptLoaded, setScriptLoaded] = useState(false);
115
-
116
- useEffect(() => {
117
- const scriptTag = document.createElement('script');
118
- scriptTag.src = 'https://accounts.google.com/gsi/client';
119
- scriptTag.async = true;
120
- scriptTag.defer = true;
121
- // scriptTag.nonce = nonce;
122
-
123
- scriptTag.onload = () => {
124
- setScriptLoaded(true);
125
- };
126
- scriptTag.onerror = () => {
127
- setScriptLoaded(false);
128
- };
129
-
130
- document.body.appendChild(scriptTag);
131
- return () => {
132
- document.body.removeChild(scriptTag);
133
- };
134
- }, []);
135
-
136
- const { onInitiateGoogleSignIn, waitingForOAuth } = useGoogleLogin({
137
- doNotAlertErrors,
138
- onFinishSignIn,
139
- scriptLoaded,
140
- onError: (err: any) => {
141
- console.log('ERROR', err);
142
- },
143
- });
144
-
145
- return {
146
- waitingForOAuth,
147
- onInitiateGoogleSignIn,
148
- scriptLoaded
149
- };
232
+ const { doNotAlertErrors, onFinishSignIn, onRespondentToken } = params;
233
+ const [scriptLoaded, setScriptLoaded] = useState(false);
234
+
235
+ useEffect(() => {
236
+ const scriptTag = document.createElement('script');
237
+ scriptTag.src = 'https://accounts.google.com/gsi/client';
238
+ scriptTag.async = true;
239
+ scriptTag.defer = true;
240
+ // scriptTag.nonce = nonce;
241
+
242
+ scriptTag.onload = () => {
243
+ setScriptLoaded(true);
244
+ };
245
+ scriptTag.onerror = () => {
246
+ setScriptLoaded(false);
247
+ };
248
+
249
+ document.body.appendChild(scriptTag);
250
+ return () => {
251
+ document.body.removeChild(scriptTag);
252
+ };
253
+ }, []);
254
+
255
+ const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } =
256
+ useGoogleLogin({
257
+ doNotAlertErrors,
258
+ onFinishSignIn,
259
+ onRespondentToken,
260
+ scriptLoaded,
261
+ });
262
+
263
+ return {
264
+ oauthButtonDisabled,
265
+ waitingForOAuth,
266
+ onInitiateGoogleSignIn,
267
+ scriptLoaded,
268
+ };
150
269
  }
151
270
 
271
+ // MSAL client is cached at module level so repeated hook mounts reuse one instance
272
+ let msalClientPromise: Promise<any> | null = null;
273
+
152
274
  /**
153
- * Web sign in with Apple
275
+ * Get or lazily create the MSAL public client application
154
276
  */
155
277
 
156
- export function useContinueWithApple() {
157
-
158
- const onInitiateAppleSignIn = () => {
159
- globalThis.location.href = (
160
- 'https://appleid.apple.com/auth/authorize' +
161
- '?client_id=' + getENVVariable('APPLE_APP_ID') +
162
- '&redirect_uri=' + encodeURIComponent(getENVVariable('APP_URL') + 'auth/apple') +
163
- '&response_type=' + encodeURIComponent('code id_token') +
164
- '&state=' + getTimeBasedUnique() +
165
- '&scope=' + encodeURIComponent('email name') +
166
- '&response_mode=form_post'
167
- // '&frame_id'=36394414-f7d7-4021-8f98-64e7be74e283&m=11&v=1.5.5'
168
- );
169
- };
170
-
171
- return {
172
- onInitiateAppleSignIn
173
- };
278
+ function getMSALClient() {
279
+ if (!msalClientPromise) {
280
+ // Dynamic import keeps MSAL out of the main bundle until Microsoft sign in is used
281
+ msalClientPromise = import('@azure/msal-browser')
282
+ .then(async ({ PublicClientApplication }) => {
283
+ const pca = new PublicClientApplication({
284
+ auth: {
285
+ clientId: String(getENVVariable('MICROSOFT_OAUTH') || ''),
286
+ authority: 'https://login.microsoftonline.com/common',
287
+ redirectUri: getENVVariable('APP_URL') + 'auth/msal',
288
+ },
289
+ });
290
+
291
+ await pca.initialize();
292
+ return pca;
293
+ })
294
+ .catch((err) => {
295
+ // Do not cache a failed load/initialization; let the next click retry
296
+ msalClientPromise = null;
297
+ throw err;
298
+ });
299
+ }
300
+
301
+ return msalClientPromise;
302
+ }
303
+
304
+ /**
305
+ * Web sign in with Microsoft
306
+ */
307
+
308
+ export function useContinueWithMicrosoft(params: ContinueWithMicrosoftParams) {
309
+ const { doNotAlertErrors, onFinishSignIn, onRespondentToken, onError } =
310
+ params;
311
+ const { dispatchApp } = useContext(AppContext);
312
+ const openModalPopUp = useOpenModalPopUp();
313
+ const [waitingForPopUp, setWaitingForPopUp] = useState(false);
314
+ const [waitingForOAuth, setWaitingForOAuth] = useState(false);
315
+
316
+ const onRespondentTokenRef = useRef(onRespondentToken);
317
+ onRespondentTokenRef.current = onRespondentToken;
318
+
319
+ const onFinishSignInRef = useRef(onFinishSignIn);
320
+ onFinishSignInRef.current = onFinishSignIn;
321
+
322
+ const onErrorRef = useRef(onError);
323
+ onErrorRef.current = onError;
324
+
325
+ const openModalPopUpRef = useRef(openModalPopUp);
326
+ openModalPopUpRef.current = openModalPopUp;
327
+
328
+ const doNotAlertErrorsRef = useRef(doNotAlertErrors);
329
+ doNotAlertErrorsRef.current = doNotAlertErrors;
330
+
331
+ const dispatchAppRef = useRef(dispatchApp);
332
+ dispatchAppRef.current = dispatchApp;
333
+
334
+ const onInitiateMicrosoftSignIn = useCallback(
335
+ async (
336
+ ssoOption?: SsoLoginOptionData | any,
337
+ loginHint?: string,
338
+ formPublicId?: string | null,
339
+ authenticateOnly?: boolean,
340
+ ) => {
341
+ setWaitingForPopUp(true);
342
+
343
+ // A plain onClick passes the click event here; only a real SSO option
344
+ // (with a tenant id) changes the popup behavior
345
+ const ssoTenantId = ssoOption?.microsoftTenantId || null;
346
+ const ssoConnectionId = ssoTenantId ? ssoOption?.id : null;
347
+
348
+ try {
349
+ const pca = await getMSALClient();
350
+ const result = await pca.loginPopup({
351
+ scopes: ['openid', 'profile', 'email'],
352
+ prompt: 'select_account',
353
+ // Pin the popup to the org's Entra tenant instead of "common"
354
+ ...(ssoTenantId
355
+ ? { authority: `https://login.microsoftonline.com/${ssoTenantId}` }
356
+ : null),
357
+ ...(loginHint ? { loginHint } : null),
358
+ });
359
+
360
+ if (result?.idToken) {
361
+ setWaitingForOAuth(true);
362
+ const variables = {
363
+ provider: 'MICROSOFT' as const,
364
+ idToken: result.idToken,
365
+ ssoConnectionId,
366
+ formPublicId,
367
+ authenticateOnly,
368
+ };
369
+ const authentication =
370
+ await authenticateOAuthSignInSession(variables);
371
+ if (authentication.error) {
372
+ setWaitingForOAuth(false);
373
+ if (!doNotAlertErrorsRef.current) {
374
+ openModalPopUpRef.current(null, authentication.error);
375
+ }
376
+ onErrorRef.current?.(authentication.error, variables);
377
+ } else {
378
+ const authenticated = await applyOAuthAuthenticationResult(
379
+ authentication.auth,
380
+ onFinishSignInRef.current,
381
+ onRespondentTokenRef.current,
382
+ dispatchAppRef.current,
383
+ );
384
+ if (!authenticated) {
385
+ setWaitingForOAuth(false);
386
+ }
387
+ }
388
+ }
389
+ } catch (err: any) {
390
+ setWaitingForOAuth(false);
391
+ // User closing/cancelling the popup is not an error
392
+ if (err?.errorCode !== 'user_cancelled') {
393
+ console.warn(err);
394
+ }
395
+ } finally {
396
+ setWaitingForPopUp(false);
397
+ }
398
+ },
399
+ [],
400
+ );
401
+
402
+ return {
403
+ onInitiateMicrosoftSignIn,
404
+ oauthButtonDisabled: waitingForPopUp,
405
+ waitingForOAuth,
406
+ };
174
407
  }
package/src/main.ts CHANGED
@@ -1,3 +1,10 @@
1
- export * from './modules/AuthForm';
1
+ export * from './hooks/use-oauth';
2
+ export * from './modules/AssignRequiredAuth';
3
+ export * from './modules/AuthForms';
4
+ export * from './modules/AuthFormUI';
2
5
  export * from './modules/AuthGate';
6
+ export { default as InlineAuthForm } from './modules/InlineAuthForm';
7
+ export * from './modules/ManagedSessions';
8
+ export * from './modules/OtherAuthButtons';
3
9
  export * from './modules/schemas';
10
+ export * from './ui/ManagedSessionUI';