diff --git a/.eslintrc.js b/.eslintrc.js index 679e9c307d1..70174f4533a 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -43,7 +43,7 @@ module.exports = { // 'packages/api', 'packages/api-graphql', // 'packages/api-rest', - 'packages/auth', + // 'packages/auth', // 'packages/aws-amplify', // 'packages/core', 'packages/datastore', diff --git a/packages/adapter-nextjs/src/index.ts b/packages/adapter-nextjs/src/index.ts index 14ec009a4a7..fdd0971f1d4 100644 --- a/packages/adapter-nextjs/src/index.ts +++ b/packages/adapter-nextjs/src/index.ts @@ -2,3 +2,4 @@ // SPDX-License-Identifier: Apache-2.0 export { createServerRunner } from './createServerRunner'; +export { NextServer } from './types'; diff --git a/packages/api-graphql/__tests__/fixtures/modeled/amplifyconfiguration.ts b/packages/api-graphql/__tests__/fixtures/modeled/amplifyconfiguration.ts index 4ba26a0916f..cf7504ef3ee 100644 --- a/packages/api-graphql/__tests__/fixtures/modeled/amplifyconfiguration.ts +++ b/packages/api-graphql/__tests__/fixtures/modeled/amplifyconfiguration.ts @@ -1261,6 +1261,106 @@ const amplifyConfig = { sortKeyFieldNames: [], }, }, + Product: { + name: 'Product', + fields: { + sku: { + name: 'sku', + isArray: false, + type: 'String', + isRequired: true, + attributes: [], + }, + factoryId: { + name: 'factoryId', + isArray: false, + type: 'String', + isRequired: true, + attributes: [], + }, + warehouseId: { + name: 'warehouseId', + isArray: false, + type: 'String', + isRequired: true, + attributes: [], + }, + description: { + name: 'description', + isArray: false, + type: 'String', + isRequired: false, + attributes: [], + }, + trackingMeta: { + name: 'trackingMeta', + isArray: false, + type: { + nonModel: 'ProductTrackingMeta', + }, + isRequired: false, + attributes: [], + }, + owner: { + name: 'owner', + isArray: false, + type: 'String', + isRequired: false, + attributes: [], + }, + createdAt: { + name: 'createdAt', + isArray: false, + type: 'AWSDateTime', + isRequired: true, + attributes: [], + }, + updatedAt: { + name: 'updatedAt', + isArray: false, + type: 'AWSDateTime', + isRequired: true, + attributes: [], + }, + }, + syncable: true, + pluralName: 'Products', + attributes: [ + { + type: 'model', + properties: {}, + }, + { + type: 'key', + properties: { + fields: ['sku', 'factoryId', 'warehouseId'], + }, + }, + { + type: 'auth', + properties: { + rules: [ + { + provider: 'userPools', + ownerField: 'owner', + allow: 'owner', + identityClaim: 'cognito:username', + operations: ['create', 'update', 'delete', 'read'], + }, + { + allow: 'public', + operations: ['read'], + }, + ], + }, + }, + ], + primaryKeyInfo: { + isCustomPrimaryKey: true, + primaryKeyFieldName: 'sku', + sortKeyFieldNames: ['factoryId', 'warehouseId'], + }, + }, }, enums: { Status: { @@ -1313,6 +1413,69 @@ const amplifyConfig = { }, }, }, + ProductMeta: { + name: 'ProductMeta', + fields: { + releaseDate: { + name: 'releaseDate', + isArray: false, + type: 'AWSDate', + isRequired: false, + attributes: [], + }, + status: { + name: 'status', + isArray: false, + type: { + enum: 'ProductMetaStatus', + }, + isRequired: false, + attributes: [], + }, + deepMeta: { + name: 'deepMeta', + isArray: false, + type: { + nonModel: 'ProductMetaDeepMeta', + }, + isRequired: false, + attributes: [], + }, + }, + }, + ProductTrackingMeta: { + name: 'ProductTrackingMeta', + fields: { + productMeta: { + name: 'productMeta', + isArray: false, + type: { + nonModel: 'ProductMeta', + }, + isRequired: false, + attributes: [], + }, + note: { + name: 'note', + isArray: false, + type: 'String', + isRequired: false, + attributes: [], + }, + }, + }, + ProductMetaDeepMeta: { + name: 'ProductMetaDeepMeta', + fields: { + content: { + name: 'content', + isArray: false, + type: 'String', + isRequired: false, + attributes: [], + }, + }, + }, }, queries: { echo: { diff --git a/packages/api-graphql/__tests__/internals/APIClient.test.ts b/packages/api-graphql/__tests__/internals/APIClient.test.ts index 8a3894e20ac..4004fc6cb50 100644 --- a/packages/api-graphql/__tests__/internals/APIClient.test.ts +++ b/packages/api-graphql/__tests__/internals/APIClient.test.ts @@ -43,7 +43,7 @@ describe('APIClient', () => { const normalized = normalizeMutationInput( note, noteModelDef, - modelIntroSchema, + modelIntroSchema ); expect(normalized).toEqual(expectedInput); @@ -427,6 +427,15 @@ describe('flattenItems', () => { expect(selSet).toEqual(expected); }); + it('generates default selection set for nested custom types', () => { + const generated = generateSelectionSet(modelIntroSchema, 'Product'); + + const expected = + 'sku factoryId warehouseId description trackingMeta { productMeta { releaseDate status deepMeta { content } } note } owner createdAt updatedAt'; + + expect(generated).toEqual(expected); + }); + test('it should generate custom selection set - top-level fields', () => { const selSet = generateSelectionSet(modelIntroSchema, 'Todo', [ 'id', @@ -476,6 +485,20 @@ describe('flattenItems', () => { expect(selSet).toEqual(expected); }); + + it('generates custom selection set for nested custom types', () => { + const generated = generateSelectionSet(modelIntroSchema, 'Product', [ + 'sku', + 'trackingMeta.note', + 'trackingMeta.productMeta.status', + 'trackingMeta.productMeta.deepMeta.content', + ]); + + const expected = + 'sku trackingMeta { note productMeta { status deepMeta { content } } }'; + + expect(generated).toEqual(expected); + }); }); }); @@ -489,7 +512,7 @@ describe('generateGraphQLDocument()', () => { models: { User: userSchemaModel, Product: productSchemaModel, - } + }, }; test.each([ @@ -501,11 +524,11 @@ describe('generateGraphQLDocument()', () => { const document = generateGraphQLDocument( mockModelDefinitions, modelName, - modelOperation, + modelOperation ); expect(document.includes(expectedArgs)).toBe(true); - }, + } ); }); }); diff --git a/packages/api-graphql/__tests__/internals/generateClient.test.ts b/packages/api-graphql/__tests__/internals/generateClient.test.ts index c5c38f7e1c3..810cd69ed98 100644 --- a/packages/api-graphql/__tests__/internals/generateClient.test.ts +++ b/packages/api-graphql/__tests__/internals/generateClient.test.ts @@ -127,6 +127,7 @@ describe('generateClient', () => { 'SecondaryIndexModel', 'Post', 'Comment', + 'Product', ]; it('generates `models` property when Amplify.getConfig() returns valid GraphQL provider config', () => { diff --git a/packages/api-graphql/src/internals/APIClient.ts b/packages/api-graphql/src/internals/APIClient.ts index c0610b460b4..59bff2c418b 100644 --- a/packages/api-graphql/src/internals/APIClient.ts +++ b/packages/api-graphql/src/internals/APIClient.ts @@ -7,7 +7,6 @@ import { ModelFieldType, NonModelFieldType, SchemaModel, - SchemaModels, AssociationHasOne, AssociationBelongsTo, } from '@aws-amplify/core/internals/utils'; @@ -17,7 +16,6 @@ import { ListArgs, QueryArgs, V6Client, - V6ClientSSRCookies, V6ClientSSRRequest, __authMode, __authToken, @@ -316,25 +314,39 @@ type OperationPrefix = const SELECTION_SET_WILDCARD = '*'; -function defaultSelectionSetForNonModel( - nonModelDefinition: SchemaNonModel -): string[] { - // fields that are explicitly part of the graphql schema; +function defaultSelectionSetForNonModelWithIR( + nonModelDefinition: SchemaNonModel, + modelIntrospection: ModelIntrospectionSchema, +): Record { const { fields } = nonModelDefinition; - const explicitFields = Object.values(fields) - // Default selection set omits non-model fields - .map( - ({ type, name }) => - (typeof type === 'string' || - (typeof type === 'object' && typeof type?.enum === 'string')) && - name, - ) - .filter(Boolean); + const mappedFields = Object.values(fields) + .map(({ type, name }) => { + if (typeof (type as { enum: string }).enum === 'string') { + return [name, FIELD_IR]; + } - // fields used for owner auth rules that may or may not also - // be explicit on the model. + if (typeof (type as NonModelFieldType).nonModel === 'string') { + return [ + name, + defaultSelectionSetForNonModelWithIR( + modelIntrospection.nonModels[(type as NonModelFieldType).nonModel], + modelIntrospection, + ), + ]; + } + + if (typeof type === 'string') { + return [name, FIELD_IR]; + } - return Array.from(new Set(explicitFields)); + return undefined; + }) + .filter( + ( + pair: (string | Record)[] | undefined, + ): pair is (string | Record)[] => pair !== undefined, + ); + return Object.fromEntries(mappedFields); } function defaultSelectionSetForModel(modelDefinition: SchemaModel): string[] { @@ -385,7 +397,7 @@ const FIELD_IR = ''; * ``` */ export function customSelectionSetToIR( - modelInstrospection: ModelIntrospectionSchema, + modelIntrospection: ModelIntrospectionSchema, modelName: string, selectionSet: string[], ): Record { @@ -393,38 +405,42 @@ export function customSelectionSetToIR( const [fieldName, ...rest] = path.split('.'); const nested = rest[0]; - const modelDefinition = modelInstrospection.models[modelOrNonModelName]; + const modelOrNonModelDefinition = + modelIntrospection.models[modelOrNonModelName] ?? + modelIntrospection.nonModels[modelOrNonModelName]; - const modelFields = modelDefinition?.fields; - const relatedModel = (modelFields?.[fieldName]?.type as ModelFieldType) - ?.model; + const modelOrNonModelFields = modelOrNonModelDefinition?.fields; + const relatedModel = ( + modelOrNonModelFields?.[fieldName]?.type as ModelFieldType + )?.model; - const relatedModelDefinition = modelInstrospection.models[relatedModel]; + const relatedModelDefinition = modelIntrospection.models[relatedModel]; const relatedNonModel = ( - modelFields?.[fieldName]?.type as NonModelFieldType + modelOrNonModelFields?.[fieldName]?.type as NonModelFieldType )?.nonModel; const relatedNonModelDefinition = - modelInstrospection.nonModels[relatedNonModel]; + modelIntrospection.nonModels[relatedNonModel]; - const isModelOrNonModelOrField = relatedModelDefinition + const isModelOrNonModelOrFieldType = relatedModelDefinition ? 'model' : relatedNonModelDefinition - ? 'nonModel' - : 'field'; + ? 'nonModel' + : 'field'; - if (isModelOrNonModelOrField === 'nonModel') { + if (isModelOrNonModelOrFieldType === 'nonModel') { let result: Record = {}; if (!nested) { throw Error( - `${fieldName} must declare a wildcard (*) or a field of custom type ${relatedNonModel}` + `${fieldName} must declare a wildcard (*) or a field of custom type ${relatedNonModel}`, ); } if (nested === SELECTION_SET_WILDCARD) { result = { - [fieldName]: nonModelsDefaultSelectionSetIR( - relatedNonModelDefinition + [fieldName]: defaultSelectionSetForNonModelWithIR( + relatedNonModelDefinition, + modelIntrospection, ), }; } else { @@ -434,17 +450,17 @@ export function customSelectionSetToIR( } return result; - } else if (isModelOrNonModelOrField === 'model') { + } else if (isModelOrNonModelOrFieldType === 'model') { let result: Record = {}; if (!nested) { throw Error( - `${fieldName} must declare a wildcard (*) or a field of model ${relatedModel}` + `${fieldName} must declare a wildcard (*) or a field of model ${relatedModel}`, ); } if (nested === SELECTION_SET_WILDCARD) { - const relatedModelDefinition = modelInstrospection.models[relatedModel]; + const relatedModelDefinition = modelIntrospection.models[relatedModel]; result = { [fieldName]: modelsDefaultSelectionSetIR(relatedModelDefinition), @@ -455,7 +471,7 @@ export function customSelectionSetToIR( }; } - if (modelFields[fieldName]?.isArray) { + if (modelOrNonModelFields[fieldName]?.isArray) { result = { [fieldName]: { items: result[fieldName], @@ -465,25 +481,26 @@ export function customSelectionSetToIR( return result; } else { - const modelField = modelFields?.[fieldName]; + const modelField = modelOrNonModelFields?.[fieldName]; const nonModelDefinition = - modelInstrospection.nonModels[modelOrNonModelName]; + modelIntrospection.nonModels[modelOrNonModelName]; const nonModelField = nonModelDefinition?.fields?.[fieldName]; if (!nonModelDefinition) { - const isOwnerField = - resolveOwnerFields(modelDefinition).includes(fieldName); + const isOwnerField = resolveOwnerFields( + modelOrNonModelDefinition, + ).includes(fieldName); if (!modelField && !isOwnerField) { throw Error( - `${fieldName} is not a field of model ${modelOrNonModelName}` + `${fieldName} is not a field of model ${modelOrNonModelName}`, ); } } else { if (!nonModelField) { throw Error( - `${fieldName} is not a field of custom type ${modelOrNonModelName}` + `${fieldName} is not a field of custom type ${modelOrNonModelName}`, ); } } @@ -518,24 +535,6 @@ const modelsDefaultSelectionSetIR = (relatedModelDefinition: SchemaModel) => { return reduced; }; -const nonModelsDefaultSelectionSetIR = ( - relatedNonModelDefinition: SchemaNonModel -) => { - const defaultSelectionSet = defaultSelectionSetForNonModel( - relatedNonModelDefinition - ); - - const reduced = defaultSelectionSet.reduce( - (acc: Record, curVal) => { - acc[curVal] = FIELD_IR; - return acc; - }, - {} - ); - - return reduced; -}; - /** * Stringifies selection set IR * * @example @@ -608,16 +607,16 @@ function deepMergeSelectionSetObjects>( } export function generateSelectionSet( - modelInstrospection: ModelIntrospectionSchema, + modelIntrospection: ModelIntrospectionSchema, modelName: string, selectionSet?: string[], ) { - const modelDefinition = modelInstrospection.models[modelName]; + const modelDefinition = modelIntrospection.models[modelName]; const selSetIr = customSelectionSetToIR( - modelInstrospection, + modelIntrospection, modelName, - selectionSet ?? defaultSelectionSetForModel(modelDefinition) + selectionSet ?? defaultSelectionSetForModel(modelDefinition), ); const selSetString = selectionSetIRToString(selSetIr); @@ -625,13 +624,13 @@ export function generateSelectionSet( } export function generateGraphQLDocument( - modelInstrospection: ModelIntrospectionSchema, + modelIntrospection: ModelIntrospectionSchema, modelName: string, modelOperation: ModelOperation, listArgs?: ListArgs | QueryArgs, indexMeta?: IndexMeta, ): string { - const modelDefinition = modelInstrospection.models[modelName]; + const modelDefinition = modelIntrospection.models[modelName]; const { name, @@ -678,7 +677,7 @@ export function generateGraphQLDocument( let graphQLArguments: Record | undefined; const selectionSetFields = generateSelectionSet( - modelInstrospection, + modelIntrospection, modelName, selectionSet as ListArgs['selectionSet'], ); @@ -955,7 +954,7 @@ export function normalizeMutationInput( * as a fallback. * * @param client Configured client from `generateClient` - * @param options Args/Options obect from call site. + * @param options Args/Options object from call site. * @returns */ export function authModeParams( diff --git a/packages/api-rest/src/apis/index.ts b/packages/api-rest/src/apis/index.ts index 57b9dbd310f..820e6f35bb2 100644 --- a/packages/api-rest/src/apis/index.ts +++ b/packages/api-rest/src/apis/index.ts @@ -59,7 +59,7 @@ import { * cancel(message); * try { * await response; - * } cache (e) { + * } catch (e) { * if (isCancelError(e)) { * // handle request cancellation * } @@ -100,7 +100,7 @@ export const get = (input: GetInput): GetOperation => commonGet(Amplify, input); * cancel(message); * try { * await response; - * } cache (e) { + * } catch (e) { * if (isCancelError(e)) { * // handle request cancellation * } @@ -141,7 +141,7 @@ export const post = (input: PostInput): PostOperation => * cancel(message); * try { * await response; - * } cache (e) { + * } catch (e) { * if (isCancelError(e)) { * // handle request cancellation * } @@ -229,7 +229,7 @@ export const head = (input: HeadInput): HeadOperation => * cancel(message); * try { * await response; - * } cache (e) { + * } catch (e) { * if (isCancelError(e)) { * // handle request cancellation * } diff --git a/packages/auth/package.json b/packages/auth/package.json index c9832be5d09..443aa41d80b 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -25,7 +25,8 @@ "clean": "npm run clean:size && rimraf lib-esm lib dist", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", - "lint": "tslint '{src}/**/*.ts' && npm run ts-coverage", + "lint": "eslint '**/*.{ts,tsx}' && npm run ts-coverage", + "lint:fix": "eslint '**/*.{ts,tsx}' --fix", "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 91.18" }, "typesVersions": { diff --git a/packages/auth/src/Errors.ts b/packages/auth/src/Errors.ts index 22b88d09db3..a64da33a0fb 100644 --- a/packages/auth/src/Errors.ts +++ b/packages/auth/src/Errors.ts @@ -3,8 +3,9 @@ // TODO: delete this module when the Auth class is removed. -import { AuthErrorMessages, AuthErrorTypes } from './types/Auth'; import { ConsoleLogger } from '@aws-amplify/core'; + +import { AuthErrorMessages, AuthErrorTypes } from './types/Auth'; import { AuthErrorStrings } from './common/AuthErrorStrings'; const logger = new ConsoleLogger('AuthError'); diff --git a/packages/auth/src/common/AuthErrorStrings.ts b/packages/auth/src/common/AuthErrorStrings.ts index 200ed2d6520..c05e4d7bf4c 100644 --- a/packages/auth/src/common/AuthErrorStrings.ts +++ b/packages/auth/src/common/AuthErrorStrings.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { AmplifyErrorMap } from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../errors/types/validation'; export const validationErrorMap: AmplifyErrorMap = { diff --git a/packages/auth/src/errors/constants.ts b/packages/auth/src/errors/constants.ts index 30fab5cb4ff..18ae41d71a6 100644 --- a/packages/auth/src/errors/constants.ts +++ b/packages/auth/src/errors/constants.ts @@ -26,4 +26,5 @@ export const invalidOriginException = new AuthError({ }); export const OAUTH_SIGNOUT_EXCEPTION = 'OAuthSignOutException'; export const TOKEN_REFRESH_EXCEPTION = 'TokenRefreshException'; -export const UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION = 'UnexpectedSignInInterruptionException'; +export const UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION = + 'UnexpectedSignInInterruptionException'; diff --git a/packages/auth/src/errors/utils/assertServiceError.ts b/packages/auth/src/errors/utils/assertServiceError.ts index 9d32c43d3de..8f69e5ef82b 100644 --- a/packages/auth/src/errors/utils/assertServiceError.ts +++ b/packages/auth/src/errors/utils/assertServiceError.ts @@ -1,12 +1,13 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { AuthError } from '../AuthError'; import { AmplifyErrorCode, ServiceError, } from '@aws-amplify/core/internals/utils'; +import { AuthError } from '../AuthError'; + export function assertServiceError( error: unknown, ): asserts error is ServiceError { diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index cd9c90280a0..799492edb39 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -77,6 +77,8 @@ export { AuthError } from './errors/AuthError'; export { fetchAuthSession, + FetchAuthSessionOptions, + AuthSession, decodeJWT, CredentialsAndIdentityIdProvider, GetCredentialsOptions, diff --git a/packages/auth/src/providers/cognito/apis/autoSignIn.ts b/packages/auth/src/providers/cognito/apis/autoSignIn.ts index 7ee698b3b9c..d10b4a8c820 100644 --- a/packages/auth/src/providers/cognito/apis/autoSignIn.ts +++ b/packages/auth/src/providers/cognito/apis/autoSignIn.ts @@ -97,6 +97,8 @@ const initialAutoSignIn: AutoSignInCallback = * * ``` */ +// TODO(Eslint): can this be refactored not using `let` on exported member? +// eslint-disable-next-line import/no-mutable-exports export let autoSignIn: AutoSignInCallback = initialAutoSignIn; /** diff --git a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts index fa2732515d0..29081093e5c 100644 --- a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts @@ -3,9 +3,10 @@ import { Amplify } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { ConfirmResetPasswordInput } from '../types'; @@ -64,7 +65,7 @@ export async function confirmResetPassword( Password: newPassword, ClientMetadata: metadata, ClientId: authConfig.userPoolClientId, - UserContextData: UserContextData, + UserContextData, }, ); } diff --git a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts index 3738eeec5ec..6aad224af30 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts @@ -1,10 +1,13 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { Amplify } from '@aws-amplify/core'; +import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; + import { - VerifySoftwareTokenException, - RespondToAuthChallengeException, AssociateSoftwareTokenException, + RespondToAuthChallengeException, + VerifySoftwareTokenException, } from '../types/errors'; import { ConfirmSignInInput, ConfirmSignInOutput } from '../types'; import { @@ -23,18 +26,12 @@ import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { AuthErrorCodes } from '../../../common/AuthErrorStrings'; -import { Amplify, Hub } from '@aws-amplify/core'; -import { - AMPLIFY_SYMBOL, - assertTokenProviderConfig, -} from '@aws-amplify/core/internals/utils'; import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; import { ChallengeName, ChallengeParameters, } from '../utils/clients/CognitoIdentityProvider/types'; import { tokenOrchestrator } from '../tokenProvider'; -import { getCurrentUser } from './getCurrentUser'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; /** @@ -89,9 +86,9 @@ export async function confirmSignIn( try { const { Session, - ChallengeName, + ChallengeName: handledChallengeName, AuthenticationResult, - ChallengeParameters, + ChallengeParameters: handledChallengeParameters, } = await handleChallengeName( username, challengeName as ChallengeName, @@ -107,7 +104,7 @@ export async function confirmSignIn( setActiveSignInState({ signInSession: Session, username, - challengeName: ChallengeName as ChallengeName, + challengeName: handledChallengeName as ChallengeName, signInDetails, }); @@ -133,8 +130,8 @@ export async function confirmSignIn( } return getSignInResult({ - challengeName: ChallengeName as ChallengeName, - challengeParameters: ChallengeParameters as ChallengeParameters, + challengeName: handledChallengeName as ChallengeName, + challengeParameters: handledChallengeParameters as ChallengeParameters, }); } catch (error) { assertServiceError(error); diff --git a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts index e0fa39b3628..62fdf93a82c 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts @@ -3,10 +3,11 @@ import { Amplify } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, HubInternal, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { ConfirmSignUpInput, ConfirmSignUpOutput } from '../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; @@ -85,7 +86,9 @@ export async function confirmSignUp( !isAutoSignInStarted() || !isAutoSignInUserUsingConfirmSignUp(username) ) { - return resolve(signUpOut); + resolve(signUpOut); + + return; } const stopListener = HubInternal.listen( diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index 4d464388929..951a97f2822 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -3,9 +3,10 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { verifyUserAttribute } from '../utils/clients/CognitoIdentityProvider'; diff --git a/packages/auth/src/providers/cognito/apis/deleteUser.ts b/packages/auth/src/providers/cognito/apis/deleteUser.ts index 361f06c16df..e14bde07f09 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUser.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUser.ts @@ -3,17 +3,19 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { deleteUser as serviceDeleteUser } from '../utils/clients/CognitoIdentityProvider'; import { DeleteUserException } from '../types/errors'; import { tokenOrchestrator } from '../tokenProvider'; -import { signOut } from './signOut'; import { getAuthUserAgentValue } from '../../../utils'; +import { signOut } from './signOut'; + /** * Deletes a user from the user pool while authenticated. * diff --git a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts index 7963dffcdfa..5812b656d60 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts @@ -3,9 +3,10 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { deleteUserAttributes as deleteUserAttributesClient } from '../utils/clients/CognitoIdentityProvider'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; diff --git a/packages/auth/src/providers/cognito/apis/fetchDevices.ts b/packages/auth/src/providers/cognito/apis/fetchDevices.ts index a0d746dddf0..2ac3bddde30 100644 --- a/packages/auth/src/providers/cognito/apis/fetchDevices.ts +++ b/packages/auth/src/providers/cognito/apis/fetchDevices.ts @@ -3,9 +3,10 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { FetchDevicesOutput } from '../types'; import { listDevices } from '../utils/clients/CognitoIdentityProvider'; import { DeviceType } from '../utils/clients/CognitoIdentityProvider/types'; @@ -43,6 +44,7 @@ export async function fetchDevices(): Promise { Limit: MAX_DEVICES, }, ); + return parseDevicesResponse(response.Devices ?? []); } @@ -62,10 +64,12 @@ const parseDevicesResponse = async ( if (Name && Value) { attrs[Name] = Value; } + return attrs; }, {}, ); + return { id, attributes, diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index 104bc401522..ef42d34f72f 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -1,15 +1,16 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { FetchMFAPreferenceOutput } from '../types'; -import { getMFAType, getMFATypes } from '../utils/signInHelpers'; -import { GetUserException } from '../types/errors'; -import { getUser } from '../utils/clients/CognitoIdentityProvider'; import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + +import { FetchMFAPreferenceOutput } from '../types'; +import { getMFAType, getMFATypes } from '../utils/signInHelpers'; +import { GetUserException } from '../types/errors'; +import { getUser } from '../utils/clients/CognitoIdentityProvider'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts index 79ba1e48b8a..0a3673fd6e4 100644 --- a/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; + import { FetchUserAttributesOutput } from '../types'; +import { GetUserException } from '../types/errors'; + import { fetchUserAttributes as fetchUserAttributesInternal } from './internal/fetchUserAttributes'; /** diff --git a/packages/auth/src/providers/cognito/apis/forgetDevice.ts b/packages/auth/src/providers/cognito/apis/forgetDevice.ts index 1e5d634a6f9..66dd3488f7b 100644 --- a/packages/auth/src/providers/cognito/apis/forgetDevice.ts +++ b/packages/auth/src/providers/cognito/apis/forgetDevice.ts @@ -1,13 +1,14 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { forgetDevice as serviceForgetDevice } from '../utils/clients/CognitoIdentityProvider'; import { Amplify, fetchAuthSession } from '@aws-amplify/core'; -import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + +import { forgetDevice as serviceForgetDevice } from '../utils/clients/CognitoIdentityProvider'; +import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { tokenOrchestrator } from '../tokenProvider'; import { ForgetDeviceInput } from '../types'; diff --git a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts index db5a9c30235..2c35937b8ba 100644 --- a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; + import { GetCurrentUserOutput } from '../types'; +import { InitiateAuthException } from '../types/errors'; + import { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentUser'; /** diff --git a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts index 00c6ead5bf3..c1e4e9dd008 100644 --- a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts @@ -7,6 +7,7 @@ import { assertTokenProviderConfig, fetchAuthSession, } from '@aws-amplify/core/internals/utils'; + import { getUser } from '../../utils/clients/CognitoIdentityProvider'; import { getRegion } from '../../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../../utils/types'; diff --git a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts index 8c99395b6b0..350651dd4bf 100644 --- a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts @@ -3,10 +3,11 @@ import { AmplifyClassV6, AuthTokens } from '@aws-amplify/core'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; + import { assertAuthTokens } from '../../utils/types'; import { - CognitoAuthSignInDetails, AuthUser, + CognitoAuthSignInDetails, GetCurrentUserOutput, } from '../../types'; @@ -29,6 +30,7 @@ export const getCurrentUser = async ( if (signInDetails) { authUser.signInDetails = signInDetails; } + return authUser; }; diff --git a/packages/auth/src/providers/cognito/apis/rememberDevice.ts b/packages/auth/src/providers/cognito/apis/rememberDevice.ts index 50abd592329..218b7b533e6 100644 --- a/packages/auth/src/providers/cognito/apis/rememberDevice.ts +++ b/packages/auth/src/providers/cognito/apis/rememberDevice.ts @@ -1,13 +1,14 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { updateDeviceStatus } from '../utils/clients/CognitoIdentityProvider'; import { Amplify, fetchAuthSession } from '@aws-amplify/core'; -import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + +import { updateDeviceStatus } from '../utils/clients/CognitoIdentityProvider'; +import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { tokenOrchestrator } from '../tokenProvider'; import { UpdateDeviceStatusException } from '../../cognito/types/errors'; diff --git a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts index 857fbf630a2..99ef3996f52 100644 --- a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts +++ b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts @@ -3,10 +3,11 @@ import { Amplify } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, AuthVerifiableAttributeKey, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthDeliveryMedium } from '../../../types'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; @@ -15,6 +16,7 @@ import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { resendConfirmationCode } from '../utils/clients/CognitoIdentityProvider'; import { getAuthUserAgentValue } from '../../../utils'; import { getUserContextData } from '../utils/userContextData'; +import { ResendConfirmationException } from '../types/errors'; /** * Resend the confirmation code while signing up @@ -28,7 +30,7 @@ import { getUserContextData } from '../utils/userContextData'; export async function resendSignUpCode( input: ResendSignUpCodeInput, ): Promise { - const username = input.username; + const { username } = input; assertValidationError( !!username, AuthValidationErrorCode.EmptySignUpUsername, @@ -59,6 +61,7 @@ export async function resendSignUpCode( const { DeliveryMedium, AttributeName, Destination } = { ...CodeDeliveryDetails, }; + return { destination: Destination as string, deliveryMedium: DeliveryMedium as AuthDeliveryMedium, diff --git a/packages/auth/src/providers/cognito/apis/resetPassword.ts b/packages/auth/src/providers/cognito/apis/resetPassword.ts index b236e416949..273a77d413d 100644 --- a/packages/auth/src/providers/cognito/apis/resetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/resetPassword.ts @@ -3,10 +3,11 @@ import { Amplify } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, AuthVerifiableAttributeKey, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthDeliveryMedium } from '../../../types'; @@ -31,7 +32,7 @@ import { getUserContextData } from '../utils/userContextData'; export async function resetPassword( input: ResetPasswordInput, ): Promise { - const username = input.username; + const { username } = input; assertValidationError( !!username, AuthValidationErrorCode.EmptyResetPasswordUsername, @@ -60,6 +61,7 @@ export async function resetPassword( }, ); const codeDeliveryDetails = res.CodeDeliveryDetails; + return { isPasswordReset: false, nextStep: { diff --git a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts index 2e8d37e02a1..55e5a8b5a84 100644 --- a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts +++ b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts @@ -3,10 +3,11 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, AuthVerifiableAttributeKey, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthDeliveryMedium } from '../../../types'; import { SendUserAttributeVerificationCodeInput, @@ -51,6 +52,7 @@ export const sendUserAttributeVerificationCode = async ( const { DeliveryMedium, AttributeName, Destination } = { ...CodeDeliveryDetails, }; + return { destination: Destination, deliveryMedium: DeliveryMedium as AuthDeliveryMedium, diff --git a/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts index 4266d34197b..d30db35b787 100644 --- a/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts @@ -5,6 +5,7 @@ import { AmplifyServer, getAmplifyServerContext, } from '@aws-amplify/core/internals/adapter-core'; + import { FetchUserAttributesOutput } from '../../types'; import { fetchUserAttributes as fetchUserAttributesInternal } from '../internal/fetchUserAttributes'; diff --git a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts index 7b2a48f9cf3..ea96605b16e 100644 --- a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts @@ -5,8 +5,10 @@ import { AmplifyServer, getAmplifyServerContext, } from '@aws-amplify/core/internals/adapter-core'; + import { GetCurrentUserOutput } from '../../types'; import { getCurrentUser as getCurrentUserInternal } from '../internal/getCurrentUser'; +import { InitiateAuthException } from '../../types/errors'; /** * Gets the current user from the idToken. diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index f41685551f0..e99b8618995 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -3,13 +3,14 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthError } from '../../../errors/AuthError'; import { - SETUP_TOTP_EXCEPTION, AssociateSoftwareTokenException, + SETUP_TOTP_EXCEPTION, } from '../types/errors'; import { SetUpTOTPOutput } from '../types'; import { getTOTPSetupDetails } from '../utils/signInHelpers'; @@ -49,5 +50,6 @@ export async function setUpTOTP(): Promise { message: 'Failed to set up TOTP.', }); } + return getTOTPSetupDetails(SecretCode, JSON.stringify(username)); } diff --git a/packages/auth/src/providers/cognito/apis/signIn.ts b/packages/auth/src/providers/cognito/apis/signIn.ts index 40a3cc98b49..10a9be79214 100644 --- a/packages/auth/src/providers/cognito/apis/signIn.ts +++ b/packages/auth/src/providers/cognito/apis/signIn.ts @@ -5,13 +5,15 @@ import { InitiateAuthException, RespondToAuthChallengeException, } from '../types/errors'; +import { assertUserNotAuthenticated } from '../utils/signInHelpers'; +import { SignInInput, SignInOutput } from '../types'; +import { AuthValidationErrorCode } from '../../../errors/types/validation'; + 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 * diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts index 52c0f627393..e55e3f0a50d 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts @@ -1,22 +1,20 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +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 { assertServiceError } from '../../../errors/utils/assertServiceError'; import { - handleCustomAuthFlowWithoutSRP, + getActiveSignInUsername, + getNewDeviceMetatada, getSignInResult, getSignInResultFromError, - getNewDeviceMetatada, + handleCustomAuthFlowWithoutSRP, retryOnResourceNotFoundException, - getActiveSignInUsername, } from '../utils/signInHelpers'; -import { Amplify, Hub } from '@aws-amplify/core'; -import { - AMPLIFY_SYMBOL, - assertTokenProviderConfig, -} from '@aws-amplify/core/internals/utils'; import { InitiateAuthException } from '../types/errors'; import { CognitoAuthSignInDetails, @@ -33,7 +31,6 @@ import { ChallengeParameters, } from '../utils/clients/CognitoIdentityProvider/types'; import { tokenOrchestrator } from '../tokenProvider'; -import { getCurrentUser } from './getCurrentUser'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; /** @@ -68,8 +65,8 @@ export async function signInWithCustomAuth( try { const { - ChallengeName, - ChallengeParameters, + ChallengeName: retriedChallengeName, + ChallengeParameters: retiredChallengeParameters, AuthenticationResult, Session, } = await retryOnResourceNotFoundException( @@ -83,7 +80,7 @@ export async function signInWithCustomAuth( setActiveSignInState({ signInSession: Session, username: activeUsername, - challengeName: ChallengeName as ChallengeName, + challengeName: retriedChallengeName as ChallengeName, signInDetails, }); if (AuthenticationResult) { @@ -109,8 +106,8 @@ export async function signInWithCustomAuth( } return getSignInResult({ - challengeName: ChallengeName as ChallengeName, - challengeParameters: ChallengeParameters as ChallengeParameters, + challengeName: retriedChallengeName as ChallengeName, + challengeParameters: retiredChallengeParameters as ChallengeParameters, }); } catch (error) { cleanActiveSignInState(); diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts index 688c0ed0c35..a67fa9f861c 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts @@ -1,20 +1,18 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify, Hub } from '@aws-amplify/core'; -import { - AMPLIFY_SYMBOL, - assertTokenProviderConfig, -} from '@aws-amplify/core/internals/utils'; +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 { assertServiceError } from '../../../errors/utils/assertServiceError'; import { - handleCustomSRPAuthFlow, + getActiveSignInUsername, + getNewDeviceMetatada, getSignInResult, getSignInResultFromError, - getNewDeviceMetatada, - getActiveSignInUsername, + handleCustomSRPAuthFlow, } from '../utils/signInHelpers'; import { InitiateAuthException, @@ -35,7 +33,6 @@ import { ChallengeParameters, } from '../utils/clients/CognitoIdentityProvider/types'; import { tokenOrchestrator } from '../tokenProvider'; -import { getCurrentUser } from './getCurrentUser'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; /** @@ -71,8 +68,8 @@ export async function signInWithCustomSRPAuth( try { const { - ChallengeName, - ChallengeParameters, + ChallengeName: handledChallengeName, + ChallengeParameters: handledChallengeParameters, AuthenticationResult, Session, } = await handleCustomSRPAuthFlow( @@ -88,7 +85,7 @@ export async function signInWithCustomSRPAuth( setActiveSignInState({ signInSession: Session, username: activeUsername, - challengeName: ChallengeName as ChallengeName, + challengeName: handledChallengeName as ChallengeName, signInDetails, }); if (AuthenticationResult) { @@ -113,8 +110,8 @@ export async function signInWithCustomSRPAuth( } return getSignInResult({ - challengeName: ChallengeName as ChallengeName, - challengeParameters: ChallengeParameters as ChallengeParameters, + challengeName: handledChallengeName as ChallengeName, + challengeParameters: handledChallengeParameters as ChallengeParameters, }); } catch (error) { cleanActiveSignInState(); diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index d0bbaee9137..adfc9dacea9 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -8,20 +8,20 @@ import { assertTokenProviderConfig, urlSafeEncode, } from '@aws-amplify/core/internals/utils'; + import '../utils/oauth/enableOAuthListener'; import { cognitoHostedUIIdentityProviderMap } from '../types/models'; import { getAuthUserAgentValue, openAuthSession } from '../../../utils'; import { assertUserNotAuthenticated } from '../utils/signInHelpers'; import { SignInWithRedirectInput } from '../types'; import { + completeOAuthFlow, generateCodeVerifier, generateState, getRedirectUrl, handleFailure, - completeOAuthFlow, oAuthStore, } from '../utils/oauth'; -import { AuthError } from '../../../errors/AuthError'; import { createOAuthError } from '../utils/oauth/createOAuthError'; /** @@ -74,11 +74,11 @@ const oauthSignIn = async ({ const { domain, redirectSignIn, responseType, scopes } = oauthConfig; const randomState = generateState(); - /* encodeURIComponent is not URL safe, use urlSafeEncode instead. Cognito + /* encodeURIComponent is not URL safe, use urlSafeEncode instead. Cognito single-encodes/decodes url on first sign in and double-encodes/decodes url - when user already signed in. Using encodeURIComponent, Base32, Base64 add - characters % or = which on further encoding becomes unsafe. '=' create issue - for parsing query params. + when user already signed in. Using encodeURIComponent, Base32, Base64 add + characters % or = which on further encoding becomes unsafe. '=' create issue + for parsing query params. Refer: https://github.com/aws-amplify/amplify-js/issues/5218 */ const state = customState ? `${randomState}-${urlSafeEncode(customState)}` @@ -129,9 +129,9 @@ const oauthSignIn = async ({ preferPrivateSession, }); } - } catch (error) { - await handleFailure(error); + } catch (err) { + await handleFailure(err); // rethrow the error so it can be caught by `await signInWithRedirect()` in react-native - throw error; + throw err; } }; diff --git a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts index a29e1716ab9..32f0ca11b99 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts @@ -1,6 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +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 { assertServiceError } from '../../../errors/utils/assertServiceError'; @@ -12,11 +15,6 @@ import { InitiateAuthException, RespondToAuthChallengeException, } from '../types/errors'; -import { Amplify, Hub } from '@aws-amplify/core'; -import { - AMPLIFY_SYMBOL, - assertTokenProviderConfig, -} from '@aws-amplify/core/internals/utils'; import { getActiveSignInUsername, getNewDeviceMetatada, @@ -30,12 +28,11 @@ import { SignInWithSRPOutput, } from '../types'; import { - setActiveSignInState, cleanActiveSignInState, + setActiveSignInState, } from '../utils/signInStore'; import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; import { tokenOrchestrator } from '../tokenProvider'; -import { getCurrentUser } from './getCurrentUser'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; /** @@ -71,8 +68,8 @@ export async function signInWithSRP( try { const { - ChallengeName, - ChallengeParameters, + ChallengeName: handledChallengeName, + ChallengeParameters: handledChallengeParameters, AuthenticationResult, Session, } = await handleUserSRPAuthFlow( @@ -88,7 +85,7 @@ export async function signInWithSRP( setActiveSignInState({ signInSession: Session, username: activeUsername, - challengeName: ChallengeName as ChallengeName, + challengeName: handledChallengeName as ChallengeName, signInDetails, }); if (AuthenticationResult) { @@ -113,8 +110,8 @@ export async function signInWithSRP( } return getSignInResult({ - challengeName: ChallengeName as ChallengeName, - challengeParameters: ChallengeParameters as ChallengeParameters, + challengeName: handledChallengeName as ChallengeName, + challengeParameters: handledChallengeParameters as ChallengeParameters, }); } catch (error) { cleanActiveSignInState(); diff --git a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts index d4702e46633..e1de730cb1c 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts @@ -1,6 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { Amplify } from '@aws-amplify/core'; +import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertServiceError } from '../../../errors/utils/assertServiceError'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; @@ -16,11 +19,6 @@ import { handleUserPasswordAuthFlow, retryOnResourceNotFoundException, } from '../utils/signInHelpers'; -import { Amplify, Hub } from '@aws-amplify/core'; -import { - AMPLIFY_SYMBOL, - assertTokenProviderConfig, -} from '@aws-amplify/core/internals/utils'; import { InitiateAuthException } from '../types/errors'; import { CognitoAuthSignInDetails, @@ -33,7 +31,6 @@ import { } from '../utils/signInStore'; import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; import { tokenOrchestrator } from '../tokenProvider'; -import { getCurrentUser } from './getCurrentUser'; import { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent'; /** @@ -68,8 +65,8 @@ export async function signInWithUserPassword( try { const { - ChallengeName, - ChallengeParameters, + ChallengeName: retiredChallengeName, + ChallengeParameters: retriedChallengeParameters, AuthenticationResult, Session, } = await retryOnResourceNotFoundException( @@ -83,7 +80,7 @@ export async function signInWithUserPassword( setActiveSignInState({ signInSession: Session, username: activeUsername, - challengeName: ChallengeName as ChallengeName, + challengeName: retiredChallengeName as ChallengeName, signInDetails, }); if (AuthenticationResult) { @@ -108,8 +105,8 @@ export async function signInWithUserPassword( } return getSignInResult({ - challengeName: ChallengeName as ChallengeName, - challengeParameters: ChallengeParameters as ChallengeParameters, + challengeName: retiredChallengeName as ChallengeName, + challengeParameters: retriedChallengeParameters as ChallengeParameters, }); } catch (error) { cleanActiveSignInState(); diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index 59fde5dcca2..65be0162927 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -3,23 +3,23 @@ import { Amplify, - clearCredentials, CognitoUserPoolConfig, ConsoleLogger, - defaultStorage, Hub, + clearCredentials, + defaultStorage, } from '@aws-amplify/core'; - -import { getAuthUserAgentValue } from '../../../utils'; -import { SignOutInput } from '../types'; -import { tokenOrchestrator } from '../tokenProvider'; import { - AuthAction, AMPLIFY_SYMBOL, + AuthAction, + JWT, assertOAuthConfig, assertTokenProviderConfig, - JWT, } from '@aws-amplify/core/internals/utils'; + +import { getAuthUserAgentValue } from '../../../utils'; +import { SignOutInput } from '../types'; +import { tokenOrchestrator } from '../tokenProvider'; import { globalSignOut as globalSignOutClient, revokeToken, diff --git a/packages/auth/src/providers/cognito/apis/signUp.ts b/packages/auth/src/providers/cognito/apis/signUp.ts index 4d41baeb170..aff6ac83028 100644 --- a/packages/auth/src/providers/cognito/apis/signUp.ts +++ b/packages/auth/src/providers/cognito/apis/signUp.ts @@ -3,12 +3,13 @@ import { Amplify } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, AuthVerifiableAttributeKey, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthDeliveryMedium } from '../../../types'; -import { SignUpInput, SignUpOutput, SignInInput } from '../types'; +import { SignInInput, SignUpInput, SignUpOutput } from '../types'; import { signUp as signUpClient } from '../utils/clients/CognitoIdentityProvider'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; @@ -16,17 +17,18 @@ import { SignUpException } from '../types/errors'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { toAttributeType } from '../utils/apiHelpers'; import { + autoSignInUserConfirmed, + autoSignInWhenUserIsConfirmedWithLink, handleCodeAutoSignIn, isAutoSignInStarted, - setAutoSignInStarted, isSignUpComplete, - autoSignInUserConfirmed, - autoSignInWhenUserIsConfirmedWithLink, + setAutoSignInStarted, setUsernameUsedForAutoSignIn, } from '../utils/signUpHelpers'; -import { setAutoSignIn } from './autoSignIn'; import { getAuthUserAgentValue } from '../../../utils'; +import { setAutoSignIn } from './autoSignIn'; + /** * Creates a user * @@ -63,7 +65,7 @@ export async function signUp(input: SignUpInput): Promise { // if the authFlowType is 'CUSTOM_WITHOUT_SRP' then we don't include the password if (signInServiceOptions?.authFlowType !== 'CUSTOM_WITHOUT_SRP') { - signInInput['password'] = password; + signInInput.password = password; } if (signInServiceOptions || autoSignIn === true) { setUsernameUsedForAutoSignIn(username); @@ -88,6 +90,7 @@ export async function signUp(input: SignUpInput): Promise { if (isSignUpComplete(clientOutput) && isAutoSignInStarted()) { setAutoSignIn(autoSignInUserConfirmed(signInInput)); + return { isSignUpComplete: true, nextStep: { @@ -113,6 +116,7 @@ export async function signUp(input: SignUpInput): Promise { signUpVerificationMethod === 'link' ) { setAutoSignIn(autoSignInWhenUserIsConfirmedWithLink(signInInput)); + return { isSignUpComplete: false, nextStep: { diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index 1a37e7cd75e..790cc82f8bd 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -3,9 +3,10 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { UpdateMFAPreferenceInput } from '../types'; import { SetUserMFAPreferenceException } from '../types/errors'; import { MFAPreference } from '../types/models'; diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index 33ab12c4eba..0f83fc9f1df 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -1,16 +1,17 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + AuthAction, + assertTokenProviderConfig, +} from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { UpdatePasswordInput } from '../types'; import { changePassword } from '../utils/clients/CognitoIdentityProvider'; import { ChangePasswordException } from '../../cognito/types/errors'; -import { Amplify, fetchAuthSession } from '@aws-amplify/core'; -import { - assertTokenProviderConfig, - AuthAction, -} from '@aws-amplify/core/internals/utils'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts b/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts index 094fa308297..242eb7dfe7c 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts @@ -3,6 +3,7 @@ import { UpdateUserAttributeInput, UpdateUserAttributeOutput } from '../types'; import { UpdateUserAttributesException } from '../types/errors'; + import { updateUserAttributes } from './updateUserAttributes'; /** @@ -24,5 +25,6 @@ export const updateUserAttribute = async ( userAttributes: { [attributeKey]: value }, options, }); + return Object.values(output)[0]; }; diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index d2fcd2b5b45..b0e6cc7f3f7 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -3,13 +3,14 @@ import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { - assertTokenProviderConfig, AuthAction, + assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + import { - AuthUserAttributes, - AuthUpdateUserAttributesOutput, AuthDeliveryMedium, + AuthUpdateUserAttributesOutput, + AuthUserAttributes, } from '../../../types'; import { UpdateUserAttributesInput, @@ -93,5 +94,6 @@ function getUnConfirmedAttributes( }, }; }); + return unConfirmedAttributes; } diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index 678c758fa14..66c68fe9690 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -1,16 +1,17 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + AuthAction, + assertTokenProviderConfig, +} from '@aws-amplify/core/internals/utils'; + import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { VerifyTOTPSetupInput } from '../types'; import { verifySoftwareToken } from '../utils/clients/CognitoIdentityProvider'; import { VerifySoftwareTokenException } from '../types/errors'; -import { Amplify, fetchAuthSession } from '@aws-amplify/core'; -import { - assertTokenProviderConfig, - AuthAction, -} from '@aws-amplify/core/internals/utils'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts index 2a46ce98d8f..32fbaeb1369 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts @@ -1,12 +1,14 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { AuthTokens, getId, ConsoleLogger } from '@aws-amplify/core'; +import { AuthTokens, ConsoleLogger, Identity, getId } from '@aws-amplify/core'; import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils'; + import { AuthError } from '../../../errors/AuthError'; -import { IdentityIdStore } from './types'; import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; -import { Identity } from '@aws-amplify/core'; +import { GetIdException } from '../types/errors'; + +import { IdentityIdStore } from './types'; import { formLoginsMap } from './utils'; const logger = new ConsoleLogger('CognitoIdentityIdProvider'); @@ -16,9 +18,9 @@ const logger = new ConsoleLogger('CognitoIdentityIdProvider'); * * @param tokens - The AuthTokens received after SignIn * @returns string - * @throws configuration excpetions: {@link InvalidIdentityPoolIdException } + * @throws configuration exceptions: {@link InvalidIdentityPoolIdException } * - Auth errors that may arise from misconfiguration. - * @throws service excpetions: {@link GetIdException } + * @throws service exceptions: {@link GetIdException } */ export async function cognitoIdentityIdProvider({ tokens, @@ -70,11 +72,12 @@ export async function cognitoIdentityIdProvider({ // Store in-memory or local storage depending on guest or primary identityId identityIdStore.storeIdentityId(identityId); + return identityId.id; } async function generateIdentityId( - logins: {}, + logins: Record, authConfig: CognitoIdentityPoolConfig, ): Promise { const identityPoolId = authConfig?.identityPoolId; @@ -103,5 +106,6 @@ async function generateIdentityId( 'Make sure to pass a valid identityPoolId in the configuration.', }); } + return idResult; } diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts index 732729ffc1c..ec4bc9ef6b4 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts @@ -8,10 +8,12 @@ import { KeyValueStorageInterface, } from '@aws-amplify/core'; import { assertIdentityPoolIdConfig } from '@aws-amplify/core/internals/utils'; -import { IdentityIdStorageKeys, IdentityIdStore } from './types'; + import { getAuthStorageKeys } from '../tokenProvider/TokenStore'; import { AuthKeys } from '../tokenProvider/types'; +import { IdentityIdStorageKeys, IdentityIdStore } from './types'; + const logger = new ConsoleLogger('DefaultIdentityIdStore'); export class DefaultIdentityIdStore implements IdentityIdStore { @@ -28,7 +30,6 @@ export class DefaultIdentityIdStore implements IdentityIdStore { 'Cognito', authConfigParam.Cognito.identityPoolId, ); - return; } constructor(keyValueStorage: KeyValueStorageInterface) { @@ -38,7 +39,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { async loadIdentityId(): Promise { assertIdentityPoolIdConfig(this.authConfig?.Cognito); try { - if (!!this._primaryIdentityId) { + if (this._primaryIdentityId) { return { id: this._primaryIdentityId, type: 'primary', @@ -47,16 +48,18 @@ export class DefaultIdentityIdStore implements IdentityIdStore { const storedIdentityId = await this.keyValueStorage.getItem( this._authKeys.identityId, ); - if (!!storedIdentityId) { + if (storedIdentityId) { return { id: storedIdentityId, type: 'guest', }; } + return null; } } catch (err) { logger.log('Error getting stored IdentityId.', err); + return null; } } diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index 0b5fbc7ce1a..fd02d349513 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -1,24 +1,25 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { cognitoIdentityIdProvider } from './IdentityIdProvider'; import { AuthTokens, - CredentialsAndIdentityIdProvider, + ConsoleLogger, CredentialsAndIdentityId, - getCredentialsForIdentity, + CredentialsAndIdentityIdProvider, GetCredentialsOptions, - ConsoleLogger, + getCredentialsForIdentity, } from '@aws-amplify/core'; import { - assertIdentityPoolIdConfig, - decodeJWT, CognitoIdentityPoolConfig, + assertIdentityPoolIdConfig, } from '@aws-amplify/core/internals/utils'; + import { AuthError } from '../../../errors/AuthError'; -import { IdentityIdStore } from './types'; import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertIdTokenInAuthTokens } from '../utils/types'; + +import { IdentityIdStore } from './types'; +import { cognitoIdentityIdProvider } from './IdentityIdProvider'; import { formLoginsMap } from './utils'; const logger = new ConsoleLogger('CognitoCredentialsProvider'); @@ -36,7 +37,8 @@ export class CognitoAWSCredentialsAndIdentityIdProvider isAuthenticatedCreds: boolean; associatedIdToken?: string; }; - private _nextCredentialsRefresh: number = 0; + + private _nextCredentialsRefresh = 0; async clearCredentialsAndIdentityId(): Promise { logger.debug('Clearing out credentials and identityId'); @@ -53,8 +55,8 @@ export class CognitoAWSCredentialsAndIdentityIdProvider getCredentialsOptions: GetCredentialsOptions, ): Promise { const isAuthenticated = getCredentialsOptions.authenticated; - const tokens = getCredentialsOptions.tokens; - const authConfig = getCredentialsOptions.authConfig; + const { tokens } = getCredentialsOptions; + const { authConfig } = getCredentialsOptions; try { assertIdentityPoolIdConfig(authConfig?.Cognito); } catch { @@ -67,7 +69,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider return; } - const forceRefresh = getCredentialsOptions.forceRefresh; + const { forceRefresh } = getCredentialsOptions; const tokenHasChanged = this.hasTokenChanged(tokens); const identityId = await cognitoIdentityIdProvider({ tokens, @@ -83,6 +85,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider return this.getGuestCredentials(identityId, authConfig.Cognito); } else { assertIdTokenInAuthTokens(tokens); + return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId); } } @@ -100,6 +103,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider logger.info( 'returning stored credentials as they neither past TTL nor expired.', ); + return this._credentialsAndIdentityId; } @@ -169,6 +173,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider logger.debug( 'returning stored credentials as they neither past TTL nor expired.', ); + return this._credentialsAndIdentityId; } @@ -219,6 +224,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider type: 'primary', }); } + return res; } else { throw new AuthError({ @@ -233,6 +239,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider ? true : this._nextCredentialsRefresh <= Date.now(); } + private hasTokenChanged(tokens?: AuthTokens): boolean { return ( !!tokens && diff --git a/packages/auth/src/providers/cognito/credentialsProvider/index.ts b/packages/auth/src/providers/cognito/credentialsProvider/index.ts index db51be1a3f1..389c08bcf4d 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/index.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/index.ts @@ -1,9 +1,15 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { defaultStorage } from '@aws-amplify/core'; + +import { + GetCredentialsForIdentityException, + GetIdException, +} from '../types/errors'; + import { DefaultIdentityIdStore } from './IdentityIdStore'; import { CognitoAWSCredentialsAndIdentityIdProvider } from './credentialsProvider'; -import { defaultStorage } from '@aws-amplify/core'; /** * Cognito specific implmentation of the CredentialsProvider interface diff --git a/packages/auth/src/providers/cognito/credentialsProvider/utils.ts b/packages/auth/src/providers/cognito/credentialsProvider/utils.ts index f0b5e15cb7c..c5113e7ceb2 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/utils.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/utils.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { decodeJWT } from '@aws-amplify/core/internals/utils'; + import { AuthError } from '../../../errors/AuthError'; export function formLoginsMap(idToken: string) { @@ -13,8 +14,9 @@ export function formLoginsMap(idToken: string) { message: 'Invalid Idtoken.', }); } - let domainName: string = issuer.replace(/(^\w+:|^)\/\//, ''); + const domainName: string = issuer.replace(/(^\w+:|^)\/\//, ''); res[domainName] = idToken; + return res; } diff --git a/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts b/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts index 345877857a5..8a561e342f9 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts @@ -8,7 +8,9 @@ import { KeyValueStorageInterface, defaultStorage, } from '@aws-amplify/core'; + import { refreshAuthTokens } from '../utils/refreshAuthTokens'; + import { DefaultTokenStore } from './TokenStore'; import { TokenOrchestrator } from './TokenOrchestrator'; import { CognitoUserPoolTokenProviderType } from './types'; @@ -25,6 +27,7 @@ export class CognitoUserPoolsTokenProvider this.tokenOrchestrator.setAuthTokenStore(this.authTokenStore); this.tokenOrchestrator.setTokenRefresher(refreshAuthTokens); } + getTokens( { forceRefresh }: FetchAuthSessionOptions = { forceRefresh: false }, ): Promise { @@ -34,9 +37,11 @@ export class CognitoUserPoolsTokenProvider setKeyValueStorage(keyValueStorage: KeyValueStorageInterface): void { this.authTokenStore.setKeyValueStorage(keyValueStorage); } + setWaitForInflightOAuth(waitForInflightOAuth: () => Promise): void { this.tokenOrchestrator.setWaitForInflightOAuth(waitForInflightOAuth); } + setAuthConfig(authConfig: AuthConfig) { this.authTokenStore.setAuthConfig(authConfig); this.tokenOrchestrator.setAuthConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts b/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts index 073843b036c..83383b5f2d2 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts @@ -1,9 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { + AuthConfig, AuthTokens, FetchAuthSessionOptions, - AuthConfig, Hub, } from '@aws-amplify/core'; import { @@ -11,6 +11,11 @@ import { assertTokenProviderConfig, isTokenExpired, } from '@aws-amplify/core/internals/utils'; + +import { assertServiceError } from '../../../errors/utils/assertServiceError'; +import { AuthError } from '../../../errors/AuthError'; +import { CognitoAuthSignInDetails } from '../types'; + import { AuthTokenOrchestrator, AuthTokenStore, @@ -18,25 +23,27 @@ import { DeviceMetadata, TokenRefresher, } from './types'; -import { assertServiceError } from '../../../errors/utils/assertServiceError'; -import { AuthError } from '../../../errors/AuthError'; -import { CognitoAuthSignInDetails } from '../types'; export class TokenOrchestrator implements AuthTokenOrchestrator { private authConfig?: AuthConfig; tokenStore?: AuthTokenStore; tokenRefresher?: TokenRefresher; - waitForInflightOAuth: () => Promise = async () => {}; + waitForInflightOAuth: () => Promise = async () => { + // no-op + }; setAuthConfig(authConfig: AuthConfig) { this.authConfig = authConfig; } + setTokenRefresher(tokenRefresher: TokenRefresher) { this.tokenRefresher = tokenRefresher; } + setAuthTokenStore(tokenStore: AuthTokenStore) { this.tokenStore = tokenStore; } + setWaitForInflightOAuth(waitForInflightOAuth: () => Promise) { this.waitForInflightOAuth = waitForInflightOAuth; } @@ -48,6 +55,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { message: 'TokenStore not set', }); } + return this.tokenStore; } @@ -58,6 +66,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { message: 'TokenRefresher not set', }); } + return this.tokenRefresher; } @@ -154,6 +163,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { } throw err; } + async setTokens({ tokens }: { tokens: CognitoAuthTokens }) { return this.getTokenStore().storeTokens(tokens); } @@ -165,6 +175,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { getDeviceMetadata(username?: string): Promise { return this.getTokenStore().getDeviceMetadata(username); } + clearDeviceMetadata(username?: string): Promise { return this.getTokenStore().clearDeviceMetadata(username); } diff --git a/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts b/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts index 6eac198ed02..0f3d502f8e6 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts @@ -5,6 +5,9 @@ import { assertTokenProviderConfig, decodeJWT, } from '@aws-amplify/core/internals/utils'; + +import { AuthError } from '../../../errors/AuthError'; + import { AuthKeys, AuthTokenStorageKeys, @@ -12,8 +15,7 @@ import { CognitoAuthTokens, DeviceMetadata, } from './types'; -import { AuthError } from '../../../errors/AuthError'; -import { assert, TokenProviderErrorCode } from './errorHelpers'; +import { TokenProviderErrorCode, assert } from './errorHelpers'; export class DefaultTokenStore implements AuthTokenStore { private authConfig?: AuthConfig; @@ -26,11 +28,14 @@ export class DefaultTokenStore implements AuthTokenStore { message: 'KeyValueStorage was not found in TokenStore', }); } + return this.keyValueStorage; } + setKeyValueStorage(keyValueStorage: KeyValueStorageInterface) { this.keyValueStorage = keyValueStorage; } + setAuthConfig(authConfig: AuthConfig) { this.authConfig = authConfig; } @@ -80,11 +85,13 @@ export class DefaultTokenStore implements AuthTokenStore { if (signInDetails) { tokens.signInDetails = JSON.parse(signInDetails); } + return tokens; } catch (err) { return null; } } + async storeTokens(tokens: CognitoAuthTokens): Promise { assert(tokens !== undefined, TokenProviderErrorCode.InvalidAuthTokens); await this.clearTokens(); @@ -100,21 +107,21 @@ export class DefaultTokenStore implements AuthTokenStore { tokens.accessToken.toString(), ); - if (!!tokens.idToken) { + if (tokens.idToken) { await this.getKeyValueStorage().setItem( authKeys.idToken, tokens.idToken.toString(), ); } - if (!!tokens.refreshToken) { + if (tokens.refreshToken) { await this.getKeyValueStorage().setItem( authKeys.refreshToken, tokens.refreshToken, ); } - if (!!tokens.deviceMetadata) { + if (tokens.deviceMetadata) { if (tokens.deviceMetadata.deviceKey) { await this.getKeyValueStorage().setItem( authKeys.deviceKey, @@ -133,7 +140,7 @@ export class DefaultTokenStore implements AuthTokenStore { tokens.deviceMetadata.randomPassword, ); } - if (!!tokens.signInDetails) { + if (tokens.signInDetails) { await this.getKeyValueStorage().setItem( authKeys.signInDetails, JSON.stringify(tokens.signInDetails), @@ -171,7 +178,7 @@ export class DefaultTokenStore implements AuthTokenStore { authKeys.randomPasswordKey, ); - return !!randomPassword + return randomPassword ? { deviceKey: deviceKey ?? undefined, deviceGroupKey: deviceGroupKey ?? undefined, @@ -179,6 +186,7 @@ export class DefaultTokenStore implements AuthTokenStore { } : null; } + async clearDeviceMetadata(username?: string): Promise { const authKeys = await this.getAuthKeys(username); await Promise.all([ @@ -193,6 +201,7 @@ export class DefaultTokenStore implements AuthTokenStore { ): Promise> { assertTokenProviderConfig(this.authConfig?.Cognito); const lastAuthUser = username ?? (await this.getLastAuthUser()); + return createKeysForAuthStorage( this.name, `${this.authConfig.Cognito.userPoolClientId}.${lastAuthUser}`, @@ -202,6 +211,7 @@ export class DefaultTokenStore implements AuthTokenStore { private getLastAuthUserKey() { assertTokenProviderConfig(this.authConfig?.Cognito); const identifier = this.authConfig.Cognito.userPoolClientId; + return `${this.name}.${identifier}.LastAuthUser`; } @@ -225,6 +235,7 @@ export function getAuthStorageKeys>( authKeys: T, ) { const keys = Object.values({ ...authKeys }); + return (prefix: string, identifier: string) => keys.reduce( (acc, authKey) => ({ diff --git a/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts b/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts index 1d7755861dd..198ec6c4283 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts @@ -1,8 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { AmplifyError, decodeJWT } from '@aws-amplify/core/internals/utils'; + import { CognitoAuthSignInDetails } from '../types'; import { AuthenticationResultType } from '../utils/clients/CognitoIdentityProvider/types'; + import { tokenOrchestrator } from './tokenProvider'; import { CognitoAuthTokens, DeviceMetadata } from './types'; diff --git a/packages/auth/src/providers/cognito/tokenProvider/tokenProvider.ts b/packages/auth/src/providers/cognito/tokenProvider/tokenProvider.ts index 107120988e7..a6d13e84523 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/tokenProvider.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/tokenProvider.ts @@ -11,5 +11,4 @@ import { CognitoUserPoolsTokenProvider } from './CognitoUserPoolsTokenProvider'; export const cognitoUserPoolsTokenProvider = new CognitoUserPoolsTokenProvider(); -export const tokenOrchestrator = - cognitoUserPoolsTokenProvider.tokenOrchestrator; +export const { tokenOrchestrator } = cognitoUserPoolsTokenProvider; diff --git a/packages/auth/src/providers/cognito/tokenProvider/types.ts b/packages/auth/src/providers/cognito/tokenProvider/types.ts index 69478ad5864..f58483a334b 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/types.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/types.ts @@ -7,6 +7,7 @@ import { KeyValueStorageInterface, TokenProvider, } from '@aws-amplify/core'; + import { CognitoAuthSignInDetails } from '../types'; export type TokenRefresher = ({ @@ -48,20 +49,20 @@ export interface AuthTokenStore { export interface AuthTokenOrchestrator { setTokenRefresher(tokenRefresher: TokenRefresher): void; setAuthTokenStore(tokenStore: AuthTokenStore): void; - getTokens: ( + getTokens( options?: FetchAuthSessionOptions, - ) => Promise< + ): Promise< (AuthTokens & { signInDetails?: CognitoAuthSignInDetails }) | null >; - setTokens: ({ tokens }: { tokens: CognitoAuthTokens }) => Promise; - clearTokens: () => Promise; + setTokens({ tokens }: { tokens: CognitoAuthTokens }): Promise; + clearTokens(): Promise; getDeviceMetadata(username?: string): Promise; clearDeviceMetadata(username?: string): Promise; } export interface CognitoUserPoolTokenProviderType extends TokenProvider { - setKeyValueStorage: (keyValueStorage: KeyValueStorageInterface) => void; - setAuthConfig: (authConfig: AuthConfig) => void; + setKeyValueStorage(keyValueStorage: KeyValueStorageInterface): void; + setAuthConfig(authConfig: AuthConfig): void; } export type CognitoAuthTokens = AuthTokens & { @@ -72,8 +73,8 @@ export type CognitoAuthTokens = AuthTokens & { signInDetails?: CognitoAuthSignInDetails; }; -export type DeviceMetadata = { +export interface DeviceMetadata { deviceKey?: string; deviceGroupKey?: string; randomPassword: string; -}; +} diff --git a/packages/auth/src/providers/cognito/types/inputs.ts b/packages/auth/src/providers/cognito/types/inputs.ts index 000d9b444ae..fa7223f71da 100644 --- a/packages/auth/src/providers/cognito/types/inputs.ts +++ b/packages/auth/src/providers/cognito/types/inputs.ts @@ -2,40 +2,41 @@ // SPDX-License-Identifier: Apache-2.0 import { AuthVerifiableAttributeKey } from '@aws-amplify/core/internals/utils'; + import { - MFAPreference, ConfirmResetPasswordOptions, ConfirmSignInOptions, ConfirmSignUpOptions, - UserAttributeKey, - VerifiableUserAttributeKey, + MFAPreference, ResendSignUpCodeOptions, ResetPasswordOptions, + SendUserAttributeVerificationCodeOptions, SignInOptions, SignUpOptions, - UpdateUserAttributesOptions, UpdateUserAttributeOptions, + UpdateUserAttributesOptions, + UserAttributeKey, + VerifiableUserAttributeKey, VerifyTOTPSetupOptions, - SendUserAttributeVerificationCodeOptions, } from '../types'; import { AuthConfirmResetPasswordInput, AuthConfirmSignInInput, AuthConfirmSignUpInput, AuthConfirmUserAttributeInput, + AuthDeleteUserAttributesInput, + AuthForgetDeviceInput, AuthResendSignUpCodeInput, AuthResetPasswordInput, + AuthSendUserAttributeVerificationCodeInput, AuthSignInInput, AuthSignInWithRedirectInput, AuthSignOutInput, AuthSignUpInput, AuthUpdatePasswordInput, - AuthUpdateUserAttributesInput, AuthUpdateUserAttributeInput, + AuthUpdateUserAttributesInput, AuthVerifyTOTPSetupInput, - AuthSendUserAttributeVerificationCodeInput, - AuthDeleteUserAttributesInput, - AuthForgetDeviceInput, } from '../../../types'; /** @@ -114,10 +115,10 @@ export type SignUpInput = AuthSignUpInput>; /** * Input type for Cognito updateMFAPreference API. */ -export type UpdateMFAPreferenceInput = { +export interface UpdateMFAPreferenceInput { sms?: MFAPreference; totp?: MFAPreference; -}; +} /** * Input type for Cognito updatePassword API. diff --git a/packages/auth/src/providers/cognito/types/models.ts b/packages/auth/src/providers/cognito/types/models.ts index ae9dbc90acd..3341d439918 100644 --- a/packages/auth/src/providers/cognito/types/models.ts +++ b/packages/auth/src/providers/cognito/types/models.ts @@ -7,13 +7,13 @@ import { } from '@aws-amplify/core/internals/utils'; import { - AuthUserAttribute, - AuthDevice, AWSAuthUser, AuthCodeDeliveryDetails, + AuthDevice, + AuthUserAttribute, } from '../../../types'; - import { AuthProvider } from '../../../types/inputs'; + import { SignUpOutput } from './outputs'; /** @@ -36,9 +36,7 @@ export const cognitoHostedUIIdentityProviderMap: Record = /** * Arbitrary key/value pairs that may be passed as part of certain Cognito requests */ -export type ClientMetadata = { - [key: string]: string; -}; +export type ClientMetadata = Record; /** * The user attribute types available for Cognito. @@ -54,12 +52,12 @@ export type VerifiableUserAttributeKey = AuthVerifiableAttributeKey; * Cognito custom attribute type */ // TODO(V6): replace by `custom:${string}` once categories that use auth have upgraded TS -export type CustomAttribute = string & {}; +export type CustomAttribute = string & NonNullable; /** * One or more name-value pairs containing the validation data in the request to register a user. */ -export type ValidationData = { [key: string]: string }; +export type ValidationData = Record; /** * Cognito supported MFAPreference values that may be passed as part of the UpdateMFAPreferenceRequest. @@ -91,10 +89,10 @@ export type AWSAuthDevice = AuthDevice & { /** * Holds the sign in details of the user. */ -export type CognitoAuthSignInDetails = { +export interface CognitoAuthSignInDetails { loginId?: string; authFlowType?: AuthFlowType; -}; +} /** * Holds the user information along with the sign in details. diff --git a/packages/auth/src/providers/cognito/types/options.ts b/packages/auth/src/providers/cognito/types/options.ts index 3daeb7b3cba..52b4536297f 100644 --- a/packages/auth/src/providers/cognito/types/options.ts +++ b/packages/auth/src/providers/cognito/types/options.ts @@ -4,10 +4,11 @@ import { AuthServiceOptions, AuthSignUpOptions, - AuthUserAttributes, AuthUserAttributeKey, + AuthUserAttributes, } from '../../../types'; -import { ClientMetadata, AuthFlowType, ValidationData } from './models'; + +import { AuthFlowType, ClientMetadata, ValidationData } from './models'; /** * Options specific to Cognito Confirm Reset Password. diff --git a/packages/auth/src/providers/cognito/types/outputs.ts b/packages/auth/src/providers/cognito/types/outputs.ts index aa6a40c58be..595b9009998 100644 --- a/packages/auth/src/providers/cognito/types/outputs.ts +++ b/packages/auth/src/providers/cognito/types/outputs.ts @@ -2,23 +2,24 @@ // SPDX-License-Identifier: Apache-2.0 import { AuthVerifiableAttributeKey } from '@aws-amplify/core/internals/utils'; + import { - AuthMFAType, - AuthUserAttributes, AuthCodeDeliveryDetails, - AuthTOTPSetupDetails, + AuthMFAType, + AuthResetPasswordOutput, AuthSignInOutput, AuthSignUpOutput, - AuthResetPasswordOutput, - AuthUpdateUserAttributesOutput, + AuthTOTPSetupDetails, AuthUpdateUserAttributeOutput, + AuthUpdateUserAttributesOutput, + AuthUserAttributes, } from '../../../types'; import { AWSAuthDevice, AuthUser, UserAttributeKey } from '../types'; -export type FetchMFAPreferenceOutput = { +export interface FetchMFAPreferenceOutput { enabled?: AuthMFAType[]; preferred?: AuthMFAType; -}; +} /** * Output type for Cognito fetchUserAttributes API. diff --git a/packages/auth/src/providers/cognito/utils/apiHelpers.ts b/packages/auth/src/providers/cognito/utils/apiHelpers.ts index 53a078481a3..5ddd544513c 100644 --- a/packages/auth/src/providers/cognito/utils/apiHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/apiHelpers.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { AuthUserAttributes } from '../../../types'; + import { AttributeType } from './clients/CognitoIdentityProvider/types'; /** @@ -31,5 +32,6 @@ export function toAuthUserAttribute( attributes?.forEach(attribute => { if (attribute.Name) userAttributes[attribute.Name] = attribute.Value; }); + return userAttributes; } diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts index 4e63d1c8b06..cff58009b87 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts @@ -10,14 +10,14 @@ import { HttpResponse, Middleware, getDnsSuffix, - unauthenticatedHandler, - parseJsonError, getRetryDecider, jitteredBackoff, + parseJsonError, + unauthenticatedHandler, } from '@aws-amplify/core/internals/aws-client-utils'; import { - getAmplifyUserAgent, AmplifyUrl, + getAmplifyUserAgent, } from '@aws-amplify/core/internals/utils'; import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers'; @@ -44,12 +44,16 @@ const endpointResolver = ({ region }: EndpointResolverOptions) => { /** * A Cognito Identity-specific middleware that disables caching for all requests. */ -const disableCacheMiddleware: Middleware = - () => (next, context) => - async function disableCacheMiddleware(request) { - request.headers['cache-control'] = 'no-store'; - return next(request); - }; +const disableCacheMiddlewareFactory: Middleware< + HttpRequest, + HttpResponse, + Record +> = () => (next, _) => + async function disableCacheMiddleware(request) { + request.headers['cache-control'] = 'no-store'; + + return next(request); + }; /** * A Cognito Identity-specific transfer handler that does NOT sign requests, and @@ -58,11 +62,11 @@ const disableCacheMiddleware: Middleware = * @internal */ export const cognitoUserPoolTransferHandler = composeTransferHandler< - [Parameters[0]], + [Parameters[0]], HttpRequest, HttpResponse, typeof unauthenticatedHandler ->(unauthenticatedHandler, [disableCacheMiddleware]); +>(unauthenticatedHandler, [disableCacheMiddlewareFactory]); /** * @internal diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts index 037765c2251..4ea8c01b599 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts @@ -1,74 +1,76 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; +import { + Endpoint, + HttpRequest, + HttpResponse, + parseJsonBody, + parseJsonError, +} from '@aws-amplify/core/internals/aws-client-utils'; + +import { assertServiceError } from '../../../../../errors/utils/assertServiceError'; +import { AuthError } from '../../../../../errors/AuthError'; + +import { + buildHttpRpcRequest, + cognitoUserPoolTransferHandler, + defaultConfig, + getSharedHeaders, +} from './base'; import type { - ConfirmForgotPasswordCommandInput as ConfirmForgotPasswordInput, - ConfirmForgotPasswordCommandOutput as ConfirmForgotPasswordOutput, - ForgotPasswordCommandInput as ForgotPasswordInput, - ForgotPasswordCommandOutput as ForgotPasswordOutput, - ResendConfirmationCodeCommandInput as ResendConfirmationCodeInput, - ResendConfirmationCodeCommandOutput as ResendConfirmationCodeOutput, - SignUpCommandInput as SignUpInput, - SignUpCommandOutput as SignUpOutput, - InitiateAuthCommandInput as InitiateAuthInput, - InitiateAuthCommandOutput as InitiateAuthOutput, - RespondToAuthChallengeCommandInput as RespondToAuthChallengeInput, - RespondToAuthChallengeCommandOutput as RespondToAuthChallengeOutput, - ConfirmSignUpCommandOutput as ConfirmSignUpOutput, - ConfirmSignUpCommandInput as ConfirmSignUpInput, - VerifySoftwareTokenCommandInput as VerifySoftwareTokenInput, - VerifySoftwareTokenCommandOutput as VerifySoftwareTokenOutput, AssociateSoftwareTokenCommandInput as AssociateSoftwareTokenInput, AssociateSoftwareTokenCommandOutput as AssociateSoftwareTokenOutput, - SetUserMFAPreferenceCommandInput as SetUserMFAPreferenceInput, - SetUserMFAPreferenceCommandOutput as SetUserMFAPreferenceOutput, - GetUserCommandInput as GetUserInput, - GetUserCommandOutput as GetUserOutput, ChangePasswordCommandInput as ChangePasswordInput, ChangePasswordCommandOutput as ChangePasswordOutput, ConfirmDeviceCommandInput as ConfirmDeviceInput, ConfirmDeviceCommandOutput as ConfirmDeviceOutput, - ForgetDeviceCommandInput as ForgetDeviceInput, - ForgetDeviceCommandOutput as ForgetDeviceOutput, + ConfirmForgotPasswordCommandInput as ConfirmForgotPasswordInput, + ConfirmForgotPasswordCommandOutput as ConfirmForgotPasswordOutput, + ConfirmSignUpCommandInput as ConfirmSignUpInput, + ConfirmSignUpCommandOutput as ConfirmSignUpOutput, + DeleteUserAttributesCommandInput as DeleteUserAttributesInput, + DeleteUserAttributesCommandOutput as DeleteUserAttributesOutput, DeleteUserCommandInput as DeleteUserInput, DeleteUserCommandOutput as DeleteUserOutput, + ForgetDeviceCommandInput as ForgetDeviceInput, + ForgetDeviceCommandOutput as ForgetDeviceOutput, + ForgotPasswordCommandInput as ForgotPasswordInput, + ForgotPasswordCommandOutput as ForgotPasswordOutput, GetUserAttributeVerificationCodeCommandInput as GetUserAttributeVerificationCodeInput, GetUserAttributeVerificationCodeCommandOutput as GetUserAttributeVerificationCodeOutput, + GetUserCommandInput as GetUserInput, + GetUserCommandOutput as GetUserOutput, GlobalSignOutCommandInput as GlobalSignOutInput, GlobalSignOutCommandOutput as GlobalSignOutOutput, + InitiateAuthCommandInput as InitiateAuthInput, + InitiateAuthCommandOutput as InitiateAuthOutput, + ListDevicesCommandInput as ListDevicesInput, + ListDevicesCommandOutput as ListDevicesOutput, + ResendConfirmationCodeCommandInput as ResendConfirmationCodeInput, + ResendConfirmationCodeCommandOutput as ResendConfirmationCodeOutput, + RespondToAuthChallengeCommandInput as RespondToAuthChallengeInput, + RespondToAuthChallengeCommandOutput as RespondToAuthChallengeOutput, + SetUserMFAPreferenceCommandInput as SetUserMFAPreferenceInput, + SetUserMFAPreferenceCommandOutput as SetUserMFAPreferenceOutput, + SignUpCommandInput as SignUpInput, + SignUpCommandOutput as SignUpOutput, + UpdateDeviceStatusCommandInput as UpdateDeviceStatusInput, + UpdateDeviceStatusCommandOutput as UpdateDeviceStatusOutput, UpdateUserAttributesCommandInput as UpdateUserAttributesInput, UpdateUserAttributesCommandOutput as UpdateUserAttributesOutput, + VerifySoftwareTokenCommandInput as VerifySoftwareTokenInput, + VerifySoftwareTokenCommandOutput as VerifySoftwareTokenOutput, VerifyUserAttributeCommandInput as VerifyUserAttributeInput, VerifyUserAttributeCommandOutput as VerifyUserAttributeOutput, - UpdateDeviceStatusCommandInput as UpdateDeviceStatusInput, - UpdateDeviceStatusCommandOutput as UpdateDeviceStatusOutput, - ListDevicesCommandInput as ListDevicesInput, - ListDevicesCommandOutput as ListDevicesOutput, - DeleteUserAttributesCommandInput as DeleteUserAttributesInput, - DeleteUserAttributesCommandOutput as DeleteUserAttributesOutput, } from './types'; -import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers'; -import { - buildHttpRpcRequest, - cognitoUserPoolTransferHandler, - defaultConfig, - getSharedHeaders, -} from './base'; -import { - Endpoint, - HttpRequest, - HttpResponse, - parseJsonBody, - parseJsonError, -} from '@aws-amplify/core/internals/aws-client-utils'; -import { assertServiceError } from '../../../../../errors/utils/assertServiceError'; -import { AuthError } from '../../../../../errors/AuthError'; -type RevokeTokenInput = { +interface RevokeTokenInput { Token: string; ClientId: string; -}; +} -type RevokeTokenOutput = {}; +type RevokeTokenOutput = Record; type ClientOperation = | 'SignUp' @@ -100,6 +102,7 @@ const buildUserPoolSerializer = (input: Input, endpoint: Endpoint): HttpRequest => { const headers = getSharedHeaders(operation); const body = JSON.stringify(input); + return buildHttpRpcRequest(endpoint, headers, body); }; @@ -113,6 +116,7 @@ const buildUserPoolDeserializer = (): (( throw new AuthError({ name: error.name, message: error.message }); } else { const body = await parseJsonBody(response); + return body; } }; diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts index 939fc23ce3d..c08589ad448 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts @@ -3,8 +3,6 @@ // Generated by scripts/dts-bundler/README.md -/* tslint:disable */ - import { MetadataBearer as __MetadataBearer } from '@aws-sdk/types'; export type ChallengeName = @@ -28,14 +26,14 @@ export type ChallengeParameters = { PASSWORD_CLAIM_SIGNATURE?: string; MFAS_CAN_CHOOSE?: string; MFAS_CAN_SETUP?: string; -} & { [Params: string]: unknown }; +} & Record; export type CognitoMFAType = 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; -export type CognitoMFASettings = { +export interface CognitoMFASettings { Enabled?: boolean; PreferredMfa?: boolean; -}; +} declare enum AuthFlowType { ADMIN_NO_SRP_AUTH = 'ADMIN_NO_SRP_AUTH', @@ -411,8 +409,7 @@ export interface AnalyticsMetadataType { */ AnalyticsEndpointId?: string; } -export interface AssociateSoftwareTokenCommandInput - extends AssociateSoftwareTokenRequest {} +export type AssociateSoftwareTokenCommandInput = AssociateSoftwareTokenRequest; export interface AssociateSoftwareTokenCommandOutput extends AssociateSoftwareTokenResponse, __MetadataBearer {} @@ -478,7 +475,7 @@ export interface AuthenticationResultType { */ NewDeviceMetadata?: NewDeviceMetadataType; } -export interface ChangePasswordCommandInput extends ChangePasswordRequest {} +export type ChangePasswordCommandInput = ChangePasswordRequest; export interface ChangePasswordCommandOutput extends ChangePasswordResponse, __MetadataBearer {} @@ -502,7 +499,7 @@ export interface ChangePasswordRequest { /** *

The response from the server to the change password request.

*/ -export interface ChangePasswordResponse {} +export type ChangePasswordResponse = Record; /** *

The code delivery details being returned from the server.

*/ @@ -520,7 +517,7 @@ export interface CodeDeliveryDetailsType { */ AttributeName?: string; } -export interface ConfirmDeviceCommandInput extends ConfirmDeviceRequest {} +export type ConfirmDeviceCommandInput = ConfirmDeviceRequest; export interface ConfirmDeviceCommandOutput extends ConfirmDeviceResponse, __MetadataBearer {} @@ -554,8 +551,7 @@ export interface ConfirmDeviceResponse { */ UserConfirmationNecessary?: boolean; } -export interface ConfirmForgotPasswordCommandInput - extends ConfirmForgotPasswordRequest {} +export type ConfirmForgotPasswordCommandInput = ConfirmForgotPasswordRequest; export interface ConfirmForgotPasswordCommandOutput extends ConfirmForgotPasswordResponse, __MetadataBearer {} @@ -620,15 +616,13 @@ export interface ConfirmForgotPasswordRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

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

*/ -export interface ConfirmForgotPasswordResponse {} -export interface ConfirmSignUpCommandInput extends ConfirmSignUpRequest {} +export type ConfirmForgotPasswordResponse = Record; +export type ConfirmSignUpCommandInput = ConfirmSignUpRequest; export interface ConfirmSignUpCommandOutput extends ConfirmSignUpResponse, __MetadataBearer {} @@ -695,15 +689,13 @@ export interface ConfirmSignUpRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

Represents the response from the server for the registration confirmation.

*/ -export interface ConfirmSignUpResponse {} -export interface DeleteUserCommandInput extends DeleteUserRequest {} +export type ConfirmSignUpResponse = Record; +export type DeleteUserCommandInput = DeleteUserRequest; export interface DeleteUserCommandOutput extends DeleteUserResponse, __MetadataBearer {} @@ -716,7 +708,7 @@ export interface DeleteUserRequest { */ AccessToken: string | undefined; } -export interface DeleteUserResponse {} +export type DeleteUserResponse = Record; /** *

The device verifier against which it is authenticated.

*/ @@ -755,8 +747,8 @@ export interface DeviceType { */ DeviceLastAuthenticatedDate?: number; } -export interface ForgetDeviceCommandInput extends ForgetDeviceRequest {} -export interface ForgetDeviceCommandOutput extends __MetadataBearer {} +export type ForgetDeviceCommandInput = ForgetDeviceRequest; +export type ForgetDeviceCommandOutput = __MetadataBearer; /** *

Represents the request to forget the device.

*/ @@ -770,7 +762,7 @@ export interface ForgetDeviceRequest { */ DeviceKey: string | undefined; } -export interface ForgotPasswordCommandInput extends ForgotPasswordRequest {} +export type ForgotPasswordCommandInput = ForgotPasswordRequest; export interface ForgotPasswordCommandOutput extends ForgotPasswordResponse, __MetadataBearer {} @@ -825,9 +817,7 @@ export interface ForgotPasswordRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

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

@@ -838,8 +828,8 @@ export interface ForgotPasswordResponse { */ CodeDeliveryDetails?: CodeDeliveryDetailsType; } -export interface GetUserAttributeVerificationCodeCommandInput - extends GetUserAttributeVerificationCodeRequest {} +export type GetUserAttributeVerificationCodeCommandInput = + GetUserAttributeVerificationCodeRequest; export interface GetUserAttributeVerificationCodeCommandOutput extends GetUserAttributeVerificationCodeResponse, __MetadataBearer {} @@ -883,9 +873,7 @@ export interface GetUserAttributeVerificationCodeRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

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

@@ -896,7 +884,7 @@ export interface GetUserAttributeVerificationCodeResponse { */ CodeDeliveryDetails?: CodeDeliveryDetailsType; } -export interface GetUserCommandInput extends GetUserRequest {} +export type GetUserCommandInput = GetUserRequest; export interface GetUserCommandOutput extends GetUserResponse, __MetadataBearer {} @@ -937,7 +925,7 @@ export interface GetUserResponse { */ UserMFASettingList?: string[]; } -export interface GlobalSignOutCommandInput extends GlobalSignOutRequest {} +export type GlobalSignOutCommandInput = GlobalSignOutRequest; export interface GlobalSignOutCommandOutput extends GlobalSignOutResponse, __MetadataBearer {} @@ -953,8 +941,8 @@ export interface GlobalSignOutRequest { /** *

The response to the request to sign out all devices.

*/ -export interface GlobalSignOutResponse {} -export interface InitiateAuthCommandInput extends InitiateAuthRequest {} +export type GlobalSignOutResponse = Record; +export type InitiateAuthCommandInput = InitiateAuthRequest; export interface InitiateAuthCommandOutput extends InitiateAuthResponse, __MetadataBearer {} @@ -1021,9 +1009,7 @@ export interface InitiateAuthRequest { * * */ - AuthParameters?: { - [key: string]: string; - }; + AuthParameters?: Record; /** *

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

*

You create custom workflows by assigning Lambda functions to user pool triggers. When you use the InitiateAuth API action, Amazon Cognito invokes the Lambda functions that are specified for various @@ -1082,9 +1068,7 @@ export interface InitiateAuthRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; /** *

The app client ID.

*/ @@ -1156,16 +1140,14 @@ export interface InitiateAuthResponse { * the next call (RespondToAuthChallenge).

*

All challenges require USERNAME and SECRET_HASH (if applicable).

*/ - ChallengeParameters?: { - [key: string]: string; - }; + ChallengeParameters?: Record; /** *

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

*/ AuthenticationResult?: AuthenticationResultType; } -export interface ListDevicesCommandInput extends ListDevicesRequest {} +export type ListDevicesCommandInput = ListDevicesRequest; export interface ListDevicesCommandOutput extends ListDevicesResponse, __MetadataBearer {} @@ -1227,8 +1209,7 @@ export interface NewDeviceMetadataType { */ DeviceGroupKey?: string; } -export interface ResendConfirmationCodeCommandInput - extends ResendConfirmationCodeRequest {} +export type ResendConfirmationCodeCommandInput = ResendConfirmationCodeRequest; export interface ResendConfirmationCodeCommandOutput extends ResendConfirmationCodeResponse, __MetadataBearer {} @@ -1284,9 +1265,7 @@ export interface ResendConfirmationCodeRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

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

@@ -1297,8 +1276,7 @@ export interface ResendConfirmationCodeResponse { */ CodeDeliveryDetails?: CodeDeliveryDetailsType; } -export interface RespondToAuthChallengeCommandInput - extends RespondToAuthChallengeRequest {} +export type RespondToAuthChallengeCommandInput = RespondToAuthChallengeRequest; export interface RespondToAuthChallengeCommandOutput extends RespondToAuthChallengeResponse, __MetadataBearer {} @@ -1363,9 +1341,7 @@ export interface RespondToAuthChallengeRequest { * * */ - ChallengeResponses?: { - [key: string]: string; - }; + ChallengeResponses?: Record; /** *

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

*/ @@ -1401,9 +1377,7 @@ export interface RespondToAuthChallengeRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

The response to respond to the authentication challenge.

@@ -1421,9 +1395,7 @@ export interface RespondToAuthChallengeResponse { /** *

The challenge parameters. For more information, see InitiateAuth.

*/ - ChallengeParameters?: { - [key: string]: string; - }; + ChallengeParameters?: Record; /** *

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

*/ @@ -1445,8 +1417,7 @@ export interface SMSMfaSettingsType { */ PreferredMfa?: boolean; } -export interface SetUserMFAPreferenceCommandInput - extends SetUserMFAPreferenceRequest {} +export type SetUserMFAPreferenceCommandInput = SetUserMFAPreferenceRequest; export interface SetUserMFAPreferenceCommandOutput extends SetUserMFAPreferenceResponse, __MetadataBearer {} @@ -1464,8 +1435,8 @@ export interface SetUserMFAPreferenceRequest { */ AccessToken: string | undefined; } -export interface SetUserMFAPreferenceResponse {} -export interface SignUpCommandInput extends SignUpRequest {} +export type SetUserMFAPreferenceResponse = Record; +export type SignUpCommandInput = SignUpRequest; export interface SignUpCommandOutput extends SignUpResponse, __MetadataBearer {} /** *

Represents the request to register a user.

@@ -1532,9 +1503,7 @@ export interface SignUpRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

The response from the server for a registration request.

@@ -1569,8 +1538,7 @@ export interface SoftwareTokenMfaSettingsType { */ PreferredMfa?: boolean; } -export interface UpdateDeviceStatusCommandInput - extends UpdateDeviceStatusRequest {} +export type UpdateDeviceStatusCommandInput = UpdateDeviceStatusRequest; export interface UpdateDeviceStatusCommandOutput extends UpdateDeviceStatusResponse, __MetadataBearer {} @@ -1594,9 +1562,8 @@ export interface UpdateDeviceStatusRequest { /** *

The response to the request to update the device status.

*/ -export interface UpdateDeviceStatusResponse {} -export interface UpdateUserAttributesCommandInput - extends UpdateUserAttributesRequest {} +export type UpdateDeviceStatusResponse = Record; +export type UpdateUserAttributesCommandInput = UpdateUserAttributesRequest; export interface UpdateUserAttributesCommandOutput extends UpdateUserAttributesResponse, __MetadataBearer {} @@ -1640,9 +1607,7 @@ export interface UpdateUserAttributesRequest { * * */ - ClientMetadata?: { - [key: string]: string; - }; + ClientMetadata?: Record; } /** *

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

@@ -1662,8 +1627,7 @@ export interface UserContextDataType { */ EncodedData?: string; } -export interface VerifySoftwareTokenCommandInput - extends VerifySoftwareTokenRequest {} +export type VerifySoftwareTokenCommandInput = VerifySoftwareTokenRequest; export interface VerifySoftwareTokenCommandOutput extends VerifySoftwareTokenResponse, __MetadataBearer {} @@ -1696,8 +1660,7 @@ export interface VerifySoftwareTokenResponse { */ Session?: string; } -export interface VerifyUserAttributeCommandInput - extends VerifyUserAttributeRequest {} +export type VerifyUserAttributeCommandInput = VerifyUserAttributeRequest; export interface VerifyUserAttributeCommandOutput extends VerifyUserAttributeResponse, __MetadataBearer {} @@ -1721,9 +1684,8 @@ export interface VerifyUserAttributeRequest { /** *

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

*/ -export interface VerifyUserAttributeResponse {} -export interface DeleteUserAttributesCommandInput - extends DeleteUserAttributesRequest {} +export type VerifyUserAttributeResponse = Record; +export type DeleteUserAttributesCommandInput = DeleteUserAttributesRequest; export interface DeleteUserAttributesCommandOutput extends DeleteUserAttributesResponse, __MetadataBearer {} @@ -1746,5 +1708,5 @@ export interface DeleteUserAttributesRequest { /** *

Represents the response from the server to delete user attributes.

*/ -export interface DeleteUserAttributesResponse {} +export type DeleteUserAttributesResponse = Record; export {}; diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts index 71ab71bd22c..2202f2dcd37 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts @@ -15,6 +15,7 @@ export function getRegion(userPoolId?: string): string { name: 'InvalidUserPoolId', message: 'Invalid user pool id provided.', }); + return region; } @@ -27,5 +28,6 @@ export function getRegionFromIdentityPoolId(identityPoolId?: string): string { 'Make sure a valid identityPoolId is given in the config.', }); } + return identityPoolId.split(':')[0]; } diff --git a/packages/auth/src/providers/cognito/utils/clients/base.ts b/packages/auth/src/providers/cognito/utils/clients/base.ts index 00035fdc1cc..a6a5fb6aca0 100644 --- a/packages/auth/src/providers/cognito/utils/clients/base.ts +++ b/packages/auth/src/providers/cognito/utils/clients/base.ts @@ -9,14 +9,14 @@ import { HttpResponse, Middleware, getDnsSuffix, - unauthenticatedHandler, - parseJsonError, getRetryDecider, jitteredBackoff, + parseJsonError, + unauthenticatedHandler, } from '@aws-amplify/core/internals/aws-client-utils'; import { - getAmplifyUserAgent, AmplifyUrl, + getAmplifyUserAgent, } from '@aws-amplify/core/internals/utils'; import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers'; @@ -37,12 +37,16 @@ const endpointResolver = ({ region }: EndpointResolverOptions) => ({ /** * A Cognito Identity-specific middleware that disables caching for all requests. */ -const disableCacheMiddleware: Middleware = - () => (next, context) => - async function disableCacheMiddleware(request) { - request.headers['cache-control'] = 'no-store'; - return next(request); - }; +const disableCacheMiddlewareFactory: Middleware< + HttpRequest, + HttpResponse, + Record +> = () => (next, _) => + async function disableCacheMiddleware(request) { + request.headers['cache-control'] = 'no-store'; + + return next(request); + }; /** * A Cognito Identity-specific transfer handler that does NOT sign requests, and @@ -51,11 +55,11 @@ const disableCacheMiddleware: Middleware = * @internal */ export const cognitoUserPoolTransferHandler = composeTransferHandler< - [Parameters[0]], + [Parameters[0]], HttpRequest, HttpResponse, typeof unauthenticatedHandler ->(unauthenticatedHandler, [disableCacheMiddleware]); +>(unauthenticatedHandler, [disableCacheMiddlewareFactory]); /** * @internal diff --git a/packages/auth/src/providers/cognito/utils/dispatchSignedInHubEvent.ts b/packages/auth/src/providers/cognito/utils/dispatchSignedInHubEvent.ts index b68b55e24dd..76fd6a4c24e 100644 --- a/packages/auth/src/providers/cognito/utils/dispatchSignedInHubEvent.ts +++ b/packages/auth/src/providers/cognito/utils/dispatchSignedInHubEvent.ts @@ -2,8 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { Hub } from '@aws-amplify/core'; -import { getCurrentUser } from '../apis/getCurrentUser'; import { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils'; + +import { getCurrentUser } from '../apis/getCurrentUser'; import { UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION, USER_UNAUTHENTICATED_EXCEPTION, diff --git a/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts b/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts index b805e613b6c..ebf375246bb 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts @@ -7,12 +7,14 @@ import { assertOAuthConfig, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils'; + +import { getAuthUserAgentValue } from '../../../../utils'; +import { cognitoUserPoolsTokenProvider } from '../../tokenProvider'; + import { oAuthStore } from './oAuthStore'; import { completeOAuthFlow } from './completeOAuthFlow'; -import { getAuthUserAgentValue } from '../../../../utils'; import { getRedirectUrl } from './getRedirectUrl'; import { handleFailure } from './handleFailure'; -import { cognitoUserPoolsTokenProvider } from '../../tokenProvider'; import { addInflightPromise } from './inflightPromise'; export const attemptCompleteOAuthFlow = async ( @@ -37,7 +39,7 @@ export const attemptCompleteOAuthFlow = async ( // when there is valid oauth config and there is an inflight oauth flow, try // to block async calls that require fetching tokens before the oauth flow completes // e.g. getCurrentUser, fetchAuthSession etc. - const asyncGetSessionBlocker = new Promise((resolve, _) => { + const asyncGetSessionBlocker = new Promise((resolve, _reject) => { addInflightPromise(resolve); }); cognitoUserPoolsTokenProvider.setWaitForInflightOAuth( diff --git a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts index c55839d2649..c10e1406524 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts @@ -7,16 +7,17 @@ import { USER_AGENT_HEADER, urlSafeDecode, } from '@aws-amplify/core/internals/utils'; -import { oAuthStore } from './oAuthStore'; import { Hub, decodeJWT } from '@aws-amplify/core'; -import { validateState } from './validateState'; -import { resolveAndClearInflightPromises } from './inflightPromise'; + import { cacheCognitoTokens } from '../../tokenProvider/cacheTokens'; -import { getCurrentUser } from '../../apis/getCurrentUser'; -import { createOAuthError } from './createOAuthError'; import { cognitoUserPoolsTokenProvider } from '../../tokenProvider'; import { dispatchSignedInHubEvent } from '../dispatchSignedInHubEvent'; +import { createOAuthError } from './createOAuthError'; +import { resolveAndClearInflightPromises } from './inflightPromise'; +import { validateState } from './validateState'; +import { oAuthStore } from './oAuthStore'; + export const completeOAuthFlow = async ({ currentUrl, userAgentValue, @@ -115,10 +116,10 @@ const handleCodeFlow = async ({ .join('&'); const { access_token, - refresh_token, + refresh_token: refreshToken, id_token, error, - error_message, + error_message: errorMessage, token_type, expires_in, } = await ( @@ -134,7 +135,7 @@ const handleCodeFlow = async ({ if (error) { // error is being caught in attemptCompleteOAuthFlow.ts - throw createOAuthError(error_message ?? error); + throw createOAuthError(errorMessage ?? error); } const username = @@ -144,7 +145,7 @@ const handleCodeFlow = async ({ username, AccessToken: access_token, IdToken: id_token, - RefreshToken: refresh_token, + RefreshToken: refreshToken, TokenType: token_type, ExpiresIn: expires_in, }); @@ -237,7 +238,9 @@ const completeFlow = async ({ // when the oauth flow is completed, there should be nothing to block the async calls // that involves fetchAuthSession in the `TokenOrchestrator` - cognitoUserPoolsTokenProvider.setWaitForInflightOAuth(async () => {}); + cognitoUserPoolsTokenProvider.setWaitForInflightOAuth(async () => { + // no-op + }); if (isCustomState(state)) { Hub.dispatch( @@ -255,7 +258,7 @@ const completeFlow = async ({ clearHistory(redirectUri); }; -const isCustomState = (state: string): Boolean => { +const isCustomState = (state: string): boolean => { return /-/.test(state); }; diff --git a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts index 0a904f3e5f9..bb2a30bac7e 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts @@ -1,8 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { clearCredentials, Hub } from '@aws-amplify/core'; +import { Hub, clearCredentials } from '@aws-amplify/core'; import { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils'; + import { DefaultOAuthStore } from '../../utils/signInWithRedirectStore'; import { tokenOrchestrator } from '../../tokenProvider'; diff --git a/packages/auth/src/providers/cognito/utils/oauth/enableOAuthListener.ts b/packages/auth/src/providers/cognito/utils/oauth/enableOAuthListener.ts index 0938781b451..c0ec3df85db 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/enableOAuthListener.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/enableOAuthListener.ts @@ -6,9 +6,7 @@ import { ADD_OAUTH_LISTENER, isBrowser, } from '@aws-amplify/core/internals/utils'; -import { cognitoUserPoolsTokenProvider } from '../../tokenProvider'; -import { oAuthStore } from './oAuthStore'; -import { addInflightPromise } from './inflightPromise'; + import { attemptCompleteOAuthFlow } from './attemptCompleteOAuthFlow'; // attach the side effect for handling the completion of an inflight oauth flow diff --git a/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts b/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts index 8215eec4cf5..b6251e95ac8 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts @@ -23,7 +23,7 @@ export const generateCodeVerifier = ( ): { value: string; method: 'S256'; - toCodeChallenge: () => string; + toCodeChallenge(): string; } => { const randomBytes = new Uint8Array(length); getCrypto().getRandomValues(randomBytes); @@ -31,7 +31,7 @@ export const generateCodeVerifier = ( let value = ''; let codeChallenge: string | undefined; - for (let byte of randomBytes) { + for (const byte of randomBytes) { value += CODE_VERIFIER_CHARSET.charAt(byte % CODE_VERIFIER_CHARSET.length); } @@ -43,6 +43,7 @@ export const generateCodeVerifier = ( return codeChallenge; } codeChallenge = generateCodeChallenge(value); + return codeChallenge; }, }; diff --git a/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts b/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts index d653b7967ed..315074aa69d 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts @@ -5,12 +5,13 @@ import { invalidRedirectException } from '../../../../errors/constants'; /** @internal */ export function getRedirectUrl(redirects: string[]): string { - const redirect = redirects?.find( + const redirectUrl = redirects?.find( redirect => !redirect.startsWith('http://') && !redirect.startsWith('https://'), ); - if (!redirect) { + if (!redirectUrl) { throw invalidRedirectException; } - return redirect; + + return redirectUrl; } diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts b/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts index 8851c252bb5..8c304290c37 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts @@ -5,6 +5,7 @@ import { Hub } from '@aws-amplify/core'; import { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../../errors/AuthError'; + import { oAuthStore } from './oAuthStore'; import { resolveAndClearInflightPromises } from './inflightPromise'; diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts index 5f08c646c94..bd9c8416b55 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts @@ -2,8 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { CognitoUserPoolConfig } from '@aws-amplify/core'; + import { OpenAuthSessionResult } from '../../../../utils/types'; import { DefaultOAuthStore } from '../../utils/signInWithRedirectStore'; + import { completeOAuthSignOut } from './completeOAuthSignOut'; import { oAuthSignOutRedirect } from './oAuthSignOutRedirect'; @@ -25,6 +27,7 @@ export const handleOAuthSignOut = async ( if (shouldCompleteSignOut) { await completeOAuthSignOut(store); } + return result; } diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts index db535717759..0e16008e752 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts @@ -2,8 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { CognitoUserPoolConfig } from '@aws-amplify/core'; + import { OpenAuthSessionResult } from '../../../../utils/types'; import { DefaultOAuthStore } from '../../utils/signInWithRedirectStore'; + import { completeOAuthSignOut } from './completeOAuthSignOut'; import { oAuthSignOutRedirect } from './oAuthSignOutRedirect'; diff --git a/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts b/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts index fb5c87ef34d..2dd1eda520a 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts @@ -3,13 +3,15 @@ import { CognitoUserPoolConfig } from '@aws-amplify/core'; import { assertOAuthConfig } from '@aws-amplify/core/internals/utils'; + import { openAuthSession } from '../../../../utils'; import { OpenAuthSessionResult } from '../../../../utils/types'; + import { getRedirectUrl } from './getRedirectUrl'; export const oAuthSignOutRedirect = async ( authConfig: CognitoUserPoolConfig, - preferPrivateSession: boolean = false, + preferPrivateSession = false, ): Promise => { assertOAuthConfig(authConfig); const { loginWith, userPoolClientId } = authConfig; diff --git a/packages/auth/src/providers/cognito/utils/oauth/oAuthStore.ts b/packages/auth/src/providers/cognito/utils/oauth/oAuthStore.ts index 33e992a5de9..90f50fa5c61 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/oAuthStore.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/oAuthStore.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { defaultStorage } from '@aws-amplify/core'; + import { DefaultOAuthStore } from '../signInWithRedirectStore'; export const oAuthStore = new DefaultOAuthStore(defaultStorage); diff --git a/packages/auth/src/providers/cognito/utils/oauth/validateState.ts b/packages/auth/src/providers/cognito/utils/oauth/validateState.ts index 8f19ca2db80..d52a322bf71 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/validateState.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/validateState.ts @@ -3,6 +3,7 @@ import { AuthError } from '../../../../errors/AuthError'; import { AuthErrorTypes } from '../../../../types/Auth'; + import { oAuthStore } from './oAuthStore'; export const flowCancelledMessage = '`signInWithRedirect` has been canceled.'; @@ -24,5 +25,6 @@ export const validateState = async (state?: string | null): Promise => { state === null ? undefined : validationRecoverySuggestion, }); } + return validatedState; }; diff --git a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts index 556b9a7a95a..bd5e8b33358 100644 --- a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts +++ b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts @@ -1,17 +1,19 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { CognitoAuthTokens, TokenRefresher } from '../tokenProvider/types'; import { AuthConfig } from '@aws-amplify/core'; import { assertTokenProviderConfig, - decodeJWT, deDupeAsyncFunction, + decodeJWT, } from '@aws-amplify/core/internals/utils'; + +import { CognitoAuthTokens, TokenRefresher } from '../tokenProvider/types'; import { initiateAuth } from '../utils/clients/CognitoIdentityProvider'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokensWithRefreshToken } from '../utils/types'; import { AuthError } from '../../../errors/AuthError'; + import { getUserContextData } from './userContextData'; const refreshAuthTokensFunction: TokenRefresher = async ({ @@ -32,7 +34,7 @@ const refreshAuthTokensFunction: TokenRefresher = async ({ REFRESH_TOKEN: refreshTokenString, }; if (tokens.deviceMetadata?.deviceKey) { - AuthParameters['DEVICE_KEY'] = tokens.deviceMetadata.deviceKey; + AuthParameters.DEVICE_KEY = tokens.deviceMetadata.deviceKey; } const UserContextData = getUserContextData({ @@ -55,7 +57,7 @@ const refreshAuthTokensFunction: TokenRefresher = async ({ const idToken = AuthenticationResult?.IdToken ? decodeJWT(AuthenticationResult.IdToken) : undefined; - const iat = accessToken.payload.iat; + const { iat } = accessToken.payload; // This should never happen. If it does, it's a bug from the service. if (!iat) { throw new AuthError({ diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index b31291bfc60..ce1336ce611 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -3,44 +3,41 @@ import { Amplify, CognitoUserPoolConfig } from '@aws-amplify/core'; import { + AmplifyUrl, AuthAction, assertTokenProviderConfig, base64Encoder, - AmplifyUrl, } from '@aws-amplify/core/internals/utils'; -import { AuthenticationHelper } from './srp/AuthenticationHelper'; -import { BigInteger } from './srp/BigInteger'; -import { - getAuthenticationHelper, - getBytesFromHex, - getNowString, - getSignatureString, -} from './srp'; import { ClientMetadata, ConfirmSignInOptions } from '../types'; import { AuthAdditionalInfo, - AuthSignInOutput, AuthDeliveryMedium, + AuthSignInOutput, } from '../../../types'; import { AuthError } from '../../../errors/AuthError'; import { InitiateAuthException } from '../types/errors'; import { AWSAuthUser, - AuthUserAttributes, AuthMFAType, AuthTOTPSetupDetails, + AuthUserAttributes, } from '../../../types/models'; import { AuthErrorCodes } from '../../../common/AuthErrorStrings'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; +import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../errors/constants'; +import { getCurrentUser } from '../apis/getCurrentUser'; +import { AuthTokenOrchestrator, DeviceMetadata } from '../tokenProvider/types'; +import { getAuthUserAgentValue } from '../../../utils'; + import { signInStore } from './signInStore'; import { + associateSoftwareToken, + confirmDevice, initiateAuth, respondToAuthChallenge, verifySoftwareToken, - associateSoftwareToken, - confirmDevice, } from './clients/CognitoIdentityProvider'; import { ChallengeName, @@ -53,16 +50,20 @@ 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'; -import { AuthTokenOrchestrator, DeviceMetadata } from '../tokenProvider/types'; import { assertDeviceMetadata } from './types'; -import { getAuthUserAgentValue } from '../../../utils'; +import { + getAuthenticationHelper, + getBytesFromHex, + getNowString, + getSignatureString, +} from './srp'; +import { BigInteger } from './srp/BigInteger'; +import { AuthenticationHelper } from './srp/AuthenticationHelper'; import { getUserContextData } from './userContextData'; const USER_ATTRIBUTES = 'userAttributes.'; -type HandleAuthChallengeRequest = { +interface HandleAuthChallengeRequest { challengeResponse: string; username: string; clientMetadata?: ClientMetadata; @@ -70,15 +71,15 @@ type HandleAuthChallengeRequest = { deviceName?: string; requiredAttributes?: AuthUserAttributes; config: CognitoUserPoolConfig; -}; +} -type HandleDeviceSRPInput = { +interface HandleDeviceSRPInput { username: string; config: CognitoUserPoolConfig; clientMetadata: ClientMetadata | undefined; session: string | undefined; tokenOrchestrator?: AuthTokenOrchestrator; -}; +} export async function handleCustomChallenge({ challengeResponse, @@ -98,7 +99,7 @@ export async function handleCustomChallenge({ const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username); if (deviceMetadata && deviceMetadata.deviceKey) { - challengeResponses['DEVICE_KEY'] = deviceMetadata.deviceKey; + challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey; } const UserContextData = getUserContextData({ @@ -174,6 +175,7 @@ export async function handleMFASetupChallenge({ ClientMetadata: clientMetadata, ClientId: userPoolClientId, }; + return respondToAuthChallenge({ region: getRegion(userPoolId) }, jsonReq); } @@ -280,6 +282,7 @@ export async function handleSoftwareTokenMFAChallenge({ ClientId: userPoolClientId, UserContextData, }; + return respondToAuthChallenge( { region: getRegion(userPoolId), @@ -342,7 +345,7 @@ export async function handleUserPasswordAuthFlow( const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username); if (deviceMetadata && deviceMetadata.deviceKey) { - authParameters['DEVICE_KEY'] = deviceMetadata.deviceKey; + authParameters.DEVICE_KEY = deviceMetadata.deviceKey; } const UserContextData = getUserContextData({ @@ -382,6 +385,7 @@ export async function handleUserPasswordAuthFlow( session: response.Session, tokenOrchestrator, }); + return response; } @@ -425,6 +429,7 @@ export async function handleUserSRPAuthFlow( const { ChallengeParameters: challengeParameters, Session: session } = resp; const activeUsername = challengeParameters?.USERNAME ?? username; setActiveSignInUsername(activeUsername); + return retryOnResourceNotFoundException( handlePasswordVerifierChallenge, [ @@ -448,14 +453,13 @@ export async function handleCustomAuthFlowWithoutSRP( tokenOrchestrator: AuthTokenOrchestrator, ): Promise { const { userPoolClientId, userPoolId } = config; - const { dispatch } = signInStore; const authParameters: Record = { USERNAME: username, }; const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username); if (deviceMetadata && deviceMetadata.deviceKey) { - authParameters['DEVICE_KEY'] = deviceMetadata.deviceKey; + authParameters.DEVICE_KEY = deviceMetadata.deviceKey; } const UserContextData = getUserContextData({ @@ -489,6 +493,7 @@ export async function handleCustomAuthFlowWithoutSRP( session: response.Session, tokenOrchestrator, }); + return response; } @@ -559,7 +564,7 @@ async function handleDeviceSRPAuth({ session, tokenOrchestrator, }: HandleDeviceSRPInput): Promise { - const userPoolId = config.userPoolId; + const { userPoolId } = config; const clientId = config.userPoolClientId; const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username); assertDeviceMetadata(deviceMetadata); @@ -579,14 +584,15 @@ async function handleDeviceSRPAuth({ ClientMetadata: clientMetadata, Session: session, }; - const { ChallengeParameters, Session } = await respondToAuthChallenge( - { region: getRegion(userPoolId) }, - jsonReqResponseChallenge, - ); + const { ChallengeParameters: respondedChallengeParameters, Session } = + await respondToAuthChallenge( + { region: getRegion(userPoolId) }, + jsonReqResponseChallenge, + ); return handleDevicePasswordVerifier( username, - ChallengeParameters as ChallengeParameters, + respondedChallengeParameters as ChallengeParameters, clientMetadata, Session, authenticationHelper, @@ -609,8 +615,8 @@ async function handleDevicePasswordVerifier( const serverBValue = new BigInteger(challengeParameters?.SRP_B, 16); const salt = new BigInteger(challengeParameters?.SALT, 16); - const deviceKey = deviceMetadata.deviceKey; - const deviceGroupKey = deviceMetadata.deviceGroupKey; + const { deviceKey } = deviceMetadata; + const { deviceGroupKey } = deviceMetadata; const hkdf = await authenticationHelper.getPasswordAuthenticationKey({ username: deviceMetadata.deviceKey, password: deviceMetadata.randomPassword, @@ -631,7 +637,7 @@ async function handleDevicePasswordVerifier( hkdf, }), DEVICE_KEY: deviceKey, - } as { [key: string]: string }; + } as Record; const UserContextData = getUserContextData({ username, @@ -693,11 +699,11 @@ export async function handlePasswordVerifierChallenge( dateNow, hkdf, }), - } as { [key: string]: string }; + } as Record; const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username); if (deviceMetadata && deviceMetadata.deviceKey) { - challengeResponses['DEVICE_KEY'] = deviceMetadata.deviceKey; + challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey; } const UserContextData = getUserContextData({ @@ -728,6 +734,7 @@ export async function handlePasswordVerifierChallenge( session: response.Session, tokenOrchestrator, }); + return response; } @@ -748,7 +755,7 @@ export async function getSignInResult(params: { additionalInfo: challengeParameters as AuthAdditionalInfo, }, }; - case 'MFA_SETUP': + case 'MFA_SETUP': { const { signInSession, username } = signInStore.getState(); if (!isMFATypeEnabled(challengeParameters, 'TOTP')) @@ -776,6 +783,7 @@ export async function getSignInResult(params: { totpSetupDetails: getTOTPSetupDetails(secretCode!, username), }, }; + } case 'NEW_PASSWORD_REQUIRED': return { isSignedIn: false, @@ -867,7 +875,7 @@ export function getSignInResultFromError( export function parseAttributes(attributes: string | undefined): string[] { if (!attributes) return []; - const parsedAttributes = (JSON.parse(attributes) as Array).map(att => + const parsedAttributes = (JSON.parse(attributes) as string[]).map(att => att.includes(USER_ATTRIBUTES) ? att.replace(USER_ATTRIBUTES, '') : att, ); @@ -884,6 +892,7 @@ export function createAttributes( Object.entries(attributes).forEach(([key, value]) => { if (value) newAttributes[`${USER_ATTRIBUTES}${key}`] = value; }); + return newAttributes; } @@ -983,10 +992,12 @@ export function getMFAType(type?: string): AuthMFAType | undefined { export function getMFATypes(types?: string[]): AuthMFAType[] | undefined { if (!types) return undefined; + return types.map(getMFAType).filter(Boolean) as AuthMFAType[]; } export function parseMFATypes(mfa?: string): CognitoMFAType[] { if (!mfa) return []; + return JSON.parse(mfa) as CognitoMFAType[]; } @@ -997,6 +1008,7 @@ export function isMFATypeEnabled( const { MFAS_CAN_SETUP } = challengeParams; const mfaTypes = getMFATypes(parseMFATypes(MFAS_CAN_SETUP)); if (!mfaTypes) return false; + return mfaTypes.includes(mfaType); } @@ -1099,7 +1111,7 @@ export async function retryOnResourceNotFoundException< ) { await tokenOrchestrator.clearDeviceMetadata(username); - return await func(...args); + return func(...args); } throw error; } @@ -1113,5 +1125,6 @@ export function setActiveSignInUsername(username: string) { export function getActiveSignInUsername(username: string): string { const state = signInStore.getState(); + return state.username ?? username; } diff --git a/packages/auth/src/providers/cognito/utils/signInStore.ts b/packages/auth/src/providers/cognito/utils/signInStore.ts index b50774b1c71..0028ab71067 100644 --- a/packages/auth/src/providers/cognito/utils/signInStore.ts +++ b/packages/auth/src/providers/cognito/utils/signInStore.ts @@ -2,15 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { CognitoAuthSignInDetails } from '../types'; + import { ChallengeName } from './clients/CognitoIdentityProvider/types'; // TODO: replace all of this implementation with state machines -type SignInState = { +interface SignInState { username?: string; challengeName?: ChallengeName; signInSession?: string; signInDetails?: CognitoAuthSignInDetails; -}; +} type SignInAction = | { type: 'SET_INITIAL_STATE' } @@ -20,7 +21,7 @@ type SignInAction = | { type: 'SET_SIGN_IN_SESSION'; value?: string }; type Store = (reducer: Reducer) => { - getState: () => ReturnType>; + getState(): ReturnType>; dispatch(action: Action): void; }; diff --git a/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts b/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts index f449e698070..a72469b6ab5 100644 --- a/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts +++ b/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts @@ -5,10 +5,12 @@ import { CognitoUserPoolConfig, KeyValueStorageInterface, } from '@aws-amplify/core'; -import { OAuthStorageKeys, OAuthStore } from './types'; -import { getAuthStorageKeys } from '../tokenProvider/TokenStore'; import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; +import { getAuthStorageKeys } from '../tokenProvider/TokenStore'; + +import { OAuthStorageKeys, OAuthStore } from './types'; + const V5_HOSTED_UI_KEY = 'amplify-signin-with-hostedUI'; const name = 'CognitoIdentityServiceProvider'; @@ -19,6 +21,7 @@ export class DefaultOAuthStore implements OAuthStore { constructor(keyValueStorage: KeyValueStorageInterface) { this.keyValueStorage = keyValueStorage; } + async clearOAuthInflightData(): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -32,6 +35,7 @@ export class DefaultOAuthStore implements OAuthStore { this.keyValueStorage.removeItem(authKeys.oauthState), ]); } + async clearOAuthData(): Promise { assertTokenProviderConfig(this.cognitoConfig); const authKeys = createKeysForAuthStorage( @@ -40,8 +44,10 @@ export class DefaultOAuthStore implements OAuthStore { ); await this.clearOAuthInflightData(); await this.keyValueStorage.removeItem(V5_HOSTED_UI_KEY); // remove in case a customer migrated an App from v5 to v6 + return this.keyValueStorage.removeItem(authKeys.oauthSignIn); } + loadOAuthState(): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -52,6 +58,7 @@ export class DefaultOAuthStore implements OAuthStore { return this.keyValueStorage.getItem(authKeys.oauthState); } + storeOAuthState(state: string): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -62,6 +69,7 @@ export class DefaultOAuthStore implements OAuthStore { return this.keyValueStorage.setItem(authKeys.oauthState, state); } + loadPKCE(): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -72,6 +80,7 @@ export class DefaultOAuthStore implements OAuthStore { return this.keyValueStorage.getItem(authKeys.oauthPKCE); } + storePKCE(pkce: string): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -86,6 +95,7 @@ export class DefaultOAuthStore implements OAuthStore { setAuthConfig(authConfigParam: CognitoUserPoolConfig): void { this.cognitoConfig = authConfigParam; } + async loadOAuthInFlight(): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -106,10 +116,7 @@ export class DefaultOAuthStore implements OAuthStore { this.cognitoConfig.userPoolClientId, ); - return await this.keyValueStorage.setItem( - authKeys.inflightOAuth, - `${inflight}`, - ); + await this.keyValueStorage.setItem(authKeys.inflightOAuth, `${inflight}`); } async loadOAuthSignIn(): Promise<{ @@ -139,7 +146,7 @@ export class DefaultOAuthStore implements OAuthStore { async storeOAuthSignIn( oauthSignIn: boolean, - preferPrivateSession: boolean = false, + preferPrivateSession = false, ): Promise { assertTokenProviderConfig(this.cognitoConfig); @@ -148,7 +155,7 @@ export class DefaultOAuthStore implements OAuthStore { this.cognitoConfig.userPoolClientId, ); - return await this.keyValueStorage.setItem( + await this.keyValueStorage.setItem( authKeys.oauthSignIn, `${oauthSignIn},${preferPrivateSession}`, ); diff --git a/packages/auth/src/providers/cognito/utils/signUpHelpers.ts b/packages/auth/src/providers/cognito/utils/signUpHelpers.ts index b071da039d9..73e59c78406 100644 --- a/packages/auth/src/providers/cognito/utils/signUpHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signUpHelpers.ts @@ -2,15 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { HubInternal } from '@aws-amplify/core/internals/utils'; + import { signIn } from '../apis/signIn'; import { SignInInput, SignInOutput } from '../types'; import { AutoSignInEventData } from '../types/models'; import { AutoSignInCallback } from '../../../types/models'; import { AuthError } from '../../../errors/AuthError'; -import { SignUpCommandOutput } from './clients/CognitoIdentityProvider/types'; import { resetAutoSignIn, setAutoSignIn } from '../apis/autoSignIn'; import { AUTO_SIGN_IN_EXCEPTION } from '../../../errors/constants'; +import { SignUpCommandOutput } from './clients/CognitoIdentityProvider/types'; + const MAX_AUTOSIGNIN_POLLING_MS = 3 * 60 * 1000; export function handleCodeAutoSignIn(signInInput: SignInInput) { @@ -50,9 +52,8 @@ export function handleCodeAutoSignIn(signInInput: SignInInput) { type TimeOutOutput = ReturnType; function debounce any>(fun: F, delay: number) { let timer: TimeOutOutput | undefined; - return function ( - args: F extends (...args: infer A) => any ? A : never, - ): void { + + return (args: F extends (...args: infer A) => any ? A : never): void => { if (!timer) { fun(...args); } @@ -65,8 +66,8 @@ function debounce any>(fun: F, delay: number) { function handleAutoSignInWithLink( signInInput: SignInInput, - resolve: Function, - reject: Function, + resolve: (value: SignInOutput) => void, + reject: (reason?: any) => void, ) { const start = Date.now(); const autoSignInPollingIntervalId = setInterval(async () => { @@ -84,7 +85,6 @@ function handleAutoSignInWithLink( }), ); resetAutoSignIn(); - return; } else { try { const signInOutput = await signIn(signInInput); @@ -93,7 +93,6 @@ function handleAutoSignInWithLink( clearInterval(autoSignInPollingIntervalId); setAutoSignInStarted(false); resetAutoSignIn(); - return; } } catch (error) { clearInterval(autoSignInPollingIntervalId); @@ -110,7 +109,7 @@ const debouncedAutoSignWithCodeOrUserConfirmed = debounce( 300, ); -let autoSignInStarted: boolean = false; +let autoSignInStarted = false; let usernameUsedForAutoSignIn: string | undefined; @@ -139,15 +138,15 @@ export function autoSignInWhenUserIsConfirmedWithLink( signInInput: SignInInput, ): AutoSignInCallback { return async () => { - return new Promise(async (resolve, reject) => { + return new Promise((resolve, reject) => { debouncedAutoSignInWithLink([signInInput, resolve, reject]); }); }; } async function handleAutoSignInWithCodeOrUserConfirmed( signInInput: SignInInput, - resolve: Function, - reject: Function, + resolve: (value: SignInOutput) => void, + reject: (reason?: any) => void, ) { try { const output = await signIn(signInInput); @@ -161,7 +160,7 @@ async function handleAutoSignInWithCodeOrUserConfirmed( function autoSignInWithCode(signInInput: SignInInput): AutoSignInCallback { return async () => { - return new Promise(async (resolve, reject) => { + return new Promise((resolve, reject) => { debouncedAutoSignWithCodeOrUserConfirmed([signInInput, resolve, reject]); }); }; diff --git a/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts b/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts index 29cd9660bd5..d170e4b76c5 100644 --- a/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts +++ b/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts @@ -62,6 +62,7 @@ export default class AuthenticationHelper { message: 'random password is empty', }); } + return this.randomPassword; } @@ -75,6 +76,7 @@ export default class AuthenticationHelper { message: 'saltToHashDevices is empty', }); } + return this.saltToHashDevices; } @@ -88,6 +90,7 @@ export default class AuthenticationHelper { message: 'verifyDevices is empty', }); } + return this.verifierDevices; } @@ -122,6 +125,7 @@ export default class AuthenticationHelper { (err: unknown, result: AuthBigInteger) => { if (err) { reject(err); + return; } @@ -188,6 +192,7 @@ export default class AuthenticationHelper { getBytesFromHex(getPaddedHex(U)), info, ); + return hkdfKey; } } diff --git a/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts b/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts index 03e99647746..895dedd0999 100644 --- a/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts +++ b/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts @@ -1,4 +1,4 @@ -/* tslint:disable */ +/* eslint-disable */ // @ts-nocheck -> BigInteger is already a vended utility // A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/ // @@ -21,7 +21,10 @@ import { AuthBigInteger } from './types'; export default BigInteger as AuthBigInteger; -type BNP = { s: number; t: number }; +interface BNP { + s: number; + t: number; +} /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. @@ -91,6 +94,7 @@ function am1( c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } + return c; } // am2 avoids a big mult-and-extract completely. @@ -104,8 +108,8 @@ function am2( c: number, n: number, ): number { - const xl = x & 0x7fff, - xh = x >> 15; + const xl = x & 0x7fff; + const xh = x >> 15; while (--n >= 0) { let l = this[i] & 0x7fff; const h = this[i++] >> 15; @@ -114,6 +118,7 @@ function am2( c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } + return c; } // Alternately, set max digit bits to 28 since some @@ -126,8 +131,8 @@ function am3( c: number, n: number, ): number { - const xl = x & 0x3fff, - xh = x >> 14; + const xl = x & 0x3fff; + const xh = x >> 14; while (--n >= 0) { let l = this[i] & 0x3fff; const h = this[i++] >> 14; @@ -136,6 +141,7 @@ function am3( c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } + return c; } const inBrowser = typeof navigator !== 'undefined'; @@ -162,7 +168,7 @@ BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions const BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'; -const BI_RC = new Array(); +const BI_RC = []; let rr: number, vv: number; rr = '0'.charCodeAt(0); for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; @@ -175,13 +181,14 @@ function int2char(n: number): string { return BI_RM.charAt(n); } function intAt(s: string, i: number): number { - var c = BI_RC[s.charCodeAt(i)]; + const c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r: { t: number; s: number }): void { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + for (let i = this.t - 1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } @@ -197,7 +204,7 @@ function bnpFromInt(x: number): void { // return bigint initialized to value function nbv(i: number) { - var r = nbi(); + const r = nbi(); r.fromInt(i); @@ -215,9 +222,9 @@ function bnpFromString(s: string, b: number): void { else throw new Error('Only radix 2, 4, 8, 16, 32 are supported'); this.t = 0; this.s = 0; - let i = s.length, - mi = false, - sh = 0; + let i = s.length; + let mi = false; + let sh = 0; while (--i >= 0) { const x = intAt(s, i); if (x < 0) { @@ -239,25 +246,25 @@ function bnpFromString(s: string, b: number): void { // (protected) clamp off excess high words function bnpClamp(): void { - var c = this.s & this.DM; + const c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b: number): string { if (this.s < 0) return '-' + this.negate().toString(b); - var k: number; + let k: number; if (b == 16) k = 4; else if (b === 8) k = 3; else if (b === 2) k = 1; else if (b === 32) k = 5; else if (b === 4) k = 2; else throw new Error('Only radix 2, 4, 8, 16, 32 are supported'); - let km = (1 << k) - 1, - d: number, - m = false, - r = '', - i = this.t; + const km = (1 << k) - 1; + let d: number; + let m = false; + let r = ''; + let i = this.t; let p = this.DB - ((i * this.DB) % k); if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { @@ -279,12 +286,13 @@ function bnToString(b: number): string { if (m) r += int2char(d); } } + return m ? r : '0'; } // (public) -this function bnNegate() { - var r = nbi(); + const r = nbi(); BigInteger.ZERO.subTo(this, r); @@ -298,19 +306,20 @@ function bnAbs() { // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a: BNP): number { - var r = this.s - a.s; + let r = this.s - a.s; if (r != 0) return r; - var i = this.t; + let i = this.t; r = i - a.t; if (r != 0) return this.s < 0 ? -r : r; while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; + return 0; } // returns bit length of the integer x function nbits(x: number): number { - var r = 1, - t: number; + let r = 1; + let t: number; if ((t = x >>> 16) !== 0) { x = t; r += 16; @@ -331,12 +340,14 @@ function nbits(x: number): number { x = t; r += 1; } + return r; } // (public) return the number of bits in "this" function bnBitLength(): number { if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); } @@ -364,9 +375,9 @@ function bnpLShiftTo( const bs = n % this.DB; const cbs = this.DB - bs; const bm = (1 << cbs) - 1; - let ds = Math.floor(n / this.DB), - c = (this.s << bs) & this.DM, - i; + const ds = Math.floor(n / this.DB); + let c = (this.s << bs) & this.DM; + let i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = (this[i] >> cbs) | c; c = (this[i] & bm) << bs; @@ -384,6 +395,7 @@ function bnpRShiftTo(n: number, r: BNP & { clamp: Function }): void { const ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; + return; } const bs = n % this.DB; @@ -401,9 +413,9 @@ function bnpRShiftTo(n: number, r: BNP & { clamp: Function }): void { // (protected) r = this - a function bnpSubTo(a: BNP, r: BNP & { clamp: Function }): void { - let i = 0, - c = 0, - m = Math.min(a.t, this.t); + let i = 0; + let c = 0; + const m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; @@ -439,8 +451,8 @@ function bnpMultiplyTo( a: BNP & { abs: Function }, r: BNP & { clamp: Function }, ): void { - const x = this.abs(), - y = a.abs(); + const x = this.abs(); + const y = a.abs(); let i = x.t; r.t = i + y.t; while (--i >= 0) r[i] = 0; @@ -452,11 +464,11 @@ function bnpMultiplyTo( // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { - var x = this.abs(); - var i = (r.t = 2 * x.t); + const x = this.abs(); + let i = (r.t = 2 * x.t); while (--i >= 0) r[i] = 0; for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); + const c = x.am(i, x[i], r, 2 * i, 0, 1); if ( (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV @@ -483,19 +495,20 @@ function bnpDivRemTo( rShiftTo: Function; }, ): void { - var pm = m.abs(); + const pm = m.abs(); if (pm.t <= 0) return; - var pt = this.abs(); + const pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); + return; } if (r === null) r = nbi(); - var y = nbi(), - ts = this.s, - ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); + const y = nbi(); + const ts = this.s; + const ms = m.s; + const nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); @@ -508,12 +521,12 @@ function bnpDivRemTo( const y0 = y[ys - 1]; if (y0 === 0) return; const yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); - const d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - let i = r.t, - j = i - ys, - t = q === null ? nbi() : q; + const d1 = this.FV / yt; + const d2 = (1 << this.F1) / yt; + const e = 1 << this.F2; + let i = r.t; + let j = i - ys; + const t = q === null ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; @@ -525,7 +538,7 @@ function bnpDivRemTo( while (y.t < ys) y[y.t++] = 0; while (--j >= 0) { // Estimate quotient digit - var qd = + let qd = r[--i] === y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out @@ -547,9 +560,10 @@ function bnpDivRemTo( // (public) this mod a function bnMod(a) { - var r = nbi(); + const r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; } @@ -565,9 +579,9 @@ function bnMod(a) { // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit(): number { if (this.t < 1) return 0; - var x = this[0]; + const x = this[0]; if ((x & 1) === 0) return 0; - var y = x & 3; + let y = x & 3; // y == 1/x mod 2^2 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 @@ -578,6 +592,7 @@ function bnpInvDigit(): number { // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y * (2 - ((x * y) % this.DV))) % this.DV; + // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return y > 0 ? this.DV - y : -y; @@ -589,9 +604,9 @@ function bnEquals(a: number): boolean { // (protected) r = this + a function bnpAddTo(a: BNP, r: BNP & { clamp: Function }): void { - let i = 0, - c = 0, - m = Math.min(a.t, this.t); + let i = 0; + let c = 0; + const m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; @@ -623,7 +638,7 @@ function bnpAddTo(a: BNP, r: BNP & { clamp: Function }): void { // (public) this + a function bnAdd(a: number) { - var r = nbi(); + const r = nbi(); this.addTo(a, r); @@ -632,7 +647,7 @@ function bnAdd(a: number) { // (public) this - a function bnSubtract(a: number): number { - var r = nbi(); + const r = nbi(); this.subTo(a, r); @@ -641,7 +656,7 @@ function bnSubtract(a: number): number { // (public) this * a function bnMultiply(a: number): number { - var r = nbi(); + const r = nbi(); this.multiplyTo(a, r); @@ -650,7 +665,7 @@ function bnMultiply(a: number): number { // (public) this / a function bnDivide(a: number): number { - var r = nbi(); + const r = nbi(); this.divRemTo(a, r, null); @@ -669,18 +684,20 @@ function Montgomery(m: { invDigit: Function; DB: number; t: number }): void { // xR mod m function montConvert(x: BNP & { abs: Function }): number { - var r = nbi(); + const r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; } // x/R mod m function montRevert(x: { copyTo: Function }): number { - var r = nbi(); + const r = nbi(); x.copyTo(r); this.reduce(r); + return r; } @@ -697,10 +714,10 @@ function montReduce(x: { while (x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { + for (let i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = + let j = x[i] & 0x7fff; + const u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; @@ -748,10 +765,10 @@ function bnModPow( }, callback: Function, ) { - let i = e.bitLength(), - k: number, - r = nbv(1), - z = new Montgomery(m); + let i = e.bitLength(); + let k: number; + let r = nbv(1); + const z = new Montgomery(m); if (i <= 0) return r; else if (i < 18) k = 1; else if (i < 48) k = 3; @@ -760,10 +777,10 @@ function bnModPow( else k = 6; // precomputation - let g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1; + const g = []; + let n = 3; + const k1 = k - 1; + const km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { const g2 = nbi(); @@ -775,11 +792,11 @@ function bnModPow( } } - let j = e.t - 1, - w: number, - is1 = true, - r2 = nbi(), - t: number; + let j = e.t - 1; + let w: number; + let is1 = true; + let r2 = nbi(); + let t: number; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = (e[j] >> (i - k1)) & km; @@ -827,8 +844,9 @@ function bnModPow( } } } - var result = z.revert(r); + const result = z.revert(r); callback(null, result); + return result; } diff --git a/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts b/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts index 5aae6ed471b..51e49f4e163 100644 --- a/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts +++ b/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts @@ -9,15 +9,19 @@ import { AuthBigInteger } from './types'; BigInteger.prototype.modPow = function modPow( e: AuthBigInteger, m: AuthBigInteger, - callback: Function, + callback: (error: Error | null, result: AuthBigInteger | null) => void, ) { computeModPow({ base: (this as unknown as AuthBigInteger).toString(16), exponent: e.toString(16), divisor: m.toString(16), }) - .then((result: any) => callback(null, new BigInteger(result, 16))) - .catch((error: any) => callback(new Error(error), null)); + .then((result: any) => { + callback(null, new BigInteger(result, 16)); + }) + .catch((error: any) => { + callback(new Error(error), null); + }); }; export { BigInteger }; diff --git a/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.ts b/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.ts index 8bb8d7e19cc..83be1d1b7fc 100644 --- a/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.ts +++ b/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.ts @@ -2,5 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import BigInteger from './BigInteger'; + export { AuthBigInteger } from './types'; export { BigInteger }; diff --git a/packages/auth/src/providers/cognito/utils/srp/BigInteger/types.ts b/packages/auth/src/providers/cognito/utils/srp/BigInteger/types.ts index 55888d19fb2..3d19f0d0677 100644 --- a/packages/auth/src/providers/cognito/utils/srp/BigInteger/types.ts +++ b/packages/auth/src/providers/cognito/utils/srp/BigInteger/types.ts @@ -1,3 +1,6 @@ +/* eslint-disable */ +// @ts-nocheck -> BigInteger is already a vended utility + // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 @@ -13,6 +16,6 @@ export interface AuthBigInteger { ZERO: any; abs: Function; compareTo: Function; - fromInt: (num: number) => void; - toString: (radix: number) => string; + fromInt(num: number): void; + toString(radix: number): string; } diff --git a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateA.ts b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateA.ts index ba8f1a99d4f..a273a2eebad 100644 --- a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateA.ts +++ b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateA.ts @@ -19,11 +19,13 @@ export const calculateA = async ({ g.modPow(a, N, (err: unknown, A: AuthBigInteger) => { if (err) { reject(err); + return; } if (A.mod(N).equals(BigInteger.ZERO)) { reject(new Error('Illegal parameter. A mod N cannot be 0.')); + return; } diff --git a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.native.ts b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.native.ts index 8e42da77e36..3d0e6631301 100644 --- a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.native.ts +++ b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { computeS } from '@aws-amplify/react-native'; + import { AuthBigInteger, BigInteger } from '../BigInteger'; export const calculateS = async ({ @@ -10,7 +11,7 @@ export const calculateS = async ({ k, x, B, - N, + N: _, U, }: { a: AuthBigInteger; @@ -29,5 +30,6 @@ export const calculateS = async ({ b: B.toString(16), u: U.toString(16), }); + return new BigInteger(result, 16); }; diff --git a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts index c27d14d301d..be6bdb4ea35 100644 --- a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts +++ b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts @@ -27,6 +27,7 @@ export const calculateS = async ({ g.modPow(x, N, (outerErr: unknown, outerResult: AuthBigInteger) => { if (outerErr) { reject(outerErr); + return; } @@ -36,6 +37,7 @@ export const calculateS = async ({ (innerErr: unknown, innerResult: AuthBigInteger) => { if (innerErr) { reject(innerErr); + return; } resolve(innerResult.mod(N)); diff --git a/packages/auth/src/providers/cognito/utils/srp/getHashFromData.ts b/packages/auth/src/providers/cognito/utils/srp/getHashFromData.ts index 89987bc0503..e99646bf62e 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getHashFromData.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getHashFromData.ts @@ -3,6 +3,7 @@ import { Sha256 } from '@aws-crypto/sha256-js'; import { SourceData } from '@smithy/types'; + import { getHexFromBytes } from './getHexFromBytes'; /** @@ -17,5 +18,6 @@ export const getHashFromData = (data: SourceData): string => { const hashedData = sha256.digestSync(); const hashHexFromUint8 = getHexFromBytes(hashedData); + return new Array(64 - hashHexFromUint8.length).join('0') + hashHexFromUint8; }; diff --git a/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts b/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts index 54b83624ad0..8baae17bbe2 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts @@ -56,6 +56,7 @@ export const getPaddedHex = (bigInt: AuthBigInteger): string => { .split('') .map((x: string) => { const invertedNibble = ~parseInt(x, 16) & 0xf; + return '0123456789ABCDEF'.charAt(invertedNibble); }) .join(''); diff --git a/packages/auth/src/providers/cognito/utils/srp/getRandomBytes.ts b/packages/auth/src/providers/cognito/utils/srp/getRandomBytes.ts index 58c4ceaf4ed..151f773519e 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getRandomBytes.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getRandomBytes.ts @@ -1,9 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { getBytesFromHex } from './getBytesFromHex'; import { WordArray } from '@aws-amplify/core/internals/utils'; +import { getBytesFromHex } from './getBytesFromHex'; + /** * Returns a Uint8Array with a sequence of random nBytes * diff --git a/packages/auth/src/providers/cognito/utils/srp/getRandomString.ts b/packages/auth/src/providers/cognito/utils/srp/getRandomString.ts index 097fab42fde..7c32c8814f6 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getRandomString.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getRandomString.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { base64Encoder } from '@aws-amplify/core/internals/utils'; + import { getRandomBytes } from './getRandomBytes'; /** diff --git a/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts b/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts index 06af8a78fed..61afae9971b 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts @@ -7,6 +7,7 @@ import { base64Decoder, base64Encoder, } from '@aws-amplify/core/internals/utils'; + import { textEncoder } from '../textEncoder'; export const getSignatureString = ({ @@ -45,14 +46,13 @@ export const getSignatureString = ({ awsCryptoHash.update(bufConcat); const resultFromAWSCrypto = awsCryptoHash.digestSync(); const signatureString = base64Encoder.convert(resultFromAWSCrypto); + return signatureString; }; const urlB64ToUint8Array = (base64String: string): Uint8Array => { const padding = '='.repeat((4 - (base64String.length % 4)) % 4); - const base64 = (base64String + padding) - .replace(/\-/g, '+') - .replace(/_/g, '/'); + const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); const rawData = base64Decoder.convert(base64); const outputArray = new Uint8Array(rawData.length); @@ -60,5 +60,6 @@ const urlB64ToUint8Array = (base64String: string): Uint8Array => { for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } + return outputArray; }; diff --git a/packages/auth/src/providers/cognito/utils/textEncoder/index.native.ts b/packages/auth/src/providers/cognito/utils/textEncoder/index.native.ts index ce6acecc866..681d5d87429 100644 --- a/packages/auth/src/providers/cognito/utils/textEncoder/index.native.ts +++ b/packages/auth/src/providers/cognito/utils/textEncoder/index.native.ts @@ -2,11 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { loadBuffer } from '@aws-amplify/react-native'; + import { TextEncoder } from './types'; export const textEncoder: TextEncoder = { convert(input) { const Buffer = loadBuffer(); + return new Buffer(input, 'utf8'); }, }; diff --git a/packages/auth/src/providers/cognito/utils/userContextData.native.ts b/packages/auth/src/providers/cognito/utils/userContextData.native.ts index ff5d7f226d5..9268cba0d02 100644 --- a/packages/auth/src/providers/cognito/utils/userContextData.native.ts +++ b/packages/auth/src/providers/cognito/utils/userContextData.native.ts @@ -3,11 +3,7 @@ // TODO: add support after https://amazon-cognito-assets.us-east-1.amazoncognito.com/amazon-cognito-advanced-security-data.min.js can be imported -export function getUserContextData({ - username, - userPoolId, - userPoolClientId, -}: { +export function getUserContextData(_: { username: string; userPoolId: string; userPoolClientId: string; diff --git a/packages/auth/src/providers/cognito/utils/userContextData.ts b/packages/auth/src/providers/cognito/utils/userContextData.ts index d45cc3250ff..43b2a1f3d5a 100644 --- a/packages/auth/src/providers/cognito/utils/userContextData.ts +++ b/packages/auth/src/providers/cognito/utils/userContextData.ts @@ -30,6 +30,7 @@ export function getUserContextData({ const userContextData = { EncodedData: advancedSecurityData, }; + return userContextData; } diff --git a/packages/auth/src/types/inputs.ts b/packages/auth/src/types/inputs.ts index 2e326686ef4..2ea988e227d 100644 --- a/packages/auth/src/types/inputs.ts +++ b/packages/auth/src/types/inputs.ts @@ -2,21 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 import { - AuthUserAttributes, + AuthDevice, AuthUserAttribute, AuthUserAttributeKey, - AuthDevice, + AuthUserAttributes, } from './models'; import { AuthServiceOptions, AuthSignUpOptions } from './options'; -export type AuthConfirmResetPasswordInput< +export interface AuthConfirmResetPasswordInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { username: string; newPassword: string; confirmationCode: string; options?: ServiceOptions; -}; +} /** * The parameters for constructing a Resend Sign Up code input. @@ -24,34 +24,34 @@ export type AuthConfirmResetPasswordInput< * @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 AuthResendSignUpCodeInput< +export interface AuthResendSignUpCodeInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { username: string; options?: ServiceOptions; -}; +} -export type AuthResetPasswordInput< +export interface AuthResetPasswordInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { username: string; options?: ServiceOptions; -}; +} -export type AuthSignInInput< +export interface AuthSignInInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { username: string; password?: string; options?: ServiceOptions; -}; -export type AuthSignOutInput = { +} +export interface AuthSignOutInput { global: boolean; -}; +} export type AuthProvider = 'Amazon' | 'Apple' | 'Facebook' | 'Google'; -export type AuthSignInWithRedirectInput = { +export interface AuthSignInWithRedirectInput { provider?: AuthProvider | { custom: string }; customState?: string; options?: { @@ -66,7 +66,7 @@ export type AuthSignInWithRedirectInput = { */ preferPrivateSession?: boolean; }; -}; +} /** * The parameters for constructing a Sign Up input. @@ -75,14 +75,14 @@ export type AuthSignInWithRedirectInput = { * @param password - the user's password * @param options - optional parameters for the Sign Up process, including user attributes */ -export type AuthSignUpInput< +export interface AuthSignUpInput< ServiceOptions extends AuthSignUpOptions = AuthSignUpOptions, -> = { +> { username: string; password: string; options?: ServiceOptions; -}; +} /** * Constructs a `confirmSignUp` input. @@ -91,13 +91,13 @@ export type AuthSignUpInput< * @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 AuthConfirmSignUpInput< +export interface AuthConfirmSignUpInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { username: string; confirmationCode: string; options?: ServiceOptions; -}; +} /** * Constructs a `confirmSignIn` input. * @@ -105,12 +105,12 @@ export type AuthConfirmSignUpInput< * the sign in process. * @param options - optional parameters for the Confirm Sign In process such as the service options */ -export type AuthConfirmSignInInput< +export interface AuthConfirmSignInInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { challengeResponse: string; options?: ServiceOptions; -}; +} /** * Constructs a `VerifyTOTPSetup` input. @@ -118,12 +118,12 @@ export type AuthConfirmSignInInput< * @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 AuthVerifyTOTPSetupInput< +export interface AuthVerifyTOTPSetupInput< ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { code: string; options?: ServiceOptions; -}; +} /** * Constructs a `updatePassword` input. @@ -131,10 +131,10 @@ export type AuthVerifyTOTPSetupInput< * @param oldPassword - previous password used for `signIn` * @param newPassword - new password to be used for `signIn` */ -export type AuthUpdatePasswordInput = { +export interface AuthUpdatePasswordInput { oldPassword: string; newPassword: string; -}; +} /** * Constructs a `updateUserAttributes` input. @@ -142,26 +142,26 @@ export type AuthUpdatePasswordInput = { * @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 AuthUpdateUserAttributesInput< +export interface AuthUpdateUserAttributesInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { userAttributes: AuthUserAttributes; options?: ServiceOptions; -}; +} /** * Constructs a `updateUserAttributes` input. * @param userAttributes - the user attribute to be updated * @param options - optional parameters for the Update User Attributes process such as the service options. */ -export type AuthUpdateUserAttributeInput< +export interface AuthUpdateUserAttributeInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { userAttribute: AuthUserAttribute; options?: ServiceOptions; -}; +} /* * Constructs a `verifyUserAttribute` input. @@ -170,9 +170,12 @@ export type AuthUpdateUserAttributeInput< * @param confirmationCode - the user attribute verification code sent to email or cellphone * */ -export type AuthConfirmUserAttributeInput< +export interface AuthConfirmUserAttributeInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { userAttributeKey: UserAttributeKey; confirmationCode: string }; +> { + userAttributeKey: UserAttributeKey; + confirmationCode: string; +} /** * Constructs a `sendUserAttributeVerificationCode` request. @@ -180,28 +183,30 @@ export type AuthConfirmUserAttributeInput< * @param userAttributeKey - the user attribute key * @param options - optional parameters for the Resend Attribute Code process such as the service options. */ -export type AuthSendUserAttributeVerificationCodeInput< +export interface AuthSendUserAttributeVerificationCodeInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, ServiceOptions extends AuthServiceOptions = AuthServiceOptions, -> = { +> { userAttributeKey: UserAttributeKey; options?: ServiceOptions; -}; +} /** * Constructs a `deleteUserAttributes` input. * * @param userAttributeKeys - the user attribute keys to be deleted */ -export type AuthDeleteUserAttributesInput< +export interface AuthDeleteUserAttributesInput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { userAttributeKeys: [UserAttributeKey, ...UserAttributeKey[]] }; +> { + userAttributeKeys: [UserAttributeKey, ...UserAttributeKey[]]; +} /** * Constructs a `forgetDevice` input. * * @param device - optional parameter to forget an external device */ -export type AuthForgetDeviceInput = { +export interface AuthForgetDeviceInput { device?: AuthDevice; -}; +} diff --git a/packages/auth/src/types/models.ts b/packages/auth/src/types/models.ts index 08ff0c4f016..9bcc006141d 100644 --- a/packages/auth/src/types/models.ts +++ b/packages/auth/src/types/models.ts @@ -1,15 +1,16 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { SignInOutput } from '../providers/cognito'; import { AuthStandardAttributeKey } from '@aws-amplify/core/internals/utils'; +import { SignInOutput } from '../providers/cognito'; + /** * Additional data that may be returned from Auth APIs. */ -export type AuthAdditionalInfo = { [key: string]: string }; +export type AuthAdditionalInfo = Record; -export type AuthAnyAttribute = string & {}; +export type AuthAnyAttribute = string & NonNullable; /** * Denotes the medium over which a confirmation code was sent. @@ -19,35 +20,35 @@ export type AuthDeliveryMedium = 'EMAIL' | 'SMS' | 'PHONE' | 'UNKNOWN'; /** * Data describing the dispatch of a confirmation code. */ -export type AuthCodeDeliveryDetails< +export interface AuthCodeDeliveryDetails< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { destination?: string; deliveryMedium?: AuthDeliveryMedium; attributeName?: UserAttributeKey; -}; +} /** * Denotes the next step in the Reset Password process. */ export type AuthResetPasswordStep = 'CONFIRM_RESET_PASSWORD_WITH_CODE' | 'DONE'; -export type AuthNextResetPasswordStep< +export interface AuthNextResetPasswordStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { resetPasswordStep: AuthResetPasswordStep; additionalInfo?: AuthAdditionalInfo; codeDeliveryDetails: AuthCodeDeliveryDetails; -}; +} -export type AuthTOTPSetupDetails = { +export interface AuthTOTPSetupDetails { sharedSecret: string; - getSetupUri: (appName: string, accountName?: string) => URL; -}; + getSetupUri(appName: string, accountName?: string): URL; +} export type AuthMFAType = 'SMS' | 'TOTP'; export type AuthAllowedMFATypes = AuthMFAType[]; -export type ContinueSignInWithTOTPSetup = { +export interface ContinueSignInWithTOTPSetup { /** * Auth step requires user to set up TOTP as multifactor authentication by associating an authenticator app * and retrieving an OTP code. @@ -61,8 +62,8 @@ export type ContinueSignInWithTOTPSetup = { */ signInStep: 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP'; totpSetupDetails: AuthTOTPSetupDetails; -}; -export type ConfirmSignInWithTOTPCode = { +} +export interface ConfirmSignInWithTOTPCode { /** * Auth step requires user to use TOTP as multifactor authentication by retriving an OTP code from authenticator app. * @@ -74,9 +75,9 @@ export type ConfirmSignInWithTOTPCode = { * ``` */ signInStep: 'CONFIRM_SIGN_IN_WITH_TOTP_CODE'; -}; +} -export type ContinueSignInWithMFASelection = { +export interface ContinueSignInWithMFASelection { /** * Auth step requires user to select an mfa option (SMS | TOTP) to continue with the sign-in flow. * @@ -89,9 +90,9 @@ export type ContinueSignInWithMFASelection = { */ signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION'; allowedMFATypes?: AuthAllowedMFATypes; -}; +} -export type ConfirmSignInWithCustomChallenge = { +export interface ConfirmSignInWithCustomChallenge { /** * Auth step requires user to respond to a custom challenge. * @@ -103,11 +104,11 @@ export type ConfirmSignInWithCustomChallenge = { */ signInStep: 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE'; additionalInfo?: AuthAdditionalInfo; -}; +} -export type ConfirmSignInWithNewPasswordRequired< +export interface ConfirmSignInWithNewPasswordRequired< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { /** * Auth step requires user to change their password with any required attributes. * @@ -128,9 +129,9 @@ export type ConfirmSignInWithNewPasswordRequired< */ signInStep: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED'; missingAttributes?: UserAttributeKey[]; -}; +} -export type ConfirmSignInWithSMSCode = { +export interface ConfirmSignInWithSMSCode { /** * Auth step requires user to use SMS as multifactor authentication by retrieving a code sent to cellphone. * @@ -143,34 +144,34 @@ export type ConfirmSignInWithSMSCode = { */ signInStep: 'CONFIRM_SIGN_IN_WITH_SMS_CODE'; codeDeliveryDetails?: AuthCodeDeliveryDetails; -}; +} -export type ConfirmSignUpStep = { +export interface ConfirmSignUpStep { /** * Auth step requires to confirm user's sign-up. * * Try calling confirmSignUp. */ signInStep: 'CONFIRM_SIGN_UP'; -}; +} -export type ResetPasswordStep = { +export interface ResetPasswordStep { /** * Auth step requires user to change their password. * * Try calling resetPassword. */ signInStep: 'RESET_PASSWORD'; -}; +} -export type DoneSignInStep = { +export interface DoneSignInStep { /** * The sign-in process is complete. * * No further action is needed. */ signInStep: 'DONE'; -}; +} export type AuthNextSignInStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, @@ -197,12 +198,12 @@ export type AuthUserAttributes< /** * The interface of a user attribute. */ -export type AuthUserAttribute< +export interface AuthUserAttribute< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { attributeKey: UserAttributeKey; value: string; -}; +} /** * A user attribute key type consisting of standard OIDC claims or custom attributes. @@ -233,42 +234,42 @@ export type AuthNextSignUpStep< | DoneSignUpStep; export type AutoSignInCallback = () => Promise; -export type DoneSignUpStep = { +export interface DoneSignUpStep { signUpStep: 'DONE'; -}; +} -export type ConfirmSignUpSignUpStep< +export interface ConfirmSignUpSignUpStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { signUpStep: 'CONFIRM_SIGN_UP'; codeDeliveryDetails: AuthCodeDeliveryDetails; -}; +} -export type AutoSignInSignUpStep< +export interface AutoSignInSignUpStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { signUpStep: 'COMPLETE_AUTO_SIGN_IN'; codeDeliveryDetails?: AuthCodeDeliveryDetails; -}; +} -export type AuthNextUpdateAttributeStep< +export interface AuthNextUpdateAttributeStep< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { updateAttributeStep: AuthUpdateAttributeStep; codeDeliveryDetails?: AuthCodeDeliveryDetails; -}; +} /** * The AWSAuthUser object contains username and userId from the idToken. */ -export type AWSAuthUser = { +export interface AWSAuthUser { username: string; userId: string; -}; +} /** * The AuthDevice object contains id and name of the device. */ -export type AuthDevice = { +export interface AuthDevice { id: string; -}; +} diff --git a/packages/auth/src/types/options.ts b/packages/auth/src/types/options.ts index d026ef3bfb6..2302cd2624f 100644 --- a/packages/auth/src/types/options.ts +++ b/packages/auth/src/types/options.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { AuthUserAttributes, AuthUserAttributeKey } from './models'; +import { AuthUserAttributeKey, AuthUserAttributes } from './models'; /** * Base type for service options. @@ -14,10 +14,10 @@ export type AuthServiceOptions = Record; * @remarks * Particular services may require some of these parameters. */ -export type AuthSignUpOptions< +export interface AuthSignUpOptions< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { userAttributes: AuthUserAttributes; -}; +} export type SignInWithWebUIOptions = ServiceOptions; diff --git a/packages/auth/src/types/outputs.ts b/packages/auth/src/types/outputs.ts index 5e1d65cd3be..c21b44991eb 100644 --- a/packages/auth/src/types/outputs.ts +++ b/packages/auth/src/types/outputs.ts @@ -2,41 +2,41 @@ // SPDX-License-Identifier: Apache-2.0 import { - AuthUserAttributeKey, + AuthNextResetPasswordStep, AuthNextSignInStep, AuthNextSignUpStep, - AuthNextResetPasswordStep, AuthNextUpdateAttributeStep, + AuthUserAttributeKey, } from './models'; -export type AuthSignInOutput< +export interface AuthSignInOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { isSignedIn: boolean; nextStep: AuthNextSignInStep; -}; +} -export type AuthSignUpOutput< +export interface AuthSignUpOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { isSignUpComplete: boolean; userId?: string; nextStep: AuthNextSignUpStep; -}; +} -export type AuthResetPasswordOutput< +export interface AuthResetPasswordOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { isPasswordReset: boolean; nextStep: AuthNextResetPasswordStep; -}; +} -export type AuthUpdateUserAttributeOutput< +export interface AuthUpdateUserAttributeOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, -> = { +> { isUpdated: boolean; nextStep: AuthNextUpdateAttributeStep; -}; +} export type AuthUpdateUserAttributesOutput< UserAttributeKey extends AuthUserAttributeKey = AuthUserAttributeKey, diff --git a/packages/auth/src/utils/openAuthSession.native.ts b/packages/auth/src/utils/openAuthSession.native.ts index 9315fe86fd4..24869ecc56a 100644 --- a/packages/auth/src/utils/openAuthSession.native.ts +++ b/packages/auth/src/utils/openAuthSession.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAmplifyWebBrowser } from '@aws-amplify/react-native'; + import { OpenAuthSession, OpenAuthSessionResult } from './types'; export const openAuthSession: OpenAuthSession = async ( @@ -18,6 +19,7 @@ export const openAuthSession: OpenAuthSession = async ( if (!redirectUrl) { return { type: 'canceled' }; } + return { type: 'success', url: redirectUrl }; } catch (error) { return { type: 'error', error }; diff --git a/packages/auth/src/utils/types.ts b/packages/auth/src/utils/types.ts index 65e545cbe93..4a2ddc53ac9 100644 --- a/packages/auth/src/utils/types.ts +++ b/packages/auth/src/utils/types.ts @@ -9,16 +9,16 @@ export type OpenAuthSession = ( type OpenAuthSessionResultType = 'canceled' | 'success' | 'error'; -export type OpenAuthSessionResult = { +export interface OpenAuthSessionResult { type: OpenAuthSessionResultType; error?: unknown; url?: string; -}; +} -export type AmplifyWebBrowser = { - openAuthSessionAsync: ( +export interface AmplifyWebBrowser { + openAuthSessionAsync( url: string, redirectUrls: string[], prefersEphemeralSession?: boolean, - ) => Promise; -}; + ): Promise; +} diff --git a/packages/auth/tslint.json b/packages/auth/tslint.json deleted file mode 100644 index 1bb9e144d24..00000000000 --- a/packages/auth/tslint.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "defaultSeverity": "error", - "plugins": ["prettier"], - "extends": [], - "jsRules": {}, - "rules": { - "prefer-const": true, - "max-line-length": [true, 120], - "no-empty-interface": true, - "no-var-keyword": true, - "object-literal-shorthand": true, - "no-eval": true, - "space-before-function-paren": [ - true, - { - "anonymous": "never", - "named": "never" - } - ], - "no-parameter-reassignment": true, - "align": [true, "parameters"], - "no-duplicate-imports": true, - "one-variable-per-declaration": [false, "ignore-for-loop"], - "triple-equals": [true, "allow-null-check"], - "comment-format": [true, "check-space"], - "indent": [false], - "whitespace": [ - false, - "check-branch", - "check-decl", - "check-operator", - "check-preblock" - ], - "eofline": true, - "variable-name": [ - true, - "check-format", - "allow-pascal-case", - "allow-snake-case", - "allow-leading-underscore" - ], - "semicolon": [true, "always", "ignore-interfaces"] - }, - "rulesDirectory": [] -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 05c753c7e6b..f17968928c6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,6 +13,7 @@ export { TokenProvider, AuthTokens, FetchAuthSessionOptions, + AuthSession, CredentialsAndIdentityIdProvider, CredentialsAndIdentityId, Identity, diff --git a/packages/core/src/singleton/apis/fetchAuthSession.ts b/packages/core/src/singleton/apis/fetchAuthSession.ts index 858edcd1cd9..f7e1248ae54 100644 --- a/packages/core/src/singleton/apis/fetchAuthSession.ts +++ b/packages/core/src/singleton/apis/fetchAuthSession.ts @@ -2,10 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '../Amplify'; -import { FetchAuthSessionOptions } from '../Auth/types'; +import { AuthSession, FetchAuthSessionOptions } from '../Auth/types'; import { fetchAuthSession as fetchAuthSessionInternal } from './internal/fetchAuthSession'; -export const fetchAuthSession = (options?: FetchAuthSessionOptions) => { +export const fetchAuthSession = ( + options?: FetchAuthSessionOptions, +): Promise => { return fetchAuthSessionInternal(Amplify, options); };