From b0fb78ae2d950ae9c40c1a22bf52c9bd0a71543b Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 15 Aug 2024 10:29:14 -0700 Subject: [PATCH 01/11] chore(auth): add the service client factories into foundation --- .../core/cognitoUserPoolEndpointResolver.ts | 15 + .../auth/src/foundation/core/constants.ts | 4 + .../src/foundation/core/parsers/getRegion.ts | 17 + .../auth/src/foundation/core/parsers/index.ts | 1 + .../cognitoIdentityProvider/constants.ts | 19 + .../createAssociateSoftwareTokenClient.ts | 28 + .../createChangePasswordClient.ts | 24 + .../createConfirmDeviceClient.ts | 24 + .../createConfirmForgotPasswordClient.ts | 28 + .../createConfirmSignUpClient.ts | 24 + .../createDeleteUserAttributesClient.ts | 28 + .../createDeleteUserClient.ts | 21 + .../createForgetDeviceClient.ts | 24 + .../createForgotPasswordClient.ts | 24 + ...eGetUserAttributeVerificationCodeClient.ts | 28 + .../createGetUserClient.ts | 21 + .../createGlobalSignOutClient.ts | 24 + .../createInitiateAuthClient.ts | 27 + .../createListDevicesClient.ts | 21 + .../createResendConfirmationCodeClient.ts | 28 + .../createRespondToAuthChallengeClient.ts | 28 + .../createRevokeTokenClient.ts | 27 + .../createSetUserMFAPreferenceClient.ts | 28 + .../createSignUpClient.ts | 21 + .../createUpdateDeviceStatusClient.ts | 28 + .../createUpdateUserAttributesClient.ts | 28 + .../createVerifySoftwareTokenClient.ts | 28 + .../createVerifyUserAttributeClient.ts | 28 + .../cognitoIdentityProvider/index.ts | 26 + .../handler/cognitoUserPoolTransferHandler.ts | 37 + .../shared/handler/index.ts | 4 + .../buildEmptyResponseDeserializer.ts | 21 + .../buildUserPoolDeserializer.ts | 27 + .../serialization/buildUserPoolSerializer.ts | 58 + .../shared/serialization/index.ts | 6 + .../cognitoIdentityProvider/types/Sdk.ts | 1712 +++++++++++++++++ .../types/ServiceClient.ts | 8 + .../cognitoIdentityProvider/types/index.ts | 2 + 38 files changed, 2547 insertions(+) create mode 100644 packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts create mode 100644 packages/auth/src/foundation/core/constants.ts create mode 100644 packages/auth/src/foundation/core/parsers/getRegion.ts create mode 100644 packages/auth/src/foundation/core/parsers/index.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/index.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/index.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts create mode 100644 packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts diff --git a/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts b/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts new file mode 100644 index 00000000000..6f7bf9c30d4 --- /dev/null +++ b/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts @@ -0,0 +1,15 @@ +import { + EndpointResolverOptions, + getDnsSuffix, +} from '@aws-amplify/core/internals/aws-client-utils'; +import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; + +import { COGNITO_IDP_SERVICE_NAME } from './constants'; + +export const cognitoUserPoolEndpointResolver = ({ + region, +}: EndpointResolverOptions): { url: URL } => ({ + url: new AmplifyUrl( + `https://${COGNITO_IDP_SERVICE_NAME}.${region}.${getDnsSuffix(region)}`, + ), +}); diff --git a/packages/auth/src/foundation/core/constants.ts b/packages/auth/src/foundation/core/constants.ts new file mode 100644 index 00000000000..1b97d4e9f62 --- /dev/null +++ b/packages/auth/src/foundation/core/constants.ts @@ -0,0 +1,4 @@ +/** + * The service name used to sign requests if the API requires authentication. + */ +export const COGNITO_IDP_SERVICE_NAME = 'cognito-idp'; diff --git a/packages/auth/src/foundation/core/parsers/getRegion.ts b/packages/auth/src/foundation/core/parsers/getRegion.ts new file mode 100644 index 00000000000..ff4755cd836 --- /dev/null +++ b/packages/auth/src/foundation/core/parsers/getRegion.ts @@ -0,0 +1,17 @@ +import { AuthError } from '../../../errors/AuthError'; + +export function getRegion(userPoolId?: string): string { + const region = userPoolId?.split('_')[0]; + if ( + !userPoolId || + userPoolId.indexOf('_') < 0 || + !region || + typeof region !== 'string' + ) + throw new AuthError({ + name: 'InvalidUserPoolId', + message: 'Invalid user pool id provided.', + }); + + return region; +} diff --git a/packages/auth/src/foundation/core/parsers/index.ts b/packages/auth/src/foundation/core/parsers/index.ts new file mode 100644 index 00000000000..1fe194e362a --- /dev/null +++ b/packages/auth/src/foundation/core/parsers/index.ts @@ -0,0 +1 @@ +export { getRegion } from './getRegion'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts new file mode 100644 index 00000000000..c013285cfb0 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts @@ -0,0 +1,19 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + getRetryDecider, + jitteredBackoff, + parseJsonError, +} from '@aws-amplify/core/internals/aws-client-utils'; +import { getAmplifyUserAgent } from '@aws-amplify/core/internals/utils'; + +import { COGNITO_IDP_SERVICE_NAME } from '../../../core/constants'; + +export const DEFAULT_SERVICE_CLIENT_API_CONFIG = { + service: COGNITO_IDP_SERVICE_NAME, + retryDecider: getRetryDecider(parseJsonError), + computeDelay: jitteredBackoff, + userAgentValue: getAmplifyUserAgent(), + cache: 'no-store', +}; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts new file mode 100644 index 00000000000..6b5a54298d8 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + AssociateSoftwareTokenCommandInput, + AssociateSoftwareTokenCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createAssociateSoftwareTokenClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'AssociateSoftwareToken', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts new file mode 100644 index 00000000000..dd2b03422f9 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts @@ -0,0 +1,24 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + ChangePasswordCommandInput, + ChangePasswordCommandOutput, +} from './types/Sdk'; +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createChangePasswordClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('ChangePassword'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts new file mode 100644 index 00000000000..25030468b4c --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts @@ -0,0 +1,24 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + ConfirmDeviceCommandInput, + ConfirmDeviceCommandOutput, +} from './types/Sdk'; +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createConfirmDeviceClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('ConfirmDevice'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts new file mode 100644 index 00000000000..685005aaee9 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + ConfirmForgotPasswordCommandInput, + ConfirmForgotPasswordCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createConfirmForgotPasswordClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'ConfirmForgotPassword', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts new file mode 100644 index 00000000000..460263ed85a --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts @@ -0,0 +1,24 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + ConfirmSignUpCommandInput, + ConfirmSignUpCommandOutput, +} from './types/Sdk'; +import { ServiceClientAPIConfig } from './types/ServiceClient'; + +export const createConfirmSignUpClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('ConfirmSignUp'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts new file mode 100644 index 00000000000..df791e777b5 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + DeleteUserAttributesCommandInput, + DeleteUserAttributesCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createDeleteUserAttributesClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'DeleteUserAttributes', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts new file mode 100644 index 00000000000..5473da6290a --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts @@ -0,0 +1,21 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildEmptyResponseDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { DeleteUserCommandInput, DeleteUserCommandOutput } from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createDeleteUserClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('DeleteUser'), + buildEmptyResponseDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts new file mode 100644 index 00000000000..4f088e2e60f --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts @@ -0,0 +1,24 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildEmptyResponseDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { + ForgetDeviceCommandInput, + ForgetDeviceCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createForgetDeviceClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('ForgetDevice'), + buildEmptyResponseDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts new file mode 100644 index 00000000000..681270eeda3 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts @@ -0,0 +1,24 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + ForgotPasswordCommandInput, + ForgotPasswordCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createForgotPasswordClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('ForgotPassword'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts new file mode 100644 index 00000000000..faea85fd08b --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + GetUserAttributeVerificationCodeCommandInput, + GetUserAttributeVerificationCodeCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createGetUserAttributeVerificationCodeClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'GetUserAttributeVerificationCode', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts new file mode 100644 index 00000000000..2637a4028a4 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts @@ -0,0 +1,21 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { GetUserCommandInput, GetUserCommandOutput } from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createGetUserClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('GetUser'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts new file mode 100644 index 00000000000..4de9ff27ec2 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts @@ -0,0 +1,24 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + GlobalSignOutCommandInput, + GlobalSignOutCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createGlobalSignOutClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('GlobalSignOut'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts new file mode 100644 index 00000000000..9bffc384a85 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts @@ -0,0 +1,27 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + InitiateAuthCommandInput, + InitiateAuthCommandOutput, +} from './types/Sdk'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createInitiateAuthClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('InitiateAuth'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts new file mode 100644 index 00000000000..f445ea9feb6 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts @@ -0,0 +1,21 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { ListDevicesCommandInput, ListDevicesCommandOutput } from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createListDevicesClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('ListDevices'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts new file mode 100644 index 00000000000..16eb230f95e --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + ResendConfirmationCodeCommandInput, + ResendConfirmationCodeCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createResendConfirmationCodeClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'ResendConfirmationCode', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts new file mode 100644 index 00000000000..482069f2039 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + RespondToAuthChallengeCommandInput, + RespondToAuthChallengeCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createRespondToAuthChallengeClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'RespondToAuthChallenge', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts new file mode 100644 index 00000000000..bc9a46aa187 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts @@ -0,0 +1,27 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +interface RevokeTokenInput { + Token: string; + ClientId: string; +} + +type RevokeTokenOutput = Record; + +export const createRevokeTokenClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('RevokeToken'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts new file mode 100644 index 00000000000..1801e416d08 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + SetUserMFAPreferenceCommandInput, + SetUserMFAPreferenceCommandOutput, +} from './types/Sdk'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createSetUserMFAPreferenceClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'SetUserMFAPreference', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts new file mode 100644 index 00000000000..fa99aa9b4ed --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts @@ -0,0 +1,21 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { SignUpCommandInput, SignUpCommandOutput } from './types/Sdk'; + +export const createSignUpClient = (config: ServiceClientAPIConfig) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer('SignUp'), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts new file mode 100644 index 00000000000..b9e72f7834c --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + UpdateDeviceStatusCommandInput, + UpdateDeviceStatusCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createUpdateDeviceStatusClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'UpdateDeviceStatus', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts new file mode 100644 index 00000000000..f69ea5513a2 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + UpdateUserAttributesCommandInput, + UpdateUserAttributesCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createUpdateUserAttributesClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'UpdateUserAttributes', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts new file mode 100644 index 00000000000..e9900b0033e --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + VerifySoftwareTokenCommandInput, + VerifySoftwareTokenCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createVerifySoftwareTokenClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'VerifySoftwareToken', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts new file mode 100644 index 00000000000..6a2f91a69aa --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts @@ -0,0 +1,28 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + buildUserPoolDeserializer, + buildUserPoolSerializer, +} from './shared/serialization'; +import { + VerifyUserAttributeCommandInput, + VerifyUserAttributeCommandOutput, +} from './types/Sdk'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; + +export const createVerifyUserAttributeClient = ( + config: ServiceClientAPIConfig, +) => + composeServiceApi( + cognitoUserPoolTransferHandler, + buildUserPoolSerializer( + 'VerifyUserAttribute', + ), + buildUserPoolDeserializer(), + { + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...config, + }, + ); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/index.ts new file mode 100644 index 00000000000..2b93cd09150 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/index.ts @@ -0,0 +1,26 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { createInitiateAuthClient } from './createInitiateAuthClient'; +export { createRevokeTokenClient } from './createRevokeTokenClient'; +export { createSignUpClient } from './createSignUpClient'; +export { createConfirmSignUpClient } from './createConfirmSignUpClient'; +export { createForgotPasswordClient } from './createForgotPasswordClient'; +export { createConfirmForgotPasswordClient } from './createConfirmForgotPasswordClient'; +export { createRespondToAuthChallengeClient } from './createRespondToAuthChallengeClient'; +export { createResendConfirmationCodeClient } from './createResendConfirmationCodeClient'; +export { createVerifySoftwareTokenClient } from './createVerifySoftwareTokenClient'; +export { createAssociateSoftwareTokenClient } from './createAssociateSoftwareTokenClient'; +export { createSetUserMFAPreferenceClient } from './createSetUserMFAPreferenceClient'; +export { createGetUserClient } from './createGetUserClient'; +export { createChangePasswordClient } from './createChangePasswordClient'; +export { createConfirmDeviceClient } from './createConfirmDeviceClient'; +export { createForgetDeviceClient } from './createForgetDeviceClient'; +export { createDeleteUserClient } from './createDeleteUserClient'; +export { createGetUserAttributeVerificationCodeClient } from './createGetUserAttributeVerificationCodeClient'; +export { createGlobalSignOutClient } from './createGlobalSignOutClient'; +export { createUpdateUserAttributesClient } from './createUpdateUserAttributesClient'; +export { createVerifyUserAttributeClient } from './createVerifyUserAttributeClient'; +export { createUpdateDeviceStatusClient } from './createUpdateDeviceStatusClient'; +export { createListDevicesClient } from './createListDevicesClient'; +export { createDeleteUserAttributesClient } from './createDeleteUserAttributesClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.ts new file mode 100644 index 00000000000..b1b917f0a08 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.ts @@ -0,0 +1,37 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers'; +import { + HttpRequest, + Middleware, + unauthenticatedHandler, +} from '@aws-amplify/core/internals/aws-client-utils'; +import { HttpResponse } from '@aws-amplify/core/src/clients/types'; + +/** + * A Cognito Identity-specific middleware that disables caching for all requests. + */ +const disableCacheMiddlewareFactory: Middleware< + HttpRequest, + HttpResponse, + Record +> = () => (next, _) => + async function disableCacheMiddleware(request) { + request.headers['cache-control'] = 'no-store'; + + return next(request); + }; + +/** + * A Cognito Identity-specific transfer handler that does NOT sign requests, and + * disables caching. + * + * @internal + */ +export const cognitoUserPoolTransferHandler = composeTransferHandler< + [Parameters[0]], + HttpRequest, + HttpResponse, + typeof unauthenticatedHandler +>(unauthenticatedHandler, [disableCacheMiddlewareFactory]); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/index.ts new file mode 100644 index 00000000000..c0df8483e89 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/index.ts @@ -0,0 +1,4 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { cognitoUserPoolTransferHandler } from './cognitoUserPoolTransferHandler'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts new file mode 100644 index 00000000000..37e1af5a0ad --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts @@ -0,0 +1,21 @@ +import { + HttpResponse, + parseJsonError, +} from '@aws-amplify/core/internals/aws-client-utils'; + +import { assertServiceError } from '../../../../../../errors/utils/assertServiceError'; +import { AuthError } from '../../../../../../errors/AuthError'; + +export const buildEmptyResponseDeserializer = (): (( + response: HttpResponse, +) => Promise) => { + return async (response: HttpResponse): Promise => { + if (response.statusCode >= 300) { + const error = await parseJsonError(response); + assertServiceError(error); + throw new AuthError({ name: error.name, message: error.message }); + } else { + return undefined as any; + } + }; +}; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts new file mode 100644 index 00000000000..cc68d55cb94 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts @@ -0,0 +1,27 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + HttpResponse, + parseJsonBody, + parseJsonError, +} from '@aws-amplify/core/internals/aws-client-utils'; + +import { assertServiceError } from '../../../../../../errors/utils/assertServiceError'; +import { AuthError } from '../../../../../../errors/AuthError'; + +export const buildUserPoolDeserializer = (): (( + response: HttpResponse, +) => Promise) => { + return async (response: HttpResponse): Promise => { + if (response.statusCode >= 300) { + const error = await parseJsonError(response); + assertServiceError(error); + throw new AuthError({ name: error.name, message: error.message }); + } else { + const body = await parseJsonBody(response); + + return body; + } + }; +}; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts new file mode 100644 index 00000000000..ae9c9c64225 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts @@ -0,0 +1,58 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + Endpoint, + Headers, + HttpRequest, +} from '@aws-amplify/core/internals/aws-client-utils'; + +type ClientOperation = + | 'SignUp' + | 'ConfirmSignUp' + | 'ForgotPassword' + | 'ConfirmForgotPassword' + | 'InitiateAuth' + | 'RespondToAuthChallenge' + | 'ResendConfirmationCode' + | 'VerifySoftwareToken' + | 'AssociateSoftwareToken' + | 'SetUserMFAPreference' + | 'GetUser' + | 'ChangePassword' + | 'ConfirmDevice' + | 'ForgetDevice' + | 'DeleteUser' + | 'GetUserAttributeVerificationCode' + | 'GlobalSignOut' + | 'UpdateUserAttributes' + | 'VerifyUserAttribute' + | 'DeleteUserAttributes' + | 'UpdateDeviceStatus' + | 'ListDevices' + | 'RevokeToken'; + +export const buildUserPoolSerializer = + (operation: ClientOperation) => + (input: Input, endpoint: Endpoint): HttpRequest => { + const headers = getSharedHeaders(operation); + const body = JSON.stringify(input); + + return buildHttpRpcRequest(endpoint, headers, body); + }; + +const getSharedHeaders = (operation: string): Headers => ({ + 'content-type': 'application/x-amz-json-1.1', + 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}`, +}); + +const buildHttpRpcRequest = ( + { url }: Endpoint, + headers: Headers, + body: string, +): HttpRequest => ({ + headers, + url, + body, + method: 'POST', +}); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts new file mode 100644 index 00000000000..c0e4ae9b71f --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts @@ -0,0 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { buildUserPoolSerializer } from './buildUserPoolSerializer'; +export { buildUserPoolDeserializer } from './buildUserPoolDeserializer'; +export { buildEmptyResponseDeserializer } from './buildEmptyResponseDeserializer'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts new file mode 100644 index 00000000000..c08589ad448 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts @@ -0,0 +1,1712 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Generated by scripts/dts-bundler/README.md + +import { MetadataBearer as __MetadataBearer } from '@aws-sdk/types'; + +export type ChallengeName = + | 'SMS_MFA' + | 'SOFTWARE_TOKEN_MFA' + | 'SELECT_MFA_TYPE' + | 'MFA_SETUP' + | 'PASSWORD_VERIFIER' + | 'CUSTOM_CHALLENGE' + | 'DEVICE_SRP_AUTH' + | 'DEVICE_PASSWORD_VERIFIER' + | 'ADMIN_NO_SRP_AUTH' + | 'NEW_PASSWORD_REQUIRED'; + +export type ChallengeParameters = { + CODE_DELIVERY_DESTINATION?: string; + CODE_DELIVERY_DELIVERY_MEDIUM?: string; + requiredAttributes?: string; + USER_ID_FOR_SRP?: string; + SECRET_BLOCK?: string; + PASSWORD_CLAIM_SIGNATURE?: string; + MFAS_CAN_CHOOSE?: string; + MFAS_CAN_SETUP?: string; +} & Record; + +export type CognitoMFAType = 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; + +export interface CognitoMFASettings { + Enabled?: boolean; + PreferredMfa?: boolean; +} + +declare enum AuthFlowType { + ADMIN_NO_SRP_AUTH = 'ADMIN_NO_SRP_AUTH', + ADMIN_USER_PASSWORD_AUTH = 'ADMIN_USER_PASSWORD_AUTH', + CUSTOM_AUTH = 'CUSTOM_AUTH', + REFRESH_TOKEN = 'REFRESH_TOKEN', + REFRESH_TOKEN_AUTH = 'REFRESH_TOKEN_AUTH', + USER_PASSWORD_AUTH = 'USER_PASSWORD_AUTH', + USER_SRP_AUTH = 'USER_SRP_AUTH', +} +declare enum ChallengeNameType { + ADMIN_NO_SRP_AUTH = 'ADMIN_NO_SRP_AUTH', + CUSTOM_CHALLENGE = 'CUSTOM_CHALLENGE', + DEVICE_PASSWORD_VERIFIER = 'DEVICE_PASSWORD_VERIFIER', + DEVICE_SRP_AUTH = 'DEVICE_SRP_AUTH', + MFA_SETUP = 'MFA_SETUP', + NEW_PASSWORD_REQUIRED = 'NEW_PASSWORD_REQUIRED', + PASSWORD_VERIFIER = 'PASSWORD_VERIFIER', + SELECT_MFA_TYPE = 'SELECT_MFA_TYPE', + SMS_MFA = 'SMS_MFA', + SOFTWARE_TOKEN_MFA = 'SOFTWARE_TOKEN_MFA', +} +declare enum DeliveryMediumType { + EMAIL = 'EMAIL', + SMS = 'SMS', +} +declare enum DeviceRememberedStatusType { + NOT_REMEMBERED = 'not_remembered', + REMEMBERED = 'remembered', +} +declare enum VerifySoftwareTokenResponseType { + ERROR = 'ERROR', + SUCCESS = 'SUCCESS', +} +declare namespace AnalyticsMetadataType { + /** + * @internal + */ + const filterSensitiveLog: (obj: AnalyticsMetadataType) => any; +} +declare namespace AssociateSoftwareTokenRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: AssociateSoftwareTokenRequest) => any; +} +declare namespace AssociateSoftwareTokenResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: AssociateSoftwareTokenResponse) => any; +} +declare namespace AttributeType { + /** + * @internal + */ + const filterSensitiveLog: (obj: AttributeType) => any; +} +declare namespace AuthenticationResultType { + /** + * @internal + */ + const filterSensitiveLog: (obj: AuthenticationResultType) => any; +} +declare namespace ChangePasswordRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ChangePasswordRequest) => any; +} +declare namespace ChangePasswordResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ChangePasswordResponse) => any; +} +declare namespace CodeDeliveryDetailsType { + /** + * @internal + */ + const filterSensitiveLog: (obj: CodeDeliveryDetailsType) => any; +} +declare namespace ConfirmDeviceRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ConfirmDeviceRequest) => any; +} +declare namespace ConfirmDeviceResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ConfirmDeviceResponse) => any; +} +declare namespace ConfirmForgotPasswordRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ConfirmForgotPasswordRequest) => any; +} +declare namespace ConfirmForgotPasswordResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ConfirmForgotPasswordResponse) => any; +} +declare namespace ConfirmSignUpRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ConfirmSignUpRequest) => any; +} +declare namespace ConfirmSignUpResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ConfirmSignUpResponse) => any; +} +declare namespace DeleteUserRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: DeleteUserRequest) => any; +} +declare namespace DeleteUserResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: DeleteUserResponse) => any; +} +declare namespace DeviceSecretVerifierConfigType { + /** + * @internal + */ + const filterSensitiveLog: (obj: DeviceSecretVerifierConfigType) => any; +} +declare namespace DeviceType { + /** + * @internal + */ + const filterSensitiveLog: (obj: DeviceType) => any; +} +declare namespace ForgetDeviceRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ForgetDeviceRequest) => any; +} +declare namespace ForgotPasswordRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ForgotPasswordRequest) => any; +} +declare namespace ForgotPasswordResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ForgotPasswordResponse) => any; +} +declare namespace GetUserAttributeVerificationCodeRequest { + /** + * @internal + */ + const filterSensitiveLog: ( + obj: GetUserAttributeVerificationCodeRequest, + ) => any; +} +declare namespace GetUserAttributeVerificationCodeResponse { + /** + * @internal + */ + const filterSensitiveLog: ( + obj: GetUserAttributeVerificationCodeResponse, + ) => any; +} +declare namespace GetUserRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: GetUserRequest) => any; +} +declare namespace GetUserResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: GetUserResponse) => any; +} +declare namespace GlobalSignOutRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: GlobalSignOutRequest) => any; +} +declare namespace GlobalSignOutResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: GlobalSignOutResponse) => any; +} +declare namespace InitiateAuthRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: InitiateAuthRequest) => any; +} +declare namespace InitiateAuthResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: InitiateAuthResponse) => any; +} +declare namespace ListDevicesRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ListDevicesRequest) => any; +} +declare namespace ListDevicesResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ListDevicesResponse) => any; +} +declare namespace MFAOptionType { + /** + * @internal + */ + const filterSensitiveLog: (obj: MFAOptionType) => any; +} +declare namespace NewDeviceMetadataType { + /** + * @internal + */ + const filterSensitiveLog: (obj: NewDeviceMetadataType) => any; +} +declare namespace ResendConfirmationCodeRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: ResendConfirmationCodeRequest) => any; +} +declare namespace ResendConfirmationCodeResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: ResendConfirmationCodeResponse) => any; +} +declare namespace RespondToAuthChallengeRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: RespondToAuthChallengeRequest) => any; +} +declare namespace RespondToAuthChallengeResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: RespondToAuthChallengeResponse) => any; +} +declare namespace SMSMfaSettingsType { + /** + * @internal + */ + const filterSensitiveLog: (obj: SMSMfaSettingsType) => any; +} +declare namespace SetUserMFAPreferenceRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: SetUserMFAPreferenceRequest) => any; +} +declare namespace SetUserMFAPreferenceResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: SetUserMFAPreferenceResponse) => any; +} +declare namespace SignUpRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: SignUpRequest) => any; +} +declare namespace SignUpResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: SignUpResponse) => any; +} +declare namespace SoftwareTokenMfaSettingsType { + /** + * @internal + */ + const filterSensitiveLog: (obj: SoftwareTokenMfaSettingsType) => any; +} +declare namespace UpdateDeviceStatusRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: UpdateDeviceStatusRequest) => any; +} +declare namespace UpdateDeviceStatusResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: UpdateDeviceStatusResponse) => any; +} +declare namespace UpdateUserAttributesRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: UpdateUserAttributesRequest) => any; +} +declare namespace UpdateUserAttributesResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: UpdateUserAttributesResponse) => any; +} +declare namespace UserContextDataType { + /** + * @internal + */ + const filterSensitiveLog: (obj: UserContextDataType) => any; +} +declare namespace VerifySoftwareTokenRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: VerifySoftwareTokenRequest) => any; +} +declare namespace VerifySoftwareTokenResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: VerifySoftwareTokenResponse) => any; +} +declare namespace VerifyUserAttributeRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: VerifyUserAttributeRequest) => any; +} +declare namespace VerifyUserAttributeResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: VerifyUserAttributeResponse) => any; +} +declare namespace DeleteUserAttributesRequest { + /** + * @internal + */ + const filterSensitiveLog: (obj: DeleteUserAttributesRequest) => any; +} +declare namespace DeleteUserAttributesResponse { + /** + * @internal + */ + const filterSensitiveLog: (obj: DeleteUserAttributesResponse) => any; +} +/** + *

An Amazon Pinpoint analytics endpoint.

+ *

An endpoint uniquely identifies a mobile device, email address, or phone number that can receive messages from Amazon Pinpoint analytics.

+ * + *

Amazon Cognito User Pools only supports sending events to Amazon Pinpoint projects in the US East (N. Virginia) us-east-1 Region, regardless of the Region in which the user pool resides.

+ *
+ */ +export interface AnalyticsMetadataType { + /** + *

The endpoint ID.

+ */ + AnalyticsEndpointId?: string; +} +export type AssociateSoftwareTokenCommandInput = AssociateSoftwareTokenRequest; +export interface AssociateSoftwareTokenCommandOutput + extends AssociateSoftwareTokenResponse, + __MetadataBearer {} +export interface AssociateSoftwareTokenRequest { + /** + *

The access token.

+ */ + AccessToken?: string; + /** + *

The session that should be passed both ways in challenge-response calls to the service. This allows authentication of the user as part of the MFA setup process.

+ */ + Session?: string; +} +export interface AssociateSoftwareTokenResponse { + /** + *

A unique generated shared secret code that is used in the time-based one-time password (TOTP) algorithm to generate a one-time code.

+ */ + SecretCode?: string; + /** + *

The session that should be passed both ways in challenge-response calls to the service. This allows authentication of the user as part of the MFA setup process.

+ */ + Session?: string; +} +/** + *

Specifies whether the attribute is standard or custom.

+ */ +export interface AttributeType { + /** + *

The name of the attribute.

+ */ + Name: string | undefined; + /** + *

The value of the attribute.

+ */ + Value?: string; +} +/** + *

The authentication result.

+ */ +export interface AuthenticationResultType { + /** + *

The access token.

+ */ + AccessToken?: string; + /** + *

The expiration period of the authentication result in seconds.

+ */ + ExpiresIn?: number; + /** + *

The token type.

+ */ + TokenType?: string; + /** + *

The refresh token.

+ */ + RefreshToken?: string; + /** + *

The ID token.

+ */ + IdToken?: string; + /** + *

The new device metadata from an authentication result.

+ */ + NewDeviceMetadata?: NewDeviceMetadataType; +} +export type ChangePasswordCommandInput = ChangePasswordRequest; +export interface ChangePasswordCommandOutput + extends ChangePasswordResponse, + __MetadataBearer {} +/** + *

Represents the request to change a user password.

+ */ +export interface ChangePasswordRequest { + /** + *

The old password.

+ */ + PreviousPassword: string | undefined; + /** + *

The new password.

+ */ + ProposedPassword: string | undefined; + /** + *

The access token.

+ */ + AccessToken: string | undefined; +} +/** + *

The response from the server to the change password request.

+ */ +export type ChangePasswordResponse = Record; +/** + *

The code delivery details being returned from the server.

+ */ +export interface CodeDeliveryDetailsType { + /** + *

The destination for the code delivery details.

+ */ + Destination?: string; + /** + *

The delivery medium (email message or phone number).

+ */ + DeliveryMedium?: DeliveryMediumType | string; + /** + *

The attribute name.

+ */ + AttributeName?: string; +} +export type ConfirmDeviceCommandInput = ConfirmDeviceRequest; +export interface ConfirmDeviceCommandOutput + extends ConfirmDeviceResponse, + __MetadataBearer {} +/** + *

Confirms the device request.

+ */ +export interface ConfirmDeviceRequest { + /** + *

The access token.

+ */ + AccessToken: string | undefined; + /** + *

The device key.

+ */ + DeviceKey: string | undefined; + /** + *

The configuration of the device secret verifier.

+ */ + DeviceSecretVerifierConfig?: DeviceSecretVerifierConfigType; + /** + *

The device name.

+ */ + DeviceName?: string; +} +/** + *

Confirms the device response.

+ */ +export interface ConfirmDeviceResponse { + /** + *

Indicates whether the user confirmation must confirm the device response.

+ */ + UserConfirmationNecessary?: boolean; +} +export type ConfirmForgotPasswordCommandInput = ConfirmForgotPasswordRequest; +export interface ConfirmForgotPasswordCommandOutput + extends ConfirmForgotPasswordResponse, + __MetadataBearer {} +/** + *

The request representing the confirmation for a password reset.

+ */ +export interface ConfirmForgotPasswordRequest { + /** + *

The app client ID of the app associated with the user pool.

+ */ + ClientId: string | undefined; + /** + *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

+ */ + SecretHash?: string; + /** + *

The user name of the user for whom you want to enter a code to retrieve a forgotten password.

+ */ + Username: string | undefined; + /** + *

The confirmation code sent by a user's request to retrieve a forgotten password. For more information, + * see ForgotPassword.

+ */ + ConfirmationCode: string | undefined; + /** + *

The password sent by a user's request to retrieve a forgotten password.

+ */ + Password: string | undefined; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for ConfirmForgotPassword calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ConfirmForgotPassword API action, Amazon Cognito + * invokes the function that is assigned to the post confirmation trigger. When Amazon Cognito invokes this function, it passes a + * JSON payload, + * which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned + * to the ClientMetadata parameter in your ConfirmForgotPassword request. In your function code in Lambda, you can process the + * clientMetadata value to enhance your workflow for your specific needs.

+ *

For more information, + * see Customizing User Pool Workflows with Lambda Triggers + * in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

The response from the server that results from a user's request to retrieve a forgotten password.

+ */ +export type ConfirmForgotPasswordResponse = Record; +export type ConfirmSignUpCommandInput = ConfirmSignUpRequest; +export interface ConfirmSignUpCommandOutput + extends ConfirmSignUpResponse, + __MetadataBearer {} +/** + *

Represents the request to confirm registration of a user.

+ */ +export interface ConfirmSignUpRequest { + /** + *

The ID of the app client associated with the user pool.

+ */ + ClientId: string | undefined; + /** + *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

+ */ + SecretHash?: string; + /** + *

The user name of the user whose registration you want to confirm.

+ */ + Username: string | undefined; + /** + *

The confirmation code sent by a user's request to confirm registration.

+ */ + ConfirmationCode: string | undefined; + /** + *

Boolean to be specified to force user confirmation irrespective of existing alias. By default set to False. If this parameter is set to + * True and the phone number/email used for sign up confirmation already exists as an alias with a different user, the API call will migrate + * the alias from the previous user to the newly created user being confirmed. If set to False, the API will throw an + * AliasExistsException error.

+ */ + ForceAliasCreation?: boolean; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for ConfirmSignUp calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ * + *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ConfirmSignUp API action, + * Amazon Cognito invokes the function that is assigned to the post confirmation trigger. When Amazon Cognito invokes this + * function, it passes a JSON payload, which the function receives as input. This payload contains a clientMetadata attribute, which + * provides the data that you assigned to the ClientMetadata parameter in your ConfirmSignUp request. In your function code in Lambda, + * you can process the clientMetadata value to enhance your workflow for your specific needs.

+ *

For more information, + * see Customizing User Pool Workflows with Lambda Triggers + * in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

Represents the response from the server for the registration confirmation.

+ */ +export type ConfirmSignUpResponse = Record; +export type DeleteUserCommandInput = DeleteUserRequest; +export interface DeleteUserCommandOutput + extends DeleteUserResponse, + __MetadataBearer {} +/** + *

Represents the request to delete a user.

+ */ +export interface DeleteUserRequest { + /** + *

The access token from a request to delete a user.

+ */ + AccessToken: string | undefined; +} +export type DeleteUserResponse = Record; +/** + *

The device verifier against which it is authenticated.

+ */ +export interface DeviceSecretVerifierConfigType { + /** + *

The password verifier.

+ */ + PasswordVerifier?: string; + /** + *

The salt.

+ */ + Salt?: string; +} +/** + *

The device type.

+ */ +export interface DeviceType { + /** + *

The device key.

+ */ + DeviceKey?: string; + /** + *

The device attributes.

+ */ + DeviceAttributes?: AttributeType[]; + /** + *

The creation date of the device.

+ */ + DeviceCreateDate?: number; + /** + *

The last modified date of the device.

+ */ + DeviceLastModifiedDate?: number; + /** + *

The date when the device was last authenticated.

+ */ + DeviceLastAuthenticatedDate?: number; +} +export type ForgetDeviceCommandInput = ForgetDeviceRequest; +export type ForgetDeviceCommandOutput = __MetadataBearer; +/** + *

Represents the request to forget the device.

+ */ +export interface ForgetDeviceRequest { + /** + *

The access token for the forgotten device request.

+ */ + AccessToken?: string; + /** + *

The device key.

+ */ + DeviceKey: string | undefined; +} +export type ForgotPasswordCommandInput = ForgotPasswordRequest; +export interface ForgotPasswordCommandOutput + extends ForgotPasswordResponse, + __MetadataBearer {} +/** + *

Represents the request to reset a user's password.

+ */ +export interface ForgotPasswordRequest { + /** + *

The ID of the client associated with the user pool.

+ */ + ClientId: string | undefined; + /** + *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

+ */ + SecretHash?: string; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; + /** + *

The user name of the user for whom you want to enter a code to reset a forgotten password.

+ */ + Username: string | undefined; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for ForgotPassword calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ForgotPassword API action, + * Amazon Cognito invokes any functions that are assigned to the following triggers: pre sign-up, custom message, + * and user migration. When Amazon Cognito invokes any of these functions, it passes a JSON + * payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned + * to the ClientMetadata parameter in your ForgotPassword request. In your function code in Lambda, you can process the + * clientMetadata value to enhance your workflow for your specific needs.

+ *

For more information, see Customizing User Pool Workflows + * with Lambda Triggers in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

Respresents the response from the server regarding the request to reset a password.

+ */ +export interface ForgotPasswordResponse { + /** + *

The code delivery details returned by the server in response to the request to reset a password.

+ */ + CodeDeliveryDetails?: CodeDeliveryDetailsType; +} +export type GetUserAttributeVerificationCodeCommandInput = + GetUserAttributeVerificationCodeRequest; +export interface GetUserAttributeVerificationCodeCommandOutput + extends GetUserAttributeVerificationCodeResponse, + __MetadataBearer {} +/** + *

Represents the request to get user attribute verification.

+ */ +export interface GetUserAttributeVerificationCodeRequest { + /** + *

The access token returned by the server response to get the user attribute verification code.

+ */ + AccessToken: string | undefined; + /** + *

The attribute name returned by the server response to get the user attribute verification code.

+ */ + AttributeName: string | undefined; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ * + *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the GetUserAttributeVerificationCode + * API action, Amazon Cognito invokes the function that is assigned to the custom message trigger. When Amazon Cognito invokes this function, it + * passes a JSON payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data + * that you assigned to the ClientMetadata parameter in your GetUserAttributeVerificationCode request. In your function code in Lambda, + * you can process the clientMetadata value to enhance your workflow for your specific needs.

+ *

For more information, + * see Customizing User Pool Workflows with Lambda Triggers + * in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

The verification code response returned by the server response to get the user attribute verification code.

+ */ +export interface GetUserAttributeVerificationCodeResponse { + /** + *

The code delivery details returned by the server in response to the request to get the user attribute verification code.

+ */ + CodeDeliveryDetails?: CodeDeliveryDetailsType; +} +export type GetUserCommandInput = GetUserRequest; +export interface GetUserCommandOutput + extends GetUserResponse, + __MetadataBearer {} +/** + *

Represents the request to get information about the user.

+ */ +export interface GetUserRequest { + /** + *

The access token returned by the server response to get information about the user.

+ */ + AccessToken: string | undefined; +} +/** + *

Represents the response from the server from the request to get information about the user.

+ */ +export interface GetUserResponse { + /** + *

The user name of the user you want to retrieve from the get user request.

+ */ + Username: string | undefined; + /** + *

An array of name-value pairs representing user attributes.

+ *

For custom attributes, you must prepend the custom: prefix to the attribute name.

+ */ + UserAttributes: AttributeType[] | undefined; + /** + *

+ * This response parameter is no longer supported. It provides information only about SMS MFA configurations. It doesn't provide information about time-based one-time + * password (TOTP) software token MFA configurations. To look up information about either type of MFA configuration, use UserMFASettingList instead.

+ */ + MFAOptions?: MFAOptionType[]; + /** + *

The user's preferred MFA setting.

+ */ + PreferredMfaSetting?: string; + /** + *

The MFA options that are activated for the user. The possible values in this list are SMS_MFA and SOFTWARE_TOKEN_MFA.

+ */ + UserMFASettingList?: string[]; +} +export type GlobalSignOutCommandInput = GlobalSignOutRequest; +export interface GlobalSignOutCommandOutput + extends GlobalSignOutResponse, + __MetadataBearer {} +/** + *

Represents the request to sign out all devices.

+ */ +export interface GlobalSignOutRequest { + /** + *

The access token.

+ */ + AccessToken: string | undefined; +} +/** + *

The response to the request to sign out all devices.

+ */ +export type GlobalSignOutResponse = Record; +export type InitiateAuthCommandInput = InitiateAuthRequest; +export interface InitiateAuthCommandOutput + extends InitiateAuthResponse, + __MetadataBearer {} +/** + *

Initiates the authentication request.

+ */ +export interface InitiateAuthRequest { + /** + *

The authentication flow for this call to run. The API action will depend on this value. For example:

+ *
    + *
  • + *

    + * REFRESH_TOKEN_AUTH takes in a valid refresh token and returns new tokens.

    + *
  • + *
  • + *

    + * USER_SRP_AUTH takes in USERNAME and SRP_A and returns the SRP variables to be used for next challenge execution.

    + *
  • + *
  • + *

    + * USER_PASSWORD_AUTH takes in USERNAME and PASSWORD and returns the next challenge or tokens.

    + *
  • + *
+ *

Valid values include:

+ * + *
    + *
  • + *

    + * USER_SRP_AUTH: Authentication flow for the Secure Remote Password (SRP) protocol.

    + *
  • + *
  • + *

    + * REFRESH_TOKEN_AUTH/REFRESH_TOKEN: Authentication flow for refreshing the access token and ID token by supplying a valid refresh token.

    + *
  • + *
  • + *

    + * CUSTOM_AUTH: Custom authentication flow.

    + *
  • + *
  • + *

    + * USER_PASSWORD_AUTH: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a user migration Lambda trigger is set, this flow will invoke the user migration + * Lambda if it doesn't find the USERNAME in the user pool.

    + *
  • + *
+ *

+ * ADMIN_NO_SRP_AUTH isn't a valid value.

+ */ + AuthFlow: AuthFlowType | string | undefined; + /** + *

The authentication parameters. These are inputs corresponding to the AuthFlow that you're invoking. The required values depend on the value of AuthFlow:

+ * + *
    + *
  • + *

    For USER_SRP_AUTH: USERNAME (required), SRP_A (required), SECRET_HASH (required if the app client is configured with a client secret), + * DEVICE_KEY.

    + *
  • + *
  • + *

    For REFRESH_TOKEN_AUTH/REFRESH_TOKEN: REFRESH_TOKEN (required), SECRET_HASH (required if the app client is configured with a client secret), + * DEVICE_KEY.

    + *
  • + *
  • + *

    For CUSTOM_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), DEVICE_KEY. To start the + * authentication flow with password verification, include ChallengeName: SRP_A and SRP_A: (The SRP_A Value).

    + *
  • + *
+ */ + AuthParameters?: Record; + /** + *

A map of custom key-value pairs that you can provide as input for certain custom workflows that this action triggers.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the InitiateAuth API action, Amazon Cognito invokes the Lambda functions that are specified for various + * triggers. The ClientMetadata value is passed as input to the functions for only the following triggers:

+ *
    + *
  • + *

    Pre signup

    + *
  • + *
  • + *

    Pre authentication

    + *
  • + *
  • + *

    User migration

    + *
  • + *
+ *

When Amazon Cognito invokes the functions for these triggers, it passes a JSON + * payload, which the function receives as input. This payload contains a validationData attribute, which provides the data that you assigned to the ClientMetadata parameter in your + * InitiateAuth request. In your function code in Lambda, you can process the validationData value to enhance your workflow for your specific needs.

+ *

When you use the InitiateAuth API action, Amazon Cognito also invokes the functions for the following triggers, but it doesn't provide the ClientMetadata value as input:

+ *
    + *
  • + *

    Post authentication

    + *
  • + *
  • + *

    Custom message

    + *
  • + *
  • + *

    Pre token generation

    + *
  • + *
  • + *

    Create auth challenge

    + *
  • + *
  • + *

    Define auth challenge

    + *
  • + *
  • + *

    Verify auth challenge

    + *
  • + *
+ *

For more information, see Customizing User Pool Workflows with + * Lambda Triggers in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool configuration + * doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; + /** + *

The app client ID.

+ */ + ClientId: string | undefined; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for InitiateAuth calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; +} +/** + *

Initiates the authentication response.

+ */ +export interface InitiateAuthResponse { + /** + *

The name of the challenge that you're responding to with this call. This name is returned in the AdminInitiateAuth response if you must pass another challenge.

+ *

Valid values include the following. Note that all of these challenges require + * USERNAME and SECRET_HASH (if applicable) in the parameters.

+ * + *
    + *
  • + *

    + * SMS_MFA: Next challenge is to supply an SMS_MFA_CODE, delivered via SMS.

    + *
  • + *
  • + *

    + * PASSWORD_VERIFIER: Next challenge is to supply PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, and TIMESTAMP after the + * client-side SRP calculations.

    + *
  • + *
  • + *

    + * CUSTOM_CHALLENGE: This is returned if your custom authentication flow determines that the user should pass another challenge before tokens are issued.

    + *
  • + *
  • + *

    + * DEVICE_SRP_AUTH: If device tracking was activated on your user pool and the previous challenges were passed, this challenge is returned so that Amazon Cognito can start tracking + * this device.

    + *
  • + *
  • + *

    + * DEVICE_PASSWORD_VERIFIER: Similar to PASSWORD_VERIFIER, but for devices only.

    + *
  • + *
  • + *

    + * NEW_PASSWORD_REQUIRED: For users who are required to change their passwords after successful first login. This challenge should be passed with NEW_PASSWORD + * and any other required attributes.

    + *
  • + *
  • + *

    + * MFA_SETUP: For users who are required to setup an MFA factor before they can sign in. The MFA types activated for the user pool will be listed in the challenge parameters + * MFA_CAN_SETUP value.

    + *

    To set up software token MFA, use the session returned here from InitiateAuth as an input to AssociateSoftwareToken. Use the session returned by + * VerifySoftwareToken as an input to RespondToAuthChallenge with challenge name MFA_SETUP to complete sign-in. To set up SMS MFA, an + * administrator should help the user to add a phone number to their account, and then the user should call InitiateAuth again to restart sign-in.

    + *
  • + *
+ */ + ChallengeName?: ChallengeNameType | string; + /** + *

The session that should pass both ways in challenge-response calls to the service. If the caller must pass another challenge, they return a session with other challenge parameters. This session + * should be passed as it is to the next RespondToAuthChallenge API call.

+ */ + Session?: string; + /** + *

The challenge parameters. These are returned in the InitiateAuth response if you must pass another challenge. The responses in this parameter should be used to compute inputs to + * the next call (RespondToAuthChallenge).

+ *

All challenges require USERNAME and SECRET_HASH (if applicable).

+ */ + ChallengeParameters?: Record; + /** + *

The result of the authentication response. This result is only returned if the caller doesn't need to pass another challenge. If the caller does need to pass another challenge before it gets + * tokens, ChallengeName, ChallengeParameters, and Session are returned.

+ */ + AuthenticationResult?: AuthenticationResultType; +} +export type ListDevicesCommandInput = ListDevicesRequest; +export interface ListDevicesCommandOutput + extends ListDevicesResponse, + __MetadataBearer {} +/** + *

Represents the request to list the devices.

+ */ +export interface ListDevicesRequest { + /** + *

The access tokens for the request to list devices.

+ */ + AccessToken: string | undefined; + /** + *

The limit of the device request.

+ */ + Limit?: number; + /** + *

The pagination token for the list request.

+ */ + PaginationToken?: string; +} +/** + *

Represents the response to list devices.

+ */ +export interface ListDevicesResponse { + /** + *

The devices returned in the list devices response.

+ */ + Devices?: DeviceType[]; + /** + *

The pagination token for the list device response.

+ */ + PaginationToken?: string; +} +/** + *

+ * This data type is no longer supported. You can use it + * only for SMS multi-factor authentication (MFA) configurations. You can't use it for time-based one-time password (TOTP) software token MFA configurations.

+ */ +export interface MFAOptionType { + /** + *

The delivery medium to send the MFA code. You can use this parameter to set only the SMS delivery medium value.

+ */ + DeliveryMedium?: DeliveryMediumType | string; + /** + *

The attribute name of the MFA option type. The only valid value is phone_number.

+ */ + AttributeName?: string; +} +/** + *

The new device metadata type.

+ */ +export interface NewDeviceMetadataType { + /** + *

The device key.

+ */ + DeviceKey?: string; + /** + *

The device group key.

+ */ + DeviceGroupKey?: string; +} +export type ResendConfirmationCodeCommandInput = ResendConfirmationCodeRequest; +export interface ResendConfirmationCodeCommandOutput + extends ResendConfirmationCodeResponse, + __MetadataBearer {} +/** + *

Represents the request to resend the confirmation code.

+ */ +export interface ResendConfirmationCodeRequest { + /** + *

The ID of the client associated with the user pool.

+ */ + ClientId: string | undefined; + /** + *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

+ */ + SecretHash?: string; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; + /** + *

The username attribute of the user to whom you want to resend a confirmation code.

+ */ + Username: string | undefined; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for ResendConfirmationCode calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ResendConfirmationCode API action, Amazon Cognito + * invokes the function that is assigned to the custom message trigger. When Amazon Cognito invokes this function, it passes a + * JSON + * payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned + * to the ClientMetadata parameter in your ResendConfirmationCode request. In your function code in Lambda, you can process the clientMetadata + * value to enhance your workflow for your specific needs.

+ *

For more information, + * see Customizing User Pool Workflows with Lambda Triggers + * in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

The response from the server when Amazon Cognito makes the request to resend a confirmation code.

+ */ +export interface ResendConfirmationCodeResponse { + /** + *

The code delivery details returned by the server in response to the request to resend the confirmation code.

+ */ + CodeDeliveryDetails?: CodeDeliveryDetailsType; +} +export type RespondToAuthChallengeCommandInput = RespondToAuthChallengeRequest; +export interface RespondToAuthChallengeCommandOutput + extends RespondToAuthChallengeResponse, + __MetadataBearer {} +/** + *

The request to respond to an authentication challenge.

+ */ +export interface RespondToAuthChallengeRequest { + /** + *

The app client ID.

+ */ + ClientId: string | undefined; + /** + *

The challenge name. For more information, see InitiateAuth.

+ *

+ * ADMIN_NO_SRP_AUTH isn't a valid value.

+ */ + ChallengeName: ChallengeNameType | string | undefined; + /** + *

The session that should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines + * that the caller must pass another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge + * API call.

+ */ + Session?: string; + /** + *

The challenge responses. These are inputs corresponding to the value of ChallengeName, for example:

+ * + *

+ * SECRET_HASH (if app client is configured with client secret) applies to all of the inputs that follow (including SOFTWARE_TOKEN_MFA).

+ *
+ *
    + *
  • + *

    + * SMS_MFA: SMS_MFA_CODE, USERNAME.

    + *
  • + *
  • + *

    + * PASSWORD_VERIFIER: PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, TIMESTAMP, USERNAME.

    + * + *

    + * PASSWORD_VERIFIER requires DEVICE_KEY when signing in with a remembered device.

    + *
    + *
  • + *
  • + *

    + * NEW_PASSWORD_REQUIRED: NEW_PASSWORD, any other required attributes, USERNAME.

    + *
  • + *
  • + *

    + * SOFTWARE_TOKEN_MFA: USERNAME and SOFTWARE_TOKEN_MFA_CODE are required attributes.

    + *
  • + *
  • + *

    + * DEVICE_SRP_AUTH requires USERNAME, DEVICE_KEY, SRP_A (and SECRET_HASH).

    + *
  • + *
  • + *

    + * DEVICE_PASSWORD_VERIFIER requires everything that PASSWORD_VERIFIER requires, plus DEVICE_KEY.

    + *
  • + *
  • + *

    + * MFA_SETUP requires USERNAME, plus you must use the session value returned by VerifySoftwareToken in the Session parameter.

    + *
  • + *
+ */ + ChallengeResponses?: Record; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for RespondToAuthChallenge calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the RespondToAuthChallenge API action, Amazon Cognito + * invokes any functions that are assigned to the following triggers: post authentication, pre token generation, + * define auth challenge, create auth challenge, and verify auth challenge. When Amazon Cognito + * invokes any of these functions, it passes a JSON payload, which the function receives as input. This payload contains a clientMetadata + * attribute, which provides the data that you assigned to the ClientMetadata parameter in your RespondToAuthChallenge request. In your function code in + * Lambda, you can process the clientMetadata value to enhance your workflow for your specific needs.

+ *

For more information, see Customizing + * User Pool Workflows with Lambda Triggers in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool configuration + * doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

The response to respond to the authentication challenge.

+ */ +export interface RespondToAuthChallengeResponse { + /** + *

The challenge name. For more information, see InitiateAuth.

+ */ + ChallengeName?: ChallengeNameType | string; + /** + *

The session that should be passed both ways in challenge-response calls to the service. If the caller must pass another challenge, they return a session with other challenge parameters. + * This session should be passed as it is to the next RespondToAuthChallenge API call.

+ */ + Session?: string; + /** + *

The challenge parameters. For more information, see InitiateAuth.

+ */ + ChallengeParameters?: Record; + /** + *

The result returned by the server in response to the request to respond to the authentication challenge.

+ */ + AuthenticationResult?: AuthenticationResultType; +} +/** + *

The type used for enabling SMS multi-factor authentication (MFA) at the user level. Phone numbers don't need to be verified to be used for SMS MFA. If an MFA type + * is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking is turned on and the device has been trusted. If you + * would like MFA to be applied selectively based on the assessed risk level of sign-in attempts, deactivate MFA for users and turn on Adaptive Authentication for the user pool.

+ */ +export interface SMSMfaSettingsType { + /** + *

Specifies whether SMS text message MFA is activated. If an MFA type is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking is + * turned on and the device has been trusted.

+ */ + Enabled?: boolean; + /** + *

Specifies whether SMS is the preferred MFA method.

+ */ + PreferredMfa?: boolean; +} +export type SetUserMFAPreferenceCommandInput = SetUserMFAPreferenceRequest; +export interface SetUserMFAPreferenceCommandOutput + extends SetUserMFAPreferenceResponse, + __MetadataBearer {} +export interface SetUserMFAPreferenceRequest { + /** + *

The SMS text message multi-factor authentication (MFA) settings.

+ */ + SMSMfaSettings?: SMSMfaSettingsType; + /** + *

The time-based one-time password software token MFA settings.

+ */ + SoftwareTokenMfaSettings?: SoftwareTokenMfaSettingsType; + /** + *

The access token for the user.

+ */ + AccessToken: string | undefined; +} +export type SetUserMFAPreferenceResponse = Record; +export type SignUpCommandInput = SignUpRequest; +export interface SignUpCommandOutput extends SignUpResponse, __MetadataBearer {} +/** + *

Represents the request to register a user.

+ */ +export interface SignUpRequest { + /** + *

The ID of the client associated with the user pool.

+ */ + ClientId: string | undefined; + /** + *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

+ */ + SecretHash?: string; + /** + *

The user name of the user you want to register.

+ */ + Username: string | undefined; + /** + *

The password of the user you want to register.

+ */ + Password: string | undefined; + /** + *

An array of name-value pairs representing user attributes.

+ *

For custom attributes, you must prepend the custom: prefix to the attribute name.

+ */ + UserAttributes?: AttributeType[]; + /** + *

The validation data in the request to register a user.

+ */ + ValidationData?: AttributeType[]; + /** + *

The Amazon Pinpoint analytics metadata for collecting metrics for SignUp calls.

+ */ + AnalyticsMetadata?: AnalyticsMetadataType; + /** + *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + UserContextData?: UserContextDataType; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the SignUp API action, Amazon Cognito + * invokes any functions that are assigned to the following triggers: pre sign-up, custom message, + * and post confirmation. When Amazon Cognito invokes any of these functions, it passes a JSON payload, which the function + * receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned to the + * ClientMetadata parameter in your SignUp request. In your function code in Lambda, you can process the clientMetadata + * value to enhance your workflow for your specific needs.

+ *

For more information, + * see Customizing User Pool Workflows with Lambda Triggers + * in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

The response from the server for a registration request.

+ */ +export interface SignUpResponse { + /** + *

A response from the server indicating that a user registration has been confirmed.

+ */ + UserConfirmed: boolean | undefined; + /** + *

The code delivery details returned by the server response to the user registration request.

+ */ + CodeDeliveryDetails?: CodeDeliveryDetailsType; + /** + *

The UUID of the authenticated user. This isn't the same as username.

+ */ + UserSub: string | undefined; +} +/** + *

The type used for enabling software token MFA at the user level. If an MFA type is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking + * is turned on and the device has been trusted. If you want MFA to be applied selectively based on the assessed risk level of sign-in attempts, deactivate MFA for users and turn on Adaptive + * Authentication for the user pool.

+ */ +export interface SoftwareTokenMfaSettingsType { + /** + *

Specifies whether software token MFA is activated. If an MFA type is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking is turned + * on and the device has been trusted.

+ */ + Enabled?: boolean; + /** + *

Specifies whether software token MFA is the preferred MFA method.

+ */ + PreferredMfa?: boolean; +} +export type UpdateDeviceStatusCommandInput = UpdateDeviceStatusRequest; +export interface UpdateDeviceStatusCommandOutput + extends UpdateDeviceStatusResponse, + __MetadataBearer {} +/** + *

Represents the request to update the device status.

+ */ +export interface UpdateDeviceStatusRequest { + /** + *

The access token.

+ */ + AccessToken: string | undefined; + /** + *

The device key.

+ */ + DeviceKey: string | undefined; + /** + *

The status of whether a device is remembered.

+ */ + DeviceRememberedStatus?: DeviceRememberedStatusType | string; +} +/** + *

The response to the request to update the device status.

+ */ +export type UpdateDeviceStatusResponse = Record; +export type UpdateUserAttributesCommandInput = UpdateUserAttributesRequest; +export interface UpdateUserAttributesCommandOutput + extends UpdateUserAttributesResponse, + __MetadataBearer {} +/** + *

Represents the request to update user attributes.

+ */ +export interface UpdateUserAttributesRequest { + /** + *

An array of name-value pairs representing user attributes.

+ *

For custom attributes, you must prepend the custom: prefix to the attribute name.

+ */ + UserAttributes: AttributeType[] | undefined; + /** + *

The access token for the request to update user attributes.

+ */ + AccessToken: string | undefined; + /** + *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action initiates.

+ *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the UpdateUserAttributes API action, Amazon Cognito invokes the + * function that is assigned to the custom message trigger. When Amazon Cognito invokes this function, it passes a + * JSON + * payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you + * assigned to the ClientMetadata parameter in your UpdateUserAttributes request. In your function code in Lambda, you can process the clientMetadata + * value to enhance your workflow for your specific needs.

+ *

For more information, see Customizing User Pool + * Workflows with Lambda Triggers in the Amazon Cognito Developer Guide.

+ * + * + *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

+ *
    + *
  • + *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool + * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    + *
  • + *
  • + *

    Validate the ClientMetadata value.

    + *
  • + *
  • + *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    + *
  • + *
+ *
+ */ + ClientMetadata?: Record; +} +/** + *

Represents the response from the server for the request to update user attributes.

+ */ +export interface UpdateUserAttributesResponse { + /** + *

The code delivery details list from the server for the request to update user attributes.

+ */ + CodeDeliveryDetailsList?: CodeDeliveryDetailsType[]; +} +/** + *

Contextual data, such as the user's device fingerprint, IP address, or location, used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ +export interface UserContextDataType { + /** + *

Contextual data, such as the user's device fingerprint, IP address, or location, used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

+ */ + EncodedData?: string; +} +export type VerifySoftwareTokenCommandInput = VerifySoftwareTokenRequest; +export interface VerifySoftwareTokenCommandOutput + extends VerifySoftwareTokenResponse, + __MetadataBearer {} +export interface VerifySoftwareTokenRequest { + /** + *

The access token.

+ */ + AccessToken?: string; + /** + *

The session that should be passed both ways in challenge-response calls to the service.

+ */ + Session?: string; + /** + *

The one- time password computed using the secret code returned by + * AssociateSoftwareToken.

+ */ + UserCode: string | undefined; + /** + *

The friendly device name.

+ */ + FriendlyDeviceName?: string; +} +export interface VerifySoftwareTokenResponse { + /** + *

The status of the verify software token.

+ */ + Status?: VerifySoftwareTokenResponseType | string; + /** + *

The session that should be passed both ways in challenge-response calls to the service.

+ */ + Session?: string; +} +export type VerifyUserAttributeCommandInput = VerifyUserAttributeRequest; +export interface VerifyUserAttributeCommandOutput + extends VerifyUserAttributeResponse, + __MetadataBearer {} +/** + *

Represents the request to verify user attributes.

+ */ +export interface VerifyUserAttributeRequest { + /** + *

The access token of the request to verify user attributes.

+ */ + AccessToken: string | undefined; + /** + *

The attribute name in the request to verify user attributes.

+ */ + AttributeName: string | undefined; + /** + *

The verification code in the request to verify user attributes.

+ */ + Code: string | undefined; +} +/** + *

A container representing the response from the server from the request to verify user attributes.

+ */ +export type VerifyUserAttributeResponse = Record; +export type DeleteUserAttributesCommandInput = DeleteUserAttributesRequest; +export interface DeleteUserAttributesCommandOutput + extends DeleteUserAttributesResponse, + __MetadataBearer {} +/** + *

Represents the request to delete user attributes.

+ */ +export interface DeleteUserAttributesRequest { + /** + *

An array of strings representing the user attribute names you want to delete.

+ *

For custom attributes, you must prependattach the custom: prefix to the + * front of the attribute name.

+ */ + UserAttributeNames: string[] | undefined; + /** + *

A valid access token that Amazon Cognito issued to the user whose attributes you want to + * delete.

+ */ + AccessToken: string | undefined; +} +/** + *

Represents the response from the server to delete user attributes.

+ */ +export type DeleteUserAttributesResponse = Record; +export {}; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts new file mode 100644 index 00000000000..3f3821222b7 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts @@ -0,0 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { EndpointResolverOptions } from '@aws-amplify/core/internals/aws-client-utils'; + +export interface ServiceClientAPIConfig { + endpointResolver(options: EndpointResolverOptions): { url: URL }; +} diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts new file mode 100644 index 00000000000..4f6fc4295d5 --- /dev/null +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts @@ -0,0 +1,2 @@ +export * from './Sdk'; +export * from './ServiceClient'; From a1c11a1518655e49fd906dae2c62ffea30ee9174 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 15 Aug 2024 16:19:06 -0700 Subject: [PATCH 02/11] refactor(auth): use service clients in foundation --- .../cognito/getNewDeviceMetadata.test.ts | 6 +- .../src/foundation/core/parsers/getRegion.ts | 15 +- .../auth/src/foundation/core/parsers/index.ts | 5 +- .../cognito/apis/confirmResetPassword.ts | 15 +- .../providers/cognito/apis/confirmSignIn.ts | 19 +- .../providers/cognito/apis/confirmSignUp.ts | 15 +- .../cognito/apis/confirmUserAttribute.ts | 13 +- .../src/providers/cognito/apis/deleteUser.ts | 15 +- .../cognito/apis/deleteUserAttributes.ts | 13 +- .../providers/cognito/apis/fetchDevices.ts | 17 +- .../cognito/apis/fetchMFAPreference.ts | 13 +- .../providers/cognito/apis/forgetDevice.ts | 15 +- .../apis/internal/fetchUserAttributes.ts | 14 +- .../providers/cognito/apis/rememberDevice.ts | 15 +- .../cognito/apis/resendSignUpCode.ts | 15 +- .../providers/cognito/apis/resetPassword.ts | 16 +- .../apis/sendUserAttributeVerificationCode.ts | 14 +- .../src/providers/cognito/apis/setUpTOTP.ts | 13 +- .../cognito/apis/signInWithCustomAuth.ts | 15 +- .../cognito/apis/signInWithCustomSRPAuth.ts | 15 +- .../providers/cognito/apis/signInWithSRP.ts | 15 +- .../cognito/apis/signInWithUserPassword.ts | 15 +- .../src/providers/cognito/apis/signOut.ts | 30 +- .../auth/src/providers/cognito/apis/signUp.ts | 15 +- .../cognito/apis/updateMFAPreference.ts | 15 +- .../providers/cognito/apis/updatePassword.ts | 13 +- .../cognito/apis/updateUserAttributes.ts | 15 +- .../providers/cognito/apis/verifyTOTPSetup.ts | 13 +- .../credentialsProvider/IdentityIdProvider.ts | 2 +- .../credentialsProvider.ts | 2 +- .../createCognitoUserPoolEndpointResolver.ts | 14 + .../src/providers/cognito/factories/index.ts | 1 + .../cognito/tokenProvider/cacheTokens.ts | 2 +- .../src/providers/cognito/utils/apiHelpers.ts | 3 +- .../clients/CognitoIdentityProvider/base.ts | 103 - .../clients/CognitoIdentityProvider/index.ts | 286 --- .../clients/CognitoIdentityProvider/types.ts | 1712 ----------------- .../clients/CognitoIdentityProvider/utils.ts | 33 - .../providers/cognito/utils/clients/base.ts | 95 - .../cognito/utils/refreshAuthTokens.ts | 20 +- .../providers/cognito/utils/signInHelpers.ts | 190 +- .../providers/cognito/utils/signInStore.ts | 3 +- .../providers/cognito/utils/signUpHelpers.ts | 3 +- packages/aws-amplify/package.json | 2 +- 44 files changed, 462 insertions(+), 2418 deletions(-) create mode 100644 packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts create mode 100644 packages/auth/src/providers/cognito/factories/index.ts delete mode 100644 packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts delete mode 100644 packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts delete mode 100644 packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts delete mode 100644 packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts delete mode 100644 packages/auth/src/providers/cognito/utils/clients/base.ts diff --git a/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts b/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts index cb600ce133e..5f82457a4b9 100644 --- a/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts +++ b/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts @@ -7,7 +7,7 @@ import { AuthError } from '../../../src/errors/AuthError'; import { ConfirmDeviceException } from '../../../src/providers/cognito/types/errors'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { ConfirmDeviceCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -import { getNewDeviceMetatada } from '../../../src/providers/cognito/utils/signInHelpers'; +import { getNewDeviceMetadata } from '../../../src/providers/cognito/utils/signInHelpers'; const userPoolId = 'us-west-2_zzzzz'; Amplify.configure({ @@ -31,7 +31,7 @@ describe('test getNewDeviceMetadata API', () => { }); const mockedDeviceKey = 'mockedDeviceKey'; const mockedGroupDeviceKey = 'mockedGroupDeviceKey'; - const deviceMetadata = await getNewDeviceMetatada( + const deviceMetadata = await getNewDeviceMetadata( userPoolId, { DeviceKey: mockedDeviceKey, @@ -64,7 +64,7 @@ describe('test getNewDeviceMetadata API', () => { }); const mockedDeviceKey = 'mockedDeviceKey'; const mockedGroupDeviceKey = 'mockedGroupDeviceKey'; - const deviceMetadata = await getNewDeviceMetatada( + const deviceMetadata = await getNewDeviceMetadata( userPoolId, { DeviceKey: mockedDeviceKey, diff --git a/packages/auth/src/foundation/core/parsers/getRegion.ts b/packages/auth/src/foundation/core/parsers/getRegion.ts index ff4755cd836..a4d8a5d9a91 100644 --- a/packages/auth/src/foundation/core/parsers/getRegion.ts +++ b/packages/auth/src/foundation/core/parsers/getRegion.ts @@ -1,6 +1,6 @@ import { AuthError } from '../../../errors/AuthError'; -export function getRegion(userPoolId?: string): string { +export function getRegionFromUserPoolId(userPoolId?: string): string { const region = userPoolId?.split('_')[0]; if ( !userPoolId || @@ -15,3 +15,16 @@ export function getRegion(userPoolId?: string): string { return region; } + +export function getRegionFromIdentityPoolId(identityPoolId?: string): string { + if (!identityPoolId || !identityPoolId.includes(':')) { + throw new AuthError({ + name: 'InvalidIdentityPoolIdException', + message: 'Invalid identity pool id provided.', + recoverySuggestion: + 'Make sure a valid identityPoolId is given in the config.', + }); + } + + return identityPoolId.split(':')[0]; +} diff --git a/packages/auth/src/foundation/core/parsers/index.ts b/packages/auth/src/foundation/core/parsers/index.ts index 1fe194e362a..9100093993d 100644 --- a/packages/auth/src/foundation/core/parsers/index.ts +++ b/packages/auth/src/foundation/core/parsers/index.ts @@ -1 +1,4 @@ -export { getRegion } from './getRegion'; +export { + getRegionFromUserPoolId, + getRegionFromIdentityPoolId, +} from './getRegion'; diff --git a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts index 29081093e5c..291bd2df2b8 100644 --- a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts @@ -10,11 +10,12 @@ import { import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { ConfirmResetPasswordInput } from '../types'; -import { confirmForgotPassword } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { ConfirmForgotPasswordException } from '../../cognito/types/errors'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; +import { createConfirmForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; /** * Confirms the new password and verification code to reset the password. * @@ -30,7 +31,7 @@ export async function confirmResetPassword( ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { userPoolClientId, userPoolId } = authConfig; + const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig; const { username, newPassword } = input; assertValidationError( !!username, @@ -53,10 +54,14 @@ export async function confirmResetPassword( userPoolId, userPoolClientId, }); - + const confirmForgotPassword = createConfirmForgotPasswordClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await confirmForgotPassword( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(authConfig.userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmResetPassword), }, { diff --git a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts index 6aad224af30..b8e8475aa42 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts @@ -17,7 +17,7 @@ import { } from '../utils/signInStore'; import { AuthError } from '../../../errors/AuthError'; import { - getNewDeviceMetatada, + getNewDeviceMetadata, getSignInResult, getSignInResultFromError, handleChallengeName, @@ -27,12 +27,12 @@ import { assertValidationError } from '../../../errors/utils/assertValidationErr import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { AuthErrorCodes } from '../../../common/AuthErrorStrings'; import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; +import { tokenOrchestrator } from '../tokenProvider'; +import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; import { ChallengeName, ChallengeParameters, -} from '../utils/clients/CognitoIdentityProvider/types'; -import { tokenOrchestrator } from '../tokenProvider'; -import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; /** * Continues or completes the sign in process when required by the initial call to `signIn`. @@ -113,11 +113,12 @@ export async function confirmSignIn( await cacheCognitoTokens({ username, ...AuthenticationResult, - NewDeviceMetadata: await getNewDeviceMetatada( - authConfig.userPoolId, - AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken, - ), + NewDeviceMetadata: await getNewDeviceMetadata({ + userPoolId: authConfig.userPoolId, + userPoolEndpoint: authConfig.userPoolEndpoint, + newDeviceMetadata: AuthenticationResult.NewDeviceMetadata, + accessToken: AuthenticationResult.AccessToken, + }), signInDetails, }); diff --git a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts index 62fdf93a82c..a5e27decdf3 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts @@ -12,8 +12,7 @@ import { ConfirmSignUpInput, ConfirmSignUpOutput } from '../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { ConfirmSignUpException } from '../types/errors'; -import { confirmSignUp as confirmSignUpClient } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { AutoSignInEventData } from '../types/models'; import { isAutoSignInStarted, @@ -22,6 +21,8 @@ import { } from '../utils/signUpHelpers'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; +import { createConfirmSignUpClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Confirms a new user account. @@ -41,7 +42,7 @@ export async function confirmSignUp( const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { userPoolId, userPoolClientId } = authConfig; + const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig; const clientMetadata = options?.clientMetadata; assertValidationError( !!username, @@ -58,9 +59,15 @@ export async function confirmSignUp( userPoolClientId, }); + const confirmSignUpClient = createConfirmSignUpClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + await confirmSignUpClient( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(authConfig.userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignUp), }, { diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index 951a97f2822..f580df7b50e 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -9,12 +9,13 @@ import { import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { verifyUserAttribute } from '../utils/clients/CognitoIdentityProvider'; import { VerifyUserAttributeException } from '../types/errors'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; import { ConfirmUserAttributeInput } from '../types'; import { getAuthUserAgentValue } from '../../../utils'; +import { createVerifyUserAttributeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Confirms a user attribute with the confirmation code. @@ -30,6 +31,7 @@ export async function confirmUserAttribute( ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { confirmationCode, userAttributeKey } = input; assertValidationError( !!confirmationCode, @@ -37,9 +39,14 @@ export async function confirmUserAttribute( ); const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const verifyUserAttribute = createVerifyUserAttributeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await verifyUserAttribute( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmUserAttribute), }, { diff --git a/packages/auth/src/providers/cognito/apis/deleteUser.ts b/packages/auth/src/providers/cognito/apis/deleteUser.ts index e14bde07f09..49bd8580a61 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUser.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUser.ts @@ -7,12 +7,13 @@ import { assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; -import { deleteUser as serviceDeleteUser } from '../utils/clients/CognitoIdentityProvider'; import { DeleteUserException } from '../types/errors'; import { tokenOrchestrator } from '../tokenProvider'; import { getAuthUserAgentValue } from '../../../utils'; +import { createDeleteUserClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; import { signOut } from './signOut'; @@ -25,13 +26,17 @@ import { signOut } from './signOut'; export async function deleteUser(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession(); assertAuthTokens(tokens); - + const serviceDeleteUser = createDeleteUserClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await serviceDeleteUser( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.DeleteUser), }, { diff --git a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts index 5812b656d60..1a17d837efb 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts @@ -7,12 +7,13 @@ import { assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; -import { deleteUserAttributes as deleteUserAttributesClient } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; import { DeleteUserAttributesInput } from '../types'; import { DeleteUserAttributesException } from '../types/errors'; import { getAuthUserAgentValue } from '../../../utils'; +import { createDeleteUserAttributesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Deletes user attributes. @@ -27,11 +28,17 @@ export async function deleteUserAttributes( const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userAttributeKeys } = input; + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const deleteUserAttributesClient = createDeleteUserAttributesClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await deleteUserAttributesClient( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.DeleteUserAttributes), }, { diff --git a/packages/auth/src/providers/cognito/apis/fetchDevices.ts b/packages/auth/src/providers/cognito/apis/fetchDevices.ts index 29be20e7a78..dd1dc8ebe71 100644 --- a/packages/auth/src/providers/cognito/apis/fetchDevices.ts +++ b/packages/auth/src/providers/cognito/apis/fetchDevices.ts @@ -8,12 +8,13 @@ import { } from '@aws-amplify/core/internals/utils'; import { FetchDevicesOutput } from '../types'; -import { listDevices } from '../utils/clients/CognitoIdentityProvider'; -import { DeviceType } from '../utils/clients/CognitoIdentityProvider/types'; +import { DeviceType } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { assertAuthTokens } from '../utils/types'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { rememberDevice } from '..'; import { getAuthUserAgentValue } from '../../../utils'; +import { createListDevicesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; // Cognito Documentation for max device // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html#API_ListDevices_RequestSyntax @@ -30,13 +31,17 @@ const MAX_DEVICES = 60; export async function fetchDevices(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession(); assertAuthTokens(tokens); - + const listDevices = createListDevicesClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const response = await listDevices( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.FetchDevices), }, { diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index ef42d34f72f..3dd30a1d365 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -10,10 +10,11 @@ import { import { FetchMFAPreferenceOutput } from '../types'; import { getMFAType, getMFATypes } from '../utils/signInHelpers'; import { GetUserException } from '../types/errors'; -import { getUser } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; +import { createGetUserClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Fetches the preferred MFA setting and enabled MFA settings for the user. @@ -26,11 +27,17 @@ import { getAuthUserAgentValue } from '../../../utils'; export async function fetchMFAPreference(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const getUser = createGetUserClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { PreferredMfaSetting, UserMFASettingList } = await getUser( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.FetchMFAPreference), }, { diff --git a/packages/auth/src/providers/cognito/apis/forgetDevice.ts b/packages/auth/src/providers/cognito/apis/forgetDevice.ts index 66dd3488f7b..df17a7262b8 100644 --- a/packages/auth/src/providers/cognito/apis/forgetDevice.ts +++ b/packages/auth/src/providers/cognito/apis/forgetDevice.ts @@ -7,13 +7,14 @@ import { assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; -import { forgetDevice as serviceForgetDevice } from '../utils/clients/CognitoIdentityProvider'; import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { tokenOrchestrator } from '../tokenProvider'; import { ForgetDeviceInput } from '../types'; import { ForgetDeviceException } from '../../cognito/types/errors'; import { getAuthUserAgentValue } from '../../../utils'; +import { createForgetDeviceClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Forget a remembered device while authenticated. @@ -27,17 +28,21 @@ export async function forgetDevice(input?: ForgetDeviceInput): Promise { const { device: { id: externalDeviceKey } = { id: undefined } } = input ?? {}; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession(); assertAuthTokens(tokens); const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(); const currentDeviceKey = deviceMetadata?.deviceKey; if (!externalDeviceKey) assertDeviceMetadata(deviceMetadata); - + const serviceForgetDevice = createForgetDeviceClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await serviceForgetDevice( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ForgetDevice), }, { diff --git a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts index c1e4e9dd008..1a984ae00bd 100644 --- a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts @@ -8,26 +8,32 @@ import { fetchAuthSession, } from '@aws-amplify/core/internals/utils'; -import { getUser } from '../../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../../foundation/core/parsers'; import { assertAuthTokens } from '../../utils/types'; import { FetchUserAttributesOutput } from '../../types'; import { toAuthUserAttribute } from '../../utils/apiHelpers'; import { getAuthUserAgentValue } from '../../../../utils'; +import { createGetUserClient } from '../../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../factories'; export const fetchUserAttributes = async ( amplify: AmplifyClassV6, ): Promise => { const authConfig = amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession(amplify, { forceRefresh: false, }); assertAuthTokens(tokens); - + const getUser = createGetUserClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { UserAttributes } = await getUser( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.FetchUserAttributes), }, { diff --git a/packages/auth/src/providers/cognito/apis/rememberDevice.ts b/packages/auth/src/providers/cognito/apis/rememberDevice.ts index 218b7b533e6..1fa4a5912da 100644 --- a/packages/auth/src/providers/cognito/apis/rememberDevice.ts +++ b/packages/auth/src/providers/cognito/apis/rememberDevice.ts @@ -7,12 +7,13 @@ import { assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; -import { updateDeviceStatus } from '../utils/clients/CognitoIdentityProvider'; import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { tokenOrchestrator } from '../tokenProvider'; import { UpdateDeviceStatusException } from '../../cognito/types/errors'; import { getAuthUserAgentValue } from '../../../utils'; +import { createUpdateDeviceStatusClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Marks device as remembered while authenticated. @@ -24,16 +25,20 @@ import { getAuthUserAgentValue } from '../../../utils'; export async function rememberDevice(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession(); assertAuthTokens(tokens); const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(); assertDeviceMetadata(deviceMetadata); - + const updateDeviceStatus = createUpdateDeviceStatusClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await updateDeviceStatus( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.RememberDevice), }, { diff --git a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts index 99ef3996f52..43b324a90ed 100644 --- a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts +++ b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts @@ -12,11 +12,12 @@ import { AuthDeliveryMedium } from '../../../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { ResendSignUpCodeInput, ResendSignUpCodeOutput } from '../types'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; -import { resendConfirmationCode } from '../utils/clients/CognitoIdentityProvider'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; import { ResendConfirmationException } from '../types/errors'; +import { createResendConfirmationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Resend the confirmation code while signing up @@ -37,7 +38,7 @@ export async function resendSignUpCode( ); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { userPoolClientId, userPoolId } = authConfig; + const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig; const clientMetadata = input.options?.clientMetadata; const UserContextData = getUserContextData({ @@ -45,10 +46,14 @@ export async function resendSignUpCode( userPoolId, userPoolClientId, }); - + const resendConfirmationCode = createResendConfirmationCodeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { CodeDeliveryDetails } = await resendConfirmationCode( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(authConfig.userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ResendSignUpCode), }, { diff --git a/packages/auth/src/providers/cognito/apis/resetPassword.ts b/packages/auth/src/providers/cognito/apis/resetPassword.ts index 273a77d413d..9190329e778 100644 --- a/packages/auth/src/providers/cognito/apis/resetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/resetPassword.ts @@ -12,11 +12,12 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthDeliveryMedium } from '../../../types'; import { ResetPasswordInput, ResetPasswordOutput } from '../types'; -import { forgotPassword } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { ForgotPasswordException } from '../../cognito/types/errors'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; +import { createForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Resets a user's password. @@ -39,7 +40,7 @@ export async function resetPassword( ); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { userPoolClientId, userPoolId } = authConfig; + const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig; const clientMetadata = input.options?.clientMetadata; const UserContextData = getUserContextData({ @@ -48,15 +49,20 @@ export async function resetPassword( userPoolClientId, }); + const forgotPassword = createForgotPasswordClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const res = await forgotPassword( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ResetPassword), }, { Username: username, ClientMetadata: clientMetadata, - ClientId: authConfig.userPoolClientId, + ClientId: userPoolClientId, UserContextData, }, ); diff --git a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts index 55e5a8b5a84..7ad297818d8 100644 --- a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts +++ b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts @@ -13,11 +13,12 @@ import { SendUserAttributeVerificationCodeInput, SendUserAttributeVerificationCodeOutput, } from '../types'; -import { getUserAttributeVerificationCode } from '../utils/clients/CognitoIdentityProvider'; import { assertAuthTokens } from '../utils/types'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { GetUserAttributeVerificationException } from '../types/errors'; import { getAuthUserAgentValue } from '../../../utils'; +import { createGetUserAttributeVerificationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Resends user's confirmation code when updating attributes while authenticated. @@ -34,11 +35,18 @@ export const sendUserAttributeVerificationCode = async ( const authConfig = Amplify.getConfig().Auth?.Cognito; const clientMetadata = options?.clientMetadata; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const getUserAttributeVerificationCode = + createGetUserAttributeVerificationCodeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { CodeDeliveryDetails } = await getUserAttributeVerificationCode( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue( AuthAction.SendUserAttributeVerificationCode, ), diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index e99b8618995..d5876cad54e 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -14,10 +14,11 @@ import { } from '../types/errors'; import { SetUpTOTPOutput } from '../types'; import { getTOTPSetupDetails } from '../utils/signInHelpers'; -import { associateSoftwareToken } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; +import { createAssociateSoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Sets up TOTP for the user. @@ -30,12 +31,18 @@ import { getAuthUserAgentValue } from '../../../utils'; export async function setUpTOTP(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); const username = tokens.idToken?.payload['cognito:username'] ?? ''; + const associateSoftwareToken = createAssociateSoftwareTokenClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { SecretCode } = await associateSoftwareToken( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SetUpTOTP), }, { diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts index e55e3f0a50d..a666fba0acb 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts @@ -9,7 +9,7 @@ import { assertValidationError } from '../../../errors/utils/assertValidationErr import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { getActiveSignInUsername, - getNewDeviceMetatada, + getNewDeviceMetadata, getSignInResult, getSignInResultFromError, handleCustomAuthFlowWithoutSRP, @@ -29,7 +29,7 @@ import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; import { ChallengeName, ChallengeParameters, -} from '../utils/clients/CognitoIdentityProvider/types'; +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { tokenOrchestrator } from '../tokenProvider'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; @@ -89,11 +89,12 @@ export async function signInWithCustomAuth( await cacheCognitoTokens({ username: activeUsername, ...AuthenticationResult, - NewDeviceMetadata: await getNewDeviceMetatada( - authConfig.userPoolId, - AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken, - ), + NewDeviceMetadata: await getNewDeviceMetadata({ + userPoolId: authConfig.userPoolId, + userPoolEndpoint: authConfig.userPoolEndpoint, + newDeviceMetadata: AuthenticationResult.NewDeviceMetadata, + accessToken: AuthenticationResult.AccessToken, + }), signInDetails, }); diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts index a67fa9f861c..a22f98b3804 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts @@ -9,7 +9,7 @@ import { assertValidationError } from '../../../errors/utils/assertValidationErr import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { getActiveSignInUsername, - getNewDeviceMetatada, + getNewDeviceMetadata, getSignInResult, getSignInResultFromError, handleCustomSRPAuthFlow, @@ -31,7 +31,7 @@ import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; import { ChallengeName, ChallengeParameters, -} from '../utils/clients/CognitoIdentityProvider/types'; +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { tokenOrchestrator } from '../tokenProvider'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; @@ -92,11 +92,12 @@ export async function signInWithCustomSRPAuth( await cacheCognitoTokens({ username: activeUsername, ...AuthenticationResult, - NewDeviceMetadata: await getNewDeviceMetatada( - authConfig.userPoolId, - AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken, - ), + NewDeviceMetadata: await getNewDeviceMetadata({ + userPoolId: authConfig.userPoolId, + userPoolEndpoint: authConfig.userPoolEndpoint, + newDeviceMetadata: AuthenticationResult.NewDeviceMetadata, + accessToken: AuthenticationResult.AccessToken, + }), signInDetails, }); cleanActiveSignInState(); diff --git a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts index 32f0ca11b99..9bb8d4deca7 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts @@ -10,14 +10,14 @@ import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { ChallengeName, ChallengeParameters, -} from '../utils/clients/CognitoIdentityProvider/types'; +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { InitiateAuthException, RespondToAuthChallengeException, } from '../types/errors'; import { getActiveSignInUsername, - getNewDeviceMetatada, + getNewDeviceMetadata, getSignInResult, getSignInResultFromError, handleUserSRPAuthFlow, @@ -93,11 +93,12 @@ export async function signInWithSRP( await cacheCognitoTokens({ username: activeUsername, ...AuthenticationResult, - NewDeviceMetadata: await getNewDeviceMetatada( - authConfig.userPoolId, - AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken, - ), + NewDeviceMetadata: await getNewDeviceMetadata({ + userPoolId: authConfig.userPoolId, + userPoolEndpoint: authConfig.userPoolEndpoint, + newDeviceMetadata: AuthenticationResult.NewDeviceMetadata, + accessToken: AuthenticationResult.AccessToken, + }), signInDetails, }); diff --git a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts index e1de730cb1c..071f54f8313 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts @@ -10,10 +10,10 @@ import { assertValidationError } from '../../../errors/utils/assertValidationErr import { ChallengeName, ChallengeParameters, -} from '../utils/clients/CognitoIdentityProvider/types'; +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { getActiveSignInUsername, - getNewDeviceMetatada, + getNewDeviceMetadata, getSignInResult, getSignInResultFromError, handleUserPasswordAuthFlow, @@ -87,11 +87,12 @@ export async function signInWithUserPassword( await cacheCognitoTokens({ ...AuthenticationResult, username: activeUsername, - NewDeviceMetadata: await getNewDeviceMetatada( - authConfig.userPoolId, - AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken, - ), + NewDeviceMetadata: await getNewDeviceMetadata({ + userPoolId: authConfig.userPoolId, + userPoolEndpoint: authConfig.userPoolEndpoint, + newDeviceMetadata: AuthenticationResult.NewDeviceMetadata, + accessToken: AuthenticationResult.AccessToken, + }), signInDetails, }); cleanActiveSignInState(); diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index 65be0162927..132e57ef54e 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -20,11 +20,7 @@ import { import { getAuthUserAgentValue } from '../../../utils'; import { SignOutInput } from '../types'; import { tokenOrchestrator } from '../tokenProvider'; -import { - globalSignOut as globalSignOutClient, - revokeToken, -} from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens, assertAuthTokensWithRefreshToken, @@ -33,6 +29,11 @@ import { handleOAuthSignOut } from '../utils/oauth'; import { DefaultOAuthStore } from '../utils/signInWithRedirectStore'; import { AuthError } from '../../../errors/AuthError'; import { OAUTH_SIGNOUT_EXCEPTION } from '../../../errors/constants'; +import { + createGlobalSignOutClient, + createRevokeTokenClient, +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; const logger = new ConsoleLogger('Auth'); @@ -83,16 +84,23 @@ export async function signOut(input?: SignOutInput): Promise { async function clientSignOut(cognitoConfig: CognitoUserPoolConfig) { try { + const { userPoolEndpoint, userPoolId, userPoolClientId } = cognitoConfig; const authTokens = await tokenOrchestrator.getTokenStore().loadTokens(); assertAuthTokensWithRefreshToken(authTokens); if (isSessionRevocable(authTokens.accessToken)) { + const revokeToken = createRevokeTokenClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + await revokeToken( { - region: getRegion(cognitoConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignOut), }, { - ClientId: cognitoConfig.userPoolClientId, + ClientId: userPoolClientId, Token: authTokens.refreshToken, }, ); @@ -107,11 +115,17 @@ async function clientSignOut(cognitoConfig: CognitoUserPoolConfig) { async function globalSignOut(cognitoConfig: CognitoUserPoolConfig) { try { + const { userPoolEndpoint, userPoolId } = cognitoConfig; const authTokens = await tokenOrchestrator.getTokenStore().loadTokens(); assertAuthTokens(authTokens); + const globalSignOutClient = createGlobalSignOutClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await globalSignOutClient( { - region: getRegion(cognitoConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignOut), }, { diff --git a/packages/auth/src/providers/cognito/apis/signUp.ts b/packages/auth/src/providers/cognito/apis/signUp.ts index ef9aef32fa2..d33aedb7c6d 100644 --- a/packages/auth/src/providers/cognito/apis/signUp.ts +++ b/packages/auth/src/providers/cognito/apis/signUp.ts @@ -10,11 +10,10 @@ import { import { AuthDeliveryMedium } from '../../../types'; import { SignInInput, SignUpInput, SignUpOutput } from '../types'; -import { signUp as signUpClient } from '../utils/clients/CognitoIdentityProvider'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { SignUpException } from '../types/errors'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { toAttributeType } from '../utils/apiHelpers'; import { autoSignInUserConfirmed, @@ -27,6 +26,8 @@ import { } from '../utils/signUpHelpers'; import { getUserContextData } from '../utils/userContextData'; import { getAuthUserAgentValue } from '../../../utils'; +import { createSignUpClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; import { setAutoSignIn } from './autoSignIn'; @@ -72,11 +73,15 @@ export async function signUp(input: SignUpInput): Promise { setAutoSignInStarted(true); } - const { userPoolId, userPoolClientId } = authConfig; - + const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig; + const signUpClient = createSignUpClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const clientOutput = await signUpClient( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignUp), }, { diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index 790cc82f8bd..9bef999800e 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -10,11 +10,12 @@ import { import { UpdateMFAPreferenceInput } from '../types'; import { SetUserMFAPreferenceException } from '../types/errors'; import { MFAPreference } from '../types/models'; -import { setUserMFAPreference } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; -import { CognitoMFASettings } from '../utils/clients/CognitoIdentityProvider/types'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { CognitoMFASettings } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; +import { createSetUserMFAPreferenceClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Updates the MFA preference of the user. @@ -29,11 +30,17 @@ export async function updateMFAPreference( const { sms, totp } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const setUserMFAPreference = createSetUserMFAPreferenceClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await setUserMFAPreference( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.UpdateMFAPreference), }, { diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index 0f83fc9f1df..b3f2e5c988c 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -10,11 +10,12 @@ import { import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { UpdatePasswordInput } from '../types'; -import { changePassword } from '../utils/clients/CognitoIdentityProvider'; import { ChangePasswordException } from '../../cognito/types/errors'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; +import { createChangePasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Updates user's password while authenticated. @@ -29,6 +30,7 @@ export async function updatePassword( ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { oldPassword, newPassword } = input; assertValidationError( !!oldPassword, @@ -41,9 +43,14 @@ export async function updatePassword( ); const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const changePassword = createChangePasswordClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await changePassword( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.UpdatePassword), }, { diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index b0e6cc7f3f7..d99de8988d0 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -16,13 +16,14 @@ import { UpdateUserAttributesInput, UpdateUserAttributesOutput, } from '../types'; -import { updateUserAttributes as updateUserAttributesClient } from '../utils/clients/CognitoIdentityProvider'; import { assertAuthTokens } from '../utils/types'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { toAttributeType } from '../utils/apiHelpers'; -import { CodeDeliveryDetailsType } from '../utils/clients/CognitoIdentityProvider/types'; +import { CodeDeliveryDetailsType } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { UpdateUserAttributesException } from '../types/errors'; import { getAuthUserAgentValue } from '../../../utils'; +import { createUpdateUserAttributesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Updates user's attributes while authenticated. @@ -39,11 +40,17 @@ export const updateUserAttributes = async ( const authConfig = Amplify.getConfig().Auth?.Cognito; const clientMetadata = options?.clientMetadata; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const updateUserAttributesClient = createUpdateUserAttributesClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { CodeDeliveryDetailsList } = await updateUserAttributesClient( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.UpdateUserAttributes), }, { diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index 66c68fe9690..1a5aac7a916 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -10,11 +10,12 @@ import { import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { VerifyTOTPSetupInput } from '../types'; -import { verifySoftwareToken } from '../utils/clients/CognitoIdentityProvider'; import { VerifySoftwareTokenException } from '../types/errors'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; +import { createVerifySoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; /** * Verifies an OTP code retrieved from an associated authentication app. @@ -31,6 +32,7 @@ export async function verifyTOTPSetup( ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); + const { userPoolEndpoint, userPoolId } = authConfig; const { code, options } = input; assertValidationError( !!code, @@ -38,9 +40,14 @@ export async function verifyTOTPSetup( ); const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); + const verifySoftwareToken = createVerifySoftwareTokenClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await verifySoftwareToken( { - region: getRegion(authConfig.userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.VerifyTOTPSetup), }, { diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts index 4a8614a3db0..f96082fcde5 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts @@ -5,7 +5,7 @@ import { AuthTokens, ConsoleLogger, Identity, getId } from '@aws-amplify/core'; import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../errors/AuthError'; -import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromIdentityPoolId } from '../../../foundation/core/parsers'; import { GetIdException } from '../types/errors'; import { IdentityIdStore } from './types'; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index fd02d349513..0e42643fd76 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -15,7 +15,7 @@ import { } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../errors/AuthError'; -import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromIdentityPoolId } from '../../../foundation/core/parsers'; import { assertIdTokenInAuthTokens } from '../utils/types'; import { IdentityIdStore } from './types'; diff --git a/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts b/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts new file mode 100644 index 00000000000..6e190a1ef2b --- /dev/null +++ b/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts @@ -0,0 +1,14 @@ +import { EndpointResolverOptions } from '@aws-amplify/core/internals/aws-client-utils'; +import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; + +import { cognitoUserPoolEndpointResolver } from '../../../foundation/core/cognitoUserPoolEndpointResolver'; + +export const createCognitoUserPoolEndpointResolver = + ({ endpointOverride }: { endpointOverride: string | undefined }) => + (input: EndpointResolverOptions): { url: URL } => { + if (endpointOverride) { + return { url: new AmplifyUrl(endpointOverride) }; + } + + return cognitoUserPoolEndpointResolver(input); + }; diff --git a/packages/auth/src/providers/cognito/factories/index.ts b/packages/auth/src/providers/cognito/factories/index.ts new file mode 100644 index 00000000000..be3e983fc51 --- /dev/null +++ b/packages/auth/src/providers/cognito/factories/index.ts @@ -0,0 +1 @@ +export { createCognitoUserPoolEndpointResolver } from './createCognitoUserPoolEndpointResolver'; diff --git a/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts b/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts index 198ec6c4283..0be44aeb697 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts @@ -3,7 +3,7 @@ import { AmplifyError, decodeJWT } from '@aws-amplify/core/internals/utils'; import { CognitoAuthSignInDetails } from '../types'; -import { AuthenticationResultType } from '../utils/clients/CognitoIdentityProvider/types'; +import { AuthenticationResultType } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { tokenOrchestrator } from './tokenProvider'; import { CognitoAuthTokens, DeviceMetadata } from './types'; diff --git a/packages/auth/src/providers/cognito/utils/apiHelpers.ts b/packages/auth/src/providers/cognito/utils/apiHelpers.ts index 5ddd544513c..70da22165a5 100644 --- a/packages/auth/src/providers/cognito/utils/apiHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/apiHelpers.ts @@ -2,8 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { AuthUserAttributes } from '../../../types'; - -import { AttributeType } from './clients/CognitoIdentityProvider/types'; +import { AttributeType } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; /** * Transforms a user attributes object into an array of AttributeType objects. diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts deleted file mode 100644 index cff58009b87..00000000000 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { Amplify } from '@aws-amplify/core'; -import { - Endpoint, - EndpointResolverOptions, - Headers, - HttpRequest, - HttpResponse, - Middleware, - getDnsSuffix, - getRetryDecider, - jitteredBackoff, - parseJsonError, - unauthenticatedHandler, -} from '@aws-amplify/core/internals/aws-client-utils'; -import { - AmplifyUrl, - getAmplifyUserAgent, -} from '@aws-amplify/core/internals/utils'; -import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers'; - -/** - * The service name used to sign requests if the API requires authentication. - */ -const SERVICE_NAME = 'cognito-idp'; - -/** - * The endpoint resolver function that returns the endpoint URL for a given region. - */ -const endpointResolver = ({ region }: EndpointResolverOptions) => { - const authConfig = Amplify.getConfig().Auth?.Cognito; - const customURL = authConfig?.userPoolEndpoint; - const defaultURL = new AmplifyUrl( - `https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`, - ); - - return { - url: customURL ? new AmplifyUrl(customURL) : defaultURL, - }; -}; - -/** - * A Cognito Identity-specific middleware that disables caching for all requests. - */ -const disableCacheMiddlewareFactory: Middleware< - HttpRequest, - HttpResponse, - Record -> = () => (next, _) => - async function disableCacheMiddleware(request) { - request.headers['cache-control'] = 'no-store'; - - return next(request); - }; - -/** - * A Cognito Identity-specific transfer handler that does NOT sign requests, and - * disables caching. - * - * @internal - */ -export const cognitoUserPoolTransferHandler = composeTransferHandler< - [Parameters[0]], - HttpRequest, - HttpResponse, - typeof unauthenticatedHandler ->(unauthenticatedHandler, [disableCacheMiddlewareFactory]); - -/** - * @internal - */ -export const defaultConfig = { - service: SERVICE_NAME, - endpointResolver, - retryDecider: getRetryDecider(parseJsonError), - computeDelay: jitteredBackoff, - userAgentValue: getAmplifyUserAgent(), - cache: 'no-store', -}; - -/** - * @internal - */ -export const getSharedHeaders = (operation: string): Headers => ({ - 'content-type': 'application/x-amz-json-1.1', - 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}`, -}); - -/** - * @internal - */ -export const buildHttpRpcRequest = ( - { url }: Endpoint, - headers: Headers, - body: string, -): HttpRequest => ({ - headers, - url, - body, - method: 'POST', -}); diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts deleted file mode 100644 index 4ea8c01b599..00000000000 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { - Endpoint, - HttpRequest, - HttpResponse, - parseJsonBody, - parseJsonError, -} from '@aws-amplify/core/internals/aws-client-utils'; - -import { assertServiceError } from '../../../../../errors/utils/assertServiceError'; -import { AuthError } from '../../../../../errors/AuthError'; - -import { - buildHttpRpcRequest, - cognitoUserPoolTransferHandler, - defaultConfig, - getSharedHeaders, -} from './base'; -import type { - AssociateSoftwareTokenCommandInput as AssociateSoftwareTokenInput, - AssociateSoftwareTokenCommandOutput as AssociateSoftwareTokenOutput, - ChangePasswordCommandInput as ChangePasswordInput, - ChangePasswordCommandOutput as ChangePasswordOutput, - ConfirmDeviceCommandInput as ConfirmDeviceInput, - ConfirmDeviceCommandOutput as ConfirmDeviceOutput, - ConfirmForgotPasswordCommandInput as ConfirmForgotPasswordInput, - ConfirmForgotPasswordCommandOutput as ConfirmForgotPasswordOutput, - ConfirmSignUpCommandInput as ConfirmSignUpInput, - ConfirmSignUpCommandOutput as ConfirmSignUpOutput, - DeleteUserAttributesCommandInput as DeleteUserAttributesInput, - DeleteUserAttributesCommandOutput as DeleteUserAttributesOutput, - DeleteUserCommandInput as DeleteUserInput, - DeleteUserCommandOutput as DeleteUserOutput, - ForgetDeviceCommandInput as ForgetDeviceInput, - ForgetDeviceCommandOutput as ForgetDeviceOutput, - ForgotPasswordCommandInput as ForgotPasswordInput, - ForgotPasswordCommandOutput as ForgotPasswordOutput, - GetUserAttributeVerificationCodeCommandInput as GetUserAttributeVerificationCodeInput, - GetUserAttributeVerificationCodeCommandOutput as GetUserAttributeVerificationCodeOutput, - GetUserCommandInput as GetUserInput, - GetUserCommandOutput as GetUserOutput, - GlobalSignOutCommandInput as GlobalSignOutInput, - GlobalSignOutCommandOutput as GlobalSignOutOutput, - InitiateAuthCommandInput as InitiateAuthInput, - InitiateAuthCommandOutput as InitiateAuthOutput, - ListDevicesCommandInput as ListDevicesInput, - ListDevicesCommandOutput as ListDevicesOutput, - ResendConfirmationCodeCommandInput as ResendConfirmationCodeInput, - ResendConfirmationCodeCommandOutput as ResendConfirmationCodeOutput, - RespondToAuthChallengeCommandInput as RespondToAuthChallengeInput, - RespondToAuthChallengeCommandOutput as RespondToAuthChallengeOutput, - SetUserMFAPreferenceCommandInput as SetUserMFAPreferenceInput, - SetUserMFAPreferenceCommandOutput as SetUserMFAPreferenceOutput, - SignUpCommandInput as SignUpInput, - SignUpCommandOutput as SignUpOutput, - UpdateDeviceStatusCommandInput as UpdateDeviceStatusInput, - UpdateDeviceStatusCommandOutput as UpdateDeviceStatusOutput, - UpdateUserAttributesCommandInput as UpdateUserAttributesInput, - UpdateUserAttributesCommandOutput as UpdateUserAttributesOutput, - VerifySoftwareTokenCommandInput as VerifySoftwareTokenInput, - VerifySoftwareTokenCommandOutput as VerifySoftwareTokenOutput, - VerifyUserAttributeCommandInput as VerifyUserAttributeInput, - VerifyUserAttributeCommandOutput as VerifyUserAttributeOutput, -} from './types'; - -interface RevokeTokenInput { - Token: string; - ClientId: string; -} - -type RevokeTokenOutput = Record; - -type ClientOperation = - | 'SignUp' - | 'ConfirmSignUp' - | 'ForgotPassword' - | 'ConfirmForgotPassword' - | 'InitiateAuth' - | 'RespondToAuthChallenge' - | 'ResendConfirmationCode' - | 'VerifySoftwareToken' - | 'AssociateSoftwareToken' - | 'SetUserMFAPreference' - | 'GetUser' - | 'ChangePassword' - | 'ConfirmDevice' - | 'ForgetDevice' - | 'DeleteUser' - | 'GetUserAttributeVerificationCode' - | 'GlobalSignOut' - | 'UpdateUserAttributes' - | 'VerifyUserAttribute' - | 'DeleteUserAttributes' - | 'UpdateDeviceStatus' - | 'ListDevices' - | 'RevokeToken'; - -const buildUserPoolSerializer = - (operation: ClientOperation) => - (input: Input, endpoint: Endpoint): HttpRequest => { - const headers = getSharedHeaders(operation); - const body = JSON.stringify(input); - - return buildHttpRpcRequest(endpoint, headers, body); - }; - -const buildUserPoolDeserializer = (): (( - response: HttpResponse, -) => Promise) => { - return async (response: HttpResponse): Promise => { - if (response.statusCode >= 300) { - const error = await parseJsonError(response); - assertServiceError(error); - throw new AuthError({ name: error.name, message: error.message }); - } else { - const body = await parseJsonBody(response); - - return body; - } - }; -}; - -const handleEmptyResponseDeserializer = (): (( - response: HttpResponse, -) => Promise) => { - return async (response: HttpResponse): Promise => { - if (response.statusCode >= 300) { - const error = await parseJsonError(response); - assertServiceError(error); - throw new AuthError({ name: error.name, message: error.message }); - } else { - return undefined as any; - } - }; -}; - -export const initiateAuth = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('InitiateAuth'), - buildUserPoolDeserializer(), - defaultConfig, -); - -export const revokeToken = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('RevokeToken'), - buildUserPoolDeserializer(), - defaultConfig, -); - -export const signUp = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('SignUp'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const confirmSignUp = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ConfirmSignUp'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const forgotPassword = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ForgotPassword'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const confirmForgotPassword = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ConfirmForgotPassword'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const respondToAuthChallenge = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer( - 'RespondToAuthChallenge', - ), - buildUserPoolDeserializer(), - defaultConfig, -); -export const resendConfirmationCode = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer( - 'ResendConfirmationCode', - ), - buildUserPoolDeserializer(), - defaultConfig, -); -export const verifySoftwareToken = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('VerifySoftwareToken'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const associateSoftwareToken = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer( - 'AssociateSoftwareToken', - ), - buildUserPoolDeserializer(), - defaultConfig, -); -export const setUserMFAPreference = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('SetUserMFAPreference'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const getUser = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('GetUser'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const changePassword = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ChangePassword'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const confirmDevice = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ConfirmDevice'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const forgetDevice = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ForgetDevice'), - handleEmptyResponseDeserializer(), - defaultConfig, -); -export const deleteUser = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('DeleteUser'), - handleEmptyResponseDeserializer(), - defaultConfig, -); -export const getUserAttributeVerificationCode = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer( - 'GetUserAttributeVerificationCode', - ), - buildUserPoolDeserializer(), - defaultConfig, -); -export const globalSignOut = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('GlobalSignOut'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const updateUserAttributes = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('UpdateUserAttributes'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const verifyUserAttribute = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('VerifyUserAttribute'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const updateDeviceStatus = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('UpdateDeviceStatus'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const listDevices = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ListDevices'), - buildUserPoolDeserializer(), - defaultConfig, -); -export const deleteUserAttributes = composeServiceApi( - cognitoUserPoolTransferHandler, - buildUserPoolSerializer('DeleteUserAttributes'), - buildUserPoolDeserializer(), - defaultConfig, -); diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts deleted file mode 100644 index c08589ad448..00000000000 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts +++ /dev/null @@ -1,1712 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// Generated by scripts/dts-bundler/README.md - -import { MetadataBearer as __MetadataBearer } from '@aws-sdk/types'; - -export type ChallengeName = - | 'SMS_MFA' - | 'SOFTWARE_TOKEN_MFA' - | 'SELECT_MFA_TYPE' - | 'MFA_SETUP' - | 'PASSWORD_VERIFIER' - | 'CUSTOM_CHALLENGE' - | 'DEVICE_SRP_AUTH' - | 'DEVICE_PASSWORD_VERIFIER' - | 'ADMIN_NO_SRP_AUTH' - | 'NEW_PASSWORD_REQUIRED'; - -export type ChallengeParameters = { - CODE_DELIVERY_DESTINATION?: string; - CODE_DELIVERY_DELIVERY_MEDIUM?: string; - requiredAttributes?: string; - USER_ID_FOR_SRP?: string; - SECRET_BLOCK?: string; - PASSWORD_CLAIM_SIGNATURE?: string; - MFAS_CAN_CHOOSE?: string; - MFAS_CAN_SETUP?: string; -} & Record; - -export type CognitoMFAType = 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; - -export interface CognitoMFASettings { - Enabled?: boolean; - PreferredMfa?: boolean; -} - -declare enum AuthFlowType { - ADMIN_NO_SRP_AUTH = 'ADMIN_NO_SRP_AUTH', - ADMIN_USER_PASSWORD_AUTH = 'ADMIN_USER_PASSWORD_AUTH', - CUSTOM_AUTH = 'CUSTOM_AUTH', - REFRESH_TOKEN = 'REFRESH_TOKEN', - REFRESH_TOKEN_AUTH = 'REFRESH_TOKEN_AUTH', - USER_PASSWORD_AUTH = 'USER_PASSWORD_AUTH', - USER_SRP_AUTH = 'USER_SRP_AUTH', -} -declare enum ChallengeNameType { - ADMIN_NO_SRP_AUTH = 'ADMIN_NO_SRP_AUTH', - CUSTOM_CHALLENGE = 'CUSTOM_CHALLENGE', - DEVICE_PASSWORD_VERIFIER = 'DEVICE_PASSWORD_VERIFIER', - DEVICE_SRP_AUTH = 'DEVICE_SRP_AUTH', - MFA_SETUP = 'MFA_SETUP', - NEW_PASSWORD_REQUIRED = 'NEW_PASSWORD_REQUIRED', - PASSWORD_VERIFIER = 'PASSWORD_VERIFIER', - SELECT_MFA_TYPE = 'SELECT_MFA_TYPE', - SMS_MFA = 'SMS_MFA', - SOFTWARE_TOKEN_MFA = 'SOFTWARE_TOKEN_MFA', -} -declare enum DeliveryMediumType { - EMAIL = 'EMAIL', - SMS = 'SMS', -} -declare enum DeviceRememberedStatusType { - NOT_REMEMBERED = 'not_remembered', - REMEMBERED = 'remembered', -} -declare enum VerifySoftwareTokenResponseType { - ERROR = 'ERROR', - SUCCESS = 'SUCCESS', -} -declare namespace AnalyticsMetadataType { - /** - * @internal - */ - const filterSensitiveLog: (obj: AnalyticsMetadataType) => any; -} -declare namespace AssociateSoftwareTokenRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: AssociateSoftwareTokenRequest) => any; -} -declare namespace AssociateSoftwareTokenResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: AssociateSoftwareTokenResponse) => any; -} -declare namespace AttributeType { - /** - * @internal - */ - const filterSensitiveLog: (obj: AttributeType) => any; -} -declare namespace AuthenticationResultType { - /** - * @internal - */ - const filterSensitiveLog: (obj: AuthenticationResultType) => any; -} -declare namespace ChangePasswordRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ChangePasswordRequest) => any; -} -declare namespace ChangePasswordResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ChangePasswordResponse) => any; -} -declare namespace CodeDeliveryDetailsType { - /** - * @internal - */ - const filterSensitiveLog: (obj: CodeDeliveryDetailsType) => any; -} -declare namespace ConfirmDeviceRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ConfirmDeviceRequest) => any; -} -declare namespace ConfirmDeviceResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ConfirmDeviceResponse) => any; -} -declare namespace ConfirmForgotPasswordRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ConfirmForgotPasswordRequest) => any; -} -declare namespace ConfirmForgotPasswordResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ConfirmForgotPasswordResponse) => any; -} -declare namespace ConfirmSignUpRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ConfirmSignUpRequest) => any; -} -declare namespace ConfirmSignUpResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ConfirmSignUpResponse) => any; -} -declare namespace DeleteUserRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: DeleteUserRequest) => any; -} -declare namespace DeleteUserResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: DeleteUserResponse) => any; -} -declare namespace DeviceSecretVerifierConfigType { - /** - * @internal - */ - const filterSensitiveLog: (obj: DeviceSecretVerifierConfigType) => any; -} -declare namespace DeviceType { - /** - * @internal - */ - const filterSensitiveLog: (obj: DeviceType) => any; -} -declare namespace ForgetDeviceRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ForgetDeviceRequest) => any; -} -declare namespace ForgotPasswordRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ForgotPasswordRequest) => any; -} -declare namespace ForgotPasswordResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ForgotPasswordResponse) => any; -} -declare namespace GetUserAttributeVerificationCodeRequest { - /** - * @internal - */ - const filterSensitiveLog: ( - obj: GetUserAttributeVerificationCodeRequest, - ) => any; -} -declare namespace GetUserAttributeVerificationCodeResponse { - /** - * @internal - */ - const filterSensitiveLog: ( - obj: GetUserAttributeVerificationCodeResponse, - ) => any; -} -declare namespace GetUserRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: GetUserRequest) => any; -} -declare namespace GetUserResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: GetUserResponse) => any; -} -declare namespace GlobalSignOutRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: GlobalSignOutRequest) => any; -} -declare namespace GlobalSignOutResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: GlobalSignOutResponse) => any; -} -declare namespace InitiateAuthRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: InitiateAuthRequest) => any; -} -declare namespace InitiateAuthResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: InitiateAuthResponse) => any; -} -declare namespace ListDevicesRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ListDevicesRequest) => any; -} -declare namespace ListDevicesResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ListDevicesResponse) => any; -} -declare namespace MFAOptionType { - /** - * @internal - */ - const filterSensitiveLog: (obj: MFAOptionType) => any; -} -declare namespace NewDeviceMetadataType { - /** - * @internal - */ - const filterSensitiveLog: (obj: NewDeviceMetadataType) => any; -} -declare namespace ResendConfirmationCodeRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: ResendConfirmationCodeRequest) => any; -} -declare namespace ResendConfirmationCodeResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: ResendConfirmationCodeResponse) => any; -} -declare namespace RespondToAuthChallengeRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: RespondToAuthChallengeRequest) => any; -} -declare namespace RespondToAuthChallengeResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: RespondToAuthChallengeResponse) => any; -} -declare namespace SMSMfaSettingsType { - /** - * @internal - */ - const filterSensitiveLog: (obj: SMSMfaSettingsType) => any; -} -declare namespace SetUserMFAPreferenceRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: SetUserMFAPreferenceRequest) => any; -} -declare namespace SetUserMFAPreferenceResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: SetUserMFAPreferenceResponse) => any; -} -declare namespace SignUpRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: SignUpRequest) => any; -} -declare namespace SignUpResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: SignUpResponse) => any; -} -declare namespace SoftwareTokenMfaSettingsType { - /** - * @internal - */ - const filterSensitiveLog: (obj: SoftwareTokenMfaSettingsType) => any; -} -declare namespace UpdateDeviceStatusRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: UpdateDeviceStatusRequest) => any; -} -declare namespace UpdateDeviceStatusResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: UpdateDeviceStatusResponse) => any; -} -declare namespace UpdateUserAttributesRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: UpdateUserAttributesRequest) => any; -} -declare namespace UpdateUserAttributesResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: UpdateUserAttributesResponse) => any; -} -declare namespace UserContextDataType { - /** - * @internal - */ - const filterSensitiveLog: (obj: UserContextDataType) => any; -} -declare namespace VerifySoftwareTokenRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: VerifySoftwareTokenRequest) => any; -} -declare namespace VerifySoftwareTokenResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: VerifySoftwareTokenResponse) => any; -} -declare namespace VerifyUserAttributeRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: VerifyUserAttributeRequest) => any; -} -declare namespace VerifyUserAttributeResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: VerifyUserAttributeResponse) => any; -} -declare namespace DeleteUserAttributesRequest { - /** - * @internal - */ - const filterSensitiveLog: (obj: DeleteUserAttributesRequest) => any; -} -declare namespace DeleteUserAttributesResponse { - /** - * @internal - */ - const filterSensitiveLog: (obj: DeleteUserAttributesResponse) => any; -} -/** - *

An Amazon Pinpoint analytics endpoint.

- *

An endpoint uniquely identifies a mobile device, email address, or phone number that can receive messages from Amazon Pinpoint analytics.

- * - *

Amazon Cognito User Pools only supports sending events to Amazon Pinpoint projects in the US East (N. Virginia) us-east-1 Region, regardless of the Region in which the user pool resides.

- *
- */ -export interface AnalyticsMetadataType { - /** - *

The endpoint ID.

- */ - AnalyticsEndpointId?: string; -} -export type AssociateSoftwareTokenCommandInput = AssociateSoftwareTokenRequest; -export interface AssociateSoftwareTokenCommandOutput - extends AssociateSoftwareTokenResponse, - __MetadataBearer {} -export interface AssociateSoftwareTokenRequest { - /** - *

The access token.

- */ - AccessToken?: string; - /** - *

The session that should be passed both ways in challenge-response calls to the service. This allows authentication of the user as part of the MFA setup process.

- */ - Session?: string; -} -export interface AssociateSoftwareTokenResponse { - /** - *

A unique generated shared secret code that is used in the time-based one-time password (TOTP) algorithm to generate a one-time code.

- */ - SecretCode?: string; - /** - *

The session that should be passed both ways in challenge-response calls to the service. This allows authentication of the user as part of the MFA setup process.

- */ - Session?: string; -} -/** - *

Specifies whether the attribute is standard or custom.

- */ -export interface AttributeType { - /** - *

The name of the attribute.

- */ - Name: string | undefined; - /** - *

The value of the attribute.

- */ - Value?: string; -} -/** - *

The authentication result.

- */ -export interface AuthenticationResultType { - /** - *

The access token.

- */ - AccessToken?: string; - /** - *

The expiration period of the authentication result in seconds.

- */ - ExpiresIn?: number; - /** - *

The token type.

- */ - TokenType?: string; - /** - *

The refresh token.

- */ - RefreshToken?: string; - /** - *

The ID token.

- */ - IdToken?: string; - /** - *

The new device metadata from an authentication result.

- */ - NewDeviceMetadata?: NewDeviceMetadataType; -} -export type ChangePasswordCommandInput = ChangePasswordRequest; -export interface ChangePasswordCommandOutput - extends ChangePasswordResponse, - __MetadataBearer {} -/** - *

Represents the request to change a user password.

- */ -export interface ChangePasswordRequest { - /** - *

The old password.

- */ - PreviousPassword: string | undefined; - /** - *

The new password.

- */ - ProposedPassword: string | undefined; - /** - *

The access token.

- */ - AccessToken: string | undefined; -} -/** - *

The response from the server to the change password request.

- */ -export type ChangePasswordResponse = Record; -/** - *

The code delivery details being returned from the server.

- */ -export interface CodeDeliveryDetailsType { - /** - *

The destination for the code delivery details.

- */ - Destination?: string; - /** - *

The delivery medium (email message or phone number).

- */ - DeliveryMedium?: DeliveryMediumType | string; - /** - *

The attribute name.

- */ - AttributeName?: string; -} -export type ConfirmDeviceCommandInput = ConfirmDeviceRequest; -export interface ConfirmDeviceCommandOutput - extends ConfirmDeviceResponse, - __MetadataBearer {} -/** - *

Confirms the device request.

- */ -export interface ConfirmDeviceRequest { - /** - *

The access token.

- */ - AccessToken: string | undefined; - /** - *

The device key.

- */ - DeviceKey: string | undefined; - /** - *

The configuration of the device secret verifier.

- */ - DeviceSecretVerifierConfig?: DeviceSecretVerifierConfigType; - /** - *

The device name.

- */ - DeviceName?: string; -} -/** - *

Confirms the device response.

- */ -export interface ConfirmDeviceResponse { - /** - *

Indicates whether the user confirmation must confirm the device response.

- */ - UserConfirmationNecessary?: boolean; -} -export type ConfirmForgotPasswordCommandInput = ConfirmForgotPasswordRequest; -export interface ConfirmForgotPasswordCommandOutput - extends ConfirmForgotPasswordResponse, - __MetadataBearer {} -/** - *

The request representing the confirmation for a password reset.

- */ -export interface ConfirmForgotPasswordRequest { - /** - *

The app client ID of the app associated with the user pool.

- */ - ClientId: string | undefined; - /** - *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

- */ - SecretHash?: string; - /** - *

The user name of the user for whom you want to enter a code to retrieve a forgotten password.

- */ - Username: string | undefined; - /** - *

The confirmation code sent by a user's request to retrieve a forgotten password. For more information, - * see ForgotPassword.

- */ - ConfirmationCode: string | undefined; - /** - *

The password sent by a user's request to retrieve a forgotten password.

- */ - Password: string | undefined; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for ConfirmForgotPassword calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ConfirmForgotPassword API action, Amazon Cognito - * invokes the function that is assigned to the post confirmation trigger. When Amazon Cognito invokes this function, it passes a - * JSON payload, - * which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned - * to the ClientMetadata parameter in your ConfirmForgotPassword request. In your function code in Lambda, you can process the - * clientMetadata value to enhance your workflow for your specific needs.

- *

For more information, - * see Customizing User Pool Workflows with Lambda Triggers - * in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

The response from the server that results from a user's request to retrieve a forgotten password.

- */ -export type ConfirmForgotPasswordResponse = Record; -export type ConfirmSignUpCommandInput = ConfirmSignUpRequest; -export interface ConfirmSignUpCommandOutput - extends ConfirmSignUpResponse, - __MetadataBearer {} -/** - *

Represents the request to confirm registration of a user.

- */ -export interface ConfirmSignUpRequest { - /** - *

The ID of the app client associated with the user pool.

- */ - ClientId: string | undefined; - /** - *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

- */ - SecretHash?: string; - /** - *

The user name of the user whose registration you want to confirm.

- */ - Username: string | undefined; - /** - *

The confirmation code sent by a user's request to confirm registration.

- */ - ConfirmationCode: string | undefined; - /** - *

Boolean to be specified to force user confirmation irrespective of existing alias. By default set to False. If this parameter is set to - * True and the phone number/email used for sign up confirmation already exists as an alias with a different user, the API call will migrate - * the alias from the previous user to the newly created user being confirmed. If set to False, the API will throw an - * AliasExistsException error.

- */ - ForceAliasCreation?: boolean; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for ConfirmSignUp calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- * - *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ConfirmSignUp API action, - * Amazon Cognito invokes the function that is assigned to the post confirmation trigger. When Amazon Cognito invokes this - * function, it passes a JSON payload, which the function receives as input. This payload contains a clientMetadata attribute, which - * provides the data that you assigned to the ClientMetadata parameter in your ConfirmSignUp request. In your function code in Lambda, - * you can process the clientMetadata value to enhance your workflow for your specific needs.

- *

For more information, - * see Customizing User Pool Workflows with Lambda Triggers - * in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

Represents the response from the server for the registration confirmation.

- */ -export type ConfirmSignUpResponse = Record; -export type DeleteUserCommandInput = DeleteUserRequest; -export interface DeleteUserCommandOutput - extends DeleteUserResponse, - __MetadataBearer {} -/** - *

Represents the request to delete a user.

- */ -export interface DeleteUserRequest { - /** - *

The access token from a request to delete a user.

- */ - AccessToken: string | undefined; -} -export type DeleteUserResponse = Record; -/** - *

The device verifier against which it is authenticated.

- */ -export interface DeviceSecretVerifierConfigType { - /** - *

The password verifier.

- */ - PasswordVerifier?: string; - /** - *

The salt.

- */ - Salt?: string; -} -/** - *

The device type.

- */ -export interface DeviceType { - /** - *

The device key.

- */ - DeviceKey?: string; - /** - *

The device attributes.

- */ - DeviceAttributes?: AttributeType[]; - /** - *

The creation date of the device.

- */ - DeviceCreateDate?: number; - /** - *

The last modified date of the device.

- */ - DeviceLastModifiedDate?: number; - /** - *

The date when the device was last authenticated.

- */ - DeviceLastAuthenticatedDate?: number; -} -export type ForgetDeviceCommandInput = ForgetDeviceRequest; -export type ForgetDeviceCommandOutput = __MetadataBearer; -/** - *

Represents the request to forget the device.

- */ -export interface ForgetDeviceRequest { - /** - *

The access token for the forgotten device request.

- */ - AccessToken?: string; - /** - *

The device key.

- */ - DeviceKey: string | undefined; -} -export type ForgotPasswordCommandInput = ForgotPasswordRequest; -export interface ForgotPasswordCommandOutput - extends ForgotPasswordResponse, - __MetadataBearer {} -/** - *

Represents the request to reset a user's password.

- */ -export interface ForgotPasswordRequest { - /** - *

The ID of the client associated with the user pool.

- */ - ClientId: string | undefined; - /** - *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

- */ - SecretHash?: string; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; - /** - *

The user name of the user for whom you want to enter a code to reset a forgotten password.

- */ - Username: string | undefined; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for ForgotPassword calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ForgotPassword API action, - * Amazon Cognito invokes any functions that are assigned to the following triggers: pre sign-up, custom message, - * and user migration. When Amazon Cognito invokes any of these functions, it passes a JSON - * payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned - * to the ClientMetadata parameter in your ForgotPassword request. In your function code in Lambda, you can process the - * clientMetadata value to enhance your workflow for your specific needs.

- *

For more information, see Customizing User Pool Workflows - * with Lambda Triggers in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

Respresents the response from the server regarding the request to reset a password.

- */ -export interface ForgotPasswordResponse { - /** - *

The code delivery details returned by the server in response to the request to reset a password.

- */ - CodeDeliveryDetails?: CodeDeliveryDetailsType; -} -export type GetUserAttributeVerificationCodeCommandInput = - GetUserAttributeVerificationCodeRequest; -export interface GetUserAttributeVerificationCodeCommandOutput - extends GetUserAttributeVerificationCodeResponse, - __MetadataBearer {} -/** - *

Represents the request to get user attribute verification.

- */ -export interface GetUserAttributeVerificationCodeRequest { - /** - *

The access token returned by the server response to get the user attribute verification code.

- */ - AccessToken: string | undefined; - /** - *

The attribute name returned by the server response to get the user attribute verification code.

- */ - AttributeName: string | undefined; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- * - *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the GetUserAttributeVerificationCode - * API action, Amazon Cognito invokes the function that is assigned to the custom message trigger. When Amazon Cognito invokes this function, it - * passes a JSON payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data - * that you assigned to the ClientMetadata parameter in your GetUserAttributeVerificationCode request. In your function code in Lambda, - * you can process the clientMetadata value to enhance your workflow for your specific needs.

- *

For more information, - * see Customizing User Pool Workflows with Lambda Triggers - * in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

The verification code response returned by the server response to get the user attribute verification code.

- */ -export interface GetUserAttributeVerificationCodeResponse { - /** - *

The code delivery details returned by the server in response to the request to get the user attribute verification code.

- */ - CodeDeliveryDetails?: CodeDeliveryDetailsType; -} -export type GetUserCommandInput = GetUserRequest; -export interface GetUserCommandOutput - extends GetUserResponse, - __MetadataBearer {} -/** - *

Represents the request to get information about the user.

- */ -export interface GetUserRequest { - /** - *

The access token returned by the server response to get information about the user.

- */ - AccessToken: string | undefined; -} -/** - *

Represents the response from the server from the request to get information about the user.

- */ -export interface GetUserResponse { - /** - *

The user name of the user you want to retrieve from the get user request.

- */ - Username: string | undefined; - /** - *

An array of name-value pairs representing user attributes.

- *

For custom attributes, you must prepend the custom: prefix to the attribute name.

- */ - UserAttributes: AttributeType[] | undefined; - /** - *

- * This response parameter is no longer supported. It provides information only about SMS MFA configurations. It doesn't provide information about time-based one-time - * password (TOTP) software token MFA configurations. To look up information about either type of MFA configuration, use UserMFASettingList instead.

- */ - MFAOptions?: MFAOptionType[]; - /** - *

The user's preferred MFA setting.

- */ - PreferredMfaSetting?: string; - /** - *

The MFA options that are activated for the user. The possible values in this list are SMS_MFA and SOFTWARE_TOKEN_MFA.

- */ - UserMFASettingList?: string[]; -} -export type GlobalSignOutCommandInput = GlobalSignOutRequest; -export interface GlobalSignOutCommandOutput - extends GlobalSignOutResponse, - __MetadataBearer {} -/** - *

Represents the request to sign out all devices.

- */ -export interface GlobalSignOutRequest { - /** - *

The access token.

- */ - AccessToken: string | undefined; -} -/** - *

The response to the request to sign out all devices.

- */ -export type GlobalSignOutResponse = Record; -export type InitiateAuthCommandInput = InitiateAuthRequest; -export interface InitiateAuthCommandOutput - extends InitiateAuthResponse, - __MetadataBearer {} -/** - *

Initiates the authentication request.

- */ -export interface InitiateAuthRequest { - /** - *

The authentication flow for this call to run. The API action will depend on this value. For example:

- *
    - *
  • - *

    - * REFRESH_TOKEN_AUTH takes in a valid refresh token and returns new tokens.

    - *
  • - *
  • - *

    - * USER_SRP_AUTH takes in USERNAME and SRP_A and returns the SRP variables to be used for next challenge execution.

    - *
  • - *
  • - *

    - * USER_PASSWORD_AUTH takes in USERNAME and PASSWORD and returns the next challenge or tokens.

    - *
  • - *
- *

Valid values include:

- * - *
    - *
  • - *

    - * USER_SRP_AUTH: Authentication flow for the Secure Remote Password (SRP) protocol.

    - *
  • - *
  • - *

    - * REFRESH_TOKEN_AUTH/REFRESH_TOKEN: Authentication flow for refreshing the access token and ID token by supplying a valid refresh token.

    - *
  • - *
  • - *

    - * CUSTOM_AUTH: Custom authentication flow.

    - *
  • - *
  • - *

    - * USER_PASSWORD_AUTH: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a user migration Lambda trigger is set, this flow will invoke the user migration - * Lambda if it doesn't find the USERNAME in the user pool.

    - *
  • - *
- *

- * ADMIN_NO_SRP_AUTH isn't a valid value.

- */ - AuthFlow: AuthFlowType | string | undefined; - /** - *

The authentication parameters. These are inputs corresponding to the AuthFlow that you're invoking. The required values depend on the value of AuthFlow:

- * - *
    - *
  • - *

    For USER_SRP_AUTH: USERNAME (required), SRP_A (required), SECRET_HASH (required if the app client is configured with a client secret), - * DEVICE_KEY.

    - *
  • - *
  • - *

    For REFRESH_TOKEN_AUTH/REFRESH_TOKEN: REFRESH_TOKEN (required), SECRET_HASH (required if the app client is configured with a client secret), - * DEVICE_KEY.

    - *
  • - *
  • - *

    For CUSTOM_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), DEVICE_KEY. To start the - * authentication flow with password verification, include ChallengeName: SRP_A and SRP_A: (The SRP_A Value).

    - *
  • - *
- */ - AuthParameters?: Record; - /** - *

A map of custom key-value pairs that you can provide as input for certain custom workflows that this action triggers.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the InitiateAuth API action, Amazon Cognito invokes the Lambda functions that are specified for various - * triggers. The ClientMetadata value is passed as input to the functions for only the following triggers:

- *
    - *
  • - *

    Pre signup

    - *
  • - *
  • - *

    Pre authentication

    - *
  • - *
  • - *

    User migration

    - *
  • - *
- *

When Amazon Cognito invokes the functions for these triggers, it passes a JSON - * payload, which the function receives as input. This payload contains a validationData attribute, which provides the data that you assigned to the ClientMetadata parameter in your - * InitiateAuth request. In your function code in Lambda, you can process the validationData value to enhance your workflow for your specific needs.

- *

When you use the InitiateAuth API action, Amazon Cognito also invokes the functions for the following triggers, but it doesn't provide the ClientMetadata value as input:

- *
    - *
  • - *

    Post authentication

    - *
  • - *
  • - *

    Custom message

    - *
  • - *
  • - *

    Pre token generation

    - *
  • - *
  • - *

    Create auth challenge

    - *
  • - *
  • - *

    Define auth challenge

    - *
  • - *
  • - *

    Verify auth challenge

    - *
  • - *
- *

For more information, see Customizing User Pool Workflows with - * Lambda Triggers in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool configuration - * doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; - /** - *

The app client ID.

- */ - ClientId: string | undefined; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for InitiateAuth calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; -} -/** - *

Initiates the authentication response.

- */ -export interface InitiateAuthResponse { - /** - *

The name of the challenge that you're responding to with this call. This name is returned in the AdminInitiateAuth response if you must pass another challenge.

- *

Valid values include the following. Note that all of these challenges require - * USERNAME and SECRET_HASH (if applicable) in the parameters.

- * - *
    - *
  • - *

    - * SMS_MFA: Next challenge is to supply an SMS_MFA_CODE, delivered via SMS.

    - *
  • - *
  • - *

    - * PASSWORD_VERIFIER: Next challenge is to supply PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, and TIMESTAMP after the - * client-side SRP calculations.

    - *
  • - *
  • - *

    - * CUSTOM_CHALLENGE: This is returned if your custom authentication flow determines that the user should pass another challenge before tokens are issued.

    - *
  • - *
  • - *

    - * DEVICE_SRP_AUTH: If device tracking was activated on your user pool and the previous challenges were passed, this challenge is returned so that Amazon Cognito can start tracking - * this device.

    - *
  • - *
  • - *

    - * DEVICE_PASSWORD_VERIFIER: Similar to PASSWORD_VERIFIER, but for devices only.

    - *
  • - *
  • - *

    - * NEW_PASSWORD_REQUIRED: For users who are required to change their passwords after successful first login. This challenge should be passed with NEW_PASSWORD - * and any other required attributes.

    - *
  • - *
  • - *

    - * MFA_SETUP: For users who are required to setup an MFA factor before they can sign in. The MFA types activated for the user pool will be listed in the challenge parameters - * MFA_CAN_SETUP value.

    - *

    To set up software token MFA, use the session returned here from InitiateAuth as an input to AssociateSoftwareToken. Use the session returned by - * VerifySoftwareToken as an input to RespondToAuthChallenge with challenge name MFA_SETUP to complete sign-in. To set up SMS MFA, an - * administrator should help the user to add a phone number to their account, and then the user should call InitiateAuth again to restart sign-in.

    - *
  • - *
- */ - ChallengeName?: ChallengeNameType | string; - /** - *

The session that should pass both ways in challenge-response calls to the service. If the caller must pass another challenge, they return a session with other challenge parameters. This session - * should be passed as it is to the next RespondToAuthChallenge API call.

- */ - Session?: string; - /** - *

The challenge parameters. These are returned in the InitiateAuth response if you must pass another challenge. The responses in this parameter should be used to compute inputs to - * the next call (RespondToAuthChallenge).

- *

All challenges require USERNAME and SECRET_HASH (if applicable).

- */ - ChallengeParameters?: Record; - /** - *

The result of the authentication response. This result is only returned if the caller doesn't need to pass another challenge. If the caller does need to pass another challenge before it gets - * tokens, ChallengeName, ChallengeParameters, and Session are returned.

- */ - AuthenticationResult?: AuthenticationResultType; -} -export type ListDevicesCommandInput = ListDevicesRequest; -export interface ListDevicesCommandOutput - extends ListDevicesResponse, - __MetadataBearer {} -/** - *

Represents the request to list the devices.

- */ -export interface ListDevicesRequest { - /** - *

The access tokens for the request to list devices.

- */ - AccessToken: string | undefined; - /** - *

The limit of the device request.

- */ - Limit?: number; - /** - *

The pagination token for the list request.

- */ - PaginationToken?: string; -} -/** - *

Represents the response to list devices.

- */ -export interface ListDevicesResponse { - /** - *

The devices returned in the list devices response.

- */ - Devices?: DeviceType[]; - /** - *

The pagination token for the list device response.

- */ - PaginationToken?: string; -} -/** - *

- * This data type is no longer supported. You can use it - * only for SMS multi-factor authentication (MFA) configurations. You can't use it for time-based one-time password (TOTP) software token MFA configurations.

- */ -export interface MFAOptionType { - /** - *

The delivery medium to send the MFA code. You can use this parameter to set only the SMS delivery medium value.

- */ - DeliveryMedium?: DeliveryMediumType | string; - /** - *

The attribute name of the MFA option type. The only valid value is phone_number.

- */ - AttributeName?: string; -} -/** - *

The new device metadata type.

- */ -export interface NewDeviceMetadataType { - /** - *

The device key.

- */ - DeviceKey?: string; - /** - *

The device group key.

- */ - DeviceGroupKey?: string; -} -export type ResendConfirmationCodeCommandInput = ResendConfirmationCodeRequest; -export interface ResendConfirmationCodeCommandOutput - extends ResendConfirmationCodeResponse, - __MetadataBearer {} -/** - *

Represents the request to resend the confirmation code.

- */ -export interface ResendConfirmationCodeRequest { - /** - *

The ID of the client associated with the user pool.

- */ - ClientId: string | undefined; - /** - *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

- */ - SecretHash?: string; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; - /** - *

The username attribute of the user to whom you want to resend a confirmation code.

- */ - Username: string | undefined; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for ResendConfirmationCode calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the ResendConfirmationCode API action, Amazon Cognito - * invokes the function that is assigned to the custom message trigger. When Amazon Cognito invokes this function, it passes a - * JSON - * payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned - * to the ClientMetadata parameter in your ResendConfirmationCode request. In your function code in Lambda, you can process the clientMetadata - * value to enhance your workflow for your specific needs.

- *

For more information, - * see Customizing User Pool Workflows with Lambda Triggers - * in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

The response from the server when Amazon Cognito makes the request to resend a confirmation code.

- */ -export interface ResendConfirmationCodeResponse { - /** - *

The code delivery details returned by the server in response to the request to resend the confirmation code.

- */ - CodeDeliveryDetails?: CodeDeliveryDetailsType; -} -export type RespondToAuthChallengeCommandInput = RespondToAuthChallengeRequest; -export interface RespondToAuthChallengeCommandOutput - extends RespondToAuthChallengeResponse, - __MetadataBearer {} -/** - *

The request to respond to an authentication challenge.

- */ -export interface RespondToAuthChallengeRequest { - /** - *

The app client ID.

- */ - ClientId: string | undefined; - /** - *

The challenge name. For more information, see InitiateAuth.

- *

- * ADMIN_NO_SRP_AUTH isn't a valid value.

- */ - ChallengeName: ChallengeNameType | string | undefined; - /** - *

The session that should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines - * that the caller must pass another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge - * API call.

- */ - Session?: string; - /** - *

The challenge responses. These are inputs corresponding to the value of ChallengeName, for example:

- * - *

- * SECRET_HASH (if app client is configured with client secret) applies to all of the inputs that follow (including SOFTWARE_TOKEN_MFA).

- *
- *
    - *
  • - *

    - * SMS_MFA: SMS_MFA_CODE, USERNAME.

    - *
  • - *
  • - *

    - * PASSWORD_VERIFIER: PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, TIMESTAMP, USERNAME.

    - * - *

    - * PASSWORD_VERIFIER requires DEVICE_KEY when signing in with a remembered device.

    - *
    - *
  • - *
  • - *

    - * NEW_PASSWORD_REQUIRED: NEW_PASSWORD, any other required attributes, USERNAME.

    - *
  • - *
  • - *

    - * SOFTWARE_TOKEN_MFA: USERNAME and SOFTWARE_TOKEN_MFA_CODE are required attributes.

    - *
  • - *
  • - *

    - * DEVICE_SRP_AUTH requires USERNAME, DEVICE_KEY, SRP_A (and SECRET_HASH).

    - *
  • - *
  • - *

    - * DEVICE_PASSWORD_VERIFIER requires everything that PASSWORD_VERIFIER requires, plus DEVICE_KEY.

    - *
  • - *
  • - *

    - * MFA_SETUP requires USERNAME, plus you must use the session value returned by VerifySoftwareToken in the Session parameter.

    - *
  • - *
- */ - ChallengeResponses?: Record; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for RespondToAuthChallenge calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the RespondToAuthChallenge API action, Amazon Cognito - * invokes any functions that are assigned to the following triggers: post authentication, pre token generation, - * define auth challenge, create auth challenge, and verify auth challenge. When Amazon Cognito - * invokes any of these functions, it passes a JSON payload, which the function receives as input. This payload contains a clientMetadata - * attribute, which provides the data that you assigned to the ClientMetadata parameter in your RespondToAuthChallenge request. In your function code in - * Lambda, you can process the clientMetadata value to enhance your workflow for your specific needs.

- *

For more information, see Customizing - * User Pool Workflows with Lambda Triggers in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool configuration - * doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

The response to respond to the authentication challenge.

- */ -export interface RespondToAuthChallengeResponse { - /** - *

The challenge name. For more information, see InitiateAuth.

- */ - ChallengeName?: ChallengeNameType | string; - /** - *

The session that should be passed both ways in challenge-response calls to the service. If the caller must pass another challenge, they return a session with other challenge parameters. - * This session should be passed as it is to the next RespondToAuthChallenge API call.

- */ - Session?: string; - /** - *

The challenge parameters. For more information, see InitiateAuth.

- */ - ChallengeParameters?: Record; - /** - *

The result returned by the server in response to the request to respond to the authentication challenge.

- */ - AuthenticationResult?: AuthenticationResultType; -} -/** - *

The type used for enabling SMS multi-factor authentication (MFA) at the user level. Phone numbers don't need to be verified to be used for SMS MFA. If an MFA type - * is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking is turned on and the device has been trusted. If you - * would like MFA to be applied selectively based on the assessed risk level of sign-in attempts, deactivate MFA for users and turn on Adaptive Authentication for the user pool.

- */ -export interface SMSMfaSettingsType { - /** - *

Specifies whether SMS text message MFA is activated. If an MFA type is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking is - * turned on and the device has been trusted.

- */ - Enabled?: boolean; - /** - *

Specifies whether SMS is the preferred MFA method.

- */ - PreferredMfa?: boolean; -} -export type SetUserMFAPreferenceCommandInput = SetUserMFAPreferenceRequest; -export interface SetUserMFAPreferenceCommandOutput - extends SetUserMFAPreferenceResponse, - __MetadataBearer {} -export interface SetUserMFAPreferenceRequest { - /** - *

The SMS text message multi-factor authentication (MFA) settings.

- */ - SMSMfaSettings?: SMSMfaSettingsType; - /** - *

The time-based one-time password software token MFA settings.

- */ - SoftwareTokenMfaSettings?: SoftwareTokenMfaSettingsType; - /** - *

The access token for the user.

- */ - AccessToken: string | undefined; -} -export type SetUserMFAPreferenceResponse = Record; -export type SignUpCommandInput = SignUpRequest; -export interface SignUpCommandOutput extends SignUpResponse, __MetadataBearer {} -/** - *

Represents the request to register a user.

- */ -export interface SignUpRequest { - /** - *

The ID of the client associated with the user pool.

- */ - ClientId: string | undefined; - /** - *

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

- */ - SecretHash?: string; - /** - *

The user name of the user you want to register.

- */ - Username: string | undefined; - /** - *

The password of the user you want to register.

- */ - Password: string | undefined; - /** - *

An array of name-value pairs representing user attributes.

- *

For custom attributes, you must prepend the custom: prefix to the attribute name.

- */ - UserAttributes?: AttributeType[]; - /** - *

The validation data in the request to register a user.

- */ - ValidationData?: AttributeType[]; - /** - *

The Amazon Pinpoint analytics metadata for collecting metrics for SignUp calls.

- */ - AnalyticsMetadata?: AnalyticsMetadataType; - /** - *

Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - UserContextData?: UserContextDataType; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the SignUp API action, Amazon Cognito - * invokes any functions that are assigned to the following triggers: pre sign-up, custom message, - * and post confirmation. When Amazon Cognito invokes any of these functions, it passes a JSON payload, which the function - * receives as input. This payload contains a clientMetadata attribute, which provides the data that you assigned to the - * ClientMetadata parameter in your SignUp request. In your function code in Lambda, you can process the clientMetadata - * value to enhance your workflow for your specific needs.

- *

For more information, - * see Customizing User Pool Workflows with Lambda Triggers - * in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

The response from the server for a registration request.

- */ -export interface SignUpResponse { - /** - *

A response from the server indicating that a user registration has been confirmed.

- */ - UserConfirmed: boolean | undefined; - /** - *

The code delivery details returned by the server response to the user registration request.

- */ - CodeDeliveryDetails?: CodeDeliveryDetailsType; - /** - *

The UUID of the authenticated user. This isn't the same as username.

- */ - UserSub: string | undefined; -} -/** - *

The type used for enabling software token MFA at the user level. If an MFA type is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking - * is turned on and the device has been trusted. If you want MFA to be applied selectively based on the assessed risk level of sign-in attempts, deactivate MFA for users and turn on Adaptive - * Authentication for the user pool.

- */ -export interface SoftwareTokenMfaSettingsType { - /** - *

Specifies whether software token MFA is activated. If an MFA type is activated for a user, the user will be prompted for MFA during all sign-in attempts, unless device tracking is turned - * on and the device has been trusted.

- */ - Enabled?: boolean; - /** - *

Specifies whether software token MFA is the preferred MFA method.

- */ - PreferredMfa?: boolean; -} -export type UpdateDeviceStatusCommandInput = UpdateDeviceStatusRequest; -export interface UpdateDeviceStatusCommandOutput - extends UpdateDeviceStatusResponse, - __MetadataBearer {} -/** - *

Represents the request to update the device status.

- */ -export interface UpdateDeviceStatusRequest { - /** - *

The access token.

- */ - AccessToken: string | undefined; - /** - *

The device key.

- */ - DeviceKey: string | undefined; - /** - *

The status of whether a device is remembered.

- */ - DeviceRememberedStatus?: DeviceRememberedStatusType | string; -} -/** - *

The response to the request to update the device status.

- */ -export type UpdateDeviceStatusResponse = Record; -export type UpdateUserAttributesCommandInput = UpdateUserAttributesRequest; -export interface UpdateUserAttributesCommandOutput - extends UpdateUserAttributesResponse, - __MetadataBearer {} -/** - *

Represents the request to update user attributes.

- */ -export interface UpdateUserAttributesRequest { - /** - *

An array of name-value pairs representing user attributes.

- *

For custom attributes, you must prepend the custom: prefix to the attribute name.

- */ - UserAttributes: AttributeType[] | undefined; - /** - *

The access token for the request to update user attributes.

- */ - AccessToken: string | undefined; - /** - *

A map of custom key-value pairs that you can provide as input for any custom workflows that this action initiates.

- *

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the UpdateUserAttributes API action, Amazon Cognito invokes the - * function that is assigned to the custom message trigger. When Amazon Cognito invokes this function, it passes a - * JSON - * payload, which the function receives as input. This payload contains a clientMetadata attribute, which provides the data that you - * assigned to the ClientMetadata parameter in your UpdateUserAttributes request. In your function code in Lambda, you can process the clientMetadata - * value to enhance your workflow for your specific needs.

- *

For more information, see Customizing User Pool - * Workflows with Lambda Triggers in the Amazon Cognito Developer Guide.

- * - * - *

When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:

- *
    - *
  • - *

    Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool to support custom workflows. If your user pool - * configuration doesn't include triggers, the ClientMetadata parameter serves no purpose.

    - *
  • - *
  • - *

    Validate the ClientMetadata value.

    - *
  • - *
  • - *

    Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.

    - *
  • - *
- *
- */ - ClientMetadata?: Record; -} -/** - *

Represents the response from the server for the request to update user attributes.

- */ -export interface UpdateUserAttributesResponse { - /** - *

The code delivery details list from the server for the request to update user attributes.

- */ - CodeDeliveryDetailsList?: CodeDeliveryDetailsType[]; -} -/** - *

Contextual data, such as the user's device fingerprint, IP address, or location, used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ -export interface UserContextDataType { - /** - *

Contextual data, such as the user's device fingerprint, IP address, or location, used for evaluating the risk of an unexpected event by Amazon Cognito advanced security.

- */ - EncodedData?: string; -} -export type VerifySoftwareTokenCommandInput = VerifySoftwareTokenRequest; -export interface VerifySoftwareTokenCommandOutput - extends VerifySoftwareTokenResponse, - __MetadataBearer {} -export interface VerifySoftwareTokenRequest { - /** - *

The access token.

- */ - AccessToken?: string; - /** - *

The session that should be passed both ways in challenge-response calls to the service.

- */ - Session?: string; - /** - *

The one- time password computed using the secret code returned by - * AssociateSoftwareToken.

- */ - UserCode: string | undefined; - /** - *

The friendly device name.

- */ - FriendlyDeviceName?: string; -} -export interface VerifySoftwareTokenResponse { - /** - *

The status of the verify software token.

- */ - Status?: VerifySoftwareTokenResponseType | string; - /** - *

The session that should be passed both ways in challenge-response calls to the service.

- */ - Session?: string; -} -export type VerifyUserAttributeCommandInput = VerifyUserAttributeRequest; -export interface VerifyUserAttributeCommandOutput - extends VerifyUserAttributeResponse, - __MetadataBearer {} -/** - *

Represents the request to verify user attributes.

- */ -export interface VerifyUserAttributeRequest { - /** - *

The access token of the request to verify user attributes.

- */ - AccessToken: string | undefined; - /** - *

The attribute name in the request to verify user attributes.

- */ - AttributeName: string | undefined; - /** - *

The verification code in the request to verify user attributes.

- */ - Code: string | undefined; -} -/** - *

A container representing the response from the server from the request to verify user attributes.

- */ -export type VerifyUserAttributeResponse = Record; -export type DeleteUserAttributesCommandInput = DeleteUserAttributesRequest; -export interface DeleteUserAttributesCommandOutput - extends DeleteUserAttributesResponse, - __MetadataBearer {} -/** - *

Represents the request to delete user attributes.

- */ -export interface DeleteUserAttributesRequest { - /** - *

An array of strings representing the user attribute names you want to delete.

- *

For custom attributes, you must prependattach the custom: prefix to the - * front of the attribute name.

- */ - UserAttributeNames: string[] | undefined; - /** - *

A valid access token that Amazon Cognito issued to the user whose attributes you want to - * delete.

- */ - AccessToken: string | undefined; -} -/** - *

Represents the response from the server to delete user attributes.

- */ -export type DeleteUserAttributesResponse = Record; -export {}; diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts deleted file mode 100644 index 2202f2dcd37..00000000000 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { AuthError } from '../../../../../errors/AuthError'; - -export function getRegion(userPoolId?: string): string { - const region = userPoolId?.split('_')[0]; - if ( - !userPoolId || - userPoolId.indexOf('_') < 0 || - !region || - typeof region !== 'string' - ) - throw new AuthError({ - name: 'InvalidUserPoolId', - message: 'Invalid user pool id provided.', - }); - - return region; -} - -export function getRegionFromIdentityPoolId(identityPoolId?: string): string { - if (!identityPoolId || !identityPoolId.includes(':')) { - throw new AuthError({ - name: 'InvalidIdentityPoolIdException', - message: 'Invalid identity pool id provided.', - recoverySuggestion: - 'Make sure a valid identityPoolId is given in the config.', - }); - } - - return identityPoolId.split(':')[0]; -} diff --git a/packages/auth/src/providers/cognito/utils/clients/base.ts b/packages/auth/src/providers/cognito/utils/clients/base.ts deleted file mode 100644 index a6a5fb6aca0..00000000000 --- a/packages/auth/src/providers/cognito/utils/clients/base.ts +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { - Endpoint, - EndpointResolverOptions, - Headers, - HttpRequest, - HttpResponse, - Middleware, - getDnsSuffix, - getRetryDecider, - jitteredBackoff, - parseJsonError, - unauthenticatedHandler, -} from '@aws-amplify/core/internals/aws-client-utils'; -import { - AmplifyUrl, - getAmplifyUserAgent, -} from '@aws-amplify/core/internals/utils'; -import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers'; - -/** - * The service name used to sign requests if the API requires authentication. - */ -const SERVICE_NAME = 'cognito-idp'; - -/** - * The endpoint resolver function that returns the endpoint URL for a given region. - */ -const endpointResolver = ({ region }: EndpointResolverOptions) => ({ - url: new AmplifyUrl( - `https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`, - ), -}); - -/** - * A Cognito Identity-specific middleware that disables caching for all requests. - */ -const disableCacheMiddlewareFactory: Middleware< - HttpRequest, - HttpResponse, - Record -> = () => (next, _) => - async function disableCacheMiddleware(request) { - request.headers['cache-control'] = 'no-store'; - - return next(request); - }; - -/** - * A Cognito Identity-specific transfer handler that does NOT sign requests, and - * disables caching. - * - * @internal - */ -export const cognitoUserPoolTransferHandler = composeTransferHandler< - [Parameters[0]], - HttpRequest, - HttpResponse, - typeof unauthenticatedHandler ->(unauthenticatedHandler, [disableCacheMiddlewareFactory]); - -/** - * @internal - */ -export const defaultConfig = { - service: SERVICE_NAME, - endpointResolver, - retryDecider: getRetryDecider(parseJsonError), - computeDelay: jitteredBackoff, - userAgentValue: getAmplifyUserAgent(), -}; - -/** - * @internal - */ -export const getSharedHeaders = (operation: string): Headers => ({ - 'content-type': 'application/x-amz-json-1.1', - 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}`, -}); - -/** - * @internal - */ -export const buildHttpRpcRequest = ( - { url }: Endpoint, - headers: Headers, - body: any, -): HttpRequest => ({ - headers, - url, - body, - method: 'POST', -}); diff --git a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts index 6c3df620492..e1b545a42e9 100644 --- a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts +++ b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts @@ -9,10 +9,11 @@ import { } from '@aws-amplify/core/internals/utils'; import { CognitoAuthTokens, TokenRefresher } from '../tokenProvider/types'; -import { initiateAuth } from '../utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; import { assertAuthTokensWithRefreshToken } from '../utils/types'; import { AuthError } from '../../../errors/AuthError'; +import { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; import { getUserContextData } from './userContextData'; @@ -26,7 +27,8 @@ const refreshAuthTokensFunction: TokenRefresher = async ({ username: string; }): Promise => { assertTokenProviderConfig(authConfig?.Cognito); - const region = getRegion(authConfig.Cognito.userPoolId); + const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig.Cognito; + const region = getRegionFromUserPoolId(userPoolId); assertAuthTokensWithRefreshToken(tokens); const refreshTokenString = tokens.refreshToken; @@ -39,14 +41,20 @@ const refreshAuthTokensFunction: TokenRefresher = async ({ const UserContextData = getUserContextData({ username, - userPoolId: authConfig.Cognito.userPoolId, - userPoolClientId: authConfig.Cognito.userPoolClientId, + userPoolId, + userPoolClientId, + }); + + const initiateAuth = createInitiateAuthClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), }); const { AuthenticationResult } = await initiateAuth( { region }, { - ClientId: authConfig?.Cognito?.userPoolClientId, + ClientId: userPoolClientId, AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters, UserContextData, diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index 13edcd84e62..cb7bd49dd0e 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -31,15 +31,14 @@ import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../errors/constants' import { getCurrentUser } from '../apis/getCurrentUser'; import { AuthTokenOrchestrator, DeviceMetadata } from '../tokenProvider/types'; import { getAuthUserAgentValue } from '../../../utils'; - -import { signInStore } from './signInStore'; import { - associateSoftwareToken, - confirmDevice, - initiateAuth, - respondToAuthChallenge, - verifySoftwareToken, -} from './clients/CognitoIdentityProvider'; + createAssociateSoftwareTokenClient, + createConfirmDeviceClient, + createInitiateAuthClient, + createRespondToAuthChallengeClient, + createVerifySoftwareTokenClient, +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../factories'; import { ChallengeName, ChallengeParameters, @@ -49,8 +48,10 @@ import { NewDeviceMetadataType, RespondToAuthChallengeCommandInput, RespondToAuthChallengeCommandOutput, -} from './clients/CognitoIdentityProvider/types'; -import { getRegion } from './clients/CognitoIdentityProvider/utils'; +} from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; +import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; + +import { signInStore } from './signInStore'; import { assertDeviceMetadata } from './types'; import { getAuthenticationHelper, @@ -92,7 +93,7 @@ export async function handleCustomChallenge({ }: HandleAuthChallengeRequest & { tokenOrchestrator: AuthTokenOrchestrator; }): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const challengeResponses: Record = { USERNAME: username, ANSWER: challengeResponse, @@ -118,9 +119,14 @@ export async function handleCustomChallenge({ UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const response = await respondToAuthChallenge( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, jsonReq, @@ -147,14 +153,18 @@ export async function handleMFASetupChallenge({ deviceName, config, }: HandleAuthChallengeRequest): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const challengeResponses = { USERNAME: username, }; - + const verifySoftwareToken = createVerifySoftwareTokenClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { Session } = await verifySoftwareToken( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, { @@ -177,7 +187,16 @@ export async function handleMFASetupChallenge({ ClientId: userPoolClientId, }; - return respondToAuthChallenge({ region: getRegion(userPoolId) }, jsonReq); + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + + return respondToAuthChallenge( + { region: getRegionFromUserPoolId(userPoolId) }, + jsonReq, + ); } export async function handleSelectMFATypeChallenge({ @@ -187,7 +206,7 @@ export async function handleSelectMFATypeChallenge({ session, config, }: HandleAuthChallengeRequest): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; assertValidationError( challengeResponse === 'TOTP' || challengeResponse === 'SMS', AuthValidationErrorCode.IncorrectMFAMethod, @@ -213,9 +232,15 @@ export async function handleSelectMFATypeChallenge({ UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + return respondToAuthChallenge( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, jsonReq, @@ -229,7 +254,7 @@ export async function handleSMSMFAChallenge({ username, config, }: HandleAuthChallengeRequest): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const challengeResponses = { USERNAME: username, SMS_MFA_CODE: challengeResponse, @@ -248,9 +273,15 @@ export async function handleSMSMFAChallenge({ UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + return respondToAuthChallenge( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, jsonReq, @@ -263,7 +294,7 @@ export async function handleSoftwareTokenMFAChallenge({ username, config, }: HandleAuthChallengeRequest): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const challengeResponses = { USERNAME: username, SOFTWARE_TOKEN_MFA_CODE: challengeResponse, @@ -284,9 +315,15 @@ export async function handleSoftwareTokenMFAChallenge({ UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + return respondToAuthChallenge( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, jsonReq, @@ -300,7 +337,7 @@ export async function handleCompleteNewPasswordChallenge({ requiredAttributes, config, }: HandleAuthChallengeRequest): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const challengeResponses = { ...createAttributes(requiredAttributes), NEW_PASSWORD: challengeResponse, @@ -322,9 +359,15 @@ export async function handleCompleteNewPasswordChallenge({ UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + return respondToAuthChallenge( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, jsonReq, @@ -338,7 +381,7 @@ export async function handleUserPasswordAuthFlow( config: CognitoUserPoolConfig, tokenOrchestrator: AuthTokenOrchestrator, ): Promise { - const { userPoolClientId, userPoolId } = config; + const { userPoolClientId, userPoolId, userPoolEndpoint } = config; const authParameters: Record = { USERNAME: username, PASSWORD: password, @@ -363,9 +406,15 @@ export async function handleUserPasswordAuthFlow( UserContextData, }; + const initiateAuth = createInitiateAuthClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + const response = await initiateAuth( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, jsonReq, @@ -397,7 +446,7 @@ export async function handleUserSRPAuthFlow( config: CognitoUserPoolConfig, tokenOrchestrator: AuthTokenOrchestrator, ): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const userPoolName = userPoolId?.split('_')[1] || ''; const authenticationHelper = await getAuthenticationHelper(userPoolName); @@ -420,9 +469,15 @@ export async function handleUserSRPAuthFlow( UserContextData, }; + const initiateAuth = createInitiateAuthClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + const resp = await initiateAuth( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, jsonReq, @@ -453,7 +508,7 @@ export async function handleCustomAuthFlowWithoutSRP( config: CognitoUserPoolConfig, tokenOrchestrator: AuthTokenOrchestrator, ): Promise { - const { userPoolClientId, userPoolId } = config; + const { userPoolClientId, userPoolId, userPoolEndpoint } = config; const authParameters: Record = { USERNAME: username, }; @@ -477,9 +532,15 @@ export async function handleCustomAuthFlowWithoutSRP( UserContextData, }; + const initiateAuth = createInitiateAuthClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + const response = await initiateAuth( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, jsonReq, @@ -506,7 +567,7 @@ export async function handleCustomSRPAuthFlow( tokenOrchestrator: AuthTokenOrchestrator, ) { assertTokenProviderConfig(config); - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const userPoolName = userPoolId?.split('_')[1] || ''; const authenticationHelper = await getAuthenticationHelper(userPoolName); @@ -531,10 +592,16 @@ export async function handleCustomSRPAuthFlow( UserContextData, }; + const initiateAuth = createInitiateAuthClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + const { ChallengeParameters: challengeParameters, Session: session } = await initiateAuth( { - region: getRegion(userPoolId), + region: getRegionFromUserPoolId(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, jsonReq, @@ -565,7 +632,7 @@ async function handleDeviceSRPAuth({ session, tokenOrchestrator, }: HandleDeviceSRPInput): Promise { - const { userPoolId } = config; + const { userPoolId, userPoolEndpoint } = config; const clientId = config.userPoolClientId; const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username); assertDeviceMetadata(deviceMetadata); @@ -585,9 +652,14 @@ async function handleDeviceSRPAuth({ ClientMetadata: clientMetadata, Session: session, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); const { ChallengeParameters: respondedChallengeParameters, Session } = await respondToAuthChallenge( - { region: getRegion(userPoolId) }, + { region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge, ); @@ -608,7 +680,7 @@ async function handleDevicePasswordVerifier( clientMetadata: ClientMetadata | undefined, session: string | undefined, authenticationHelper: AuthenticationHelper, - { userPoolId, userPoolClientId }: CognitoUserPoolConfig, + { userPoolId, userPoolClientId, userPoolEndpoint }: CognitoUserPoolConfig, tokenOrchestrator?: AuthTokenOrchestrator, ): Promise { const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username); @@ -654,9 +726,14 @@ async function handleDevicePasswordVerifier( ClientMetadata: clientMetadata, UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); return respondToAuthChallenge( - { region: getRegion(userPoolId) }, + { region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge, ); } @@ -670,7 +747,7 @@ export async function handlePasswordVerifierChallenge( config: CognitoUserPoolConfig, tokenOrchestrator: AuthTokenOrchestrator, ): Promise { - const { userPoolId, userPoolClientId } = config; + const { userPoolId, userPoolClientId, userPoolEndpoint } = config; const userPoolName = userPoolId?.split('_')[1] || ''; const serverBValue = new (BigInteger as any)(challengeParameters?.SRP_B, 16); const salt = new (BigInteger as any)(challengeParameters?.SALT, 16); @@ -722,8 +799,14 @@ export async function handlePasswordVerifierChallenge( UserContextData, }; + const respondToAuthChallenge = createRespondToAuthChallengeClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); + const response = await respondToAuthChallenge( - { region: getRegion(userPoolId) }, + { region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge, ); @@ -766,8 +849,14 @@ export async function getSignInResult(params: { parseMFATypes(challengeParameters.MFAS_CAN_SETUP), )}`, }); + + const associateSoftwareToken = createAssociateSoftwareTokenClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: authConfig.userPoolEndpoint, + }), + }); const { Session, SecretCode: secretCode } = await associateSoftwareToken( - { region: getRegion(authConfig.userPoolId) }, + { region: getRegionFromUserPoolId(authConfig.userPoolId) }, { Session: signInSession, }, @@ -1037,11 +1126,17 @@ export async function assertUserNotAuthenticated() { * * @returns DeviceMetadata | undefined */ -export async function getNewDeviceMetatada( - userPoolId: string, - newDeviceMetadata?: NewDeviceMetadataType, - accessToken?: string, -): Promise { +export async function getNewDeviceMetadata({ + userPoolId, + userPoolEndpoint, + newDeviceMetadata, + accessToken, +}: { + userPoolId: string; + userPoolEndpoint: string | undefined; + newDeviceMetadata?: NewDeviceMetadataType; + accessToken?: string; +}): Promise { if (!newDeviceMetadata) return undefined; const userPoolName = userPoolId.split('_')[1] || ''; const authenticationHelper = await getAuthenticationHelper(userPoolName); @@ -1069,8 +1164,13 @@ export async function getNewDeviceMetatada( const randomPassword = authenticationHelper.getRandomPassword(); try { + const confirmDevice = createConfirmDeviceClient({ + endpointResolver: createCognitoUserPoolEndpointResolver({ + endpointOverride: userPoolEndpoint, + }), + }); await confirmDevice( - { region: getRegion(userPoolId) }, + { region: getRegionFromUserPoolId(userPoolId) }, { AccessToken: accessToken, DeviceName: await getDeviceName(), diff --git a/packages/auth/src/providers/cognito/utils/signInStore.ts b/packages/auth/src/providers/cognito/utils/signInStore.ts index 0028ab71067..fd07cb15e6d 100644 --- a/packages/auth/src/providers/cognito/utils/signInStore.ts +++ b/packages/auth/src/providers/cognito/utils/signInStore.ts @@ -2,8 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { CognitoAuthSignInDetails } from '../types'; - -import { ChallengeName } from './clients/CognitoIdentityProvider/types'; +import { ChallengeName } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; // TODO: replace all of this implementation with state machines interface SignInState { diff --git a/packages/auth/src/providers/cognito/utils/signUpHelpers.ts b/packages/auth/src/providers/cognito/utils/signUpHelpers.ts index 73e59c78406..8ab2943ce2a 100644 --- a/packages/auth/src/providers/cognito/utils/signUpHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signUpHelpers.ts @@ -10,8 +10,7 @@ import { AutoSignInCallback } from '../../../types/models'; import { AuthError } from '../../../errors/AuthError'; import { resetAutoSignIn, setAutoSignIn } from '../apis/autoSignIn'; import { AUTO_SIGN_IN_EXCEPTION } from '../../../errors/constants'; - -import { SignUpCommandOutput } from './clients/CognitoIdentityProvider/types'; +import { SignUpCommandOutput } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; const MAX_AUTOSIGNIN_POLLING_MS = 3 * 60 * 1000; diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index c23c9eae63b..981f9f44baf 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -449,7 +449,7 @@ "name": "[Auth] Basic Auth Flow (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ signIn, signOut, fetchAuthSession, confirmSignIn }", - "limit": "30.15 kB" + "limit": "30.20 kB" }, { "name": "[Auth] OAuth Auth Flow (Cognito)", From 64bee045b7103eb71c78769bd7da8c688e2aa89a Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 19 Aug 2024 13:46:49 -0700 Subject: [PATCH 03/11] chore(auth): refactor existing unit test suites --- .../providers/cognito/autoSignIn.test.ts | 37 ++-- .../cognito/confirmResetPassword.test.ts | 39 ++++- .../cognito/confirmSignInErrorCases.test.ts | 19 ++- .../cognito/confirmSignInHappyCases.test.ts | 159 +++++++++--------- .../providers/cognito/confirmSignUp.test.ts | 45 ++++- .../cognito/confirmUserAttribute.test.ts | 40 ++++- .../providers/cognito/deleteUser.test.ts | 35 +++- .../cognito/deleteUserAttributes.test.ts | 39 ++++- .../providers/cognito/fetchDevices.test.ts | 33 +++- .../cognito/fetchMFAPreference.test.ts | 32 +++- .../cognito/fetchUserAttributes.test.ts | 33 +++- .../providers/cognito/forgetDevice.test.ts | 35 +++- .../cognito/getNewDeviceMetadata.test.ts | 91 +++++++--- .../providers/cognito/refreshToken.test.ts | 58 ++++++- .../providers/cognito/rememberDevice.test.ts | 37 +++- .../cognito/resendSignUpCode.test.ts | 37 +++- .../providers/cognito/resetPassword.test.ts | 37 +++- .../sendUserAttributeVerificationCode.test.ts | 43 ++++- .../providers/cognito/setUpTOTP.test.ts | 38 ++++- .../cognito/signInErrorCases.test.ts | 11 +- .../cognito/signInStateManagement.test.ts | 2 +- .../cognito/signInWithCustomAuth.test.ts | 37 ++-- .../cognito/signInWithCustomSRPAuth.test.ts | 36 ++-- .../providers/cognito/signInWithSRP.test.ts | 70 +++++--- .../cognito/signInWithUserPassword.test.ts | 51 +++--- .../providers/cognito/signOut.test.ts | 100 ++++++++--- .../providers/cognito/signUp.test.ts | 50 +++++- .../cognito/updateMFAPreference.test.ts | 37 +++- .../providers/cognito/updatePassword.test.ts | 35 +++- .../cognito/updateUserAttributes.test.ts | 42 ++++- .../providers/cognito/verifyTOTPSetup.test.ts | 41 ++++- 31 files changed, 1089 insertions(+), 310 deletions(-) diff --git a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts index 783fc2e9699..d787c2cdedf 100644 --- a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts +++ b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts @@ -8,13 +8,10 @@ import { signUp, } from '../../../src/providers/cognito'; import { autoSignIn } from '../../../src/providers/cognito/apis/autoSignIn'; -import * as signUpClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { - RespondToAuthChallengeCommandOutput, - SignUpCommandOutput, -} from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { AuthError } from '../../../src/errors/AuthError'; +import { createSignUpClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { RespondToAuthChallengeCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; @@ -23,6 +20,9 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); const authConfig = { Cognito: { @@ -35,27 +35,30 @@ Amplify.configure({ Auth: authConfig, }); describe('Auto sign-in API Happy Path Cases:', () => { - let signUpSpy; - let handleUserSRPAuthflowSpy; + let handleUserSRPAuthFlowSpy: jest.SpyInstance; + + const mockSignUp = jest.fn(); + const mockCreateSignUpClient = jest.mocked(createSignUpClient); + const { user1 } = authAPITestParams; beforeEach(async () => { - signUpSpy = jest - .spyOn(signUpClient, 'signUp') - .mockImplementationOnce( - async () => ({ UserConfirmed: true }) as SignUpCommandOutput, - ); + mockSignUp.mockResolvedValueOnce({ UserConfirmed: true }); + mockCreateSignUpClient.mockReturnValueOnce(mockSignUp); - handleUserSRPAuthflowSpy = jest + handleUserSRPAuthFlowSpy = jest .spyOn(initiateAuthHelpers, 'handleUserSRPAuthFlow') .mockImplementationOnce( async (): Promise => authAPITestParams.RespondToAuthChallengeCommandOutput, ); }); + afterEach(() => { - signUpSpy.mockClear(); - handleUserSRPAuthflowSpy.mockClear(); + mockSignUp.mockClear(); + mockCreateSignUpClient.mockClear(); + handleUserSRPAuthFlowSpy.mockClear(); }); + test('signUp should enable autoSignIn and return COMPLETE_AUTO_SIGN_IN step', async () => { const resp = await signUp({ username: user1.username, @@ -71,13 +74,13 @@ describe('Auto sign-in API Happy Path Cases:', () => { signUpStep: 'COMPLETE_AUTO_SIGN_IN', }, }); - expect(signUpSpy).toHaveBeenCalledTimes(1); + expect(mockSignUp).toHaveBeenCalledTimes(1); }); test('Auto sign-in should resolve to a signIn output', async () => { const signInOutput = await autoSignIn(); expect(signInOutput).toEqual(authAPITestParams.signInResult()); - expect(handleUserSRPAuthflowSpy).toHaveBeenCalledTimes(1); + expect(handleUserSRPAuthFlowSpy).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts index df8167e5030..d07979c5d9c 100644 --- a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts @@ -7,7 +7,8 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { confirmResetPassword } from '../../../src/providers/cognito'; import { ConfirmForgotPasswordException } from '../../../src/providers/cognito/types/errors'; -import { confirmForgotPassword } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createConfirmForgotPasswordClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError } from './testUtils/data'; @@ -22,12 +23,19 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('confirmResetPassword', () => { // assert mocks - const mockConfirmForgotPassword = confirmForgotPassword as jest.Mock; + const mockConfirmForgotPassword = jest.fn(); + const mockCreateConfirmResetPasswordClient = jest.mocked( + createConfirmForgotPasswordClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -37,10 +45,15 @@ describe('confirmResetPassword', () => { mockConfirmForgotPassword.mockResolvedValue( authAPITestParams.confirmResetPasswordHttpCallResult, ); + mockCreateConfirmResetPasswordClient.mockReturnValueOnce( + mockConfirmForgotPassword, + ); }); afterEach(() => { mockConfirmForgotPassword.mockReset(); + mockCreateConfirmResetPasswordClient.mockClear(); + mockCreateCognitoUserPoolEndpointResolver.mockClear(); }); it('should call the confirmForgotPassword and return void', async () => { @@ -50,6 +63,26 @@ describe('confirmResetPassword', () => { expect(mockConfirmForgotPassword).toHaveBeenCalled(); }); + it('invokes createCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + + await confirmResetPassword(authAPITestParams.confirmResetPasswordRequest); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should contain clientMetadata from request', async () => { await confirmResetPassword({ username: 'username', diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts index 0f20b1703f3..a2d561799d9 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts @@ -4,8 +4,8 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { confirmSignIn } from '../../../src/providers/cognito/apis/confirmSignIn'; import { RespondToAuthChallengeException } from '../../../src/providers/cognito/types/errors'; -import { respondToAuthChallenge } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { signInStore } from '../../../src/providers/cognito/utils/signInStore'; +import { createRespondToAuthChallengeClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; import { getMockError } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -15,10 +15,11 @@ jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), Amplify: { getConfig: jest.fn(() => ({})) }, })); +jest.mock('../../../src/providers/cognito/utils/signInStore'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); -jest.mock('../../../src/providers/cognito/utils/signInStore'); +jest.mock('../../../src/providers/cognito/factories'); describe('confirmSignIn API error path cases:', () => { const challengeName = 'SELECT_MFA_TYPE'; @@ -26,7 +27,10 @@ describe('confirmSignIn API error path cases:', () => { const { username } = authAPITestParams.user1; // assert mocks const mockStoreGetState = signInStore.getState as jest.Mock; - const mockRespondToAuthChallenge = respondToAuthChallenge as jest.Mock; + const mockRespondToAuthChallenge = jest.fn(); + const mockCreateRespondToAuthChallengeClient = jest.mocked( + createRespondToAuthChallengeClient, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -37,8 +41,15 @@ describe('confirmSignIn API error path cases:', () => { }); }); + beforeEach(() => { + mockCreateRespondToAuthChallengeClient.mockReturnValueOnce( + mockRespondToAuthChallenge, + ); + }); + afterEach(() => { mockRespondToAuthChallenge.mockReset(); + mockCreateRespondToAuthChallengeClient.mockClear(); }); it('confirmSignIn API should throw an error when challengeResponse is empty', async () => { diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts index ddeb3c368fd..ddfcc9c2d8e 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts @@ -9,16 +9,22 @@ import { signIn, } from '../../../src/providers/cognito/'; import * as signInHelpers from '../../../src/providers/cognito/utils/signInHelpers'; -import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; -import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { + createInitiateAuthClient, + createRespondToAuthChallengeClient, +} from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { RespondToAuthChallengeCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); const authConfig = { Cognito: { @@ -35,6 +41,9 @@ describe('confirmSignIn API happy path cases', () => { let handleChallengeNameSpy: jest.SpyInstance; const { username, password } = authAPITestParams.user1; + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); + beforeEach(async () => { cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); @@ -56,10 +65,14 @@ describe('confirmSignIn API happy path cases', () => { $metadata: {}, }), ); + + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); }); afterEach(() => { handleChallengeNameSpy.mockClear(); + mockInitiateAuth.mockClear(); + mockCreateInitiateAuthClient.mockClear(); }); afterAll(() => { @@ -234,20 +247,16 @@ describe('confirmSignIn API happy path cases', () => { const mockedUserSub = '1111-2222-3333-4444'; const activeSignInSession = '1234234232'; const activeChallengeName = 'SMS_MFA'; - const initiateAuthSpy = jest - .spyOn(clients, 'initiateAuth') - .mockImplementationOnce( - async (): Promise => ({ - ChallengeName: activeChallengeName, - Session: activeSignInSession, - $metadata: {}, - ChallengeParameters: { - USER_ID_FOR_SRP: mockedUserSub, - CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', - CODE_DELIVERY_DESTINATION: '*******9878', - }, - }), - ); + mockInitiateAuth.mockResolvedValueOnce({ + ChallengeName: activeChallengeName, + Session: activeSignInSession, + $metadata: {}, + ChallengeParameters: { + USER_ID_FOR_SRP: mockedUserSub, + CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', + CODE_DELIVERY_DESTINATION: '*******9878', + }, + }); await signIn({ username, password, @@ -260,6 +269,7 @@ describe('confirmSignIn API happy path cases', () => { options: authAPITestParams.configWithClientMetadata, }); const options = authAPITestParams.configWithClientMetadata; + expect(handleChallengeNameSpy).toHaveBeenCalledWith( mockedUserSub, activeChallengeName, @@ -270,14 +280,17 @@ describe('confirmSignIn API happy path cases', () => { authAPITestParams.configWithClientMetadata.clientMetadata, options, ); - initiateAuthSpy.mockClear(); }); }); describe('Cognito ASF', () => { - let respondToAuthChallengeSpy: jest.SpyInstance; let handleUserSRPAuthFlowSpy: jest.SpyInstance; + const mockRespondToAuthChallenge = jest.fn(); + const mockCreateRespondToAuthChallengeClient = jest.mocked( + createRespondToAuthChallengeClient, + ); + const { username } = authAPITestParams.user1; const { password } = authAPITestParams.user1; beforeEach(() => { @@ -292,30 +305,28 @@ describe('Cognito ASF', () => { }, }; - respondToAuthChallengeSpy = jest - .spyOn(clients, 'respondToAuthChallenge') - .mockImplementation( - async (): Promise => { - return { - Session: '1234234232', - $metadata: {}, - ChallengeName: undefined, - ChallengeParameters: {}, - AuthenticationResult: { - AccessToken: - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0', - ExpiresIn: 1000, - IdToken: - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0', - RefreshToken: 'qwersfsafsfssfasf', - }, - }; - }, - ); + mockRespondToAuthChallenge.mockResolvedValueOnce({ + Session: '1234234232', + $metadata: {}, + ChallengeName: undefined, + ChallengeParameters: {}, + AuthenticationResult: { + AccessToken: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0', + ExpiresIn: 1000, + IdToken: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0', + RefreshToken: 'qwersfsafsfssfasf', + }, + }); + mockCreateRespondToAuthChallengeClient.mockReturnValueOnce( + mockRespondToAuthChallenge, + ); }); afterEach(() => { - respondToAuthChallengeSpy.mockClear(); + mockRespondToAuthChallenge.mockClear(); + mockCreateRespondToAuthChallengeClient.mockClear(); handleUserSRPAuthFlowSpy.mockClear(); (window as any).AmazonCognitoAdvancedSecurityData = undefined; }); @@ -342,15 +353,11 @@ describe('Cognito ASF', () => { expect(result.isSignedIn).toBe(false); expect(result.nextStep.signInStep).toBe('CONFIRM_SIGN_IN_WITH_SMS_CODE'); - try { - await confirmSignIn({ - challengeResponse: '777', - }); - } catch (err) { - console.log(err); - } - - expect(respondToAuthChallengeSpy).toHaveBeenCalledWith( + await confirmSignIn({ + challengeResponse: '777', + }); + + expect(mockRespondToAuthChallenge).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), @@ -384,15 +391,11 @@ describe('Cognito ASF', () => { expect(result.nextStep.signInStep).toBe( 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION', ); - try { - await confirmSignIn({ - challengeResponse: 'SMS', - }); - } catch (err) { - console.log(err); - } - - expect(respondToAuthChallengeSpy).toHaveBeenCalledWith( + await confirmSignIn({ + challengeResponse: 'SMS', + }); + + expect(mockRespondToAuthChallenge).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), @@ -427,15 +430,11 @@ describe('Cognito ASF', () => { expect(result.isSignedIn).toBe(false); expect(result.nextStep.signInStep).toBe('CONFIRM_SIGN_IN_WITH_TOTP_CODE'); - try { - await confirmSignIn({ - challengeResponse: '123456', - }); - } catch (err) { - console.log(err); - } - - expect(respondToAuthChallengeSpy).toHaveBeenCalledWith( + await confirmSignIn({ + challengeResponse: '123456', + }); + + expect(mockRespondToAuthChallenge).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), @@ -472,15 +471,11 @@ describe('Cognito ASF', () => { expect(result.nextStep.signInStep).toBe( 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED', ); - try { - await confirmSignIn({ - challengeResponse: 'password', - }); - } catch (err) { - console.log(err); - } - - expect(respondToAuthChallengeSpy).toHaveBeenCalledWith( + await confirmSignIn({ + challengeResponse: 'password', + }); + + expect(mockRespondToAuthChallenge).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), @@ -516,15 +511,11 @@ describe('Cognito ASF', () => { expect(result.nextStep.signInStep).toBe( 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE', ); - try { - await confirmSignIn({ - challengeResponse: 'secret-answer', - }); - } catch (err) { - console.log(err); - } - - expect(respondToAuthChallengeSpy).toHaveBeenCalledWith( + await confirmSignIn({ + challengeResponse: 'secret-answer', + }); + + expect(mockRespondToAuthChallenge).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), diff --git a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts index e6528e4b1ed..3523f9495aa 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts @@ -4,16 +4,22 @@ import { Amplify } from '@aws-amplify/core'; import { confirmSignUp } from '../../../src/providers/cognito'; -import { confirmSignUp as providerConfirmSignUp } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { AuthError } from '../../../src/errors/AuthError'; import { ConfirmSignUpException } from '../../../src/providers/cognito/types/errors'; -import { ConfirmSignUpCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; +import { createConfirmSignUpClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; +import { ConfirmSignUpCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); +jest.mock('../../../src/providers/cognito/factories'); + jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), Amplify: { getConfig: jest.fn(() => ({})) }, @@ -22,15 +28,16 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); -jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', -); describe('confirmSignUp', () => { const { user1 } = authAPITestParams; const confirmationCode = '123456'; // assert mocks - const mockConfirmSignUp = providerConfirmSignUp as jest.Mock; + const mockConfirmSignUp = jest.fn(); + const mockCreateConfirmSignUpClient = jest.mocked(createConfirmSignUpClient); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -38,10 +45,13 @@ describe('confirmSignUp', () => { beforeEach(() => { mockConfirmSignUp.mockResolvedValue({} as ConfirmSignUpCommandOutput); + mockCreateConfirmSignUpClient.mockReturnValueOnce(mockConfirmSignUp); }); afterEach(() => { mockConfirmSignUp.mockReset(); + mockCreateConfirmSignUpClient.mockClear(); + mockCreateCognitoUserPoolEndpointResolver.mockClear(); }); it('should call confirmSignUp and return a SignUpResult', async () => { @@ -68,6 +78,29 @@ describe('confirmSignUp', () => { expect(mockConfirmSignUp).toHaveBeenCalledTimes(1); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + + await confirmSignUp({ + username: user1.username, + confirmationCode, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should contain force alias creation', async () => { await confirmSignUp({ username: user1.username, diff --git a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts index 3c7961d125a..56608241897 100644 --- a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts @@ -7,8 +7,9 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { confirmUserAttribute } from '../../../src/providers/cognito'; import { VerifyUserAttributeException } from '../../../src/providers/cognito/types/errors'; -import { verifyUserAttribute } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; +import { createVerifyUserAttributeClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -22,14 +23,21 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('confirmUserAttribute', () => { const confirmationCode = '123456'; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockVerifyUserAttribute = verifyUserAttribute as jest.Mock; + const mockVerifyUserAttribute = jest.fn(); + const mockCreateVerifyUserAttributeClient = jest.mocked( + createVerifyUserAttributeClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -40,11 +48,15 @@ describe('confirmUserAttribute', () => { beforeEach(() => { mockVerifyUserAttribute.mockResolvedValue({ $metadata: {} }); + mockCreateVerifyUserAttributeClient.mockReturnValueOnce( + mockVerifyUserAttribute, + ); }); afterEach(() => { mockVerifyUserAttribute.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateVerifyUserAttributeClient.mockClear(); }); it('should call the service', async () => { @@ -63,6 +75,28 @@ describe('confirmUserAttribute', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await confirmUserAttribute({ + userAttributeKey: 'email', + confirmationCode, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when confirmationCode is not defined', async () => { try { await confirmUserAttribute({ diff --git a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts index ec1cf3a90d9..b56e9736e12 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts @@ -7,9 +7,10 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { deleteUser } from '../../../src/providers/cognito'; import { tokenOrchestrator } from '../../../src/providers/cognito/tokenProvider'; -import { deleteUser as providerDeleteUser } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { DeleteUserException } from '../../../src/providers/cognito/types/errors'; import { signOut } from '../../../src/providers/cognito/apis/signOut'; +import { createDeleteUserClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -23,18 +24,23 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock('../../../src/providers/cognito/apis/signOut'); +jest.mock('../../../src/providers/cognito/tokenProvider'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); -jest.mock('../../../src/providers/cognito/tokenProvider'); +jest.mock('../../../src/providers/cognito/factories'); describe('deleteUser', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockDeleteUser = providerDeleteUser as jest.Mock; + const mockDeleteUser = jest.fn(); + const mockCreateDeleteUserClient = jest.mocked(createDeleteUserClient); const mockSignOut = signOut as jest.Mock; const mockClearDeviceMetadata = tokenOrchestrator.clearDeviceMetadata as jest.Mock; + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -45,12 +51,14 @@ describe('deleteUser', () => { beforeEach(() => { mockDeleteUser.mockResolvedValue({ $metadata: {} }); + mockCreateDeleteUserClient.mockReturnValueOnce(mockDeleteUser); }); afterEach(() => { mockDeleteUser.mockReset(); mockClearDeviceMetadata.mockClear(); mockFetchAuthSession.mockClear(); + mockCreateDeleteUserClient.mockClear(); }); it('should delete user, sign out and clear device tokens', async () => { @@ -72,6 +80,25 @@ describe('deleteUser', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await deleteUser(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockDeleteUser.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts index 959592a5b87..c791b224fdb 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts @@ -7,7 +7,8 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { deleteUserAttributes } from '../../../src/providers/cognito'; import { DeleteUserAttributesException } from '../../../src/providers/cognito/types/errors'; -import { deleteUserAttributes as providerDeleteUserAttributes } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createDeleteUserAttributesClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -21,13 +22,20 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('deleteUserAttributes', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockDeleteUserAttributes = providerDeleteUserAttributes as jest.Mock; + const mockDeleteUserAttributes = jest.fn(); + const mockCreateDeleteUserAttributesClient = jest.mocked( + createDeleteUserAttributesClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -38,11 +46,15 @@ describe('deleteUserAttributes', () => { beforeEach(() => { mockDeleteUserAttributes.mockResolvedValue({ $metadata: {} }); + mockCreateDeleteUserAttributesClient.mockReturnValueOnce( + mockDeleteUserAttributes, + ); }); afterEach(() => { mockDeleteUserAttributes.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateDeleteUserAttributesClient.mockClear(); }); it('should delete user attributes', async () => { @@ -60,6 +72,27 @@ describe('deleteUserAttributes', () => { expect(mockDeleteUserAttributes).toHaveBeenCalledTimes(1); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await deleteUserAttributes({ + userAttributeKeys: ['given_name', 'address'], + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockDeleteUserAttributes.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts index 1e8a48ab84e..4cdb79a13bd 100644 --- a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts @@ -6,8 +6,9 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { fetchDevices } from '../../../src/providers/cognito'; -import { listDevices } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { ListDevicesException } from '../../../src/providers/cognito/types/errors'; +import { createListDevicesClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -21,8 +22,9 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('fetchDevices', () => { const dateEpoch = 1.696296885807e9; @@ -51,7 +53,11 @@ describe('fetchDevices', () => { }; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockListDevices = listDevices as jest.Mock; + const mockListDevices = jest.fn(); + const mockCreateListDevicesClient = jest.mocked(createListDevicesClient); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -65,11 +71,13 @@ describe('fetchDevices', () => { Devices: [clientResponseDevice], $metadata: {}, }); + mockCreateListDevicesClient.mockReturnValueOnce(mockListDevices); }); afterEach(() => { mockListDevices.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateListDevicesClient.mockClear(); }); it('should fetch devices and parse client response correctly', async () => { @@ -84,6 +92,25 @@ describe('fetchDevices', () => { expect(mockListDevices).toHaveBeenCalledTimes(1); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await fetchDevices(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockListDevices.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts index ed2517a358e..c4d8a7a9efa 100644 --- a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts @@ -4,10 +4,11 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import { getUser } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthError } from '../../../src/errors/AuthError'; import { fetchMFAPreference } from '../../../src/providers/cognito/apis/fetchMFAPreference'; import { GetUserException } from '../../../src/providers/cognito/types/errors'; +import { createGetUserClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -17,13 +18,18 @@ jest.mock('@aws-amplify/core', () => ({ Amplify: { getConfig: jest.fn(() => ({})) }, })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('fetchMFAPreference', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockGetUser = getUser as jest.Mock; + const mockGetUser = jest.fn(); + const mockCreateGetUserClient = jest.mocked(createGetUserClient); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -40,6 +46,7 @@ describe('fetchMFAPreference', () => { UserMFASettingList: ['SMS_MFA', 'SOFTWARE_TOKEN_MFA'], $metadata: {}, }); + mockCreateGetUserClient.mockReturnValueOnce(mockGetUser); }); afterEach(() => { @@ -62,6 +69,25 @@ describe('fetchMFAPreference', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await fetchMFAPreference(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockGetUser.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts index cff5ff01b64..87cf79e715d 100644 --- a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts @@ -4,10 +4,11 @@ import { Amplify } from '@aws-amplify/core'; import { decodeJWT, fetchAuthSession } from '@aws-amplify/core/internals/utils'; -import { getUser } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthError } from '../../../src/errors/AuthError'; import { GetUserException } from '../../../src/providers/cognito/types/errors'; import { fetchUserAttributes } from '../../../src/providers/cognito/apis/fetchUserAttributes'; +import { createGetUserClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -21,13 +22,18 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ fetchAuthSession: jest.fn(), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('fetchUserAttributes', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockGetUser = getUser as jest.Mock; + const mockGetUser = jest.fn(); + const mockCreateGetUserClient = jest.mocked(createGetUserClient); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -47,11 +53,13 @@ describe('fetchUserAttributes', () => { UserMFASettingList: ['SMS_MFA', 'SOFTWARE_TOKEN_MFA'], $metadata: {}, }); + mockCreateGetUserClient.mockReturnValueOnce(mockGetUser); }); afterEach(() => { mockGetUser.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateGetUserClient.mockClear(); }); it('should return the current user attributes into a map format', async () => { @@ -71,6 +79,25 @@ describe('fetchUserAttributes', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await fetchUserAttributes(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockGetUser.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts index 6371e2b41a8..cc0a2d37407 100644 --- a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts @@ -8,8 +8,9 @@ import { AuthError } from '../../../src/errors/AuthError'; import { DEVICE_METADATA_NOT_FOUND_EXCEPTION } from '../../../src/errors/constants'; import { forgetDevice } from '../../../src/providers/cognito'; import { ForgetDeviceException } from '../../../src/providers/cognito/types/errors'; -import { forgetDevice as providerForgetDevice } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { tokenOrchestrator } from '../../../src/providers/cognito/tokenProvider'; +import { createForgetDeviceClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -22,10 +23,11 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); +jest.mock('../../../src/providers/cognito/tokenProvider'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); -jest.mock('../../../src/providers/cognito/tokenProvider'); +jest.mock('../../../src/providers/cognito/factories'); describe('fetchMFAPreference', () => { const mockDeviceMetadata = { @@ -35,11 +37,15 @@ describe('fetchMFAPreference', () => { }; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockForgetDevice = providerForgetDevice as jest.Mock; + const mockForgetDevice = jest.fn(); + const mockCreateForgetDeviceClient = jest.mocked(createForgetDeviceClient); const mockClearDeviceMetadata = tokenOrchestrator.clearDeviceMetadata as jest.Mock; const mockGetDeviceMetadata = tokenOrchestrator.getDeviceMetadata as jest.Mock; + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -51,6 +57,7 @@ describe('fetchMFAPreference', () => { beforeEach(() => { mockForgetDevice.mockResolvedValue({ $metadata: {} }); mockGetDeviceMetadata.mockResolvedValue(mockDeviceMetadata); + mockCreateForgetDeviceClient.mockReturnValueOnce(mockForgetDevice); }); afterEach(() => { @@ -58,6 +65,7 @@ describe('fetchMFAPreference', () => { mockGetDeviceMetadata.mockReset(); mockFetchAuthSession.mockClear(); mockClearDeviceMetadata.mockClear(); + mockCreateForgetDeviceClient.mockClear(); }); it(`should forget 'external device' 'with' inputParams when tokenStore deviceMetadata 'present'`, async () => { @@ -74,6 +82,25 @@ describe('fetchMFAPreference', () => { expect(mockClearDeviceMetadata).not.toHaveBeenCalled(); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await forgetDevice({ device: { id: 'externalDeviceKey' } }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it(`should forget 'current device' 'with' inputParams when tokenStore deviceMetadata 'present'`, async () => { expect.assertions(3); await forgetDevice({ device: { id: mockDeviceMetadata.deviceKey } }); diff --git a/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts b/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts index 5f82457a4b9..6058fc363b7 100644 --- a/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts +++ b/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts @@ -5,11 +5,17 @@ import { Amplify } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { ConfirmDeviceException } from '../../../src/providers/cognito/types/errors'; -import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { ConfirmDeviceCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { getNewDeviceMetadata } from '../../../src/providers/cognito/utils/signInHelpers'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; +import { createConfirmDeviceClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; + +jest.mock('../../../src/providers/cognito/factories'); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); const userPoolId = 'us-west-2_zzzzz'; + Amplify.configure({ Auth: { Cognito: { @@ -22,66 +28,95 @@ Amplify.configure({ const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; +const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, +); + describe('test getNewDeviceMetadata API', () => { + const mockConfirmDevice = jest.fn(); + const mockCreateConfirmDeviceClient = jest.mocked(createConfirmDeviceClient); + + beforeEach(() => { + mockCreateConfirmDeviceClient.mockReturnValueOnce(mockConfirmDevice); + }); + + afterEach(() => { + mockConfirmDevice.mockClear(); + mockCreateConfirmDeviceClient.mockClear(); + }); + test('getNewDeviceMetadata should call confirmDevice and return DeviceMetadata', async () => { - const confirmDeviceClientSpy = jest - .spyOn(clients, 'confirmDevice') - .mockImplementationOnce(async (): Promise => { - return { UserConfirmationNecessary: true, $metadata: {} }; - }); + mockConfirmDevice.mockResolvedValueOnce({ + UserConfirmationNecessary: true, + $metadata: {}, + }); + const mockedDeviceKey = 'mockedDeviceKey'; const mockedGroupDeviceKey = 'mockedGroupDeviceKey'; - const deviceMetadata = await getNewDeviceMetadata( + const deviceMetadata = await getNewDeviceMetadata({ userPoolId, - { + userPoolEndpoint: undefined, + newDeviceMetadata: { DeviceKey: mockedDeviceKey, DeviceGroupKey: mockedGroupDeviceKey, }, - mockedAccessToken, - ); + accessToken: mockedAccessToken, + }); expect(deviceMetadata?.deviceKey).toBe(mockedDeviceKey); expect(deviceMetadata?.deviceGroupKey).toBe(mockedGroupDeviceKey); - expect(confirmDeviceClientSpy).toHaveBeenCalledWith( + expect(mockConfirmDevice).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2' }), expect.objectContaining({ AccessToken: mockedAccessToken, DeviceKey: mockedDeviceKey, }), ); - - confirmDeviceClientSpy.mockClear(); }); test('getNewDeviceMetadata should return undefined when ConfirmDevice throws an error', async () => { - const confirmDeviceClientSpy = jest - .spyOn(clients, 'confirmDevice') - .mockImplementationOnce(async (): Promise => { - throw new AuthError({ - name: ConfirmDeviceException.InternalErrorException, - message: 'error while calling confirmDevice', - }); - }); + mockConfirmDevice.mockRejectedValueOnce( + new AuthError({ + name: ConfirmDeviceException.InternalErrorException, + message: 'error while calling confirmDevice', + }), + ); const mockedDeviceKey = 'mockedDeviceKey'; const mockedGroupDeviceKey = 'mockedGroupDeviceKey'; - const deviceMetadata = await getNewDeviceMetadata( + const deviceMetadata = await getNewDeviceMetadata({ userPoolId, - { + userPoolEndpoint: undefined, + newDeviceMetadata: { DeviceKey: mockedDeviceKey, DeviceGroupKey: mockedGroupDeviceKey, }, - mockedAccessToken, - ); + accessToken: mockedAccessToken, + }); expect(deviceMetadata).toBeUndefined(); - expect(confirmDeviceClientSpy).toHaveBeenCalledWith( + expect(mockConfirmDevice).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2' }), expect.objectContaining({ AccessToken: mockedAccessToken, DeviceKey: mockedDeviceKey, }), ); + }); + + it('invokes createCognitoUserPoolEndpointResolver with expected userPoolEndpoint parameter', async () => { + const expectedEndpoint = 'https://custom-endpoint.com'; + await getNewDeviceMetadata({ + userPoolId, + userPoolEndpoint: expectedEndpoint, + newDeviceMetadata: { + DeviceKey: 'devicekey', + DeviceGroupKey: 'groupkey', + }, + accessToken: mockedAccessToken, + }); - confirmDeviceClientSpy.mockClear(); + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedEndpoint, + }); }); }); diff --git a/packages/auth/__tests__/providers/cognito/refreshToken.test.ts b/packages/auth/__tests__/providers/cognito/refreshToken.test.ts index 86ac80a1fee..bef5cb28d61 100644 --- a/packages/auth/__tests__/providers/cognito/refreshToken.test.ts +++ b/packages/auth/__tests__/providers/cognito/refreshToken.test.ts @@ -2,23 +2,39 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { refreshAuthTokens } from '../../../src/providers/cognito/utils/refreshAuthTokens'; import { CognitoAuthTokens } from '../../../src/providers/cognito/tokenProvider/types'; -import { initiateAuth } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { oAuthTokenRefreshException, tokenRefreshException, } from '../../../src/providers/cognito/utils/types'; +import { createInitiateAuthClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { mockAccessToken, mockRequestId } from './testUtils/data'; jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); +jest.mock('../../../src/providers/cognito/factories'); + +const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); +const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, ); describe('refreshToken', () => { const mockedUsername = 'mockedUsername'; const mockedRefreshToken = 'mockedRefreshToken'; - // assert mocks - const mockInitiateAuth = initiateAuth as jest.Mock; + const mockInitiateAuth = jest.fn(); + + beforeEach(() => { + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); + }); + + afterEach(() => { + mockCreateInitiateAuthClient.mockClear(); + mockCreateCognitoUserPoolEndpointResolver.mockClear(); + }); + describe('positive cases', () => { beforeEach(() => { mockInitiateAuth.mockResolvedValue({ @@ -119,6 +135,39 @@ describe('refreshToken', () => { ); (window as any).AmazonCognitoAdvancedSecurityData = undefined; }); + + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected parameters', async () => { + const expectedParam = 'https://my-custom-endpoint.com'; + const expectedEndpointResolver = jest.fn(); + mockCreateCognitoUserPoolEndpointResolver.mockReturnValueOnce( + expectedEndpointResolver, + ); + + await refreshAuthTokens({ + username: 'username', + tokens: { + accessToken: { payload: {} }, + idToken: { payload: {} }, + clockDrift: 0, + refreshToken: 'refreshtoken', + username: 'username', + }, + authConfig: { + Cognito: { + userPoolId: 'us-east-1_aaaaaaa', + userPoolClientId: 'aaaaaaaaaaaa', + userPoolEndpoint: expectedParam, + }, + }, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedParam, + }); + expect(mockCreateInitiateAuthClient).toHaveBeenCalledWith({ + endpointResolver: expectedEndpointResolver, + }); + }); }); describe('negative cases', () => { @@ -153,6 +202,7 @@ describe('refreshToken', () => { }), ).rejects.toThrow(oAuthTokenRefreshException); }); + it('should throw an exception when cognito tokens are not available', async () => { await expect( refreshAuthTokens({ diff --git a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts index 820b2a1ef5f..0521e928654 100644 --- a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts @@ -7,9 +7,10 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { rememberDevice } from '../../../src/providers/cognito'; import { UpdateDeviceStatusException } from '../../../src/providers/cognito/types/errors'; -import { updateDeviceStatus } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { tokenOrchestrator } from '../../../src/providers/cognito/tokenProvider'; import { DeviceMetadata } from '../../../src/providers/cognito/tokenProvider/types'; +import { createUpdateDeviceStatusClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -23,8 +24,9 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); jest.mock('../../../src/providers/cognito/tokenProvider'); describe('rememberDevice', () => { @@ -35,7 +37,13 @@ describe('rememberDevice', () => { }; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockUpdateDeviceStatus = updateDeviceStatus as jest.Mock; + const mockUpdateDeviceStatus = jest.fn(); + const mockCreateUpdateDeviceStatusClient = jest.mocked( + createUpdateDeviceStatusClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); const mockGetDeviceMetadata = tokenOrchestrator.getDeviceMetadata as jest.Mock; @@ -49,12 +57,16 @@ describe('rememberDevice', () => { beforeEach(() => { mockGetDeviceMetadata.mockResolvedValue(mockDeviceMetadata); mockUpdateDeviceStatus.mockResolvedValue({ $metadata: {} }); + mockCreateUpdateDeviceStatusClient.mockReturnValueOnce( + mockUpdateDeviceStatus, + ); }); afterEach(() => { mockGetDeviceMetadata.mockReset(); mockUpdateDeviceStatus.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateUpdateDeviceStatusClient.mockClear(); }); it('should call updateDeviceStatus client with correct request', async () => { @@ -71,6 +83,25 @@ describe('rememberDevice', () => { expect(mockUpdateDeviceStatus).toHaveBeenCalledTimes(1); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await rememberDevice(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockUpdateDeviceStatus.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts index d723a69eda8..d351a950484 100644 --- a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts @@ -7,7 +7,8 @@ import { resendSignUpCode } from '../../../src/providers/cognito'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { AuthError } from '../../../src/errors/AuthError'; import { ResendConfirmationException } from '../../../src/providers/cognito/types/errors'; -import { resendConfirmationCode } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createResendConfirmationCodeClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError } from './testUtils/data'; @@ -22,13 +23,20 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('resendSignUpCode', () => { const { user1 } = authAPITestParams; // assert mocks - const mockResendConfirmationCode = resendConfirmationCode as jest.Mock; + const mockResendConfirmationCode = jest.fn(); + const mockCreateResendConfirmationCodeClient = jest.mocked( + createResendConfirmationCodeClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -38,6 +46,9 @@ describe('resendSignUpCode', () => { mockResendConfirmationCode.mockResolvedValue( authAPITestParams.resendSignUpClientResult, ); + mockCreateResendConfirmationCodeClient.mockReturnValueOnce( + mockResendConfirmationCode, + ); }); afterEach(() => { @@ -63,6 +74,26 @@ describe('resendSignUpCode', () => { expect(mockResendConfirmationCode).toHaveBeenCalledTimes(1); }); + it('invokes createCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await resendSignUpCode({ + username: user1.username, + }); + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when username is empty', async () => { expect.assertions(2); try { diff --git a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts index 3432ae17c0a..41deeeb170a 100644 --- a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts @@ -6,7 +6,8 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { resetPassword } from '../../../src/providers/cognito'; import { ForgotPasswordException } from '../../../src/providers/cognito/types/errors'; -import { forgotPassword } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createForgotPasswordClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError } from './testUtils/data'; @@ -21,12 +22,19 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('resetPassword', () => { // assert mocks - const mockForgotPassword = forgotPassword as jest.Mock; + const mockForgotPassword = jest.fn(); + const mockCreateForgotPasswordClient = jest.mocked( + createForgotPasswordClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -36,10 +44,13 @@ describe('resetPassword', () => { mockForgotPassword.mockResolvedValue( authAPITestParams.resetPasswordHttpCallResult, ); + mockCreateForgotPasswordClient.mockReturnValueOnce(mockForgotPassword); }); afterEach(() => { mockForgotPassword.mockReset(); + mockCreateForgotPasswordClient.mockClear(); + mockCreateCognitoUserPoolEndpointResolver.mockClear(); }); it('should call forgotPassword and return a result', async () => { @@ -47,6 +58,26 @@ describe('resetPassword', () => { expect(result).toEqual(authAPITestParams.resetPasswordResult); }); + it('invokes createCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + + await resetPassword(authAPITestParams.resetPasswordRequest); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should contain clientMetadata from request', async () => { await resetPassword({ username: 'username', diff --git a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts index 2b236d1db5a..31376edf642 100644 --- a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts @@ -7,7 +7,8 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { sendUserAttributeVerificationCode } from '../../../src/providers/cognito'; import { GetUserAttributeVerificationException } from '../../../src/providers/cognito/types/errors'; -import { getUserAttributeVerificationCode } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createGetUserAttributeVerificationCodeClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError, mockAccessToken } from './testUtils/data'; @@ -22,14 +23,20 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('sendUserAttributeVerificationCode', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockGetUserAttributeVerificationCode = - getUserAttributeVerificationCode as jest.Mock; + const mockGetUserAttributeVerificationCode = jest.fn(); + const mockCreateGetUserAttributeVerificationCodeClient = jest.mocked( + createGetUserAttributeVerificationCodeClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -42,11 +49,15 @@ describe('sendUserAttributeVerificationCode', () => { mockGetUserAttributeVerificationCode.mockResolvedValue( authAPITestParams.resendSignUpClientResult, ); + mockCreateGetUserAttributeVerificationCodeClient.mockReturnValueOnce( + mockGetUserAttributeVerificationCode, + ); }); afterEach(() => { mockGetUserAttributeVerificationCode.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateGetUserAttributeVerificationCodeClient.mockClear(); }); it('should return a result', async () => { @@ -69,6 +80,30 @@ describe('sendUserAttributeVerificationCode', () => { expect(mockGetUserAttributeVerificationCode).toHaveBeenCalledTimes(1); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await sendUserAttributeVerificationCode({ + userAttributeKey: 'email', + options: { + clientMetadata: { foo: 'bar' }, + }, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockGetUserAttributeVerificationCode.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts index 1f7399093cc..1a7d0cfbc4b 100644 --- a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts +++ b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts @@ -6,8 +6,9 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { AssociateSoftwareTokenException } from '../../../src/providers/cognito/types/errors'; -import { associateSoftwareToken } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { setUpTOTP } from '../../../src/providers/cognito'; +import { createAssociateSoftwareTokenClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -21,14 +22,21 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('setUpTOTP', () => { const secretCode = 'secret-code'; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockAssociateSoftwareToken = associateSoftwareToken as jest.Mock; + const mockAssociateSoftwareToken = jest.fn(); + const mockCreateAssociateSoftwareTokenClient = jest.mocked( + createAssociateSoftwareTokenClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -42,11 +50,15 @@ describe('setUpTOTP', () => { SecretCode: secretCode, $metadata: {}, }); + mockCreateAssociateSoftwareTokenClient.mockReturnValueOnce( + mockAssociateSoftwareToken, + ); }); afterEach(() => { mockAssociateSoftwareToken.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateAssociateSoftwareTokenClient.mockClear(); }); it('setUpTOTP API should call the UserPoolClient and should return a TOTPSetupDetails', async () => { @@ -64,6 +76,26 @@ describe('setUpTOTP', () => { expect(result.getSetupUri('appName', 'amplify')).toBeInstanceOf(URL); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + + await setUpTOTP(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockAssociateSoftwareToken.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts index b4e8453b17d..f66241497f3 100644 --- a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts @@ -6,9 +6,9 @@ import { Amplify } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { getCurrentUser, signIn } from '../../../src/providers/cognito'; -import { initiateAuth } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; +import { createInitiateAuthClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError } from './testUtils/data'; @@ -24,18 +24,23 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ })); jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); describe('signIn API error path cases:', () => { // assert mocks - const mockInitiateAuth = initiateAuth as jest.Mock; + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); + const mockInitiateAuth = jest.fn(); const mockedGetCurrentUser = getCurrentUser as jest.Mock; beforeAll(() => { setUpGetConfig(Amplify); }); + beforeEach(() => { + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); + }); + afterEach(() => { mockedGetCurrentUser.mockReset(); mockInitiateAuth.mockClear(); diff --git a/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts b/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts index dcefb80a121..80006cbf675 100644 --- a/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts @@ -6,8 +6,8 @@ import { Amplify } from '@aws-amplify/core'; import { getCurrentUser, signIn } from '../../../src/providers/cognito'; import * as signInHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { signInStore } from '../../../src/providers/cognito/utils/signInStore'; -import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { cognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; +import { RespondToAuthChallengeCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts index 87828e427f8..c9e5ec7ab68 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts @@ -6,12 +6,12 @@ import { Amplify } from 'aws-amplify'; import { signIn } from '../../../src/providers/cognito'; import { signInWithCustomAuth } from '../../../src/providers/cognito/apis/signInWithCustomAuth'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; -import { InitiateAuthCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; -import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createInitiateAuthClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { InitiateAuthCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; @@ -19,6 +19,9 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); const authConfig = { Cognito: { @@ -85,25 +88,23 @@ describe('signIn API happy path cases', () => { }); describe('Cognito ASF', () => { - let initiateAuthSpy: jest.SpyInstance; + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); afterAll(() => { jest.restoreAllMocks(); }); beforeEach(() => { - initiateAuthSpy = jest - .spyOn(clients, 'initiateAuth') - .mockImplementationOnce( - async (): Promise => ({ - ChallengeName: 'SMS_MFA', - Session: '1234234232', - $metadata: {}, - ChallengeParameters: { - CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', - CODE_DELIVERY_DESTINATION: '*******9878', - }, - }), - ); + mockInitiateAuth.mockResolvedValueOnce({ + ChallengeName: 'SMS_MFA', + Session: '1234234232', + $metadata: {}, + ChallengeParameters: { + CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', + CODE_DELIVERY_DESTINATION: '*******9878', + }, + }); + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); // load Cognito ASF polyfill (window as any).AmazonCognitoAdvancedSecurityData = { getData() { @@ -113,7 +114,7 @@ describe('Cognito ASF', () => { }); afterEach(() => { - initiateAuthSpy.mockClear(); + mockInitiateAuth.mockClear(); (window as any).AmazonCognitoAdvancedSecurityData = undefined; }); @@ -124,7 +125,7 @@ describe('Cognito ASF', () => { authFlowType: 'CUSTOM_WITHOUT_SRP', }, }); - expect(initiateAuthSpy).toHaveBeenCalledWith( + expect(mockInitiateAuth).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts index 108e928d683..5d6aa8a1740 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts @@ -6,12 +6,12 @@ import { Amplify } from 'aws-amplify'; import { signIn } from '../../../src/providers/cognito'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { signInWithCustomSRPAuth } from '../../../src/providers/cognito/apis/signInWithCustomSRPAuth'; -import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; -import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createInitiateAuthClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { RespondToAuthChallengeCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; @@ -20,6 +20,10 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); + const authConfig = { Cognito: { userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', @@ -92,22 +96,23 @@ describe('signIn API happy path cases', () => { }); describe('Cognito ASF', () => { - let initiateAuthSpy: jest.SpyInstance; + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); afterAll(() => { jest.restoreAllMocks(); }); beforeEach(() => { - initiateAuthSpy = jest - .spyOn(clients, 'initiateAuth') - .mockImplementationOnce(async () => ({ - ChallengeName: 'SRP_AUTH', - Session: '1234234232', - $metadata: {}, - ChallengeParameters: { - USER_ID_FOR_SRP: authAPITestParams.user1.username, - }, - })); + mockInitiateAuth.mockResolvedValueOnce({ + ChallengeName: 'SRP_AUTH', + Session: '1234234232', + $metadata: {}, + ChallengeParameters: { + USER_ID_FOR_SRP: authAPITestParams.user1.username, + }, + }); + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); + // load Cognito ASF polyfill (window as any).AmazonCognitoAdvancedSecurityData = { getData() { @@ -117,7 +122,8 @@ describe('Cognito ASF', () => { }); afterEach(() => { - initiateAuthSpy.mockClear(); + mockInitiateAuth.mockClear(); + mockCreateInitiateAuthClient.mockClear(); (window as any).AmazonCognitoAdvancedSecurityData = undefined; }); @@ -133,7 +139,7 @@ describe('Cognito ASF', () => { } catch (_) { // only want to test the contents } - expect(initiateAuthSpy).toHaveBeenCalledWith( + expect(mockInitiateAuth).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), diff --git a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts index c43e773f1d7..36c8d3c118a 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts @@ -6,14 +6,17 @@ import { Amplify } from 'aws-amplify'; import { signIn } from '../../../src/providers/cognito'; import { signInWithSRP } from '../../../src/providers/cognito/apis/signInWithSRP'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; -import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; import { AuthError } from '../../../src'; import { createKeysForAuthStorage } from '../../../src/providers/cognito/tokenProvider/TokenStore'; -import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { + createInitiateAuthClient, + createRespondToAuthChallengeClient, +} from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { RespondToAuthChallengeCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; @@ -33,6 +36,9 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); const authConfig = { Cognito: { @@ -193,15 +199,17 @@ describe('signIn API happy path cases', () => { }); describe('sign in with device keys', () => { - const initiateAuthSpy = jest.spyOn(clients, 'initiateAuth'); - const respondToAuthChallengeAuthSpy = jest.spyOn( - clients, - 'respondToAuthChallenge', + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); + const mockRespondToAuthChallenge = jest.fn(); + const mockCreateRespondToAuthChallengeClient = jest.mocked( + createRespondToAuthChallengeClient, ); + beforeEach(() => { setDeviceKeys(); handleUserSRPAuthflowSpy.mockRestore(); - initiateAuthSpy.mockResolvedValueOnce({ + mockInitiateAuth.mockResolvedValueOnce({ ChallengeName: 'SRP_AUTH', Session: '1234234232', $metadata: {}, @@ -209,14 +217,20 @@ describe('signIn API happy path cases', () => { USER_ID_FOR_SRP: lastAuthUser, }, }); - respondToAuthChallengeAuthSpy.mockResolvedValueOnce( + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); + mockRespondToAuthChallenge.mockResolvedValueOnce( authAPITestParams.RespondToAuthChallengeCommandOutput, ); + mockCreateRespondToAuthChallengeClient.mockReturnValueOnce( + mockRespondToAuthChallenge, + ); }); afterEach(() => { - initiateAuthSpy.mockClear(); - respondToAuthChallengeAuthSpy.mockClear(); + mockInitiateAuth.mockClear(); + mockCreateInitiateAuthClient.mockClear(); + mockRespondToAuthChallenge.mockClear(); + mockCreateRespondToAuthChallengeClient.mockClear(); }); test('respondToAuthChallenge should include device key in the request', async () => { @@ -225,9 +239,9 @@ describe('signIn API happy path cases', () => { password: 'XXXXXXXX', }); - expect(respondToAuthChallengeAuthSpy).toHaveBeenCalledTimes(1); + expect(mockRespondToAuthChallenge).toHaveBeenCalledTimes(1); const deviceKeyFromRequest = - respondToAuthChallengeAuthSpy.mock.calls[0][1].ChallengeResponses + mockRespondToAuthChallenge.mock.calls[0][1].ChallengeResponses ?.DEVICE_KEY; expect(deviceKeyFromRequest).toBe('mockedKey'); }); @@ -245,9 +259,9 @@ describe('signIn API happy path cases', () => { password: 'XXXXXXXX', }); - expect(respondToAuthChallengeAuthSpy).toHaveBeenCalledTimes(1); + expect(mockRespondToAuthChallenge).toHaveBeenCalledTimes(1); const deviceKeyFromRequest = - respondToAuthChallengeAuthSpy.mock.calls[0][1].ChallengeResponses + mockRespondToAuthChallenge.mock.calls[0][1].ChallengeResponses ?.DEVICE_KEY; expect(deviceKeyFromRequest).toBe(undefined); }, @@ -256,22 +270,23 @@ describe('signIn API happy path cases', () => { }); describe('Cognito ASF', () => { - let initiateAuthSpy: jest.SpyInstance; + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); beforeAll(() => { jest.restoreAllMocks(); }); + beforeEach(() => { - initiateAuthSpy = jest - .spyOn(clients, 'initiateAuth') - .mockImplementationOnce(async () => ({ - ChallengeName: 'SRP_AUTH', - Session: '1234234232', - $metadata: {}, - ChallengeParameters: { - USER_ID_FOR_SRP: authAPITestParams.user1.username, - }, - })); + mockInitiateAuth.mockResolvedValueOnce({ + ChallengeName: 'SRP_AUTH', + Session: '1234234232', + $metadata: {}, + ChallengeParameters: { + USER_ID_FOR_SRP: authAPITestParams.user1.username, + }, + }); + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); // load Cognito ASF polyfill (window as any).AmazonCognitoAdvancedSecurityData = { getData() { @@ -281,7 +296,8 @@ describe('Cognito ASF', () => { }); afterEach(() => { - initiateAuthSpy.mockClear(); + mockInitiateAuth.mockClear(); + mockCreateInitiateAuthClient.mockClear(); (window as any).AmazonCognitoAdvancedSecurityData = undefined; }); @@ -294,7 +310,7 @@ describe('Cognito ASF', () => { } catch (_) { // only want to test the contents } - expect(initiateAuthSpy).toHaveBeenCalledWith( + expect(mockInitiateAuth).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), diff --git a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts index 83f3a7d2813..d675ace40a2 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts @@ -6,12 +6,12 @@ import { Amplify } from 'aws-amplify'; import { signIn } from '../../../src/providers/cognito'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { signInWithUserPassword } from '../../../src/providers/cognito/apis/signInWithUserPassword'; -import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; -import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createInitiateAuthClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { RespondToAuthChallengeCommandOutput } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { authAPITestParams } from './testUtils/authApiTestParams'; @@ -20,21 +20,28 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); const authConfig = { Cognito: { userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', userPoolId: 'us-west-2_zzzzz', + userPoolEndpoint: 'https://custom-endpoint.com', }, }; -cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); -Amplify.configure({ - Auth: authConfig, -}); describe('signIn API happy path cases', () => { let handleUserPasswordFlowSpy: jest.SpyInstance; + beforeAll(() => { + Amplify.configure({ + Auth: authConfig, + }); + cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); + }); + beforeEach(() => { handleUserPasswordFlowSpy = jest .spyOn(initiateAuthHelpers, 'handleUserPasswordAuthFlow') @@ -60,7 +67,7 @@ describe('signIn API happy path cases', () => { expect(handleUserPasswordFlowSpy).toHaveBeenCalledTimes(1); }); - test('handleUserPasswordAuthFlow should be called with clientMetada from request', async () => { + test('handleUserPasswordAuthFlow should be called with clientMetadata from request', async () => { const { username } = authAPITestParams.user1; const { password } = authAPITestParams.user1; await signInWithUserPassword({ @@ -79,22 +86,19 @@ describe('signIn API happy path cases', () => { }); describe('Cognito ASF', () => { - let initiateAuthSpy: jest.SpyInstance; + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); - afterAll(() => { - jest.restoreAllMocks(); - }); beforeEach(() => { - initiateAuthSpy = jest - .spyOn(clients, 'initiateAuth') - .mockImplementationOnce(async () => ({ - ChallengeName: 'SRP_AUTH', - Session: '1234234232', - $metadata: {}, - ChallengeParameters: { - USER_ID_FOR_SRP: authAPITestParams.user1.username, - }, - })); + mockInitiateAuth.mockResolvedValueOnce({ + ChallengeName: 'SRP_AUTH', + Session: '1234234232', + $metadata: {}, + ChallengeParameters: { + USER_ID_FOR_SRP: authAPITestParams.user1.username, + }, + }); + mockCreateInitiateAuthClient.mockReturnValueOnce(mockInitiateAuth); // load Cognito ASF polyfill (window as any).AmazonCognitoAdvancedSecurityData = { getData() { @@ -104,7 +108,8 @@ describe('Cognito ASF', () => { }); afterEach(() => { - initiateAuthSpy.mockClear(); + mockInitiateAuth.mockClear(); + mockCreateInitiateAuthClient.mockClear(); (window as any).AmazonCognitoAdvancedSecurityData = undefined; }); @@ -120,7 +125,7 @@ describe('Cognito ASF', () => { } catch (_) { // only want to test the contents } - expect(initiateAuthSpy).toHaveBeenCalledWith( + expect(mockInitiateAuth).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-west-2', }), diff --git a/packages/auth/__tests__/providers/cognito/signOut.test.ts b/packages/auth/__tests__/providers/cognito/signOut.test.ts index adae8c494cc..cedf8bed06d 100644 --- a/packages/auth/__tests__/providers/cognito/signOut.test.ts +++ b/packages/auth/__tests__/providers/cognito/signOut.test.ts @@ -11,26 +11,26 @@ import { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils'; import { signOut } from '../../../src/providers/cognito/apis/signOut'; import { tokenOrchestrator } from '../../../src/providers/cognito/tokenProvider'; -import { - globalSignOut, - revokeToken, -} from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { getRegion } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/utils'; import { DefaultOAuthStore } from '../../../src/providers/cognito/utils/signInWithRedirectStore'; import { handleOAuthSignOut } from '../../../src/providers/cognito/utils/oauth'; import { AuthTokenStore } from '../../../src/providers/cognito/tokenProvider/types'; +import { + createGlobalSignOutClient, + createRevokeTokenClient, +} from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { getRegionFromUserPoolId } from '../../../src/foundation/core/parsers'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; jest.mock('@aws-amplify/core'); jest.mock('../../../src/providers/cognito/tokenProvider'); -jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', -); -jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/utils', -); jest.mock('../../../src/providers/cognito/utils/oauth'); jest.mock('../../../src/providers/cognito/utils/signInWithRedirectStore'); jest.mock('../../../src/utils'); +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); +jest.mock('../../../src/foundation/core/parsers'); +jest.mock('../../../src/providers/cognito/factories'); describe('signOut', () => { // eslint-disable-next-line camelcase @@ -54,15 +54,20 @@ describe('signOut', () => { // assert mocks const mockAmplify = Amplify as jest.Mocked; const mockClearCredentials = clearCredentials as jest.Mock; - const mockGetRegion = getRegion as jest.Mock; - const mockGlobalSignOut = globalSignOut as jest.Mock; + const mockGetRegionFromUserPoolId = jest.mocked(getRegionFromUserPoolId); + const mockGlobalSignOut = jest.fn(); + const mockCreateGlobalSignOutClient = jest.mocked(createGlobalSignOutClient); const mockHandleOAuthSignOut = handleOAuthSignOut as jest.Mock; const mockHub = Hub as jest.Mocked; - const mockRevokeToken = revokeToken as jest.Mock; + const mockRevokeToken = jest.fn(); + const mockedRevokeTokenClient = jest.mocked(createRevokeTokenClient); const mockTokenOrchestrator = tokenOrchestrator as jest.Mocked< typeof tokenOrchestrator >; const MockDefaultOAuthStore = DefaultOAuthStore as jest.Mock; + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); // create mocks const mockLoadTokens = jest.fn(); const mockAuthTokenStore = { @@ -95,7 +100,7 @@ describe('signOut', () => { }); beforeAll(() => { - mockGetRegion.mockReturnValue(region); + mockGetRegionFromUserPoolId.mockReturnValue(region); MockDefaultOAuthStore.mockImplementation( () => mockDefaultOAuthStoreInstance, ); @@ -104,7 +109,9 @@ describe('signOut', () => { beforeEach(() => { mockAmplify.getConfig.mockReturnValue({ Auth: { Cognito: cognitoConfig } }); mockGlobalSignOut.mockResolvedValue({ $metadata: {} }); + mockCreateGlobalSignOutClient.mockReturnValueOnce(mockGlobalSignOut); mockRevokeToken.mockResolvedValue({}); + mockedRevokeTokenClient.mockReturnValueOnce(mockRevokeToken); mockTokenOrchestrator.getTokenStore.mockReturnValue(mockAuthTokenStore); mockLoadTokens.mockResolvedValue(cognitoAuthTokens); }); @@ -114,10 +121,11 @@ describe('signOut', () => { mockGlobalSignOut.mockReset(); mockRevokeToken.mockReset(); mockClearCredentials.mockClear(); - mockGetRegion.mockClear(); + mockGetRegionFromUserPoolId.mockClear(); mockHub.dispatch.mockClear(); mockTokenOrchestrator.clearTokens.mockClear(); loggerDebugSpy.mockClear(); + mockCreateCognitoUserPoolEndpointResolver.mockClear(); }); describe('Without OAuth configured', () => { @@ -128,11 +136,36 @@ describe('signOut', () => { { region }, { ClientId: cognitoConfig.userPoolClientId, Token: refreshToken }, ); - expect(mockGetRegion).toHaveBeenCalledTimes(1); + expect(mockGetRegionFromUserPoolId).toHaveBeenCalledTimes(1); expect(mockGlobalSignOut).not.toHaveBeenCalled(); expectSignOut().toComplete(); }); + it('invokes createCognitoUserPoolEndpointResolver with the userPoolEndpoint for creating the revokeToken client', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + const expectedEndpointResolver = jest.fn(); + mockAmplify.getConfig.mockReturnValueOnce({ + Auth: { + Cognito: { + ...cognitoConfig, + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + mockCreateCognitoUserPoolEndpointResolver.mockReturnValueOnce( + expectedEndpointResolver, + ); + + await signOut(); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + expect(mockedRevokeTokenClient).toHaveBeenCalledWith({ + endpointResolver: expectedEndpointResolver, + }); + }); + it('should perform client sign out on an irrevocable session', async () => { mockLoadTokens.mockResolvedValue({ ...cognitoAuthTokens, @@ -143,7 +176,7 @@ describe('signOut', () => { expect(mockRevokeToken).not.toHaveBeenCalled(); expect(mockGlobalSignOut).not.toHaveBeenCalled(); - expect(mockGetRegion).not.toHaveBeenCalled(); + expect(mockGetRegionFromUserPoolId).not.toHaveBeenCalled(); expectSignOut().toComplete(); }); @@ -154,11 +187,36 @@ describe('signOut', () => { { region: 'us-west-2' }, { AccessToken: accessToken.toString() }, ); - expect(mockGetRegion).toHaveBeenCalledTimes(1); + expect(mockGetRegionFromUserPoolId).toHaveBeenCalledTimes(1); expect(mockRevokeToken).not.toHaveBeenCalled(); expectSignOut().toComplete(); }); + it('invokes createCognitoUserPoolEndpointResolver with the userPoolEndpoint for creating the globalSignOut client', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + const expectedEndpointResolver = jest.fn(); + mockAmplify.getConfig.mockReturnValueOnce({ + Auth: { + Cognito: { + ...cognitoConfig, + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + mockCreateCognitoUserPoolEndpointResolver.mockReturnValueOnce( + expectedEndpointResolver, + ); + + await signOut({ global: true }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + expect(mockCreateGlobalSignOutClient).toHaveBeenCalledWith({ + endpointResolver: expectedEndpointResolver, + }); + }); + it('should still perform client sign out if token revoke fails', async () => { mockRevokeToken.mockRejectedValue(new Error()); @@ -167,7 +225,7 @@ describe('signOut', () => { expect(loggerDebugSpy).toHaveBeenCalledWith( expect.stringContaining('Client signOut error caught'), ); - expect(mockGetRegion).toHaveBeenCalledTimes(1); + expect(mockGetRegionFromUserPoolId).toHaveBeenCalledTimes(1); expectSignOut().toComplete(); }); @@ -179,7 +237,7 @@ describe('signOut', () => { expect(loggerDebugSpy).toHaveBeenCalledWith( expect.stringContaining('Global signOut error caught'), ); - expect(mockGetRegion).toHaveBeenCalledTimes(1); + expect(mockGetRegionFromUserPoolId).toHaveBeenCalledTimes(1); expectSignOut().toComplete(); }); }); diff --git a/packages/auth/__tests__/providers/cognito/signUp.test.ts b/packages/auth/__tests__/providers/cognito/signUp.test.ts index 87e0dda27c6..cb2b9b84d64 100644 --- a/packages/auth/__tests__/providers/cognito/signUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/signUp.test.ts @@ -4,10 +4,11 @@ import { Amplify } from '@aws-amplify/core'; import { signUp } from '../../../src/providers/cognito'; -import { signUp as providerSignUp } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { AuthError } from '../../../src/errors/AuthError'; import { SignUpException } from '../../../src/providers/cognito/types/errors'; +import { createSignUpClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { getMockError } from './testUtils/data'; @@ -21,21 +22,35 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), isBrowser: jest.fn(() => false), })); + jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); - -const userId = '1234567890'; +jest.mock('../../../src/providers/cognito/factories'); describe('signUp', () => { + const userId = '1234567890'; const { user1 } = authAPITestParams; // assert mocks - const mockSignUp = providerSignUp as jest.Mock; + const mockSignUp = jest.fn(); + const mockCreateSignUpClient = jest.mocked(createSignUpClient); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); }); + beforeEach(() => { + mockCreateSignUpClient.mockReturnValueOnce(mockSignUp); + }); + + afterEach(() => { + mockCreateSignUpClient.mockClear(); + mockCreateCognitoUserPoolEndpointResolver.mockClear(); + }); + describe('Happy Path Cases:', () => { beforeEach(() => { mockSignUp.mockResolvedValue(authAPITestParams.signUpHttpCallResult); @@ -70,6 +85,31 @@ describe('signUp', () => { expect(mockSignUp).toHaveBeenCalledTimes(1); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await signUp({ + username: user1.username, + password: user1.password, + options: { + userAttributes: { email: user1.email }, + }, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should return `CONFIRM_SIGN_UP` step when user isn`t confirmed yet', async () => { const result = await signUp({ username: user1.username, diff --git a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts index dbaeca398f6..a9d4d6c9e65 100644 --- a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts @@ -8,10 +8,11 @@ import { UpdateMFAPreferenceInput, updateMFAPreference, } from '../../../src/providers/cognito'; -import { setUserMFAPreference } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthError } from '../../../src/errors/AuthError'; import { SetUserMFAPreferenceException } from '../../../src/providers/cognito/types/errors'; import { getMFASettings } from '../../../src/providers/cognito/apis/updateMFAPreference'; +import { createSetUserMFAPreferenceClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -25,8 +26,9 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); const mfaChoices: UpdateMFAPreferenceInput[] = [ { sms: 'DISABLED', totp: 'DISABLED' }, @@ -51,7 +53,13 @@ const mfaChoices: UpdateMFAPreferenceInput[] = [ describe('updateMFAPreference', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockSetUserMFAPreference = setUserMFAPreference as jest.Mock; + const mockSetUserMFAPreference = jest.fn(); + const mockCreateSetUserMFAPreferenceClient = jest.mocked( + createSetUserMFAPreferenceClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -62,11 +70,15 @@ describe('updateMFAPreference', () => { beforeEach(() => { mockSetUserMFAPreference.mockResolvedValue({}); + mockCreateSetUserMFAPreferenceClient.mockReturnValueOnce( + mockSetUserMFAPreference, + ); }); afterEach(() => { mockSetUserMFAPreference.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateSetUserMFAPreferenceClient.mockClear(); }); it.each(mfaChoices)( @@ -88,6 +100,25 @@ describe('updateMFAPreference', () => { }, ); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await updateMFAPreference(mfaChoices[0]); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockSetUserMFAPreference.mockImplementation(() => { diff --git a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts index 42c0869a9a3..72dfe80119e 100644 --- a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts @@ -8,7 +8,8 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { updatePassword } from '../../../src/providers/cognito'; import { ChangePasswordException } from '../../../src/providers/cognito/types/errors'; -import { changePassword } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createChangePasswordClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -22,15 +23,22 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('updatePassword', () => { const oldPassword = 'oldPassword'; const newPassword = 'newPassword'; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockChangePassword = changePassword as jest.Mock; + const mockChangePassword = jest.fn(); + const mockCreateChangePasswordClient = jest.mocked( + createChangePasswordClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -41,11 +49,13 @@ describe('updatePassword', () => { beforeEach(() => { mockChangePassword.mockResolvedValue({}); + mockCreateChangePasswordClient.mockReturnValueOnce(mockChangePassword); }); afterEach(() => { mockChangePassword.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateChangePasswordClient.mockClear(); }); it('should call changePassword', async () => { @@ -61,6 +71,25 @@ describe('updatePassword', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await updatePassword({ oldPassword, newPassword }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when oldPassword is empty', async () => { expect.assertions(2); try { diff --git a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts index 3b1ca0f9d99..bfa9643b76d 100644 --- a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts @@ -7,8 +7,9 @@ import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { updateUserAttributes } from '../../../src/providers/cognito'; import { UpdateUserAttributesException } from '../../../src/providers/cognito/types/errors'; -import { updateUserAttributes as providerUpdateUserAttributes } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { toAttributeType } from '../../../src/providers/cognito/utils/apiHelpers'; +import { createUpdateUserAttributesClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -22,13 +23,20 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('updateUserAttributes', () => { // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockUpdateUserAttributes = providerUpdateUserAttributes as jest.Mock; + const mockUpdateUserAttributes = jest.fn(); + const mockCreateUpdateUserAttributesClient = jest.mocked( + createUpdateUserAttributesClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -52,11 +60,15 @@ describe('updateUserAttributes', () => { }, ], }); + mockCreateUpdateUserAttributesClient.mockReturnValueOnce( + mockUpdateUserAttributes, + ); }); afterEach(() => { mockUpdateUserAttributes.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateUpdateUserAttributesClient.mockClear(); }); it('should return a map with updated and not updated attributes', async () => { @@ -121,6 +133,30 @@ describe('updateUserAttributes', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + await updateUserAttributes({ + userAttributes: {}, + options: { + clientMetadata: { foo: 'bar' }, + }, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('updateUserAttributes API should return a map with updated attributes only', async () => { mockUpdateUserAttributes.mockResolvedValue({}); const userAttributes = { diff --git a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts index aceb6ed480a..0f7c5bcb109 100644 --- a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts +++ b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts @@ -8,7 +8,8 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { VerifySoftwareTokenException } from '../../../src/providers/cognito/types/errors'; import { verifyTOTPSetup } from '../../../src/providers/cognito'; -import { verifySoftwareToken } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; +import { createVerifySoftwareTokenClient } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; import { getMockError, mockAccessToken } from './testUtils/data'; import { setUpGetConfig } from './testUtils/setUpGetConfig'; @@ -22,15 +23,22 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); +jest.mock('../../../src/providers/cognito/factories'); describe('verifyTOTPSetup', () => { const code = '123456'; const friendlyDeviceName = 'FriendlyDeviceName'; // assert mocks const mockFetchAuthSession = fetchAuthSession as jest.Mock; - const mockVerifySoftwareToken = verifySoftwareToken as jest.Mock; + const mockVerifySoftwareToken = jest.fn(); + const mockCreateVerifySoftwareTokenClient = jest.mocked( + createVerifySoftwareTokenClient, + ); + const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( + createCognitoUserPoolEndpointResolver, + ); beforeAll(() => { setUpGetConfig(Amplify); @@ -41,11 +49,15 @@ describe('verifyTOTPSetup', () => { beforeEach(() => { mockVerifySoftwareToken.mockResolvedValue({}); + mockCreateVerifySoftwareTokenClient.mockReturnValueOnce( + mockVerifySoftwareToken, + ); }); afterEach(() => { mockVerifySoftwareToken.mockReset(); mockFetchAuthSession.mockClear(); + mockCreateVerifySoftwareTokenClient.mockClear(); }); it('should return successful response', async () => { @@ -64,6 +76,29 @@ describe('verifyTOTPSetup', () => { ); }); + it('invokes mockCreateCognitoUserPoolEndpointResolver with expected endpointOverride', async () => { + const expectedUserPoolEndpoint = 'https://my-custom-endpoint.com'; + jest.mocked(Amplify.getConfig).mockReturnValueOnce({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + userPoolEndpoint: expectedUserPoolEndpoint, + }, + }, + }); + + await verifyTOTPSetup({ + code, + options: { friendlyDeviceName }, + }); + + expect(mockCreateCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + endpointOverride: expectedUserPoolEndpoint, + }); + }); + it('should throw an error when code is empty', async () => { expect.assertions(2); try { From 50c9e8afb6bae3b1539c7f52c421b4185df4595b Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 20 Aug 2024 14:22:40 -0700 Subject: [PATCH 04/11] chore(auth): add unit tests for newly added modules --- .../cognitoUserPoolEndpointResolver.test.ts | 16 +++++ .../foundation/core/parsers/getRegion.test.ts | 47 +++++++++++++++ .../cognitoIdentityProvider/index.test.ts | 41 +++++++++++++ .../cognitoUserPoolTransferHandler.test.ts | 44 ++++++++++++++ .../buildEmptyResponseDeserializer.test.ts | 55 +++++++++++++++++ .../buildUserPoolDeserializer.test.ts | 59 +++++++++++++++++++ .../buildUserPoolSerializer.test.ts | 27 +++++++++ .../cognitoIdentityProvider/testUtils/data.ts | 7 +++ ...ateCognitoUserPoolEndpointResolver.test.ts | 55 +++++++++++++++++ 9 files changed, 351 insertions(+) create mode 100644 packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts create mode 100644 packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts create mode 100644 packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/index.test.ts create mode 100644 packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts create mode 100644 packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts create mode 100644 packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts create mode 100644 packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts create mode 100644 packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts create mode 100644 packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts diff --git a/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts b/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts new file mode 100644 index 00000000000..ff2fc5282d4 --- /dev/null +++ b/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts @@ -0,0 +1,16 @@ +import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; + +import { cognitoUserPoolEndpointResolver } from '../../../src/foundation/core/cognitoUserPoolEndpointResolver'; +import { COGNITO_IDP_SERVICE_NAME } from '../../../src/foundation/core/constants'; + +describe('cognitoUserPoolEndpointResolver', () => { + it('should return the Cognito User Pool endpoint', () => { + const region = 'us-west-2'; + const { url } = cognitoUserPoolEndpointResolver({ region }); + + expect(url instanceof AmplifyUrl).toBe(true); + expect(url.toString()).toEqual( + `https://${COGNITO_IDP_SERVICE_NAME}.us-west-2.amazonaws.com/`, + ); + }); +}); diff --git a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts b/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts new file mode 100644 index 00000000000..f5b2aac720b --- /dev/null +++ b/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts @@ -0,0 +1,47 @@ +import { AuthError } from '../../../../src/errors/AuthError'; +import { + getRegionFromIdentityPoolId, + getRegionFromUserPoolId, +} from '../../../../src/foundation/core/parsers/getRegion'; + +describe('getRegionFromIdentityPoolId()', () => { + it('returns the region from the identity pool id', () => { + const identityPoolId = 'us-west-2:12345678-1234-1234-1234-123456789012'; + const region = getRegionFromIdentityPoolId(identityPoolId); + expect(region).toEqual('us-west-2'); + }); + + test.each([undefined, 'invalid-id-123'])( + `throws an error when the identity pool id is invalid as %p`, + identityPoolId => { + expect(() => getRegionFromIdentityPoolId(identityPoolId)).toThrow( + new AuthError({ + name: 'InvalidIdentityPoolIdException', + message: 'Invalid identity pool id provided.', + recoverySuggestion: + 'Make sure a valid identityPoolId is given in the config.', + }), + ); + }, + ); +}); + +describe('getRegionFromUserPoolId()', () => { + it('should return the region from the user pool id', () => { + const userPoolId = 'us-west-2_12345678'; + const region = getRegionFromUserPoolId(userPoolId); + expect(region).toEqual('us-west-2'); + }); + + test.each([undefined, 'invalid-id-123'])( + `throws an error when the user pool id is invalid as %p`, + userPoolId => { + expect(() => getRegionFromUserPoolId(userPoolId)).toThrow( + new AuthError({ + name: 'InvalidUserPoolId', + message: 'Invalid user pool id provided.', + }), + ); + }, + ); +}); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/index.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/index.test.ts new file mode 100644 index 00000000000..9138718bb58 --- /dev/null +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/index.test.ts @@ -0,0 +1,41 @@ +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import * as serviceClients from '../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from '../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/constants'; + +import { mockServiceClientAPIConfig } from './testUtils/data'; + +jest.mock('@aws-amplify/core/internals/aws-client-utils/composers', () => ({ + ...jest.requireActual( + '@aws-amplify/core/internals/aws-client-utils/composers', + ), + composeServiceApi: jest.fn(), +})); + +export const mockComposeServiceApi = jest.mocked(composeServiceApi); + +describe('service clients', () => { + const serviceClientFactories = Object.keys(serviceClients); + + afterEach(() => { + mockComposeServiceApi.mockClear(); + }); + + test.each(serviceClientFactories)( + 'factory `%s` should invoke composeServiceApi with expected parameters', + serviceClientFactory => { + // eslint-disable-next-line import/namespace + serviceClients[serviceClientFactory](mockServiceClientAPIConfig); + + expect(mockComposeServiceApi).toHaveBeenCalledWith( + expect.any(Function), + expect.any(Function), + expect.any(Function), + expect.objectContaining({ + ...DEFAULT_SERVICE_CLIENT_API_CONFIG, + ...mockServiceClientAPIConfig, + }), + ); + }, + ); +}); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts new file mode 100644 index 00000000000..cca1b86ce04 --- /dev/null +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts @@ -0,0 +1,44 @@ +import { unauthenticatedHandler } from '@aws-amplify/core/internals/aws-client-utils'; +import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers'; + +import { cognitoUserPoolTransferHandler } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler'; + +jest.mock('@aws-amplify/core/internals/aws-client-utils/composers'); +jest.mock('@aws-amplify/core/internals/aws-client-utils'); + +const mockComposeTransferHandler = jest.mocked(composeTransferHandler); +const mockUnauthenticatedHandler = jest.mocked(unauthenticatedHandler); + +describe('cognitoUserPoolTransferHandler', () => { + beforeAll(() => { + // need to make sure cognitoUserPoolTransferHandler is imported and used in + // the scope of the test + const _ = cognitoUserPoolTransferHandler; + }); + + it('adds the disableCacheMiddlewareFactory at module loading', () => { + console.log(mockComposeTransferHandler); + expect(mockComposeTransferHandler).toHaveBeenCalledTimes(1); + + const [core, middleware] = mockComposeTransferHandler.mock.calls[0]; + + expect(core).toStrictEqual(mockUnauthenticatedHandler); + expect(middleware).toHaveLength(1); + + const disableCacheMiddlewareFactory = middleware[0] as any; + const disableCacheMiddlewarePendingNext = disableCacheMiddlewareFactory(); + + const mockNext = jest.fn(); + const disableCacheMiddleware = disableCacheMiddlewarePendingNext(mockNext); + const mockRequest = { + headers: {}, + }; + + disableCacheMiddleware(mockRequest); + + expect(mockNext).toHaveBeenCalledWith(mockRequest); + expect(mockRequest.headers).toEqual({ + 'cache-control': 'no-store', + }); + }); +}); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts new file mode 100644 index 00000000000..32a2c6c1e2b --- /dev/null +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts @@ -0,0 +1,55 @@ +import { + HttpResponse, + parseJsonError, +} from '@aws-amplify/core/internals/aws-client-utils'; + +import { buildEmptyResponseDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer'; +import { AuthError } from '../../../../../../../src/errors/AuthError'; + +jest.mock('@aws-amplify/core/internals/aws-client-utils'); + +const mockParseJsonError = jest.mocked(parseJsonError); + +describe('buildEmptyResponseDeserializer created response deserializer', () => { + const deserializer = buildEmptyResponseDeserializer(); + + it('returns undefined for 2xx status code', async () => { + const response: HttpResponse = { + statusCode: 200, + body: { + json: () => Promise.resolve({}), + blob: () => Promise.resolve(new Blob()), + text: () => Promise.resolve(''), + }, + headers: {}, + }; + const output = await deserializer(response); + + expect(output).toBeUndefined(); + }); + + it('throws AuthError for 4xx status code', async () => { + const expectedErrorName = 'TestError'; + const expectedErrorMessage = 'TestErrorMessage'; + const expectedError = new Error(expectedErrorMessage); + expectedError.name = expectedErrorName; + + mockParseJsonError.mockReturnValueOnce(expectedError as any); + const response: HttpResponse = { + statusCode: 400, + body: { + json: () => Promise.resolve({}), + blob: () => Promise.resolve(new Blob()), + text: () => Promise.resolve(''), + }, + headers: {}, + }; + + expect(deserializer(response as any)).rejects.toThrow( + new AuthError({ + name: expectedErrorName, + message: expectedErrorMessage, + }), + ); + }); +}); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts new file mode 100644 index 00000000000..03696f3b894 --- /dev/null +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts @@ -0,0 +1,59 @@ +import { + HttpResponse, + parseJsonBody, + parseJsonError, +} from '@aws-amplify/core/internals/aws-client-utils'; + +import { buildUserPoolDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer'; +import { AuthError } from '../../../../../../../src/errors/AuthError'; + +jest.mock('@aws-amplify/core/internals/aws-client-utils'); + +const mockParseJsonBody = jest.mocked(parseJsonBody); +const mockParseJsonError = jest.mocked(parseJsonError); + +describe('buildUserPoolDeserializer created response deserializer', () => { + const deserializer = buildUserPoolDeserializer(); + + it('returns body for 2xx status code', async () => { + const expectedBody = { test: 'test' }; + mockParseJsonBody.mockResolvedValueOnce(expectedBody); + const response: HttpResponse = { + statusCode: 200, + body: { + json: () => Promise.resolve({}), + blob: () => Promise.resolve(new Blob()), + text: () => Promise.resolve(''), + }, + headers: {}, + }; + const output = await deserializer(response); + + expect(output).toStrictEqual(expectedBody); + }); + + it('throws AuthError for 4xx status code', async () => { + const expectedErrorName = 'TestError'; + const expectedErrorMessage = 'TestErrorMessage'; + const expectedError = new Error(expectedErrorMessage); + expectedError.name = expectedErrorName; + + mockParseJsonError.mockReturnValueOnce(expectedError as any); + const response: HttpResponse = { + statusCode: 400, + body: { + json: () => Promise.resolve({}), + blob: () => Promise.resolve(new Blob()), + text: () => Promise.resolve(''), + }, + headers: {}, + }; + + expect(deserializer(response as any)).rejects.toThrow( + new AuthError({ + name: expectedErrorName, + message: expectedErrorMessage, + }), + ); + }); +}); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts new file mode 100644 index 00000000000..594d3f2ceaf --- /dev/null +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts @@ -0,0 +1,27 @@ +import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; + +import { buildUserPoolSerializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer'; + +describe('buildUserPoolSerializer created request serializer', () => { + test.each(['SignUp', 'InitiateAuth', 'RevokeToken'] as const)( + `it serializes requests from operation %s`, + operation => { + const testInput = { testBody: 'testBody' }; + const testEndpoint = { + url: new AmplifyUrl('http://test.com'), + }; + const serializer = buildUserPoolSerializer(operation); + const result = serializer(testInput, testEndpoint); + + expect(result).toEqual({ + method: 'POST', + url: testEndpoint.url, + headers: { + 'content-type': 'application/x-amz-json-1.1', + 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}`, + }, + body: JSON.stringify(testInput), + }); + }, + ); +}); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts new file mode 100644 index 00000000000..efe5657d084 --- /dev/null +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts @@ -0,0 +1,7 @@ +import { ServiceClientAPIConfig } from '../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient'; + +export const mockServiceClientAPIConfig: ServiceClientAPIConfig = { + endpointResolver: jest.fn() as jest.MockedFunction< + ServiceClientAPIConfig['endpointResolver'] + >, +}; diff --git a/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts b/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts new file mode 100644 index 00000000000..b842e95a392 --- /dev/null +++ b/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts @@ -0,0 +1,55 @@ +import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; + +import { cognitoUserPoolEndpointResolver } from '../../../../src/foundation/core/cognitoUserPoolEndpointResolver'; +import { createCognitoUserPoolEndpointResolver } from '../../../../src/providers/cognito/factories/createCognitoUserPoolEndpointResolver'; + +jest.mock('../../../../src/foundation/core/cognitoUserPoolEndpointResolver'); + +const mockCognitoUserPoolEndpointResolver = jest.mocked( + cognitoUserPoolEndpointResolver, +); + +describe('createCognitoUserPoolEndpointResolver()', () => { + afterEach(() => { + mockCognitoUserPoolEndpointResolver.mockClear(); + }); + + describe('creating a resolver with overrideEndpoint as `undefined`', () => { + const resolver = createCognitoUserPoolEndpointResolver({ + endpointOverride: undefined, + }); + + it('invokes cognitoUserPoolEndpointResolver with the expected region', () => { + const expectedReturningUrl = { + url: new AmplifyUrl('https://cognito-idp.us-west-2.amazonaws.com/'), + }; + mockCognitoUserPoolEndpointResolver.mockReturnValueOnce( + expectedReturningUrl, + ); + + const expectedRegion = 'us-west-2'; + const { url } = resolver({ region: expectedRegion }); + + expect(mockCognitoUserPoolEndpointResolver).toHaveBeenCalledWith({ + region: expectedRegion, + }); + expect(url).toStrictEqual(expectedReturningUrl.url); + }); + }); + + describe('creating a resolver with overrideEndpoint', () => { + const endpointOverride = 'https://cognito-idp.example.com'; + const resolver = createCognitoUserPoolEndpointResolver({ + endpointOverride, + }); + + it('returns the endpoint override', () => { + const expectedRegion = 'us-west-2'; + const { url } = resolver({ region: expectedRegion }); + expect(mockCognitoUserPoolEndpointResolver).not.toHaveBeenCalled(); + expect(url).toStrictEqual( + new AmplifyUrl('https://cognito-idp.example.com'), + ); + }); + }); +}); From 5de1cde940c81c78ce30c5e4c4015de1a724aec5 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 20 Aug 2024 14:28:06 -0700 Subject: [PATCH 05/11] chore(auth): add missing license header --- .../auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts | 2 ++ packages/auth/src/foundation/core/constants.ts | 2 ++ packages/auth/src/foundation/core/parsers/getRegion.ts | 2 ++ packages/auth/src/foundation/core/parsers/index.ts | 2 ++ .../createAssociateSoftwareTokenClient.ts | 2 ++ .../cognitoIdentityProvider/createChangePasswordClient.ts | 2 ++ .../cognitoIdentityProvider/createConfirmDeviceClient.ts | 2 ++ .../createConfirmForgotPasswordClient.ts | 2 ++ .../cognitoIdentityProvider/createConfirmSignUpClient.ts | 2 ++ .../cognitoIdentityProvider/createDeleteUserAttributesClient.ts | 2 ++ .../cognitoIdentityProvider/createDeleteUserClient.ts | 2 ++ .../cognitoIdentityProvider/createForgetDeviceClient.ts | 2 ++ .../cognitoIdentityProvider/createForgotPasswordClient.ts | 2 ++ .../createGetUserAttributeVerificationCodeClient.ts | 2 ++ .../cognitoIdentityProvider/createGetUserClient.ts | 2 ++ .../cognitoIdentityProvider/createGlobalSignOutClient.ts | 2 ++ .../cognitoIdentityProvider/createListDevicesClient.ts | 2 ++ .../createResendConfirmationCodeClient.ts | 2 ++ .../createRespondToAuthChallengeClient.ts | 2 ++ .../cognitoIdentityProvider/createRevokeTokenClient.ts | 2 ++ .../cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts | 2 ++ .../cognitoIdentityProvider/createSignUpClient.ts | 2 ++ .../cognitoIdentityProvider/createUpdateDeviceStatusClient.ts | 2 ++ .../cognitoIdentityProvider/createUpdateUserAttributesClient.ts | 2 ++ .../cognitoIdentityProvider/createVerifySoftwareTokenClient.ts | 2 ++ .../cognitoIdentityProvider/createVerifyUserAttributeClient.ts | 2 ++ .../shared/serialization/buildEmptyResponseDeserializer.ts | 2 ++ .../serviceClients/cognitoIdentityProvider/types/index.ts | 2 ++ .../cognito/factories/createCognitoUserPoolEndpointResolver.ts | 2 ++ packages/auth/src/providers/cognito/factories/index.ts | 2 ++ 30 files changed, 60 insertions(+) diff --git a/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts b/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts index 6f7bf9c30d4..dc57e2e0ce4 100644 --- a/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts +++ b/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { EndpointResolverOptions, getDnsSuffix, diff --git a/packages/auth/src/foundation/core/constants.ts b/packages/auth/src/foundation/core/constants.ts index 1b97d4e9f62..56814b3e66f 100644 --- a/packages/auth/src/foundation/core/constants.ts +++ b/packages/auth/src/foundation/core/constants.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * The service name used to sign requests if the API requires authentication. */ diff --git a/packages/auth/src/foundation/core/parsers/getRegion.ts b/packages/auth/src/foundation/core/parsers/getRegion.ts index a4d8a5d9a91..da6133b44db 100644 --- a/packages/auth/src/foundation/core/parsers/getRegion.ts +++ b/packages/auth/src/foundation/core/parsers/getRegion.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AuthError } from '../../../errors/AuthError'; export function getRegionFromUserPoolId(userPoolId?: string): string { diff --git a/packages/auth/src/foundation/core/parsers/index.ts b/packages/auth/src/foundation/core/parsers/index.ts index 9100093993d..f90234201e7 100644 --- a/packages/auth/src/foundation/core/parsers/index.ts +++ b/packages/auth/src/foundation/core/parsers/index.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export { getRegionFromUserPoolId, getRegionFromIdentityPoolId, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts index 6b5a54298d8..82c6e03aa1d 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts index dd2b03422f9..12a47bb05dc 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { cognitoUserPoolTransferHandler } from './shared/handler'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts index 25030468b4c..cdc90e53334 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { cognitoUserPoolTransferHandler } from './shared/handler'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts index 685005aaee9..5e60c29802e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts index 460263ed85a..5ccfb89e470 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts index df791e777b5..00a38e7350f 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts index 5473da6290a..234de9b8404 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts index 4f088e2e60f..bbb18ddda8c 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { cognitoUserPoolTransferHandler } from './shared/handler'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts index 681270eeda3..db1a70af4d1 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts index faea85fd08b..6e07a050516 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts index 2637a4028a4..a5d816a4806 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts index 4de9ff27ec2..96f0b20eb6e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts index f445ea9feb6..b0667a2e0b3 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts index 16eb230f95e..d96771bf1b7 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts index 482069f2039..d0fcd9c2d1e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts index bc9a46aa187..2d1757adb49 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { cognitoUserPoolTransferHandler } from './shared/handler'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts index 1801e416d08..868e3f973b1 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts index fa99aa9b4ed..718603e2757 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts index b9e72f7834c..a2a6020c3c1 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts index f69ea5513a2..0691e99a006 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts index e9900b0033e..00bcac6b69f 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts index 6a2f91a69aa..96729eaa85a 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; import { ServiceClientAPIConfig } from './types/ServiceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts index 37e1af5a0ad..8c2a9063164 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { HttpResponse, parseJsonError, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts index 4f6fc4295d5..1df781ff734 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts @@ -1,2 +1,4 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export * from './Sdk'; export * from './ServiceClient'; diff --git a/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts b/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts index 6e190a1ef2b..e9908dcc384 100644 --- a/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts +++ b/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { EndpointResolverOptions } from '@aws-amplify/core/internals/aws-client-utils'; import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; diff --git a/packages/auth/src/providers/cognito/factories/index.ts b/packages/auth/src/providers/cognito/factories/index.ts index be3e983fc51..7f8050064d3 100644 --- a/packages/auth/src/providers/cognito/factories/index.ts +++ b/packages/auth/src/providers/cognito/factories/index.ts @@ -1 +1,3 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export { createCognitoUserPoolEndpointResolver } from './createCognitoUserPoolEndpointResolver'; From 37fece1fe230692c03638afb25a76343d2e8e7d7 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 20 Aug 2024 15:50:48 -0700 Subject: [PATCH 06/11] chore(repo): update sdk type extractio destination for the auth package --- scripts/dts-bundler/dts-bundler.config.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts/dts-bundler/dts-bundler.config.js b/scripts/dts-bundler/dts-bundler.config.js index 77671630aeb..90210b58cee 100644 --- a/scripts/dts-bundler/dts-bundler.config.js +++ b/scripts/dts-bundler/dts-bundler.config.js @@ -44,12 +44,15 @@ const authPackageSrcClientsPath = join( 'packages', 'auth', 'src', - 'providers', - 'cognito', - 'utils', - 'clients', + 'foundation', + 'factories', + 'serviceClients', + 'cognitoIdentityProvider', + 'types', ); +// packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts + /** @type import('dts-bundle-generator/config-schema').BundlerConfig */ const config = { compilationOptions: { @@ -84,8 +87,7 @@ const config = { filePath: './cognito-identity-provider.d.ts', outFile: join( authPackageSrcClientsPath, - 'CognitoIdentityProvider', - 'types.ts', + 'Sdk.ts', ), libraries: { inlinedLibraries: ['@aws-sdk/client-cognito-identity-provider'], From d30b77eeb2aae6ff2de7520fc779f6b70c301017 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 21 Aug 2024 16:59:54 -0700 Subject: [PATCH 07/11] chore: resolve most of the comments from cshfang --- .../foundation/core/parsers/getRegion.test.ts | 2 +- .../cognitoUserPoolTransferHandler.test.ts | 1 - .../buildEmptyResponseDeserializer.test.ts | 4 ++-- .../buildUserPoolDeserializer.test.ts | 4 ++-- .../buildUserPoolSerializer.test.ts | 4 ++-- .../cognitoIdentityProvider/testUtils/data.ts | 6 +++--- .../auth/src/foundation/core/parsers/index.ts | 2 +- .../{getRegion.ts => regionParsers.ts} | 0 .../createAssociateSoftwareTokenClient.ts | 20 +++++++++---------- .../createChangePasswordClient.ts | 14 ++++++------- .../createConfirmDeviceClient.ts | 14 ++++++------- .../createConfirmForgotPasswordClient.ts | 20 +++++++++---------- .../createConfirmSignUpClient.ts | 14 ++++++------- .../createDeleteUserAttributesClient.ts | 20 +++++++++---------- .../createDeleteUserClient.ts | 17 +++++++++------- .../createForgetDeviceClient.ts | 14 ++++++------- .../createForgotPasswordClient.ts | 20 +++++++++---------- ...eGetUserAttributeVerificationCodeClient.ts | 20 +++++++++---------- .../createGetUserClient.ts | 17 +++++++++------- .../createGlobalSignOutClient.ts | 20 +++++++++---------- .../createInitiateAuthClient.ts | 18 ++++++++--------- .../createListDevicesClient.ts | 17 +++++++++------- .../createResendConfirmationCodeClient.ts | 20 +++++++++---------- .../createRespondToAuthChallengeClient.ts | 20 +++++++++---------- .../createRevokeTokenClient.ts | 12 +++++------ .../createSetUserMFAPreferenceClient.ts | 16 +++++++-------- .../createSignUpClient.ts | 17 +++++++++------- .../createUpdateDeviceStatusClient.ts | 20 +++++++++---------- .../createUpdateUserAttributesClient.ts | 20 +++++++++---------- .../createVerifySoftwareTokenClient.ts | 20 +++++++++---------- .../createVerifyUserAttributeClient.ts | 20 +++++++++---------- ....ts => createEmptyResponseDeserializer.ts} | 12 ++++------- ...lizer.ts => createUserPoolDeserializer.ts} | 8 +++++--- ...ializer.ts => createUserPoolSerializer.ts} | 2 +- .../shared/serialization/index.ts | 6 +++--- .../cognitoIdentityProvider/types/index.ts | 4 ++-- .../types/{Sdk.ts => sdk.ts} | 0 .../{ServiceClient.ts => serviceClient.ts} | 2 +- 38 files changed, 238 insertions(+), 229 deletions(-) rename packages/auth/src/foundation/core/parsers/{getRegion.ts => regionParsers.ts} (100%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/{buildUserPoolDeserializer.ts => createEmptyResponseDeserializer.ts} (72%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/{buildEmptyResponseDeserializer.ts => createUserPoolDeserializer.ts} (85%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/{buildUserPoolSerializer.ts => createUserPoolSerializer.ts} (97%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/{Sdk.ts => sdk.ts} (100%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/{ServiceClient.ts => serviceClient.ts} (85%) diff --git a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts b/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts index f5b2aac720b..6a5780e8d18 100644 --- a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts +++ b/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts @@ -2,7 +2,7 @@ import { AuthError } from '../../../../src/errors/AuthError'; import { getRegionFromIdentityPoolId, getRegionFromUserPoolId, -} from '../../../../src/foundation/core/parsers/getRegion'; +} from '../../../../src/foundation/core/parsers/regionParsers'; describe('getRegionFromIdentityPoolId()', () => { it('returns the region from the identity pool id', () => { diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts index cca1b86ce04..8f5bbc8c7f9 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.test.ts @@ -17,7 +17,6 @@ describe('cognitoUserPoolTransferHandler', () => { }); it('adds the disableCacheMiddlewareFactory at module loading', () => { - console.log(mockComposeTransferHandler); expect(mockComposeTransferHandler).toHaveBeenCalledTimes(1); const [core, middleware] = mockComposeTransferHandler.mock.calls[0]; diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts index 32a2c6c1e2b..9bfb5fa1391 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts @@ -3,7 +3,7 @@ import { parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils'; -import { buildEmptyResponseDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer'; +import { createEmptyResponseDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer'; import { AuthError } from '../../../../../../../src/errors/AuthError'; jest.mock('@aws-amplify/core/internals/aws-client-utils'); @@ -11,7 +11,7 @@ jest.mock('@aws-amplify/core/internals/aws-client-utils'); const mockParseJsonError = jest.mocked(parseJsonError); describe('buildEmptyResponseDeserializer created response deserializer', () => { - const deserializer = buildEmptyResponseDeserializer(); + const deserializer = createEmptyResponseDeserializer(); it('returns undefined for 2xx status code', async () => { const response: HttpResponse = { diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts index 03696f3b894..065d2a548bf 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts @@ -4,7 +4,7 @@ import { parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils'; -import { buildUserPoolDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer'; +import { createUserPoolDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer'; import { AuthError } from '../../../../../../../src/errors/AuthError'; jest.mock('@aws-amplify/core/internals/aws-client-utils'); @@ -13,7 +13,7 @@ const mockParseJsonBody = jest.mocked(parseJsonBody); const mockParseJsonError = jest.mocked(parseJsonError); describe('buildUserPoolDeserializer created response deserializer', () => { - const deserializer = buildUserPoolDeserializer(); + const deserializer = createUserPoolDeserializer(); it('returns body for 2xx status code', async () => { const expectedBody = { test: 'test' }; diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts index 594d3f2ceaf..3b48d1a5a04 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts @@ -1,6 +1,6 @@ import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; -import { buildUserPoolSerializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer'; +import { createUserPoolSerializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer'; describe('buildUserPoolSerializer created request serializer', () => { test.each(['SignUp', 'InitiateAuth', 'RevokeToken'] as const)( @@ -10,7 +10,7 @@ describe('buildUserPoolSerializer created request serializer', () => { const testEndpoint = { url: new AmplifyUrl('http://test.com'), }; - const serializer = buildUserPoolSerializer(operation); + const serializer = createUserPoolSerializer(operation); const result = serializer(testInput, testEndpoint); expect(result).toEqual({ diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts index efe5657d084..33a9a3d5534 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/testUtils/data.ts @@ -1,7 +1,7 @@ -import { ServiceClientAPIConfig } from '../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient'; +import { ServiceClientFactoryInput } from '../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/types'; -export const mockServiceClientAPIConfig: ServiceClientAPIConfig = { +export const mockServiceClientAPIConfig: ServiceClientFactoryInput = { endpointResolver: jest.fn() as jest.MockedFunction< - ServiceClientAPIConfig['endpointResolver'] + ServiceClientFactoryInput['endpointResolver'] >, }; diff --git a/packages/auth/src/foundation/core/parsers/index.ts b/packages/auth/src/foundation/core/parsers/index.ts index f90234201e7..901f99a010e 100644 --- a/packages/auth/src/foundation/core/parsers/index.ts +++ b/packages/auth/src/foundation/core/parsers/index.ts @@ -3,4 +3,4 @@ export { getRegionFromUserPoolId, getRegionFromIdentityPoolId, -} from './getRegion'; +} from './regionParsers'; diff --git a/packages/auth/src/foundation/core/parsers/getRegion.ts b/packages/auth/src/foundation/core/parsers/regionParsers.ts similarity index 100% rename from packages/auth/src/foundation/core/parsers/getRegion.ts rename to packages/auth/src/foundation/core/parsers/regionParsers.ts diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts index 82c6e03aa1d..757f6bea2d1 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { AssociateSoftwareTokenCommandInput, AssociateSoftwareTokenCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createAssociateSoftwareTokenClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'AssociateSoftwareToken', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts index 12a47bb05dc..ea5a4f0aa90 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts @@ -4,21 +4,21 @@ import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; import { ChangePasswordCommandInput, ChangePasswordCommandOutput, -} from './types/Sdk'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; + ServiceClientFactoryInput, +} from './types'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createChangePasswordClient = (config: ServiceClientAPIConfig) => +export const createChangePasswordClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ChangePassword'), - buildUserPoolDeserializer(), + createUserPoolSerializer('ChangePassword'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts index cdc90e53334..fb5fd05e7c1 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts @@ -4,21 +4,21 @@ import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; import { ConfirmDeviceCommandInput, ConfirmDeviceCommandOutput, -} from './types/Sdk'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; + ServiceClientFactoryInput, +} from './types'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createConfirmDeviceClient = (config: ServiceClientAPIConfig) => +export const createConfirmDeviceClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ConfirmDevice'), - buildUserPoolDeserializer(), + createUserPoolSerializer('ConfirmDevice'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts index 5e60c29802e..ca64848ad74 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { ConfirmForgotPasswordCommandInput, ConfirmForgotPasswordCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createConfirmForgotPasswordClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'ConfirmForgotPassword', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts index 5ccfb89e470..1eee1f81f94 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts @@ -5,20 +5,20 @@ import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/ import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; import { ConfirmSignUpCommandInput, ConfirmSignUpCommandOutput, -} from './types/Sdk'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; + ServiceClientFactoryInput, +} from './types'; -export const createConfirmSignUpClient = (config: ServiceClientAPIConfig) => +export const createConfirmSignUpClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ConfirmSignUp'), - buildUserPoolDeserializer(), + createUserPoolSerializer('ConfirmSignUp'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts index 00a38e7350f..b9e0c5c021a 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { DeleteUserAttributesCommandInput, DeleteUserAttributesCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createDeleteUserAttributesClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'DeleteUserAttributes', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts index 234de9b8404..39c3db1efce 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts @@ -2,20 +2,23 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { + DeleteUserCommandInput, + DeleteUserCommandOutput, + ServiceClientFactoryInput, +} from './types'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildEmptyResponseDeserializer, - buildUserPoolSerializer, + createEmptyResponseDeserializer, + createUserPoolSerializer, } from './shared/serialization'; -import { DeleteUserCommandInput, DeleteUserCommandOutput } from './types/Sdk'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createDeleteUserClient = (config: ServiceClientAPIConfig) => +export const createDeleteUserClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('DeleteUser'), - buildEmptyResponseDeserializer(), + createUserPoolSerializer('DeleteUser'), + createEmptyResponseDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts index bbb18ddda8c..009d888c2b7 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts @@ -4,21 +4,21 @@ import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildEmptyResponseDeserializer, - buildUserPoolSerializer, + createEmptyResponseDeserializer, + createUserPoolSerializer, } from './shared/serialization'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; import { ForgetDeviceCommandInput, ForgetDeviceCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createForgetDeviceClient = (config: ServiceClientAPIConfig) => +export const createForgetDeviceClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ForgetDevice'), - buildEmptyResponseDeserializer(), + createUserPoolSerializer('ForgetDevice'), + createEmptyResponseDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts index db1a70af4d1..a381b0209f0 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts @@ -2,23 +2,23 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { ForgotPasswordCommandInput, ForgotPasswordCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createForgotPasswordClient = (config: ServiceClientAPIConfig) => +export const createForgotPasswordClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ForgotPassword'), - buildUserPoolDeserializer(), + createUserPoolSerializer('ForgotPassword'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts index 6e07a050516..1354ed2c93e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { GetUserAttributeVerificationCodeCommandInput, GetUserAttributeVerificationCodeCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createGetUserAttributeVerificationCodeClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'GetUserAttributeVerificationCode', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts index a5d816a4806..aa38363567e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts @@ -2,20 +2,23 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { + GetUserCommandInput, + GetUserCommandOutput, + ServiceClientFactoryInput, +} from './types'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; -import { GetUserCommandInput, GetUserCommandOutput } from './types/Sdk'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createGetUserClient = (config: ServiceClientAPIConfig) => +export const createGetUserClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('GetUser'), - buildUserPoolDeserializer(), + createUserPoolSerializer('GetUser'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts index 96f0b20eb6e..422cb43f406 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts @@ -2,23 +2,23 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { GlobalSignOutCommandInput, GlobalSignOutCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createGlobalSignOutClient = (config: ServiceClientAPIConfig) => +export const createGlobalSignOutClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('GlobalSignOut'), - buildUserPoolDeserializer(), + createUserPoolSerializer('GlobalSignOut'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts index 9bffc384a85..eef86cb6304 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts @@ -3,23 +3,23 @@ import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { InitiateAuthCommandInput, InitiateAuthCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createInitiateAuthClient = (config: ServiceClientAPIConfig) => +export const createInitiateAuthClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('InitiateAuth'), - buildUserPoolDeserializer(), + createUserPoolSerializer('InitiateAuth'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts index b0667a2e0b3..ce784df5e6a 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts @@ -2,20 +2,23 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { + ListDevicesCommandInput, + ListDevicesCommandOutput, + ServiceClientFactoryInput, +} from './types'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; -import { ListDevicesCommandInput, ListDevicesCommandOutput } from './types/Sdk'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; -export const createListDevicesClient = (config: ServiceClientAPIConfig) => +export const createListDevicesClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('ListDevices'), - buildUserPoolDeserializer(), + createUserPoolSerializer('ListDevices'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts index d96771bf1b7..a94b9b1347c 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { ResendConfirmationCodeCommandInput, ResendConfirmationCodeCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createResendConfirmationCodeClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'ResendConfirmationCode', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts index d0fcd9c2d1e..24baa618f6f 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { RespondToAuthChallengeCommandInput, RespondToAuthChallengeCommandOutput, -} from './types/Sdk'; + ServiceClientFactoryInput, +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createRespondToAuthChallengeClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'RespondToAuthChallenge', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts index 2d1757adb49..4e4f1232eaf 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts @@ -4,10 +4,10 @@ import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { ServiceClientFactoryInput } from './types'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; interface RevokeTokenInput { @@ -17,11 +17,11 @@ interface RevokeTokenInput { type RevokeTokenOutput = Record; -export const createRevokeTokenClient = (config: ServiceClientAPIConfig) => +export const createRevokeTokenClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('RevokeToken'), - buildUserPoolDeserializer(), + createUserPoolSerializer('RevokeToken'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts index 868e3f973b1..9ffdc31fc1e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; import { + ServiceClientFactoryInput, SetUserMFAPreferenceCommandInput, SetUserMFAPreferenceCommandOutput, -} from './types/Sdk'; +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createSetUserMFAPreferenceClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'SetUserMFAPreference', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts index 718603e2757..93880c56702 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts @@ -2,20 +2,23 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; +import { + ServiceClientFactoryInput, + SignUpCommandInput, + SignUpCommandOutput, +} from './types'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { - buildUserPoolDeserializer, - buildUserPoolSerializer, + createUserPoolDeserializer, + createUserPoolSerializer, } from './shared/serialization'; -import { SignUpCommandInput, SignUpCommandOutput } from './types/Sdk'; -export const createSignUpClient = (config: ServiceClientAPIConfig) => +export const createSignUpClient = (config: ServiceClientFactoryInput) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer('SignUp'), - buildUserPoolDeserializer(), + createUserPoolSerializer('SignUp'), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts index a2a6020c3c1..32b4471fbf7 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { + ServiceClientFactoryInput, UpdateDeviceStatusCommandInput, UpdateDeviceStatusCommandOutput, -} from './types/Sdk'; +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createUpdateDeviceStatusClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'UpdateDeviceStatus', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts index 0691e99a006..c37329a47dc 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { + ServiceClientFactoryInput, UpdateUserAttributesCommandInput, UpdateUserAttributesCommandOutput, -} from './types/Sdk'; +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createUpdateUserAttributesClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'UpdateUserAttributes', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts index 00bcac6b69f..355e2dc224e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { + ServiceClientFactoryInput, VerifySoftwareTokenCommandInput, VerifySoftwareTokenCommandOutput, -} from './types/Sdk'; +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createVerifySoftwareTokenClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'VerifySoftwareToken', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts index 96729eaa85a..5417839112c 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts @@ -2,27 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { ServiceClientAPIConfig } from './types/ServiceClient'; -import { cognitoUserPoolTransferHandler } from './shared/handler'; -import { - buildUserPoolDeserializer, - buildUserPoolSerializer, -} from './shared/serialization'; import { + ServiceClientFactoryInput, VerifyUserAttributeCommandInput, VerifyUserAttributeCommandOutput, -} from './types/Sdk'; +} from './types'; +import { cognitoUserPoolTransferHandler } from './shared/handler'; +import { + createUserPoolDeserializer, + createUserPoolSerializer, +} from './shared/serialization'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createVerifyUserAttributeClient = ( - config: ServiceClientAPIConfig, + config: ServiceClientFactoryInput, ) => composeServiceApi( cognitoUserPoolTransferHandler, - buildUserPoolSerializer( + createUserPoolSerializer( 'VerifyUserAttribute', ), - buildUserPoolDeserializer(), + createUserPoolDeserializer(), { ...DEFAULT_SERVICE_CLIENT_API_CONFIG, ...config, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts similarity index 72% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts index cc68d55cb94..005c28e4570 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts @@ -1,27 +1,23 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 - import { HttpResponse, - parseJsonBody, parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils'; import { assertServiceError } from '../../../../../../errors/utils/assertServiceError'; import { AuthError } from '../../../../../../errors/AuthError'; -export const buildUserPoolDeserializer = (): (( +export const createEmptyResponseDeserializer = (): (( response: HttpResponse, -) => Promise) => { - return async (response: HttpResponse): Promise => { +) => Promise) => { + return async (response: HttpResponse): Promise => { if (response.statusCode >= 300) { const error = await parseJsonError(response); assertServiceError(error); throw new AuthError({ name: error.name, message: error.message }); } else { - const body = await parseJsonBody(response); - - return body; + return undefined; } }; }; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts similarity index 85% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts index 8c2a9063164..07a4214f5f0 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts @@ -1,14 +1,16 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 + import { HttpResponse, + parseJsonBody, parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils'; import { assertServiceError } from '../../../../../../errors/utils/assertServiceError'; import { AuthError } from '../../../../../../errors/AuthError'; -export const buildEmptyResponseDeserializer = (): (( +export const createUserPoolDeserializer = (): (( response: HttpResponse, ) => Promise) => { return async (response: HttpResponse): Promise => { @@ -16,8 +18,8 @@ export const buildEmptyResponseDeserializer = (): (( const error = await parseJsonError(response); assertServiceError(error); throw new AuthError({ name: error.name, message: error.message }); - } else { - return undefined as any; } + + return parseJsonBody(response); }; }; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer.ts similarity index 97% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer.ts index ae9c9c64225..81f22df9312 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer.ts @@ -32,7 +32,7 @@ type ClientOperation = | 'ListDevices' | 'RevokeToken'; -export const buildUserPoolSerializer = +export const createUserPoolSerializer = (operation: ClientOperation) => (input: Input, endpoint: Endpoint): HttpRequest => { const headers = getSharedHeaders(operation); diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts index c0e4ae9b71f..bb805866e28 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export { buildUserPoolSerializer } from './buildUserPoolSerializer'; -export { buildUserPoolDeserializer } from './buildUserPoolDeserializer'; -export { buildEmptyResponseDeserializer } from './buildEmptyResponseDeserializer'; +export { createUserPoolSerializer } from './createUserPoolSerializer'; +export { createUserPoolDeserializer } from './createUserPoolDeserializer'; +export { createEmptyResponseDeserializer } from './createEmptyResponseDeserializer'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts index 1df781ff734..3374c6b6194 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/index.ts @@ -1,4 +1,4 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export * from './Sdk'; -export * from './ServiceClient'; +export * from './sdk'; +export * from './serviceClient'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/sdk.ts similarity index 100% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/Sdk.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/sdk.ts diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/serviceClient.ts similarity index 85% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/serviceClient.ts index 3f3821222b7..0f358133832 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/ServiceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/types/serviceClient.ts @@ -3,6 +3,6 @@ import { EndpointResolverOptions } from '@aws-amplify/core/internals/aws-client-utils'; -export interface ServiceClientAPIConfig { +export interface ServiceClientFactoryInput { endpointResolver(options: EndpointResolverOptions): { url: URL }; } From d418f0f3b342fc76e4a3f7f4c8aa9859922b74ca Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 21 Aug 2024 17:06:54 -0700 Subject: [PATCH 08/11] chore: resolve most of the comments from cshfang cont. --- .../serialization/createEmptyResponseDeserializer.ts | 8 +++----- .../shared/serialization/createUserPoolDeserializer.ts | 8 +++----- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts index 005c28e4570..a27f4ef0564 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts @@ -8,10 +8,9 @@ import { import { assertServiceError } from '../../../../../../errors/utils/assertServiceError'; import { AuthError } from '../../../../../../errors/AuthError'; -export const createEmptyResponseDeserializer = (): (( - response: HttpResponse, -) => Promise) => { - return async (response: HttpResponse): Promise => { +export const createEmptyResponseDeserializer = + (): ((response: HttpResponse) => Promise) => + async (response: HttpResponse): Promise => { if (response.statusCode >= 300) { const error = await parseJsonError(response); assertServiceError(error); @@ -20,4 +19,3 @@ export const createEmptyResponseDeserializer = (): (( return undefined; } }; -}; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts index 07a4214f5f0..dc9c16d7d9f 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts @@ -10,10 +10,9 @@ import { import { assertServiceError } from '../../../../../../errors/utils/assertServiceError'; import { AuthError } from '../../../../../../errors/AuthError'; -export const createUserPoolDeserializer = (): (( - response: HttpResponse, -) => Promise) => { - return async (response: HttpResponse): Promise => { +export const createUserPoolDeserializer = + (): ((response: HttpResponse) => Promise) => + async (response: HttpResponse): Promise => { if (response.statusCode >= 300) { const error = await parseJsonError(response); assertServiceError(error); @@ -22,4 +21,3 @@ export const createUserPoolDeserializer = (): (( return parseJsonBody(response); }; -}; From 1c8833650533c9b2fada91f077e287d50784cd0e Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 21 Aug 2024 17:17:39 -0700 Subject: [PATCH 09/11] chore: resolve most of the comments from cshfang cont. 2 --- .../shared/serialization/buildEmptyResponseDeserializer.test.ts | 2 +- .../shared/serialization/buildUserPoolDeserializer.test.ts | 2 +- .../shared/serialization/buildUserPoolSerializer.test.ts | 2 +- .../createAssociateSoftwareTokenClient.ts | 2 +- .../cognitoIdentityProvider/createChangePasswordClient.ts | 2 +- .../cognitoIdentityProvider/createConfirmDeviceClient.ts | 2 +- .../createConfirmForgotPasswordClient.ts | 2 +- .../cognitoIdentityProvider/createConfirmSignUpClient.ts | 2 +- .../cognitoIdentityProvider/createDeleteUserAttributesClient.ts | 2 +- .../cognitoIdentityProvider/createDeleteUserClient.ts | 2 +- .../cognitoIdentityProvider/createForgetDeviceClient.ts | 2 +- .../cognitoIdentityProvider/createForgotPasswordClient.ts | 2 +- .../createGetUserAttributeVerificationCodeClient.ts | 2 +- .../cognitoIdentityProvider/createGetUserClient.ts | 2 +- .../cognitoIdentityProvider/createGlobalSignOutClient.ts | 2 +- .../cognitoIdentityProvider/createInitiateAuthClient.ts | 2 +- .../cognitoIdentityProvider/createListDevicesClient.ts | 2 +- .../createResendConfirmationCodeClient.ts | 2 +- .../createRespondToAuthChallengeClient.ts | 2 +- .../cognitoIdentityProvider/createRevokeTokenClient.ts | 2 +- .../cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts | 2 +- .../cognitoIdentityProvider/createSignUpClient.ts | 2 +- .../cognitoIdentityProvider/createUpdateDeviceStatusClient.ts | 2 +- .../cognitoIdentityProvider/createUpdateUserAttributesClient.ts | 2 +- .../cognitoIdentityProvider/createVerifySoftwareTokenClient.ts | 2 +- .../cognitoIdentityProvider/createVerifyUserAttributeClient.ts | 2 +- .../{serialization => serde}/createEmptyResponseDeserializer.ts | 0 .../{serialization => serde}/createUserPoolDeserializer.ts | 0 .../shared/{serialization => serde}/createUserPoolSerializer.ts | 0 .../shared/{serialization => serde}/index.ts | 0 30 files changed, 26 insertions(+), 26 deletions(-) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization => serde}/createEmptyResponseDeserializer.ts (100%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization => serde}/createUserPoolDeserializer.ts (100%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization => serde}/createUserPoolSerializer.ts (100%) rename packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization => serde}/index.ts (100%) diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts index 9bfb5fa1391..39658867d7e 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts @@ -3,7 +3,7 @@ import { parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils'; -import { createEmptyResponseDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer'; +import { createEmptyResponseDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer'; import { AuthError } from '../../../../../../../src/errors/AuthError'; jest.mock('@aws-amplify/core/internals/aws-client-utils'); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts index 065d2a548bf..18bc775caca 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts @@ -4,7 +4,7 @@ import { parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils'; -import { createUserPoolDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer'; +import { createUserPoolDeserializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer'; import { AuthError } from '../../../../../../../src/errors/AuthError'; jest.mock('@aws-amplify/core/internals/aws-client-utils'); diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts index 3b48d1a5a04..ea117c568eb 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts @@ -1,6 +1,6 @@ import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; -import { createUserPoolSerializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer'; +import { createUserPoolSerializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer'; describe('buildUserPoolSerializer created request serializer', () => { test.each(['SignUp', 'InitiateAuth', 'RevokeToken'] as const)( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts index 757f6bea2d1..4fa07c8a217 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createAssociateSoftwareTokenClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts index ea5a4f0aa90..f8e76959850 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts @@ -6,7 +6,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { ChangePasswordCommandInput, ChangePasswordCommandOutput, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts index fb5fd05e7c1..3d9ced2e060 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts @@ -6,7 +6,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { ConfirmDeviceCommandInput, ConfirmDeviceCommandOutput, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts index ca64848ad74..a300a4ccadb 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createConfirmForgotPasswordClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts index 1eee1f81f94..d5a712af669 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts @@ -7,7 +7,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { ConfirmSignUpCommandInput, ConfirmSignUpCommandOutput, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts index b9e0c5c021a..052ff8c9b0a 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createDeleteUserAttributesClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts index 39c3db1efce..70cb9860ee2 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createEmptyResponseDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createDeleteUserClient = (config: ServiceClientFactoryInput) => diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts index 009d888c2b7..f2851a80f78 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts @@ -6,7 +6,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createEmptyResponseDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { ForgetDeviceCommandInput, ForgetDeviceCommandOutput, diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts index a381b0209f0..965e8475d83 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createForgotPasswordClient = (config: ServiceClientFactoryInput) => diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts index 1354ed2c93e..4b699383ffe 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createGetUserAttributeVerificationCodeClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts index aa38363567e..0a0eed9f070 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createGetUserClient = (config: ServiceClientFactoryInput) => diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts index 422cb43f406..3ef65818bbf 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createGlobalSignOutClient = (config: ServiceClientFactoryInput) => diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts index eef86cb6304..b505144933e 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts @@ -11,7 +11,7 @@ import { import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { cognitoUserPoolTransferHandler } from './shared/handler'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts index ce784df5e6a..b6ec1ffd385 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createListDevicesClient = (config: ServiceClientFactoryInput) => diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts index a94b9b1347c..7fda8d140c5 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createResendConfirmationCodeClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts index 24baa618f6f..736fdfd0ed7 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createRespondToAuthChallengeClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts index 4e4f1232eaf..4deb8a8faf3 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts @@ -6,7 +6,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { ServiceClientFactoryInput } from './types'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts index 9ffdc31fc1e..60b0f4bfddd 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createSetUserMFAPreferenceClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts index 93880c56702..e77676bab1d 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts @@ -12,7 +12,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; export const createSignUpClient = (config: ServiceClientFactoryInput) => composeServiceApi( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts index 32b4471fbf7..9e511187ba5 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createUpdateDeviceStatusClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts index c37329a47dc..5c71001c41d 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createUpdateUserAttributesClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts index 355e2dc224e..c5b63486c42 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createVerifySoftwareTokenClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts index 5417839112c..ad24b27c97a 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts @@ -11,7 +11,7 @@ import { cognitoUserPoolTransferHandler } from './shared/handler'; import { createUserPoolDeserializer, createUserPoolSerializer, -} from './shared/serialization'; +} from './shared/serde'; import { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants'; export const createVerifyUserAttributeClient = ( diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer.ts similarity index 100% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createEmptyResponseDeserializer.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer.ts diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer.ts similarity index 100% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolDeserializer.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer.ts diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.ts similarity index 100% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/createUserPoolSerializer.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.ts diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/index.ts similarity index 100% rename from packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/index.ts rename to packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/index.ts From 49c28c70647cf7547ebe967504a67a810768ff34 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 21 Aug 2024 17:27:55 -0700 Subject: [PATCH 10/11] chore: flatten out the /core from foundation --- .../foundation/core/cognitoUserPoolEndpointResolver.test.ts | 4 ++-- .../auth/__tests__/foundation/core/parsers/getRegion.test.ts | 2 +- .../factories/createCognitoUserPoolEndpointResolver.test.ts | 4 ++-- packages/auth/__tests__/providers/cognito/signOut.test.ts | 4 ++-- .../foundation/{core => }/cognitoUserPoolEndpointResolver.ts | 0 packages/auth/src/foundation/{core => }/constants.ts | 0 .../serviceClients/cognitoIdentityProvider/constants.ts | 2 +- packages/auth/src/foundation/{core => }/parsers/index.ts | 0 .../auth/src/foundation/{core => }/parsers/regionParsers.ts | 2 +- .../auth/src/providers/cognito/apis/confirmResetPassword.ts | 2 +- packages/auth/src/providers/cognito/apis/confirmSignUp.ts | 2 +- .../auth/src/providers/cognito/apis/confirmUserAttribute.ts | 2 +- packages/auth/src/providers/cognito/apis/deleteUser.ts | 2 +- .../auth/src/providers/cognito/apis/deleteUserAttributes.ts | 2 +- packages/auth/src/providers/cognito/apis/fetchDevices.ts | 2 +- .../auth/src/providers/cognito/apis/fetchMFAPreference.ts | 2 +- packages/auth/src/providers/cognito/apis/forgetDevice.ts | 2 +- .../providers/cognito/apis/internal/fetchUserAttributes.ts | 2 +- packages/auth/src/providers/cognito/apis/rememberDevice.ts | 2 +- packages/auth/src/providers/cognito/apis/resendSignUpCode.ts | 2 +- packages/auth/src/providers/cognito/apis/resetPassword.ts | 2 +- .../cognito/apis/sendUserAttributeVerificationCode.ts | 2 +- packages/auth/src/providers/cognito/apis/setUpTOTP.ts | 2 +- packages/auth/src/providers/cognito/apis/signOut.ts | 2 +- packages/auth/src/providers/cognito/apis/signUp.ts | 2 +- .../auth/src/providers/cognito/apis/updateMFAPreference.ts | 2 +- packages/auth/src/providers/cognito/apis/updatePassword.ts | 2 +- .../auth/src/providers/cognito/apis/updateUserAttributes.ts | 2 +- packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts | 2 +- .../cognito/credentialsProvider/IdentityIdProvider.ts | 2 +- .../cognito/credentialsProvider/credentialsProvider.ts | 2 +- .../factories/createCognitoUserPoolEndpointResolver.ts | 2 +- .../auth/src/providers/cognito/utils/refreshAuthTokens.ts | 2 +- packages/auth/src/providers/cognito/utils/signInHelpers.ts | 2 +- 34 files changed, 34 insertions(+), 34 deletions(-) rename packages/auth/src/foundation/{core => }/cognitoUserPoolEndpointResolver.ts (100%) rename packages/auth/src/foundation/{core => }/constants.ts (100%) rename packages/auth/src/foundation/{core => }/parsers/index.ts (100%) rename packages/auth/src/foundation/{core => }/parsers/regionParsers.ts (93%) diff --git a/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts b/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts index ff2fc5282d4..c5d5c90eaf4 100644 --- a/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts +++ b/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts @@ -1,7 +1,7 @@ import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; -import { cognitoUserPoolEndpointResolver } from '../../../src/foundation/core/cognitoUserPoolEndpointResolver'; -import { COGNITO_IDP_SERVICE_NAME } from '../../../src/foundation/core/constants'; +import { cognitoUserPoolEndpointResolver } from '../../../src/foundation/cognitoUserPoolEndpointResolver'; +import { COGNITO_IDP_SERVICE_NAME } from '../../../src/foundation/constants'; describe('cognitoUserPoolEndpointResolver', () => { it('should return the Cognito User Pool endpoint', () => { diff --git a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts b/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts index 6a5780e8d18..e3593846607 100644 --- a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts +++ b/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts @@ -2,7 +2,7 @@ import { AuthError } from '../../../../src/errors/AuthError'; import { getRegionFromIdentityPoolId, getRegionFromUserPoolId, -} from '../../../../src/foundation/core/parsers/regionParsers'; +} from '../../../../src/foundation/parsers/regionParsers'; describe('getRegionFromIdentityPoolId()', () => { it('returns the region from the identity pool id', () => { diff --git a/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts b/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts index b842e95a392..1c499146921 100644 --- a/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts +++ b/packages/auth/__tests__/providers/cognito/factories/createCognitoUserPoolEndpointResolver.test.ts @@ -1,9 +1,9 @@ import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; -import { cognitoUserPoolEndpointResolver } from '../../../../src/foundation/core/cognitoUserPoolEndpointResolver'; +import { cognitoUserPoolEndpointResolver } from '../../../../src/foundation/cognitoUserPoolEndpointResolver'; import { createCognitoUserPoolEndpointResolver } from '../../../../src/providers/cognito/factories/createCognitoUserPoolEndpointResolver'; -jest.mock('../../../../src/foundation/core/cognitoUserPoolEndpointResolver'); +jest.mock('../../../../src/foundation/cognitoUserPoolEndpointResolver'); const mockCognitoUserPoolEndpointResolver = jest.mocked( cognitoUserPoolEndpointResolver, diff --git a/packages/auth/__tests__/providers/cognito/signOut.test.ts b/packages/auth/__tests__/providers/cognito/signOut.test.ts index cedf8bed06d..7facf3a2f4a 100644 --- a/packages/auth/__tests__/providers/cognito/signOut.test.ts +++ b/packages/auth/__tests__/providers/cognito/signOut.test.ts @@ -18,7 +18,7 @@ import { createGlobalSignOutClient, createRevokeTokenClient, } from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; -import { getRegionFromUserPoolId } from '../../../src/foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../src/foundation/parsers'; import { createCognitoUserPoolEndpointResolver } from '../../../src/providers/cognito/factories'; jest.mock('@aws-amplify/core'); @@ -29,7 +29,7 @@ jest.mock('../../../src/utils'); jest.mock( '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', ); -jest.mock('../../../src/foundation/core/parsers'); +jest.mock('../../../src/foundation/parsers'); jest.mock('../../../src/providers/cognito/factories'); describe('signOut', () => { diff --git a/packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts b/packages/auth/src/foundation/cognitoUserPoolEndpointResolver.ts similarity index 100% rename from packages/auth/src/foundation/core/cognitoUserPoolEndpointResolver.ts rename to packages/auth/src/foundation/cognitoUserPoolEndpointResolver.ts diff --git a/packages/auth/src/foundation/core/constants.ts b/packages/auth/src/foundation/constants.ts similarity index 100% rename from packages/auth/src/foundation/core/constants.ts rename to packages/auth/src/foundation/constants.ts diff --git a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts index c013285cfb0..8898f8bc32a 100644 --- a/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts +++ b/packages/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts @@ -8,7 +8,7 @@ import { } from '@aws-amplify/core/internals/aws-client-utils'; import { getAmplifyUserAgent } from '@aws-amplify/core/internals/utils'; -import { COGNITO_IDP_SERVICE_NAME } from '../../../core/constants'; +import { COGNITO_IDP_SERVICE_NAME } from '../../../constants'; export const DEFAULT_SERVICE_CLIENT_API_CONFIG = { service: COGNITO_IDP_SERVICE_NAME, diff --git a/packages/auth/src/foundation/core/parsers/index.ts b/packages/auth/src/foundation/parsers/index.ts similarity index 100% rename from packages/auth/src/foundation/core/parsers/index.ts rename to packages/auth/src/foundation/parsers/index.ts diff --git a/packages/auth/src/foundation/core/parsers/regionParsers.ts b/packages/auth/src/foundation/parsers/regionParsers.ts similarity index 93% rename from packages/auth/src/foundation/core/parsers/regionParsers.ts rename to packages/auth/src/foundation/parsers/regionParsers.ts index da6133b44db..193ddee374d 100644 --- a/packages/auth/src/foundation/core/parsers/regionParsers.ts +++ b/packages/auth/src/foundation/parsers/regionParsers.ts @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { AuthError } from '../../../errors/AuthError'; +import { AuthError } from '../../errors/AuthError'; export function getRegionFromUserPoolId(userPoolId?: string): string { const region = userPoolId?.split('_')[0]; diff --git a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts index 291bd2df2b8..5c4edc100cf 100644 --- a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts @@ -15,7 +15,7 @@ import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; import { createConfirmForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; import { createCognitoUserPoolEndpointResolver } from '../factories'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; /** * Confirms the new password and verification code to reset the password. * diff --git a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts index a5e27decdf3..92adf180210 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts @@ -12,7 +12,7 @@ import { ConfirmSignUpInput, ConfirmSignUpOutput } from '../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { ConfirmSignUpException } from '../types/errors'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { AutoSignInEventData } from '../types/models'; import { isAutoSignInStarted, diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index f580df7b50e..8c0c4dba1ad 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -10,7 +10,7 @@ import { import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { VerifyUserAttributeException } from '../types/errors'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { ConfirmUserAttributeInput } from '../types'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/apis/deleteUser.ts b/packages/auth/src/providers/cognito/apis/deleteUser.ts index 49bd8580a61..53c0c18c6dd 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUser.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUser.ts @@ -7,7 +7,7 @@ import { assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { DeleteUserException } from '../types/errors'; import { tokenOrchestrator } from '../tokenProvider'; diff --git a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts index 1a17d837efb..b958dfacc1f 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts @@ -7,7 +7,7 @@ import { assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { DeleteUserAttributesInput } from '../types'; import { DeleteUserAttributesException } from '../types/errors'; diff --git a/packages/auth/src/providers/cognito/apis/fetchDevices.ts b/packages/auth/src/providers/cognito/apis/fetchDevices.ts index dd1dc8ebe71..c0dc69f22f4 100644 --- a/packages/auth/src/providers/cognito/apis/fetchDevices.ts +++ b/packages/auth/src/providers/cognito/apis/fetchDevices.ts @@ -10,7 +10,7 @@ import { import { FetchDevicesOutput } from '../types'; import { DeviceType } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { assertAuthTokens } from '../utils/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { rememberDevice } from '..'; import { getAuthUserAgentValue } from '../../../utils'; import { createListDevicesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index 3dd30a1d365..e6da216ba81 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -10,7 +10,7 @@ import { import { FetchMFAPreferenceOutput } from '../types'; import { getMFAType, getMFATypes } from '../utils/signInHelpers'; import { GetUserException } from '../types/errors'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; import { createGetUserClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/apis/forgetDevice.ts b/packages/auth/src/providers/cognito/apis/forgetDevice.ts index df17a7262b8..b1ca574e1e4 100644 --- a/packages/auth/src/providers/cognito/apis/forgetDevice.ts +++ b/packages/auth/src/providers/cognito/apis/forgetDevice.ts @@ -8,7 +8,7 @@ import { } from '@aws-amplify/core/internals/utils'; import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { tokenOrchestrator } from '../tokenProvider'; import { ForgetDeviceInput } from '../types'; import { ForgetDeviceException } from '../../cognito/types/errors'; diff --git a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts index 1a984ae00bd..01230bf5153 100644 --- a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts @@ -8,7 +8,7 @@ import { fetchAuthSession, } from '@aws-amplify/core/internals/utils'; -import { getRegionFromUserPoolId } from '../../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../../foundation/parsers'; import { assertAuthTokens } from '../../utils/types'; import { FetchUserAttributesOutput } from '../../types'; import { toAuthUserAttribute } from '../../utils/apiHelpers'; diff --git a/packages/auth/src/providers/cognito/apis/rememberDevice.ts b/packages/auth/src/providers/cognito/apis/rememberDevice.ts index 1fa4a5912da..eb24022096e 100644 --- a/packages/auth/src/providers/cognito/apis/rememberDevice.ts +++ b/packages/auth/src/providers/cognito/apis/rememberDevice.ts @@ -8,7 +8,7 @@ import { } from '@aws-amplify/core/internals/utils'; import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { tokenOrchestrator } from '../tokenProvider'; import { UpdateDeviceStatusException } from '../../cognito/types/errors'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts index 43b324a90ed..cdda7b980eb 100644 --- a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts +++ b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts @@ -12,7 +12,7 @@ import { AuthDeliveryMedium } from '../../../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { ResendSignUpCodeInput, ResendSignUpCodeOutput } from '../types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; import { ResendConfirmationException } from '../types/errors'; diff --git a/packages/auth/src/providers/cognito/apis/resetPassword.ts b/packages/auth/src/providers/cognito/apis/resetPassword.ts index 9190329e778..cd6d37a39ca 100644 --- a/packages/auth/src/providers/cognito/apis/resetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/resetPassword.ts @@ -12,7 +12,7 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthDeliveryMedium } from '../../../types'; import { ResetPasswordInput, ResetPasswordOutput } from '../types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { ForgotPasswordException } from '../../cognito/types/errors'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; diff --git a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts index 7ad297818d8..4b04b2a85d1 100644 --- a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts +++ b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts @@ -14,7 +14,7 @@ import { SendUserAttributeVerificationCodeOutput, } from '../types'; import { assertAuthTokens } from '../utils/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { GetUserAttributeVerificationException } from '../types/errors'; import { getAuthUserAgentValue } from '../../../utils'; import { createGetUserAttributeVerificationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index d5876cad54e..43dac4c787b 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -14,7 +14,7 @@ import { } from '../types/errors'; import { SetUpTOTPOutput } from '../types'; import { getTOTPSetupDetails } from '../utils/signInHelpers'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; import { createAssociateSoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index 132e57ef54e..a56cd64df30 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -20,7 +20,7 @@ import { import { getAuthUserAgentValue } from '../../../utils'; import { SignOutInput } from '../types'; import { tokenOrchestrator } from '../tokenProvider'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens, assertAuthTokensWithRefreshToken, diff --git a/packages/auth/src/providers/cognito/apis/signUp.ts b/packages/auth/src/providers/cognito/apis/signUp.ts index d33aedb7c6d..3ec246648f5 100644 --- a/packages/auth/src/providers/cognito/apis/signUp.ts +++ b/packages/auth/src/providers/cognito/apis/signUp.ts @@ -13,7 +13,7 @@ import { SignInInput, SignUpInput, SignUpOutput } from '../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { SignUpException } from '../types/errors'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { toAttributeType } from '../utils/apiHelpers'; import { autoSignInUserConfirmed, diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index 9bef999800e..5f87522af5a 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -10,7 +10,7 @@ import { import { UpdateMFAPreferenceInput } from '../types'; import { SetUserMFAPreferenceException } from '../types/errors'; import { MFAPreference } from '../types/models'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { CognitoMFASettings } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index b3f2e5c988c..f8c8c4bdeae 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -11,7 +11,7 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { UpdatePasswordInput } from '../types'; import { ChangePasswordException } from '../../cognito/types/errors'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; import { createChangePasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index d99de8988d0..5076e3145a5 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -17,7 +17,7 @@ import { UpdateUserAttributesOutput, } from '../types'; import { assertAuthTokens } from '../utils/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { toAttributeType } from '../utils/apiHelpers'; import { CodeDeliveryDetailsType } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; import { UpdateUserAttributesException } from '../types/errors'; diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index 1a5aac7a916..c5c1212c194 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -11,7 +11,7 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { VerifyTOTPSetupInput } from '../types'; import { VerifySoftwareTokenException } from '../types/errors'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; import { createVerifySoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts index f96082fcde5..b96adf08fbc 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts @@ -5,7 +5,7 @@ import { AuthTokens, ConsoleLogger, Identity, getId } from '@aws-amplify/core'; import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../errors/AuthError'; -import { getRegionFromIdentityPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromIdentityPoolId } from '../../../foundation/parsers'; import { GetIdException } from '../types/errors'; import { IdentityIdStore } from './types'; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index 0e42643fd76..6356ff0fd09 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -15,7 +15,7 @@ import { } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../errors/AuthError'; -import { getRegionFromIdentityPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromIdentityPoolId } from '../../../foundation/parsers'; import { assertIdTokenInAuthTokens } from '../utils/types'; import { IdentityIdStore } from './types'; diff --git a/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts b/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts index e9908dcc384..42a5b979402 100644 --- a/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts +++ b/packages/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts @@ -3,7 +3,7 @@ import { EndpointResolverOptions } from '@aws-amplify/core/internals/aws-client-utils'; import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; -import { cognitoUserPoolEndpointResolver } from '../../../foundation/core/cognitoUserPoolEndpointResolver'; +import { cognitoUserPoolEndpointResolver } from '../../../foundation/cognitoUserPoolEndpointResolver'; export const createCognitoUserPoolEndpointResolver = ({ endpointOverride }: { endpointOverride: string | undefined }) => diff --git a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts index e1b545a42e9..01f35a40b2b 100644 --- a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts +++ b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts @@ -9,7 +9,7 @@ import { } from '@aws-amplify/core/internals/utils'; import { CognitoAuthTokens, TokenRefresher } from '../tokenProvider/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { assertAuthTokensWithRefreshToken } from '../utils/types'; import { AuthError } from '../../../errors/AuthError'; import { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index cb7bd49dd0e..ef4c1422bf3 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -49,7 +49,7 @@ import { RespondToAuthChallengeCommandInput, RespondToAuthChallengeCommandOutput, } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/types'; -import { getRegionFromUserPoolId } from '../../../foundation/core/parsers'; +import { getRegionFromUserPoolId } from '../../../foundation/parsers'; import { signInStore } from './signInStore'; import { assertDeviceMetadata } from './types'; From a9e1b9021ceb2081f156acc85c8f16a2e66dec5f Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 22 Aug 2024 16:02:55 -0700 Subject: [PATCH 11/11] chore: update outdate test file name to match the src changes --- .../{core => }/cognitoUserPoolEndpointResolver.test.ts | 4 ++-- .../createEmptyResponseDeserializer.test.ts} | 2 +- .../createUserPoolDeserializer.test.ts} | 0 .../createUserPoolSerializer.test.ts} | 2 +- .../getRegion.test.ts => parsers/regionParsers.test.ts} | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) rename packages/auth/__tests__/foundation/{core => }/cognitoUserPoolEndpointResolver.test.ts (70%) rename packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization/buildEmptyResponseDeserializer.test.ts => serde/createEmptyResponseDeserializer.test.ts} (95%) rename packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization/buildUserPoolDeserializer.test.ts => serde/createUserPoolDeserializer.test.ts} (100%) rename packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/{serialization/buildUserPoolSerializer.test.ts => serde/createUserPoolSerializer.test.ts} (92%) rename packages/auth/__tests__/foundation/{core/parsers/getRegion.test.ts => parsers/regionParsers.test.ts} (91%) diff --git a/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts b/packages/auth/__tests__/foundation/cognitoUserPoolEndpointResolver.test.ts similarity index 70% rename from packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts rename to packages/auth/__tests__/foundation/cognitoUserPoolEndpointResolver.test.ts index c5d5c90eaf4..04bbff52546 100644 --- a/packages/auth/__tests__/foundation/core/cognitoUserPoolEndpointResolver.test.ts +++ b/packages/auth/__tests__/foundation/cognitoUserPoolEndpointResolver.test.ts @@ -1,7 +1,7 @@ import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; -import { cognitoUserPoolEndpointResolver } from '../../../src/foundation/cognitoUserPoolEndpointResolver'; -import { COGNITO_IDP_SERVICE_NAME } from '../../../src/foundation/constants'; +import { cognitoUserPoolEndpointResolver } from '../../src/foundation/cognitoUserPoolEndpointResolver'; +import { COGNITO_IDP_SERVICE_NAME } from '../../src/foundation/constants'; describe('cognitoUserPoolEndpointResolver', () => { it('should return the Cognito User Pool endpoint', () => { diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer.test.ts similarity index 95% rename from packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts rename to packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer.test.ts index 39658867d7e..80f9ddfedb7 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildEmptyResponseDeserializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer.test.ts @@ -10,7 +10,7 @@ jest.mock('@aws-amplify/core/internals/aws-client-utils'); const mockParseJsonError = jest.mocked(parseJsonError); -describe('buildEmptyResponseDeserializer created response deserializer', () => { +describe('createEmptyResponseDeserializer created response deserializer', () => { const deserializer = createEmptyResponseDeserializer(); it('returns undefined for 2xx status code', async () => { diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer.test.ts similarity index 100% rename from packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolDeserializer.test.ts rename to packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer.test.ts diff --git a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.test.ts similarity index 92% rename from packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts rename to packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.test.ts index ea117c568eb..70d9a054a42 100644 --- a/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serialization/buildUserPoolSerializer.test.ts +++ b/packages/auth/__tests__/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.test.ts @@ -2,7 +2,7 @@ import { AmplifyUrl } from '@aws-amplify/core/internals/utils'; import { createUserPoolSerializer } from '../../../../../../../src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer'; -describe('buildUserPoolSerializer created request serializer', () => { +describe('createUserPoolSerializer created request serializer', () => { test.each(['SignUp', 'InitiateAuth', 'RevokeToken'] as const)( `it serializes requests from operation %s`, operation => { diff --git a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts b/packages/auth/__tests__/foundation/parsers/regionParsers.test.ts similarity index 91% rename from packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts rename to packages/auth/__tests__/foundation/parsers/regionParsers.test.ts index e3593846607..978ac7d8029 100644 --- a/packages/auth/__tests__/foundation/core/parsers/getRegion.test.ts +++ b/packages/auth/__tests__/foundation/parsers/regionParsers.test.ts @@ -1,8 +1,8 @@ -import { AuthError } from '../../../../src/errors/AuthError'; +import { AuthError } from '../../../src/errors/AuthError'; import { getRegionFromIdentityPoolId, getRegionFromUserPoolId, -} from '../../../../src/foundation/parsers/regionParsers'; +} from '../../../src/foundation/parsers/regionParsers'; describe('getRegionFromIdentityPoolId()', () => { it('returns the region from the identity pool id', () => {