@vardario/cognito-client 4.0.6 → 5.0.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.
package/lib/browser.js CHANGED
@@ -223,23 +223,23 @@ var GlobalSignOutException = /* @__PURE__ */ ((GlobalSignOutException3) => {
223
223
  GlobalSignOutException3["UserNotConfirmedException"] = "UserNotConfirmedException";
224
224
  return GlobalSignOutException3;
225
225
  })(GlobalSignOutException || {});
226
- var InitiateAuthException = /* @__PURE__ */ ((InitiateAuthException3) => {
227
- InitiateAuthException3["PasswordResetRequiredException"] = "PasswordResetRequiredException";
228
- InitiateAuthException3["ForbiddenException"] = "ForbiddenException";
229
- InitiateAuthException3["InternalErrorException"] = "InternalErrorException";
230
- InitiateAuthException3["InvalidLambdaResponseException"] = "InvalidLambdaResponseException";
231
- InitiateAuthException3["InvalidParameterException"] = "InvalidParameterException";
232
- InitiateAuthException3["InvalidSmsRoleAccessPolicyException"] = "InvalidSmsRoleAccessPolicyException";
233
- InitiateAuthException3["InvalidSmsRoleTrustRelationshipException"] = "InvalidSmsRoleTrustRelationshipException";
234
- InitiateAuthException3["InvalidUserPoolConfigurationException"] = "InvalidUserPoolConfigurationException";
235
- InitiateAuthException3["NotAuthorizedException"] = "NotAuthorizedException";
236
- InitiateAuthException3["ResourceNotFoundException"] = "ResourceNotFoundException";
237
- InitiateAuthException3["TooManyRequestsException"] = "TooManyRequestsException";
238
- InitiateAuthException3["UnexpectedLambdaException"] = "UnexpectedLambdaException";
239
- InitiateAuthException3["UserLambdaValidationException"] = "UserLambdaValidationException";
240
- InitiateAuthException3["UserNotConfirmedException"] = "UserNotConfirmedException";
241
- InitiateAuthException3["UserNotFoundException"] = "UserNotFoundException";
242
- return InitiateAuthException3;
226
+ var InitiateAuthException = /* @__PURE__ */ ((InitiateAuthException2) => {
227
+ InitiateAuthException2["PasswordResetRequiredException"] = "PasswordResetRequiredException";
228
+ InitiateAuthException2["ForbiddenException"] = "ForbiddenException";
229
+ InitiateAuthException2["InternalErrorException"] = "InternalErrorException";
230
+ InitiateAuthException2["InvalidLambdaResponseException"] = "InvalidLambdaResponseException";
231
+ InitiateAuthException2["InvalidParameterException"] = "InvalidParameterException";
232
+ InitiateAuthException2["InvalidSmsRoleAccessPolicyException"] = "InvalidSmsRoleAccessPolicyException";
233
+ InitiateAuthException2["InvalidSmsRoleTrustRelationshipException"] = "InvalidSmsRoleTrustRelationshipException";
234
+ InitiateAuthException2["InvalidUserPoolConfigurationException"] = "InvalidUserPoolConfigurationException";
235
+ InitiateAuthException2["NotAuthorizedException"] = "NotAuthorizedException";
236
+ InitiateAuthException2["ResourceNotFoundException"] = "ResourceNotFoundException";
237
+ InitiateAuthException2["TooManyRequestsException"] = "TooManyRequestsException";
238
+ InitiateAuthException2["UnexpectedLambdaException"] = "UnexpectedLambdaException";
239
+ InitiateAuthException2["UserLambdaValidationException"] = "UserLambdaValidationException";
240
+ InitiateAuthException2["UserNotConfirmedException"] = "UserNotConfirmedException";
241
+ InitiateAuthException2["UserNotFoundException"] = "UserNotFoundException";
242
+ return InitiateAuthException2;
243
243
  })(InitiateAuthException || {});
244
244
  var ResendConfirmationException = /* @__PURE__ */ ((ResendConfirmationException3) => {
245
245
  ResendConfirmationException3["CodeDeliveryFailureException"] = "CodeDeliveryFailureException";
@@ -333,21 +333,21 @@ var UpdateUserAttributesException = /* @__PURE__ */ ((UpdateUserAttributesExcept
333
333
  UpdateUserAttributesException3["UserNotFoundException"] = "UserNotFoundException";
334
334
  return UpdateUserAttributesException3;
335
335
  })(UpdateUserAttributesException || {});
336
- var VerifySoftwareTokenException = /* @__PURE__ */ ((VerifySoftwareTokenException2) => {
337
- VerifySoftwareTokenException2["CodeMismatchException"] = "CodeMismatchException";
338
- VerifySoftwareTokenException2["EnableSoftwareTokenMFAException"] = "EnableSoftwareTokenMFAException";
339
- VerifySoftwareTokenException2["ForbiddenException"] = "ForbiddenException";
340
- VerifySoftwareTokenException2["InternalErrorException"] = "InternalErrorException";
341
- VerifySoftwareTokenException2["InvalidParameterException"] = "InvalidParameterException";
342
- VerifySoftwareTokenException2["InvalidUserPoolConfigurationException"] = "InvalidUserPoolConfigurationException";
343
- VerifySoftwareTokenException2["NotAuthorizedException"] = "NotAuthorizedException";
344
- VerifySoftwareTokenException2["PasswordResetRequiredException"] = "PasswordResetRequiredException";
345
- VerifySoftwareTokenException2["ResourceNotFoundException"] = "ResourceNotFoundException";
346
- VerifySoftwareTokenException2["SoftwareTokenMFANotFoundException"] = "SoftwareTokenMFANotFoundException";
347
- VerifySoftwareTokenException2["TooManyRequestsException"] = "TooManyRequestsException";
348
- VerifySoftwareTokenException2["UserNotConfirmedException"] = "UserNotConfirmedException";
349
- VerifySoftwareTokenException2["UserNotFoundException"] = "UserNotFoundException";
350
- return VerifySoftwareTokenException2;
336
+ var VerifySoftwareTokenException = /* @__PURE__ */ ((VerifySoftwareTokenException3) => {
337
+ VerifySoftwareTokenException3["CodeMismatchException"] = "CodeMismatchException";
338
+ VerifySoftwareTokenException3["EnableSoftwareTokenMFAException"] = "EnableSoftwareTokenMFAException";
339
+ VerifySoftwareTokenException3["ForbiddenException"] = "ForbiddenException";
340
+ VerifySoftwareTokenException3["InternalErrorException"] = "InternalErrorException";
341
+ VerifySoftwareTokenException3["InvalidParameterException"] = "InvalidParameterException";
342
+ VerifySoftwareTokenException3["InvalidUserPoolConfigurationException"] = "InvalidUserPoolConfigurationException";
343
+ VerifySoftwareTokenException3["NotAuthorizedException"] = "NotAuthorizedException";
344
+ VerifySoftwareTokenException3["PasswordResetRequiredException"] = "PasswordResetRequiredException";
345
+ VerifySoftwareTokenException3["ResourceNotFoundException"] = "ResourceNotFoundException";
346
+ VerifySoftwareTokenException3["SoftwareTokenMFANotFoundException"] = "SoftwareTokenMFANotFoundException";
347
+ VerifySoftwareTokenException3["TooManyRequestsException"] = "TooManyRequestsException";
348
+ VerifySoftwareTokenException3["UserNotConfirmedException"] = "UserNotConfirmedException";
349
+ VerifySoftwareTokenException3["UserNotFoundException"] = "UserNotFoundException";
350
+ return VerifySoftwareTokenException3;
351
351
  })(VerifySoftwareTokenException || {});
352
352
  var VerifyUserAttributeException = /* @__PURE__ */ ((VerifyUserAttributeException3) => {
353
353
  VerifyUserAttributeException3["AliasExistsException"] = "AliasExistsException";
@@ -486,16 +486,25 @@ var GlobalSignOutError = class extends CognitoError {
486
486
  this.cognitoException = cognitoException;
487
487
  }
488
488
  };
489
+ var VerifySoftwareTokenError = class extends CognitoError {
490
+ constructor(message, cognitoException) {
491
+ super(message, "VerifySoftwareTokenError", cognitoException);
492
+ this.cognitoException = cognitoException;
493
+ }
494
+ };
495
+ var AssociateSoftwareTokenError = class extends CognitoError {
496
+ constructor(message, cognitoException) {
497
+ super(message, "AssociateSoftwareTokenError", cognitoException);
498
+ this.cognitoException = cognitoException;
499
+ }
500
+ };
489
501
 
490
502
  // src/bigint-math.ts
491
503
  var abs = (n) => n < 0n ? -n : n;
492
504
  function eGcd(a, b) {
493
- if (typeof a === "number")
494
- a = BigInt(a);
495
- if (typeof b === "number")
496
- b = BigInt(b);
497
- if (a <= 0n || b <= 0n)
498
- throw new RangeError("a and b MUST be > 0");
505
+ if (typeof a === "number") a = BigInt(a);
506
+ if (typeof b === "number") b = BigInt(b);
507
+ if (a <= 0n || b <= 0n) throw new RangeError("a and b MUST be > 0");
499
508
  let x = 0n;
500
509
  let y = 1n;
501
510
  let u = 1n;
@@ -708,6 +717,11 @@ var ServiceTarget = /* @__PURE__ */ ((ServiceTarget2) => {
708
717
  ServiceTarget2["UpdateUserAttributes"] = "UpdateUserAttributes";
709
718
  ServiceTarget2["VerifyUserAttribute"] = "VerifyUserAttribute";
710
719
  ServiceTarget2["GlobalSignOut"] = "GlobalSignOut";
720
+ ServiceTarget2["GetUser"] = "GetUser";
721
+ ServiceTarget2["AssociateSoftwareToken"] = "AssociateSoftwareToken";
722
+ ServiceTarget2["VerifySoftwareToken"] = "VerifySoftwareToken";
723
+ ServiceTarget2["ListDevices"] = "ListDevices";
724
+ ServiceTarget2["SetUserMFAPreference"] = "SetUserMFAPreference";
711
725
  return ServiceTarget2;
712
726
  })(ServiceTarget || {});
713
727
  var IdentityProvider = /* @__PURE__ */ ((IdentityProvider2) => {
@@ -718,12 +732,10 @@ var IdentityProvider = /* @__PURE__ */ ((IdentityProvider2) => {
718
732
  IdentityProvider2["Apple"] = "SignInWithApple";
719
733
  return IdentityProvider2;
720
734
  })(IdentityProvider || {});
721
- function authResultToSession(authenticationResult) {
735
+ function adaptExpiresIn(auth) {
722
736
  return {
723
- accessToken: authenticationResult.AccessToken,
724
- idToken: authenticationResult.IdToken,
725
- expiresIn: (/* @__PURE__ */ new Date()).getTime() + authenticationResult.ExpiresIn * 1e3,
726
- refreshToken: authenticationResult.RefreshToken
737
+ ...auth,
738
+ ExpiresIn: (/* @__PURE__ */ new Date()).getTime() + auth.ExpiresIn * 1e3
727
739
  };
728
740
  }
729
741
  async function cognitoRequest(body, serviceTarget, cognitoEndpoint) {
@@ -778,6 +790,8 @@ async function cognitoRequest(body, serviceTarget, cognitoEndpoint) {
778
790
  throw new VerifyUserAttributeError(errorMessage, cognitoException);
779
791
  case "GlobalSignOut" /* GlobalSignOut */:
780
792
  throw new GlobalSignOutError(errorMessage, cognitoException);
793
+ case "VerifySoftwareToken" /* VerifySoftwareToken */:
794
+ throw new VerifySoftwareTokenError(errorMessage, cognitoException);
781
795
  }
782
796
  }
783
797
  var CognitoClient = class {
@@ -789,9 +803,9 @@ var CognitoClient = class {
789
803
  this.oAuth = oAuth;
790
804
  this.clientSecret = clientSecret;
791
805
  }
792
- static getDecodedTokenFromSession(session) {
793
- const { payload: idToken } = decodeJwt(session.idToken);
794
- const { payload: accessToken } = decodeJwt(session.accessToken);
806
+ static getDecodedTokenFromSession(auth) {
807
+ const { payload: idToken } = decodeJwt(auth.IdToken);
808
+ const { payload: accessToken } = decodeJwt(auth.AccessToken);
795
809
  return {
796
810
  idToken,
797
811
  accessToken
@@ -810,27 +824,29 @@ var CognitoClient = class {
810
824
  async authenticateUserSrp(username, password) {
811
825
  const smallA = await generateSmallA();
812
826
  const A = generateA(smallA);
813
- const initiateAuthPayload = {
814
- AuthFlow: "USER_SRP_AUTH",
815
- ClientId: this.userPoolClientId,
816
- AuthParameters: {
817
- USERNAME: username,
818
- SRP_A: A.toString(16),
819
- SECRET_HASH: this.clientSecret && await calculateSecretHash(this.clientSecret, this.userPoolClientId, username)
827
+ const initUserSrpAuthResponse = await cognitoRequest(
828
+ {
829
+ AuthFlow: "USER_SRP_AUTH",
830
+ ClientId: this.userPoolClientId,
831
+ AuthParameters: {
832
+ USERNAME: username,
833
+ SRP_A: A.toString(16),
834
+ SECRET_HASH: this.clientSecret && await calculateSecretHash(this.clientSecret, this.userPoolClientId, username)
835
+ },
836
+ ClientMetadata: {}
820
837
  },
821
- ClientMetadata: {}
822
- };
823
- const challenge = await cognitoRequest(
824
- initiateAuthPayload,
825
838
  "InitiateAuth" /* InitiateAuth */,
826
839
  this.cognitoEndpoint
827
840
  );
828
- const B = BigInt("0x" + challenge.ChallengeParameters.SRP_B);
829
- const salt = BigInt("0x" + challenge.ChallengeParameters.SALT);
841
+ if (initUserSrpAuthResponse.ChallengeName !== "PASSWORD_VERIFIER") {
842
+ return initUserSrpAuthResponse;
843
+ }
844
+ const B = BigInt("0x" + initUserSrpAuthResponse.ChallengeParameters.SRP_B);
845
+ const salt = BigInt("0x" + initUserSrpAuthResponse.ChallengeParameters.SALT);
830
846
  const U = await calculateU(A, B);
831
847
  const hkdf = await getPasswordAuthenticationKey(
832
848
  this.cognitoPoolName,
833
- challenge.ChallengeParameters.USER_ID_FOR_SRP,
849
+ initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP,
834
850
  password,
835
851
  B,
836
852
  U,
@@ -839,32 +855,31 @@ var CognitoClient = class {
839
855
  );
840
856
  const { signature, timeStamp } = await calculateSignature(
841
857
  this.cognitoPoolName,
842
- challenge.ChallengeParameters.USER_ID_FOR_SRP,
843
- challenge.ChallengeParameters.SECRET_BLOCK,
858
+ initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP,
859
+ initUserSrpAuthResponse.ChallengeParameters.SECRET_BLOCK,
844
860
  hkdf
845
861
  );
846
- const respondToAuthChallengeRequest = {
862
+ const passwordAuthChallengeResponse = await this.respondToAuthChallenge({
847
863
  ChallengeName: "PASSWORD_VERIFIER",
848
- ClientId: this.userPoolClientId,
849
864
  ChallengeResponses: {
850
- PASSWORD_CLAIM_SECRET_BLOCK: challenge.ChallengeParameters.SECRET_BLOCK,
865
+ PASSWORD_CLAIM_SECRET_BLOCK: initUserSrpAuthResponse.ChallengeParameters.SECRET_BLOCK,
851
866
  PASSWORD_CLAIM_SIGNATURE: signature,
852
- USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP,
867
+ USERNAME: initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP,
853
868
  TIMESTAMP: timeStamp,
854
869
  SECRET_HASH: this.clientSecret && await calculateSecretHash(
855
870
  this.clientSecret,
856
871
  this.userPoolClientId,
857
- challenge.ChallengeParameters.USER_ID_FOR_SRP
872
+ initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP
858
873
  )
859
874
  },
860
875
  ClientMetadata: {}
861
- };
862
- const { AuthenticationResult } = await cognitoRequest(
863
- respondToAuthChallengeRequest,
864
- "RespondToAuthChallenge" /* RespondToAuthChallenge */,
865
- this.cognitoEndpoint
866
- );
867
- return authResultToSession(AuthenticationResult);
876
+ });
877
+ if (passwordAuthChallengeResponse.AuthenticationResult) {
878
+ passwordAuthChallengeResponse.AuthenticationResult = adaptExpiresIn(
879
+ passwordAuthChallengeResponse.AuthenticationResult
880
+ );
881
+ }
882
+ return passwordAuthChallengeResponse;
868
883
  }
869
884
  /**
870
885
  *
@@ -886,13 +901,18 @@ var CognitoClient = class {
886
901
  },
887
902
  ClientMetadata: {}
888
903
  };
889
- const { AuthenticationResult } = await cognitoRequest(
904
+ const initUserPasswordAuthResponse = await cognitoRequest(
890
905
  initiateAuthPayload,
891
906
  "InitiateAuth" /* InitiateAuth */,
892
907
  this.cognitoEndpoint
893
908
  );
894
- const session = authResultToSession(AuthenticationResult);
895
- return session;
909
+ if (!initUserPasswordAuthResponse.AuthenticationResult) {
910
+ return initUserPasswordAuthResponse;
911
+ }
912
+ initUserPasswordAuthResponse.AuthenticationResult = adaptExpiresIn(
913
+ initUserPasswordAuthResponse.AuthenticationResult
914
+ );
915
+ return initUserPasswordAuthResponse;
896
916
  }
897
917
  /**
898
918
  * Returns a new session based on the given refresh token.
@@ -917,10 +937,16 @@ var CognitoClient = class {
917
937
  "InitiateAuth" /* InitiateAuth */,
918
938
  this.cognitoEndpoint
919
939
  );
940
+ if (!AuthenticationResult) {
941
+ throw new InitAuthError(
942
+ "Authentication failed, no authentication result returned",
943
+ "InternalErrorException" /* InternalErrorException */
944
+ );
945
+ }
920
946
  if (!AuthenticationResult.RefreshToken) {
921
947
  AuthenticationResult.RefreshToken = refreshToken;
922
948
  }
923
- return authResultToSession(AuthenticationResult);
949
+ return adaptExpiresIn(AuthenticationResult);
924
950
  }
925
951
  /**
926
952
  *
@@ -975,6 +1001,63 @@ var CognitoClient = class {
975
1001
  };
976
1002
  await cognitoRequest(changePasswordPayload, "ChangePassword" /* ChangePassword */, this.cognitoEndpoint);
977
1003
  }
1004
+ async getUser(accessToken) {
1005
+ const getUserPayload = {
1006
+ AccessToken: accessToken
1007
+ };
1008
+ return cognitoRequest(getUserPayload, "GetUser" /* GetUser */, this.cognitoEndpoint);
1009
+ }
1010
+ async associateSoftwareToken(params) {
1011
+ return cognitoRequest(params, "AssociateSoftwareToken" /* AssociateSoftwareToken */, this.cognitoEndpoint);
1012
+ }
1013
+ async verifySoftwareToken(params) {
1014
+ return cognitoRequest(params, "VerifySoftwareToken" /* VerifySoftwareToken */, this.cognitoEndpoint);
1015
+ }
1016
+ /**
1017
+ * Responds to an authentication challenge.
1018
+ * @param params Request to respond to an authentication challenge.
1019
+ * @param params.ChallengeName Name of the challenge to respond to.
1020
+ * @param params.ChallengeResponses Responses to the challenge.
1021
+ * @param params.Session Session identifier for the authentication process.
1022
+ * @param params.ClientMetadata Optional metadata to pass to the service.
1023
+ * @param params.AccessToken Access token of the current user.
1024
+ * @param params.SecretHash Optional secret hash for the user pool client.
1025
+ * @returns
1026
+ */
1027
+ async respondToAuthChallenge(params) {
1028
+ return cognitoRequest(
1029
+ {
1030
+ ...params,
1031
+ ClientId: this.userPoolClientId
1032
+ },
1033
+ "RespondToAuthChallenge" /* RespondToAuthChallenge */,
1034
+ this.cognitoEndpoint
1035
+ );
1036
+ }
1037
+ /**
1038
+ * Lists the devices associated with the user.
1039
+ * @param request Request to list devices.
1040
+ * @param request.AccessToken Access token of the current user.
1041
+ * @param request.Limit Maximum number of devices to return.
1042
+ * @param request.PaginationToken Pagination token to continue listing devices.
1043
+ * @returns
1044
+ */
1045
+ async listDevices(request) {
1046
+ return cognitoRequest(request, "ListDevices" /* ListDevices */, this.cognitoEndpoint);
1047
+ }
1048
+ /**
1049
+ *
1050
+ * @param request Request to set user MFA preferences.
1051
+ * @param request.AccessToken Access token of the current user.
1052
+ * @param request.EmailMfaSettings Optional settings for email MFA.
1053
+ * @param request.SMSMfaSettings Optional settings for SMS MFA.
1054
+ * @param request.SoftwareTokenMfaSettings Optional settings for software token MFA.
1055
+
1056
+ * @returns
1057
+ */
1058
+ async setUserMFAPreference(request) {
1059
+ return cognitoRequest(request, "SetUserMFAPreference" /* SetUserMFAPreference */, this.cognitoEndpoint);
1060
+ }
978
1061
  /**
979
1062
  * Updates the user attributes.
980
1063
  *
@@ -1111,15 +1194,17 @@ var CognitoClient = class {
1111
1194
  *
1112
1195
  * @throws {Error}
1113
1196
  */
1114
- async handleCodeFlow(returnUrl, pkce) {
1197
+ async handleCodeFlow(returnUrl, pkce, state) {
1115
1198
  if (this.oAuth === void 0) {
1116
1199
  throw Error("You have to define oAuth options to use handleCodeFlow");
1117
1200
  }
1118
1201
  const url = new URL(returnUrl);
1119
1202
  const code = url.searchParams.get("code");
1120
- const state = url.searchParams.get("state");
1121
- if (code === null || state === null) {
1122
- throw Error("code or state parameter is missing from return url.");
1203
+ if (code === null) {
1204
+ throw Error("code parameter is missing from return url.");
1205
+ }
1206
+ if (url.searchParams.get("state") !== state) {
1207
+ throw Error("State parameter does not match.");
1123
1208
  }
1124
1209
  const urlParams = new URLSearchParams();
1125
1210
  urlParams.append("grant_type", "authorization_code");
@@ -1139,13 +1224,12 @@ var CognitoClient = class {
1139
1224
  if (error) {
1140
1225
  throw new Error(error);
1141
1226
  }
1142
- const session = authResultToSession({
1227
+ return adaptExpiresIn({
1143
1228
  AccessToken: access_token,
1144
1229
  RefreshToken: refresh_token,
1145
1230
  IdToken: id_token,
1146
1231
  ExpiresIn: expires_in
1147
1232
  });
1148
- return session;
1149
1233
  }
1150
1234
  /**
1151
1235
  * Invalidates the identity, access, and refresh tokens that Amazon Cognito issued to a user. Call this operation when your user signs out of your app. This results in the following behavior.
@@ -1159,6 +1243,7 @@ var CognitoClient = class {
1159
1243
  }
1160
1244
  };
1161
1245
  export {
1246
+ AssociateSoftwareTokenError,
1162
1247
  AssociateSoftwareTokenException,
1163
1248
  COMMON_EXCEPTIONS,
1164
1249
  ChangePasswordError,
@@ -1200,9 +1285,10 @@ export {
1200
1285
  UpdateDeviceStatusException,
1201
1286
  UpdateUserAttributesError,
1202
1287
  UpdateUserAttributesException,
1288
+ VerifySoftwareTokenError,
1203
1289
  VerifySoftwareTokenException,
1204
1290
  VerifyUserAttributeError,
1205
1291
  VerifyUserAttributeException,
1206
- authResultToSession,
1292
+ adaptExpiresIn,
1207
1293
  cognitoRequest
1208
1294
  };
@@ -9,7 +9,7 @@ export interface CognitoBaseRequest {
9
9
  IpAddress?: string;
10
10
  };
11
11
  }
12
- export interface AuthIntiUserSrpRequest 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 AuthIntiUserSrpRequest extends CognitoBaseRequest {
17
17
  SECRET_HASH?: string;
18
18
  };
19
19
  }
20
- export interface AuthIntiUserPasswordRequest extends CognitoBaseRequest {
20
+ export interface InitiateAuthUserPasswordAuthRequest extends CognitoBaseRequest {
21
21
  AuthFlow: 'USER_PASSWORD_AUTH';
22
22
  AuthParameters: {
23
23
  USERNAME: string;
@@ -25,25 +25,25 @@ export interface AuthIntiUserPasswordRequest extends CognitoBaseRequest {
25
25
  SECRET_HASH?: string;
26
26
  };
27
27
  }
28
- export interface AuthIntiRefreshTokenRequest 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
33
  };
34
34
  }
35
- export interface AuthIntiCustomAuthRequest extends CognitoBaseRequest {
35
+ export interface InitiateAuthCustomAuthRequest extends CognitoBaseRequest {
36
36
  AuthFlow: 'CUSTOM_AUTH';
37
37
  AuthParameters: {
38
38
  USERNAME: string;
39
39
  SECRET_HASH?: string;
40
40
  };
41
41
  }
42
- export type AuthIntiRequest = AuthIntiUserSrpRequest | AuthIntiRefreshTokenRequest | AuthIntiCustomAuthRequest | AuthIntiUserPasswordRequest;
42
+ export type InitiateAuthRequest = InitiateAuthUserSrpAuthRequest | InitiateAuthRefreshTokenAuthRequest | InitiateAuthCustomAuthRequest | InitiateAuthUserPasswordAuthRequest;
43
43
  export interface RespondToAuthChallengeBaseRequest extends CognitoBaseRequest {
44
44
  Session?: string;
45
45
  }
46
- export interface RespondToAuthChallengePasswordVerifierRequest extends RespondToAuthChallengeBaseRequest {
46
+ export interface _RespondToAuthChallengePasswordVerifierRequest extends RespondToAuthChallengeBaseRequest {
47
47
  ChallengeName: 'PASSWORD_VERIFIER';
48
48
  ChallengeResponses: {
49
49
  USERNAME: string;
@@ -53,7 +53,7 @@ export interface RespondToAuthChallengePasswordVerifierRequest extends RespondTo
53
53
  SECRET_HASH?: string;
54
54
  };
55
55
  }
56
- export interface RespondToAuthChallengeSmsMfaRequest extends RespondToAuthChallengeBaseRequest {
56
+ export interface _RespondToAuthChallengeSmsMfaRequest extends RespondToAuthChallengeBaseRequest {
57
57
  ChallengeName: 'SMS_MFA';
58
58
  ChallengeResponses: {
59
59
  USERNAME: string;
@@ -61,7 +61,7 @@ export interface RespondToAuthChallengeSmsMfaRequest extends RespondToAuthChalle
61
61
  SECRET_HASH?: string;
62
62
  };
63
63
  }
64
- export interface RespondToAuthChallengeCustomChallengeNameRequest extends RespondToAuthChallengeBaseRequest {
64
+ export interface _RespondToAuthChallengeCustomChallengeNameRequest extends RespondToAuthChallengeBaseRequest {
65
65
  ChallengeName: 'CUSTOM_CHALLENGE';
66
66
  ChallengeResponses: {
67
67
  USERNAME: string;
@@ -69,7 +69,7 @@ export interface RespondToAuthChallengeCustomChallengeNameRequest extends Respon
69
69
  SECRET_HASH?: string;
70
70
  };
71
71
  }
72
- export interface RespondToAuthChallengeNewPasswordRequiredRequest extends RespondToAuthChallengeBaseRequest {
72
+ export interface _RespondToAuthChallengeNewPasswordRequiredRequest extends RespondToAuthChallengeBaseRequest {
73
73
  ChallengeName: 'NEW_PASSWORD_REQUIRED';
74
74
  ChallengeResponses: {
75
75
  USERNAME: string;
@@ -77,7 +77,7 @@ export interface RespondToAuthChallengeNewPasswordRequiredRequest extends Respon
77
77
  SECRET_HASH?: string;
78
78
  };
79
79
  }
80
- export interface RespondToAuthChallengeSoftwareTokenMfaRequest extends RespondToAuthChallengeBaseRequest {
80
+ export interface _RespondToAuthChallengeSoftwareTokenMfaRequest extends RespondToAuthChallengeBaseRequest {
81
81
  ChallengeName: 'SOFTWARE_TOKEN_MFA';
82
82
  ChallengeResponses: {
83
83
  USERNAME: string;
@@ -85,7 +85,7 @@ export interface RespondToAuthChallengeSoftwareTokenMfaRequest extends RespondTo
85
85
  SECRET_HASH?: string;
86
86
  };
87
87
  }
88
- export interface RespondToAuthChallengeDeviceSrpAuthRequest extends RespondToAuthChallengeBaseRequest {
88
+ export interface _RespondToAuthChallengeDeviceSrpAuthRequest extends RespondToAuthChallengeBaseRequest {
89
89
  ChallengeName: 'DEVICE_SRP_AUTH';
90
90
  ChallengeResponses: {
91
91
  USERNAME: string;
@@ -93,7 +93,7 @@ export interface RespondToAuthChallengeDeviceSrpAuthRequest extends RespondToAut
93
93
  SECRET_HASH?: string;
94
94
  };
95
95
  }
96
- export interface RespondToAuthChallengeDevicePasswordVerifierRequest extends RespondToAuthChallengeBaseRequest {
96
+ export interface _RespondToAuthChallengeDevicePasswordVerifierRequest extends RespondToAuthChallengeBaseRequest {
97
97
  ChallengeName: 'DEVICE_PASSWORD_VERIFIER';
98
98
  ChallengeResponses: {
99
99
  USERNAME: string;
@@ -104,7 +104,7 @@ export interface RespondToAuthChallengeDevicePasswordVerifierRequest extends Res
104
104
  SECRET_HASH?: string;
105
105
  };
106
106
  }
107
- export interface RespondToAuthChallengeMfaSetupRequest extends RespondToAuthChallengeBaseRequest {
107
+ export interface _RespondToAuthChallengeMfaSetupRequest extends RespondToAuthChallengeBaseRequest {
108
108
  ChallengeName: 'MFA_SETUP';
109
109
  ChallengeResponses: {
110
110
  USERNAME: string;
@@ -113,7 +113,7 @@ export interface RespondToAuthChallengeMfaSetupRequest extends RespondToAuthChal
113
113
  SECRET_HASH?: string;
114
114
  };
115
115
  }
116
- export interface RespondToAuthChallengeSelectMfaTypeRequest extends RespondToAuthChallengeBaseRequest {
116
+ export interface _RespondToAuthChallengeSelectMfaTypeRequest extends RespondToAuthChallengeBaseRequest {
117
117
  ChallengeName: 'SELECT_MFA_TYPE';
118
118
  ChallengeResponses: {
119
119
  USERNAME: string;
@@ -121,7 +121,8 @@ export interface RespondToAuthChallengeSelectMfaTypeRequest extends RespondToAut
121
121
  SECRET_HASH?: string;
122
122
  };
123
123
  }
124
- export type RespondToAuthChallengeRequest = RespondToAuthChallengePasswordVerifierRequest | RespondToAuthChallengeSmsMfaRequest | RespondToAuthChallengeCustomChallengeNameRequest | RespondToAuthChallengeNewPasswordRequiredRequest | RespondToAuthChallengeSoftwareTokenMfaRequest | RespondToAuthChallengeDeviceSrpAuthRequest | RespondToAuthChallengeDevicePasswordVerifierRequest | RespondToAuthChallengeMfaSetupRequest | RespondToAuthChallengeSelectMfaTypeRequest;
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'>;
125
126
  export interface UserAttribute {
126
127
  Name: string;
127
128
  Value: string;
@@ -199,27 +200,6 @@ export interface CognitoClientProps {
199
200
  */
200
201
  clientSecret?: string;
201
202
  }
202
- /**
203
- * Cognito User Session
204
- */
205
- export interface Session {
206
- /**
207
- * JWT Access Token
208
- */
209
- accessToken: string;
210
- /**
211
- * JWT ID Token
212
- */
213
- idToken: string;
214
- /**
215
- * JWT refresh token
216
- */
217
- refreshToken: string;
218
- /**
219
- * Validity of the session in time stamp as milliseconds.
220
- */
221
- expiresIn: number;
222
- }
223
203
  /**
224
204
  * Represents the decoded values from a JWT ID token.
225
205
  */
@@ -273,7 +253,51 @@ export declare enum ServiceTarget {
273
253
  ResendConfirmationCode = "ResendConfirmationCode",
274
254
  UpdateUserAttributes = "UpdateUserAttributes",
275
255
  VerifyUserAttribute = "VerifyUserAttribute",
276
- GlobalSignOut = "GlobalSignOut"
256
+ GlobalSignOut = "GlobalSignOut",
257
+ GetUser = "GetUser",
258
+ AssociateSoftwareToken = "AssociateSoftwareToken",
259
+ VerifySoftwareToken = "VerifySoftwareToken",
260
+ ListDevices = "ListDevices",
261
+ SetUserMFAPreference = "SetUserMFAPreference"
262
+ }
263
+ export interface AssociateSoftwareTokenRequest {
264
+ AccessToken?: string;
265
+ Session?: string;
266
+ }
267
+ export interface AssociateSoftwareResponse {
268
+ SecretCode: string;
269
+ Session: string;
270
+ }
271
+ export interface VerifySoftwareTokenRequest {
272
+ AccessToken?: string;
273
+ FriendlyDeviceName?: string;
274
+ Session?: string;
275
+ UserCode: string;
276
+ }
277
+ export interface VerifySoftwareTokenResponse {
278
+ Session: string;
279
+ Status: 'SUCCESS' | 'ERROR';
280
+ }
281
+ export interface ListDevicesRequest {
282
+ AccessToken: string;
283
+ Limit: number;
284
+ PaginationToken?: 'string';
285
+ }
286
+ export interface Device {
287
+ DeviceAttributes: [
288
+ {
289
+ Name: string;
290
+ Value: string;
291
+ }
292
+ ];
293
+ DeviceCreateDate: number;
294
+ DeviceKey: string;
295
+ DeviceLastAuthenticatedDate: number;
296
+ DeviceLastModifiedDate: number;
297
+ }
298
+ export interface ListDevicesResponse {
299
+ Devices: Device[];
300
+ PaginationToken?: string;
277
301
  }
278
302
  /**
279
303
  * Cognito supported federated identities public providers.
@@ -291,11 +315,19 @@ export interface AuthenticationResult {
291
315
  ExpiresIn: number;
292
316
  IdToken: string;
293
317
  RefreshToken: string;
318
+ NewDeviceMetadata?: NewDeviceMetadata;
319
+ }
320
+ export interface NewDeviceMetadata {
321
+ DeviceKey?: string;
322
+ DeviceGroupKey?: string;
294
323
  }
295
- export interface AuthenticationResponse {
324
+ export interface InitiateAuthAuthenticationResponse {
296
325
  AuthenticationResult: AuthenticationResult;
326
+ ChallengeName?: never;
327
+ session?: never;
297
328
  }
298
- export interface ChallengeResponse {
329
+ export interface InitiateAuthPasswordVerifierChallengeResponse {
330
+ AuthenticationResult?: never;
299
331
  ChallengeName: 'PASSWORD_VERIFIER';
300
332
  ChallengeParameters: {
301
333
  SALT: string;
@@ -304,9 +336,117 @@ export interface ChallengeResponse {
304
336
  USERNAME: string;
305
337
  USER_ID_FOR_SRP: string;
306
338
  };
339
+ session?: never;
340
+ }
341
+ export interface InitiateAuthSoftwareTokenMfaChallengeResponse {
342
+ AuthenticationResult?: never;
343
+ ChallengeName: 'SOFTWARE_TOKEN_MFA';
344
+ Session: string;
345
+ }
346
+ export interface InitiateEmailOtpChallengeResponse {
347
+ ChallengeName: 'EMAIL_OTP';
348
+ ChallengeParameters: {
349
+ CODE_DELIVERY_DELIVERY_MEDIUM: string;
350
+ CODE_DELIVERY_DESTINATION: string;
351
+ };
352
+ session: string;
353
+ }
354
+ export interface MfaOption {
355
+ DeliveryMedium: 'SMS' | 'EMAIL';
356
+ AttributeName: string;
357
+ }
358
+ export interface GetUserResponse {
359
+ UserAttributes: UserAttribute[];
360
+ Username: string;
361
+ UserMFASettingList?: string[];
362
+ MFAOptions?: MfaOption[];
363
+ PreferredMfaSetting: string;
364
+ }
365
+ export interface SetUserMFAPreferenceRequest {
366
+ AccessToken: string;
367
+ EmailMfaSettings?: {
368
+ Enabled?: boolean;
369
+ PreferredMfa?: boolean;
370
+ };
371
+ SMSMfaSettings?: {
372
+ Enabled?: boolean;
373
+ PreferredMfa?: boolean;
374
+ };
375
+ SoftwareTokenMfaSettings?: {
376
+ Enabled?: boolean;
377
+ PreferredMfa?: boolean;
378
+ };
307
379
  }
308
- export declare function authResultToSession(authenticationResult: AuthenticationResult): Session;
309
- export declare function cognitoRequest(body: object, serviceTarget: ServiceTarget, cognitoEndpoint: string): Promise<any>;
380
+ export type InitiateAuthChallengeResponse = InitiateAuthPasswordVerifierChallengeResponse | InitiateAuthSoftwareTokenMfaChallengeResponse;
381
+ export type InitiateAuthResponse = InitiateAuthAuthenticationResponse | InitiateAuthPasswordVerifierChallengeResponse | InitiateAuthChallengeResponse;
382
+ type CognitoResponseMap = {
383
+ [ServiceTarget.InitiateAuth]: InitiateAuthResponse;
384
+ [ServiceTarget.RespondToAuthChallenge]: InitiateAuthResponse;
385
+ [ServiceTarget.SignUp]: {
386
+ UserConfirmed: boolean;
387
+ UserSub: string;
388
+ };
389
+ [ServiceTarget.ConfirmSignUp]: void;
390
+ [ServiceTarget.ChangePassword]: void;
391
+ [ServiceTarget.RevokeToken]: void;
392
+ [ServiceTarget.ForgotPassword]: void;
393
+ [ServiceTarget.ConfirmForgotPassword]: void;
394
+ [ServiceTarget.ResendConfirmationCode]: void;
395
+ [ServiceTarget.UpdateUserAttributes]: void;
396
+ [ServiceTarget.VerifyUserAttribute]: void;
397
+ [ServiceTarget.GlobalSignOut]: void;
398
+ [ServiceTarget.GetUser]: GetUserResponse;
399
+ [ServiceTarget.AssociateSoftwareToken]: AssociateSoftwareResponse;
400
+ [ServiceTarget.VerifySoftwareToken]: VerifySoftwareTokenResponse;
401
+ [ServiceTarget.ListDevices]: ListDevicesResponse;
402
+ [ServiceTarget.SetUserMFAPreference]: void;
403
+ };
404
+ type CognitoRequestMap = {
405
+ [ServiceTarget.InitiateAuth]: InitiateAuthRequest;
406
+ [ServiceTarget.RespondToAuthChallenge]: _RespondToAuthChallengeRequest;
407
+ [ServiceTarget.SignUp]: SignUpRequest;
408
+ [ServiceTarget.ConfirmSignUp]: ConfirmSignUpRequest;
409
+ [ServiceTarget.ChangePassword]: {
410
+ PreviousPassword: string;
411
+ ProposedPassword: string;
412
+ AccessToken: string;
413
+ };
414
+ [ServiceTarget.RevokeToken]: {
415
+ Token: string;
416
+ ClientId: string;
417
+ ClientSecret?: string;
418
+ };
419
+ [ServiceTarget.ForgotPassword]: ForgotPasswordRequest;
420
+ [ServiceTarget.ConfirmForgotPassword]: ConfirmForgotPasswordRequest;
421
+ [ServiceTarget.ResendConfirmationCode]: ResendConfirmationCodeRequest;
422
+ [ServiceTarget.UpdateUserAttributes]: {
423
+ UserAttributes: UserAttribute[];
424
+ AccessToken: string;
425
+ };
426
+ [ServiceTarget.VerifyUserAttribute]: {
427
+ AttributeName: string;
428
+ Code: string;
429
+ AccessToken: string;
430
+ };
431
+ [ServiceTarget.GlobalSignOut]: {
432
+ AccessToken: string;
433
+ };
434
+ [ServiceTarget.GetUser]: {
435
+ AccessToken: string;
436
+ };
437
+ [ServiceTarget.AssociateSoftwareToken]: AssociateSoftwareTokenRequest;
438
+ [ServiceTarget.VerifySoftwareToken]: VerifySoftwareTokenRequest;
439
+ [ServiceTarget.ListDevices]: ListDevicesRequest;
440
+ [ServiceTarget.SetUserMFAPreference]: SetUserMFAPreferenceRequest;
441
+ };
442
+ export declare function adaptExpiresIn(auth: AuthenticationResult): {
443
+ ExpiresIn: number;
444
+ AccessToken: string;
445
+ IdToken: string;
446
+ RefreshToken: string;
447
+ NewDeviceMetadata?: NewDeviceMetadata | undefined;
448
+ };
449
+ export declare function cognitoRequest<T extends ServiceTarget>(body: CognitoRequestMap[T], serviceTarget: T, cognitoEndpoint: string): Promise<CognitoResponseMap[T]>;
310
450
  /**
311
451
  * Lightweight AWS Cogito client without any AWS SDK dependencies.
312
452
  */
@@ -317,7 +457,7 @@ export declare class CognitoClient {
317
457
  private readonly oAuth?;
318
458
  private readonly clientSecret?;
319
459
  constructor({ userPoolId, userPoolClientId, endpoint, oAuth2: oAuth, clientSecret }: CognitoClientProps);
320
- static getDecodedTokenFromSession(session: Session): DecodedTokens;
460
+ static getDecodedTokenFromSession(auth: AuthenticationResult): DecodedTokens;
321
461
  /**
322
462
  *
323
463
  * Performs user authentication with username and password through ALLOW_USER_SRP_AUTH .
@@ -328,7 +468,7 @@ export declare class CognitoClient {
328
468
  *
329
469
  * @throws {InitAuthError, CognitoRespondToAuthChallengeError}
330
470
  */
331
- authenticateUserSrp(username: string, password: string): Promise<Session>;
471
+ authenticateUserSrp(username: string, password: string): Promise<InitiateAuthResponse>;
332
472
  /**
333
473
  *
334
474
  * Performs user authentication with username and password through USER_PASSWORD_AUTH .
@@ -338,7 +478,7 @@ export declare class CognitoClient {
338
478
  * @param password Password
339
479
  * @throws {InitAuthError}
340
480
  */
341
- authenticateUser(username: string, password: string): Promise<Session>;
481
+ authenticateUser(username: string, password: string): Promise<InitiateAuthResponse>;
342
482
  /**
343
483
  * Returns a new session based on the given refresh token.
344
484
  *
@@ -347,7 +487,7 @@ export declare class CognitoClient {
347
487
  * @returns @see Session
348
488
  * @throws {InitAuthError}
349
489
  */
350
- refreshSession(refreshToken: string, username?: string): Promise<Session>;
490
+ refreshSession(refreshToken: string, username?: string): Promise<AuthenticationResult>;
351
491
  /**
352
492
  *
353
493
  * @param username Username
@@ -376,6 +516,41 @@ export declare class CognitoClient {
376
516
  * @throws {ChangePasswordError}
377
517
  */
378
518
  changePassword(currentPassword: string, newPassword: string, accessToken: string): Promise<void>;
519
+ getUser(accessToken: string): Promise<GetUserResponse>;
520
+ associateSoftwareToken(params: AssociateSoftwareTokenRequest): Promise<AssociateSoftwareResponse>;
521
+ verifySoftwareToken(params: VerifySoftwareTokenRequest): Promise<VerifySoftwareTokenResponse>;
522
+ /**
523
+ * Responds to an authentication challenge.
524
+ * @param params Request to respond to an authentication challenge.
525
+ * @param params.ChallengeName Name of the challenge to respond to.
526
+ * @param params.ChallengeResponses Responses to the challenge.
527
+ * @param params.Session Session identifier for the authentication process.
528
+ * @param params.ClientMetadata Optional metadata to pass to the service.
529
+ * @param params.AccessToken Access token of the current user.
530
+ * @param params.SecretHash Optional secret hash for the user pool client.
531
+ * @returns
532
+ */
533
+ respondToAuthChallenge(params: RespondToAuthChallengeRequest): Promise<InitiateAuthResponse>;
534
+ /**
535
+ * Lists the devices associated with the user.
536
+ * @param request Request to list devices.
537
+ * @param request.AccessToken Access token of the current user.
538
+ * @param request.Limit Maximum number of devices to return.
539
+ * @param request.PaginationToken Pagination token to continue listing devices.
540
+ * @returns
541
+ */
542
+ listDevices(request: ListDevicesRequest): Promise<ListDevicesResponse>;
543
+ /**
544
+ *
545
+ * @param request Request to set user MFA preferences.
546
+ * @param request.AccessToken Access token of the current user.
547
+ * @param request.EmailMfaSettings Optional settings for email MFA.
548
+ * @param request.SMSMfaSettings Optional settings for SMS MFA.
549
+ * @param request.SoftwareTokenMfaSettings Optional settings for software token MFA.
550
+
551
+ * @returns
552
+ */
553
+ setUserMFAPreference(request: SetUserMFAPreferenceRequest): Promise<void>;
379
554
  /**
380
555
  * Updates the user attributes.
381
556
  *
@@ -452,10 +627,11 @@ export declare class CognitoClient {
452
627
  *
453
628
  * @throws {Error}
454
629
  */
455
- handleCodeFlow(returnUrl: string, pkce: string): Promise<Session>;
630
+ handleCodeFlow(returnUrl: string, pkce: string, state: string): Promise<AuthenticationResult>;
456
631
  /**
457
632
  * Invalidates the identity, access, and refresh tokens that Amazon Cognito issued to a user. Call this operation when your user signs out of your app. This results in the following behavior.
458
633
  * @param accessToken Access token of the current user.
459
634
  */
460
635
  globalSignOut(accessToken: string): Promise<void>;
461
636
  }
637
+ export {};
@@ -1,4 +1,4 @@
1
- import { ChangePasswordError, ConfirmForgotPasswordError, ConfirmSignUpError, ForgotPasswordError, GlobalSignOutError, InitAuthError, ResendConfirmationCodeError, RespondToAuthChallengeError, RevokeTokenError, SignUpError, UpdateUserAttributesError, VerifyUserAttributeError, COMMON_EXCEPTIONS, CommonError } from './error.js';
1
+ import { ChangePasswordError, ConfirmForgotPasswordError, ConfirmSignUpError, ForgotPasswordError, GlobalSignOutError, InitAuthError, ResendConfirmationCodeError, RespondToAuthChallengeError, RevokeTokenError, SignUpError, UpdateUserAttributesError, VerifyUserAttributeError, InitiateAuthException, COMMON_EXCEPTIONS, CommonError, VerifySoftwareTokenError } from './error.js';
2
2
  import { calculateSecretHash, calculateSignature, calculateU, decodeJwt, digest, generateA, generateSmallA, getPasswordAuthenticationKey, randomBytes, uint8ArrayFromString, uint8ArrayToBase64String } from './utils.js';
3
3
  /**
4
4
  * List of used and supported Cognito API calls.
@@ -18,6 +18,11 @@ export var ServiceTarget;
18
18
  ServiceTarget["UpdateUserAttributes"] = "UpdateUserAttributes";
19
19
  ServiceTarget["VerifyUserAttribute"] = "VerifyUserAttribute";
20
20
  ServiceTarget["GlobalSignOut"] = "GlobalSignOut";
21
+ ServiceTarget["GetUser"] = "GetUser";
22
+ ServiceTarget["AssociateSoftwareToken"] = "AssociateSoftwareToken";
23
+ ServiceTarget["VerifySoftwareToken"] = "VerifySoftwareToken";
24
+ ServiceTarget["ListDevices"] = "ListDevices";
25
+ ServiceTarget["SetUserMFAPreference"] = "SetUserMFAPreference";
21
26
  })(ServiceTarget || (ServiceTarget = {}));
22
27
  /**
23
28
  * Cognito supported federated identities public providers.
@@ -31,12 +36,11 @@ export var IdentityProvider;
31
36
  IdentityProvider["Amazon"] = "LoginWithAmazon";
32
37
  IdentityProvider["Apple"] = "SignInWithApple";
33
38
  })(IdentityProvider || (IdentityProvider = {}));
34
- export function authResultToSession(authenticationResult) {
39
+ export function adaptExpiresIn(auth) {
40
+ // Cognito returns expiresIn in seconds, but we want it in milliseconds from now
35
41
  return {
36
- accessToken: authenticationResult.AccessToken,
37
- idToken: authenticationResult.IdToken,
38
- expiresIn: new Date().getTime() + authenticationResult.ExpiresIn * 1000,
39
- refreshToken: authenticationResult.RefreshToken
42
+ ...auth,
43
+ ExpiresIn: new Date().getTime() + auth.ExpiresIn * 1000
40
44
  };
41
45
  }
42
46
  export async function cognitoRequest(body, serviceTarget, cognitoEndpoint) {
@@ -99,6 +103,8 @@ export async function cognitoRequest(body, serviceTarget, cognitoEndpoint) {
99
103
  throw new VerifyUserAttributeError(errorMessage, cognitoException);
100
104
  case ServiceTarget.GlobalSignOut:
101
105
  throw new GlobalSignOutError(errorMessage, cognitoException);
106
+ case ServiceTarget.VerifySoftwareToken:
107
+ throw new VerifySoftwareTokenError(errorMessage, cognitoException);
102
108
  }
103
109
  }
104
110
  /**
@@ -113,9 +119,9 @@ export class CognitoClient {
113
119
  this.oAuth = oAuth;
114
120
  this.clientSecret = clientSecret;
115
121
  }
116
- static getDecodedTokenFromSession(session) {
117
- const { payload: idToken } = decodeJwt(session.idToken);
118
- const { payload: accessToken } = decodeJwt(session.accessToken);
122
+ static getDecodedTokenFromSession(auth) {
123
+ const { payload: idToken } = decodeJwt(auth.IdToken);
124
+ const { payload: accessToken } = decodeJwt(auth.AccessToken);
119
125
  return {
120
126
  idToken,
121
127
  accessToken
@@ -134,7 +140,7 @@ export class CognitoClient {
134
140
  async authenticateUserSrp(username, password) {
135
141
  const smallA = await generateSmallA();
136
142
  const A = generateA(smallA);
137
- const initiateAuthPayload = {
143
+ const initUserSrpAuthResponse = await cognitoRequest({
138
144
  AuthFlow: 'USER_SRP_AUTH',
139
145
  ClientId: this.userPoolClientId,
140
146
  AuthParameters: {
@@ -143,28 +149,31 @@ export class CognitoClient {
143
149
  SECRET_HASH: this.clientSecret && (await calculateSecretHash(this.clientSecret, this.userPoolClientId, username))
144
150
  },
145
151
  ClientMetadata: {}
146
- };
147
- const challenge = (await cognitoRequest(initiateAuthPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint));
148
- const B = BigInt('0x' + challenge.ChallengeParameters.SRP_B);
149
- const salt = BigInt('0x' + challenge.ChallengeParameters.SALT);
152
+ }, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
153
+ if (initUserSrpAuthResponse.ChallengeName !== 'PASSWORD_VERIFIER') {
154
+ return initUserSrpAuthResponse;
155
+ }
156
+ const B = BigInt('0x' + initUserSrpAuthResponse.ChallengeParameters.SRP_B);
157
+ const salt = BigInt('0x' + initUserSrpAuthResponse.ChallengeParameters.SALT);
150
158
  const U = await calculateU(A, B);
151
- const hkdf = await getPasswordAuthenticationKey(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, password, B, U, smallA, salt);
152
- const { signature, timeStamp } = await calculateSignature(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, challenge.ChallengeParameters.SECRET_BLOCK, hkdf);
153
- const respondToAuthChallengeRequest = {
159
+ const hkdf = await getPasswordAuthenticationKey(this.cognitoPoolName, initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP, password, B, U, smallA, salt);
160
+ const { signature, timeStamp } = await calculateSignature(this.cognitoPoolName, initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP, initUserSrpAuthResponse.ChallengeParameters.SECRET_BLOCK, hkdf);
161
+ const passwordAuthChallengeResponse = await this.respondToAuthChallenge({
154
162
  ChallengeName: 'PASSWORD_VERIFIER',
155
- ClientId: this.userPoolClientId,
156
163
  ChallengeResponses: {
157
- PASSWORD_CLAIM_SECRET_BLOCK: challenge.ChallengeParameters.SECRET_BLOCK,
164
+ PASSWORD_CLAIM_SECRET_BLOCK: initUserSrpAuthResponse.ChallengeParameters.SECRET_BLOCK,
158
165
  PASSWORD_CLAIM_SIGNATURE: signature,
159
- USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP,
166
+ USERNAME: initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP,
160
167
  TIMESTAMP: timeStamp,
161
168
  SECRET_HASH: this.clientSecret &&
162
- (await calculateSecretHash(this.clientSecret, this.userPoolClientId, challenge.ChallengeParameters.USER_ID_FOR_SRP))
169
+ (await calculateSecretHash(this.clientSecret, this.userPoolClientId, initUserSrpAuthResponse.ChallengeParameters.USER_ID_FOR_SRP))
163
170
  },
164
171
  ClientMetadata: {}
165
- };
166
- const { AuthenticationResult } = await cognitoRequest(respondToAuthChallengeRequest, ServiceTarget.RespondToAuthChallenge, this.cognitoEndpoint);
167
- return authResultToSession(AuthenticationResult);
172
+ });
173
+ if (passwordAuthChallengeResponse.AuthenticationResult) {
174
+ passwordAuthChallengeResponse.AuthenticationResult = adaptExpiresIn(passwordAuthChallengeResponse.AuthenticationResult);
175
+ }
176
+ return passwordAuthChallengeResponse;
168
177
  }
169
178
  /**
170
179
  *
@@ -186,9 +195,12 @@ export class CognitoClient {
186
195
  },
187
196
  ClientMetadata: {}
188
197
  };
189
- const { AuthenticationResult } = (await cognitoRequest(initiateAuthPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint));
190
- const session = authResultToSession(AuthenticationResult);
191
- return session;
198
+ const initUserPasswordAuthResponse = await cognitoRequest(initiateAuthPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
199
+ if (!initUserPasswordAuthResponse.AuthenticationResult) {
200
+ return initUserPasswordAuthResponse;
201
+ }
202
+ initUserPasswordAuthResponse.AuthenticationResult = adaptExpiresIn(initUserPasswordAuthResponse.AuthenticationResult);
203
+ return initUserPasswordAuthResponse;
192
204
  }
193
205
  /**
194
206
  * Returns a new session based on the given refresh token.
@@ -210,11 +222,14 @@ export class CognitoClient {
210
222
  },
211
223
  ClientMetadata: {}
212
224
  };
213
- const { AuthenticationResult } = (await cognitoRequest(refreshTokenPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint));
225
+ const { AuthenticationResult } = await cognitoRequest(refreshTokenPayload, ServiceTarget.InitiateAuth, this.cognitoEndpoint);
226
+ if (!AuthenticationResult) {
227
+ throw new InitAuthError('Authentication failed, no authentication result returned', InitiateAuthException.InternalErrorException);
228
+ }
214
229
  if (!AuthenticationResult.RefreshToken) {
215
230
  AuthenticationResult.RefreshToken = refreshToken;
216
231
  }
217
- return authResultToSession(AuthenticationResult);
232
+ return adaptExpiresIn(AuthenticationResult);
218
233
  }
219
234
  /**
220
235
  *
@@ -269,6 +284,59 @@ export class CognitoClient {
269
284
  };
270
285
  await cognitoRequest(changePasswordPayload, ServiceTarget.ChangePassword, this.cognitoEndpoint);
271
286
  }
287
+ async getUser(accessToken) {
288
+ const getUserPayload = {
289
+ AccessToken: accessToken
290
+ };
291
+ return cognitoRequest(getUserPayload, ServiceTarget.GetUser, this.cognitoEndpoint);
292
+ }
293
+ async associateSoftwareToken(params) {
294
+ return cognitoRequest(params, ServiceTarget.AssociateSoftwareToken, this.cognitoEndpoint);
295
+ }
296
+ async verifySoftwareToken(params) {
297
+ return cognitoRequest(params, ServiceTarget.VerifySoftwareToken, this.cognitoEndpoint);
298
+ }
299
+ /**
300
+ * Responds to an authentication challenge.
301
+ * @param params Request to respond to an authentication challenge.
302
+ * @param params.ChallengeName Name of the challenge to respond to.
303
+ * @param params.ChallengeResponses Responses to the challenge.
304
+ * @param params.Session Session identifier for the authentication process.
305
+ * @param params.ClientMetadata Optional metadata to pass to the service.
306
+ * @param params.AccessToken Access token of the current user.
307
+ * @param params.SecretHash Optional secret hash for the user pool client.
308
+ * @returns
309
+ */
310
+ async respondToAuthChallenge(params) {
311
+ return cognitoRequest({
312
+ ...params,
313
+ ClientId: this.userPoolClientId
314
+ }, ServiceTarget.RespondToAuthChallenge, this.cognitoEndpoint);
315
+ }
316
+ /**
317
+ * Lists the devices associated with the user.
318
+ * @param request Request to list devices.
319
+ * @param request.AccessToken Access token of the current user.
320
+ * @param request.Limit Maximum number of devices to return.
321
+ * @param request.PaginationToken Pagination token to continue listing devices.
322
+ * @returns
323
+ */
324
+ async listDevices(request) {
325
+ return cognitoRequest(request, ServiceTarget.ListDevices, this.cognitoEndpoint);
326
+ }
327
+ /**
328
+ *
329
+ * @param request Request to set user MFA preferences.
330
+ * @param request.AccessToken Access token of the current user.
331
+ * @param request.EmailMfaSettings Optional settings for email MFA.
332
+ * @param request.SMSMfaSettings Optional settings for SMS MFA.
333
+ * @param request.SoftwareTokenMfaSettings Optional settings for software token MFA.
334
+
335
+ * @returns
336
+ */
337
+ async setUserMFAPreference(request) {
338
+ return cognitoRequest(request, ServiceTarget.SetUserMFAPreference, this.cognitoEndpoint);
339
+ }
272
340
  /**
273
341
  * Updates the user attributes.
274
342
  *
@@ -408,15 +476,17 @@ export class CognitoClient {
408
476
  *
409
477
  * @throws {Error}
410
478
  */
411
- async handleCodeFlow(returnUrl, pkce) {
479
+ async handleCodeFlow(returnUrl, pkce, state) {
412
480
  if (this.oAuth === undefined) {
413
481
  throw Error('You have to define oAuth options to use handleCodeFlow');
414
482
  }
415
483
  const url = new URL(returnUrl);
416
484
  const code = url.searchParams.get('code');
417
- const state = url.searchParams.get('state');
418
- if (code === null || state === null) {
419
- throw Error('code or state parameter is missing from return url.');
485
+ if (code === null) {
486
+ throw Error('code parameter is missing from return url.');
487
+ }
488
+ if (url.searchParams.get('state') !== state) {
489
+ throw Error('State parameter does not match.');
420
490
  }
421
491
  const urlParams = new URLSearchParams();
422
492
  urlParams.append('grant_type', 'authorization_code');
@@ -436,13 +506,12 @@ export class CognitoClient {
436
506
  if (error) {
437
507
  throw new Error(error);
438
508
  }
439
- const session = authResultToSession({
509
+ return adaptExpiresIn({
440
510
  AccessToken: access_token,
441
511
  RefreshToken: refresh_token,
442
512
  IdToken: id_token,
443
513
  ExpiresIn: expires_in
444
514
  });
445
- return session;
446
515
  }
447
516
  /**
448
517
  * Invalidates the identity, access, and refresh tokens that Amazon Cognito issued to a user. Call this operation when your user signs out of your app. This results in the following behavior.
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' | 'ChangePasswordError' | 'RevokeTokenError' | 'ForgotPasswordError' | 'ConfirmForgotPasswordError' | 'ResendConfirmationCodeError' | 'UpdateUserAttributesError' | 'VerifyUserAttributeError' | 'GlobalSignOutError';
365
+ export type CognitoErrorType = 'CommonError' | 'InitAuthError' | 'RespondToAuthChallengeError' | 'SignUpError' | 'ConfirmSignUpError' | 'VerifySoftwareTokenError' | 'ChangePasswordError' | 'RevokeTokenError' | 'ForgotPasswordError' | 'ConfirmForgotPasswordError' | 'ResendConfirmationCodeError' | 'UpdateUserAttributesError' | 'VerifyUserAttributeError' | 'AssociateSoftwareTokenError' | 'GlobalSignOutError';
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;
369
- constructor(message: string, errorType: CognitoErrorType, cognitoException: CommonException | InitiateAuthException | RespondToAuthChallengeException | SignUpException | ConfirmSignUpException | ChangePasswordException | RevokeTokenException | ForgotPasswordException | ConfirmForgotPasswordException | ResendConfirmationException | UpdateUserAttributesException | VerifyUserAttributeException | GlobalSignOutException);
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);
370
370
  }
371
371
  export declare class CommonError extends CognitoError {
372
372
  readonly cognitoException: CommonException;
@@ -420,3 +420,11 @@ export declare class GlobalSignOutError extends CognitoError {
420
420
  readonly cognitoException: GlobalSignOutException;
421
421
  constructor(message: string, cognitoException: GlobalSignOutException);
422
422
  }
423
+ export declare class VerifySoftwareTokenError extends CognitoError {
424
+ readonly cognitoException: VerifySoftwareTokenException;
425
+ constructor(message: string, cognitoException: VerifySoftwareTokenException);
426
+ }
427
+ export declare class AssociateSoftwareTokenError extends CognitoError {
428
+ readonly cognitoException: AssociateSoftwareTokenException;
429
+ constructor(message: string, cognitoException: AssociateSoftwareTokenException);
430
+ }
package/lib/error.js CHANGED
@@ -485,3 +485,15 @@ export class GlobalSignOutError extends CognitoError {
485
485
  this.cognitoException = cognitoException;
486
486
  }
487
487
  }
488
+ export class VerifySoftwareTokenError extends CognitoError {
489
+ constructor(message, cognitoException) {
490
+ super(message, 'VerifySoftwareTokenError', cognitoException);
491
+ this.cognitoException = cognitoException;
492
+ }
493
+ }
494
+ export class AssociateSoftwareTokenError extends CognitoError {
495
+ constructor(message, cognitoException) {
496
+ super(message, 'AssociateSoftwareTokenError', cognitoException);
497
+ this.cognitoException = cognitoException;
498
+ }
499
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vardario/cognito-client",
3
- "version": "4.0.6",
3
+ "version": "5.0.0",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "author": "Sahin Vardar",
@@ -16,7 +16,7 @@
16
16
  ],
17
17
  "scripts": {
18
18
  "build": "pnpm build:lib && pnpm build:browser",
19
- "build:browser": "esbuild src/index.ts --bundle --outfile=lib/browser.js --platform=neutral --external:zod",
19
+ "build:browser": "esbuild src/index.ts --bundle --outfile=lib/browser.js --platform=neutral",
20
20
  "build:lib": "tsc --build",
21
21
  "format": "prettier --plugin-search-dir . --write . && prettier-package-json --write && eslint --fix .",
22
22
  "integration-test": "vitest run integration",
@@ -27,12 +27,13 @@
27
27
  "devDependencies": {
28
28
  "@aws-sdk/client-cognito-identity-provider": "^3.465.0",
29
29
  "@types/jsdom": "^21.1.5",
30
+ "@types/node": "^20",
30
31
  "@typescript-eslint/eslint-plugin": "^6.11.0",
31
32
  "@typescript-eslint/parser": "^6.11.0",
32
- "esbuild": "^0.20.2",
33
+ "esbuild": "^0.25.8",
33
34
  "eslint": "^8.54.0",
34
- "eslint-config-prettier": "^9.0.0",
35
- "eslint-plugin-unused-imports": "^3.0.0",
35
+ "eslint-config-prettier": "^10.1.8",
36
+ "eslint-plugin-unused-imports": "^4.1.4",
36
37
  "husky": "^8.0.3",
37
38
  "isomorphic-fetch": "^3.0.0",
38
39
  "jsdom": "^22.1.0",