-
-
Notifications
You must be signed in to change notification settings - Fork 166
/
GoTrueClient.ts
2561 lines (2260 loc) · 78.3 KB
/
GoTrueClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import GoTrueAdminApi from './GoTrueAdminApi'
import { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, STORAGE_KEY } from './lib/constants'
import {
AuthError,
AuthImplicitGrantRedirectError,
AuthPKCEGrantCodeExchangeError,
AuthInvalidCredentialsError,
AuthSessionMissingError,
AuthInvalidTokenResponseError,
AuthUnknownError,
isAuthApiError,
isAuthError,
isAuthRetryableFetchError,
} from './lib/errors'
import {
Fetch,
_request,
_sessionResponse,
_sessionResponsePassword,
_userResponse,
_ssoResponse,
} from './lib/fetch'
import {
decodeJWTPayload,
Deferred,
getItemAsync,
isBrowser,
removeItemAsync,
resolveFetch,
setItemAsync,
uuid,
retryable,
sleep,
supportsLocalStorage,
parseParametersFromURL,
getCodeChallengeAndMethod,
} from './lib/helpers'
import { localStorageAdapter, memoryLocalStorageAdapter } from './lib/local-storage'
import { polyfillGlobalThis } from './lib/polyfills'
import { version } from './lib/version'
import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'
import type {
AuthChangeEvent,
AuthResponse,
AuthResponsePassword,
AuthTokenResponse,
AuthTokenResponsePassword,
AuthOtpResponse,
CallRefreshTokenResult,
GoTrueClientOptions,
InitializeResult,
OAuthResponse,
SSOResponse,
Provider,
Session,
SignInWithIdTokenCredentials,
SignInWithOAuthCredentials,
SignInWithPasswordCredentials,
SignInWithPasswordlessCredentials,
SignUpWithPasswordCredentials,
SignInWithSSO,
SignOut,
Subscription,
SupportedStorage,
User,
UserAttributes,
UserResponse,
VerifyOtpParams,
GoTrueMFAApi,
MFAEnrollParams,
AuthMFAEnrollResponse,
MFAChallengeParams,
AuthMFAChallengeResponse,
MFAUnenrollParams,
AuthMFAUnenrollResponse,
MFAVerifyParams,
AuthMFAVerifyResponse,
AuthMFAListFactorsResponse,
AMREntry,
AuthMFAGetAuthenticatorAssuranceLevelResponse,
AuthenticatorAssuranceLevels,
Factor,
MFAChallengeAndVerifyParams,
ResendParams,
AuthFlowType,
LockFunc,
UserIdentity,
SignInAnonymouslyCredentials,
} from './lib/types'
polyfillGlobalThis() // Make "globalThis" available
const DEFAULT_OPTIONS: Omit<Required<GoTrueClientOptions>, 'fetch' | 'storage' | 'lock'> = {
url: GOTRUE_URL,
storageKey: STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: DEFAULT_HEADERS,
flowType: 'implicit',
debug: false,
hasCustomAuthorizationHeader: false,
}
/** Current session will be checked for refresh at this interval. */
const AUTO_REFRESH_TICK_DURATION = 30 * 1000
/**
* A token refresh will be attempted this many ticks before the current session expires. */
const AUTO_REFRESH_TICK_THRESHOLD = 3
async function lockNoOp<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R> {
return await fn()
}
export default class GoTrueClient {
private static nextInstanceID = 0
private instanceID: number
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string
protected flowType: AuthFlowType
protected autoRefreshToken: boolean
protected persistSession: boolean
protected storage: SupportedStorage
protected memoryStorage: { [key: string]: string } | null = null
protected stateChangeEmitters: Map<string, Subscription> = new Map()
protected autoRefreshTicker: ReturnType<typeof setInterval> | null = null
protected visibilityChangedCallback: (() => Promise<any>) | null = null
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null = null
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the the auth state is known and it's save to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null = null
protected detectSessionInUrl = true
protected url: string
protected headers: {
[key: string]: string
}
protected hasCustomAuthorizationHeader = false
protected suppressGetSessionWarning = false
protected fetch: Fetch
protected lock: LockFunc
protected lockAcquired = false
protected pendingInLock: Promise<any>[] = []
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null = null
protected logDebugMessages: boolean
protected logger: (message: string, ...args: any[]) => void = console.log
/**
* Create a new client for use in the browser.
*/
constructor(options: GoTrueClientOptions) {
this.instanceID = GoTrueClient.nextInstanceID
GoTrueClient.nextInstanceID += 1
if (this.instanceID > 0 && isBrowser()) {
console.warn(
'Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'
)
}
const settings = { ...DEFAULT_OPTIONS, ...options }
this.logDebugMessages = !!settings.debug
if (typeof settings.debug === 'function') {
this.logger = settings.debug
}
this.persistSession = settings.persistSession
this.storageKey = settings.storageKey
this.autoRefreshToken = settings.autoRefreshToken
this.admin = new GoTrueAdminApi({
url: settings.url,
headers: settings.headers,
fetch: settings.fetch,
})
this.url = settings.url
this.headers = settings.headers
this.fetch = resolveFetch(settings.fetch)
this.lock = settings.lock || lockNoOp
this.detectSessionInUrl = settings.detectSessionInUrl
this.flowType = settings.flowType
this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader
if (settings.lock) {
this.lock = settings.lock
} else if (isBrowser() && globalThis?.navigator?.locks) {
this.lock = navigatorLock
} else {
this.lock = lockNoOp
}
this.mfa = {
verify: this._verify.bind(this),
enroll: this._enroll.bind(this),
unenroll: this._unenroll.bind(this),
challenge: this._challenge.bind(this),
listFactors: this._listFactors.bind(this),
challengeAndVerify: this._challengeAndVerify.bind(this),
getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
}
if (this.persistSession) {
if (settings.storage) {
this.storage = settings.storage
} else {
if (supportsLocalStorage()) {
this.storage = localStorageAdapter
} else {
this.memoryStorage = {}
this.storage = memoryLocalStorageAdapter(this.memoryStorage)
}
}
} else {
this.memoryStorage = {}
this.storage = memoryLocalStorageAdapter(this.memoryStorage)
}
if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
try {
this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey)
} catch (e: any) {
console.error(
'Failed to create a new BroadcastChannel, multi-tab state changes will not be available',
e
)
}
this.broadcastChannel?.addEventListener('message', async (event) => {
this._debug('received broadcast notification from other tab or client', event)
await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages
})
}
this.initialize()
}
private _debug(...args: any[]): GoTrueClient {
if (this.logDebugMessages) {
this.logger(
`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`,
...args
)
}
return this
}
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
async initialize(): Promise<InitializeResult> {
if (this.initializePromise) {
return await this.initializePromise
}
this.initializePromise = (async () => {
return await this._acquireLock(-1, async () => {
return await this._initialize()
})
})()
return await this.initializePromise
}
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
private async _initialize(): Promise<InitializeResult> {
try {
const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false
this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow)
if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) {
const { data, error } = await this._getSessionFromURL(isPKCEFlow)
if (error) {
this._debug('#_initialize()', 'error detecting session from URL', error)
// hacky workaround to keep the existing session if there's an error returned from identity linking
// TODO: once error codes are ready, we should match against it instead of the message
if (
error?.message === 'Identity is already linked' ||
error?.message === 'Identity is already linked to another user'
) {
return { error }
}
// failed login attempt via url,
// remove old session as in verifyOtp, signUp and signInWith*
await this._removeSession()
return { error }
}
const { session, redirectType } = data
this._debug(
'#_initialize()',
'detected session in URL',
session,
'redirect type',
redirectType
)
await this._saveSession(session)
setTimeout(async () => {
if (redirectType === 'recovery') {
await this._notifyAllSubscribers('PASSWORD_RECOVERY', session)
} else {
await this._notifyAllSubscribers('SIGNED_IN', session)
}
}, 0)
return { error: null }
}
// no login attempt via callback url try to recover session from storage
await this._recoverAndRefresh()
return { error: null }
} catch (error) {
if (isAuthError(error)) {
return { error }
}
return {
error: new AuthUnknownError('Unexpected error during initialization', error),
}
} finally {
await this._handleVisibilityChange()
this._debug('#_initialize()', 'end')
}
}
/**
* Creates a new anonymous user.
*
* @returns A session where the is_anonymous claim in the access token JWT set to true
*/
async signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse> {
try {
await this._removeSession()
const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
data: credentials?.options?.data ?? {},
gotrue_meta_security: { captcha_token: credentials?.options?.captchaToken },
},
xform: _sessionResponse,
})
const { data, error } = res
if (error || !data) {
return { data: { user: null, session: null }, error: error }
}
const session: Session | null = data.session
const user: User | null = data.user
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', session)
}
return { data: { user, session }, error: null }
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*/
async signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse> {
try {
await this._removeSession()
let res: AuthResponse
if ('email' in credentials) {
const { email, password, options } = credentials
let codeChallenge: string | null = null
let codeChallengeMethod: string | null = null
if (this.flowType === 'pkce') {
;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(
this.storage,
this.storageKey
)
}
res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
redirectTo: options?.emailRedirectTo,
body: {
email,
password,
data: options?.data ?? {},
gotrue_meta_security: { captcha_token: options?.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
xform: _sessionResponse,
})
} else if ('phone' in credentials) {
const { phone, password, options } = credentials
res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
phone,
password,
data: options?.data ?? {},
channel: options?.channel ?? 'sms',
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponse,
})
} else {
throw new AuthInvalidCredentialsError(
'You must provide either an email or phone number and a password'
)
}
const { data, error } = res
if (error || !data) {
return { data: { user: null, session: null }, error: error }
}
const session: Session | null = data.session
const user: User | null = data.user
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', session)
}
return { data: { user, session }, error: null }
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
async signInWithPassword(
credentials: SignInWithPasswordCredentials
): Promise<AuthTokenResponsePassword> {
try {
await this._removeSession()
let res: AuthResponsePassword
if ('email' in credentials) {
const { email, password, options } = credentials
res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
email,
password,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponsePassword,
})
} else if ('phone' in credentials) {
const { phone, password, options } = credentials
res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
phone,
password,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponsePassword,
})
} else {
throw new AuthInvalidCredentialsError(
'You must provide either an email or phone number and a password'
)
}
const { data, error } = res
if (error) {
return { data: { user: null, session: null }, error }
} else if (!data || !data.session || !data.user) {
return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }
}
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', data.session)
}
return {
data: {
user: data.user,
session: data.session,
...(data.weak_password ? { weakPassword: data.weak_password } : null),
},
error,
}
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
async signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse> {
await this._removeSession()
return await this._handleProviderSignIn(credentials.provider, {
redirectTo: credentials.options?.redirectTo,
scopes: credentials.options?.scopes,
queryParams: credentials.options?.queryParams,
skipBrowserRedirect: credentials.options?.skipBrowserRedirect,
})
}
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
async exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse> {
await this.initializePromise
return this._acquireLock(-1, async () => {
return this._exchangeCodeForSession(authCode)
})
}
private async _exchangeCodeForSession(authCode: string): Promise<
| {
data: { session: Session; user: User; redirectType: string | null }
error: null
}
| { data: { session: null; user: null; redirectType: null }; error: AuthError }
> {
const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`)
const [codeVerifier, redirectType] = ((storageItem ?? '') as string).split('/')
const { data, error } = await _request(
this.fetch,
'POST',
`${this.url}/token?grant_type=pkce`,
{
headers: this.headers,
body: {
auth_code: authCode,
code_verifier: codeVerifier,
},
xform: _sessionResponse,
}
)
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)
if (error) {
return { data: { user: null, session: null, redirectType: null }, error }
} else if (!data || !data.session || !data.user) {
return {
data: { user: null, session: null, redirectType: null },
error: new AuthInvalidTokenResponseError(),
}
}
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', data.session)
}
return { data: { ...data, redirectType: redirectType ?? null }, error }
}
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
async signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse> {
await this._removeSession()
try {
const { options, provider, token, access_token, nonce } = credentials
const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {
headers: this.headers,
body: {
provider,
id_token: token,
access_token,
nonce,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponse,
})
const { data, error } = res
if (error) {
return { data: { user: null, session: null }, error }
} else if (!data || !data.session || !data.user) {
return {
data: { user: null, session: null },
error: new AuthInvalidTokenResponseError(),
}
}
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', data.session)
}
return { data, error }
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
async signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse> {
try {
await this._removeSession()
if ('email' in credentials) {
const { email, options } = credentials
let codeChallenge: string | null = null
let codeChallengeMethod: string | null = null
if (this.flowType === 'pkce') {
;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(
this.storage,
this.storageKey
)
}
const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
headers: this.headers,
body: {
email,
data: options?.data ?? {},
create_user: options?.shouldCreateUser ?? true,
gotrue_meta_security: { captcha_token: options?.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
redirectTo: options?.emailRedirectTo,
})
return { data: { user: null, session: null }, error }
}
if ('phone' in credentials) {
const { phone, options } = credentials
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
headers: this.headers,
body: {
phone,
data: options?.data ?? {},
create_user: options?.shouldCreateUser ?? true,
gotrue_meta_security: { captcha_token: options?.captchaToken },
channel: options?.channel ?? 'sms',
},
})
return { data: { user: null, session: null, messageId: data?.message_id }, error }
}
throw new AuthInvalidCredentialsError('You must provide either an email or phone number.')
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
async verifyOtp(params: VerifyOtpParams): Promise<AuthResponse> {
try {
if (params.type !== 'email_change' && params.type !== 'phone_change') {
// we don't want to remove the authenticated session if the user is performing an email_change or phone_change verification
await this._removeSession()
}
let redirectTo = undefined
let captchaToken = undefined
if ('options' in params) {
redirectTo = params.options?.redirectTo
captchaToken = params.options?.captchaToken
}
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {
headers: this.headers,
body: {
...params,
gotrue_meta_security: { captcha_token: captchaToken },
},
redirectTo,
xform: _sessionResponse,
})
if (error) {
throw error
}
if (!data) {
throw new Error('An error occurred on token verification.')
}
const session: Session | null = data.session
const user: User = data.user
if (session?.access_token) {
await this._saveSession(session as Session)
await this._notifyAllSubscribers(
params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN',
session
)
}
return { data: { user, session }, error: null }
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
async signInWithSSO(params: SignInWithSSO): Promise<SSOResponse> {
try {
await this._removeSession()
let codeChallenge: string | null = null
let codeChallengeMethod: string | null = null
if (this.flowType === 'pkce') {
;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(
this.storage,
this.storageKey
)
}
return await _request(this.fetch, 'POST', `${this.url}/sso`, {
body: {
...('providerId' in params ? { provider_id: params.providerId } : null),
...('domain' in params ? { domain: params.domain } : null),
redirect_to: params.options?.redirectTo ?? undefined,
...(params?.options?.captchaToken
? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }
: null),
skip_http_redirect: true, // fetch does not handle redirects
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
headers: this.headers,
xform: _ssoResponse,
})
} catch (error) {
if (isAuthError(error)) {
return { data: null, error }
}
throw error
}
}
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
async reauthenticate(): Promise<AuthResponse> {
await this.initializePromise
return await this._acquireLock(-1, async () => {
return await this._reauthenticate()
})
}
private async _reauthenticate(): Promise<AuthResponse> {
try {
return await this._useSession(async (result) => {
const {
data: { session },
error: sessionError,
} = result
if (sessionError) throw sessionError
if (!session) throw new AuthSessionMissingError()
const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {
headers: this.headers,
jwt: session.access_token,
})
return { data: { user: null, session: null }, error }
})
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
async resend(credentials: ResendParams): Promise<AuthOtpResponse> {
try {
if (credentials.type != 'email_change' && credentials.type != 'phone_change') {
await this._removeSession()
}
const endpoint = `${this.url}/resend`
if ('email' in credentials) {
const { email, type, options } = credentials
const { error } = await _request(this.fetch, 'POST', endpoint, {
headers: this.headers,
body: {
email,
type,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
redirectTo: options?.emailRedirectTo,
})
return { data: { user: null, session: null }, error }
} else if ('phone' in credentials) {
const { phone, type, options } = credentials
const { data, error } = await _request(this.fetch, 'POST', endpoint, {
headers: this.headers,
body: {
phone,
type,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
})
return { data: { user: null, session: null, messageId: data?.message_id }, error }
}
throw new AuthInvalidCredentialsError(
'You must provide either an email or phone number and a type'
)
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error }
}
throw error
}
}
/**
* Returns the session, refreshing it if necessary.
*
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*
* **IMPORTANT:** This method loads values directly from the storage attached
* to the client. If that storage is based on request cookies for example,
* the values in it may not be authentic and therefore it's strongly advised
* against using this method and its results in such circumstances. A warning
* will be emitted if this is detected. Use {@link #getUser()} instead.
*/
async getSession() {
await this.initializePromise
const result = await this._acquireLock(-1, async () => {
return this._useSession(async (result) => {
return result
})
})
return result
}
/**
* Acquires a global lock based on the storage key.
*/
private async _acquireLock<R>(acquireTimeout: number, fn: () => Promise<R>): Promise<R> {
this._debug('#_acquireLock', 'begin', acquireTimeout)
try {
if (this.lockAcquired) {
const last = this.pendingInLock.length
? this.pendingInLock[this.pendingInLock.length - 1]
: Promise.resolve()
const result = (async () => {
await last
return await fn()
})()
this.pendingInLock.push(
(async () => {
try {
await result
} catch (e: any) {
// we just care if it finished
}
})()
)
return result
}
return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => {
this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey)
try {
this.lockAcquired = true
const result = fn()
this.pendingInLock.push(
(async () => {
try {
await result
} catch (e: any) {
// we just care if it finished
}
})()
)
await result
// keep draining the queue until there's nothing to wait on
while (this.pendingInLock.length) {
const waitOn = [...this.pendingInLock]
await Promise.all(waitOn)
this.pendingInLock.splice(0, waitOn.length)
}
return await result
} finally {