-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
1405 lines (1295 loc) · 45.2 KB
/
Copy pathindex.ts
File metadata and controls
1405 lines (1295 loc) · 45.2 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
// Note: write gql query in single line to reduce bundle size
import crossFetch from 'cross-fetch';
import {
DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
GRANT_TYPE_TOKEN_EXCHANGE,
} from './constants';
import * as Types from './types';
import {
bufferToBase64UrlEncoded,
coerceInt64Fields,
createQueryParams,
createRandomString,
encode,
executeIframe,
hasWindow,
sha256,
trimURL,
} from './utils';
import { toSDKError } from './errors';
import * as webauthn from './webauthn';
// re-usable gql response fragment
const userFragment =
'id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at revoked_timestamp is_multi_factor_auth_enabled has_skipped_mfa_setup_at mfa_locked_at app_data';
const authTokenFragment = `message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen should_offer_webauthn_mfa_verify should_offer_webauthn_mfa_setup should_offer_email_otp_mfa_setup should_offer_sms_otp_mfa_setup authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${userFragment} }`;
// set fetch based on window object. Cross fetch have issues with umd build
const getFetcher = () => (hasWindow() ? window.fetch : crossFetch);
function toErrorList(errors: unknown): Types.AuthorizerSDKError[] {
if (Array.isArray(errors)) {
return errors.map(toSDKError);
}
if (errors instanceof Error) return [errors];
if (errors !== null && typeof errors === 'object') {
const o = errors as Record<string, unknown>;
if (typeof o.error_description === 'string')
return [new Error(o.error_description)];
if (typeof o.error === 'string') {
const desc =
typeof o.error_description === 'string'
? `: ${o.error_description}`
: '';
return [new Error(`${o.error}${desc}`)];
}
if (typeof o.message === 'string') return [new Error(o.message)];
}
if (errors === undefined || errors === null)
return [new Error('Unknown error')];
return [new Error(String(errors))];
}
export * from './types';
export { AuthorizerAdmin } from './admin';
export { isWebauthnSupported } from './webauthn';
export {
parseMfaRedirectParams,
MFA_REQUIRED_PARAM,
MFA_METHODS_PARAM,
} from './mfaRedirect';
export type { MfaRedirectParams } from './mfaRedirect';
export {
CLIENT_ASSERTION_TYPE_JWT_BEARER,
GRANT_TYPE_AUTHORIZATION_CODE,
GRANT_TYPE_CLIENT_CREDENTIALS,
GRANT_TYPE_REFRESH_TOKEN,
GRANT_TYPE_TOKEN_EXCHANGE,
TOKEN_TYPE_ACCESS_TOKEN,
TOKEN_TYPE_JWT,
} from './constants';
/**
* Client for the Authorizer API. All network calls go to `config.authorizerURL`
* with cookies included where the runtime allows; only configure URLs you trust.
*/
export class Authorizer {
// class variable
config: Types.ConfigType;
codeVerifier: string;
// Tracks the in-flight passkey-autofill (conditional mediation) ceremony so
// it can be aborted before a modal ceremony starts - the browser allows only
// one outstanding navigator.credentials.get() at a time.
private conditionalPasskeyAbort?: AbortController;
// constructor
constructor(config: Types.ConfigType) {
if (!config) throw new Error('Configuration is required');
this.config = config;
if (!config.authorizerURL?.trim()) throw new Error('Invalid authorizerURL');
this.config.authorizerURL = trimURL(config.authorizerURL);
if (!config.redirectURL?.trim()) throw new Error('Invalid redirectURL');
this.config.redirectURL = trimURL(config.redirectURL);
this.config.clientID = (config?.clientID || '').trim();
if ((config.protocol as string) === 'grpc')
throw new Error(
'protocol \'grpc\' is not supported in authorizer-js (browsers cannot speak raw gRPC); use \'graphql\' or \'rest\'',
);
this.config.protocol = config.protocol || 'graphql';
this.config.extraHeaders = {
...(config.extraHeaders || {}),
'x-authorizer-url': config.authorizerURL,
'x-authorizer-client-id': config.clientID || '',
'Content-Type': 'application/json',
};
}
authorize = async (
data: Types.AuthorizeRequest,
): Promise<
| Types.ApiResponse<Types.GetTokenResponse>
| Types.ApiResponse<Types.AuthorizeResponse>
> => {
if (!hasWindow())
return this.errorResponse([
new Error('this feature is only supported in browser'),
]);
const scopes = ['openid', 'profile', 'email'];
if (data.use_refresh_token) scopes.push('offline_access');
const requestData: Record<string, string> = {
redirect_uri: this.config.redirectURL,
response_mode: data.response_mode || 'web_message',
state: encode(createRandomString()),
nonce: encode(createRandomString()),
response_type: data.response_type,
scope: scopes.join(' '),
client_id: this.config?.clientID || '',
};
if (data.response_type === Types.ResponseTypes.Code) {
this.codeVerifier = createRandomString();
const sha = await sha256(this.codeVerifier);
const codeChallenge = bufferToBase64UrlEncoded(sha);
requestData.code_challenge = codeChallenge;
requestData.code_challenge_method = 'S256';
}
const authorizeURL = `${
this.config.authorizerURL
}/authorize?${createQueryParams(requestData)}`;
if (requestData.response_mode !== 'web_message') {
window.location.replace(authorizeURL);
return this.okResponse(undefined);
}
try {
const iframeRes = await executeIframe(
authorizeURL,
this.config.authorizerURL,
DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
);
if (data.response_type === Types.ResponseTypes.Code) {
// get token and return it
const tokenResp: Types.ApiResponse<Types.GetTokenResponse> =
await this.getToken({
code: iframeRes.code,
});
return tokenResp.errors.length
? this.errorResponse(tokenResp.errors)
: this.okResponse(tokenResp.data);
}
// this includes access_token, id_token & refresh_token(optionally)
return this.okResponse(iframeRes);
} catch (err) {
if (err.error) {
window.location.replace(
`${this.config.authorizerURL}/app?state=${encode(
JSON.stringify({
clientID: this.config.clientID,
redirectURL: this.config.redirectURL,
authorizerURL: this.config.authorizerURL,
}),
)}&redirect_uri=${encodeURIComponent(this.config.redirectURL || '')}`,
);
}
return this.errorResponse(err);
}
};
browserLogin = async (): Promise<Types.ApiResponse<Types.AuthToken>> => {
try {
const tokenResp: Types.ApiResponse<Types.AuthToken> =
await this.getSession();
return tokenResp.errors.length
? this.errorResponse(tokenResp.errors)
: this.okResponse(tokenResp.data);
} catch (err) {
if (!hasWindow()) {
return {
data: undefined,
errors: [new Error('browserLogin is only supported for browsers')],
};
}
window.location.replace(
`${this.config.authorizerURL}/app?state=${encode(
JSON.stringify({
clientID: this.config.clientID,
redirectURL: this.config.redirectURL,
authorizerURL: this.config.authorizerURL,
}),
)}&redirect_uri=${encodeURIComponent(this.config.redirectURL || '')}`,
);
return this.errorResponse(err);
}
};
forgotPassword = async (
data: Types.ForgotPasswordRequest,
): Promise<Types.ApiResponse<Types.ForgotPasswordResponse>> => {
if (!data.state) data.state = encode(createRandomString());
if (!data.redirect_uri) data.redirect_uri = this.config.redirectURL;
try {
const forgotPasswordResp = await this.dispatch(
'forgotPassword',
['graphql', 'rest'],
{
query:
'mutation forgot_password($data: ForgotPasswordRequest!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }',
operationName: 'forgot_password',
op: 'forgot_password',
},
{ method: 'POST', path: '/v1/forgot_password', body: data },
{ data },
);
return forgotPasswordResp?.errors?.length
? this.errorResponse(forgotPasswordResp.errors)
: this.okResponse(forgotPasswordResp?.data);
} catch (error) {
return this.errorResponse([error]);
}
};
getMetaData = async (): Promise<Types.ApiResponse<Types.MetaData>> => {
try {
const res = await this.dispatch(
'getMetaData',
['graphql', 'rest'],
{
query:
'query meta { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_discord_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_roblox_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled is_totp_mfa_enabled is_email_otp_mfa_enabled is_sms_otp_mfa_enabled is_webauthn_enabled is_mfa_enforced is_org_discovery_enabled } }',
operationName: 'meta',
op: 'meta',
},
{ method: 'GET', path: '/v1/meta' },
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (error) {
return this.errorResponse([error]);
}
};
getProfile = async (
headers?: Types.Headers,
): Promise<Types.ApiResponse<Types.User>> => {
try {
const profileRes = await this.dispatch(
'getProfile',
['graphql', 'rest'],
{
query: `query profile { profile { ${userFragment} } }`,
operationName: 'profile',
op: 'profile',
},
{ method: 'GET', path: '/v1/profile' },
undefined,
headers,
);
return profileRes?.errors?.length
? this.errorResponse(profileRes.errors)
: this.okResponse(profileRes.data);
} catch (error) {
return this.errorResponse([error]);
}
};
// checkPermissions evaluates one or more permission checks ("does the
// subject have `relation` on `object`?") in a single round trip using the
// embedded OpenFGA engine. Results come back in the same order as the
// supplied `checks`, each echoing its relation/object pair.
//
// The subject defaults to the authenticated caller and is pinned server-side
// from the request (session cookie by default; pass the authorization header
// in node.js). The optional `params.user` ("type:id", or a bare id treated
// as "user:<id>") is honored only for super-admin callers or when it equals
// the caller's own token subject; anything else is rejected by the server.
checkPermissions = async (
params: Types.CheckPermissionsInput,
headers?: Types.Headers,
): Promise<Types.ApiResponse<Types.CheckPermissionsResponse>> => {
try {
const res = await this.dispatch(
'checkPermissions',
['graphql', 'rest'],
{
query:
'query checkPermissions($params: CheckPermissionsInput!){ check_permissions(params: $params) { results { relation object allowed } } }',
operationName: 'checkPermissions',
op: 'check_permissions',
},
{ method: 'POST', path: '/v1/check_permissions', body: params },
{ params },
headers,
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (error) {
return this.errorResponse([error]);
}
};
// listPermissions returns the fully-qualified ids of objects of
// `object_type` the subject holds `relation` on (handy for filtering a list
// to what the user can see). Subject resolution follows the same rules as
// checkPermissions: it defaults to the authenticated caller, and the
// optional `params.user` override is honored only for super-admin callers
// or when it equals the caller's own token subject.
listPermissions = async (
params: Types.ListPermissionsInput,
headers?: Types.Headers,
): Promise<Types.ApiResponse<Types.ListPermissionsResponse>> => {
try {
const res = await this.dispatch(
'listPermissions',
['graphql', 'rest'],
{
query:
'query listPermissions($params: ListPermissionsInput!){ list_permissions(params: $params) { objects } }',
operationName: 'listPermissions',
op: 'list_permissions',
},
{ method: 'POST', path: '/v1/list_permissions', body: params },
{ params },
headers,
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (error) {
return this.errorResponse([error]);
}
};
// this is used to verify / get session using cookie by default. If using node.js pass authorization header
getSession = async (
headers?: Types.Headers,
params?: Types.SessionQueryRequest,
): Promise<Types.ApiResponse<Types.AuthToken>> => {
try {
const res = await this.dispatch(
'getSession',
['graphql', 'rest'],
{
query: `query session($params: SessionQueryRequest){session(params: $params) { ${authTokenFragment} } }`,
operationName: 'session',
op: 'session',
},
{
method: 'POST',
path: '/v1/session',
body: params || {},
},
{ params },
headers,
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (err) {
return this.errorResponse(err);
}
};
/**
* Exchange credentials for tokens at `/oauth/token`.
*
* Supported grants: `authorization_code` (default), `refresh_token`,
* `client_credentials` (RFC 6749 §4.4) and RFC 8693 token exchange
* (`urn:ietf:params:oauth:grant-type:token-exchange`).
*
* WARNING: `client_credentials` and token exchange are machine/service
* flows for trusted server-side code ONLY. Never ship `client_secret`,
* `client_assertion`, or subject/actor tokens in a browser bundle.
*/
getToken = async (
data: Types.GetTokenRequest,
): Promise<Types.ApiResponse<Types.GetTokenResponse>> => {
if (!data.grant_type) data.grant_type = 'authorization_code';
if (data.grant_type === 'refresh_token' && !data.refresh_token?.trim())
return this.errorResponse([new Error('Invalid refresh_token')]);
if (data.grant_type === 'authorization_code' && !this.codeVerifier)
return this.errorResponse([new Error('Invalid code verifier')]);
if (
data.grant_type === GRANT_TYPE_TOKEN_EXCHANGE &&
!data.subject_token?.trim()
)
return this.errorResponse([new Error('Invalid subject_token')]);
const requestData: Record<string, string> = {
client_id: this.config.clientID || '',
grant_type: data.grant_type,
};
if (data.grant_type === 'authorization_code') {
requestData.code = data.code || '';
requestData.code_verifier = this.codeVerifier || '';
}
// only include optional params that are actually set
const optionalParams = [
'refresh_token',
'client_secret',
'scope',
'client_assertion',
'client_assertion_type',
'subject_token',
'subject_token_type',
'actor_token',
'actor_token_type',
'resource',
] as const;
for (const key of optionalParams) {
if (data[key]) requestData[key] = data[key];
}
try {
const fetcher = getFetcher();
// RFC 6749 token requests MUST be form-encoded. The server binds most
// params from JSON too, but reads `resource` (RFC 8707) only from the
// POST form — a JSON body would silently break token exchange.
const res = await fetcher(`${this.config.authorizerURL}/oauth/token`, {
method: 'POST',
body: new URLSearchParams(requestData).toString(),
headers: {
...this.config.extraHeaders,
'Content-Type': 'application/x-www-form-urlencoded',
},
credentials: 'include',
});
const text = await res.text();
let json: {
error?: string;
error_description?: string;
} & Record<string, unknown> = {};
if (text) {
try {
json = JSON.parse(text);
} catch {
return this.errorResponse([
new Error(
res.ok
? 'Invalid JSON from token endpoint'
: `HTTP ${res.status}`,
),
]);
}
}
if (!res.ok) {
return this.errorResponse([
new Error(
String(
json.error_description || json.error || `HTTP ${res.status}`,
),
),
]);
}
return this.okResponse(json);
} catch (err) {
return this.errorResponse(err);
}
};
login = async (
data: Types.LoginRequest,
): Promise<Types.ApiResponse<Types.AuthToken>> => {
try {
const res = await this.dispatch(
'login',
['graphql', 'rest'],
{
query: `mutation login($data: LoginRequest!) { login(params: $data) { ${authTokenFragment}}}`,
operationName: 'login',
op: 'login',
},
{ method: 'POST', path: '/v1/login', body: data },
{ data },
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (err) {
return this.errorResponse(err);
}
};
logout = async (
headers?: Types.Headers,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const res = await this.dispatch(
'logout',
['graphql', 'rest'],
{
query: 'mutation logout { logout { message } }',
operationName: 'logout',
op: 'logout',
},
{ method: 'POST', path: '/v1/logout' },
undefined,
headers,
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (err) {
return this.errorResponse([err]);
}
};
magicLinkLogin = async (
data: Types.MagicLinkLoginRequest,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
if (!data.state) data.state = encode(createRandomString());
if (!data.redirect_uri) data.redirect_uri = this.config.redirectURL;
const res = await this.dispatch(
'magicLinkLogin',
['graphql', 'rest'],
{
query:
'mutation magic_link_login($data: MagicLinkLoginRequest!) { magic_link_login(params: $data) { message }}',
operationName: 'magic_link_login',
op: 'magic_link_login',
},
{ method: 'POST', path: '/v1/magic_link_login', body: data },
{ data },
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (err) {
return this.errorResponse([err]);
}
};
oauthLogin = async (
oauthProvider: string,
roles?: string[],
redirect_uri?: string,
state?: string,
): Promise<void> => {
let urlState = state;
if (!urlState) {
urlState = encode(createRandomString());
}
const oauthProviderIds = Object.values(Types.OAuthProviders) as string[];
if (!oauthProviderIds.includes(oauthProvider)) {
throw new Error(
`only following oauth providers are supported: ${oauthProviderIds.join(', ')}`,
);
}
if (!hasWindow())
throw new Error('oauthLogin is only supported for browsers');
if (roles && roles.length) urlState += `&roles=${roles.join(',')}`;
window.location.replace(
`${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirect_uri=${encodeURIComponent(
redirect_uri || this.config.redirectURL || '',
)}&state=${encodeURIComponent(urlState)}`,
);
};
resendOtp = async (
data: Types.ResendOtpRequest,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const res = await this.dispatch(
'resendOtp',
['graphql', 'rest'],
{
query:
'mutation resend_otp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}',
operationName: 'resend_otp',
op: 'resend_otp',
},
{ method: 'POST', path: '/v1/resend_otp', body: data },
{ data },
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (err) {
return this.errorResponse([err]);
}
};
// WebAuthn / passkey ops are GraphQL-only (no REST route), so these call
// graphqlQuery directly rather than going through dispatch.
webauthnRegistrationOptions = async (
email?: string,
): Promise<Types.ApiResponse<Types.WebauthnRegistrationOptionsResponse>> => {
try {
const res = await this.graphqlQuery({
query:
'mutation webauthn_registration_options($email: String) { webauthn_registration_options(email: $email) { options } }',
variables: { email },
operationName: 'webauthn_registration_options',
});
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data?.webauthn_registration_options);
} catch (err) {
return this.errorResponse([err]);
}
};
webauthnRegistrationVerify = async (
data: Types.WebauthnRegistrationVerifyRequest,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const res = await this.graphqlQuery({
query:
'mutation webauthn_registration_verify($data: WebauthnRegistrationVerifyRequest!) { webauthn_registration_verify(params: $data) { message } }',
variables: { data },
operationName: 'webauthn_registration_verify',
});
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data?.webauthn_registration_verify);
} catch (err) {
return this.errorResponse([err]);
}
};
webauthnLoginOptions = async (
email?: string,
): Promise<Types.ApiResponse<Types.WebauthnLoginOptionsResponse>> => {
try {
const res = await this.graphqlQuery({
query:
'mutation webauthn_login_options($email: String) { webauthn_login_options(email: $email) { options } }',
variables: { email },
operationName: 'webauthn_login_options',
});
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data?.webauthn_login_options);
} catch (err) {
return this.errorResponse([err]);
}
};
webauthnLoginVerify = async (
data: Types.WebauthnLoginVerifyRequest,
): Promise<Types.ApiResponse<Types.AuthToken>> => {
try {
const res = await this.graphqlQuery({
query: `mutation webauthn_login_verify($data: WebauthnLoginVerifyRequest!) { webauthn_login_verify(params: $data) { ${authTokenFragment} } }`,
variables: { data },
operationName: 'webauthn_login_verify',
});
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data?.webauthn_login_verify);
} catch (err) {
return this.errorResponse([err]);
}
};
webauthnCredentials = async (): Promise<
Types.ApiResponse<Types.WebauthnCredentialInfo[]>
> => {
try {
const res = await this.graphqlQuery({
query:
'query webauthn_credentials { webauthn_credentials { id name transports created_at updated_at last_used_at } }',
operationName: 'webauthn_credentials',
});
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data?.webauthn_credentials);
} catch (err) {
return this.errorResponse([err]);
}
};
webauthnDeleteCredential = async (
id: string,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const res = await this.graphqlQuery({
query:
'mutation webauthn_delete_credential($id: ID!) { webauthn_delete_credential(id: $id) { message } }',
variables: { id },
operationName: 'webauthn_delete_credential',
});
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data?.webauthn_delete_credential);
} catch (err) {
return this.errorResponse([err]);
}
};
// registerPasskey drives the full registration ceremony end to end: fetch
// options from the server, prompt the platform authenticator via the
// browser's WebAuthn API, and send the resulting credential back for
// verification. Requires an authenticated session (a passkey is always
// added to the caller's own account).
registerPasskey = async (
name?: string,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const optRes = await this.webauthnRegistrationOptions();
if (optRes.errors.length) return this.errorResponse(optRes.errors);
const credential = await webauthn.registerPasskey(
optRes.data!.options,
);
return this.webauthnRegistrationVerify({ name, credential });
} catch (err) {
return this.errorResponse([err]);
}
};
// loginWithPasskey drives the full login ceremony end to end. Omit `email`
// for a usernameless (discoverable-credential) login; pass it to scope the
// ceremony to one account's own passkeys (the MFA-alternative flow). Pass
// `opts.mediation: 'conditional'` (with an AbortSignal) for passkey autofill;
// prefer loginWithPasskeyAutofill() which manages the signal for you.
loginWithPasskey = async (
email?: string,
opts?: { mediation?: CredentialMediationRequirement; signal?: AbortSignal },
): Promise<Types.ApiResponse<Types.AuthToken>> => {
try {
// A modal ceremony must cancel any pending autofill request first, or the
// browser rejects the modal get() with "a request is already pending".
if (opts?.mediation !== 'conditional') {
this.conditionalPasskeyAbort?.abort();
this.conditionalPasskeyAbort = undefined;
}
const optRes = await this.webauthnLoginOptions(email);
if (optRes.errors.length) return this.errorResponse(optRes.errors);
const credential = await webauthn.loginWithPasskey(
optRes.data!.options,
opts,
);
return this.webauthnLoginVerify({ credential });
} catch (err) {
return this.errorResponse([err]);
}
};
// loginWithPasskeyAutofill starts a "passkey autofill" (conditional
// mediation) login: the browser offers discoverable passkeys inline in a
// username field's autofill dropdown rather than a modal. The returned
// promise resolves ONLY when the user actually picks a passkey (or rejects
// when aborted/cancelled), so fire it on mount and ignore abort errors.
// Requires an input with autocomplete="username webauthn" on the page. Only
// one runs at a time: a new call, or an explicit modal loginWithPasskey(),
// aborts the previous one.
loginWithPasskeyAutofill = async (): Promise<
Types.ApiResponse<Types.AuthToken>
> => {
if (!(await webauthn.isConditionalMediationAvailable())) {
return this.errorResponse([
new Error('Passkey autofill is not available in this browser.'),
]);
}
this.conditionalPasskeyAbort?.abort();
const controller = new AbortController();
this.conditionalPasskeyAbort = controller;
return this.loginWithPasskey(undefined, {
mediation: 'conditional',
signal: controller.signal,
});
};
// cancelPasskeyAutofill aborts a pending loginWithPasskeyAutofill ceremony,
// e.g. on component unmount. Safe to call when none is in flight.
cancelPasskeyAutofill = (): void => {
this.conditionalPasskeyAbort?.abort();
this.conditionalPasskeyAbort = undefined;
};
resetPassword = async (
data: Types.ResetPasswordRequest,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const resetPasswordRes = await this.dispatch(
'resetPassword',
['graphql', 'rest'],
{
query:
'mutation reset_password($data: ResetPasswordRequest!) { reset_password(params: $data) { message } }',
operationName: 'reset_password',
op: 'reset_password',
},
{ method: 'POST', path: '/v1/reset_password', body: data },
{ data },
);
return resetPasswordRes?.errors?.length
? this.errorResponse(resetPasswordRes.errors)
: this.okResponse(resetPasswordRes.data);
} catch (error) {
return this.errorResponse([error]);
}
};
revokeToken = async (data: { refresh_token: string }) => {
if (!data.refresh_token?.trim())
return this.errorResponse([new Error('Invalid refresh_token')]);
try {
const fetcher = getFetcher();
const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, {
method: 'POST',
headers: {
...this.config.extraHeaders,
},
body: JSON.stringify({
refresh_token: data.refresh_token,
client_id: this.config.clientID,
}),
});
const text = await res.text();
let responseData: Record<string, unknown> = {};
if (text) {
try {
responseData = JSON.parse(text) as Record<string, unknown>;
} catch {
return this.errorResponse([
new Error(
res.ok
? 'Invalid JSON from revoke endpoint'
: `HTTP ${res.status}`,
),
]);
}
}
if (!res.ok) {
const errBody = responseData as {
error?: string;
error_description?: string;
};
return this.errorResponse([
new Error(
String(
errBody.error_description ||
errBody.error ||
`HTTP ${res.status}`,
),
),
]);
}
return this.okResponse(responseData);
} catch (err) {
return this.errorResponse(err);
}
};
signup = async (
data: Types.SignUpRequest,
): Promise<Types.ApiResponse<Types.AuthToken>> => {
try {
const res = await this.dispatch(
'signup',
['graphql', 'rest'],
{
query: `mutation signup($data: SignUpRequest!) { signup(params: $data) { ${authTokenFragment}}}`,
operationName: 'signup',
op: 'signup',
},
{ method: 'POST', path: '/v1/signup', body: data },
{ data },
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (err) {
return this.errorResponse([err]);
}
};
updateProfile = async (
data: Types.UpdateProfileRequest,
headers?: Types.Headers,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const updateProfileRes = await this.dispatch(
'updateProfile',
['graphql', 'rest'],
{
query:
'mutation update_profile($data: UpdateProfileRequest!) { update_profile(params: $data) { message } }',
operationName: 'update_profile',
op: 'update_profile',
},
{ method: 'POST', path: '/v1/update_profile', body: data },
{ data },
headers,
);
return updateProfileRes?.errors?.length
? this.errorResponse(updateProfileRes.errors)
: this.okResponse(updateProfileRes.data);
} catch (error) {
return this.errorResponse([error]);
}
};
deactivateAccount = async (
headers?: Types.Headers,
): Promise<Types.ApiResponse<Types.GenericResponse>> => {
try {
const res = await this.dispatch(
'deactivateAccount',
['graphql', 'rest'],
{
query:
'mutation deactivate_account { deactivate_account { message } }',
operationName: 'deactivate_account',
op: 'deactivate_account',
},
{ method: 'POST', path: '/v1/deactivate_account' },
undefined,
headers,
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (error) {
return this.errorResponse([error]);
}
};
validateJWTToken = async (
params?: Types.ValidateJWTTokenRequest,
): Promise<Types.ApiResponse<Types.ValidateJWTTokenResponse>> => {
try {
const res = await this.dispatch(
'validateJWTToken',
['graphql', 'rest'],
{
query:
'query validate_jwt_token($params: ValidateJWTTokenRequest!){validate_jwt_token(params: $params) { is_valid claims } }',
operationName: 'validate_jwt_token',
op: 'validate_jwt_token',
},
{ method: 'POST', path: '/v1/validate_jwt_token', body: params },
{ params },
);
return res?.errors?.length
? this.errorResponse(res.errors)
: this.okResponse(res.data);
} catch (error) {
return this.errorResponse([error]);
}
};
validateSession = async (
params?: Types.ValidateSessionRequest,
): Promise<Types.ApiResponse<Types.ValidateSessionResponse>> => {
try {
const res = await this.dispatch(
'validateSession',