@jsb188/auth-web 1.1.10 → 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.
@@ -11,99 +11,105 @@ import { type ManagedSessionListItem, ManagedSessionListUI } from '../ui/Managed
11
11
  * Format one managed-session timestamp for the current browser locale.
12
12
  */
13
13
  function formatManagedSessionDate(value?: string | null) {
14
- const date = value ? new Date(value) : null;
15
- return date && !isNaN(date.getTime()) ? date.toLocaleString() : '-';
14
+ const date = value ? new Date(value) : null;
15
+ return date && !isNaN(date.getTime()) ? date.toLocaleString() : '-';
16
16
  }
17
17
 
18
18
  /*
19
19
  * Convert server session rows into display-ready immutable list items.
20
20
  */
21
21
  export function mapManagedSessionItems(sessions?: AccountSessionData[] | null): ManagedSessionListItem[] {
22
- return (sessions || [])
23
- .filter((session) => !session.revokedAt)
24
- .map((session) => ({
25
- ...session,
26
- displayName: session.deviceName || session.userAgent || i18n.t('account.session_unknown_device'),
27
- displayExpiresAt: formatManagedSessionDate(session.absoluteExpiresAt),
28
- displayLastActivityAt: formatManagedSessionDate(session.lastActivityAt),
29
- }))
30
- .sort((a, b) => Number(b.current) - Number(a.current) || new Date(b.lastActivityAt).getTime() - new Date(a.lastActivityAt).getTime());
22
+ if (!sessions?.length) return [];
23
+ return sessions
24
+ .filter((session) => !session.revokedAt)
25
+ .map((session) => ({
26
+ ...session,
27
+ displayName: session.deviceName || session.userAgent || i18n.t('account.session_unknown_device'),
28
+ displayExpiresAt: formatManagedSessionDate(session.absoluteExpiresAt),
29
+ displayLastActivityAt: formatManagedSessionDate(session.lastActivityAt),
30
+ }))
31
+ .sort(
32
+ (a, b) => Number(b.current) - Number(a.current) || new Date(b.lastActivityAt).getTime() - new Date(a.lastActivityAt).getTime(),
33
+ );
31
34
  }
32
35
 
33
36
  /*
34
37
  * Load and manage the current account's active device sessions.
35
38
  */
36
39
  export function ManagedSessions() {
37
- const { accountSessions, loading } = useMyAccountSessions();
38
- const [savingSessionId, setSavingSessionId] = useState<string | null>(null);
39
- const [revokedSessionIds, setRevokedSessionIds] = useState<Set<string>>(() => new Set());
40
- const [hideOtherSessions, setHideOtherSessions] = useState(false);
41
- const { revokeMyAccountSession } = useRevokeMyAccountSession({
42
- onCompleted: (data, _error, variables) => {
43
- if (data?.revokeMyAccountSession && variables?.sessionId) {
44
- setRevokedSessionIds((current) => new Set(current).add(variables.sessionId));
45
- }
46
- setSavingSessionId(null);
47
- },
48
- onError: () => setSavingSessionId(null),
49
- });
50
- const { revokeMyOtherAccountSessions, saving: savingOthers } = useRevokeMyOtherAccountSessions({
51
- onCompleted: (data) => {
52
- if (data?.revokeMyOtherAccountSessions) {
53
- setHideOtherSessions(true);
54
- }
55
- },
56
- });
57
- const items = useMemo(
58
- () => mapManagedSessionItems(accountSessions).filter((session) => !revokedSessionIds.has(session.id) && (!hideOtherSessions || session.current)),
59
- [accountSessions, hideOtherSessions, revokedSessionIds],
60
- );
40
+ const { accountSessions, loading } = useMyAccountSessions();
41
+ const [savingSessionId, setSavingSessionId] = useState<string | null>(null);
42
+ const [revokedSessionIds, setRevokedSessionIds] = useState<Set<string>>(() => new Set());
43
+ const [hideOtherSessions, setHideOtherSessions] = useState(false);
44
+ const { revokeMyAccountSession } = useRevokeMyAccountSession({
45
+ onCompleted: (data, _error, variables) => {
46
+ if (data?.revokeMyAccountSession && variables?.sessionId) {
47
+ setRevokedSessionIds((current) => new Set(current).add(variables.sessionId));
48
+ }
49
+ setSavingSessionId(null);
50
+ },
51
+ onError: () => setSavingSessionId(null),
52
+ });
53
+ const { revokeMyOtherAccountSessions, saving: savingOthers } = useRevokeMyOtherAccountSessions({
54
+ onCompleted: (data) => {
55
+ if (data?.revokeMyOtherAccountSessions) {
56
+ setHideOtherSessions(true);
57
+ }
58
+ },
59
+ });
60
+ const items = useMemo(
61
+ () =>
62
+ mapManagedSessionItems(accountSessions).filter(
63
+ (session) => !revokedSessionIds.has(session.id) && (!hideOtherSessions || session.current),
64
+ ),
65
+ [accountSessions, hideOtherSessions, revokedSessionIds],
66
+ );
61
67
 
62
- /*
63
- * Revoke one selected managed session.
64
- */
65
- const onRevokeSession = (sessionId: string) => {
66
- setSavingSessionId(sessionId);
67
- revokeMyAccountSession({
68
- variables: {
69
- sessionId,
70
- },
71
- });
72
- };
68
+ /*
69
+ * Revoke one selected managed session.
70
+ */
71
+ const onRevokeSession = (sessionId: string) => {
72
+ setSavingSessionId(sessionId);
73
+ revokeMyAccountSession({
74
+ variables: {
75
+ sessionId,
76
+ },
77
+ });
78
+ };
73
79
 
74
- if (loading && !accountSessions) {
75
- return (
76
- <div className='h_160 v_center'>
77
- <BigLoading />
78
- </div>
79
- );
80
- }
80
+ if (loading && !accountSessions) {
81
+ return (
82
+ <div className='h_160 v_center'>
83
+ <BigLoading />
84
+ </div>
85
+ );
86
+ }
81
87
 
82
- return (
83
- <div className='max_w_600'>
84
- <p className='cl_lt mb_sm'>{i18n.t('account.sessions_desc')}</p>
85
- <ManagedSessionListUI
86
- items={items}
87
- emptyText={i18n.t('account.session_none')}
88
- revokeText={i18n.t('account.session_sign_out')}
89
- currentText={i18n.t('account.session_current')}
90
- expiresText={i18n.t('account.session_expires')}
91
- lastActiveText={i18n.t('account.session_last_active')}
92
- savingSessionId={savingSessionId}
93
- onRevoke={onRevokeSession}
94
- />
95
- {items.length <= 1 ? null : (
96
- <FullWidthButton
97
- fullWidth={false}
98
- className='mt_md'
99
- preset='outline'
100
- loading={savingOthers}
101
- disabled={savingOthers}
102
- onClick={() => revokeMyOtherAccountSessions()}
103
- >
104
- {i18n.t('account.session_sign_out_others')}
105
- </FullWidthButton>
106
- )}
107
- </div>
108
- );
88
+ return (
89
+ <div className='max_w_600'>
90
+ <p className='cl_lt mb_sm'>{i18n.t('account.sessions_desc')}</p>
91
+ <ManagedSessionListUI
92
+ items={items}
93
+ emptyText={i18n.t('account.session_none')}
94
+ revokeText={i18n.t('account.session_sign_out')}
95
+ currentText={i18n.t('account.session_current')}
96
+ expiresText={i18n.t('account.session_expires')}
97
+ lastActiveText={i18n.t('account.session_last_active')}
98
+ savingSessionId={savingSessionId}
99
+ onRevoke={onRevokeSession}
100
+ />
101
+ {items.length <= 1 ? null : (
102
+ <FullWidthButton
103
+ fullWidth={false}
104
+ className='mt_md'
105
+ preset='outline'
106
+ loading={savingOthers}
107
+ disabled={savingOthers}
108
+ onClick={() => revokeMyOtherAccountSessions()}
109
+ >
110
+ {i18n.t('account.session_sign_out_others')}
111
+ </FullWidthButton>
112
+ )}
113
+ </div>
114
+ );
109
115
  }
@@ -2,18 +2,19 @@ import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import { FullWidthButton } from '@jsb188/react-web/ui/Button';
3
3
  import { useCallback } from 'react';
4
4
  import {
5
- type OnFinishSignInFn,
6
- useContinueWithGoogle,
7
- useContinueWithMicrosoft,
5
+ type OnFinishSignInFn,
6
+ useContinueWithGoogle,
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
- formPublicId?: string | null;
12
- onFinishSignIn: OnFinishSignInFn;
12
+ formPublicId?: string | null;
13
+ onFinishSignIn: OnFinishSignInFn;
13
14
  }
14
15
 
15
16
  interface AuthMethodButtonProps {
16
- onClickButton: () => void;
17
+ onClickButton: () => void;
17
18
  }
18
19
 
19
20
  /**
@@ -21,28 +22,29 @@ interface AuthMethodButtonProps {
21
22
  */
22
23
 
23
24
  export const ContinueWithGoogle = (p: OAuthButtonProps) => {
24
- const { onFinishSignIn, formPublicId } = p;
25
- const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } = useContinueWithGoogle({
26
- onFinishSignIn
27
- });
25
+ const { onFinishSignIn, formPublicId } = p;
26
+ const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } =
27
+ useContinueWithGoogle({
28
+ onFinishSignIn,
29
+ });
28
30
 
29
- /* Launch Google OAuth with the current public-form context. */
30
- const onClick = useCallback(() => {
31
- onInitiateGoogleSignIn(undefined, null, formPublicId ?? null);
32
- }, [formPublicId, onInitiateGoogleSignIn]);
31
+ /* Launch Google OAuth with the current public-form context. */
32
+ const onClick = useCallback(() => {
33
+ onInitiateGoogleSignIn(undefined, null, formPublicId ?? null);
34
+ }, [formPublicId, onInitiateGoogleSignIn]);
33
35
 
34
- return (
35
- <FullWidthButton
36
- disabled={oauthButtonDisabled}
37
- loading={waitingForOAuth}
38
- onClick={onClick}
39
- preset='em'
40
- className='mb_sm'
41
- iconName='brand-google-color'
42
- >
43
- {i18n.t('auth.continue_with_google')}
44
- </FullWidthButton>
45
- );
36
+ return (
37
+ <FullWidthButton
38
+ disabled={oauthButtonDisabled}
39
+ loading={waitingForOAuth}
40
+ onClick={onClick}
41
+ preset="em"
42
+ className="mb_sm"
43
+ iconName="brand-google-color"
44
+ >
45
+ {i18n.t('auth.continue_with_google')}
46
+ </FullWidthButton>
47
+ );
46
48
  };
47
49
 
48
50
  /**
@@ -50,28 +52,29 @@ export const ContinueWithGoogle = (p: OAuthButtonProps) => {
50
52
  */
51
53
 
52
54
  export const ContinueWithMicrosoft = (p: OAuthButtonProps) => {
53
- const { onFinishSignIn, formPublicId } = p;
54
- const { onInitiateMicrosoftSignIn, oauthButtonDisabled, waitingForOAuth } = useContinueWithMicrosoft({
55
- onFinishSignIn
56
- });
55
+ const { onFinishSignIn, formPublicId } = p;
56
+ const { onInitiateMicrosoftSignIn, oauthButtonDisabled, waitingForOAuth } =
57
+ useContinueWithMicrosoft({
58
+ onFinishSignIn,
59
+ });
57
60
 
58
- /* Launch Microsoft OAuth with the current public-form context. */
59
- const onClick = useCallback(() => {
60
- onInitiateMicrosoftSignIn(undefined, undefined, formPublicId ?? null);
61
- }, [formPublicId, onInitiateMicrosoftSignIn]);
61
+ /* Launch Microsoft OAuth with the current public-form context. */
62
+ const onClick = useCallback(() => {
63
+ onInitiateMicrosoftSignIn(undefined, undefined, formPublicId ?? null);
64
+ }, [formPublicId, onInitiateMicrosoftSignIn]);
62
65
 
63
- return (
64
- <FullWidthButton
65
- disabled={oauthButtonDisabled}
66
- loading={waitingForOAuth}
67
- onClick={onClick}
68
- preset='em'
69
- className='mb_sm'
70
- iconName='brand-microsoft-color'
71
- >
72
- {i18n.t('auth.continue_with_microsoft')}
73
- </FullWidthButton>
74
- );
66
+ return (
67
+ <FullWidthButton
68
+ disabled={oauthButtonDisabled}
69
+ loading={waitingForOAuth}
70
+ onClick={onClick}
71
+ preset="em"
72
+ className="mb_sm"
73
+ iconName="brand-microsoft-color"
74
+ >
75
+ {i18n.t('auth.continue_with_microsoft')}
76
+ </FullWidthButton>
77
+ );
75
78
  };
76
79
 
77
80
  /**
@@ -79,18 +82,19 @@ export const ContinueWithMicrosoft = (p: OAuthButtonProps) => {
79
82
  */
80
83
 
81
84
  export const ContinueWithSso = (p: AuthMethodButtonProps) => {
82
- const { onClickButton } = p;
85
+ const { onClickButton } = p;
83
86
  return (
84
87
  <FullWidthButton
85
88
  onClick={onClickButton}
86
- preset='em'
87
- className='mb_sm'
88
- iconName='buildings-2-color'
89
- iconClassName='ft_md shift_up'
90
- >
91
- {i18n.t('auth.continue_with_sso')}
92
- </FullWidthButton>
93
- );
89
+ preset="em"
90
+ className="mb_sm"
91
+ iconName={COMMON_ICON_NAMES.enterprise_signin}
92
+ iconClassName="ft_md shift_up"
93
+ tryColor
94
+ >
95
+ {i18n.t('auth.continue_with_sso')}
96
+ </FullWidthButton>
97
+ );
94
98
  };
95
99
 
96
100
  /**
@@ -98,17 +102,17 @@ export const ContinueWithSso = (p: AuthMethodButtonProps) => {
98
102
  */
99
103
 
100
104
  export const ContinueWithPhone = (p: AuthMethodButtonProps) => {
101
- const { onClickButton } = p;
102
- return (
103
- <FullWidthButton
104
- onClick={onClickButton}
105
- preset='em'
106
- className='mb_sm'
107
- iconName='phone-circle'
108
- iconClassName='ft_md shift_up'
109
- tryColor
110
- >
111
- {i18n.t('auth.continue_with_phone')}
112
- </FullWidthButton>
113
- );
105
+ const { onClickButton } = p;
106
+ return (
107
+ <FullWidthButton
108
+ onClick={onClickButton}
109
+ preset="em"
110
+ className="mb_sm"
111
+ iconName="phone-circle"
112
+ iconClassName="ft_md shift_up"
113
+ tryColor
114
+ >
115
+ {i18n.t('auth.continue_with_phone')}
116
+ </FullWidthButton>
117
+ );
114
118
  };
@@ -1,4 +1,5 @@
1
1
  import { runWithAuthSessionBrowserLock } from '@jsb188/app/utils/authSession.ts';
2
+ import { clearGoogleAutoSignInSuppression } from '../utils/googleIdentity';
2
3
 
3
4
  /**
4
5
  * Types
@@ -7,61 +8,96 @@ import { runWithAuthSessionBrowserLock } from '@jsb188/app/utils/authSession.ts'
7
8
  export type AuthPageName = 'signin' | 'signin_success' | 'signup' | 'signup_success' | 'reset_password' | 'welcome';
8
9
 
9
10
  export type OAuthSessionAuthenticationInput = {
10
- provider: 'GOOGLE' | 'MICROSOFT';
11
- oauthToken?: string | null;
12
- idToken?: string | null;
13
- ssoConnectionId?: string | null;
14
- formPublicId?: string | null;
15
- authenticateOnly?: boolean;
11
+ provider: 'GOOGLE' | 'MICROSOFT';
12
+ oauthToken?: string | null;
13
+ idToken?: string | null;
14
+ ssoConnectionId?: string | null;
15
+ formPublicId?: string | null;
16
+ authenticateOnly?: boolean;
16
17
  };
17
18
 
18
19
  export type OAuthSessionAuthenticationResult = {
19
- auth: any | null;
20
- error: any | null;
20
+ auth: any | null;
21
+ error: any | null;
22
+ };
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',
21
36
  };
22
37
 
23
38
  /**
24
39
  * Helper; get route path
25
40
  */
26
41
 
27
- export function getAuthRoute(
28
- pageName: AuthPageName,
29
- authRoutesMap?: Record<AuthPageName, string>,
30
- queryStr?: string
31
- ) {
32
- const defaultAuthRoutesMap: Record<AuthPageName, string> = {
33
- signin: '/auth/signin',
34
- signin_success: '/auth/success',
35
- signup: '/auth/signup',
36
- signup_success: '/auth/signup-finished',
37
- reset_password: '/auth/reset-password',
38
- welcome: '/auth/welcome',
39
- };
40
-
41
- const pathname = authRoutesMap?.[pageName] || defaultAuthRoutesMap[pageName] || 'auth';
42
- return queryStr ? `${pathname}?${queryStr}` : pathname;
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,
62
+ };
63
+ }
64
+
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
+ };
43
79
  }
44
80
 
45
81
  /*
46
82
  * Post one login credential to the same-origin HttpOnly-cookie endpoint.
47
83
  */
48
84
  async function postSignInSessionCredential(name: 'bootstrapToken' | 'token', value: string): Promise<boolean> {
49
- try {
50
- const response = await fetch('/auth/session', {
51
- method: 'POST',
52
- credentials: 'same-origin',
53
- headers: {
54
- 'Content-Type': 'application/x-www-form-urlencoded',
55
- },
56
- body: new URLSearchParams({
57
- [name]: value,
58
- managedSessionVersion: '1',
59
- }),
60
- });
61
- return response.ok;
62
- } catch {
63
- return false;
64
- }
85
+ try {
86
+ const response = await fetch('/auth/session', {
87
+ method: 'POST',
88
+ credentials: 'same-origin',
89
+ headers: {
90
+ 'Content-Type': 'application/x-www-form-urlencoded',
91
+ },
92
+ body: new URLSearchParams({
93
+ [name]: value,
94
+ managedSessionVersion: '1',
95
+ }),
96
+ });
97
+ return response.ok;
98
+ } catch {
99
+ return false;
100
+ }
65
101
  }
66
102
 
67
103
  /*
@@ -69,57 +105,96 @@ async function postSignInSessionCredential(name: 'bootstrapToken' | 'token', val
69
105
  * atomically persist the resulting HttpOnly managed-session cookie.
70
106
  */
71
107
  export async function authenticateOAuthSignInSession(
72
- input: OAuthSessionAuthenticationInput,
108
+ input: OAuthSessionAuthenticationInput,
109
+ signal?: AbortSignal,
73
110
  ): Promise<OAuthSessionAuthenticationResult> {
74
- if (typeof fetch !== 'function') {
75
- return { auth: null, error: { errorCode: 'network_error' } };
76
- }
77
-
78
- try {
79
- return await runWithAuthSessionBrowserLock(async () => {
80
- const body = new URLSearchParams({
81
- provider: input.provider,
82
- managedSessionVersion: '1',
83
- ...(input.oauthToken ? { oauthToken: input.oauthToken } : {}),
84
- ...(input.idToken ? { idToken: input.idToken } : {}),
85
- ...(input.ssoConnectionId ? { ssoConnectionId: input.ssoConnectionId } : {}),
86
- ...(input.formPublicId ? { formPublicId: input.formPublicId } : {}),
87
- ...(input.authenticateOnly ? { authenticateOnly: '1' } : {}),
88
- });
89
- const response = await fetch('/auth/session', {
90
- method: 'POST',
91
- credentials: 'same-origin',
92
- headers: {
93
- 'Content-Type': 'application/x-www-form-urlencoded',
94
- },
95
- body,
96
- });
97
- const result = await response.json().catch(() => null);
98
- if (!response.ok || !result?.ok) {
99
- return {
100
- auth: null,
101
- error: result?.error || { errorCode: 'network_error' },
102
- };
103
- }
104
- return { auth: result.auth || null, error: null };
105
- });
106
- } catch {
107
- return { auth: null, error: { errorCode: 'network_error' } };
108
- }
111
+ if (typeof fetch !== 'function') {
112
+ return { auth: null, error: { errorCode: 'network_error' } };
113
+ }
114
+
115
+ try {
116
+ return await runWithAuthSessionBrowserLock(async () => {
117
+ signal?.throwIfAborted();
118
+ const body = new URLSearchParams({
119
+ provider: input.provider,
120
+ managedSessionVersion: '1',
121
+ ...(input.oauthToken ? { oauthToken: input.oauthToken } : {}),
122
+ ...(input.idToken ? { idToken: input.idToken } : {}),
123
+ ...(input.ssoConnectionId ? { ssoConnectionId: input.ssoConnectionId } : {}),
124
+ ...(input.formPublicId ? { formPublicId: input.formPublicId } : {}),
125
+ ...(input.authenticateOnly ? { authenticateOnly: '1' } : {}),
126
+ });
127
+ const response = await fetch('/auth/session', {
128
+ signal,
129
+ method: 'POST',
130
+ credentials: 'same-origin',
131
+ headers: {
132
+ 'Content-Type': 'application/x-www-form-urlencoded',
133
+ },
134
+ body,
135
+ });
136
+ const result = await response.json().catch(() => null);
137
+ if (!response.ok || !result?.ok) {
138
+ return {
139
+ auth: null,
140
+ error: result?.error || { errorCode: 'network_error' },
141
+ };
142
+ }
143
+ if (input.provider === 'GOOGLE' && (result.auth?.account?.id || result.auth?.respondentToken)) {
144
+ clearGoogleAutoSignInSuppression();
145
+ }
146
+ return { auth: result.auth || null, error: null };
147
+ });
148
+ } catch {
149
+ return { auth: null, error: { errorCode: 'network_error' } };
150
+ }
151
+ }
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
+ }
109
184
  }
110
185
 
111
186
  /*
112
187
  * Persist an OAuth or phone login before navigating without a bearer-token query.
113
188
  */
114
189
  export async function persistSignInSession(token: string, bootstrapToken?: string | null): Promise<boolean> {
115
- if (typeof fetch !== 'function' || (!token && !bootstrapToken)) {
116
- return false;
117
- }
118
-
119
- return await runWithAuthSessionBrowserLock(async () => {
120
- if (bootstrapToken && await postSignInSessionCredential('bootstrapToken', bootstrapToken)) {
121
- return true;
122
- }
123
- return token ? await postSignInSessionCredential('token', token) : false;
124
- });
190
+ if (typeof fetch !== 'function' || (!token && !bootstrapToken)) {
191
+ return false;
192
+ }
193
+
194
+ return await runWithAuthSessionBrowserLock(async () => {
195
+ if (bootstrapToken && (await postSignInSessionCredential('bootstrapToken', bootstrapToken))) {
196
+ return true;
197
+ }
198
+ return token ? await postSignInSessionCredential('token', token) : false;
199
+ });
125
200
  }