@vardario/cognito-client 5.0.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ export interface CognitoBaseRequest {
9
9
  IpAddress?: string;
10
10
  };
11
11
  }
12
- export interface InitiateAuthUserSrpAuthRequest extends CognitoBaseRequest {
12
+ export interface _InitiateAuthUserSrpAuthRequest extends CognitoBaseRequest {
13
13
  AuthFlow: 'USER_SRP_AUTH';
14
14
  AuthParameters: {
15
15
  USERNAME: string;
@@ -17,7 +17,7 @@ export interface InitiateAuthUserSrpAuthRequest extends CognitoBaseRequest {
17
17
  SECRET_HASH?: string;
18
18
  };
19
19
  }
20
- export interface InitiateAuthUserPasswordAuthRequest extends CognitoBaseRequest {
20
+ export interface _InitiateAuthUserPasswordAuthRequest extends CognitoBaseRequest {
21
21
  AuthFlow: 'USER_PASSWORD_AUTH';
22
22
  AuthParameters: {
23
23
  USERNAME: string;
@@ -25,21 +25,31 @@ export interface InitiateAuthUserPasswordAuthRequest extends CognitoBaseRequest
25
25
  SECRET_HASH?: string;
26
26
  };
27
27
  }
28
- export interface InitiateAuthRefreshTokenAuthRequest extends CognitoBaseRequest {
28
+ export interface _InitiateAuthRefreshTokenAuthRequest extends CognitoBaseRequest {
29
29
  AuthFlow: 'REFRESH_TOKEN_AUTH';
30
30
  AuthParameters: {
31
31
  REFRESH_TOKEN: string;
32
32
  SECRET_HASH?: string;
33
+ USERNAME?: never;
33
34
  };
34
35
  }
35
- export interface InitiateAuthCustomAuthRequest extends CognitoBaseRequest {
36
+ export interface _InitiateAuthCustomAuthRequest extends CognitoBaseRequest {
36
37
  AuthFlow: 'CUSTOM_AUTH';
37
38
  AuthParameters: {
38
39
  USERNAME: string;
39
40
  SECRET_HASH?: string;
40
41
  };
41
42
  }
42
- export type InitiateAuthRequest = InitiateAuthUserSrpAuthRequest | InitiateAuthRefreshTokenAuthRequest | InitiateAuthCustomAuthRequest | InitiateAuthUserPasswordAuthRequest;
43
+ export interface _InitiateAuthUserAuthRequest extends CognitoBaseRequest {
44
+ AuthFlow: 'USER_AUTH';
45
+ AuthParameters: {
46
+ USERNAME: string;
47
+ PREFERRED_CHALLENGE?: AuthChallenge;
48
+ SECRET_HASH?: string;
49
+ };
50
+ }
51
+ type _InitiateAuthRequest = _InitiateAuthUserSrpAuthRequest | _InitiateAuthUserPasswordAuthRequest | _InitiateAuthRefreshTokenAuthRequest | _InitiateAuthCustomAuthRequest | _InitiateAuthUserAuthRequest;
52
+ export type InitiateAuthRequest = Omit<_InitiateAuthUserSrpAuthRequest, 'ClientId'> | Omit<_InitiateAuthUserPasswordAuthRequest, 'ClientId'> | Omit<_InitiateAuthRefreshTokenAuthRequest, 'ClientId'> | Omit<_InitiateAuthCustomAuthRequest, 'ClientId'> | Omit<_InitiateAuthUserAuthRequest, 'ClientId'>;
43
53
  export interface RespondToAuthChallengeBaseRequest extends CognitoBaseRequest {
44
54
  Session?: string;
45
55
  }
@@ -112,6 +122,7 @@ export interface _RespondToAuthChallengeMfaSetupRequest extends RespondToAuthCha
112
122
  SOFTWARE_TOKEN_MFA_CODE?: string;
113
123
  SECRET_HASH?: string;
114
124
  };
125
+ Session?: never;
115
126
  }
116
127
  export interface _RespondToAuthChallengeSelectMfaTypeRequest extends RespondToAuthChallengeBaseRequest {
117
128
  ChallengeName: 'SELECT_MFA_TYPE';
@@ -121,8 +132,16 @@ export interface _RespondToAuthChallengeSelectMfaTypeRequest extends RespondToAu
121
132
  SECRET_HASH?: string;
122
133
  };
123
134
  }
124
- type _RespondToAuthChallengeRequest = _RespondToAuthChallengePasswordVerifierRequest | _RespondToAuthChallengeSmsMfaRequest | _RespondToAuthChallengeCustomChallengeNameRequest | _RespondToAuthChallengeNewPasswordRequiredRequest | _RespondToAuthChallengeSoftwareTokenMfaRequest | _RespondToAuthChallengeDeviceSrpAuthRequest | _RespondToAuthChallengeDevicePasswordVerifierRequest | _RespondToAuthChallengeMfaSetupRequest | _RespondToAuthChallengeSelectMfaTypeRequest;
125
- export type RespondToAuthChallengeRequest = Omit<_RespondToAuthChallengePasswordVerifierRequest, 'ClientId'> | Omit<_RespondToAuthChallengeSmsMfaRequest, 'ClientId'> | Omit<_RespondToAuthChallengeCustomChallengeNameRequest, 'ClientId'> | Omit<_RespondToAuthChallengeNewPasswordRequiredRequest, 'ClientId'> | Omit<_RespondToAuthChallengeSoftwareTokenMfaRequest, 'ClientId'> | Omit<_RespondToAuthChallengeDeviceSrpAuthRequest, 'ClientId'> | Omit<_RespondToAuthChallengeDevicePasswordVerifierRequest, 'ClientId'> | Omit<_RespondToAuthChallengeMfaSetupRequest, 'ClientId'> | Omit<_RespondToAuthChallengeSelectMfaTypeRequest, 'ClientId'>;
135
+ export interface _RespondToAuthChallengeWebAuthnRequest extends RespondToAuthChallengeBaseRequest {
136
+ ChallengeName: 'WEB_AUTHN';
137
+ ChallengeResponses: {
138
+ USERNAME: string;
139
+ CREDENTIAL: any;
140
+ SECRET_HASH?: string;
141
+ };
142
+ }
143
+ type _RespondToAuthChallengeRequest = _RespondToAuthChallengePasswordVerifierRequest | _RespondToAuthChallengeSmsMfaRequest | _RespondToAuthChallengeCustomChallengeNameRequest | _RespondToAuthChallengeNewPasswordRequiredRequest | _RespondToAuthChallengeSoftwareTokenMfaRequest | _RespondToAuthChallengeDeviceSrpAuthRequest | _RespondToAuthChallengeDevicePasswordVerifierRequest | _RespondToAuthChallengeMfaSetupRequest | _RespondToAuthChallengeSelectMfaTypeRequest | _RespondToAuthChallengeWebAuthnRequest;
144
+ export type RespondToAuthChallengeRequest = Omit<_RespondToAuthChallengePasswordVerifierRequest, 'ClientId'> | Omit<_RespondToAuthChallengeSmsMfaRequest, 'ClientId'> | Omit<_RespondToAuthChallengeCustomChallengeNameRequest, 'ClientId'> | Omit<_RespondToAuthChallengeNewPasswordRequiredRequest, 'ClientId'> | Omit<_RespondToAuthChallengeSoftwareTokenMfaRequest, 'ClientId'> | Omit<_RespondToAuthChallengeDeviceSrpAuthRequest, 'ClientId'> | Omit<_RespondToAuthChallengeDevicePasswordVerifierRequest, 'ClientId'> | Omit<_RespondToAuthChallengeMfaSetupRequest, 'ClientId'> | Omit<_RespondToAuthChallengeSelectMfaTypeRequest, 'ClientId'> | Omit<_RespondToAuthChallengeWebAuthnRequest, 'ClientId'>;
126
145
  export interface UserAttribute {
127
146
  Name: string;
128
147
  Value: string;
@@ -258,7 +277,11 @@ export declare enum ServiceTarget {
258
277
  AssociateSoftwareToken = "AssociateSoftwareToken",
259
278
  VerifySoftwareToken = "VerifySoftwareToken",
260
279
  ListDevices = "ListDevices",
261
- SetUserMFAPreference = "SetUserMFAPreference"
280
+ SetUserMFAPreference = "SetUserMFAPreference",
281
+ StartWebAuthnRegistration = "StartWebAuthnRegistration",
282
+ CompleteWebAuthnRegistration = "CompleteWebAuthnRegistration",
283
+ DeleteWebAuthnCredential = "DeleteWebAuthnCredential",
284
+ ListWebAuthnCredentials = "ListWebAuthnCredentials"
262
285
  }
263
286
  export interface AssociateSoftwareTokenRequest {
264
287
  AccessToken?: string;
@@ -321,12 +344,16 @@ export interface NewDeviceMetadata {
321
344
  DeviceKey?: string;
322
345
  DeviceGroupKey?: string;
323
346
  }
324
- export interface InitiateAuthAuthenticationResponse {
347
+ export type AuthChallenge = InitiateAuthChallengeResponse['ChallengeName'];
348
+ export interface InitiateAuthBaseResponse {
349
+ AvailableChallenges: [];
350
+ Session: string;
351
+ }
352
+ export interface InitiateAuthAuthenticationResponse extends InitiateAuthBaseResponse {
325
353
  AuthenticationResult: AuthenticationResult;
326
354
  ChallengeName?: never;
327
- session?: never;
328
355
  }
329
- export interface InitiateAuthPasswordVerifierChallengeResponse {
356
+ export interface InitiateAuthPasswordVerifierChallengeResponse extends InitiateAuthBaseResponse {
330
357
  AuthenticationResult?: never;
331
358
  ChallengeName: 'PASSWORD_VERIFIER';
332
359
  ChallengeParameters: {
@@ -336,20 +363,48 @@ export interface InitiateAuthPasswordVerifierChallengeResponse {
336
363
  USERNAME: string;
337
364
  USER_ID_FOR_SRP: string;
338
365
  };
339
- session?: never;
340
366
  }
341
- export interface InitiateAuthSoftwareTokenMfaChallengeResponse {
367
+ export interface InitiateAuthSoftwareTokenMfaChallengeResponse extends InitiateAuthBaseResponse {
342
368
  AuthenticationResult?: never;
343
369
  ChallengeName: 'SOFTWARE_TOKEN_MFA';
370
+ }
371
+ export interface InitiateAuthWebAuthResponse extends InitiateAuthBaseResponse {
372
+ AuthenticationResult?: never;
373
+ ChallengeName: 'WEB_AUTHN';
344
374
  Session: string;
375
+ ChallengeParameters: {
376
+ CREDENTIAL_REQUEST_OPTIONS: string;
377
+ };
345
378
  }
346
- export interface InitiateEmailOtpChallengeResponse {
379
+ export interface InitiateEmailOtpChallengeResponse extends InitiateAuthBaseResponse {
380
+ AuthenticationResult?: never;
347
381
  ChallengeName: 'EMAIL_OTP';
348
382
  ChallengeParameters: {
349
383
  CODE_DELIVERY_DELIVERY_MEDIUM: string;
350
384
  CODE_DELIVERY_DESTINATION: string;
351
385
  };
352
- session: string;
386
+ Session: string;
387
+ }
388
+ export interface InitAuthSelectChallengeResponse extends InitiateAuthBaseResponse {
389
+ AuthenticationResult?: never;
390
+ ChallengeName: 'SELECT_CHALLENGE';
391
+ ChallengeParameters: never;
392
+ }
393
+ export interface InitAuthPasswordChallengeResponse extends InitiateAuthBaseResponse {
394
+ AuthenticationResult?: never;
395
+ ChallengeName: 'PASSWORD';
396
+ ChallengeParameters: never;
397
+ }
398
+ export interface InitAuthPasswordSRPChallengeResponse extends InitiateAuthBaseResponse {
399
+ AuthenticationResult?: never;
400
+ ChallengeName: 'PASSWORD_SRP';
401
+ ChallengeParameters: never;
402
+ }
403
+ export interface InitAuthMfaSetupChallengeResponse extends InitiateAuthBaseResponse {
404
+ AuthenticationResult?: never;
405
+ ChallengeName: 'MFA_SETUP';
406
+ ChallengeParameters: never;
407
+ MFAS_CAN_SETUP: ('SMS_MFA' | 'SOFTWARE_TOKEN_MFA')[];
353
408
  }
354
409
  export interface MfaOption {
355
410
  DeliveryMedium: 'SMS' | 'EMAIL';
@@ -377,7 +432,38 @@ export interface SetUserMFAPreferenceRequest {
377
432
  PreferredMfa?: boolean;
378
433
  };
379
434
  }
380
- export type InitiateAuthChallengeResponse = InitiateAuthPasswordVerifierChallengeResponse | InitiateAuthSoftwareTokenMfaChallengeResponse;
435
+ export interface StartWebAuthnRegistrationRequest {
436
+ AccessToken: string;
437
+ }
438
+ export interface StartWebAuthnRegistrationResponse {
439
+ CredentialCreationOptions: any;
440
+ }
441
+ export interface CompleteWebAuthnRegistrationRequest {
442
+ AccessToken: string;
443
+ Credential: PublicKeyCredential;
444
+ }
445
+ export interface DeleteWebAuthnCredentialRequest {
446
+ AccessToken: string;
447
+ CredentialId: string;
448
+ }
449
+ export interface ListWebAuthnCredentialsRequest {
450
+ AccessToken: string;
451
+ MaxResults?: number;
452
+ NextToken?: string;
453
+ }
454
+ export interface WebAuthnCredential {
455
+ AuthenticatorTransports: string[];
456
+ CreatedAt: string;
457
+ CredentialId: string;
458
+ FriendlyCredentialName: string;
459
+ RelyingPartyId: string;
460
+ AuthenticatorAttachment?: string;
461
+ }
462
+ export interface ListWebAuthnCredentialsResponse {
463
+ Credentials: WebAuthnCredential[];
464
+ NextToken?: string;
465
+ }
466
+ export type InitiateAuthChallengeResponse = InitiateAuthPasswordVerifierChallengeResponse | InitiateAuthSoftwareTokenMfaChallengeResponse | InitiateAuthWebAuthResponse | InitiateEmailOtpChallengeResponse | InitAuthSelectChallengeResponse | InitAuthPasswordChallengeResponse | InitAuthPasswordSRPChallengeResponse | InitAuthMfaSetupChallengeResponse;
381
467
  export type InitiateAuthResponse = InitiateAuthAuthenticationResponse | InitiateAuthPasswordVerifierChallengeResponse | InitiateAuthChallengeResponse;
382
468
  type CognitoResponseMap = {
383
469
  [ServiceTarget.InitiateAuth]: InitiateAuthResponse;
@@ -400,9 +486,13 @@ type CognitoResponseMap = {
400
486
  [ServiceTarget.VerifySoftwareToken]: VerifySoftwareTokenResponse;
401
487
  [ServiceTarget.ListDevices]: ListDevicesResponse;
402
488
  [ServiceTarget.SetUserMFAPreference]: void;
489
+ [ServiceTarget.StartWebAuthnRegistration]: StartWebAuthnRegistrationResponse;
490
+ [ServiceTarget.CompleteWebAuthnRegistration]: void;
491
+ [ServiceTarget.DeleteWebAuthnCredential]: void;
492
+ [ServiceTarget.ListWebAuthnCredentials]: ListWebAuthnCredentialsResponse;
403
493
  };
404
494
  type CognitoRequestMap = {
405
- [ServiceTarget.InitiateAuth]: InitiateAuthRequest;
495
+ [ServiceTarget.InitiateAuth]: _InitiateAuthRequest;
406
496
  [ServiceTarget.RespondToAuthChallenge]: _RespondToAuthChallengeRequest;
407
497
  [ServiceTarget.SignUp]: SignUpRequest;
408
498
  [ServiceTarget.ConfirmSignUp]: ConfirmSignUpRequest;
@@ -438,6 +528,10 @@ type CognitoRequestMap = {
438
528
  [ServiceTarget.VerifySoftwareToken]: VerifySoftwareTokenRequest;
439
529
  [ServiceTarget.ListDevices]: ListDevicesRequest;
440
530
  [ServiceTarget.SetUserMFAPreference]: SetUserMFAPreferenceRequest;
531
+ [ServiceTarget.StartWebAuthnRegistration]: StartWebAuthnRegistrationRequest;
532
+ [ServiceTarget.CompleteWebAuthnRegistration]: any;
533
+ [ServiceTarget.DeleteWebAuthnCredential]: DeleteWebAuthnCredentialRequest;
534
+ [ServiceTarget.ListWebAuthnCredentials]: ListWebAuthnCredentialsRequest;
441
535
  };
442
536
  export declare function adaptExpiresIn(auth: AuthenticationResult): {
443
537
  ExpiresIn: number;
@@ -458,6 +552,7 @@ export declare class CognitoClient {
458
552
  private readonly clientSecret?;
459
553
  constructor({ userPoolId, userPoolClientId, endpoint, oAuth2: oAuth, clientSecret }: CognitoClientProps);
460
554
  static getDecodedTokenFromSession(auth: AuthenticationResult): DecodedTokens;
555
+ initiateAuth(request: InitiateAuthRequest): Promise<InitiateAuthResponse>;
461
556
  /**
462
557
  *
463
558
  * Performs user authentication with username and password through ALLOW_USER_SRP_AUTH .
@@ -479,6 +574,19 @@ export declare class CognitoClient {
479
574
  * @throws {InitAuthError}
480
575
  */
481
576
  authenticateUser(username: string, password: string): Promise<InitiateAuthResponse>;
577
+ /**
578
+ * Initiates the authentication process for a user using a preferred challenge, such as WEB_AUTHN.
579
+ */
580
+ authenticateWebAuthn(username: string): Promise<InitiateAuthResponse>;
581
+ /**
582
+ * Registers a new WebAuthn device for the current user.
583
+ * This method initiates the WebAuthn registration process by requesting the necessary options from Cognito,
584
+ * then creates a new public key credential using the WebAuthn API, and finally
585
+ * completes the registration by sending the credential back to Cognito.
586
+ *
587
+ * @param accessToken Access token of the current user.
588
+ */
589
+ registerWebAuthnDevice(accessToken: string): Promise<void>;
482
590
  /**
483
591
  * Returns a new session based on the given refresh token.
484
592
  *
@@ -516,8 +624,33 @@ export declare class CognitoClient {
516
624
  * @throws {ChangePasswordError}
517
625
  */
518
626
  changePassword(currentPassword: string, newPassword: string, accessToken: string): Promise<void>;
627
+ /**
628
+ * Gets the user information.
629
+ * @param accessToken Access token of the current user.
630
+ * @returns User information.
631
+ */
519
632
  getUser(accessToken: string): Promise<GetUserResponse>;
633
+ /**
634
+ * Associates a software token with the user.
635
+ * @param params Request to associate a software token with the user.
636
+ * @param params.AccessToken Access token of the current user.
637
+ * @param params.Session Optional session identifier for the authentication process.
638
+ * @param params.ClientMetadata Optional metadata to pass to the service.
639
+ * @param params.UserContextData Optional user context data.
640
+ * @param params.AnalyticsMetadata Optional analytics metadata.
641
+ * @param params.FriendlyDeviceName Optional friendly name for the device.
642
+ * @returns
643
+ */
520
644
  associateSoftwareToken(params: AssociateSoftwareTokenRequest): Promise<AssociateSoftwareResponse>;
645
+ /**
646
+ * Verifies a software token.
647
+ * @param params Request to verify a software token.
648
+ * @param params.AccessToken Access token of the current user.
649
+ * @param params.FriendlyDeviceName Optional friendly name for the device.
650
+ * @param params.Session Optional session identifier for the authentication process.
651
+ * @param params.UserCode The user code to verify.
652
+ * @returns
653
+ */
521
654
  verifySoftwareToken(params: VerifySoftwareTokenRequest): Promise<VerifySoftwareTokenResponse>;
522
655
  /**
523
656
  * Responds to an authentication challenge.
@@ -602,6 +735,32 @@ export declare class CognitoClient {
602
735
  * @throws {ResendConfirmationCodeError}
603
736
  */
604
737
  resendConfirmationCode(username: string): Promise<void>;
738
+ startWebAuthnRegistration(request: StartWebAuthnRegistrationRequest): Promise<StartWebAuthnRegistrationResponse>;
739
+ /**
740
+ * Completes registration of a passkey authenticator for the currently signed-in user.
741
+ * @param request Request to complete WebAuthn registration.
742
+ * @param request.AccessToken Access token of the current user.
743
+ * @param request.Credential The credential object returned by the WebAuthn API.
744
+ */
745
+ completeWebAuthnRegistration(request: CompleteWebAuthnRegistrationRequest): Promise<void>;
746
+ /**
747
+ * Deletes a registered passkey, or WebAuthn, authenticator for the currently signed-in user.
748
+ *
749
+ * @param request Request to delete a WebAuthn credential.
750
+ * @param request.AccessToken Access token of the current user.
751
+ * @param request.CredentialId The ID of the credential to delete.
752
+ */
753
+ deleteWebAuthnCredential(request: DeleteWebAuthnCredentialRequest): Promise<void>;
754
+ /**
755
+ * Lists all registered WebAuthn credentials for the currently signed-in user.
756
+ *
757
+ * @param request Request to list WebAuthn credentials.
758
+ * @param request.AccessToken Access token of the current user.
759
+ * @param request.MaxResults Maximum number of credentials to return.
760
+ * @param request.NextToken Pagination token to continue listing credentials.
761
+ * @returns
762
+ */
763
+ listWebAuthnCredentials(request: ListWebAuthnCredentialsRequest): Promise<ListWebAuthnCredentialsResponse>;
605
764
  /**
606
765
  * Returns a link to Cognito`s Hosted UI for OAuth2 authentication.
607
766
  * This method works in conjunction with @see handleCodeFlow .
@@ -1,5 +1,5 @@
1
- import { ChangePasswordError, ConfirmForgotPasswordError, ConfirmSignUpError, ForgotPasswordError, GlobalSignOutError, InitAuthError, ResendConfirmationCodeError, RespondToAuthChallengeError, RevokeTokenError, SignUpError, UpdateUserAttributesError, VerifyUserAttributeError, InitiateAuthException, COMMON_EXCEPTIONS, CommonError, VerifySoftwareTokenError } from './error.js';
2
- import { calculateSecretHash, calculateSignature, calculateU, decodeJwt, digest, generateA, generateSmallA, getPasswordAuthenticationKey, randomBytes, uint8ArrayFromString, uint8ArrayToBase64String } from './utils.js';
1
+ import { ChangePasswordError, ConfirmForgotPasswordError, ConfirmSignUpError, ForgotPasswordError, GlobalSignOutError, InitAuthError, ResendConfirmationCodeError, RespondToAuthChallengeError, RevokeTokenError, SignUpError, UpdateUserAttributesError, VerifyUserAttributeError, InitiateAuthException, COMMON_EXCEPTIONS, CommonError, VerifySoftwareTokenError, AssociateSoftwareTokenError, SetUserMFAPreferenceError, ListDevicesError, GetUserError } from './error.js';
2
+ import { base64UrlToUint8Array, calculateSecretHash, calculateSignature, calculateU, decodeJwt, digest, generateA, generateSmallA, getPasswordAuthenticationKey, publicKeyCredentialToJSON, randomBytes, uint8ArrayFromString, uint8ArrayToBase64String } from './utils.js';
3
3
  /**
4
4
  * List of used and supported Cognito API calls.
5
5
  * @see https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_Operations.html for more details
@@ -23,6 +23,10 @@ export var ServiceTarget;
23
23
  ServiceTarget["VerifySoftwareToken"] = "VerifySoftwareToken";
24
24
  ServiceTarget["ListDevices"] = "ListDevices";
25
25
  ServiceTarget["SetUserMFAPreference"] = "SetUserMFAPreference";
26
+ ServiceTarget["StartWebAuthnRegistration"] = "StartWebAuthnRegistration";
27
+ ServiceTarget["CompleteWebAuthnRegistration"] = "CompleteWebAuthnRegistration";
28
+ ServiceTarget["DeleteWebAuthnCredential"] = "DeleteWebAuthnCredential";
29
+ ServiceTarget["ListWebAuthnCredentials"] = "ListWebAuthnCredentials";
26
30
  })(ServiceTarget || (ServiceTarget = {}));
27
31
  /**
28
32
  * Cognito supported federated identities public providers.
@@ -103,14 +107,27 @@ export async function cognitoRequest(body, serviceTarget, cognitoEndpoint) {
103
107
  throw new VerifyUserAttributeError(errorMessage, cognitoException);
104
108
  case ServiceTarget.GlobalSignOut:
105
109
  throw new GlobalSignOutError(errorMessage, cognitoException);
110
+ case ServiceTarget.AssociateSoftwareToken:
111
+ throw new AssociateSoftwareTokenError(errorMessage, cognitoException);
106
112
  case ServiceTarget.VerifySoftwareToken:
107
113
  throw new VerifySoftwareTokenError(errorMessage, cognitoException);
114
+ case ServiceTarget.SetUserMFAPreference:
115
+ throw new SetUserMFAPreferenceError(errorMessage, cognitoException);
116
+ case ServiceTarget.ListDevices:
117
+ throw new ListDevicesError(errorMessage, cognitoException);
118
+ case ServiceTarget.GetUser:
119
+ throw new GetUserError(errorMessage, cognitoException);
108
120
  }
109
121
  }
110
122
  /**
111
123
  * Lightweight AWS Cogito client without any AWS SDK dependencies.
112
124
  */
113
125
  export class CognitoClient {
126
+ cognitoEndpoint;
127
+ cognitoPoolName;
128
+ userPoolClientId;
129
+ oAuth;
130
+ clientSecret;
114
131
  constructor({ userPoolId, userPoolClientId, endpoint, oAuth2: oAuth, clientSecret }) {
115
132
  const [cognitoPoolRegion, cognitoPoolName] = userPoolId.split('_');
116
133
  this.cognitoEndpoint = (endpoint || `https://cognito-idp.${cognitoPoolRegion}.amazonaws.com`).replace(/\/$/, '');
@@ -127,6 +144,16 @@ export class CognitoClient {
127
144
  accessToken
128
145
  };
129
146
  }
147
+ async initiateAuth(request) {
148
+ const cognitoResponse = await cognitoRequest({
149
+ ...request,
150
+ ClientId: this.userPoolClientId
151
+ }, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
152
+ if (cognitoResponse.AuthenticationResult) {
153
+ cognitoResponse.AuthenticationResult = adaptExpiresIn(cognitoResponse.AuthenticationResult);
154
+ }
155
+ return cognitoResponse;
156
+ }
130
157
  /**
131
158
  *
132
159
  * Performs user authentication with username and password through ALLOW_USER_SRP_AUTH .
@@ -140,16 +167,15 @@ export class CognitoClient {
140
167
  async authenticateUserSrp(username, password) {
141
168
  const smallA = await generateSmallA();
142
169
  const A = generateA(smallA);
143
- const initUserSrpAuthResponse = await cognitoRequest({
170
+ const initUserSrpAuthResponse = await this.initiateAuth({
144
171
  AuthFlow: 'USER_SRP_AUTH',
145
- ClientId: this.userPoolClientId,
146
172
  AuthParameters: {
147
173
  USERNAME: username,
148
174
  SRP_A: A.toString(16),
149
175
  SECRET_HASH: this.clientSecret && (await calculateSecretHash(this.clientSecret, this.userPoolClientId, username))
150
176
  },
151
177
  ClientMetadata: {}
152
- }, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
178
+ });
153
179
  if (initUserSrpAuthResponse.ChallengeName !== 'PASSWORD_VERIFIER') {
154
180
  return initUserSrpAuthResponse;
155
181
  }
@@ -187,7 +213,6 @@ export class CognitoClient {
187
213
  async authenticateUser(username, password) {
188
214
  const initiateAuthPayload = {
189
215
  AuthFlow: 'USER_PASSWORD_AUTH',
190
- ClientId: this.userPoolClientId,
191
216
  AuthParameters: {
192
217
  USERNAME: username,
193
218
  PASSWORD: password,
@@ -195,13 +220,73 @@ export class CognitoClient {
195
220
  },
196
221
  ClientMetadata: {}
197
222
  };
198
- const initUserPasswordAuthResponse = await cognitoRequest(initiateAuthPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
223
+ const initUserPasswordAuthResponse = await this.initiateAuth(initiateAuthPayload);
199
224
  if (!initUserPasswordAuthResponse.AuthenticationResult) {
200
225
  return initUserPasswordAuthResponse;
201
226
  }
202
- initUserPasswordAuthResponse.AuthenticationResult = adaptExpiresIn(initUserPasswordAuthResponse.AuthenticationResult);
203
227
  return initUserPasswordAuthResponse;
204
228
  }
229
+ /**
230
+ * Initiates the authentication process for a user using a preferred challenge, such as WEB_AUTHN.
231
+ */
232
+ async authenticateWebAuthn(username) {
233
+ const webAuthnPayload = {
234
+ AuthFlow: 'USER_AUTH',
235
+ AuthParameters: {
236
+ USERNAME: username,
237
+ PREFERRED_CHALLENGE: 'WEB_AUTHN'
238
+ }
239
+ };
240
+ const authResponse = await this.initiateAuth(webAuthnPayload);
241
+ if (authResponse.ChallengeName !== 'WEB_AUTHN') {
242
+ throw new InitAuthError('Authentication failed, expected WEB_AUTHN challenge but received: ' + authResponse.ChallengeName, InitiateAuthException.InternalErrorException);
243
+ }
244
+ const credentialRequestOptions = JSON.parse(authResponse.ChallengeParameters.CREDENTIAL_REQUEST_OPTIONS);
245
+ credentialRequestOptions.challenge = base64UrlToUint8Array(credentialRequestOptions.challenge);
246
+ credentialRequestOptions.allowCredentials = (credentialRequestOptions.allowCredentials || []).map((allowCred) => ({
247
+ ...allowCred,
248
+ id: base64UrlToUint8Array(allowCred.id)
249
+ }));
250
+ const credentials = await navigator.credentials.get({
251
+ publicKey: credentialRequestOptions
252
+ });
253
+ const challengeResponse = await this.respondToAuthChallenge({
254
+ ChallengeName: 'WEB_AUTHN',
255
+ ChallengeResponses: {
256
+ USERNAME: username,
257
+ CREDENTIAL: JSON.stringify(publicKeyCredentialToJSON(credentials)),
258
+ SECRET_HASH: this.clientSecret && (await calculateSecretHash(this.clientSecret, this.userPoolClientId, username))
259
+ },
260
+ Session: authResponse.Session
261
+ });
262
+ if (challengeResponse.AuthenticationResult) {
263
+ challengeResponse.AuthenticationResult = adaptExpiresIn(challengeResponse.AuthenticationResult);
264
+ }
265
+ return challengeResponse;
266
+ }
267
+ /**
268
+ * Registers a new WebAuthn device for the current user.
269
+ * This method initiates the WebAuthn registration process by requesting the necessary options from Cognito,
270
+ * then creates a new public key credential using the WebAuthn API, and finally
271
+ * completes the registration by sending the credential back to Cognito.
272
+ *
273
+ * @param accessToken Access token of the current user.
274
+ */
275
+ async registerWebAuthnDevice(accessToken) {
276
+ const { CredentialCreationOptions } = await this.startWebAuthnRegistration({
277
+ AccessToken: accessToken
278
+ });
279
+ const credentials = await navigator.credentials.create({
280
+ publicKey: CredentialCreationOptions
281
+ });
282
+ if (!(credentials instanceof PublicKeyCredential)) {
283
+ throw new Error('Invalid credentials returned from WebAuthn API');
284
+ }
285
+ await this.completeWebAuthnRegistration({
286
+ AccessToken: accessToken,
287
+ Credential: credentials
288
+ });
289
+ }
205
290
  /**
206
291
  * Returns a new session based on the given refresh token.
207
292
  *
@@ -213,7 +298,6 @@ export class CognitoClient {
213
298
  async refreshSession(refreshToken, username) {
214
299
  const refreshTokenPayload = {
215
300
  AuthFlow: 'REFRESH_TOKEN_AUTH',
216
- ClientId: this.userPoolClientId,
217
301
  AuthParameters: {
218
302
  REFRESH_TOKEN: refreshToken,
219
303
  SECRET_HASH: this.clientSecret &&
@@ -222,14 +306,14 @@ export class CognitoClient {
222
306
  },
223
307
  ClientMetadata: {}
224
308
  };
225
- const { AuthenticationResult } = await cognitoRequest(refreshTokenPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
309
+ const { AuthenticationResult } = await this.initiateAuth(refreshTokenPayload);
226
310
  if (!AuthenticationResult) {
227
311
  throw new InitAuthError('Authentication failed, no authentication result returned', InitiateAuthException.InternalErrorException);
228
312
  }
229
313
  if (!AuthenticationResult.RefreshToken) {
230
314
  AuthenticationResult.RefreshToken = refreshToken;
231
315
  }
232
- return adaptExpiresIn(AuthenticationResult);
316
+ return AuthenticationResult;
233
317
  }
234
318
  /**
235
319
  *
@@ -284,15 +368,40 @@ export class CognitoClient {
284
368
  };
285
369
  await cognitoRequest(changePasswordPayload, ServiceTarget.ChangePassword, this.cognitoEndpoint);
286
370
  }
371
+ /**
372
+ * Gets the user information.
373
+ * @param accessToken Access token of the current user.
374
+ * @returns User information.
375
+ */
287
376
  async getUser(accessToken) {
288
377
  const getUserPayload = {
289
378
  AccessToken: accessToken
290
379
  };
291
380
  return cognitoRequest(getUserPayload, ServiceTarget.GetUser, this.cognitoEndpoint);
292
381
  }
382
+ /**
383
+ * Associates a software token with the user.
384
+ * @param params Request to associate a software token with the user.
385
+ * @param params.AccessToken Access token of the current user.
386
+ * @param params.Session Optional session identifier for the authentication process.
387
+ * @param params.ClientMetadata Optional metadata to pass to the service.
388
+ * @param params.UserContextData Optional user context data.
389
+ * @param params.AnalyticsMetadata Optional analytics metadata.
390
+ * @param params.FriendlyDeviceName Optional friendly name for the device.
391
+ * @returns
392
+ */
293
393
  async associateSoftwareToken(params) {
294
394
  return cognitoRequest(params, ServiceTarget.AssociateSoftwareToken, this.cognitoEndpoint);
295
395
  }
396
+ /**
397
+ * Verifies a software token.
398
+ * @param params Request to verify a software token.
399
+ * @param params.AccessToken Access token of the current user.
400
+ * @param params.FriendlyDeviceName Optional friendly name for the device.
401
+ * @param params.Session Optional session identifier for the authentication process.
402
+ * @param params.UserCode The user code to verify.
403
+ * @returns
404
+ */
296
405
  async verifySoftwareToken(params) {
297
406
  return cognitoRequest(params, ServiceTarget.VerifySoftwareToken, this.cognitoEndpoint);
298
407
  }
@@ -431,6 +540,51 @@ export class CognitoClient {
431
540
  };
432
541
  await cognitoRequest(resendConfirmationCodeRequest, ServiceTarget.ResendConfirmationCode, this.cognitoEndpoint);
433
542
  }
543
+ async startWebAuthnRegistration(request) {
544
+ const response = await cognitoRequest(request, ServiceTarget.StartWebAuthnRegistration, this.cognitoEndpoint);
545
+ response.CredentialCreationOptions.challenge = base64UrlToUint8Array(response.CredentialCreationOptions.challenge);
546
+ response.CredentialCreationOptions.user.id = base64UrlToUint8Array(response.CredentialCreationOptions.user.id);
547
+ response.CredentialCreationOptions.excludeCredentials = (response.CredentialCreationOptions.excludeCredentials || []).map((excludeCred) => ({
548
+ ...excludeCred,
549
+ id: base64UrlToUint8Array(excludeCred.id)
550
+ }));
551
+ return response;
552
+ }
553
+ /**
554
+ * Completes registration of a passkey authenticator for the currently signed-in user.
555
+ * @param request Request to complete WebAuthn registration.
556
+ * @param request.AccessToken Access token of the current user.
557
+ * @param request.Credential The credential object returned by the WebAuthn API.
558
+ */
559
+ async completeWebAuthnRegistration(request) {
560
+ await cognitoRequest({
561
+ AccessToken: request.AccessToken,
562
+ Credential: publicKeyCredentialToJSON(request.Credential)
563
+ }, ServiceTarget.CompleteWebAuthnRegistration, this.cognitoEndpoint);
564
+ }
565
+ /**
566
+ * Deletes a registered passkey, or WebAuthn, authenticator for the currently signed-in user.
567
+ *
568
+ * @param request Request to delete a WebAuthn credential.
569
+ * @param request.AccessToken Access token of the current user.
570
+ * @param request.CredentialId The ID of the credential to delete.
571
+ */
572
+ async deleteWebAuthnCredential(request) {
573
+ await cognitoRequest(request, ServiceTarget.DeleteWebAuthnCredential, this.cognitoEndpoint);
574
+ }
575
+ /**
576
+ * Lists all registered WebAuthn credentials for the currently signed-in user.
577
+ *
578
+ * @param request Request to list WebAuthn credentials.
579
+ * @param request.AccessToken Access token of the current user.
580
+ * @param request.MaxResults Maximum number of credentials to return.
581
+ * @param request.NextToken Pagination token to continue listing credentials.
582
+ * @returns
583
+ */
584
+ async listWebAuthnCredentials(request) {
585
+ const response = await cognitoRequest(request, ServiceTarget.ListWebAuthnCredentials, this.cognitoEndpoint);
586
+ return response;
587
+ }
434
588
  /**
435
589
  * Returns a link to Cognito`s Hosted UI for OAuth2 authentication.
436
590
  * This method works in conjunction with @see handleCodeFlow .
package/lib/error.d.ts CHANGED
@@ -362,11 +362,11 @@ export declare enum RevokeTokenException {
362
362
  UnsupportedOperationException = "UnsupportedOperationException",
363
363
  UnsupportedTokenTypeException = "UnsupportedTokenTypeException"
364
364
  }
365
- export type CognitoErrorType = 'CommonError' | 'InitAuthError' | 'RespondToAuthChallengeError' | 'SignUpError' | 'ConfirmSignUpError' | 'VerifySoftwareTokenError' | 'ChangePasswordError' | 'RevokeTokenError' | 'ForgotPasswordError' | 'ConfirmForgotPasswordError' | 'ResendConfirmationCodeError' | 'UpdateUserAttributesError' | 'VerifyUserAttributeError' | 'AssociateSoftwareTokenError' | 'GlobalSignOutError';
365
+ export type CognitoErrorType = 'CommonError' | 'InitAuthError' | 'RespondToAuthChallengeError' | 'SignUpError' | 'ConfirmSignUpError' | 'VerifySoftwareTokenError' | 'ChangePasswordError' | 'RevokeTokenError' | 'ForgotPasswordError' | 'ConfirmForgotPasswordError' | 'ResendConfirmationCodeError' | 'UpdateUserAttributesError' | 'VerifyUserAttributeError' | 'AssociateSoftwareTokenError' | 'GlobalSignOutError' | 'SetUserMFAPreferenceError' | 'GetUserError' | 'ListDevicesError';
366
366
  export declare class CognitoError extends Error {
367
367
  readonly errorType: CognitoErrorType;
368
- readonly cognitoException: CommonException | InitiateAuthException | RespondToAuthChallengeException | SignUpException | ConfirmSignUpException | ChangePasswordException | RevokeTokenException | ForgotPasswordException | ConfirmForgotPasswordException | ResendConfirmationException | UpdateUserAttributesException | VerifyUserAttributeException | GlobalSignOutException | VerifySoftwareTokenException | AssociateSoftwareTokenException;
369
- constructor(message: string, errorType: CognitoErrorType, cognitoException: CommonException | InitiateAuthException | RespondToAuthChallengeException | SignUpException | ConfirmSignUpException | ChangePasswordException | RevokeTokenException | ForgotPasswordException | ConfirmForgotPasswordException | ResendConfirmationException | UpdateUserAttributesException | VerifyUserAttributeException | GlobalSignOutException | VerifySoftwareTokenException | AssociateSoftwareTokenException);
368
+ readonly cognitoException: CommonException | InitiateAuthException | RespondToAuthChallengeException | SignUpException | ConfirmSignUpException | ChangePasswordException | RevokeTokenException | ForgotPasswordException | ConfirmForgotPasswordException | ResendConfirmationException | UpdateUserAttributesException | VerifyUserAttributeException | GlobalSignOutException | VerifySoftwareTokenException | AssociateSoftwareTokenException | SetUserMFAPreferenceException | ListDevicesException | GetUserException;
369
+ constructor(message: string, errorType: CognitoErrorType, cognitoException: CommonException | InitiateAuthException | RespondToAuthChallengeException | SignUpException | ConfirmSignUpException | ChangePasswordException | RevokeTokenException | ForgotPasswordException | ConfirmForgotPasswordException | ResendConfirmationException | UpdateUserAttributesException | VerifyUserAttributeException | GlobalSignOutException | VerifySoftwareTokenException | AssociateSoftwareTokenException | SetUserMFAPreferenceException | ListDevicesException | GetUserException);
370
370
  }
371
371
  export declare class CommonError extends CognitoError {
372
372
  readonly cognitoException: CommonException;
@@ -428,3 +428,15 @@ export declare class AssociateSoftwareTokenError extends CognitoError {
428
428
  readonly cognitoException: AssociateSoftwareTokenException;
429
429
  constructor(message: string, cognitoException: AssociateSoftwareTokenException);
430
430
  }
431
+ export declare class SetUserMFAPreferenceError extends CognitoError {
432
+ readonly cognitoException: SetUserMFAPreferenceException;
433
+ constructor(message: string, cognitoException: SetUserMFAPreferenceException);
434
+ }
435
+ export declare class ListDevicesError extends CognitoError {
436
+ readonly cognitoException: ListDevicesException;
437
+ constructor(message: string, cognitoException: ListDevicesException);
438
+ }
439
+ export declare class GetUserError extends CognitoError {
440
+ readonly cognitoException: GetUserException;
441
+ constructor(message: string, cognitoException: GetUserException);
442
+ }