-
Notifications
You must be signed in to change notification settings - Fork 632
Expand file tree
/
Copy pathGoTrueClient.ts
More file actions
4078 lines (3639 loc) · 131 KB
/
GoTrueClient.ts
File metadata and controls
4078 lines (3639 loc) · 131 KB
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 {
AUTO_REFRESH_TICK_DURATION_MS,
AUTO_REFRESH_TICK_THRESHOLD,
DEFAULT_HEADERS,
EXPIRY_MARGIN_MS,
GOTRUE_URL,
JWKS_TTL,
STORAGE_KEY,
} from './lib/constants'
import {
AuthError,
AuthImplicitGrantRedirectError,
AuthInvalidCredentialsError,
AuthInvalidJwtError,
AuthInvalidTokenResponseError,
AuthPKCECodeVerifierMissingError,
AuthPKCEGrantCodeExchangeError,
AuthSessionMissingError,
AuthUnknownError,
isAuthApiError,
isAuthError,
isAuthImplicitGrantRedirectError,
isAuthRetryableFetchError,
isAuthSessionMissingError,
} from './lib/errors'
import {
Fetch,
_request,
_sessionResponse,
_sessionResponsePassword,
_ssoResponse,
_userResponse,
} from './lib/fetch'
import {
decodeJWT,
deepClone,
Deferred,
generateCallbackId,
getAlgorithm,
getCodeChallengeAndMethod,
getItemAsync,
insecureUserWarningProxy,
isBrowser,
parseParametersFromURL,
removeItemAsync,
resolveFetch,
retryable,
setItemAsync,
sleep,
supportsLocalStorage,
userNotAvailableProxy,
validateExp,
} from './lib/helpers'
import { memoryLocalStorageAdapter } from './lib/local-storage'
import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'
import { polyfillGlobalThis } from './lib/polyfills'
import { version } from './lib/version'
import { bytesToBase64URL, stringToUint8Array } from './lib/base64url'
import type {
AuthChangeEvent,
AuthenticatorAssuranceLevels,
AuthFlowType,
AuthMFAChallengePhoneResponse,
AuthMFAChallengeResponse,
AuthMFAChallengeTOTPResponse,
AuthMFAChallengeWebauthnResponse,
AuthMFAChallengeWebauthnServerResponse,
AuthMFAEnrollPhoneResponse,
AuthMFAEnrollResponse,
AuthMFAEnrollTOTPResponse,
AuthMFAEnrollWebauthnResponse,
AuthMFAGetAuthenticatorAssuranceLevelResponse,
AuthMFAListFactorsResponse,
AuthMFAUnenrollResponse,
AuthMFAVerifyResponse,
AuthOtpResponse,
AuthResponse,
AuthResponsePassword,
AuthTokenResponse,
AuthTokenResponsePassword,
CallRefreshTokenResult,
EthereumWallet,
EthereumWeb3Credentials,
Factor,
GoTrueClientOptions,
GoTrueMFAApi,
InitializeResult,
JWK,
JwtHeader,
JwtPayload,
LockFunc,
MFAChallengeAndVerifyParams,
MFAChallengeParams,
MFAChallengePhoneParams,
MFAChallengeTOTPParams,
MFAChallengeWebauthnParams,
MFAEnrollParams,
MFAEnrollPhoneParams,
MFAEnrollTOTPParams,
MFAEnrollWebauthnParams,
MFAUnenrollParams,
MFAVerifyParams,
MFAVerifyPhoneParams,
MFAVerifyTOTPParams,
MFAVerifyWebauthnParamFields,
MFAVerifyWebauthnParams,
OAuthResponse,
AuthOAuthServerApi,
AuthOAuthAuthorizationDetailsResponse,
AuthOAuthConsentResponse,
AuthOAuthGrantsResponse,
AuthOAuthRevokeGrantResponse,
Prettify,
Provider,
ResendParams,
Session,
SignInAnonymouslyCredentials,
SignInWithIdTokenCredentials,
SignInWithOAuthCredentials,
SignInWithPasswordCredentials,
SignInWithPasswordlessCredentials,
SignInWithSSO,
SignOut,
SignUpWithPasswordCredentials,
SolanaWallet,
SolanaWeb3Credentials,
SSOResponse,
StrictOmit,
Subscription,
SupportedStorage,
User,
UserAttributes,
UserIdentity,
UserResponse,
VerifyOtpParams,
Web3Credentials,
} from './lib/types'
import {
createSiweMessage,
fromHex,
getAddress,
Hex,
SiweMessage,
toHex,
} from './lib/web3/ethereum'
import {
deserializeCredentialCreationOptions,
deserializeCredentialRequestOptions,
serializeCredentialCreationResponse,
serializeCredentialRequestResponse,
WebAuthnApi,
} from './lib/webauthn'
import {
AuthenticationCredential,
PublicKeyCredentialJSON,
RegistrationCredential,
} from './lib/webauthn.dom'
polyfillGlobalThis() // Make "globalThis" available
const DEFAULT_OPTIONS: Omit<
Required<GoTrueClientOptions>,
'fetch' | 'storage' | 'userStorage' | 'lock'
> = {
url: GOTRUE_URL,
storageKey: STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: DEFAULT_HEADERS,
flowType: 'implicit',
debug: false,
hasCustomAuthorizationHeader: false,
throwOnError: false,
lockAcquireTimeout: 5000, // 5 seconds
skipAutoInitialize: false,
}
async function lockNoOp<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R> {
return await fn()
}
/**
* Caches JWKS values for all clients created in the same environment. This is
* especially useful for shared-memory execution environments such as Vercel's
* Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how
* many clients are created, if they share the same storage key they will use
* the same JWKS cache, significantly speeding up getClaims() with asymmetric
* JWTs.
*/
const GLOBAL_JWKS: { [storageKey: string]: { cachedAt: number; jwks: { keys: JWK[] } } } = {}
export default class GoTrueClient {
private static nextInstanceID: Record<string, number> = {}
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
/**
* Namespace for the OAuth 2.1 authorization server methods.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
* Used to implement the authorization code flow on the consent page.
*/
oauth: AuthOAuthServerApi
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string
protected flowType: AuthFlowType
/**
* The JWKS used for verifying asymmetric JWTs
*/
protected get jwks() {
return GLOBAL_JWKS[this.storageKey]?.jwks ?? { keys: [] }
}
protected set jwks(value: { keys: JWK[] }) {
GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], jwks: value }
}
protected get jwks_cached_at() {
return GLOBAL_JWKS[this.storageKey]?.cachedAt ?? Number.MIN_SAFE_INTEGER
}
protected set jwks_cached_at(value: number) {
GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], cachedAt: value }
}
protected autoRefreshToken: boolean
protected persistSession: boolean
protected storage: SupportedStorage
/**
* @experimental
*/
protected userStorage: SupportedStorage | null = null
protected memoryStorage: { [key: string]: string } | null = null
protected stateChangeEmitters: Map<string | symbol, Subscription> = new Map()
protected autoRefreshTicker: ReturnType<typeof setInterval> | null = null
protected autoRefreshTickTimeout: ReturnType<typeof setTimeout> | 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 auth state is known and it's safe to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null = null
protected detectSessionInUrl:
| boolean
| ((url: URL, params: { [parameter: string]: string }) => boolean) = 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>[] = []
protected throwOnError: boolean
protected lockAcquireTimeout: number
/**
* 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.
*
* @example
* ```ts
* import { GoTrueClient } from '@supabase/auth-js'
*
* const auth = new GoTrueClient({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { apikey: 'public-anon-key' },
* storageKey: 'supabase-auth',
* })
* ```
*/
constructor(options: GoTrueClientOptions) {
const settings = { ...DEFAULT_OPTIONS, ...options }
this.storageKey = settings.storageKey
this.instanceID = GoTrueClient.nextInstanceID[this.storageKey] ?? 0
GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1
this.logDebugMessages = !!settings.debug
if (typeof settings.debug === 'function') {
this.logger = settings.debug
}
if (this.instanceID > 0 && isBrowser()) {
const message = `${this._logPrefix()} 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.`
console.warn(message)
if (this.logDebugMessages) {
console.trace(message)
}
}
this.persistSession = settings.persistSession
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
this.throwOnError = settings.throwOnError
this.lockAcquireTimeout = settings.lockAcquireTimeout
if (settings.lock) {
this.lock = settings.lock
} else if (this.persistSession && isBrowser() && globalThis?.navigator?.locks) {
this.lock = navigatorLock
} else {
this.lock = lockNoOp
}
if (!this.jwks) {
this.jwks = { keys: [] }
this.jwks_cached_at = Number.MIN_SAFE_INTEGER
}
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),
webauthn: new WebAuthnApi(this),
}
this.oauth = {
getAuthorizationDetails: this._getAuthorizationDetails.bind(this),
approveAuthorization: this._approveAuthorization.bind(this),
denyAuthorization: this._denyAuthorization.bind(this),
listGrants: this._listOAuthGrants.bind(this),
revokeGrant: this._revokeOAuthGrant.bind(this),
}
if (this.persistSession) {
if (settings.storage) {
this.storage = settings.storage
} else {
if (supportsLocalStorage()) {
this.storage = globalThis.localStorage
} else {
this.memoryStorage = {}
this.storage = memoryLocalStorageAdapter(this.memoryStorage)
}
}
if (settings.userStorage) {
this.userStorage = settings.userStorage
}
} 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)
try {
await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages
} catch (error) {
this._debug('#broadcastChannel', 'error', error)
}
})
}
// Only auto-initialize if not explicitly disabled. Skipped in SSR contexts
// where initialization timing must be controlled. All public methods have
// lazy initialization, so the client remains fully functional.
if (!settings.skipAutoInitialize) {
this.initialize().catch((error) => {
this._debug('#initialize()', 'error', error)
})
}
}
/**
* Returns whether error throwing mode is enabled for this client.
*/
public isThrowOnErrorEnabled(): boolean {
return this.throwOnError
}
/**
* Centralizes return handling with optional error throwing. When `throwOnError` is enabled
* and the provided result contains a non-nullish error, the error is thrown instead of
* being returned. This ensures consistent behavior across all public API methods.
*/
private _returnResult<T extends { error: any }>(result: T): T {
if (this.throwOnError && result && result.error) {
throw result.error
}
return result
}
private _logPrefix(): string {
return (
'GoTrueClient@' +
`${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}`
)
}
private _debug(...args: any[]): GoTrueClient {
if (this.logDebugMessages) {
this.logger(this._logPrefix(), ...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(this.lockAcquireTimeout, 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 {
let params: { [parameter: string]: string } = {}
let callbackUrlType = 'none'
if (isBrowser()) {
params = parseParametersFromURL(window.location.href)
if (this._isImplicitGrantCallback(params)) {
callbackUrlType = 'implicit'
} else if (await this._isPKCECallback(params)) {
callbackUrlType = 'pkce'
}
}
/**
* Attempt to get the session from the URL only if these conditions are fulfilled
*
* Note: If the URL isn't one of the callback url types (implicit or pkce),
* then there could be an existing session so we don't want to prematurely remove it
*/
if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') {
const { data, error } = await this._getSessionFromURL(params, callbackUrlType)
if (error) {
this._debug('#_initialize()', 'error detecting session from URL', error)
if (isAuthImplicitGrantRedirectError(error)) {
const errorCode = error.details?.code
if (
errorCode === 'identity_already_exists' ||
errorCode === 'identity_not_found' ||
errorCode === 'single_identity_not_deletable'
) {
return { error }
}
}
// Don't remove existing session on URL login failure.
// A failed attempt (e.g. reused magic link) shouldn't invalidate a valid session.
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 this._returnResult({ error })
}
return this._returnResult({
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 {
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 this._returnResult({ 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 this._returnResult({ data: { user, session }, error: null })
} catch (error) {
if (isAuthError(error)) {
return this._returnResult({ 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
*
* @category Auth
*
* @remarks
* - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).
* - **Confirm email** determines if users need to confirm their email address after signing up.
* - If **Confirm email** is enabled, a `user` is returned but `session` is null.
* - If **Confirm email** is disabled, both a `user` and a `session` are returned.
* - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).
* - If signUp() is called for an existing confirmed user:
* - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.
* - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.
* - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).
*
* @example Sign up with an email and password
* ```js
* const { data, error } = await supabase.auth.signUp({
* email: 'example@email.com',
* password: 'example-password',
* })
* ```
*
* @exampleResponse Sign up with an email and password
* ```json
* // Some fields may be null if "confirm email" is enabled.
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z"
* },
* "session": {
* "access_token": "<ACCESS_TOKEN>",
* "token_type": "bearer",
* "expires_in": 3600,
* "expires_at": 1700000000,
* "refresh_token": "<REFRESH_TOKEN>",
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z"
* }
* }
* },
* "error": null
* }
* ```
*
* @example Sign up with a phone number and password (SMS)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'sms'
* }
* })
* ```
*
* @exampleDescription Sign up with a phone number and password (whatsapp)
* The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
*
* @example Sign up with a phone number and password (whatsapp)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'whatsapp'
* }
* })
* ```
*
* @example Sign up with additional user metadata
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* data: {
* first_name: 'John',
* age: 27,
* }
* }
* }
* )
* ```
*
* @exampleDescription Sign up with a redirect URL
* - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
*
* @example Sign up with a redirect URL
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* emailRedirectTo: 'https://example.com/welcome'
* }
* }
* )
* ```
*/
async signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse> {
try {
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) {
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)
return this._returnResult({ 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 this._returnResult({ data: { user, session }, error: null })
} catch (error) {
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)
if (isAuthError(error)) {
return this._returnResult({ 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 {
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 this._returnResult({ data: { user: null, session: null }, error })
} else if (!data || !data.session || !data.user) {
const invalidTokenError = new AuthInvalidTokenResponseError()
return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError })
}
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', data.session)
}
return this._returnResult({
data: {
user: data.user,
session: data.session,
...(data.weak_password ? { weakPassword: data.weak_password } : null),
},
error,
})
} catch (error) {
if (isAuthError(error)) {
return this._returnResult({ 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> {
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(this.lockAcquireTimeout, async () => {
return this._exchangeCodeForSession(authCode)
})
}
/**
* Signs in a user by verifying a message signed by the user's private key.
* Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards,
* both of which derive from the EIP-4361 standard
* With slight variation on Solana's side.
* @reference https://eips.ethereum.org/EIPS/eip-4361
*/
async signInWithWeb3(credentials: Web3Credentials): Promise<
| {
data: { session: Session; user: User }
error: null
}
| { data: { session: null; user: null }; error: AuthError }
> {
const { chain } = credentials
switch (chain) {
case 'ethereum':
return await this.signInWithEthereum(credentials)
case 'solana':
return await this.signInWithSolana(credentials)
default:
throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`)
}
}
private async signInWithEthereum(
credentials: EthereumWeb3Credentials
): Promise<
| { data: { session: Session; user: User }; error: null }
| { data: { session: null; user: null }; error: AuthError }
> {
// TODO: flatten type
let message: string
let signature: Hex
if ('message' in credentials) {
message = credentials.message
signature = credentials.signature
} else {
const { chain, wallet, statement, options } = credentials
let resolvedWallet: EthereumWallet
if (!isBrowser()) {
if (typeof wallet !== 'object' || !options?.url) {
throw new Error(
'@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'
)
}
resolvedWallet = wallet
} else if (typeof wallet === 'object') {
resolvedWallet = wallet
} else {
const windowAny = window as any
if (
'ethereum' in windowAny &&
typeof windowAny.ethereum === 'object' &&
'request' in windowAny.ethereum &&
typeof windowAny.ethereum.request === 'function'
) {