From c9b7174773d80f39dc0f2885739b1cc19578da47 Mon Sep 17 00:00:00 2001 From: ManojNB Date: Thu, 14 Sep 2023 12:59:04 -0700 Subject: [PATCH 1/9] chore(auth): general clean up for credentialsProvider and also rename Credentials from sdk (#12021) * fix: remove some errors thrown and update messages * fix: use the new AWSCredsIdentity type * fix: general clean up --------- Co-authored-by: israx <70438514+israx@users.noreply.github.com> Co-authored-by: Francisco Rodriguez --- .../credentialsProvider/IdentityIdProvider.ts | 26 +++++++------- .../credentialsProvider/IdentityIdStore.ts | 34 +++---------------- .../credentialsProvider.ts | 24 +++++-------- .../cognito/credentialsProvider/index.ts | 3 +- .../cognito/credentialsProvider/types.ts | 2 +- .../clients/CognitoIdentityProvider/utils.ts | 2 +- packages/core/src/clients/types/aws.ts | 5 ++- .../core/src/singleton/Auth/utils/index.ts | 6 ++-- 8 files changed, 36 insertions(+), 66 deletions(-) diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts index e2b2923b341..bf22ab56370 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts @@ -10,6 +10,7 @@ import { formLoginsMap } from './credentialsProvider'; import { AuthError } from '../../../errors/AuthError'; import { IdentityIdStore } from './types'; import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; +import { Identity } from '@aws-amplify/core'; const logger = new Logger('CognitoIdentityIdProvider'); @@ -18,9 +19,9 @@ const logger = new Logger('CognitoIdentityIdProvider'); * * @param tokens - The AuthTokens received after SignIn * @returns string - * @throws internal: {@link AuthError } + * @throws configuration excpetions: {@link InvalidIdentityPoolIdException } * - Auth errors that may arise from misconfiguration. - * + * @throws service excpetions: {@link GetIdException } */ export async function cognitoIdentityIdProvider({ tokens, @@ -32,10 +33,13 @@ export async function cognitoIdentityIdProvider({ identityIdStore: IdentityIdStore; }): Promise { identityIdStore.setAuthConfig({ Cognito: authConfig }); - let identityId = await identityIdStore.loadIdentityId(); + // will return null only if there is no identityId cached or if there is an error retrieving it + let identityId: Identity | null = await identityIdStore.loadIdentityId(); + + // Tokens are available so return primary identityId if (tokens) { - // Tokens are available so return primary identityId + // If there is existing primary identityId in-memory return that if (identityId && identityId.type === 'primary') { return identityId.id; } else { @@ -46,10 +50,8 @@ export async function cognitoIdentityIdProvider({ const generatedIdentityId = await generateIdentityId(logins, authConfig); if (identityId && identityId.id === generatedIdentityId) { - // if guestIdentity is found and used by GetCredentialsForIdentity - // it will be linked to the logins provided, and disqualified as an unauth identity logger.debug( - `The guest identity ${identityId.id} has become the primary identity` + `The guest identity ${identityId.id} has become the primary identity.` ); } identityId = { @@ -58,7 +60,7 @@ export async function cognitoIdentityIdProvider({ }; } } else { - // Tokens are avaliable so return guest identityId + // If there is existing guest identityId cached return that if (identityId && identityId.type === 'guest') { return identityId.id; } else { @@ -69,9 +71,8 @@ export async function cognitoIdentityIdProvider({ } } - // Store in-memory or local storage + // Store in-memory or local storage depending on guest or primary identityId identityIdStore.storeIdentityId(identityId); - logger.debug(`The identity being returned ${identityId.id}`); return identityId.id; } @@ -80,7 +81,6 @@ async function generateIdentityId( authConfig: CognitoIdentityPoolConfig ): Promise { const identityPoolId = authConfig?.identityPoolId; - const region = getRegionFromIdentityPoolId(identityPoolId); // IdentityId is absent so get it using IdentityPoolId with Cognito's GetId API @@ -100,8 +100,8 @@ async function generateIdentityId( ).IdentityId; if (!idResult) { throw new AuthError({ - name: 'IdentityIdResponseException', - message: 'Did not receive an identityId from Cognito identity pool', + name: 'GetIdResponseException', + message: 'Received undefined response from getId operation', recoverySuggestion: 'Make sure to pass a valid identityPoolId in the configuration.', }); diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts index 35bdd3903fc..c2013c03621 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts @@ -8,7 +8,6 @@ import { } from '@aws-amplify/core'; import { assertIdentityPooIdConfig } from '@aws-amplify/core/internals/utils'; import { IdentityIdStorageKeys, IdentityIdStore } from './types'; -import { AuthError } from '../../../errors/AuthError'; import { getAuthStorageKeys } from '../tokenProvider/TokenStore'; import { AuthKeys } from '../tokenProvider/types'; @@ -33,18 +32,9 @@ export class DefaultIdentityIdStore implements IdentityIdStore { this.keyValueStorage = keyValueStorage; } - async loadIdentityId(): Promise { + async loadIdentityId(): Promise { assertIdentityPooIdConfig(this.authConfig?.Cognito); - if (this.keyValueStorage === undefined) { - throw new AuthError({ - message: 'No KeyValueStorage available', - name: 'KeyValueStorageNotFound', - recoverySuggestion: - 'Make sure to set the keyValueStorage before using this method', - }); - } // TODO(v6): migration logic should be here - // Reading V5 tokens old format try { if (!!this._primaryIdentityId) { return { @@ -61,30 +51,16 @@ export class DefaultIdentityIdStore implements IdentityIdStore { type: 'guest', }; } + return null; } } catch (err) { // TODO(v6): validate partial results with mobile implementation - throw new Error(`Error loading identityId from storage: ${err}`); + return null; } } async storeIdentityId(identity: Identity): Promise { assertIdentityPooIdConfig(this.authConfig?.Cognito); - if (identity === undefined) { - throw new AuthError({ - message: 'Invalid Identity parameter', - name: 'InvalidAuthIdentity', - recoverySuggestion: 'Make sure a valid Identity object is passed', - }); - } - if (this.keyValueStorage === undefined) { - throw new AuthError({ - message: 'No KeyValueStorage available', - name: 'KeyValueStorageNotFound', - recoverySuggestion: - 'Make sure to set the keyValueStorage before using this method', - }); - } if (identity.type === 'guest') { this.keyValueStorage.setItem(this._authKeys.identityId, identity.id); @@ -99,9 +75,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { async clearIdentityId(): Promise { this._primaryIdentityId = undefined; - await Promise.all([ - this.keyValueStorage.removeItem(this._authKeys.identityId), - ]); + await this.keyValueStorage.removeItem(this._authKeys.identityId); } } diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index 07209f5d441..0c3cfb5cd8a 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -22,7 +22,6 @@ import { assertIdTokenInAuthTokens } from '../utils/types'; const logger = new Logger('CognitoCredentialsProvider'); const CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future - export class CognitoAWSCredentialsAndIdentityIdProvider implements AWSCredentialsAndIdentityIdProvider { @@ -75,21 +74,13 @@ export class CognitoAWSCredentialsAndIdentityIdProvider identityIdStore: this._identityIdStore, }); - if (!identityId) { - throw new AuthError({ - name: 'IdentityIdConfigException', - message: 'No Cognito Identity Id provided', - recoverySuggestion: 'Make sure to pass a valid identityId.', - }); - } - + // Clear cached credentials when forceRefresh is true OR the cache token has changed if (forceRefresh || tokenHasChanged) { this.clearCredentials(); } if (!isAuthenticated) { return this.getGuestCredentials(identityId, authConfig.Cognito); } else { - // Tokens will always be present if getCredentialsOptions.authenticated is true as dictated by the type assertIdTokenInAuthTokens(tokens); return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId); } @@ -99,6 +90,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider identityId: string, authConfig: CognitoIdentityPoolConfig ): Promise { + // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials if ( this._credentialsAndIdentityId && !this.isPastTTL() && @@ -113,12 +105,12 @@ export class CognitoAWSCredentialsAndIdentityIdProvider // Clear to discard if any authenticated credentials are set and start with a clean slate this.clearCredentials(); + const region = getRegionFromIdentityPoolId(authConfig.identityPoolId); + // use identityId to obtain guest credentials // save credentials in-memory // No logins params should be passed for guest creds: // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html - const region = getRegionFromIdentityPoolId(authConfig.identityPoolId); - const clientResult = await getCredentialsForIdentity( { region }, { @@ -157,7 +149,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider return res; } else { throw new AuthError({ - name: 'CredentialsException', + name: 'CredentialsNotFoundException', message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`, }); } @@ -166,7 +158,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider private async credsForOIDCTokens( authConfig: CognitoIdentityPoolConfig, authTokens: AuthTokens, - identityId?: string + identityId: string ): Promise { if ( this._credentialsAndIdentityId && @@ -174,7 +166,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider this._credentialsAndIdentityId.isAuthenticatedCreds === true ) { logger.debug( - 'returning stored credentials as they neither past TTL nor expired' + 'returning stored credentials as they neither past TTL nor expired.' ); return this._credentialsAndIdentityId; } @@ -256,7 +248,7 @@ export function formLoginsMap(idToken: string) { if (!issuer) { throw new AuthError({ name: 'InvalidIdTokenException', - message: 'Invalid Idtoken', + message: 'Invalid Idtoken.', }); } let domainName: string = issuer.replace(/(^\w+:|^)\/\//, ''); diff --git a/packages/auth/src/providers/cognito/credentialsProvider/index.ts b/packages/auth/src/providers/cognito/credentialsProvider/index.ts index 5d1f4577b8d..421f1762a8a 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/index.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/index.ts @@ -9,8 +9,9 @@ import { LocalStorage } from '@aws-amplify/core'; * Cognito specific implmentation of the CredentialsProvider interface * that manages setting and getting of AWS Credentials. * - * @throws internal: {@link AuthError } + * @throws configuration expections: {@link InvalidIdentityPoolIdException } * - Auth errors that may arise from misconfiguration. + * @throws service expections: {@link GetCredentialsForIdentityException}, {@link GetIdException} * */ export const cognitoCredentialsProvider = diff --git a/packages/auth/src/providers/cognito/credentialsProvider/types.ts b/packages/auth/src/providers/cognito/credentialsProvider/types.ts index d572b8c4d11..9ef7dea018c 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/types.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/types.ts @@ -9,7 +9,7 @@ export const IdentityIdStorageKeys = { export interface IdentityIdStore { setAuthConfig(authConfigParam: AuthConfig): void; - loadIdentityId(): Promise; + loadIdentityId(): Promise; storeIdentityId(identity: Identity): Promise; clearIdentityId(): Promise; } diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts index acb7a79a3b0..71ab71bd22c 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts @@ -21,7 +21,7 @@ export function getRegion(userPoolId?: string): string { export function getRegionFromIdentityPoolId(identityPoolId?: string): string { if (!identityPoolId || !identityPoolId.includes(':')) { throw new AuthError({ - name: 'InvalidIdentityPoolId', + name: 'InvalidIdentityPoolIdException', message: 'Invalid identity pool id provided.', recoverySuggestion: 'Make sure a valid identityPoolId is given in the config.', diff --git a/packages/core/src/clients/types/aws.ts b/packages/core/src/clients/types/aws.ts index 5c6aa3baa40..778f136b906 100644 --- a/packages/core/src/clients/types/aws.ts +++ b/packages/core/src/clients/types/aws.ts @@ -5,7 +5,10 @@ import { MetadataBearer } from '@aws-sdk/types'; import { Endpoint } from './core'; import { HttpResponse } from './http'; -export type { Credentials, MetadataBearer } from '@aws-sdk/types'; +export type { + AwsCredentialIdentity as Credentials, + MetadataBearer, +} from '@aws-sdk/types'; export type SourceData = string | ArrayBuffer | ArrayBufferView; diff --git a/packages/core/src/singleton/Auth/utils/index.ts b/packages/core/src/singleton/Auth/utils/index.ts index 31c7f0729f9..0164a0df220 100644 --- a/packages/core/src/singleton/Auth/utils/index.ts +++ b/packages/core/src/singleton/Auth/utils/index.ts @@ -63,10 +63,10 @@ export function assertIdentityPooIdConfig( ): asserts cognitoConfig is CognitoIdentityPoolConfig { const validConfig = !!cognitoConfig?.identityPoolId; return asserts(validConfig, { - name: 'AuthIdentityPoolIdException', - message: 'Auth IdentityPoolId not configured', + name: 'InvalidIdentityPoolIdException', + message: 'Invalid identity pool id provided.', recoverySuggestion: - 'Make sure to call Amplify.configure in your app with a valid IdentityPoolId', + 'Make sure a valid identityPoolId is given in the config.', }); } From 1344695edbf857980767d973c2e5b1e1e301a00e Mon Sep 17 00:00:00 2001 From: Ashwin Kumar Date: Thu, 14 Sep 2023 15:05:37 -0700 Subject: [PATCH 2/9] chore(doc): add doc to provider input output types (#12059) Co-authored-by: Sridhar --- .../src/providers/pinpoint/types/inputs.ts | 6 ++++ .../storage/src/providers/s3/types/inputs.ts | 24 +++++++++++++ .../storage/src/providers/s3/types/outputs.ts | 36 +++++++++++++++++-- 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/packages/analytics/src/providers/pinpoint/types/inputs.ts b/packages/analytics/src/providers/pinpoint/types/inputs.ts index feae0a39fbd..ba55b224190 100644 --- a/packages/analytics/src/providers/pinpoint/types/inputs.ts +++ b/packages/analytics/src/providers/pinpoint/types/inputs.ts @@ -4,6 +4,9 @@ import { UserProfile } from '@aws-amplify/core'; import { PinpointAnalyticsEvent } from '@aws-amplify/core/internals/providers/pinpoint'; +/** + * Input type for Pinpoint record API. + */ export type RecordInput = { /** * An event to send to the default Analytics provider. @@ -11,6 +14,9 @@ export type RecordInput = { event: PinpointAnalyticsEvent; }; +/** + * Input type for Pinpoint identifyUser API. + */ export type IdentifyUserInput = { /** * A User ID associated to the current device. diff --git a/packages/storage/src/providers/s3/types/inputs.ts b/packages/storage/src/providers/s3/types/inputs.ts index 3640d6cd7ca..6596925cbc5 100644 --- a/packages/storage/src/providers/s3/types/inputs.ts +++ b/packages/storage/src/providers/s3/types/inputs.ts @@ -20,19 +20,43 @@ import { UploadDataOptions, } from '../types'; +/** + * Input type for S3 copy API. + */ export type CopyInput = StorageCopyInput; +/** + * Input type for S3 getProperties API. + */ export type GetPropertiesInput = StorageGetPropertiesInput; +/** + * Input type for S3 getUrl API. + */ export type GetUrlInput = StorageGetUrlInput; +/** + * Input type for S3 list API. Lists all bucket objects. + */ export type ListAllInput = StorageListInput; +/** + * Input type for S3 list API. Lists bucket objects with pagination. + */ export type ListPaginateInput = StorageListInput; +/** + * Input type for S3 remove API. + */ export type RemoveInput = StorageRemoveInput; +/** + * Input type for S3 downloadData API. + */ export type DownloadDataInput = StorageDownloadDataInput; +/** + * Input type for S3 uploadData API. + */ export type UploadDataInput = StorageUploadDataInput; diff --git a/packages/storage/src/providers/s3/types/outputs.ts b/packages/storage/src/providers/s3/types/outputs.ts index 1c149a9213a..532a4a455f1 100644 --- a/packages/storage/src/providers/s3/types/outputs.ts +++ b/packages/storage/src/providers/s3/types/outputs.ts @@ -10,6 +10,9 @@ import { UploadTask, } from '../../../types'; +/** + * type for S3 item. + */ export interface Item extends StorageItem { /** * VersionId used to reference a specific version of the object. @@ -21,22 +24,49 @@ export interface Item extends StorageItem { contentType?: string; } +/** + * type for S3 list item. + */ +export type ListOutputItem = Omit; + +/** + * Output type for S3 downloadData API. + */ export type DownloadDataOutput = DownloadTask>; +/** + * Output type for S3 getUrl API. + */ export type GetUrlOutput = StorageGetUrlOutput; +/** + * Output type for S3 uploadData API. + */ export type UploadDataOutput = UploadTask; +/** + * Output type for S3 getProperties API. + */ export type GetPropertiesOutput = Item; -export type ListOutputItem = Omit; - +/** + * Output type for S3 list API. Lists all bucket objects. + */ export type ListAllOutput = StorageListOutput; +/** + * Output type for S3 list API. Lists bucket objects with pagination. + */ export type ListPaginateOutput = StorageListOutput & { nextToken?: string; }; -// TODO: expose more properties if required +/** + * Output type for S3 copy API. + */ export type CopyOutput = Pick; + +/** + * Output type for S3 remove API. + */ export type RemoveOutput = Pick; From 5c781a7947098754bd75a22a7c232d14276bfb56 Mon Sep 17 00:00:00 2001 From: Ashwin Kumar Date: Thu, 14 Sep 2023 15:34:52 -0700 Subject: [PATCH 3/9] fix(Auth): update auth type names (#12050) * chore(auth): rename category level request.ts to input.ts * chore(auth): rename category level result.ts to output.ts * chore(auth): rename provider level requests.ts to inputs.ts * chore(auth): rename provider level result.ts to outputs.ts * fix(auth): align auth input output types * chore(auth): add doc string * chore(auth): expose input output types * fix: don't export SignInXXX types * fix: align other model types --------- Co-authored-by: Sridhar --- packages/auth/src/Errors.ts | 2 +- packages/auth/src/index.ts | 35 ++++- .../cognito/apis/confirmResetPassword.ts | 16 +- .../providers/cognito/apis/confirmSignIn.ts | 24 +-- .../providers/cognito/apis/confirmSignUp.ts | 19 +-- .../cognito/apis/confirmUserAttribute.ts | 12 +- .../cognito/apis/fetchMFAPreference.ts | 8 +- .../cognito/apis/fetchUserAttributes.ts | 8 +- .../providers/cognito/apis/getCurrentUser.ts | 15 +- .../apis/internal/fetchUserAttributes.ts | 5 +- .../cognito/apis/internal/getCurrentUser.ts | 8 +- .../cognito/apis/resendSignUpCode.ts | 27 ++-- .../providers/cognito/apis/resetPassword.ts | 27 ++-- .../apis/server/fetchUserAttributes.ts | 5 +- .../cognito/apis/server/getCurrentUser.ts | 15 +- .../src/providers/cognito/apis/setUpTOTP.ts | 9 +- .../auth/src/providers/cognito/apis/signIn.ts | 24 ++- .../cognito/apis/signInWithCustomAuth.ts | 20 ++- .../cognito/apis/signInWithCustomSRPAuth.ts | 18 +-- .../cognito/apis/signInWithRedirect.ts | 21 ++- .../providers/cognito/apis/signInWithSRP.ts | 19 +-- .../cognito/apis/signInWithUserPassword.ts | 17 ++- .../src/providers/cognito/apis/signOut.ts | 14 +- .../auth/src/providers/cognito/apis/signUp.ts | 33 ++--- .../cognito/apis/updateMFAPreference.ts | 11 +- .../providers/cognito/apis/updatePassword.ts | 11 +- .../cognito/apis/updateUserAttributes.ts | 35 ++--- .../providers/cognito/apis/verifyTOTPSetup.ts | 12 +- packages/auth/src/providers/cognito/index.ts | 32 ++++ .../auth/src/providers/cognito/types/index.ts | 61 ++++++-- .../src/providers/cognito/types/inputs.ts | 137 ++++++++++++++++++ .../src/providers/cognito/types/models.ts | 6 +- .../src/providers/cognito/types/options.ts | 36 ++--- .../src/providers/cognito/types/outputs.ts | 104 +++++++++++++ .../src/providers/cognito/types/requests.ts | 9 -- .../src/providers/cognito/types/results.ts | 9 -- .../providers/cognito/utils/signInHelpers.ts | 32 ++-- packages/auth/src/types/index.ts | 56 +++---- .../auth/src/types/{requests.ts => inputs.ts} | 50 +++---- packages/auth/src/types/models.ts | 26 ++-- .../auth/src/types/{results.ts => outputs.ts} | 29 +--- 41 files changed, 630 insertions(+), 427 deletions(-) create mode 100644 packages/auth/src/providers/cognito/types/inputs.ts create mode 100644 packages/auth/src/providers/cognito/types/outputs.ts delete mode 100644 packages/auth/src/providers/cognito/types/requests.ts delete mode 100644 packages/auth/src/providers/cognito/types/results.ts rename packages/auth/src/types/{requests.ts => inputs.ts} (77%) rename packages/auth/src/types/{results.ts => outputs.ts} (64%) diff --git a/packages/auth/src/Errors.ts b/packages/auth/src/Errors.ts index b68c92e1416..f85cf46c88a 100644 --- a/packages/auth/src/Errors.ts +++ b/packages/auth/src/Errors.ts @@ -3,7 +3,7 @@ // TODO: delete this module when the Auth class is removed. -import { AuthErrorMessages, AuthErrorTypes } from './types'; +import { AuthErrorMessages, AuthErrorTypes } from './types/Auth'; import { ConsoleLogger as Logger } from '@aws-amplify/core/internals/utils'; import { AuthErrorStrings } from './common/AuthErrorStrings'; diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 96975b4ebee..3bc11f17206 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -// Default provider APIs & enums +// Default provider APIs, types & enums export { signUp, resetPassword, @@ -23,6 +23,39 @@ export { signOut, } from './providers/cognito'; +export { + GetCurrentUserInput, + ConfirmResetPasswordInput, + ConfirmSignInInput, + ConfirmSignUpInput, + ConfirmUserAttributeInput, + ResendSignUpCodeInput, + ResetPasswordInput, + SignInInput, + SignInWithRedirectInput, + SignOutInput, + SignUpInput, + UpdateMFAPreferenceInput, + UpdatePasswordInput, + UpdateUserAttributesInput, + VerifyTOTPSetupInput, +} from './providers/cognito'; + +export { + FetchUserAttributesOutput, + GetCurrentUserOutput, + ConfirmSignInOutput, + ConfirmSignUpOutput, + FetchMFAPreferenceOutput, + ResendSignUpCodeOutput, + ResetPasswordOutput, + SetUpTOTPOutput, + SignInOutput, + SignOutOutput, + SignUpOutput, + UpdateUserAttributesOutput, +} from './providers/cognito'; + export { AuthError } from './errors/AuthError'; export { fetchAuthSession } from '@aws-amplify/core'; diff --git a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts index f1e6dff60e0..470de966987 100644 --- a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts @@ -5,30 +5,27 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { ConfirmResetPasswordRequest } from '../../../types'; -import { CognitoConfirmResetPasswordOptions } from '../types'; +import { ConfirmResetPasswordInput } from '../types'; import { confirmForgotPassword } from '../utils/clients/CognitoIdentityProvider'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { ConfirmForgotPasswordException } from '../../cognito/types/errors'; /** * Confirms the new password and verification code to reset the password. * - * @param confirmResetPasswordRequest - The ConfirmResetPasswordRequest object. + * @param input - The ConfirmResetPasswordInput object. * @throws -{@link ConfirmForgotPasswordException } * Thrown due to an invalid confirmation code or password. * @throws -{@link AuthValidationErrorCode } * Thrown due to an empty confirmation code, password or username. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * */ export async function confirmResetPassword( - confirmResetPasswordRequest: ConfirmResetPasswordRequest + input: ConfirmResetPasswordInput ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { username, newPassword } = confirmResetPasswordRequest; + const { username, newPassword } = input; assertValidationError( !!username, AuthValidationErrorCode.EmptyConfirmResetPasswordUsername @@ -38,13 +35,12 @@ export async function confirmResetPassword( !!newPassword, AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword ); - const code = confirmResetPasswordRequest.confirmationCode; + const code = input.confirmationCode; assertValidationError( !!code, AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode ); - const metadata = - confirmResetPasswordRequest.options?.serviceOptions?.clientMetadata; + const metadata = input.options?.serviceOptions?.clientMetadata; await confirmForgotPassword( { region: getRegion(authConfig.userPoolId) }, diff --git a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts index 7bed27595a0..0f7bab9df84 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts @@ -6,12 +6,7 @@ import { RespondToAuthChallengeException, AssociateSoftwareTokenException, } from '../types/errors'; -import { - AuthSignInResult, - ConfirmSignInRequest, -} from '../../../types'; -import { CognitoConfirmSignInOptions } from '../types'; - +import { ConfirmSignInInput, ConfirmSignInOutput } from '../types'; import { cleanActiveSignInState, setActiveSignInState, @@ -38,29 +33,22 @@ import { /** * Continues or completes the sign in process when required by the initial call to `signIn`. * - * @param confirmSignInRequest - The ConfirmSignInRequest object - * + * @param input - The ConfirmSignInInput object + * @returns ConfirmSignInOutput * @throws -{@link VerifySoftwareTokenException }: * Thrown due to an invalid MFA token. - * * @throws -{@link RespondToAuthChallengeException }: * Thrown due to an invalid auth challenge response. - * * @throws -{@link AssociateSoftwareTokenException}: * Thrown due to a service error during the MFA setup process. - * * @throws -{@link AuthValidationErrorCode }: * Thrown when `challengeResponse` is not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns AuthSignInResult - * */ export async function confirmSignIn( - confirmSignInRequest: ConfirmSignInRequest -): Promise { - const { challengeResponse, options } = confirmSignInRequest; + input: ConfirmSignInInput +): Promise { + const { challengeResponse, options } = input; const { username, challengeName, signInSession } = signInStore.getState(); const authConfig = Amplify.getConfig().Auth?.Cognito; diff --git a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts index 8ba0ab36f6b..278fdffa629 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts @@ -3,12 +3,7 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; -import { - AuthSignUpResult, - AuthStandardAttributeKey, - ConfirmSignUpRequest, -} from '../../../types'; -import { CustomAttribute, CognitoConfirmSignUpOptions } from '../types'; +import { ConfirmSignUpInput, ConfirmSignUpOutput } from '../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { ConfirmSignUpException } from '../types/errors'; @@ -18,20 +13,18 @@ import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; /** * Confirms a new user account. * - * @param confirmSignUpRequest - The ConfirmSignUpRequest object. + * @param input - The ConfirmSignUpInput object. + * @returns ConfirmSignUpOutput * @throws -{@link ConfirmSignUpException } * Thrown due to an invalid confirmation code. * @throws -{@link AuthValidationErrorCode } * Thrown due to an empty confirmation code - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns AuthSignUpResult */ export async function confirmSignUp( - confirmSignUpRequest: ConfirmSignUpRequest -): Promise> { - const { username, confirmationCode, options } = confirmSignUpRequest; + input: ConfirmSignUpInput +): Promise { + const { username, confirmationCode, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index ef40979f856..a1a3e1b6c25 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -5,32 +5,28 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { ConfirmUserAttributeRequest } from '../../../types/requests'; import { verifyUserAttribute } from '../utils/clients/CognitoIdentityProvider'; import { VerifyUserAttributeException } from '../types/errors'; import { fetchAuthSession } from '../../../'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; -import { CognitoUserAttributeKey } from '../types'; +import { ConfirmUserAttributeInput } from '../types'; /** * Confirms a user attribute with the confirmation code. * - * @param confirmUserAttributeRequest - The ConfirmUserAttributeRequest - * + * @param input - The ConfirmUserAttributeInput object * @throws -{@link AuthValidationErrorCode } - * Thrown when `confirmationCode` is not defined. - * * @throws -{@link VerifyUserAttributeException } - Thrown due to an invalid confirmation code or attribute. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function confirmUserAttribute( - confirmUserAttributeRequest: ConfirmUserAttributeRequest + input: ConfirmUserAttributeInput ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { confirmationCode, userAttributeKey } = confirmUserAttributeRequest; + const { confirmationCode, userAttributeKey } = input; assertValidationError( !!confirmationCode, AuthValidationErrorCode.EmptyConfirmUserAttributeCode diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index 4e35057f210..34e27bb29b6 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { FetchMFAPreferenceResult } from '../types/results'; +import { FetchMFAPreferenceOutput } from '../types'; import { getMFAType, getMFATypes } from '../utils/signInHelpers'; import { GetUserException } from '../types/errors'; import { getUser } from '../utils/clients/CognitoIdentityProvider'; @@ -13,13 +13,13 @@ import { assertAuthTokens } from '../utils/types'; /** * Fetches the preferred MFA setting and enabled MFA settings for the user. + * + * @returns FetchMFAPreferenceOutput * @throws -{@link GetUserException} : error thrown when the service fails to fetch MFA preference * and settings. * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns FetchMFAPreferenceResult */ -export async function fetchMFAPreference(): Promise { +export async function fetchMFAPreference(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { tokens } = await fetchAuthSession({ forceRefresh: false }); diff --git a/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts index bebda73e2aa..79ba1e48b8a 100644 --- a/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts @@ -2,19 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import { AuthUserAttribute } from '../../../types'; -import { CognitoUserAttributeKey } from '../types'; +import { FetchUserAttributesOutput } from '../types'; import { fetchUserAttributes as fetchUserAttributesInternal } from './internal/fetchUserAttributes'; /** * Fetches the current user attributes while authenticated. * * @throws - {@link GetUserException} - Cognito service errors thrown when the service is not able to get the user. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ -export const fetchUserAttributes = (): Promise< - AuthUserAttribute -> => { +export const fetchUserAttributes = (): Promise => { return fetchUserAttributesInternal(Amplify); }; diff --git a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts index 804166579f0..19fa2719096 100644 --- a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts @@ -2,22 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import { AuthUser, GetCurrentUserRequest } from '../../../types'; +import { GetCurrentUserInput, GetCurrentUserOutput } from '../types'; import { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentUser'; /** * Gets the current user from the idToken. * - * @param getCurrentUserRequest - The request object. - * + * @param input - The GetCurrentUserInput object. + * @returns GetCurrentUserOutput * @throws - {@link InitiateAuthException} - Thrown when the service fails to refresh the tokens. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns AuthUser */ export const getCurrentUser = async ( - getCurrentUserRequest?: GetCurrentUserRequest -): Promise => { - return getCurrentUserInternal(Amplify, getCurrentUserRequest); + input?: GetCurrentUserInput +): Promise => { + return getCurrentUserInternal(Amplify, input); }; diff --git a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts index 4322cbf5c6e..22fb636b81a 100644 --- a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts @@ -7,15 +7,14 @@ import { fetchAuthSession, } from '@aws-amplify/core/internals/utils'; import { getUser } from '../../utils/clients/CognitoIdentityProvider'; -import { AuthUserAttribute } from '../../../../types'; import { getRegion } from '../../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../../utils/types'; -import { CognitoUserAttributeKey } from '../../types'; +import { FetchUserAttributesOutput } from '../../types'; import { toAuthUserAttribute } from '../../utils/apiHelpers'; export const fetchUserAttributes = async ( amplify: AmplifyClassV6 -): Promise> => { +): Promise => { const authConfig = amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { tokens } = await fetchAuthSession(amplify, { diff --git a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts index 43f23087617..093cc506dd1 100644 --- a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts @@ -6,17 +6,17 @@ import { assertTokenProviderConfig, fetchAuthSession, } from '@aws-amplify/core/internals/utils'; -import { GetCurrentUserRequest, AuthUser } from '../../../../types'; +import { GetCurrentUserInput, GetCurrentUserOutput } from '../../types'; import { assertAuthTokens } from '../../utils/types'; export const getCurrentUser = async ( amplify: AmplifyClassV6, - getCurrentUserRequest?: GetCurrentUserRequest -): Promise => { + input?: GetCurrentUserInput +): Promise => { const authConfig = amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { tokens } = await fetchAuthSession(amplify, { - forceRefresh: getCurrentUserRequest?.recache ?? false, + forceRefresh: input?.recache ?? false, }); assertAuthTokens(tokens); const { 'cognito:username': username, sub } = tokens.idToken?.payload ?? {}; diff --git a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts index 8051e9754aa..2385908077a 100644 --- a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts +++ b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts @@ -3,42 +3,33 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; -import { - AuthCodeDeliveryDetails, - AuthStandardAttributeKey, - DeliveryMedium, - ResendSignUpCodeRequest, -} from '../../../types'; +import { AuthStandardAttributeKey, AuthDeliveryMedium } from '../../../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; -import { - CognitoResendSignUpCodeOptions, - CognitoUserAttributeKey, -} from '../types'; +import { ResendSignUpCodeInput, ResendSignUpCodeOutput } from '../types'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { resendConfirmationCode } from '../utils/clients/CognitoIdentityProvider'; /** * Resend the confirmation code while signing up * - * @param resendRequest - The resendRequest object - * @returns AuthCodeDeliveryDetails + * @param input - The ResendSignUpCodeInput object + * @returns ResendSignUpCodeOutput * @throws service: {@link ResendConfirmationException } - Cognito service errors thrown when resending the code. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown either username are not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function resendSignUpCode( - resendRequest: ResendSignUpCodeRequest -): Promise> { - const username = resendRequest.username; + input: ResendSignUpCodeInput +): Promise { + const username = input.username; assertValidationError( !!username, AuthValidationErrorCode.EmptySignUpUsername ); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const clientMetadata = resendRequest.options?.serviceOptions?.clientMetadata; + const clientMetadata = input.options?.serviceOptions?.clientMetadata; const { CodeDeliveryDetails } = await resendConfirmationCode( { region: getRegion(authConfig.userPoolId) }, { @@ -52,7 +43,7 @@ export async function resendSignUpCode( }; return { destination: Destination as string, - deliveryMedium: DeliveryMedium as DeliveryMedium, + deliveryMedium: DeliveryMedium as AuthDeliveryMedium, attributeName: AttributeName ? (AttributeName as AuthStandardAttributeKey) : undefined, diff --git a/packages/auth/src/providers/cognito/apis/resetPassword.ts b/packages/auth/src/providers/cognito/apis/resetPassword.ts index 6d23aaecce6..a569ff9bc24 100644 --- a/packages/auth/src/providers/cognito/apis/resetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/resetPassword.ts @@ -5,13 +5,8 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { - AuthStandardAttributeKey, - DeliveryMedium, - ResetPasswordRequest, - ResetPasswordResult, -} from '../../../types'; -import { CognitoResetPasswordOptions, CustomAttribute } from '../types'; +import { AuthDeliveryMedium, AuthStandardAttributeKey } from '../../../types'; +import { ResetPasswordInput, ResetPasswordOutput } from '../types'; import { forgotPassword } from '../utils/clients/CognitoIdentityProvider'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { ForgotPasswordException } from '../../cognito/types/errors'; @@ -19,28 +14,25 @@ import { ForgotPasswordException } from '../../cognito/types/errors'; /** * Resets a user's password. * - * @param resetPasswordRequest - The ResetPasswordRequest object. + * @param input - The ResetPasswordInput object. + * @returns ResetPasswordOutput * @throws -{@link ForgotPasswordException } * Thrown due to an invalid confirmation code or password. * @throws -{@link AuthValidationErrorCode } * Thrown due to an empty username. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns ResetPasswordResult **/ export async function resetPassword( - resetPasswordRequest: ResetPasswordRequest -): Promise> { - const username = resetPasswordRequest.username; + input: ResetPasswordInput +): Promise { + const username = input.username; assertValidationError( !!username, AuthValidationErrorCode.EmptyResetPasswordUsername ); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const clientMetadata = - resetPasswordRequest.options?.serviceOptions?.clientMetadata; + const clientMetadata = input.options?.serviceOptions?.clientMetadata; const res = await forgotPassword( { region: getRegion(authConfig.userPoolId) }, { @@ -55,7 +47,8 @@ export async function resetPassword( nextStep: { resetPasswordStep: 'CONFIRM_RESET_PASSWORD_WITH_CODE', codeDeliveryDetails: { - deliveryMedium: codeDeliveryDetails?.DeliveryMedium as DeliveryMedium, + deliveryMedium: + codeDeliveryDetails?.DeliveryMedium as AuthDeliveryMedium, destination: codeDeliveryDetails?.Destination as string, attributeName: codeDeliveryDetails?.AttributeName as AuthStandardAttributeKey, diff --git a/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts index c8a2960f701..b80f5ea4a2f 100644 --- a/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts @@ -5,13 +5,12 @@ import { AmplifyServer, getAmplifyServerContext, } from '@aws-amplify/core/internals/adapter-core'; -import { AuthUserAttribute } from '../../../../types'; -import { CognitoUserAttributeKey } from '../../types'; +import { FetchUserAttributesOutput } from '../../types'; import { fetchUserAttributes as fetchUserAttributesInternal } from '../internal/fetchUserAttributes'; export const fetchUserAttributes = ( contextSpec: AmplifyServer.ContextSpec -): Promise> => { +): Promise => { return fetchUserAttributesInternal( getAmplifyServerContext(contextSpec).amplify ); diff --git a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts index 94914b878a3..f59de229943 100644 --- a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts @@ -5,26 +5,23 @@ import { AmplifyServer, getAmplifyServerContext, } from '@aws-amplify/core/internals/adapter-core'; -import { AuthUser, GetCurrentUserRequest } from '../../../../types'; +import { GetCurrentUserOutput, GetCurrentUserInput } from '../../types'; import { getCurrentUser as getCurrentUserInternal } from '../internal/getCurrentUser'; /** * Gets the current user from the idToken. * - * @param getCurrentUserRequest - The request object. - * + * @param input - The GetCurrentUserInput object. + * @returns GetCurrentUserOutput * @throws - {@link InitiateAuthException} - Thrown when the service fails to refresh the tokens. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns AuthUser */ export const getCurrentUser = async ( contextSpec: AmplifyServer.ContextSpec, - getCurrentUserRequest?: GetCurrentUserRequest -): Promise => { + input?: GetCurrentUserInput +): Promise => { return getCurrentUserInternal( getAmplifyServerContext(contextSpec).amplify, - getCurrentUserRequest + input ); }; diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index 5db0d6241bd..5df778e4eac 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -5,11 +5,11 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { fetchAuthSession } from '../../../'; import { AuthError } from '../../../errors/AuthError'; -import { TOTPSetupDetails } from '../../../types/models'; import { SETUP_TOTP_EXCEPTION, AssociateSoftwareTokenException, } 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'; @@ -18,15 +18,12 @@ import { assertAuthTokens } from '../utils/types'; /** * Sets up TOTP for the user. * + * @returns SetUpTOTPOutput * @throws -{@link AssociateSoftwareTokenException} * Thrown if a service occurs while setting up TOTP. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns TOTPSetupDetails - * **/ -export async function setUpTOTP(): Promise { +export async function setUpTOTP(): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { tokens } = await fetchAuthSession({ forceRefresh: false }); diff --git a/packages/auth/src/providers/cognito/apis/signIn.ts b/packages/auth/src/providers/cognito/apis/signIn.ts index f46ee2b504c..46ec83c5eb1 100644 --- a/packages/auth/src/providers/cognito/apis/signIn.ts +++ b/packages/auth/src/providers/cognito/apis/signIn.ts @@ -9,35 +9,31 @@ import { signInWithCustomAuth } from './signInWithCustomAuth'; import { signInWithCustomSRPAuth } from './signInWithCustomSRPAuth'; import { signInWithSRP } from './signInWithSRP'; import { signInWithUserPassword } from './signInWithUserPassword'; -import { AuthSignInResult, SignInRequest } from '../../../types'; -import { CognitoSignInOptions } from '../types'; +import { SignInInput, SignInOutput } from '../types'; /** * Signs a user in * - * @param signInRequest - The SignInRequest object - * @returns AuthSignInResult + * @param input - The SignInInput object + * @returns SignInOutput * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } * - Cognito service errors thrown during the sign-in process. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password * are not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ -export async function signIn( - signInRequest: SignInRequest -): Promise { - const authFlowType = signInRequest.options?.serviceOptions?.authFlowType; +export async function signIn(input: SignInInput): Promise { + const authFlowType = input.options?.serviceOptions?.authFlowType; switch (authFlowType) { case 'USER_SRP_AUTH': - return signInWithSRP(signInRequest); + return signInWithSRP(input); case 'USER_PASSWORD_AUTH': - return signInWithUserPassword(signInRequest); + return signInWithUserPassword(input); case 'CUSTOM_WITHOUT_SRP': - return signInWithCustomAuth(signInRequest); + return signInWithCustomAuth(input); case 'CUSTOM_WITH_SRP': - return signInWithCustomSRPAuth(signInRequest); + return signInWithCustomSRPAuth(input); default: - return signInWithSRP(signInRequest); + return signInWithSRP(input); } } diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts index 9870c14adad..f642624e2c5 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts @@ -3,10 +3,6 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { - SignInRequest, - AuthSignInResult, -} from '../../../types'; import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { handleCustomAuthFlowWithoutSRP, @@ -16,7 +12,10 @@ import { import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { InitiateAuthException } from '../types/errors'; -import { CognitoSignInOptions } from '../types'; +import { + SignInWithCustomAuthInput, + SignInWithCustomAuthOutput, +} from '../types'; import { cleanActiveSignInState, setActiveSignInState, @@ -30,20 +29,19 @@ import { /** * Signs a user in using a custom authentication flow without password * - * @param signInRequest - The SignInRequest object + * @param input - The SignInWithCustomAuthInput object * @returns AuthSignInResult * @throws service: {@link InitiateAuthException } - Cognito service errors thrown during the sign-in process. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password * are not defined. - * - * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. + * @throws SignInWithCustomAuthOutput - Thrown when the token provider config is invalid. */ export async function signInWithCustomAuth( - signInRequest: SignInRequest -): Promise { + input: SignInWithCustomAuthInput +): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { username, password, options } = signInRequest; + const { username, password, options } = input; const metadata = options?.serviceOptions?.clientMetadata; assertValidationError( !!username, diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts index 2eaefdb552a..43489ba2935 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts @@ -16,10 +16,9 @@ import { RespondToAuthChallengeException, } from '../types/errors'; import { - SignInRequest, - AuthSignInResult, -} from '../../../types'; -import { CognitoSignInOptions } from '../types'; + SignInWithCustomSRPAuthInput, + SignInWithCustomSRPAuthOutput, +} from '../types'; import { cleanActiveSignInState, setActiveSignInState, @@ -33,19 +32,18 @@ import { /** * Signs a user in using a custom authentication flow with SRP * - * @param signInRequest - The SignInRequest object - * @returns AuthSignInResult + * @param input - The SignInWithCustomSRPAuthInput object + * @returns SignInWithCustomSRPAuthOutput * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito * service errors thrown during the sign-in process. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password * are not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signInWithCustomSRPAuth( - signInRequest: SignInRequest -): Promise { - const { username, password, options } = signInRequest; + input: SignInWithCustomSRPAuthInput +): Promise { + const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const metadata = options?.serviceOptions?.clientMetadata; diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index 0d4313a5472..2d8bae03995 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -10,7 +10,6 @@ import { urlSafeEncode, USER_AGENT_HEADER, } from '@aws-amplify/core/internals/utils'; -import { SignInWithRedirectRequest } from '../../../types/requests'; import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; import { CognitoUserPoolsTokenProvider } from '../tokenProvider'; import { @@ -21,40 +20,38 @@ import { import { cognitoHostedUIIdentityProviderMap } from '../types/models'; import { DefaultOAuthStore } from '../utils/signInWithRedirectStore'; import { AuthError } from '../../../errors/AuthError'; -import { AuthErrorTypes } from '../../../types'; +import { AuthErrorTypes } from '../../../types/Auth'; import { AuthErrorCodes } from '../../../common/AuthErrorStrings'; import { authErrorMessages } from '../../../Errors'; +import { SignInWithRedirectInput } from '../types'; const SELF = '_self'; /** * Signs in a user with OAuth. Redirects the application to an Identity Provider. * - * @param signInRedirectRequest - The SignInRedirectRequest object, if empty it will redirect to Cognito HostedUI + * @param input - The SignInWithRedirectInput object, if empty it will redirect to Cognito HostedUI * * TODO: add config errors */ -export function signInWithRedirect( - signInWithRedirectRequest?: SignInWithRedirectRequest -): void { +export function signInWithRedirect(input?: SignInWithRedirectInput): void { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); assertOAuthConfig(authConfig); store.setAuthConfig(authConfig); let provider = 'COGNITO'; // Default - if (typeof signInWithRedirectRequest?.provider === 'string') { - provider = - cognitoHostedUIIdentityProviderMap[signInWithRedirectRequest.provider]; - } else if (signInWithRedirectRequest?.provider?.custom) { - provider = signInWithRedirectRequest.provider.custom; + if (typeof input?.provider === 'string') { + provider = cognitoHostedUIIdentityProviderMap[input.provider]; + } else if (input?.provider?.custom) { + provider = input.provider.custom; } oauthSignIn({ oauthConfig: authConfig.loginWith.oauth, clientId: authConfig.userPoolClientId, provider, - customState: signInWithRedirectRequest?.customState, + customState: input?.customState, }); } diff --git a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts index 802fba6076b..9a93d0b9952 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts @@ -19,11 +19,7 @@ import { getSignInResultFromError, handleUserSRPAuthFlow, } from '../utils/signInHelpers'; -import { CognitoSignInOptions } from '../types'; -import { - SignInRequest, - AuthSignInResult, -} from '../../../types'; +import { SignInWithSRPInput, SignInWithSRPOutput } from '../types'; import { setActiveSignInState, cleanActiveSignInState, @@ -33,22 +29,21 @@ import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; /** * Signs a user in * - * @param signInRequest - The SignInRequest object - * @returns AuthSignInResult + * @param input - The SignInWithSRPInput object + * @returns SignInWithSRPOutput * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito service errors * thrown during the sign-in process. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password * are not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signInWithSRP( - signInRequest: SignInRequest -): Promise { - const { username, password } = signInRequest; + input: SignInWithSRPInput +): Promise { + const { username, password } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const clientMetaData = signInRequest.options?.serviceOptions?.clientMetadata; + const clientMetaData = input.options?.serviceOptions?.clientMetadata; assertValidationError( !!username, AuthValidationErrorCode.EmptySignInUsername diff --git a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts index c07f18f4096..34e266313f7 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts @@ -4,7 +4,6 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { AuthSignInResult, SignInRequest } from '../../../types'; import { ChallengeName, ChallengeParameters, @@ -17,7 +16,10 @@ import { import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { InitiateAuthException } from '../types/errors'; -import { CognitoSignInOptions } from '../types'; +import { + SignInWithUserPasswordInput, + SignInWithUserPasswordOutput, +} from '../types'; import { cleanActiveSignInState, setActiveSignInState, @@ -27,18 +29,17 @@ import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; /** * Signs a user in using USER_PASSWORD_AUTH AuthFlowType * - * @param signInRequest - The SignInRequest object - * @returns AuthSignInResult + * @param input - The SignInWithUserPasswordInput object + * @returns SignInWithUserPasswordOutput * @throws service: {@link InitiateAuthException } - Cognito service error thrown during the sign-in process. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password * are not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signInWithUserPassword( - signInRequest: SignInRequest -): Promise { - const { username, password, options } = signInRequest; + input: SignInWithUserPasswordInput +): Promise { + const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const metadata = options?.serviceOptions?.clientMetadata; diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index e165b25db07..15192941f46 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -7,8 +7,7 @@ import { LocalStorage, clearCredentials, } from '@aws-amplify/core'; -import { SignOutRequest } from '../../../types/requests'; -import { AuthSignOutResult } from '../../../types/results'; +import { SignOutInput, SignOutOutput } from '../types'; import { DefaultOAuthStore } from '../utils/signInWithRedirectStore'; import { tokenOrchestrator } from '../tokenProvider'; import { @@ -31,18 +30,15 @@ const SELF = '_self'; /** * Signs a user out * - * @param signOutRequest - The SignOutRequest object - * @returns AuthSignOutResult - * + * @param input - The SignOutInput object + * @returns SignOutOutput * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ -export async function signOut( - signOutRequest?: SignOutRequest -): Promise { +export async function signOut(input?: SignOutInput): Promise { const cognitoConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(cognitoConfig); - if (signOutRequest?.global) { + if (input?.global) { return globalSignOut(cognitoConfig); } else { return clientSignOut(cognitoConfig); diff --git a/packages/auth/src/providers/cognito/apis/signUp.ts b/packages/auth/src/providers/cognito/apis/signUp.ts index 79708b6cfce..2dc5340e15b 100644 --- a/packages/auth/src/providers/cognito/apis/signUp.ts +++ b/packages/auth/src/providers/cognito/apis/signUp.ts @@ -3,17 +3,8 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; -import { - AuthSignUpResult, - AuthStandardAttributeKey, - DeliveryMedium, - SignUpRequest, -} from '../../../types'; -import { - CognitoSignUpOptions, - CustomAttribute, - CognitoUserAttributeKey, -} from '../types'; +import { AuthDeliveryMedium } from '../../../types'; +import { UserAttributeKey, SignUpInput, SignUpOutput } from '../types'; import { signUp as signUpClient } from '../utils/clients/CognitoIdentityProvider'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; @@ -25,21 +16,17 @@ import { toAttributeType } from '../utils/apiHelpers'; /** * Creates a user * - * @param signUpRequest - The SignUpRequest object - * @returns AuthSignUpResult + * @param input - The SignUpInput object + * @returns SignUpOutput * @throws service: {@link SignUpException } - Cognito service errors thrown during the sign-up process. * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown either username or password * are not defined. - * - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ -export async function signUp( - signUpRequest: SignUpRequest -): Promise> { - const { username, password, options } = signUpRequest; +export async function signUp(input: SignUpInput): Promise { + const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; - const clientMetadata = signUpRequest.options?.serviceOptions?.clientMetadata; + const clientMetadata = input.options?.serviceOptions?.clientMetadata; assertTokenProviderConfig(authConfig); assertValidationError( !!username, @@ -87,10 +74,10 @@ export async function signUp( nextStep: { signUpStep: 'CONFIRM_SIGN_UP', codeDeliveryDetails: { - deliveryMedium: CodeDeliveryDetails?.DeliveryMedium as DeliveryMedium, + deliveryMedium: + CodeDeliveryDetails?.DeliveryMedium as AuthDeliveryMedium, destination: CodeDeliveryDetails?.Destination as string, - attributeName: - CodeDeliveryDetails?.AttributeName as CognitoUserAttributeKey, + attributeName: CodeDeliveryDetails?.AttributeName as UserAttributeKey, }, }, userId: UserSub, diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index b8f531fa77e..aaefe4b372e 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -4,7 +4,7 @@ import { Amplify } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { fetchAuthSession } from '../../../'; -import { UpdateMFAPreferenceRequest } from '../types'; +import { UpdateMFAPreferenceInput } from '../types'; import { SetUserMFAPreferenceException } from '../types/errors'; import { MFAPreference } from '../types/models'; import { setUserMFAPreference } from '../utils/clients/CognitoIdentityProvider'; @@ -15,17 +15,14 @@ import { assertAuthTokens } from '../utils/types'; /** * Updates the MFA preference of the user. * - * @param updateMFAPreferenceRequest - The request object to update MFA preference. - * + * @param input - The UpdateMFAPreferenceInput object. * @throws -{@link SetUserMFAPreferenceException } - Service error thrown when the MFA preference cannot be updated. - * - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function updateMFAPreference( - updateMFAPreferenceRequest: UpdateMFAPreferenceRequest + input: UpdateMFAPreferenceInput ): Promise { - const { sms, totp } = updateMFAPreferenceRequest; + const { sms, totp } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { tokens } = await fetchAuthSession({ forceRefresh: false }); diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index a44b1823861..32c90b40d1f 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -3,7 +3,7 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { UpdatePasswordRequest } from '../../../types/requests'; +import { UpdatePasswordInput } from '../types'; import { changePassword } from '../utils/clients/CognitoIdentityProvider'; import { ChangePasswordException } from '../../cognito/types/errors'; import { Amplify } from '@aws-amplify/core'; @@ -15,20 +15,17 @@ import { assertAuthTokens } from '../utils/types'; /** * Updates user's password while authenticated. * - * @param updatePasswordRequest - The updatePasswordRequest object. - * + * @param input - The UpdatePasswordInput object. * @throws - {@link ChangePasswordException} - Cognito service errors thrown when updating a password. - * * @throws - {@link AuthValidationErrorCode} - Validation errors thrown when oldPassword or newPassword are empty. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function updatePassword( - updatePasswordRequest: UpdatePasswordRequest + input: UpdatePasswordInput ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { oldPassword, newPassword } = updatePasswordRequest; + const { oldPassword, newPassword } = input; assertValidationError( !!oldPassword, AuthValidationErrorCode.EmptyUpdatePassword diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index d052024da4b..4672b90bada 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -6,13 +6,12 @@ import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { fetchAuthSession } from '../../../'; import { AuthUserAttribute, - UpdateUserAttributesRequest, - UpdateUserAttributesResult, - DeliveryMedium, + AuthUpdateUserAttributesOutput, + AuthDeliveryMedium, } from '../../../types'; import { - CognitoUpdateUserAttributesOptions, - CognitoUserAttributeKey, + UpdateUserAttributesInput, + UpdateUserAttributesOutput, } from '../types'; import { updateUserAttributes as updateUserAttributesClient } from '../utils/clients/CognitoIdentityProvider'; import { assertAuthTokens } from '../utils/types'; @@ -24,21 +23,15 @@ import { UpdateUserAttributesException } from '../types/errors'; /** * Updates user's attributes while authenticated. * - * @param updateUserAttributesRequest - The UpdateUserAttributesRequest object - * + * @param input - The UpdateUserAttributesInput object + * @returns UpdateUserAttributesOutput * @throws - {@link UpdateUserAttributesException} - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. - * - * @returns UpdateUserAttributesResult */ export const updateUserAttributes = async ( - updateUserAttributesRequest: UpdateUserAttributesRequest< - CognitoUserAttributeKey, - CognitoUpdateUserAttributesOptions - > -): Promise> => { - const { userAttributes, options } = updateUserAttributesRequest; + input: UpdateUserAttributesInput +): Promise => { + const { userAttributes, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const clientMetadata = options?.serviceOptions?.clientMetadata; assertTokenProviderConfig(authConfig); @@ -61,8 +54,8 @@ export const updateUserAttributes = async ( function getConfirmedAttributes( attributes: AuthUserAttribute -): UpdateUserAttributesResult { - const confirmedAttributes = {} as UpdateUserAttributesResult; +): AuthUpdateUserAttributesOutput { + const confirmedAttributes = {} as AuthUpdateUserAttributesOutput; Object.keys(attributes)?.forEach(key => { confirmedAttributes[key] = { isUpdated: true, @@ -77,8 +70,8 @@ function getConfirmedAttributes( function getUnConfirmedAttributes( codeDeliveryDetailsList?: CodeDeliveryDetailsType[] -): UpdateUserAttributesResult { - const unConfirmedAttributes = {} as UpdateUserAttributesResult; +): AuthUpdateUserAttributesOutput { + const unConfirmedAttributes = {} as AuthUpdateUserAttributesOutput; codeDeliveryDetailsList?.forEach(codeDeliveryDetails => { const { AttributeName, DeliveryMedium, Destination } = codeDeliveryDetails; if (AttributeName) @@ -88,7 +81,7 @@ function getUnConfirmedAttributes( updateAttributeStep: 'CONFIRM_ATTRIBUTE_WITH_CODE', codeDeliveryDetails: { attributeName: AttributeName, - deliveryMedium: DeliveryMedium as DeliveryMedium, + deliveryMedium: DeliveryMedium as AuthDeliveryMedium, destination: Destination, }, }, diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index 82414cd49c5..fe5370cc1a0 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -3,8 +3,7 @@ import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; -import { VerifyTOTPSetupRequest } from '../../../types/requests'; -import { CognitoVerifyTOTPSetupOptions } from '../types/options'; +import { VerifyTOTPSetupInput } from '../types'; import { verifySoftwareToken } from '../utils/clients/CognitoIdentityProvider'; import { VerifySoftwareTokenException } from '../types/errors'; import { Amplify } from '@aws-amplify/core'; @@ -16,22 +15,19 @@ import { assertAuthTokens } from '../utils/types'; /** * Verifies an OTP code retrieved from an associated authentication app. * - * @param verifyTOTPSetupRequest - The VerifyTOTPSetupRequest - * + * @param input - The VerifyTOTPSetupInput * @throws -{@link VerifySoftwareTokenException }: * Thrown due to an invalid MFA token. - * * @throws -{@link AuthValidationErrorCode }: * Thrown when `code` is not defined. - * * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function verifyTOTPSetup( - verifyTOTPSetupRequest: VerifyTOTPSetupRequest + input: VerifyTOTPSetupInput ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { code, options } = verifyTOTPSetupRequest; + const { code, options } = input; assertValidationError( !!code, AuthValidationErrorCode.EmptyVerifyTOTPSetupCode diff --git a/packages/auth/src/providers/cognito/index.ts b/packages/auth/src/providers/cognito/index.ts index 55d4149bca9..fd05b4c7075 100644 --- a/packages/auth/src/providers/cognito/index.ts +++ b/packages/auth/src/providers/cognito/index.ts @@ -19,6 +19,38 @@ export { confirmUserAttribute } from './apis/confirmUserAttribute'; export { signInWithRedirect } from './apis/signInWithRedirect'; export { fetchUserAttributes } from './apis/fetchUserAttributes'; export { signOut } from './apis/signOut'; +export { + GetCurrentUserInput, + ConfirmResetPasswordInput, + ConfirmSignInInput, + ConfirmSignUpInput, + ConfirmUserAttributeInput, + ResendSignUpCodeInput, + ResetPasswordInput, + SignInInput, + SignInWithRedirectInput, + SignOutInput, + SignUpInput, + UpdateMFAPreferenceInput, + UpdatePasswordInput, + UpdateUserAttributesInput, + VerifyTOTPSetupInput, +} from './types/inputs'; + +export { + FetchUserAttributesOutput, + GetCurrentUserOutput, + ConfirmSignInOutput, + ConfirmSignUpOutput, + FetchMFAPreferenceOutput, + ResendSignUpCodeOutput, + ResetPasswordOutput, + SetUpTOTPOutput, + SignInOutput, + SignOutOutput, + SignUpOutput, + UpdateUserAttributesOutput, +} from './types/outputs'; export { cognitoCredentialsProvider, CognitoAWSCredentialsAndIdentityIdProvider, diff --git a/packages/auth/src/providers/cognito/types/index.ts b/packages/auth/src/providers/cognito/types/index.ts index 4c193b9f1a0..15aa1cb5d8b 100644 --- a/packages/auth/src/providers/cognito/types/index.ts +++ b/packages/auth/src/providers/cognito/types/index.ts @@ -5,20 +5,59 @@ export { CustomAttribute, ValidationData, AuthFlowType, - CognitoUserAttributeKey, + UserAttributeKey, MFAPreference, } from './models'; export { - CognitoConfirmResetPasswordOptions, - CognitoSignUpOptions, - CognitoResetPasswordOptions, - CognitoSignInOptions, - CognitoResendSignUpCodeOptions, - CognitoConfirmSignUpOptions, - CognitoConfirmSignInOptions, - CognitoUpdateUserAttributesOptions, - CognitoVerifyTOTPSetupOptions, + ConfirmResetPasswordOptions, + SignUpOptions, + ResetPasswordOptions, + SignInOptions, + ResendSignUpCodeOptions, + ConfirmSignUpOptions, + ConfirmSignInOptions, + UpdateUserAttributesOptions, + VerifyTOTPSetupOptions, } from './options'; -export { UpdateMFAPreferenceRequest } from './requests'; +export { + GetCurrentUserInput, + ConfirmResetPasswordInput, + ConfirmSignInInput, + ConfirmSignUpInput, + ConfirmUserAttributeInput, + ResendSignUpCodeInput, + ResetPasswordInput, + SignInInput, + SignInWithCustomAuthInput, + SignInWithCustomSRPAuthInput, + SignInWithSRPInput, + SignInWithUserPasswordInput, + SignInWithRedirectInput, + SignOutInput, + SignUpInput, + UpdateMFAPreferenceInput, + UpdatePasswordInput, + UpdateUserAttributesInput, + VerifyTOTPSetupInput, +} from './inputs'; + +export { + FetchUserAttributesOutput, + GetCurrentUserOutput, + ConfirmSignInOutput, + ConfirmSignUpOutput, + FetchMFAPreferenceOutput, + ResendSignUpCodeOutput, + ResetPasswordOutput, + SetUpTOTPOutput, + SignInOutput, + SignInWithCustomAuthOutput, + SignInWithSRPOutput, + SignInWithUserPasswordOutput, + SignInWithCustomSRPAuthOutput, + SignOutOutput, + SignUpOutput, + UpdateUserAttributesOutput, +} from './outputs'; diff --git a/packages/auth/src/providers/cognito/types/inputs.ts b/packages/auth/src/providers/cognito/types/inputs.ts new file mode 100644 index 00000000000..be22e8bbcec --- /dev/null +++ b/packages/auth/src/providers/cognito/types/inputs.ts @@ -0,0 +1,137 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + MFAPreference, + ConfirmResetPasswordOptions, + ConfirmSignInOptions, + ConfirmSignUpOptions, + UserAttributeKey, + ResendSignUpCodeOptions, + ResetPasswordOptions, + SignInOptions, + SignUpOptions, + UpdateUserAttributesOptions, + VerifyTOTPSetupOptions, +} from '../types'; +import { + AuthGetCurrentUserInput, + AuthConfirmResetPasswordInput, + AuthConfirmSignInInput, + AuthConfirmSignUpInput, + AuthConfirmUserAttributeInput, + AuthResendSignUpCodeInput, + AuthResetPasswordInput, + AuthSignInInput, + AuthSignInWithRedirectInput, + AuthSignOutInput, + AuthSignUpInput, + AuthUpdatePasswordInput, + AuthUpdateUserAttributesInput, + AuthVerifyTOTPSetupInput, +} from '../../../types'; + +/** + * Input type for Cognito getCurrentUser API. + */ +export type GetCurrentUserInput = AuthGetCurrentUserInput; + +/** + * Input type for Cognito confirmResetPassword API. + */ +export type ConfirmResetPasswordInput = + AuthConfirmResetPasswordInput; + +/** + * Input type for Cognito confirmSignIn API. + */ +export type ConfirmSignInInput = AuthConfirmSignInInput; + +/** + * Input type for Cognito confirmSignUp API. + */ +export type ConfirmSignUpInput = AuthConfirmSignUpInput; + +/** + * Input type for Cognito confirmUserAttribute API. + */ +export type ConfirmUserAttributeInput = + AuthConfirmUserAttributeInput; + +/** + * Input type for Cognito resendSignUpCode API. + */ +export type ResendSignUpCodeInput = + AuthResendSignUpCodeInput; + +/** + * Input type for Cognito resetPassword API. + */ +export type ResetPasswordInput = AuthResetPasswordInput; + +/** + * Input type for Cognito signIn API. + */ +export type SignInInput = AuthSignInInput; + +/** + * Input type for Cognito signInWithCustomAuth API. + */ +export type SignInWithCustomAuthInput = AuthSignInInput; + +/** + * Input type for Cognito signInWithCustomSRPAuth API. + */ +export type SignInWithCustomSRPAuthInput = AuthSignInInput; + +/** + * Input type for Cognito signInWithSRP API. + */ +export type SignInWithSRPInput = AuthSignInInput; + +/** + * Input type for Cognito signInWithUserPasswordInput API. + */ +export type SignInWithUserPasswordInput = AuthSignInInput; + +/** + * Input type for Cognito signInWithRedirect API. + */ +export type SignInWithRedirectInput = AuthSignInWithRedirectInput; + +/** + * Input type for Cognito signOut API. + */ +export type SignOutInput = AuthSignOutInput; + +/** + * Input type for Cognito signUp API. + */ +export type SignUpInput = AuthSignUpInput; + +/** + * Input type for Cognito updateMFAPreference API. + */ +export type UpdateMFAPreferenceInput = { + sms?: MFAPreference; + totp?: MFAPreference; +}; + +/** + * Input type for Cognito updatePassword API. + */ +export type UpdatePasswordInput = AuthUpdatePasswordInput; + +/** + * Input type for Cognito updateUserAttributes API. + */ +export type UpdateUserAttributesInput = AuthUpdateUserAttributesInput< + UserAttributeKey, + UpdateUserAttributesOptions +>; + +/** + * Input type for Cognito verifyTOTPSetup API. + */ +export type VerifyTOTPSetupInput = + AuthVerifyTOTPSetupInput; diff --git a/packages/auth/src/providers/cognito/types/models.ts b/packages/auth/src/providers/cognito/types/models.ts index df618993ac8..d5d25e801b4 100644 --- a/packages/auth/src/providers/cognito/types/models.ts +++ b/packages/auth/src/providers/cognito/types/models.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { AuthStandardAttributeKey } from '../../../types'; -import { AuthProvider } from '../../../types/requests'; +import { AuthProvider } from '../../../types/inputs'; /** * Cognito supported AuthFlowTypes that may be passed as part of the Sign In request. @@ -31,9 +31,7 @@ export type ClientMetadata = { /** * The user attribute types available for Cognito. */ -export type CognitoUserAttributeKey = - | AuthStandardAttributeKey - | CustomAttribute; +export type UserAttributeKey = AuthStandardAttributeKey | CustomAttribute; /** * Cognito custom attribute type diff --git a/packages/auth/src/providers/cognito/types/options.ts b/packages/auth/src/providers/cognito/types/options.ts index 18592500534..1a860061a20 100644 --- a/packages/auth/src/providers/cognito/types/options.ts +++ b/packages/auth/src/providers/cognito/types/options.ts @@ -5,55 +5,55 @@ import { AuthUserAttribute } from '../../../types'; import { ClientMetadata, AuthFlowType, ValidationData } from './models'; /** - * Options specific to a Cognito Confirm Reset Password request. + * Options specific to Cognito Confirm Reset Password. */ -export type CognitoConfirmResetPasswordOptions = { +export type ConfirmResetPasswordOptions = { clientMetadata?: ClientMetadata; }; /** - * Options specific to a Cognito Resend Sign Up code request. + * Options specific to Cognito Resend Sign Up code. */ -export type CognitoResendSignUpCodeOptions = { +export type ResendSignUpCodeOptions = { clientMetadata?: ClientMetadata; }; /** - * Options specific to a Cognito Reset Password request. + * Options specific to Cognito Reset Password. */ -export type CognitoResetPasswordOptions = { +export type ResetPasswordOptions = { clientMetadata?: ClientMetadata; }; /** - * Options specific to a Cognito Sign In request. + * Options specific to Cognito Sign In. */ -export type CognitoSignInOptions = { +export type SignInOptions = { authFlowType?: AuthFlowType; clientMetadata?: ClientMetadata; }; /** - * Options specific to a Cognito Sign Up request. + * Options specific to Cognito Sign Up. */ -export type CognitoSignUpOptions = { +export type SignUpOptions = { validationData?: ValidationData; clientMetadata?: ClientMetadata; // autoSignIn?: AutoSignInOptions; }; /** - * Options specific to a Cognito Confirm Sign Up request. + * Options specific to Cognito Confirm Sign Up. */ -export type CognitoConfirmSignUpOptions = { +export type ConfirmSignUpOptions = { clientMetadata?: ClientMetadata; forceAliasCreation?: boolean; }; /** - * Options specific to a Cognito Confirm Sign In request. + * Options specific to Cognito Confirm Sign In. */ -export type CognitoConfirmSignInOptions< +export type ConfirmSignInOptions< UserAttribute extends AuthUserAttribute = AuthUserAttribute > = { userAttributes?: UserAttribute; @@ -62,15 +62,15 @@ export type CognitoConfirmSignInOptions< }; /** - * Options specific to a Cognito Verify TOTP Setup request. + * Options specific to Cognito Verify TOTP Setup. */ -export type CognitoVerifyTOTPSetupOptions = { +export type VerifyTOTPSetupOptions = { friendlyDeviceName?: string; }; /** - * Options specific to a Cognito Update User Attributes request. + * Options specific to Cognito Update User Attributes. */ -export type CognitoUpdateUserAttributesOptions = { +export type UpdateUserAttributesOptions = { clientMetadata?: ClientMetadata; }; diff --git a/packages/auth/src/providers/cognito/types/outputs.ts b/packages/auth/src/providers/cognito/types/outputs.ts new file mode 100644 index 00000000000..af2c0d91cd8 --- /dev/null +++ b/packages/auth/src/providers/cognito/types/outputs.ts @@ -0,0 +1,104 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + AuthMFAType, + AuthUserAttribute, + AuthUser, + AuthStandardAttributeKey, + AuthCodeDeliveryDetails, + AuthTOTPSetupDetails, + AuthSignInOutput, + AuthSignUpOutput, + AuthResetPasswordOutput, + AuthSignOutOutput, + AuthUpdateUserAttributesOutput, +} from '../../../types'; +import { UserAttributeKey, CustomAttribute } from '../types'; + +export type FetchMFAPreferenceOutput = { + enabled?: AuthMFAType[]; + preferred?: AuthMFAType; +}; + +/** + * Output type for Cognito fetchUserAttributes API. + */ +export type FetchUserAttributesOutput = AuthUserAttribute; + +/** + * Output type for Cognito getCurrentUser API. + */ +export type GetCurrentUserOutput = AuthUser; + +/** + * Output type for Cognito confirmSignIn API. + */ +export type ConfirmSignInOutput = AuthSignInOutput; + +/** + * Output type for Cognito confirmSignUp API. + */ +export type ConfirmSignUpOutput = AuthSignUpOutput< + AuthStandardAttributeKey | CustomAttribute +>; + +/** + * Output type for Cognito resendSignUpCode API. + */ +export type ResendSignUpCodeOutput = AuthCodeDeliveryDetails; + +/** + * Output type for Cognito resetPassword API. + */ +export type ResetPasswordOutput = AuthResetPasswordOutput< + AuthStandardAttributeKey | CustomAttribute +>; + +/** + * Output type for Cognito setUpTOTP API. + */ +export type SetUpTOTPOutput = AuthTOTPSetupDetails; + +/** + * Output type for Cognito signIn API. + */ +export type SignInOutput = AuthSignInOutput; + +/** + * Output type for Cognito signInWithCustomAuth API. + */ +export type SignInWithCustomAuthOutput = AuthSignInOutput; + +/** + * Output type for Cognito signInWithSRP API. + */ +export type SignInWithSRPOutput = AuthSignInOutput; + +/** + * Output type for Cognito signInWithUserPassword API. + */ +export type SignInWithUserPasswordOutput = AuthSignInOutput; + +/** + * Output type for Cognito signInWithCustomSRPAuth API. + */ +export type SignInWithCustomSRPAuthOutput = AuthSignInOutput; + +/** + * Output type for Cognito signOut API. + */ +export type SignOutOutput = AuthSignOutOutput; + +/** + * Output type for Cognito signUp API. + */ +export type SignUpOutput = AuthSignUpOutput< + AuthStandardAttributeKey | CustomAttribute +>; + +/** + * Output type for Cognito updateUserAttributes API. + */ +export type UpdateUserAttributesOutput = + AuthUpdateUserAttributesOutput; diff --git a/packages/auth/src/providers/cognito/types/requests.ts b/packages/auth/src/providers/cognito/types/requests.ts deleted file mode 100644 index d55d52c443e..00000000000 --- a/packages/auth/src/providers/cognito/types/requests.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { MFAPreference } from './models'; - -export type UpdateMFAPreferenceRequest = { - sms?: MFAPreference; - totp?: MFAPreference; -}; diff --git a/packages/auth/src/providers/cognito/types/results.ts b/packages/auth/src/providers/cognito/types/results.ts deleted file mode 100644 index 6bc68f0e1a7..00000000000 --- a/packages/auth/src/providers/cognito/types/results.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { MFAType } from "../../../types/models"; - -export type FetchMFAPreferenceResult = { - enabled?: MFAType[]; - preferred?: MFAType; -}; diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index dedc84075e7..218fc3be082 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -12,18 +12,18 @@ import { import AuthenticationHelper from './srp/AuthenticationHelper'; import BigInteger from './srp/BigInteger'; -import { ClientMetadata, CognitoConfirmSignInOptions } from '../types'; +import { ClientMetadata, ConfirmSignInOptions } from '../types'; import { - AdditionalInfo, - AuthSignInResult, - DeliveryMedium, + AuthAdditionalInfo, + AuthSignInOutput, + AuthDeliveryMedium, } from '../../../types'; import { AuthError } from '../../../errors/AuthError'; import { InitiateAuthException } from '../types/errors'; import { AuthUserAttribute, - MFAType, - TOTPSetupDetails, + AuthMFAType, + AuthTOTPSetupDetails, } from '../../../types/models'; import { AuthErrorCodes } from '../../../common/AuthErrorStrings'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; @@ -374,7 +374,7 @@ export async function handlePasswordVerifierChallenge( export async function getSignInResult(params: { challengeName: ChallengeName; challengeParameters: ChallengeParameters; -}): Promise { +}): Promise { const { challengeName, challengeParameters } = params; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -385,7 +385,7 @@ export async function getSignInResult(params: { isSignedIn: false, nextStep: { signInStep: 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE', - additionalInfo: challengeParameters as AdditionalInfo, + additionalInfo: challengeParameters as AuthAdditionalInfo, }, }; case 'MFA_SETUP': @@ -443,7 +443,7 @@ export async function getSignInResult(params: { signInStep: 'CONFIRM_SIGN_IN_WITH_SMS_CODE', codeDeliveryDetails: { deliveryMedium: - challengeParameters.CODE_DELIVERY_DELIVERY_MEDIUM as DeliveryMedium, + challengeParameters.CODE_DELIVERY_DELIVERY_MEDIUM as AuthDeliveryMedium, destination: challengeParameters.CODE_DELIVERY_DESTINATION, }, }, @@ -476,7 +476,7 @@ export async function getSignInResult(params: { export function getTOTPSetupDetails( secretCode: string, username?: string -): TOTPSetupDetails { +): AuthTOTPSetupDetails { return { sharedSecret: secretCode, getSetupUri: (appName, accountName) => { @@ -491,7 +491,7 @@ export function getTOTPSetupDetails( export function getSignInResultFromError( errorName: string -): AuthSignInResult | undefined { +): AuthSignInOutput | undefined { if (errorName === InitiateAuthException.PasswordResetRequiredException) { return { isSignedIn: false, @@ -534,7 +534,7 @@ export async function handleChallengeName( challengeResponse: string, config: CognitoUserPoolConfig, clientMetadata?: ClientMetadata, - options?: CognitoConfirmSignInOptions + options?: ConfirmSignInOptions ): Promise { const userAttributes = options?.userAttributes; const deviceName = options?.friendlyDeviceName; @@ -606,15 +606,15 @@ export function mapMfaType(mfa: string): CognitoMFAType { return mfaType; } -export function getMFAType(type?: string): MFAType | undefined { +export function getMFAType(type?: string): AuthMFAType | undefined { if (type === 'SMS_MFA') return 'SMS'; if (type === 'SOFTWARE_TOKEN_MFA') return 'TOTP'; // TODO: log warning for unknown MFA type } -export function getMFATypes(types?: string[]): MFAType[] | undefined { +export function getMFATypes(types?: string[]): AuthMFAType[] | undefined { if (!types) return undefined; - return types.map(getMFAType).filter(Boolean) as MFAType[]; + return types.map(getMFAType).filter(Boolean) as AuthMFAType[]; } export function parseMFATypes(mfa?: string): CognitoMFAType[] { if (!mfa) return []; @@ -623,7 +623,7 @@ export function parseMFATypes(mfa?: string): CognitoMFAType[] { export function isMFATypeEnabled( challengeParams: ChallengeParameters, - mfaType: MFAType + mfaType: AuthMFAType ): boolean { const { MFAS_CAN_SETUP } = challengeParams; const mfaTypes = getMFATypes(parseMFATypes(MFAS_CAN_SETUP)); diff --git a/packages/auth/src/types/index.ts b/packages/auth/src/types/index.ts index 78732345098..171e4ad3e90 100644 --- a/packages/auth/src/types/index.ts +++ b/packages/auth/src/types/index.ts @@ -1,13 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -// TODO: Remove "./Auth" export -export * from './Auth'; - export { - AdditionalInfo, - DeliveryMedium, - AnyAttribute, + AuthAdditionalInfo, + AuthDeliveryMedium, + AuthAnyAttribute, AuthCodeDeliveryDetails, AuthNextSignUpStep, AuthStandardAttributeKey, @@ -16,10 +13,10 @@ export { AuthNextResetPasswordStep, AuthNextSignInStep, AuthNextUpdateAttributeStep, - MFAType, - AllowedMFATypes, + AuthMFAType, + AuthAllowedMFATypes, AuthUser, - TOTPSetupDetails, + AuthTOTPSetupDetails, AuthResetPasswordStep, AuthSignUpStep, AuthUpdateAttributeStep, @@ -28,24 +25,27 @@ export { export { AuthServiceOptions, AuthSignUpOptions } from './options'; export { - ConfirmResetPasswordRequest, - ResetPasswordRequest, - ResendSignUpCodeRequest, - SignUpRequest, - SignInRequest, - ConfirmSignUpRequest, - ConfirmSignInRequest, - UpdatePasswordRequest, - UpdateUserAttributesRequest, - GetCurrentUserRequest, - ConfirmUserAttributeRequest, - VerifyTOTPSetupRequest, -} from './requests'; + AuthConfirmResetPasswordInput, + AuthResetPasswordInput, + AuthResendSignUpCodeInput, + AuthSignUpInput, + AuthSignInInput, + AuthConfirmSignUpInput, + AuthConfirmSignInInput, + AuthUpdatePasswordInput, + AuthUpdateUserAttributesInput, + AuthGetCurrentUserInput, + AuthConfirmUserAttributeInput, + AuthVerifyTOTPSetupInput, + AuthSignInWithRedirectInput, + AuthSignOutInput, +} from './inputs'; export { - AuthSignUpResult, - AuthSignInResult, - ResetPasswordResult, - UpdateUserAttributeResult, - UpdateUserAttributesResult, -} from './results'; + AuthSignUpOutput, + AuthSignInOutput, + AuthSignOutOutput, + AuthResetPasswordOutput, + AuthUpdateUserAttributeOutput, + AuthUpdateUserAttributesOutput, +} from './outputs'; diff --git a/packages/auth/src/types/requests.ts b/packages/auth/src/types/inputs.ts similarity index 77% rename from packages/auth/src/types/requests.ts rename to packages/auth/src/types/inputs.ts index 75040e98359..d94968dafb3 100644 --- a/packages/auth/src/types/requests.ts +++ b/packages/auth/src/types/inputs.ts @@ -4,7 +4,7 @@ import { AuthUserAttribute, AuthUserAttributeKey } from './models'; import { AuthServiceOptions, AuthSignUpOptions } from './options'; -export type ConfirmResetPasswordRequest< +export type AuthConfirmResetPasswordInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { username: string; @@ -16,19 +16,19 @@ export type ConfirmResetPasswordRequest< }; /** - * The parameters for constructing a Resend Sign Up code request. + * The parameters for constructing a Resend Sign Up code input. * * @param username - a standard username, potentially an email/phone number * @param options - optional parameters for the Sign Up process such as the plugin options */ -export type ResendSignUpCodeRequest< +export type AuthResendSignUpCodeInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { username: string; options?: { serviceOptions?: ServiceOptions }; }; -export type ResetPasswordRequest< +export type AuthResetPasswordInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { username: string; @@ -37,48 +37,48 @@ export type ResetPasswordRequest< }; }; -export type SignInRequest< +export type AuthSignInInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { username: string; password?: string; options?: { serviceOptions?: ServiceOptions }; }; -export type SignOutRequest = { +export type AuthSignOutInput = { global: boolean; }; export type AuthProvider = 'Amazon' | 'Apple' | 'Facebook' | 'Google'; -export type SignInWithRedirectRequest = { +export type AuthSignInWithRedirectInput = { provider?: AuthProvider | { custom: string }; customState?: string; }; /** - * The parameters for constructing a Sign Up request. + * The parameters for constructing a Sign Up input. * * @param username - a standard username, potentially an email/phone number * @param password - the user's password * @param options - optional parameters for the Sign Up process, including user attributes */ -export type SignUpRequest< - UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, +export type AuthSignUpInput< + AttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { username: string; password: string; - options?: AuthSignUpOptions; + options?: AuthSignUpOptions; }; /** - * Constructs a `confirmSignUp` request. + * Constructs a `confirmSignUp` input. * * @param username - a standard username, potentially an email/phone number * @param confirmationCode - the user's confirmation code sent to email or cellphone * @param options - optional parameters for the Sign Up process, including user attributes */ -export type ConfirmSignUpRequest< +export type AuthConfirmSignUpInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { username: string; @@ -88,13 +88,13 @@ export type ConfirmSignUpRequest< }; }; /** - * Constructs a `confirmSignIn` request. + * Constructs a `confirmSignIn` input. * * @param challengeResponse - required parameter for responding to {@link AuthSignInStep } returned during * the sign in process. * @param options - optional parameters for the Confirm Sign In process such as the service options */ -export type ConfirmSignInRequest< +export type AuthConfirmSignInInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { challengeResponse: string; @@ -102,11 +102,11 @@ export type ConfirmSignInRequest< }; /** - * Constructs a `VerifyTOTPSetup` request. + * Constructs a `VerifyTOTPSetup` input. * @param code - required parameter for verifying the TOTP setup. * @param options - optional parameters for the Verify TOTP Setup process such as the service options. */ -export type VerifyTOTPSetupRequest< +export type AuthVerifyTOTPSetupInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { code: string; @@ -114,22 +114,22 @@ export type VerifyTOTPSetupRequest< }; /** - * Constructs a `updatePassword` request. + * Constructs a `updatePassword` input. * * @param oldPassword - previous password used for `signIn` * @param newPassword - new password to be used for `signIn` */ -export type UpdatePasswordRequest = { +export type AuthUpdatePasswordInput = { oldPassword: string; newPassword: string; }; /** - * Constructs a `updateUserAttributes` request. + * Constructs a `updateUserAttributes` input. * @param userAttributes - the user attributes to be updated * @param options - optional parameters for the Update User Attributes process such as the service options. */ -export type UpdateUserAttributesRequest< +export type AuthUpdateUserAttributesInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, ServiceOptions extends AuthServiceOptions = AuthServiceOptions > = { @@ -138,18 +138,18 @@ export type UpdateUserAttributesRequest< }; /** - * Constructs a `GetCurrentUser` request. + * Constructs a `GetCurrentUser` input. * @param recache - whether to recache the user */ -export type GetCurrentUserRequest = { recache: boolean }; +export type AuthGetCurrentUserInput = { recache: boolean }; /* - * Constructs a `verifyUserAttribute` request. + * Constructs a `verifyUserAttribute` input. * * @param userAttributeKey - the user attribute key to be verified * @param confirmationCode - the user attribute verification code sent to email or cellphone * */ -export type ConfirmUserAttributeRequest< +export type AuthConfirmUserAttributeInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { userAttributeKey: UserAttributeKey; confirmationCode: string }; diff --git a/packages/auth/src/types/models.ts b/packages/auth/src/types/models.ts index a538fa0d41d..735c2b14d14 100644 --- a/packages/auth/src/types/models.ts +++ b/packages/auth/src/types/models.ts @@ -4,14 +4,14 @@ /** * Additional data that may be returned from Auth APIs. */ -export type AdditionalInfo = { [key: string]: string }; +export type AuthAdditionalInfo = { [key: string]: string }; -export type AnyAttribute = string & {}; +export type AuthAnyAttribute = string & {}; /** * Denotes the medium over which a confirmation code was sent. */ -export type DeliveryMedium = 'EMAIL' | 'SMS' | 'PHONE' | 'UNKNOWN'; +export type AuthDeliveryMedium = 'EMAIL' | 'SMS' | 'PHONE' | 'UNKNOWN'; /** * Data describing the dispatch of a confirmation code. @@ -20,7 +20,7 @@ export type AuthCodeDeliveryDetails< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { destination?: string; - deliveryMedium?: DeliveryMedium; + deliveryMedium?: AuthDeliveryMedium; attributeName?: UserAttributeKey; }; /** @@ -31,18 +31,18 @@ export type AuthNextResetPasswordStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { resetPasswordStep: AuthResetPasswordStep; - additionalInfo?: AdditionalInfo; + additionalInfo?: AuthAdditionalInfo; codeDeliveryDetails: AuthCodeDeliveryDetails; }; -export type TOTPSetupDetails = { +export type AuthTOTPSetupDetails = { sharedSecret: string; getSetupUri: (appName: string, accountName?: string) => URL; }; -export type MFAType = 'SMS' | 'TOTP'; +export type AuthMFAType = 'SMS' | 'TOTP'; -export type AllowedMFATypes = MFAType[]; +export type AuthAllowedMFATypes = AuthMFAType[]; export type ContinueSignInWithTOTPSetup = { /** @@ -57,7 +57,7 @@ export type ContinueSignInWithTOTPSetup = { * ``` */ signInStep: 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP'; - totpSetupDetails: TOTPSetupDetails; + totpSetupDetails: AuthTOTPSetupDetails; }; export type ConfirmSignInWithTOTPCode = { /** @@ -85,7 +85,7 @@ export type ContinueSignInWithMFASelection = { * ``` */ signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION'; - allowedMFATypes?: AllowedMFATypes; + allowedMFATypes?: AuthAllowedMFATypes; }; export type ConfirmSignInWithCustomChallenge = { @@ -99,7 +99,7 @@ export type ConfirmSignInWithCustomChallenge = { * ``` */ signInStep: 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE'; - additionalInfo?: AdditionalInfo; + additionalInfo?: AuthAdditionalInfo; }; export type ConfirmSignInWithNewPasswordRequired< @@ -218,7 +218,7 @@ export type AuthUserAttribute< /** * A user attribute key type consisting of standard OIDC claims or custom attributes. */ -export type AuthUserAttributeKey = AuthStandardAttributeKey | AnyAttribute; +export type AuthUserAttributeKey = AuthStandardAttributeKey | AuthAnyAttribute; /** * Denotes the next step in the Sign Up process. @@ -232,7 +232,7 @@ export type AuthNextSignUpStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { signUpStep?: AuthSignUpStep; - additionalInfo?: AdditionalInfo; + additionalInfo?: AuthAdditionalInfo; codeDeliveryDetails?: AuthCodeDeliveryDetails; }; diff --git a/packages/auth/src/types/results.ts b/packages/auth/src/types/outputs.ts similarity index 64% rename from packages/auth/src/types/results.ts rename to packages/auth/src/types/outputs.ts index dc7ae1af5d8..2d0f3b8a97f 100644 --- a/packages/auth/src/types/results.ts +++ b/packages/auth/src/types/outputs.ts @@ -9,22 +9,16 @@ import { AuthNextUpdateAttributeStep, } from './models'; -/** - * The Result of a Sign In request. - */ -export type AuthSignInResult< +export type AuthSignInOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { isSignedIn: boolean; nextStep: AuthNextSignInStep; }; -export type AuthSignOutResult = void; +export type AuthSignOutOutput = void; -/** - * The Result of a Sign Up request. - */ -export type AuthSignUpResult< +export type AuthSignUpOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { isSignUpComplete: boolean; @@ -32,31 +26,22 @@ export type AuthSignUpResult< userId?: string; }; -/** - * The Result of a Reset Password request. - */ -export type ResetPasswordResult< +export type AuthResetPasswordOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { isPasswordReset: boolean; nextStep: AuthNextResetPasswordStep; }; -/** - * The Result of a Update User Attribute request. - */ -export type UpdateUserAttributeResult< +export type AuthUpdateUserAttributeOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { isUpdated: boolean; nextStep: AuthNextUpdateAttributeStep; }; -/** - * The Result of a Update User Attributes request. - */ -export type UpdateUserAttributesResult< +export type AuthUpdateUserAttributesOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey > = { - [authKey in UserAttributeKey]: UpdateUserAttributeResult; + [authKey in UserAttributeKey]: AuthUpdateUserAttributeOutput; }; From 9f12035aa63f1eaa303e9d02c8c008c5e441ff7a Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 14 Sep 2023 15:04:24 -0700 Subject: [PATCH 4/9] fix(auth): signInWithRedirect urlListner attaches for non-browser env --- packages/auth/src/providers/cognito/apis/signInWithRedirect.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index 2d8bae03995..d77d54bbfc5 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -7,6 +7,7 @@ import { assertOAuthConfig, assertTokenProviderConfig, getAmplifyUserAgent, + isBrowser, urlSafeEncode, USER_AGENT_HEADER, } from '@aws-amplify/core/internals/utils'; @@ -391,7 +392,7 @@ function urlListener() { }); } -urlListener(); +isBrowser() && urlListener(); // This has a reference for listeners that requires to be notified, TokenOrchestrator use this for load tokens let resolveInflightPromise = () => {}; From 9f935fc9204706c5c34d0197a9523de3f04bc406 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Thu, 14 Sep 2023 18:34:29 -0500 Subject: [PATCH 5/9] chore: Enable E2E tests on push to next/release (#12061) --- .../callable-release-verification.yml | 10 +++++----- .github/workflows/push-next-release.yml | 18 +++++++++--------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/callable-release-verification.yml b/.github/workflows/callable-release-verification.yml index 30fd4b0c7e0..3d270d97521 100644 --- a/.github/workflows/callable-release-verification.yml +++ b/.github/workflows/callable-release-verification.yml @@ -7,16 +7,16 @@ jobs: uses: ./.github/workflows/callable-prebuild-amplify-js.yml with: runs_on: ubuntu-latest - prebuild-macos: - uses: ./.github/workflows/callable-prebuild-amplify-js.yml - with: - runs_on: macos-latest + # prebuild-macos: + # uses: ./.github/workflows/callable-prebuild-amplify-js.yml + # with: + # runs_on: macos-latest prebuild-samples-staging: secrets: inherit uses: ./.github/workflows/callable-prebuild-samples-staging.yml e2e: needs: - - prebuild-macos + # - prebuild-macos - prebuild-ubuntu - prebuild-samples-staging secrets: inherit diff --git a/.github/workflows/push-next-release.yml b/.github/workflows/push-next-release.yml index 564717e3b29..b749c6f406b 100644 --- a/.github/workflows/push-next-release.yml +++ b/.github/workflows/push-next-release.yml @@ -8,17 +8,17 @@ concurrency: on: push: branches: - - invalid-branch + - next/release jobs: e2e: secrets: inherit uses: ./.github/workflows/callable-release-verification.yml - next-release: - needs: - - e2e - secrets: inherit - uses: ./.github/workflows/callable-npm-publish-preid.yml - with: - preid: next - allow-protected-preid: true + # next-release: + # needs: + # - e2e + # secrets: inherit + # uses: ./.github/workflows/callable-npm-publish-preid.yml + # with: + # preid: next + # allow-protected-preid: true From e753f3bb255c88b470b8819a89aff4983bf2cd41 Mon Sep 17 00:00:00 2001 From: AllanZhengYP Date: Thu, 14 Sep 2023 16:49:02 -0700 Subject: [PATCH 6/9] feat(storage): change enums to string unions (#12056) --------- Co-authored-by: Ashwin Kumar --- .../s3/apis/utils/downloadTask.test.ts | 17 +++----- .../s3/apis/utils/uploadTask.test.ts | 39 ++++++------------- packages/storage/src/index.ts | 2 +- .../storage/src/providers/s3/apis/copy.ts | 8 ++-- .../src/providers/s3/apis/downloadData.ts | 7 ++-- .../src/providers/s3/apis/getProperties.ts | 6 +-- .../storage/src/providers/s3/apis/getUrl.ts | 9 +++-- .../storage/src/providers/s3/apis/list.ts | 8 ++-- .../storage/src/providers/s3/apis/remove.ts | 4 +- .../src/providers/s3/apis/uploadData/index.ts | 7 ++-- .../src/providers/s3/utils/transferTask.ts | 24 +++++------- packages/storage/src/types/common.ts | 13 +++---- 12 files changed, 59 insertions(+), 85 deletions(-) diff --git a/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts b/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts index c3f878f6480..75ab4eb508a 100644 --- a/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import { createDownloadTask } from '../../../../../src/providers/s3/utils'; -import { TransferTaskState } from '../../../../../src/types/common'; describe('createDownloadTask', () => { it('should create a download task', async () => { @@ -10,7 +9,7 @@ describe('createDownloadTask', () => { job: jest.fn().mockResolvedValueOnce('test'), onCancel: jest.fn(), }); - expect(task.state).toBe(TransferTaskState.IN_PROGRESS); + expect(task.state).toBe('IN_PROGRESS'); expect(await task.result).toEqual('test'); }); @@ -20,7 +19,7 @@ describe('createDownloadTask', () => { onCancel: jest.fn(), }); task.cancel(); - expect(task.state).toBe(TransferTaskState.CANCELED); + expect(task.state).toBe('CANCELED'); }); it('should set overwriting abort error to the onCancel callback', () => { @@ -31,7 +30,7 @@ describe('createDownloadTask', () => { }); const customError = new Error('Custom Error'); task.cancel(customError); - expect(task.state).toBe(TransferTaskState.CANCELED); + expect(task.state).toBe('CANCELED'); expect(onCancel).toHaveBeenCalledWith(customError); }); @@ -46,7 +45,7 @@ describe('createDownloadTask', () => { await task.result; } catch (e) { expect(e).toBe(rejectedError); - expect(task.state).toBe(TransferTaskState.ERROR); + expect(task.state).toBe('ERROR'); } }); @@ -56,14 +55,10 @@ describe('createDownloadTask', () => { onCancel: jest.fn(), }); await task.result; - expect(task.state).toBe(TransferTaskState.SUCCESS); + expect(task.state).toBe('SUCCESS'); }); - it.each([ - TransferTaskState.CANCELED, - TransferTaskState.ERROR, - TransferTaskState.SUCCESS, - ])( + it.each(['CANCELED', 'ERROR', 'SUCCESS'])( 'should not call the onCancel callback if the task is already in status of %s', async state => { const onCancel = jest.fn(); diff --git a/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts b/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts index 505868187f8..03a3c5465bb 100644 --- a/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts @@ -1,7 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { TransferTaskState } from '../../../../../src/types/common'; import { createUploadTask } from '../../../../../src/providers/s3/utils'; describe('createUploadTask', () => { @@ -10,7 +9,7 @@ describe('createUploadTask', () => { job: jest.fn().mockResolvedValueOnce('test'), onCancel: jest.fn(), }); - expect(task.state).toBe(TransferTaskState.IN_PROGRESS); + expect(task.state).toBe('IN_PROGRESS'); expect(await task.result).toEqual('test'); task.pause(); }); @@ -21,7 +20,7 @@ describe('createUploadTask', () => { onCancel: jest.fn(), }); task.cancel(); - expect(task.state).toBe(TransferTaskState.CANCELED); + expect(task.state).toBe('CANCELED'); }); it('should set overwriting abort error to the onCancel callback', () => { @@ -32,7 +31,7 @@ describe('createUploadTask', () => { }); const customError = new Error('Custom Error'); task.cancel(customError); - expect(task.state).toBe(TransferTaskState.CANCELED); + expect(task.state).toBe('CANCELED'); expect(onCancel).toHaveBeenCalledWith(customError); }); @@ -47,7 +46,7 @@ describe('createUploadTask', () => { await task.result; } catch (e) { expect(e).toBe(rejectedError); - expect(task.state).toBe(TransferTaskState.ERROR); + expect(task.state).toBe('ERROR'); } }); @@ -57,14 +56,10 @@ describe('createUploadTask', () => { onCancel: jest.fn(), }); await task.result; - expect(task.state).toBe(TransferTaskState.SUCCESS); + expect(task.state).toBe('SUCCESS'); }); - it.each([ - TransferTaskState.CANCELED, - TransferTaskState.ERROR, - TransferTaskState.SUCCESS, - ])( + it.each(['CANCELED', 'ERROR', 'SUCCESS'])( 'should not call the onCancel callback if the task is already in status of %s', async state => { const onCancel = jest.fn(); @@ -89,18 +84,13 @@ describe('createUploadTask', () => { onPause, isMultipartUpload: true, }); - expect(task.state).toBe(TransferTaskState.IN_PROGRESS); + expect(task.state).toBe('IN_PROGRESS'); task.pause(); expect(onPause).toHaveBeenCalled(); - expect(task.state).toBe(TransferTaskState.PAUSED); + expect(task.state).toBe('PAUSED'); }); - it.each([ - TransferTaskState.CANCELED, - TransferTaskState.ERROR, - TransferTaskState.SUCCESS, - TransferTaskState.PAUSED, - ])( + it.each(['CANCELED', 'ERROR', 'SUCCESS', 'PAUSED'])( 'should not call the onPause callback if the task is already in status of %s', async state => { const onPause = jest.fn(); @@ -128,18 +118,13 @@ describe('createUploadTask', () => { isMultipartUpload: true, }); task.pause(); - expect(task.state).toBe(TransferTaskState.PAUSED); + expect(task.state).toBe('PAUSED'); task.resume(); expect(onResume).toHaveBeenCalled(); - expect(task.state).toBe(TransferTaskState.IN_PROGRESS); + expect(task.state).toBe('IN_PROGRESS'); }); - it.each([ - TransferTaskState.CANCELED, - TransferTaskState.ERROR, - TransferTaskState.SUCCESS, - TransferTaskState.IN_PROGRESS, - ])( + it.each(['CANCELED', 'ERROR', 'SUCCESS', 'IN_PROGRESS'])( 'should not call the onResume callback if the task is already in status of %s', async state => { const onResume = jest.fn(); diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 06c52e118cc..647a498cf1c 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -33,7 +33,7 @@ export { GetUrlOutput, } from './providers/s3/types/outputs'; -export { TransferProgressEvent, TransferTaskState } from './types'; +export { TransferProgressEvent } from './types'; // TODO[AllanZhengYP]: support isCancelError in Node.js with node-fetch export { isCancelError } from './errors/CanceledError'; diff --git a/packages/storage/src/providers/s3/apis/copy.ts b/packages/storage/src/providers/s3/apis/copy.ts index 17c32e557e2..1eed73e3972 100644 --- a/packages/storage/src/providers/s3/apis/copy.ts +++ b/packages/storage/src/providers/s3/apis/copy.ts @@ -2,16 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import { CopyInput, CopyOutput } from '../types'; +import { CopyInput, CopyOutput, S3Exception } from '../types'; import { copy as copyInternal } from './internal/copy'; +import { StorageValidationErrorCode } from '../../../errors/types/validation'; /** * Copy an object from a source object to a new object within the same bucket. Can optionally copy files across * different level or identityId (if source object's level is 'protected'). * - * @async - * @param {CopyInput} input - The request object. - * @return {Promise} Promise resolves upon successful copy of the object. + * @param input - The CopyInput object. + * @returns Output containing the destination key. * @throws service: {@link S3Exception} - Thrown when checking for existence of the object * @throws validation: {@link StorageValidationErrorCode } - Thrown when * source or destination key are not defined. diff --git a/packages/storage/src/providers/s3/apis/downloadData.ts b/packages/storage/src/providers/s3/apis/downloadData.ts index de948b18536..494667c8269 100644 --- a/packages/storage/src/providers/s3/apis/downloadData.ts +++ b/packages/storage/src/providers/s3/apis/downloadData.ts @@ -3,7 +3,7 @@ import { Amplify } from '@aws-amplify/core'; -import { DownloadDataInput, DownloadDataOutput } from '../types'; +import { DownloadDataInput, DownloadDataOutput, S3Exception } from '../types'; import { resolveS3ConfigAndInput } from '../utils/resolveS3ConfigAndInput'; import { StorageValidationErrorCode } from '../../../errors/types/validation'; import { createDownloadTask } from '../utils'; @@ -12,9 +12,8 @@ import { getObject } from '../utils/client'; /** * Download S3 object data to memory * - * @param {DownloadDataRequest} input The parameters that are passed to the - * downloadData operation. - * @returns {DownloadDataOutput} Cancelable task exposing result promise from `result` property. + * @param input - The DownloadDataInput object. + * @returns A cancelable task exposing result promise from `result` property. * @throws service: {@link S3Exception} - thrown when checking for existence of the object * @throws validation: {@link StorageValidationErrorCode } - Validation errors * diff --git a/packages/storage/src/providers/s3/apis/getProperties.ts b/packages/storage/src/providers/s3/apis/getProperties.ts index 33034f4132a..7f012d3f2be 100644 --- a/packages/storage/src/providers/s3/apis/getProperties.ts +++ b/packages/storage/src/providers/s3/apis/getProperties.ts @@ -2,15 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import { GetPropertiesOutput, GetPropertiesInput } from '../types'; +import { GetPropertiesOutput, GetPropertiesInput, S3Exception } from '../types'; import { getProperties as getPropertiesInternal } from './internal/getProperties'; /** * Gets the properties of a file. The properties include S3 system metadata and * the user metadata that was provided when uploading the file. * - * @param {GetPropertiesInput} The input to make an API call. - * @returns {Promise} A promise that resolves the properties. + * @param input - The GetPropertiesInput object. + * @returns Requested object properties. * @throws A {@link S3Exception} when the underlying S3 service returned error. * @throws A {@link StorageValidationErrorCode} when API call parameters are invalid. */ diff --git a/packages/storage/src/providers/s3/apis/getUrl.ts b/packages/storage/src/providers/s3/apis/getUrl.ts index 4fdcafa2a4d..0ceb612c06c 100644 --- a/packages/storage/src/providers/s3/apis/getUrl.ts +++ b/packages/storage/src/providers/s3/apis/getUrl.ts @@ -2,20 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import {} from '../../../types'; -import { GetUrlInput, GetUrlOutput } from '../types'; +import { StorageValidationErrorCode } from '../../../errors/types/validation'; +import { GetUrlInput, GetUrlOutput, S3Exception } from '../types'; import { getUrl as getUrlInternal } from './internal/getUrl'; /** * Get a temporary presigned URL to download the specified S3 object. * The presigned URL expires when the associated role used to sign the request expires or * the option `expiresIn` is reached. The `expiresAt` property in the output object indicates when the URL MAY expire. + * * By default, it will not validate the object that exists in S3. If you set the `options.validateObjectExistence` * to true, this method will verify the given object already exists in S3 before returning a presigned * URL, and will throw {@link StorageError} if the object does not exist. * - * @param {GetUrlInput} The input object - * @return {Promise} url of the object + * @param input - The GetUrlInput object. + * @returns Presigned URL and timestamp when the URL MAY expire. * @throws service: {@link S3Exception} - thrown when checking for existence of the object * @throws validation: {@link StorageValidationErrorCode } - Validation errors * thrown either username or key are not defined. diff --git a/packages/storage/src/providers/s3/apis/list.ts b/packages/storage/src/providers/s3/apis/list.ts index d7910c43ba3..a1a7f3e5458 100644 --- a/packages/storage/src/providers/s3/apis/list.ts +++ b/packages/storage/src/providers/s3/apis/list.ts @@ -14,16 +14,16 @@ type ListApi = { /** * List files with given prefix in pages * pageSize defaulted to 1000. Additionally, the result will include a nextToken if there are more items to retrieve. - * @param {ListPaginateInput} The input object - * @return {Promise} - Promise resolves to list of keys and metadata with + * @param input - The ListPaginateInput object. + * @returns A list of keys and metadata with * @throws service: {@link S3Exception} - S3 service errors thrown when checking for existence of bucket * @throws validation: {@link StorageValidationErrorCode } - thrown when there are issues with credentials */ (input?: ListPaginateInput): Promise; /** * List all files from S3. You can set `listAll` to true in `options` to get all the files from S3. - * @param {ListAllInput} The input object - * @return {Promise} - Promise resolves to list of keys and metadata for all objects in path + * @param input - The ListAllInput object. + * @returns A list of keys and metadata for all objects in path * @throws service: {@link S3Exception} - S3 service errors thrown when checking for existence of bucket * @throws validation: {@link StorageValidationErrorCode } - thrown when there are issues with credentials */ diff --git a/packages/storage/src/providers/s3/apis/remove.ts b/packages/storage/src/providers/s3/apis/remove.ts index 4a4b7428c42..d26fb3058c5 100644 --- a/packages/storage/src/providers/s3/apis/remove.ts +++ b/packages/storage/src/providers/s3/apis/remove.ts @@ -7,8 +7,8 @@ import { remove as removeInternal } from './internal/remove'; /** * Remove a file from your S3 bucket. - * @param {RemoveInput} The input object - * @return {Promise} - Promise resolves upon successful removal of the object + * @param input - The RemoveInput object. + * @return Output containing the removed object key * @throws service: {@link S3Exception} - S3 service errors thrown while getting properties * @throws validation: {@link StorageValidationErrorCode } - Validation errors thrown */ diff --git a/packages/storage/src/providers/s3/apis/uploadData/index.ts b/packages/storage/src/providers/s3/apis/uploadData/index.ts index 03dbe76f19b..ff23d9780ee 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/index.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/index.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { UploadDataInput, UploadDataOutput } from '../../types'; +import { UploadDataInput, UploadDataOutput, S3Exception } from '../../types'; import { createUploadTask } from '../../utils'; import { assertValidationError } from '../../../../errors/utils/assertValidationError'; import { StorageValidationErrorCode } from '../../../../errors/types/validation'; @@ -18,9 +18,8 @@ import { getMultipartUploadHandlers } from './multipart'; * * Maximum object size is 5TB. * * Maximum object size if the size cannot be determined before upload is 50GB. * - * @param {UploadDataInput} The input parameters that are passed to the - * uploadData operation. - * @returns {UploadDataOutput} Cancelable and Resumable task exposing result promise from `result` + * @param input - The UploadDataInput object. + * @returns A cancelable and resumable task exposing result promise from `result` * property. * @throws service: {@link S3Exception} - thrown when checking for existence of the object * @throws validation: {@link StorageValidationErrorCode } - Validation errors. diff --git a/packages/storage/src/providers/s3/utils/transferTask.ts b/packages/storage/src/providers/s3/utils/transferTask.ts index 03005f24584..b271364eb54 100644 --- a/packages/storage/src/providers/s3/utils/transferTask.ts +++ b/packages/storage/src/providers/s3/utils/transferTask.ts @@ -19,20 +19,16 @@ const createCancellableTask = ({ job, onCancel, }: CreateCancellableTaskOptions): CancellableTask => { - const state = TransferTaskState.IN_PROGRESS; + const state = 'IN_PROGRESS' as TransferTaskState; let abortErrorOverwriteRecord: Error | undefined = undefined; const cancelableTask = { cancel: (abortErrorOverwrite?: Error) => { abortErrorOverwriteRecord = abortErrorOverwrite; const { state } = cancelableTask; - if ( - state === TransferTaskState.CANCELED || - state === TransferTaskState.ERROR || - state === TransferTaskState.SUCCESS - ) { + if (state === 'CANCELED' || state === 'ERROR' || state === 'SUCCESS') { return; } - cancelableTask.state = TransferTaskState.CANCELED; + cancelableTask.state = 'CANCELED'; onCancel(abortErrorOverwrite); }, state, @@ -41,14 +37,14 @@ const createCancellableTask = ({ const wrappedJobPromise = (async () => { try { const result = await job(); - cancelableTask.state = TransferTaskState.SUCCESS; + cancelableTask.state = 'SUCCESS'; return result; } catch (e) { if (isCancelError(e)) { - cancelableTask.state = TransferTaskState.CANCELED; + cancelableTask.state = 'CANCELED'; throw abortErrorOverwriteRecord ?? e; } - cancelableTask.state = TransferTaskState.ERROR; + cancelableTask.state = 'ERROR'; throw e; } })(); @@ -83,20 +79,20 @@ export const createUploadTask = ({ const uploadTask = Object.assign(cancellableTask, { pause: () => { const { state } = uploadTask; - if (!isMultipartUpload || state !== TransferTaskState.IN_PROGRESS) { + if (!isMultipartUpload || state !== 'IN_PROGRESS') { return; } // @ts-ignore - uploadTask.state = TransferTaskState.PAUSED; + uploadTask.state = 'PAUSED'; onPause?.(); }, resume: () => { const { state } = uploadTask; - if (!isMultipartUpload || state !== TransferTaskState.PAUSED) { + if (!isMultipartUpload || state !== 'PAUSED') { return; } // @ts-ignore - uploadTask.state = TransferTaskState.IN_PROGRESS; + uploadTask.state = 'IN_PROGRESS'; onResume?.(); }, }); diff --git a/packages/storage/src/types/common.ts b/packages/storage/src/types/common.ts index f1288e8cb4d..a61391b5b17 100644 --- a/packages/storage/src/types/common.ts +++ b/packages/storage/src/types/common.ts @@ -1,13 +1,12 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export enum TransferTaskState { - IN_PROGRESS = 'IN_PROGRESS', - PAUSED = 'PAUSED', - CANCELED = 'CANCELED', - SUCCESS = 'SUCCESS', - ERROR = 'ERROR', -} +export type TransferTaskState = + | 'IN_PROGRESS' + | 'PAUSED' + | 'CANCELED' + | 'SUCCESS' + | 'ERROR'; export type TransferProgressEvent = { transferredBytes: number; From c7dfaf223416d16cb1671c81be3e2c8678930179 Mon Sep 17 00:00:00 2001 From: israx <70438514+israx@users.noreply.github.com> Date: Fri, 15 Sep 2023 10:29:09 -0400 Subject: [PATCH 7/9] chore(auth): add authenticated client side validation (#12033) * chore: add already authenticated user client side validation * chore: improve error message for authenticated users * chore: add unit tests in sign-in * chore: change error message * chore: add authenticated validation in signInWithRedirect API * chore: address feedback --- .../cognito/signInWithCustomAuth.test.ts | 23 +++++++++++++- .../cognito/signInWithCustomSRPAuth.test.ts | 22 +++++++++++++- .../providers/cognito/signInWithSRP.test.ts | 23 +++++++++++++- .../cognito/signInWithUserPassword.test.ts | 30 ++++++++++++++----- packages/auth/src/errors/constants.ts | 6 ++++ .../auth/src/providers/cognito/apis/signIn.ts | 4 ++- .../cognito/apis/signInWithRedirect.ts | 6 +++- .../providers/cognito/utils/signInHelpers.ts | 19 ++++++++++++ .../auth/src/providers/cognito/utils/types.ts | 16 ++++++---- 9 files changed, 130 insertions(+), 19 deletions(-) create mode 100644 packages/auth/src/errors/constants.ts diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts index fe5e095e77b..3e042006724 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts @@ -5,15 +5,18 @@ import { Amplify } from 'aws-amplify'; import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { authAPITestParams } from './testUtils/authApiTestParams'; -import { signIn } from '../../../src/providers/cognito/apis/signIn'; +import { signIn, getCurrentUser } from '../../../src/providers/cognito'; import { signInWithCustomAuth } from '../../../src/providers/cognito/apis/signInWithCustomAuth'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { InitiateAuthCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; +import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; +jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); + const authConfig = { Cognito: { userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', @@ -83,6 +86,24 @@ describe('signIn API happy path cases', () => { }); describe('signIn API error path cases:', () => { + test('signIn API should throw a validation AuthError when a user is already signed-in', async () => { + const mockedGetCurrentUser = getCurrentUser as jest.Mock; + + mockedGetCurrentUser.mockImplementationOnce(async () => { + return { + username: 'username', + userId: 'userId', + }; + }); + + try { + await signIn({ username: 'username', password: 'password' }); + } catch (error) { + expect(error).toBeInstanceOf(AuthError); + expect(error.name).toBe(USER_ALREADY_AUTHENTICATED_EXCEPTION); + } + mockedGetCurrentUser.mockClear(); + }); test('signIn API should throw a validation AuthError when username is empty', async () => { expect.assertions(2); try { diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts index ad639174b76..9c4189d11d8 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts @@ -4,7 +4,7 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { authAPITestParams } from './testUtils/authApiTestParams'; -import { signIn } from '../../../src/providers/cognito/apis/signIn'; +import { signIn, getCurrentUser } from '../../../src/providers/cognito'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { signInWithCustomSRPAuth } from '../../../src/providers/cognito/apis/signInWithCustomSRPAuth'; @@ -12,6 +12,8 @@ import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cogn import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; +import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; +jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); const authConfig = { @@ -89,6 +91,24 @@ describe('signIn API happy path cases', () => { }); describe('signIn API error path cases:', () => { + test('signIn API should throw a validation AuthError when a user is already signed-in', async () => { + const mockedGetCurrentUser = getCurrentUser as jest.Mock; + + mockedGetCurrentUser.mockImplementationOnce(async () => { + return { + username: 'username', + userId: 'userId', + }; + }); + + try { + await signIn({ username: 'username', password: 'password' }); + } catch (error) { + expect(error).toBeInstanceOf(AuthError); + expect(error.name).toBe(USER_ALREADY_AUTHENTICATED_EXCEPTION); + } + mockedGetCurrentUser.mockClear(); + }); test('signIn API should throw a validation AuthError when username is empty', async () => { expect.assertions(2); try { diff --git a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts index be8a84f3228..55f2968d754 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts @@ -1,9 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 + import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { authAPITestParams } from './testUtils/authApiTestParams'; -import { signIn } from '../../../src/providers/cognito/apis/signIn'; +import { signIn, getCurrentUser } from '../../../src/providers/cognito'; import { signInWithSRP } from '../../../src/providers/cognito/apis/signInWithSRP'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; @@ -12,6 +13,8 @@ import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { CognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; +import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; +jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); const authConfig = { @@ -99,6 +102,24 @@ describe('signIn API happy path cases', () => { }); describe('signIn API error path cases:', () => { + test('signIn API should throw a validation AuthError when a user is already signed-in', async () => { + const mockedGetCurrentUser = getCurrentUser as jest.Mock; + + mockedGetCurrentUser.mockImplementationOnce(async () => { + return { + username: 'username', + userId: 'userId', + }; + }); + + try { + await signIn({ username: 'username', password: 'password' }); + } catch (error) { + expect(error).toBeInstanceOf(AuthError); + expect(error.name).toBe(USER_ALREADY_AUTHENTICATED_EXCEPTION); + } + mockedGetCurrentUser.mockClear(); + }); test('signIn API should throw a validation AuthError when username is empty', async () => { expect.assertions(2); try { diff --git a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts index 93e3fc71c18..e21b8d7d990 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts @@ -4,7 +4,7 @@ import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { authAPITestParams } from './testUtils/authApiTestParams'; -import { signIn } from '../../../src/providers/cognito/apis/signIn'; +import { signIn, getCurrentUser } from '../../../src/providers/cognito'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { signInWithUserPassword } from '../../../src/providers/cognito/apis/signInWithUserPassword'; @@ -12,8 +12,9 @@ import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cogn import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -import { cognitoCredentialsProvider } from '../../../src/providers/cognito/credentialsProvider'; import { CognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; +import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; +jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); const authConfig = { @@ -22,12 +23,7 @@ const authConfig = { userPoolId: 'us-west-2_zzzzz', }, }; -const authConfigWithClientmetadata = { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - }, -}; + CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); Amplify.configure({ Auth: authConfig, @@ -82,6 +78,24 @@ describe('signIn API happy path cases', () => { }); describe('signIn API error path cases:', () => { + test('signIn API should throw a validation AuthError when a user is already signed-in', async () => { + const mockedGetCurrentUser = getCurrentUser as jest.Mock; + + mockedGetCurrentUser.mockImplementationOnce(async () => { + return { + username: 'username', + userId: 'userId', + }; + }); + + try { + await signIn({ username: 'username', password: 'password' }); + } catch (error) { + expect(error).toBeInstanceOf(AuthError); + expect(error.name).toBe(USER_ALREADY_AUTHENTICATED_EXCEPTION); + } + mockedGetCurrentUser.mockClear(); + }); test('signIn API should throw a validation AuthError when username is empty', async () => { expect.assertions(2); try { diff --git a/packages/auth/src/errors/constants.ts b/packages/auth/src/errors/constants.ts new file mode 100644 index 00000000000..06baaade260 --- /dev/null +++ b/packages/auth/src/errors/constants.ts @@ -0,0 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const USER_UNAUTHENTICATED_EXCEPTION = 'UserUnAuthenticatedException'; +export const USER_ALREADY_AUTHENTICATED_EXCEPTION = + 'UserAlreadyAuthenticatedException'; diff --git a/packages/auth/src/providers/cognito/apis/signIn.ts b/packages/auth/src/providers/cognito/apis/signIn.ts index 46ec83c5eb1..e90348fbec6 100644 --- a/packages/auth/src/providers/cognito/apis/signIn.ts +++ b/packages/auth/src/providers/cognito/apis/signIn.ts @@ -9,6 +9,8 @@ import { signInWithCustomAuth } from './signInWithCustomAuth'; import { signInWithCustomSRPAuth } from './signInWithCustomSRPAuth'; import { signInWithSRP } from './signInWithSRP'; import { signInWithUserPassword } from './signInWithUserPassword'; +import { assertUserNotAuthenticated } from '../utils/signInHelpers'; + import { SignInInput, SignInOutput } from '../types'; /** * Signs a user in @@ -23,7 +25,7 @@ import { SignInInput, SignInOutput } from '../types'; */ export async function signIn(input: SignInInput): Promise { const authFlowType = input.options?.serviceOptions?.authFlowType; - + await assertUserNotAuthenticated(); switch (authFlowType) { case 'USER_SRP_AUTH': return signInWithSRP(input); diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index d77d54bbfc5..839360360c8 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -24,6 +24,7 @@ import { AuthError } from '../../../errors/AuthError'; import { AuthErrorTypes } from '../../../types/Auth'; import { AuthErrorCodes } from '../../../common/AuthErrorStrings'; import { authErrorMessages } from '../../../Errors'; +import { assertUserNotAuthenticated } from '../utils/signInHelpers'; import { SignInWithRedirectInput } from '../types'; const SELF = '_self'; @@ -35,7 +36,10 @@ const SELF = '_self'; * * TODO: add config errors */ -export function signInWithRedirect(input?: SignInWithRedirectInput): void { +export async function signInWithRedirect( + input?: SignInWithRedirectInput +): Promise { + await assertUserNotAuthenticated(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); assertOAuthConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index 218fc3be082..d3324915aae 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -21,6 +21,7 @@ import { import { AuthError } from '../../../errors/AuthError'; import { InitiateAuthException } from '../types/errors'; import { + AuthUser, AuthUserAttribute, AuthMFAType, AuthTOTPSetupDetails, @@ -45,6 +46,8 @@ import { RespondToAuthChallengeCommandOutput, } from './clients/CognitoIdentityProvider/types'; import { getRegion } from './clients/CognitoIdentityProvider/utils'; +import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../errors/constants'; +import { getCurrentUser } from '../apis/getCurrentUser'; const USER_ATTRIBUTES = 'userAttributes.'; @@ -630,3 +633,19 @@ export function isMFATypeEnabled( if (!mfaTypes) return false; return mfaTypes.includes(mfaType); } + +export async function assertUserNotAuthenticated() { + let authUser: AuthUser | undefined; + try { + authUser = await getCurrentUser(); + } catch (error) {} + + if (authUser && authUser.userId && authUser.username) { + throw new AuthError({ + name: USER_ALREADY_AUTHENTICATED_EXCEPTION, + message: + 'There is already a signed in user.', + recoverySuggestion: 'Call signOut before calling signIn again.', + }); + } +} diff --git a/packages/auth/src/providers/cognito/utils/types.ts b/packages/auth/src/providers/cognito/utils/types.ts index 0bcccf0f0cc..9a364a0eec1 100644 --- a/packages/auth/src/providers/cognito/utils/types.ts +++ b/packages/auth/src/providers/cognito/utils/types.ts @@ -10,6 +10,7 @@ import { import { AuthError } from '../../../errors/AuthError'; import { CognitoAuthTokens } from '../tokenProvider/types'; +import { USER_UNAUTHENTICATED_EXCEPTION } from '../../../errors/constants'; export function isTypeUserPoolConfig( authConfig?: AuthConfig @@ -30,8 +31,9 @@ export function assertAuthTokens( ): asserts tokens is AuthTokens { if (!tokens || !tokens.accessToken) { throw new AuthError({ - name: 'Invalid Auth Tokens', - message: 'No Auth Tokens were found', + name: USER_UNAUTHENTICATED_EXCEPTION, + message: 'User needs to be authenticated to call this API.', + recoverySuggestion: 'Sign in before calling this API again.', }); } } @@ -41,8 +43,9 @@ export function assertIdTokenInAuthTokens( ): asserts tokens is AuthTokens { if (!tokens || !tokens.idToken) { throw new AuthError({ - name: 'IdToken not present in Auth Tokens', - message: 'No IdToken in Auth Tokens', + name: USER_UNAUTHENTICATED_EXCEPTION, + message: 'User needs to be authenticated to call this API.', + recoverySuggestion: 'Sign in before calling this API again.', }); } } @@ -52,8 +55,9 @@ export function assertAuthTokensWithRefreshToken( ): asserts tokens is CognitoAuthTokens & { refreshToken: string } { if (!tokens || !tokens.accessToken || !tokens.refreshToken) { throw new AuthError({ - name: 'Invalid Cognito Auth Tokens', - message: 'No Cognito Auth Tokens were found', + name: USER_UNAUTHENTICATED_EXCEPTION, + message: 'User needs to be authenticated to call this API.', + recoverySuggestion: 'Sign in before calling this API again.', }); } } From a96ade9e8dd168ab1cbc4ed73c1c63f1ad839421 Mon Sep 17 00:00:00 2001 From: israx <70438514+israx@users.noreply.github.com> Date: Fri, 15 Sep 2023 12:24:31 -0400 Subject: [PATCH 8/9] chore(auth): fix unnecessary network calls in getCurrentUser API (#12052) * chore: fix api network calls in getCurrentUser * chore: add getTokens method in internal auth class * chore: fix tests * chore: fix build * chore: remove input types * chore: fix build issue * fix build issue * fix build issue again * chore: fix failing unit test --- .../providers/cognito/getCurrentUser.test.ts | 55 ++++++++----------- packages/auth/package.json | 2 +- packages/auth/src/index.ts | 1 - .../providers/cognito/apis/getCurrentUser.ts | 8 +-- .../cognito/apis/internal/getCurrentUser.ts | 14 ++--- .../cognito/apis/server/getCurrentUser.ts | 11 +--- packages/auth/src/providers/cognito/index.ts | 1 - .../auth/src/providers/cognito/types/index.ts | 1 - .../src/providers/cognito/types/inputs.ts | 6 -- packages/auth/src/types/index.ts | 1 - packages/auth/src/types/inputs.ts | 6 -- packages/core/src/singleton/Auth/index.ts | 11 +++- 12 files changed, 42 insertions(+), 75 deletions(-) diff --git a/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts b/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts index c7cdfe014a0..1c7b3bc2920 100644 --- a/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts @@ -2,18 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from 'aws-amplify'; -import { decodeJWT, fetchAuthSession } from '@aws-amplify/core/internals/utils'; +import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../src/errors/AuthError'; import { getCurrentUser } from '../../../src/providers/cognito'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; - +import { Amplify as AmplifyV6 } from '@aws-amplify/core'; +import { USER_UNAUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); -jest.mock('@aws-amplify/core/internals/utils', () => ({ - ...jest.requireActual('@aws-amplify/core/internals/utils'), - fetchAuthSession: jest.fn(), -})); Amplify.configure({ Auth: { @@ -26,27 +23,25 @@ Amplify.configure({ }); const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; -const mockFetchAuthSession = fetchAuthSession as jest.Mock; +const mockGetTokensFunction = jest.spyOn(AmplifyV6.Auth, 'getTokens'); const mockedSub = 'mockedSub'; const mockedUsername = 'XXXXXXXXXXXXXX'; describe('getUser API happy path cases', () => { beforeEach(() => { - mockFetchAuthSession.mockResolvedValue({ - tokens: { - accessToken: decodeJWT(mockedAccessToken), - idToken: { - payload: { - sub: mockedSub, - 'cognito:username': mockedUsername, - }, + mockGetTokensFunction.mockResolvedValue({ + accessToken: decodeJWT(mockedAccessToken), + idToken: { + payload: { + sub: mockedSub, + 'cognito:username': mockedUsername, }, }, }); }); afterEach(() => { - mockFetchAuthSession.mockClear(); + mockGetTokensFunction.mockClear(); }); test('get current user', async () => { @@ -56,26 +51,20 @@ describe('getUser API happy path cases', () => { }); describe('getUser API error path cases:', () => { - test('getUser API should raise service error', async () => { - expect.assertions(2); - mockFetchAuthSession.mockImplementationOnce(async () => { - throw new AuthError({ - name: InitiateAuthException.InternalErrorException, - message: 'error at fetchAuthSession', - }); - }); - (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse( - buildMockErrorResponse(InitiateAuthException.InternalErrorException) - ) - ); + beforeEach(() => { + mockGetTokensFunction.mockResolvedValue(null); + }); + + afterEach(() => { + mockGetTokensFunction.mockClear(); + }); + test('getUser API should raise a validation error when tokens are not found', async () => { try { - await getCurrentUser({ - recache: true, - }); + const result = await getCurrentUser(); } catch (error) { + console.log(error); expect(error).toBeInstanceOf(AuthError); - expect(error.name).toBe(InitiateAuthException.InternalErrorException); + expect(error.name).toBe(USER_UNAUTHENTICATED_EXCEPTION); } }); }); diff --git a/packages/auth/package.json b/packages/auth/package.json index 707e27a39c3..0234779df75 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -25,7 +25,7 @@ "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint '{src}/**/*.ts' && npm run ts-coverage", - "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 91.19" + "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 91.18" }, "typesVersions": { ">=3.8": { diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 3bc11f17206..39f628e6c4e 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -24,7 +24,6 @@ export { } from './providers/cognito'; export { - GetCurrentUserInput, ConfirmResetPasswordInput, ConfirmSignInInput, ConfirmSignUpInput, diff --git a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts index 19fa2719096..db5a9c30235 100644 --- a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import { GetCurrentUserInput, GetCurrentUserOutput } from '../types'; +import { GetCurrentUserOutput } from '../types'; import { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentUser'; /** @@ -13,8 +13,6 @@ import { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentU * @throws - {@link InitiateAuthException} - Thrown when the service fails to refresh the tokens. * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ -export const getCurrentUser = async ( - input?: GetCurrentUserInput -): Promise => { - return getCurrentUserInternal(Amplify, input); +export const getCurrentUser = async (): Promise => { + return getCurrentUserInternal(Amplify); }; diff --git a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts index 093cc506dd1..a1304858911 100644 --- a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts @@ -2,22 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { AmplifyClassV6 } from '@aws-amplify/core'; -import { - assertTokenProviderConfig, - fetchAuthSession, -} from '@aws-amplify/core/internals/utils'; -import { GetCurrentUserInput, GetCurrentUserOutput } from '../../types'; +import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { assertAuthTokens } from '../../utils/types'; +import { GetCurrentUserOutput } from '../../types'; export const getCurrentUser = async ( - amplify: AmplifyClassV6, - input?: GetCurrentUserInput + amplify: AmplifyClassV6 ): Promise => { const authConfig = amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); - const { tokens } = await fetchAuthSession(amplify, { - forceRefresh: input?.recache ?? false, - }); + const tokens = await amplify.Auth.getTokens({ forceRefresh: false }); assertAuthTokens(tokens); const { 'cognito:username': username, sub } = tokens.idToken?.payload ?? {}; diff --git a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts index f59de229943..daa7d7081eb 100644 --- a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts @@ -5,23 +5,18 @@ import { AmplifyServer, getAmplifyServerContext, } from '@aws-amplify/core/internals/adapter-core'; -import { GetCurrentUserOutput, GetCurrentUserInput } from '../../types'; +import { GetCurrentUserOutput } from '../../types'; import { getCurrentUser as getCurrentUserInternal } from '../internal/getCurrentUser'; /** * Gets the current user from the idToken. * - * @param input - The GetCurrentUserInput object. * @returns GetCurrentUserOutput * @throws - {@link InitiateAuthException} - Thrown when the service fails to refresh the tokens. * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const getCurrentUser = async ( - contextSpec: AmplifyServer.ContextSpec, - input?: GetCurrentUserInput + contextSpec: AmplifyServer.ContextSpec ): Promise => { - return getCurrentUserInternal( - getAmplifyServerContext(contextSpec).amplify, - input - ); + return getCurrentUserInternal(getAmplifyServerContext(contextSpec).amplify); }; diff --git a/packages/auth/src/providers/cognito/index.ts b/packages/auth/src/providers/cognito/index.ts index fd05b4c7075..0f8fb9ffb24 100644 --- a/packages/auth/src/providers/cognito/index.ts +++ b/packages/auth/src/providers/cognito/index.ts @@ -20,7 +20,6 @@ export { signInWithRedirect } from './apis/signInWithRedirect'; export { fetchUserAttributes } from './apis/fetchUserAttributes'; export { signOut } from './apis/signOut'; export { - GetCurrentUserInput, ConfirmResetPasswordInput, ConfirmSignInInput, ConfirmSignUpInput, diff --git a/packages/auth/src/providers/cognito/types/index.ts b/packages/auth/src/providers/cognito/types/index.ts index 15aa1cb5d8b..c24963b7098 100644 --- a/packages/auth/src/providers/cognito/types/index.ts +++ b/packages/auth/src/providers/cognito/types/index.ts @@ -22,7 +22,6 @@ export { } from './options'; export { - GetCurrentUserInput, ConfirmResetPasswordInput, ConfirmSignInInput, ConfirmSignUpInput, diff --git a/packages/auth/src/providers/cognito/types/inputs.ts b/packages/auth/src/providers/cognito/types/inputs.ts index be22e8bbcec..7f9ae8d4e26 100644 --- a/packages/auth/src/providers/cognito/types/inputs.ts +++ b/packages/auth/src/providers/cognito/types/inputs.ts @@ -15,7 +15,6 @@ import { VerifyTOTPSetupOptions, } from '../types'; import { - AuthGetCurrentUserInput, AuthConfirmResetPasswordInput, AuthConfirmSignInInput, AuthConfirmSignUpInput, @@ -31,11 +30,6 @@ import { AuthVerifyTOTPSetupInput, } from '../../../types'; -/** - * Input type for Cognito getCurrentUser API. - */ -export type GetCurrentUserInput = AuthGetCurrentUserInput; - /** * Input type for Cognito confirmResetPassword API. */ diff --git a/packages/auth/src/types/index.ts b/packages/auth/src/types/index.ts index 171e4ad3e90..25d923ce952 100644 --- a/packages/auth/src/types/index.ts +++ b/packages/auth/src/types/index.ts @@ -34,7 +34,6 @@ export { AuthConfirmSignInInput, AuthUpdatePasswordInput, AuthUpdateUserAttributesInput, - AuthGetCurrentUserInput, AuthConfirmUserAttributeInput, AuthVerifyTOTPSetupInput, AuthSignInWithRedirectInput, diff --git a/packages/auth/src/types/inputs.ts b/packages/auth/src/types/inputs.ts index d94968dafb3..912f5c90129 100644 --- a/packages/auth/src/types/inputs.ts +++ b/packages/auth/src/types/inputs.ts @@ -137,12 +137,6 @@ export type AuthUpdateUserAttributesInput< options?: { serviceOptions?: ServiceOptions }; }; -/** - * Constructs a `GetCurrentUser` input. - * @param recache - whether to recache the user - */ -export type AuthGetCurrentUserInput = { recache: boolean }; - /* * Constructs a `verifyUserAttribute` input. * diff --git a/packages/core/src/singleton/Auth/index.ts b/packages/core/src/singleton/Auth/index.ts index 8c84e6b89cb..66321ebb7d6 100644 --- a/packages/core/src/singleton/Auth/index.ts +++ b/packages/core/src/singleton/Auth/index.ts @@ -52,8 +52,7 @@ export class AuthClass { let userSub: string | undefined; // Get tokens will throw if session cannot be refreshed (network or service error) or return null if not available - tokens = - (await this.authOptions?.tokenProvider?.getTokens(options)) ?? undefined; + tokens = await this.getTokens(options); if (tokens) { userSub = tokens.accessToken?.payload?.sub; @@ -93,4 +92,12 @@ export class AuthClass { return await this.authOptions.credentialsProvider.clearCredentialsAndIdentityId(); } } + + async getTokens( + options: FetchAuthSessionOptions + ): Promise { + return ( + (await this.authOptions?.tokenProvider?.getTokens(options)) ?? undefined + ); + } } From 2abb1367c5359502175031a63d04a57d784d7f1a Mon Sep 17 00:00:00 2001 From: AllanZhengYP Date: Fri, 15 Sep 2023 10:39:24 -0700 Subject: [PATCH 9/9] feat: disallow targetIdentityId option in all S3 write APIs and category API (#12034) --------- Co-authored-by: Jim Blanchard --- .../__tests__/providers/s3/apis/copy.test.ts | 12 +- .../providers/s3/apis/downloadData.test.ts | 6 +- .../providers/s3/apis/getProperties.test.ts | 4 +- .../providers/s3/apis/getUrl.test.ts | 6 +- .../__tests__/providers/s3/apis/list.test.ts | 16 ++- .../storage/src/providers/s3/types/index.ts | 2 + .../storage/src/providers/s3/types/inputs.ts | 8 +- .../storage/src/providers/s3/types/options.ts | 127 ++++++++++-------- packages/storage/src/types/index.ts | 2 - packages/storage/src/types/inputs.ts | 17 ++- packages/storage/src/types/options.ts | 20 +-- 11 files changed, 121 insertions(+), 99 deletions(-) diff --git a/packages/storage/__tests__/providers/s3/apis/copy.test.ts b/packages/storage/__tests__/providers/s3/apis/copy.test.ts index 41f40ac660a..dc33c10276c 100644 --- a/packages/storage/__tests__/providers/s3/apis/copy.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/copy.test.ts @@ -2,13 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { Credentials } from '@aws-sdk/types'; -import { Amplify, StorageAccessLevel } from '@aws-amplify/core'; +import { Amplify } from '@aws-amplify/core'; import { copyObject } from '../../../../src/providers/s3/utils/client'; import { copy } from '../../../../src/providers/s3/apis'; import { - StorageCopySourceOptions, - StorageCopyDestinationOptions, -} from '../../../../src/types'; + CopySourceOptions, + CopyDestinationOptions, +} from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ @@ -153,11 +153,11 @@ describe('copy API', () => { expect( await copy({ source: { - ...(source as StorageCopySourceOptions), + ...(source as CopySourceOptions), key: sourceKey, }, destination: { - ...(destination as StorageCopyDestinationOptions), + ...(destination as CopyDestinationOptions), key: destinationKey, }, }) diff --git a/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts b/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts index a4b095a6d90..e107f05e6ad 100644 --- a/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts @@ -6,7 +6,7 @@ import { Amplify } from '@aws-amplify/core'; import { getObject } from '../../../../src/providers/s3/utils/client'; import { downloadData } from '../../../../src/providers/s3'; import { createDownloadTask } from '../../../../src/providers/s3/utils'; -import { StorageOptions } from '../../../../src/types'; +import { DownloadDataOptions } from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('../../../../src/providers/s3/utils'); @@ -93,10 +93,10 @@ describe('downloadData', () => { downloadData({ key, options: { - ...(options as StorageOptions), + ...options, useAccelerateEndpoint: true, onProgress, - }, + } as DownloadDataOptions, }); const job = mockCreateDownloadTask.mock.calls[0][0].job; await job(); diff --git a/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts b/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts index 60765c2a95f..946eac7c245 100644 --- a/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts @@ -5,7 +5,7 @@ import { headObject } from '../../../../src/providers/s3/utils/client'; import { getProperties } from '../../../../src/providers/s3'; import { Credentials } from '@aws-sdk/types'; import { Amplify } from '@aws-amplify/core'; -import { StorageOptions } from '../../../../src/types'; +import { GetPropertiesOptions } from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ @@ -107,7 +107,7 @@ describe('getProperties api', () => { expect( await getProperties({ key, - options: options as StorageOptions, + options: options as GetPropertiesOptions, }) ).toEqual(expected); expect(headObject).toBeCalledTimes(1); diff --git a/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts b/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts index 74b992f18c2..5fb759584e8 100644 --- a/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts @@ -8,7 +8,7 @@ import { getPresignedGetObjectUrl, headObject, } from '../../../../src/providers/s3/utils/client'; -import { StorageOptions } from '../../../../src/types'; +import { GetUrlOptions } from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ @@ -106,9 +106,9 @@ describe('getUrl test', () => { const result = await getUrl({ key, options: { - ...(options as StorageOptions), + ...options, validateObjectExistence: true, - }, + } as GetUrlOptions, }); expect(getPresignedGetObjectUrl).toBeCalledTimes(1); expect(headObject).toBeCalledTimes(1); diff --git a/packages/storage/__tests__/providers/s3/apis/list.test.ts b/packages/storage/__tests__/providers/s3/apis/list.test.ts index fecad15e696..c1bc773127d 100644 --- a/packages/storage/__tests__/providers/s3/apis/list.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/list.test.ts @@ -4,8 +4,11 @@ import { Credentials } from '@aws-sdk/types'; import { Amplify } from '@aws-amplify/core'; import { listObjectsV2 } from '../../../../src/providers/s3/utils/client'; -import { list } from '../../../../src/providers/s3/apis'; -import { StorageOptions } from '../../../../src/types'; +import { list } from '../../../../src/providers/s3'; +import { + ListAllOptions, + ListPaginateOptions, +} from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ @@ -135,7 +138,7 @@ describe('list API', () => { expect.assertions(4); let response = await list({ prefix: path, - options: options as StorageOptions, + options: options as ListPaginateOptions, }); expect(response.items).toEqual([ { ...listResultItem, key: path ?? '' }, @@ -170,7 +173,7 @@ describe('list API', () => { const response = await list({ prefix: path, options: { - ...(options as StorageOptions), + ...(options as ListPaginateOptions), pageSize: customPageSize, nextToken: nextToken, }, @@ -202,9 +205,10 @@ describe('list API', () => { expect.assertions(3); let response = await list({ prefix: path, - options: options as StorageOptions, + options: options as ListPaginateOptions, }); expect(response.items).toEqual([]); + // expect(response.nextToken).toEqual(undefined); expect(listObjectsV2).toHaveBeenCalledWith(listObjectClientConfig, { Bucket: bucket, @@ -225,7 +229,7 @@ describe('list API', () => { mockListObjectsV2ApiWithPages(3); const result = await list({ prefix: path, - options: { ...(options as StorageOptions), listAll: true }, + options: { ...options, listAll: true } as ListAllOptions, }); const listResult = { ...listResultItem, key: path ?? '' }; diff --git a/packages/storage/src/providers/s3/types/index.ts b/packages/storage/src/providers/s3/types/index.ts index 17c64167090..4366ee48383 100644 --- a/packages/storage/src/providers/s3/types/index.ts +++ b/packages/storage/src/providers/s3/types/index.ts @@ -9,6 +9,8 @@ export { ListPaginateOptions, RemoveOptions, DownloadDataOptions, + CopyDestinationOptions, + CopySourceOptions, } from './options'; export { DownloadDataOutput, diff --git a/packages/storage/src/providers/s3/types/inputs.ts b/packages/storage/src/providers/s3/types/inputs.ts index 6596925cbc5..51c25ab4b3f 100644 --- a/packages/storage/src/providers/s3/types/inputs.ts +++ b/packages/storage/src/providers/s3/types/inputs.ts @@ -18,12 +18,18 @@ import { RemoveOptions, DownloadDataOptions, UploadDataOptions, + CopyDestinationOptions, + CopySourceOptions, } from '../types'; +// TODO: support use accelerate endpoint option /** * Input type for S3 copy API. */ -export type CopyInput = StorageCopyInput; +export type CopyInput = StorageCopyInput< + CopySourceOptions, + CopyDestinationOptions +>; /** * Input type for S3 getProperties API. diff --git a/packages/storage/src/providers/s3/types/options.ts b/packages/storage/src/providers/s3/types/options.ts index b2bd747e1e9..5082cfd4542 100644 --- a/packages/storage/src/providers/s3/types/options.ts +++ b/packages/storage/src/providers/s3/types/options.ts @@ -1,20 +1,17 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { StorageAccessLevel } from '@aws-amplify/core'; // TODO(ashwinkumar6) this uses V5 Credentials, update to V6. import { Credentials } from '@aws-sdk/types'; import { TransferProgressEvent } from '../../../types'; import { - StorageOptions, StorageListAllOptions, StorageListPaginateOptions, } from '../../../types/options'; -/** - * Input options type for S3 Storage operations. - */ -export type Options = StorageOptions & { +type CommonOptions = { /** * Whether to use accelerate endpoint. * @default false @@ -22,68 +19,101 @@ export type Options = StorageOptions & { useAccelerateEndpoint?: boolean; }; +type ReadOptions = + | { accessLevel?: 'guest' | 'private' } + | { accessLevel: 'protected'; targetIdentityId?: string }; + +type WriteOptions = { + accessLevel?: StorageAccessLevel; +}; + +/** + * Transfer-related options type for S3 downloadData, uploadData APIs. + */ +type TransferOptions = { + /** + * Callback function tracking the upload/download progress. + */ + onProgress?: (event: TransferProgressEvent) => void; +}; + /** * Input options type for S3 getProperties API. */ -export type GetPropertiesOptions = Options; +export type GetPropertiesOptions = ReadOptions & CommonOptions; /** * Input options type for S3 getProperties API. */ -export type RemoveOptions = Options; +export type RemoveOptions = WriteOptions & CommonOptions; /** * Input options type for S3 list API. */ -export type ListAllOptions = StorageListAllOptions; +export type ListAllOptions = StorageListAllOptions & + ReadOptions & + CommonOptions; /** * Input options type for S3 list API. */ -export type ListPaginateOptions = StorageListPaginateOptions; +export type ListPaginateOptions = StorageListPaginateOptions & + ReadOptions & + CommonOptions; /** - * Input options type for S3 downloadData API. + * Input options type for S3 getUrl API. */ -export type DownloadDataOptions = TransferOptions; +export type GetUrlOptions = ReadOptions & + CommonOptions & { + /** + * Whether to head object to make sure the object existence before downloading. + * @default false + */ + validateObjectExistence?: boolean; + /** + * Number of seconds till the URL expires. + * @default 900 (15 minutes) + */ + expiresIn?: number; + }; /** - * Input options type for S3 getUrl API. + * Input options type for S3 downloadData API. */ -export type GetUrlOptions = Options & { - /** - * Whether to head object to make sure the object existence before downloading. - * @default false - */ - validateObjectExistence?: boolean; - /** - * Number of seconds till the URL expires. - * @default 900 (15 minutes) - */ - expiresIn?: number; +export type DownloadDataOptions = ReadOptions & CommonOptions & TransferOptions; + +export type UploadDataOptions = WriteOptions & + CommonOptions & + TransferOptions & { + /** + * The default content-disposition header value of the file when downloading it. + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition + */ + contentDisposition?: string; + /** + * The default content-encoding header value of the file when downloading it. + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + */ + contentEncoding?: string; + /** + * The default content-type header value of the file when downloading it. + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type + */ + contentType?: string; + /** + * The user-defined metadata for the object uploaded to S3. + * @see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html#UserMetadata + */ + metadata?: Record; + }; + +export type CopySourceOptions = ReadOptions & { + key: string; }; -export type UploadDataOptions = Omit & { - /** - * The default content-disposition header value of the file when downloading it. - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition - */ - contentDisposition?: string; - /** - * The default content-encoding header value of the file when downloading it. - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - */ - contentEncoding?: string; - /** - * The default content-type header value of the file when downloading it. - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type - */ - contentType?: string; - /** - * The user-defined metadata for the object uploaded to S3. - * @see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html#UserMetadata - */ - metadata?: Record; +export type CopyDestinationOptions = WriteOptions & { + key: string; }; /** @@ -98,12 +128,3 @@ export type ResolvedS3Config = { forcePathStyle?: boolean; useAccelerateEndpoint?: boolean; }; -/** - * Input options type for S3 downloadData, uploadData APIs. - */ -type TransferOptions = Options & { - /** - * Callback function tracking the upload/download progress. - */ - onProgress?: (event: TransferProgressEvent) => void; -}; diff --git a/packages/storage/src/types/index.ts b/packages/storage/src/types/index.ts index c85523a9c77..39bb1c049a3 100644 --- a/packages/storage/src/types/index.ts +++ b/packages/storage/src/types/index.ts @@ -23,8 +23,6 @@ export { StorageRemoveOptions, StorageListAllOptions, StorageListPaginateOptions, - StorageCopySourceOptions, - StorageCopyDestinationOptions, } from './options'; export { StorageItem, diff --git a/packages/storage/src/types/inputs.ts b/packages/storage/src/types/inputs.ts index 61ed132335b..9ef767450d6 100644 --- a/packages/storage/src/types/inputs.ts +++ b/packages/storage/src/types/inputs.ts @@ -5,8 +5,6 @@ import { StorageOptions, StorageListAllOptions, StorageListPaginateOptions, - StorageCopySourceOptions, - StorageCopyDestinationOptions, } from './options'; export type StorageOperationInput = { @@ -17,8 +15,10 @@ export type StorageOperationInput = { export type StorageGetPropertiesInput = StorageOperationInput; -export type StorageRemoveInput = - StorageOperationInput; +export type StorageRemoveInput = { + key: string; + options?: Options; +}; export type StorageListInput< Options extends StorageListAllOptions | StorageListPaginateOptions @@ -38,9 +38,12 @@ export type StorageUploadDataInput = data: StorageUploadDataPayload; }; -export type StorageCopyInput = { - source: StorageCopySourceOptions; - destination: StorageCopyDestinationOptions; +export type StorageCopyInput< + SourceOptions extends StorageOptions, + DestinationOptions extends StorageOptions +> = { + source: SourceOptions; + destination: DestinationOptions; }; /** diff --git a/packages/storage/src/types/options.ts b/packages/storage/src/types/options.ts index 3a95ffa764d..9962084dfde 100644 --- a/packages/storage/src/types/options.ts +++ b/packages/storage/src/types/options.ts @@ -3,12 +3,9 @@ import { StorageAccessLevel } from '@aws-amplify/core'; -export type StorageOptions = - | { accessLevel?: 'guest' | 'private' } - | { - accessLevel: 'protected'; - targetIdentityId?: string; - }; +export type StorageOptions = { + accessLevel?: StorageAccessLevel; +}; export type StorageListAllOptions = StorageOptions & { listAll: true; @@ -20,13 +17,4 @@ export type StorageListPaginateOptions = StorageOptions & { nextToken?: string; }; -export type StorageRemoveOptions = Omit; - -export type StorageCopySourceOptions = { - key: string; -} & StorageOptions; - -export type StorageCopyDestinationOptions = { - key: string; - accessLevel?: StorageAccessLevel; -}; +export type StorageRemoveOptions = StorageOptions;