@jsb188/auth-web 1.1.3 → 1.1.10

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.
@@ -1,9 +1,24 @@
1
- import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
2
- import type { ErrorMessageProps } from '@jsb188/react-web/ui/Layout';
3
- import { FullPageLayout, ErrorMessage } from '@jsb188/react-web/ui/Layout';
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d.ts';
3
+ import type { ErrorMessageProps } from '@jsb188/react-web/modules/layout/MainLayout';
4
+ import { AppContentArea, ErrorMessage, FullPageLayout } from '@jsb188/react-web/modules/layout/MainLayout';
4
5
  import { BigLoading } from '@jsb188/react-web/ui/Loading';
5
6
  import { useIsLoggedIn } from '@jsb188/react/states';
6
- import i18n from '@jsb188/app/i18n';
7
+
8
+ /**
9
+ * Auth gate; loading
10
+ */
11
+
12
+ function AuthGateLoading({ message }: { message?: string }) {
13
+ return <>
14
+ <BigLoading color='active' />
15
+ {message && (
16
+ <p className='mt_df cl_md'>
17
+ {message}
18
+ </p>
19
+ )}
20
+ </>
21
+ }
7
22
 
8
23
  /**
9
24
  * Loading or Error interface
@@ -11,8 +26,10 @@ import i18n from '@jsb188/app/i18n';
11
26
 
12
27
  interface AuthGateProps extends ErrorMessageProps {
13
28
  children: React.ReactNode;
29
+ notLayout?: boolean;
14
30
  connectedToServer?: boolean;
15
31
  notReady?: boolean;
32
+ appLoading?: boolean; // Only used if `notLayout=true`
16
33
  loading?: boolean;
17
34
  loadingMessage?: string;
18
35
  defaultErrorMessage?: string;
@@ -20,22 +37,38 @@ interface AuthGateProps extends ErrorMessageProps {
20
37
  }
21
38
 
22
39
  export function AuthGate(p: AuthGateProps) {
23
- const { notReady, loading, loadingMessage, defaultErrorMessage, error, children, connectedToServer, ...other } = p;
40
+ const { notReady, appLoading, loading, loadingMessage, defaultErrorMessage, error, children, notLayout, connectedToServer, ...other } = p;
24
41
  const isLoggedIn = useIsLoggedIn();
25
42
  const isNetworkError = (error as ServerErrorObj)?.errorCode === 'network_error';
43
+ const isAuthLoading = loading && !isLoggedIn;
44
+ const shouldRender = isLoggedIn && !notReady && !error;
26
45
 
27
- if (isLoggedIn && !notReady) {
46
+ if (
47
+ shouldRender ||
48
+ ((isAuthLoading || notReady) && notLayout)
49
+ ) {
50
+ if (notLayout) {
51
+ // The loading element needs to be absolute for `notLayout=true`
52
+ // NOTE: Obviously if `appLoading=true`, then this will hide the actual content forever.
53
+ // This was done intentionally-- if the route is using this feature, the route has to turn off the loading state manually from inside the route.
54
+ return <>
55
+ {appLoading &&
56
+ <div className='abs_full v_center bg z6'>
57
+ <AuthGateLoading message={loadingMessage} />
58
+ </div>}
59
+ {shouldRender ? children : null}
60
+ </>;
61
+ }
62
+
63
+ // ONLY return this if `notLayout=false`
28
64
  return children;
29
65
  }
30
66
 
31
- if (notReady || (loading && !isLoggedIn)) {
67
+ if (notReady || isAuthLoading) {
68
+ // If `notLayout=true` this code block should NEVER happen
69
+ // There should be no need to do `noLayout` check here because it should be caught above
32
70
  return <FullPageLayout>
33
- <BigLoading color='active' />
34
- {loadingMessage && (
35
- <p className='mt_df cl_md'>
36
- {loadingMessage}
37
- </p>
38
- )}
71
+ <AuthGateLoading message={loadingMessage} />
39
72
  </FullPageLayout>;
40
73
  }
41
74
 
@@ -50,22 +83,33 @@ export function AuthGate(p: AuthGateProps) {
50
83
  // {connectedToServer} is currently always true, passed down from graphql hooks.
51
84
  // This is a placeholder logic, and must properly return a real network state in the future.
52
85
 
53
- let errorMessage;
86
+ let errorCode, errorMessage;
54
87
  if (error?.message) {
55
88
  errorMessage = error.message;
56
- } else if (isNetworkError || !connectedToServer) {
89
+ } else if (isNetworkError || (!connectedToServer && isLoggedIn)) {
90
+ errorCode = 'network_error';
57
91
  errorMessage = i18n.t('error.network_error');
58
92
  } else if (!isLoggedIn) {
93
+ errorCode = '20019';
59
94
  errorMessage = i18n.t('error.20019');
60
95
  } else {
61
96
  errorMessage = defaultErrorMessage;
62
97
  }
63
98
 
99
+ const errorProps = {
100
+ ...error,
101
+ ...other,
102
+ errorCode,
103
+ message: errorMessage
104
+ };
105
+
106
+ if (notLayout) {
107
+ return <AppContentArea className='v_center pb_xl'>
108
+ <ErrorMessage {...errorProps} />
109
+ </AppContentArea>;
110
+ }
111
+
64
112
  return <FullPageLayout>
65
- <ErrorMessage
66
- message={errorMessage}
67
- {...error}
68
- {...other}
69
- />
113
+ <ErrorMessage {...errorProps} />
70
114
  </FullPageLayout>;
71
115
  }
@@ -0,0 +1,148 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { useCurrentAccount } from '@jsb188/react/states';
3
+ import { AvatarImg } from '@jsb188/react-web/ui/Avatar';
4
+ import { PageFormHeaderOAuthButton } from '@jsb188/react-web/ui/PageFormUI';
5
+ import { TextWithLinks } from '@jsb188/react-web/ui/Markdown';
6
+ import { memo, useCallback, type ReactNode } from 'react';
7
+ import { useContinueWithGoogle, useContinueWithMicrosoft } from '../hooks/use-oauth';
8
+
9
+ /**
10
+ * Types
11
+ */
12
+
13
+ interface InlineAuthFormProps {
14
+ // Sign-in button labels; a null/absent label hides that provider's button
15
+ googleLabel?: string | null;
16
+ microsoftLabel?: string | null;
17
+ // Verified email of a temporary (account-less) respondent token holder; shown
18
+ // as the identity when there is no signed-in account
19
+ respondentEmail?: string | null;
20
+ // Respondent status / helper text shown next to the buttons; a plain string
21
+ // is parsed for inline links, a node is rendered as-is
22
+ accountMessage?: ReactNode;
23
+ // When true, an OAuth-verified email with no account does not error; the
24
+ // server returns a temporary respondent token (ANYONE web forms)
25
+ authenticateOnly?: boolean;
26
+ // Public web form context (contact-gated account creation / respondent token)
27
+ formPublicId?: string | null;
28
+ // Called after a real account sign-in flips the app into a logged-in state,
29
+ // with the fresh auth token (e.g. to silently persist the SSR session cookie)
30
+ onSignedIn?: (
31
+ token: string,
32
+ sessionBootstrapToken?: string | null,
33
+ sessionPersisted?: boolean,
34
+ ) => boolean | Promise<boolean>;
35
+ // Called when authenticateOnly returned a temporary form respondent token
36
+ onRespondentToken?: (token: string, email: string | null) => void;
37
+ }
38
+
39
+ /*
40
+ * Inline Google/Microsoft sign-in that keeps the user on the current page.
41
+ * The OAuth popup authenticates the user and the underlying hooks flip the
42
+ * shared app state to logged-in (via onAccountLogin) with no navigation.
43
+ * ANYONE web forms may pass authenticateOnly to accept account-less
44
+ * respondents via a temporary token instead of forcing account creation.
45
+ */
46
+
47
+ const InlineAuthForm = (p: InlineAuthFormProps) => {
48
+ const {
49
+ googleLabel,
50
+ microsoftLabel,
51
+ respondentEmail,
52
+ accountMessage,
53
+ authenticateOnly,
54
+ formPublicId,
55
+ onSignedIn,
56
+ onRespondentToken,
57
+ } = p;
58
+
59
+ // A signed-in account takes precedence; otherwise a temporary respondent
60
+ // token holder is identified by their verified email
61
+ const { isLoggedIn, displayName, labelName } = useCurrentAccount();
62
+ const signedInName = isLoggedIn
63
+ ? (displayName || labelName)
64
+ : (respondentEmail || null);
65
+
66
+ /*
67
+ * A real account sign-in already applied the logged-in app state; hand the
68
+ * token to the caller for any follow-up (e.g. persisting the session cookie).
69
+ */
70
+ const onFinishSignIn = useCallback(
71
+ (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) =>
72
+ onSignedIn?.(token, sessionBootstrapToken, sessionPersisted) ?? false,
73
+ [onSignedIn],
74
+ );
75
+
76
+ const {
77
+ onInitiateGoogleSignIn,
78
+ oauthButtonDisabled: googleDisabled,
79
+ waitingForOAuth: googleLoading,
80
+ } =
81
+ useContinueWithGoogle({ onFinishSignIn, onRespondentToken });
82
+ const {
83
+ onInitiateMicrosoftSignIn,
84
+ oauthButtonDisabled: microsoftDisabled,
85
+ waitingForOAuth: microsoftLoading,
86
+ } =
87
+ useContinueWithMicrosoft({ onFinishSignIn, onRespondentToken });
88
+
89
+ const onGoogle = useCallback(() => {
90
+ onInitiateGoogleSignIn(undefined, null, formPublicId ?? null, authenticateOnly);
91
+ }, [onInitiateGoogleSignIn, formPublicId, authenticateOnly]);
92
+
93
+ const onMicrosoft = useCallback(() => {
94
+ onInitiateMicrosoftSignIn(undefined, undefined, formPublicId ?? null, authenticateOnly);
95
+ }, [onInitiateMicrosoftSignIn, formPublicId, authenticateOnly]);
96
+
97
+ return (
98
+ <div className='h_item gap_sm min_w_0 f_wrap rel'>
99
+ {signedInName ? (
100
+ <div className='h_item gap_8 min_w_0'>
101
+ <AvatarImg
102
+ className='shift_up'
103
+ displayName={signedInName}
104
+ size='small'
105
+ letterBackgroundClassName='bd_2 bd_lt bg'
106
+ />
107
+ <p className='ft_medium'>
108
+ {i18n.t('auth.logged_in_as_', { name: signedInName })}
109
+ </p>
110
+ </div>
111
+ ) : (
112
+ (!!googleLabel || !!microsoftLabel) && (
113
+ <div className='h_item gap_5 no_shrink'>
114
+ {!!googleLabel && (
115
+ <PageFormHeaderOAuthButton
116
+ iconName='brand-google-color'
117
+ label={googleLabel}
118
+ disabled={googleDisabled}
119
+ loading={googleLoading}
120
+ onClick={onGoogle}
121
+ />
122
+ )}
123
+ {!!microsoftLabel && (
124
+ <PageFormHeaderOAuthButton
125
+ iconName='brand-microsoft-color'
126
+ label={microsoftLabel}
127
+ disabled={microsoftDisabled}
128
+ loading={microsoftLoading}
129
+ onClick={onMicrosoft}
130
+ />
131
+ )}
132
+ </div>
133
+ )
134
+ )}
135
+ {!!accountMessage && (
136
+ typeof accountMessage === 'string'
137
+ ? (
138
+ <TextWithLinks as='p' className='cl_md ml_xs' linkClassName='u cl_df'>
139
+ {accountMessage}
140
+ </TextWithLinks>
141
+ )
142
+ : <p className='cl_md ft_md'>{accountMessage}</p>
143
+ )}
144
+ </div>
145
+ );
146
+ };
147
+
148
+ export default memo(InlineAuthForm);
@@ -0,0 +1,109 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { AccountSessionData } from '@jsb188/app/types/auth.d.ts';
3
+ import { useRevokeMyAccountSession, useRevokeMyOtherAccountSessions } from '@jsb188/graphql/hooks/use-auth-mtn';
4
+ import { useMyAccountSessions } from '@jsb188/graphql/hooks/use-auth-qry';
5
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
6
+ import { BigLoading } from '@jsb188/react-web/ui/Loading';
7
+ import { useMemo, useState } from 'react';
8
+ import { type ManagedSessionListItem, ManagedSessionListUI } from '../ui/ManagedSessionUI.tsx';
9
+
10
+ /*
11
+ * Format one managed-session timestamp for the current browser locale.
12
+ */
13
+ function formatManagedSessionDate(value?: string | null) {
14
+ const date = value ? new Date(value) : null;
15
+ return date && !isNaN(date.getTime()) ? date.toLocaleString() : '-';
16
+ }
17
+
18
+ /*
19
+ * Convert server session rows into display-ready immutable list items.
20
+ */
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());
31
+ }
32
+
33
+ /*
34
+ * Load and manage the current account's active device sessions.
35
+ */
36
+ 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
+ );
61
+
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
+ };
73
+
74
+ if (loading && !accountSessions) {
75
+ return (
76
+ <div className='h_160 v_center'>
77
+ <BigLoading />
78
+ </div>
79
+ );
80
+ }
81
+
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
+ );
109
+ }
@@ -0,0 +1,114 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
3
+ import { useCallback } from 'react';
4
+ import {
5
+ type OnFinishSignInFn,
6
+ useContinueWithGoogle,
7
+ useContinueWithMicrosoft,
8
+ } from '../hooks/use-oauth';
9
+
10
+ interface OAuthButtonProps {
11
+ formPublicId?: string | null;
12
+ onFinishSignIn: OnFinishSignInFn;
13
+ }
14
+
15
+ interface AuthMethodButtonProps {
16
+ onClickButton: () => void;
17
+ }
18
+
19
+ /**
20
+ * Google OAuth button
21
+ */
22
+
23
+ export const ContinueWithGoogle = (p: OAuthButtonProps) => {
24
+ const { onFinishSignIn, formPublicId } = p;
25
+ const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } = useContinueWithGoogle({
26
+ onFinishSignIn
27
+ });
28
+
29
+ /* Launch Google OAuth with the current public-form context. */
30
+ const onClick = useCallback(() => {
31
+ onInitiateGoogleSignIn(undefined, null, formPublicId ?? null);
32
+ }, [formPublicId, onInitiateGoogleSignIn]);
33
+
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
+ );
46
+ };
47
+
48
+ /**
49
+ * Microsoft OAuth button
50
+ */
51
+
52
+ export const ContinueWithMicrosoft = (p: OAuthButtonProps) => {
53
+ const { onFinishSignIn, formPublicId } = p;
54
+ const { onInitiateMicrosoftSignIn, oauthButtonDisabled, waitingForOAuth } = useContinueWithMicrosoft({
55
+ onFinishSignIn
56
+ });
57
+
58
+ /* Launch Microsoft OAuth with the current public-form context. */
59
+ const onClick = useCallback(() => {
60
+ onInitiateMicrosoftSignIn(undefined, undefined, formPublicId ?? null);
61
+ }, [formPublicId, onInitiateMicrosoftSignIn]);
62
+
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
+ );
75
+ };
76
+
77
+ /**
78
+ * Org SSO button (email-first home realm discovery)
79
+ */
80
+
81
+ export const ContinueWithSso = (p: AuthMethodButtonProps) => {
82
+ const { onClickButton } = p;
83
+ return (
84
+ <FullWidthButton
85
+ 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
+ );
94
+ };
95
+
96
+ /**
97
+ * Phone sign-in button
98
+ */
99
+
100
+ 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
+ );
114
+ };
@@ -0,0 +1,125 @@
1
+ import { runWithAuthSessionBrowserLock } from '@jsb188/app/utils/authSession.ts';
2
+
3
+ /**
4
+ * Types
5
+ */
6
+
7
+ export type AuthPageName = 'signin' | 'signin_success' | 'signup' | 'signup_success' | 'reset_password' | 'welcome';
8
+
9
+ 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;
16
+ };
17
+
18
+ export type OAuthSessionAuthenticationResult = {
19
+ auth: any | null;
20
+ error: any | null;
21
+ };
22
+
23
+ /**
24
+ * Helper; get route path
25
+ */
26
+
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;
43
+ }
44
+
45
+ /*
46
+ * Post one login credential to the same-origin HttpOnly-cookie endpoint.
47
+ */
48
+ 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
+ }
65
+ }
66
+
67
+ /*
68
+ * Authenticate one OAuth provider credential through the same-origin BFF and
69
+ * atomically persist the resulting HttpOnly managed-session cookie.
70
+ */
71
+ export async function authenticateOAuthSignInSession(
72
+ input: OAuthSessionAuthenticationInput,
73
+ ): 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
+ }
109
+ }
110
+
111
+ /*
112
+ * Persist an OAuth or phone login before navigating without a bearer-token query.
113
+ */
114
+ 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
+ });
125
+ }