@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jsb188/auth-web",
3
- "version": "1.1.11",
3
+ "version": "1.1.12",
4
4
  "description": "Authentication module for web.",
5
5
  "license": "ISC",
6
6
  "author": "jsb188",
@@ -12,13 +12,15 @@
12
12
  },
13
13
  "peerDependencies": {
14
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",
15
+ "@jsb188/app": "1.1.12",
16
+ "@jsb188/graphql": "1.1.12",
17
+ "@jsb188/react": "1.1.12",
18
+ "@jsb188/react-web": "1.1.12",
19
19
  "jotai": "^2.20.2",
20
- "react": "^19.2.8",
21
- "react-router": "^8.3.0"
20
+ "react": "^19.3.0",
21
+ "react-router": "^8.4.0",
22
+ "@jsb188/form": "1.1.12",
23
+ "zod": "^3.25.76"
22
24
  },
23
25
  "scripts": {
24
26
  "test": "echo \"Error: no test specified\" && exit 1",
@@ -0,0 +1,167 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { hydrateAuthenticationSession } from '../modules/_helpers.ts';
3
+ import {
4
+ type AuthPopupCompletionMessage,
5
+ isAuthPopupCompletionMessage,
6
+ isAuthPopupRespondentCompletionMessage,
7
+ } from '../utils/authPopup.ts';
8
+
9
+ interface UseAuthenticationPopupParams {
10
+ href?: string | null;
11
+ formPublicId?: string | null;
12
+ onRespondentAuthenticated?: (token: string, email: string) => void | Promise<void>;
13
+ onAuthenticated: (auth: any, completionMessage: AuthPopupCompletionMessage) => boolean | Promise<boolean>;
14
+ onError?: (error: any) => void;
15
+ }
16
+
17
+ /*
18
+ * Open one same-origin authentication window and adopt its cookie-backed
19
+ * account session after the popup reports completion.
20
+ */
21
+ export function useAuthenticationPopup(p: UseAuthenticationPopupParams) {
22
+ const [popupOpen, setPopupOpen] = useState(false);
23
+ const popupRef = useRef<Window | null>(null);
24
+ const popupIdRef = useRef<string | null>(null);
25
+ const popupFormPublicIdRef = useRef<string | null>(null);
26
+ const closeTimerRef = useRef<ReturnType<typeof globalThis.setInterval> | null>(null);
27
+ const completionStartedRef = useRef(false);
28
+ const onAuthenticatedRef = useRef(p.onAuthenticated);
29
+ const onErrorRef = useRef(p.onError);
30
+ const formPublicIdRef = useRef(p.formPublicId);
31
+ const onRespondentAuthenticatedRef = useRef(p.onRespondentAuthenticated);
32
+
33
+ onAuthenticatedRef.current = p.onAuthenticated;
34
+ onErrorRef.current = p.onError;
35
+ formPublicIdRef.current = p.formPublicId;
36
+ onRespondentAuthenticatedRef.current = p.onRespondentAuthenticated;
37
+
38
+ /*
39
+ * Clear the tracked popup and its close monitor after any terminal outcome.
40
+ */
41
+ const resetPopup = useCallback(() => {
42
+ if (closeTimerRef.current !== null) {
43
+ globalThis.clearInterval(closeTimerRef.current);
44
+ closeTimerRef.current = null;
45
+ }
46
+ popupRef.current = null;
47
+ popupIdRef.current = null;
48
+ popupFormPublicIdRef.current = null;
49
+ completionStartedRef.current = false;
50
+ setPopupOpen(false);
51
+ }, []);
52
+
53
+ useEffect(() => {
54
+ /*
55
+ * Validate a popup completion signal before rehydrating its shared session.
56
+ */
57
+ const onMessage = (event: MessageEvent) => {
58
+ const popup = popupRef.current;
59
+ const popupId = popupIdRef.current;
60
+ if (
61
+ !popup ||
62
+ !popupId ||
63
+ event.origin !== globalThis.location.origin ||
64
+ event.source !== popup ||
65
+ completionStartedRef.current
66
+ ) {
67
+ return;
68
+ }
69
+
70
+ const formPublicId = popupFormPublicIdRef.current;
71
+ const respondentCompletion =
72
+ formPublicId &&
73
+ formPublicId === formPublicIdRef.current &&
74
+ onRespondentAuthenticatedRef.current &&
75
+ isAuthPopupRespondentCompletionMessage(event.data, popupId, formPublicId)
76
+ ? event.data
77
+ : null;
78
+ const accountCompletion = isAuthPopupCompletionMessage(event.data, popupId) ? event.data : null;
79
+ if (!respondentCompletion && !accountCompletion) return;
80
+
81
+ completionStartedRef.current = true;
82
+
83
+ /* Adopt only the identity kind returned by this still-active popup. */
84
+ const completeAuthentication = async () => {
85
+ if (respondentCompletion) {
86
+ await onRespondentAuthenticatedRef.current?.(respondentCompletion.respondentToken, respondentCompletion.respondentEmail);
87
+ return;
88
+ }
89
+ const { auth, error } = await hydrateAuthenticationSession();
90
+ if (popupRef.current !== popup || popupIdRef.current !== popupId) return;
91
+ if (!auth?.token || !accountCompletion || !(await onAuthenticatedRef.current(auth, accountCompletion))) {
92
+ onErrorRef.current?.(error || { errorCode: 'network_error' });
93
+ }
94
+ };
95
+ void completeAuthentication()
96
+ .catch((error) => {
97
+ if (popupRef.current === popup) onErrorRef.current?.(error);
98
+ })
99
+ .finally(() => {
100
+ if (popupRef.current !== popup || popupIdRef.current !== popupId) return;
101
+ popup.close();
102
+ resetPopup();
103
+ });
104
+ };
105
+
106
+ globalThis.addEventListener('message', onMessage);
107
+ return () => {
108
+ globalThis.removeEventListener('message', onMessage);
109
+ popupRef.current?.close();
110
+ resetPopup();
111
+ };
112
+ }, [resetPopup]);
113
+
114
+ /*
115
+ * Launch the configured same-origin sign-in route from a direct user action.
116
+ */
117
+ const openAuthenticationPopup = useCallback(
118
+ (additionalSearchParams?: Record<string, string>) => {
119
+ if (!p.href || popupRef.current) {
120
+ return;
121
+ }
122
+
123
+ const popupUrl = new URL(p.href, globalThis.location.origin);
124
+ if (popupUrl.origin !== globalThis.location.origin) {
125
+ onErrorRef.current?.({ errorCode: 'forbidden' });
126
+ return;
127
+ }
128
+
129
+ const popupId = globalThis.crypto.randomUUID();
130
+ for (const [name, value] of Object.entries(additionalSearchParams || {})) {
131
+ popupUrl.searchParams.set(name, value);
132
+ }
133
+ popupUrl.searchParams.set('popup', '1');
134
+ popupUrl.searchParams.set('popupId', popupId);
135
+ const width = 520;
136
+ const height = 720;
137
+ const left = Math.max(0, globalThis.screenX + (globalThis.outerWidth - width) / 2);
138
+ const top = Math.max(0, globalThis.screenY + (globalThis.outerHeight - height) / 2);
139
+ const popup = globalThis.open(
140
+ popupUrl.toString(),
141
+ 'marketday-auth',
142
+ `popup,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`,
143
+ );
144
+ if (!popup) {
145
+ onErrorRef.current?.({ errorCode: 'popup_blocked' });
146
+ return;
147
+ }
148
+
149
+ popupRef.current = popup;
150
+ popupIdRef.current = popupId;
151
+ popupFormPublicIdRef.current = formPublicIdRef.current || null;
152
+ setPopupOpen(true);
153
+ popup.focus();
154
+ closeTimerRef.current = globalThis.setInterval(() => {
155
+ if (popup.closed && !completionStartedRef.current) {
156
+ resetPopup();
157
+ }
158
+ }, 500);
159
+ },
160
+ [p.href, resetPopup],
161
+ );
162
+
163
+ return {
164
+ openAuthenticationPopup,
165
+ popupOpen,
166
+ };
167
+ }
@@ -0,0 +1,138 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import { AppContext, onAccountLogin } from '@jsb188/react/states';
3
+ import { useContext, useEffect, useRef, useState } from 'react';
4
+ import { authenticateOAuthSignInSession } from '../modules/_helpers';
5
+ import {
6
+ getGoogleSignOutMarker,
7
+ getGoogleOneTapClient,
8
+ type GoogleOneTapClient,
9
+ loadGoogleIdentityServices,
10
+ } from '../utils/googleIdentity';
11
+ import type { OnFinishSignInFn } from './use-oauth';
12
+
13
+ const FILE_CONSTANTS = {
14
+ promptTimeoutMs: 60000,
15
+ authenticationTimeoutMs: 30000,
16
+ };
17
+
18
+ /*
19
+ * Try One Tap once on an eligible public form and report progress through credential adoption.
20
+ */
21
+ export function useGoogleOneTap(p: {
22
+ enabled: boolean;
23
+ formPublicId: string;
24
+ authenticateOnly: boolean;
25
+ onFinishSignIn: OnFinishSignInFn;
26
+ onRespondentToken: (token: string, email: string | null) => void;
27
+ }) {
28
+ const { dispatchApp } = useContext(AppContext);
29
+ const callbacks = useRef({ onFinishSignIn: p.onFinishSignIn, onRespondentToken: p.onRespondentToken, dispatchApp });
30
+ callbacks.current = { onFinishSignIn: p.onFinishSignIn, onRespondentToken: p.onRespondentToken, dispatchApp };
31
+ const completedForm = useRef<string | null>(null);
32
+ const [loading, setLoading] = useState(false);
33
+
34
+ useEffect(() => {
35
+ const signOutMarker = getGoogleSignOutMarker();
36
+ if (!p.enabled || completedForm.current === p.formPublicId) {
37
+ setLoading(false);
38
+ return;
39
+ }
40
+ const clientId = String(getENVVariable('GOOGLE_OAUTH') || '');
41
+ if (!clientId) return;
42
+
43
+ let active = true;
44
+ let authenticating = false;
45
+ let client: GoogleOneTapClient | undefined;
46
+ const controller = new AbortController();
47
+ let timer = globalThis.setTimeout(() => finish(), FILE_CONSTANTS.promptTimeoutMs);
48
+ setLoading(true);
49
+
50
+ /* End this attempt before cancellation can emit another SDK notification. */
51
+ const finish = () => {
52
+ if (!active) return;
53
+ active = false;
54
+ completedForm.current = p.formPublicId;
55
+ globalThis.clearTimeout(timer);
56
+ controller.abort();
57
+ client?.cancel();
58
+ setLoading(false);
59
+ };
60
+
61
+ /* Exchange a Google credential through the same-origin endpoint and adopt the verified identity. */
62
+ const onCredential = async (response: { credential: string }) => {
63
+ if (!active || authenticating || !response.credential) return;
64
+ if (getGoogleSignOutMarker() !== signOutMarker) return finish();
65
+ authenticating = true;
66
+ globalThis.clearTimeout(timer);
67
+ timer = globalThis.setTimeout(finish, FILE_CONSTANTS.authenticationTimeoutMs);
68
+ try {
69
+ const { auth, error } = await authenticateOAuthSignInSession(
70
+ {
71
+ provider: 'GOOGLE',
72
+ idToken: response.credential,
73
+ formPublicId: p.formPublicId,
74
+ authenticateOnly: p.authenticateOnly,
75
+ },
76
+ controller.signal,
77
+ );
78
+ if (!active || error) return;
79
+ if (auth?.account?.id && auth.token) {
80
+ const persisted = await callbacks.current.onFinishSignIn(auth.token, null, true);
81
+ if (active && persisted) onAccountLogin({ ...auth, sessionBootstrapToken: null }, callbacks.current.dispatchApp);
82
+ } else if (auth?.respondentToken) {
83
+ callbacks.current.onRespondentToken(auth.respondentToken, auth.respondentEmail || null);
84
+ }
85
+ } catch {
86
+ // Keep manual sign-in available if identity adoption fails.
87
+ } finally {
88
+ finish();
89
+ }
90
+ };
91
+
92
+ /* Load Google and request a browser-bound nonce before asking Google to show One Tap. */
93
+ const start = async () => {
94
+ try {
95
+ await loadGoogleIdentityServices();
96
+ if (!active) return;
97
+ const response = await fetch('/auth/session', {
98
+ method: 'POST',
99
+ credentials: 'same-origin',
100
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
101
+ body: new URLSearchParams({ googleOneTapChallenge: '1', formPublicId: p.formPublicId }),
102
+ signal: controller.signal,
103
+ });
104
+ const challenge = await response.json();
105
+ if (!active) return;
106
+ if (getGoogleSignOutMarker() !== signOutMarker) return finish();
107
+ client = getGoogleOneTapClient();
108
+ if (!response.ok || !challenge.ok || typeof challenge.nonce !== 'string' || !client) return finish();
109
+ client.initialize({
110
+ client_id: clientId,
111
+ auto_select: !signOutMarker,
112
+ nonce: challenge.nonce,
113
+ callback: onCredential,
114
+ });
115
+ client.prompt((notification) => {
116
+ if (authenticating) return;
117
+ if (
118
+ notification.isSkippedMoment() ||
119
+ (notification.isDismissedMoment() && notification.getDismissedReason() !== 'credential_returned')
120
+ ) {
121
+ finish();
122
+ }
123
+ });
124
+ } catch {
125
+ finish();
126
+ }
127
+ };
128
+ void start();
129
+ return () => {
130
+ active = false;
131
+ globalThis.clearTimeout(timer);
132
+ controller.abort();
133
+ client?.cancel();
134
+ };
135
+ }, [p.enabled, p.formPublicId, p.authenticateOnly]);
136
+
137
+ return { loading: p.enabled && loading };
138
+ }
@@ -1,12 +1,9 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
2
  import type { OnErrorGQLFn } from '@jsb188/graphql/types.d';
3
- import {
4
- AppContext,
5
- onAccountLogin,
6
- useOpenModalPopUp,
7
- } from '@jsb188/react/states';
3
+ import { AppContext, onAccountLogin, useOpenModalPopUp } from '@jsb188/react/states';
8
4
  import { useCallback, useContext, useEffect, useRef, useState } from 'react';
9
5
  import { authenticateOAuthSignInSession } from '../modules/_helpers';
6
+ import { loadGoogleIdentityServices } from '../utils/googleIdentity';
10
7
 
11
8
  /**
12
9
  * Types
@@ -133,9 +130,7 @@ function useGoogleLogin(p: GoogleLoginHookParams) {
133
130
  useEffect(() => {
134
131
  if (scriptLoaded) {
135
132
  // 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({
133
+ const client = (globalThis as any).google?.accounts?.oauth2.initTokenClient({
139
134
  client_id: getENVVariable('GOOGLE_OAUTH'),
140
135
  scope: overrideScope ? scope : `openid profile email ${scope}`,
141
136
  callback: async (response: any) => {
@@ -155,8 +150,7 @@ function useGoogleLogin(p: GoogleLoginHookParams) {
155
150
  formPublicId: formPublicIdRef.current,
156
151
  authenticateOnly: authenticateOnlyRef.current,
157
152
  };
158
- const { auth, error } =
159
- await authenticateOAuthSignInSession(variables);
153
+ const { auth, error } = await authenticateOAuthSignInSession(variables);
160
154
  if (error) {
161
155
  setWaitingForOAuth(false);
162
156
  if (!doNotAlertErrorsRef.current) {
@@ -195,12 +189,7 @@ function useGoogleLogin(p: GoogleLoginHookParams) {
195
189
  }, [scriptLoaded, scope, state]);
196
190
 
197
191
  const onInitiateGoogleSignIn = useCallback(
198
- (
199
- overrideConfig?: object,
200
- ssoConnectionId?: string | null,
201
- formPublicId?: string | null,
202
- authenticateOnly?: boolean,
203
- ) => {
192
+ (overrideConfig?: object, ssoConnectionId?: string | null, formPublicId?: string | null, authenticateOnly?: boolean) => {
204
193
  ssoConnectionIdRef.current = ssoConnectionId || null;
205
194
  formPublicIdRef.current = formPublicId || null;
206
195
  authenticateOnlyRef.current = !!authenticateOnly;
@@ -233,32 +222,26 @@ export function useContinueWithGoogle(params: ContinueWithGoogleParams) {
233
222
  const [scriptLoaded, setScriptLoaded] = useState(false);
234
223
 
235
224
  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);
225
+ let active = true;
226
+ loadGoogleIdentityServices().then(
227
+ () => {
228
+ if (active) setScriptLoaded(true);
229
+ },
230
+ () => {
231
+ if (active) setScriptLoaded(false);
232
+ },
233
+ );
250
234
  return () => {
251
- document.body.removeChild(scriptTag);
235
+ active = false;
252
236
  };
253
237
  }, []);
254
238
 
255
- const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } =
256
- useGoogleLogin({
257
- doNotAlertErrors,
258
- onFinishSignIn,
259
- onRespondentToken,
260
- scriptLoaded,
261
- });
239
+ const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } = useGoogleLogin({
240
+ doNotAlertErrors,
241
+ onFinishSignIn,
242
+ onRespondentToken,
243
+ scriptLoaded,
244
+ });
262
245
 
263
246
  return {
264
247
  oauthButtonDisabled,
@@ -306,8 +289,7 @@ function getMSALClient() {
306
289
  */
307
290
 
308
291
  export function useContinueWithMicrosoft(params: ContinueWithMicrosoftParams) {
309
- const { doNotAlertErrors, onFinishSignIn, onRespondentToken, onError } =
310
- params;
292
+ const { doNotAlertErrors, onFinishSignIn, onRespondentToken, onError } = params;
311
293
  const { dispatchApp } = useContext(AppContext);
312
294
  const openModalPopUp = useOpenModalPopUp();
313
295
  const [waitingForPopUp, setWaitingForPopUp] = useState(false);
@@ -332,12 +314,7 @@ export function useContinueWithMicrosoft(params: ContinueWithMicrosoftParams) {
332
314
  dispatchAppRef.current = dispatchApp;
333
315
 
334
316
  const onInitiateMicrosoftSignIn = useCallback(
335
- async (
336
- ssoOption?: SsoLoginOptionData | any,
337
- loginHint?: string,
338
- formPublicId?: string | null,
339
- authenticateOnly?: boolean,
340
- ) => {
317
+ async (ssoOption?: SsoLoginOptionData | any, loginHint?: string, formPublicId?: string | null, authenticateOnly?: boolean) => {
341
318
  setWaitingForPopUp(true);
342
319
 
343
320
  // A plain onClick passes the click event here; only a real SSO option
@@ -351,9 +328,7 @@ export function useContinueWithMicrosoft(params: ContinueWithMicrosoftParams) {
351
328
  scopes: ['openid', 'profile', 'email'],
352
329
  prompt: 'select_account',
353
330
  // Pin the popup to the org's Entra tenant instead of "common"
354
- ...(ssoTenantId
355
- ? { authority: `https://login.microsoftonline.com/${ssoTenantId}` }
356
- : null),
331
+ ...(ssoTenantId ? { authority: `https://login.microsoftonline.com/${ssoTenantId}` } : null),
357
332
  ...(loginHint ? { loginHint } : null),
358
333
  });
359
334
 
@@ -366,8 +341,7 @@ export function useContinueWithMicrosoft(params: ContinueWithMicrosoftParams) {
366
341
  formPublicId,
367
342
  authenticateOnly,
368
343
  };
369
- const authentication =
370
- await authenticateOAuthSignInSession(variables);
344
+ const authentication = await authenticateOAuthSignInSession(variables);
371
345
  if (authentication.error) {
372
346
  setWaitingForOAuth(false);
373
347
  if (!doNotAlertErrorsRef.current) {
package/src/main.ts CHANGED
@@ -1,4 +1,14 @@
1
+ export * from './hooks/use-auth-popup';
1
2
  export * from './hooks/use-oauth';
3
+ export * from './hooks/use-google-one-tap';
4
+ export { suppressGoogleAutoSignIn } from './utils/googleIdentity';
5
+ export {
6
+ getAuthReturnQuery,
7
+ getAuthReturnContext,
8
+ getPublicFormReturnContext,
9
+ hydrateAuthenticationSession,
10
+ persistSignInSession,
11
+ } from './modules/_helpers';
2
12
  export * from './modules/AssignRequiredAuth';
3
13
  export * from './modules/AuthForms';
4
14
  export * from './modules/AuthFormUI';
@@ -8,3 +18,4 @@ export * from './modules/ManagedSessions';
8
18
  export * from './modules/OtherAuthButtons';
9
19
  export * from './modules/schemas';
10
20
  export * from './ui/ManagedSessionUI';
21
+ export * from './utils/authPopup';