@aws-amplify/auth 6.11.3 → 6.11.4-unstable.a7df116.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/providers/cognito/credentialsProvider/IdentityIdProvider.js +13 -36
- package/dist/cjs/providers/cognito/credentialsProvider/IdentityIdProvider.js.map +1 -1
- package/dist/cjs/providers/cognito/credentialsProvider/credentialsProvider.js +12 -13
- package/dist/cjs/providers/cognito/credentialsProvider/credentialsProvider.js.map +1 -1
- package/dist/cjs/providers/cognito/utils/oauth/completeOAuthFlow.js +2 -1
- package/dist/cjs/providers/cognito/utils/oauth/completeOAuthFlow.js.map +1 -1
- package/dist/esm/providers/cognito/credentialsProvider/IdentityIdProvider.mjs +14 -37
- package/dist/esm/providers/cognito/credentialsProvider/IdentityIdProvider.mjs.map +1 -1
- package/dist/esm/providers/cognito/credentialsProvider/credentialsProvider.mjs +12 -13
- package/dist/esm/providers/cognito/credentialsProvider/credentialsProvider.mjs.map +1 -1
- package/dist/esm/providers/cognito/utils/oauth/completeOAuthFlow.mjs +2 -1
- package/dist/esm/providers/cognito/utils/oauth/completeOAuthFlow.mjs.map +1 -1
- package/package.json +106 -106
- package/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +14 -39
- package/src/providers/cognito/credentialsProvider/credentialsProvider.ts +16 -14
- package/src/providers/cognito/utils/oauth/completeOAuthFlow.ts +3 -1
|
@@ -8,7 +8,6 @@ const core_1 = require("@aws-amplify/core");
|
|
|
8
8
|
const AuthError_1 = require("../../../errors/AuthError");
|
|
9
9
|
const parsers_1 = require("../../../foundation/parsers");
|
|
10
10
|
const utils_1 = require("./utils");
|
|
11
|
-
const logger = new core_1.ConsoleLogger('CognitoIdentityIdProvider');
|
|
12
11
|
/**
|
|
13
12
|
* Provides a Cognito identityId
|
|
14
13
|
*
|
|
@@ -21,42 +20,20 @@ const logger = new core_1.ConsoleLogger('CognitoIdentityIdProvider');
|
|
|
21
20
|
async function cognitoIdentityIdProvider({ tokens, authConfig, identityIdStore, }) {
|
|
22
21
|
identityIdStore.setAuthConfig({ Cognito: authConfig });
|
|
23
22
|
// will return null only if there is no identityId cached or if there is an error retrieving it
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
// If there is existing primary identityId in-memory return that
|
|
28
|
-
if (identityId && identityId.type === 'primary') {
|
|
29
|
-
return identityId.id;
|
|
30
|
-
}
|
|
31
|
-
else {
|
|
32
|
-
const logins = tokens.idToken
|
|
33
|
-
? (0, utils_1.formLoginsMap)(tokens.idToken.toString())
|
|
34
|
-
: {};
|
|
35
|
-
const generatedIdentityId = await generateIdentityId(logins, authConfig);
|
|
36
|
-
if (identityId && identityId.id === generatedIdentityId) {
|
|
37
|
-
logger.debug(`The guest identity ${identityId.id} has become the primary identity.`);
|
|
38
|
-
}
|
|
39
|
-
identityId = {
|
|
40
|
-
id: generatedIdentityId,
|
|
41
|
-
type: 'primary',
|
|
42
|
-
};
|
|
43
|
-
}
|
|
23
|
+
const identityId = await identityIdStore.loadIdentityId();
|
|
24
|
+
if (identityId) {
|
|
25
|
+
return identityId.id;
|
|
44
26
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
// Store in-memory or local storage depending on guest or primary identityId
|
|
58
|
-
identityIdStore.storeIdentityId(identityId);
|
|
59
|
-
return identityId.id;
|
|
27
|
+
const logins = tokens?.idToken
|
|
28
|
+
? (0, utils_1.formLoginsMap)(tokens.idToken.toString())
|
|
29
|
+
: {};
|
|
30
|
+
const generatedIdentityId = await generateIdentityId(logins, authConfig);
|
|
31
|
+
// Store generated identityId
|
|
32
|
+
identityIdStore.storeIdentityId({
|
|
33
|
+
id: generatedIdentityId,
|
|
34
|
+
type: tokens ? 'primary' : 'guest',
|
|
35
|
+
});
|
|
36
|
+
return generatedIdentityId;
|
|
60
37
|
}
|
|
61
38
|
exports.cognitoIdentityIdProvider = cognitoIdentityIdProvider;
|
|
62
39
|
async function generateIdentityId(logins, authConfig) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IdentityIdProvider.js","sources":["../../../../../src/providers/cognito/credentialsProvider/IdentityIdProvider.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.cognitoIdentityIdProvider = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst AuthError_1 = require(\"../../../errors/AuthError\");\nconst parsers_1 = require(\"../../../foundation/parsers\");\nconst utils_1 = require(\"./utils\");\
|
|
1
|
+
{"version":3,"file":"IdentityIdProvider.js","sources":["../../../../../src/providers/cognito/credentialsProvider/IdentityIdProvider.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.cognitoIdentityIdProvider = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst AuthError_1 = require(\"../../../errors/AuthError\");\nconst parsers_1 = require(\"../../../foundation/parsers\");\nconst utils_1 = require(\"./utils\");\n/**\n * Provides a Cognito identityId\n *\n * @param tokens - The AuthTokens received after SignIn\n * @returns string\n * @throws configuration exceptions: `InvalidIdentityPoolIdException`\n * - Auth errors that may arise from misconfiguration.\n * @throws service exceptions: {@link GetIdException }\n */\nasync function cognitoIdentityIdProvider({ tokens, authConfig, identityIdStore, }) {\n identityIdStore.setAuthConfig({ Cognito: authConfig });\n // will return null only if there is no identityId cached or if there is an error retrieving it\n const identityId = await identityIdStore.loadIdentityId();\n if (identityId) {\n return identityId.id;\n }\n const logins = tokens?.idToken\n ? (0, utils_1.formLoginsMap)(tokens.idToken.toString())\n : {};\n const generatedIdentityId = await generateIdentityId(logins, authConfig);\n // Store generated identityId\n identityIdStore.storeIdentityId({\n id: generatedIdentityId,\n type: tokens ? 'primary' : 'guest',\n });\n return generatedIdentityId;\n}\nexports.cognitoIdentityIdProvider = cognitoIdentityIdProvider;\nasync function generateIdentityId(logins, authConfig) {\n const identityPoolId = authConfig?.identityPoolId;\n const region = (0, parsers_1.getRegionFromIdentityPoolId)(identityPoolId);\n // IdentityId is absent so get it using IdentityPoolId with Cognito's GetId API\n const idResult = \n // for a first-time user, this will return a brand new identity\n // for a returning user, this will retrieve the previous identity assocaited with the logins\n (await (0, core_1.getId)({\n region,\n }, {\n IdentityPoolId: identityPoolId,\n Logins: logins,\n })).IdentityId;\n if (!idResult) {\n throw new AuthError_1.AuthError({\n name: 'GetIdResponseException',\n message: 'Received undefined response from getId operation',\n recoverySuggestion: 'Make sure to pass a valid identityPoolId in the configuration.',\n });\n }\n return idResult;\n}\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAC9D,OAAO,CAAC,yBAAyB,GAAG,KAAK,CAAC,CAAC;AAC3C,MAAM,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;AAC5C,MAAM,WAAW,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AACzD,MAAM,SAAS,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAAC;AACzD,MAAM,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,yBAAyB,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe,GAAG,EAAE;AACnF,IAAI,eAAe,CAAC,aAAa,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;AAC3D;AACA,IAAI,MAAM,UAAU,GAAG,MAAM,eAAe,CAAC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;AACL,IAAI,OAAO,QAAQ,CAAC;AACpB;;"}
|
|
@@ -92,11 +92,10 @@ class CognitoAWSCredentialsAndIdentityIdProvider {
|
|
|
92
92
|
},
|
|
93
93
|
identityId,
|
|
94
94
|
};
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
res.identityId = identityIdRes;
|
|
95
|
+
if (clientResult.IdentityId) {
|
|
96
|
+
res.identityId = clientResult.IdentityId;
|
|
98
97
|
this._identityIdStore.storeIdentityId({
|
|
99
|
-
id:
|
|
98
|
+
id: clientResult.IdentityId,
|
|
100
99
|
type: 'guest',
|
|
101
100
|
});
|
|
102
101
|
}
|
|
@@ -133,6 +132,7 @@ class CognitoAWSCredentialsAndIdentityIdProvider {
|
|
|
133
132
|
if (clientResult.Credentials &&
|
|
134
133
|
clientResult.Credentials.AccessKeyId &&
|
|
135
134
|
clientResult.Credentials.SecretKey) {
|
|
135
|
+
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
136
136
|
const res = {
|
|
137
137
|
credentials: {
|
|
138
138
|
accessKeyId: clientResult.Credentials.AccessKeyId,
|
|
@@ -142,21 +142,20 @@ class CognitoAWSCredentialsAndIdentityIdProvider {
|
|
|
142
142
|
},
|
|
143
143
|
identityId,
|
|
144
144
|
};
|
|
145
|
+
if (clientResult.IdentityId) {
|
|
146
|
+
res.identityId = clientResult.IdentityId;
|
|
147
|
+
// note: the following call removes guest identityId from the persistent store (localStorage)
|
|
148
|
+
this._identityIdStore.storeIdentityId({
|
|
149
|
+
id: clientResult.IdentityId,
|
|
150
|
+
type: 'primary',
|
|
151
|
+
});
|
|
152
|
+
}
|
|
145
153
|
// Store the credentials in-memory along with the expiration
|
|
146
154
|
this._credentialsAndIdentityId = {
|
|
147
155
|
...res,
|
|
148
156
|
isAuthenticatedCreds: true,
|
|
149
157
|
associatedIdToken: authTokens.idToken?.toString(),
|
|
150
158
|
};
|
|
151
|
-
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
152
|
-
const identityIdRes = clientResult.IdentityId;
|
|
153
|
-
if (identityIdRes) {
|
|
154
|
-
res.identityId = identityIdRes;
|
|
155
|
-
this._identityIdStore.storeIdentityId({
|
|
156
|
-
id: identityIdRes,
|
|
157
|
-
type: 'primary',
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
159
|
return res;
|
|
161
160
|
}
|
|
162
161
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credentialsProvider.js","sources":["../../../../../src/providers/cognito/credentialsProvider/credentialsProvider.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CognitoAWSCredentialsAndIdentityIdProvider = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst AuthError_1 = require(\"../../../errors/AuthError\");\nconst parsers_1 = require(\"../../../foundation/parsers\");\nconst types_1 = require(\"../utils/types\");\nconst IdentityIdProvider_1 = require(\"./IdentityIdProvider\");\nconst utils_2 = require(\"./utils\");\nconst logger = new core_1.ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nclass CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n (0, utils_1.assertIdentityPoolIdConfig)(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await (0, IdentityIdProvider_1.cognitoIdentityIdProvider)({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n (0, types_1.assertIdTokenInAuthTokens)(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = (0, parsers_1.getRegionFromIdentityPoolId)(authConfig.identityPoolId);\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n const clientResult = await (0, core_1.getCredentialsForIdentity)({ region }, {\n IdentityId: identityId,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError_1.AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? (0, utils_2.formLoginsMap)(authTokens.idToken.toString())\n : {};\n const region = (0, parsers_1.getRegionFromIdentityPoolId)(authConfig.identityPoolId);\n const clientResult = await (0, core_1.getCredentialsForIdentity)({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'primary',\n });\n }\n return res;\n }\n else {\n throw new AuthError_1.AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\nexports.CognitoAWSCredentialsAndIdentityIdProvider = CognitoAWSCredentialsAndIdentityIdProvider;\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAC9D,OAAO,CAAC,0CAA0C,GAAG,KAAK,CAAC,CAAC;AAC5D,MAAM,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;AAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,mCAAmC,CAAC,CAAC;AAC7D,MAAM,WAAW,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AACzD,MAAM,SAAS,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAAC;AACzD,MAAM,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;AAC1C,MAAM,oBAAoB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC;AAC7D,MAAM,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;AACnC,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,aAAa,CAAC,4BAA4B,CAAC,CAAC;AACtE,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACvC,MAAM,0CAA0C,CAAC;AACjD,IAAI,WAAW,CAAC,eAAe,EAAE;AACjC,QAAQ,IAAI,CAAC,uBAAuB,GAAG,CAAC,CAAC;AACzC,QAAQ,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;AAChD,KAAK;AACL,IAAI,MAAM,6BAA6B,GAAG;AAC1C,QAAQ,MAA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AuB,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC;AAClF,YAAY,MAAM,aAAa,GAAG,YAAY,CAAC,UAAU,CAAC;AAC1D,YAAY,IAAI,aAAa,EAAE;AAC/B,gBAAgB,GAAG,CAAC,UAAU,GAAG,aAAa,CAAC;AAC/C,gBAAgB,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAAC;AACtD,oBAAoB,EAAE,EAAE,aAAa;AACrC,oBAAoB,IAAI,EAAE,SAAS;AACnC,iBAAiB,CAAC,CAAC;AACnB,aAAa;AACb,YAAY,OAAO,GAAG,CAAC;AACvB,SAAS;AACT,aAAa;AACb,YAAY,MAAM,IAAI,WAAW,CAAC,SAAS,CAAC;AAC5C,gBAAgB,IAAI,EAAE,sBAAsB;AAC5C,gBAAgB,OAAO,EAAE,CAAC,0EAA0E,CAAC;AACrG,aAAa,CAAC,CAAC;AACf,SAAS;AACT,KAAK;AACL,IAAI,SAAS,GAAG;AAChB,QAAQ,OAAO,IAAI,CAAC,uBAAuB,KAAK,SAAS;AACzD,cAAc,IAAI;AAClB,cAAc,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AACzD,KAAK;AACL,IAAI,eAAe,CAAC,MAAM,EAAE;AAC5B,QAAQ,QAAQ,CAAC,CAAC,MAAM;AACxB,YAAY,CAAC,CAAC,IAAI,CAAC,yBAAyB,EAAE,iBAAiB;AAC/D,YAAY,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE;AACtC,gBAAgB,IAAI,CAAC,yBAAyB,CAAC,iBAAiB,EAAE;AAClE,KAAK;AACL,CAAC;AACD,OAAO,CAAC,0CAA0C,GAAG,0CAA0C;;"}
|
|
1
|
+
{"version":3,"file":"credentialsProvider.js","sources":["../../../../../src/providers/cognito/credentialsProvider/credentialsProvider.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CognitoAWSCredentialsAndIdentityIdProvider = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst AuthError_1 = require(\"../../../errors/AuthError\");\nconst parsers_1 = require(\"../../../foundation/parsers\");\nconst types_1 = require(\"../utils/types\");\nconst IdentityIdProvider_1 = require(\"./IdentityIdProvider\");\nconst utils_2 = require(\"./utils\");\nconst logger = new core_1.ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nclass CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n (0, utils_1.assertIdentityPoolIdConfig)(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await (0, IdentityIdProvider_1.cognitoIdentityIdProvider)({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n (0, types_1.assertIdTokenInAuthTokens)(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = (0, parsers_1.getRegionFromIdentityPoolId)(authConfig.identityPoolId);\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n const clientResult = await (0, core_1.getCredentialsForIdentity)({ region }, {\n IdentityId: identityId,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError_1.AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? (0, utils_2.formLoginsMap)(authTokens.idToken.toString())\n : {};\n const region = (0, parsers_1.getRegionFromIdentityPoolId)(authConfig.identityPoolId);\n const clientResult = await (0, core_1.getCredentialsForIdentity)({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n // note: the following call removes guest identityId from the persistent store (localStorage)\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'primary',\n });\n }\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n return res;\n }\n else {\n throw new AuthError_1.AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\nexports.CognitoAWSCredentialsAndIdentityIdProvider = CognitoAWSCredentialsAndIdentityIdProvider;\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAC9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;AAC5C,gBAAgB,IAAI,EAAE,sBAAsB;AAC5C,gBAAgB,OAAO,EAAE,CAAC,0EAA0E,CAAC;AACrG,aAAa,CAAC,CAAC;AACf,SAAS;AACT,KAAK;AACL,IAAI,SAAS,GAAG;AAChB,QAAQ,OAAO,IAAI,CAAC,uBAAuB,KAAK,SAAS;AACzD,cAAc,IAAI;AAClB,cAAc,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AACzD,KAAK;AACL,IAAI,eAAe,CAAC,MAAM,EAAE;AAC5B,QAAQ,QAAQ,CAAC,CAAC,MAAM;AACxB,YAAY,CAAC,CAAC,IAAI,CAAC,yBAAyB,EAAE,iBAAiB;AAC/D,YAAY,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE;AACtC,gBAAgB,IAAI,CAAC,yBAAyB,CAAC,iBAAiB,EAAE;AAClE,KAAK;AACL,CAAC;AACD,OAAO,CAAC,0CAA0C,GAAG,0CAA0C;;"}
|
|
@@ -145,6 +145,8 @@ const completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {
|
|
|
145
145
|
// e.g. `getCurrentUser()` below, so it allows every inflight async calls to
|
|
146
146
|
// `fetchAuthSession` can be resolved
|
|
147
147
|
(0, inflightPromise_1.resolveAndClearInflightPromises)();
|
|
148
|
+
// clear history before sending out final Hub events
|
|
149
|
+
clearHistory(redirectUri);
|
|
148
150
|
if (isCustomState(state)) {
|
|
149
151
|
core_1.Hub.dispatch('auth', {
|
|
150
152
|
event: 'customOAuthState',
|
|
@@ -153,7 +155,6 @@ const completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {
|
|
|
153
155
|
}
|
|
154
156
|
core_1.Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', utils_1.AMPLIFY_SYMBOL);
|
|
155
157
|
await (0, dispatchSignedInHubEvent_1.dispatchSignedInHubEvent)();
|
|
156
|
-
clearHistory(redirectUri);
|
|
157
158
|
};
|
|
158
159
|
const isCustomState = (state) => {
|
|
159
160
|
return /-/.test(state);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"completeOAuthFlow.js","sources":["../../../../../../src/providers/cognito/utils/oauth/completeOAuthFlow.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.completeOAuthFlow = void 0;\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst core_1 = require(\"@aws-amplify/core\");\nconst cacheTokens_1 = require(\"../../tokenProvider/cacheTokens\");\nconst dispatchSignedInHubEvent_1 = require(\"../dispatchSignedInHubEvent\");\nconst tokenProvider_1 = require(\"../../tokenProvider\");\nconst createOAuthError_1 = require(\"./createOAuthError\");\nconst inflightPromise_1 = require(\"./inflightPromise\");\nconst validateState_1 = require(\"./validateState\");\nconst oAuthStore_1 = require(\"./oAuthStore\");\nconst completeOAuthFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, responseType, domain, preferPrivateSession, }) => {\n const urlParams = new utils_1.AmplifyUrl(currentUrl);\n const error = urlParams.searchParams.get('error');\n const errorMessage = urlParams.searchParams.get('error_description');\n if (error) {\n throw (0, createOAuthError_1.createOAuthError)(errorMessage ?? error);\n }\n if (responseType === 'code') {\n return handleCodeFlow({\n currentUrl,\n userAgentValue,\n clientId,\n redirectUri,\n domain,\n preferPrivateSession,\n });\n }\n return handleImplicitFlow({\n currentUrl,\n redirectUri,\n preferPrivateSession,\n });\n};\nexports.completeOAuthFlow = completeOAuthFlow;\nconst handleCodeFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, domain, preferPrivateSession, }) => {\n /* Convert URL into an object with parameters as keys\n{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */\n const url = new utils_1.AmplifyUrl(currentUrl);\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n // if `code` or `state` is not presented in the redirect url, most likely\n // that the end user cancelled the inflight oauth flow by:\n // 1. clicking the back button of browser\n // 2. closing the provider hosted UI page and coming back to the app\n if (!code || !state) {\n throw (0, createOAuthError_1.createOAuthError)('User cancelled OAuth flow.');\n }\n // may throw error is being caught in attemptCompleteOAuthFlow.ts\n const validatedState = await (0, validateState_1.validateState)(state);\n const oAuthTokenEndpoint = 'https://' + domain + '/oauth2/token';\n // TODO(v6): check hub events\n // dispatchAuthEvent(\n // \t'codeFlow',\n // \t{},\n // \t`Retrieving tokens from ${oAuthTokenEndpoint}`\n // );\n const codeVerifier = await oAuthStore_1.oAuthStore.loadPKCE();\n const oAuthTokenBody = {\n grant_type: 'authorization_code',\n code,\n client_id: clientId,\n redirect_uri: redirectUri,\n ...(codeVerifier ? { code_verifier: codeVerifier } : {}),\n };\n const body = Object.entries(oAuthTokenBody)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n const { access_token, refresh_token: refreshToken, id_token, error, error_message: errorMessage, token_type, expires_in, } = await (await fetch(oAuthTokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n [utils_1.USER_AGENT_HEADER]: userAgentValue,\n },\n body,\n })).json();\n if (error) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw (0, createOAuthError_1.createOAuthError)(errorMessage ?? error);\n }\n const username = (access_token && (0, core_1.decodeJWT)(access_token).payload.username) ?? 'username';\n await (0, cacheTokens_1.cacheCognitoTokens)({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n RefreshToken: refreshToken,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst handleImplicitFlow = async ({ currentUrl, redirectUri, preferPrivateSession, }) => {\n // hash is `null` if `#` doesn't exist on URL\n const url = new utils_1.AmplifyUrl(currentUrl);\n const { id_token, access_token, state, token_type, expires_in, error_description, error, } = (url.hash ?? '#')\n .substring(1) // Remove # from returned code\n .split('&')\n .map(pairings => pairings.split('='))\n .reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {\n id_token: undefined,\n access_token: undefined,\n state: undefined,\n token_type: undefined,\n expires_in: undefined,\n error_description: undefined,\n error: undefined,\n });\n if (error) {\n throw (0, createOAuthError_1.createOAuthError)(error_description ?? error);\n }\n if (!access_token) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw (0, createOAuthError_1.createOAuthError)('No access token returned from OAuth flow.');\n }\n const validatedState = await (0, validateState_1.validateState)(state);\n const username = (access_token && (0, core_1.decodeJWT)(access_token).payload.username) ?? 'username';\n await (0, cacheTokens_1.cacheCognitoTokens)({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {\n await tokenProvider_1.tokenOrchestrator.setOAuthMetadata({\n oauthSignIn: true,\n });\n await oAuthStore_1.oAuthStore.clearOAuthData();\n await oAuthStore_1.oAuthStore.storeOAuthSignIn(true, preferPrivateSession);\n // this should be called before any call that involves `fetchAuthSession`\n // e.g. `getCurrentUser()` below, so it allows every inflight async calls to\n // `fetchAuthSession` can be resolved\n (0, inflightPromise_1.resolveAndClearInflightPromises)();\n if (isCustomState(state)) {\n core_1.Hub.dispatch('auth', {\n event: 'customOAuthState',\n data: (0, utils_1.urlSafeDecode)(getCustomState(state)),\n }, 'Auth', utils_1.AMPLIFY_SYMBOL);\n }\n core_1.Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', utils_1.AMPLIFY_SYMBOL);\n await (0, dispatchSignedInHubEvent_1.dispatchSignedInHubEvent)();\n clearHistory(redirectUri);\n};\nconst isCustomState = (state) => {\n return /-/.test(state);\n};\nconst getCustomState = (state) => {\n return state.split('-').splice(1).join('-');\n};\nconst clearHistory = (redirectUri) => {\n if (typeof window !== 'undefined' && typeof window.history !== 'undefined')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use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.completeOAuthFlow = void 0;\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst core_1 = require(\"@aws-amplify/core\");\nconst cacheTokens_1 = require(\"../../tokenProvider/cacheTokens\");\nconst dispatchSignedInHubEvent_1 = require(\"../dispatchSignedInHubEvent\");\nconst tokenProvider_1 = require(\"../../tokenProvider\");\nconst createOAuthError_1 = require(\"./createOAuthError\");\nconst inflightPromise_1 = require(\"./inflightPromise\");\nconst validateState_1 = require(\"./validateState\");\nconst oAuthStore_1 = require(\"./oAuthStore\");\nconst completeOAuthFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, responseType, domain, preferPrivateSession, }) => {\n const urlParams = new utils_1.AmplifyUrl(currentUrl);\n const error = urlParams.searchParams.get('error');\n const errorMessage = urlParams.searchParams.get('error_description');\n if (error) {\n throw (0, createOAuthError_1.createOAuthError)(errorMessage ?? error);\n }\n if (responseType === 'code') {\n return handleCodeFlow({\n currentUrl,\n userAgentValue,\n clientId,\n redirectUri,\n domain,\n preferPrivateSession,\n });\n }\n return handleImplicitFlow({\n currentUrl,\n redirectUri,\n preferPrivateSession,\n });\n};\nexports.completeOAuthFlow = completeOAuthFlow;\nconst handleCodeFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, domain, preferPrivateSession, }) => {\n /* Convert URL into an object with parameters as keys\n{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */\n const url = new utils_1.AmplifyUrl(currentUrl);\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n // if `code` or `state` is not presented in the redirect url, most likely\n // that the end user cancelled the inflight oauth flow by:\n // 1. clicking the back button of browser\n // 2. closing the provider hosted UI page and coming back to the app\n if (!code || !state) {\n throw (0, createOAuthError_1.createOAuthError)('User cancelled OAuth flow.');\n }\n // may throw error is being caught in attemptCompleteOAuthFlow.ts\n const validatedState = await (0, validateState_1.validateState)(state);\n const oAuthTokenEndpoint = 'https://' + domain + '/oauth2/token';\n // TODO(v6): check hub events\n // dispatchAuthEvent(\n // \t'codeFlow',\n // \t{},\n // \t`Retrieving tokens from ${oAuthTokenEndpoint}`\n // );\n const codeVerifier = await oAuthStore_1.oAuthStore.loadPKCE();\n const oAuthTokenBody = {\n grant_type: 'authorization_code',\n code,\n client_id: clientId,\n redirect_uri: redirectUri,\n ...(codeVerifier ? { code_verifier: codeVerifier } : {}),\n };\n const body = Object.entries(oAuthTokenBody)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n const { access_token, refresh_token: refreshToken, id_token, error, error_message: errorMessage, token_type, expires_in, } = await (await fetch(oAuthTokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n [utils_1.USER_AGENT_HEADER]: userAgentValue,\n },\n body,\n })).json();\n if (error) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw (0, createOAuthError_1.createOAuthError)(errorMessage ?? error);\n }\n const username = (access_token && (0, core_1.decodeJWT)(access_token).payload.username) ?? 'username';\n await (0, cacheTokens_1.cacheCognitoTokens)({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n RefreshToken: refreshToken,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst handleImplicitFlow = async ({ currentUrl, redirectUri, preferPrivateSession, }) => {\n // hash is `null` if `#` doesn't exist on URL\n const url = new utils_1.AmplifyUrl(currentUrl);\n const { id_token, access_token, state, token_type, expires_in, error_description, error, } = (url.hash ?? '#')\n .substring(1) // Remove # from returned code\n .split('&')\n .map(pairings => pairings.split('='))\n .reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {\n id_token: undefined,\n access_token: undefined,\n state: undefined,\n token_type: undefined,\n expires_in: undefined,\n error_description: undefined,\n error: undefined,\n });\n if (error) {\n throw (0, createOAuthError_1.createOAuthError)(error_description ?? error);\n }\n if (!access_token) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw (0, createOAuthError_1.createOAuthError)('No access token returned from OAuth flow.');\n }\n const validatedState = await (0, validateState_1.validateState)(state);\n const username = (access_token && (0, core_1.decodeJWT)(access_token).payload.username) ?? 'username';\n await (0, cacheTokens_1.cacheCognitoTokens)({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {\n await tokenProvider_1.tokenOrchestrator.setOAuthMetadata({\n oauthSignIn: true,\n });\n await oAuthStore_1.oAuthStore.clearOAuthData();\n await oAuthStore_1.oAuthStore.storeOAuthSignIn(true, preferPrivateSession);\n // this should be called before any call that involves `fetchAuthSession`\n // e.g. `getCurrentUser()` below, so it allows every inflight async calls to\n // `fetchAuthSession` can be resolved\n (0, inflightPromise_1.resolveAndClearInflightPromises)();\n // clear history before sending out final Hub events\n clearHistory(redirectUri);\n if (isCustomState(state)) {\n core_1.Hub.dispatch('auth', {\n event: 'customOAuthState',\n data: (0, utils_1.urlSafeDecode)(getCustomState(state)),\n }, 'Auth', utils_1.AMPLIFY_SYMBOL);\n }\n core_1.Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', utils_1.AMPLIFY_SYMBOL);\n await (0, dispatchSignedInHubEvent_1.dispatchSignedInHubEvent)();\n};\nconst isCustomState = (state) => {\n return /-/.test(state);\n};\nconst getCustomState = (state) => {\n return state.split('-').splice(1).join('-');\n};\nconst clearHistory = (redirectUri) => {\n if (typeof window !== 'undefined' && typeof window.history !== 'undefined') {\n window.history.replaceState(window.history.state, '', redirectUri);\n }\n};\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,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Q,CAAC,MAAM,EAAE;AACpC,YAAY,KAAK,EAAE,kBAAkB;AACrC,YAAY,IAAI,EAAE,IAAI,OAAO,CAAC,aAAa,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC;AACnE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;AAC3C,KAAK;AACL,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,oBAAoB,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;AACjG,IAAI,MAAM,IAAI,0BAA0B,CAAC,wBAAwB,GAAG,CAAC;AACrE,CAAC,CAAC;AACF,MAAM,aAAa,GAAG,CAAC,KAAK,KAAK;AACjC,IAAI,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC,CAAC;AACF,MAAM,cAAc,GAAG,CAAC,KAAK,KAAK;AAClC,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC,CAAC;AACF,MAAM,YAAY,GAAG,CAAC,WAAW,KAAK;AACtC,IAAI,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,WAAW,EAAE;AAChF,QAAQ,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,WAAW,CAAC,CAAC;AAC3E,KAAK;AACL,CAAC;;"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getId } from '@aws-amplify/core';
|
|
2
2
|
import { AuthError } from '../../../errors/AuthError.mjs';
|
|
3
3
|
import { getRegionFromIdentityPoolId } from '../../../foundation/parsers/regionParsers.mjs';
|
|
4
4
|
import { formLoginsMap } from './utils.mjs';
|
|
5
5
|
|
|
6
6
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
7
7
|
// SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
const logger = new ConsoleLogger('CognitoIdentityIdProvider');
|
|
9
8
|
/**
|
|
10
9
|
* Provides a Cognito identityId
|
|
11
10
|
*
|
|
@@ -18,42 +17,20 @@ const logger = new ConsoleLogger('CognitoIdentityIdProvider');
|
|
|
18
17
|
async function cognitoIdentityIdProvider({ tokens, authConfig, identityIdStore, }) {
|
|
19
18
|
identityIdStore.setAuthConfig({ Cognito: authConfig });
|
|
20
19
|
// will return null only if there is no identityId cached or if there is an error retrieving it
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
// If there is existing primary identityId in-memory return that
|
|
25
|
-
if (identityId && identityId.type === 'primary') {
|
|
26
|
-
return identityId.id;
|
|
27
|
-
}
|
|
28
|
-
else {
|
|
29
|
-
const logins = tokens.idToken
|
|
30
|
-
? formLoginsMap(tokens.idToken.toString())
|
|
31
|
-
: {};
|
|
32
|
-
const generatedIdentityId = await generateIdentityId(logins, authConfig);
|
|
33
|
-
if (identityId && identityId.id === generatedIdentityId) {
|
|
34
|
-
logger.debug(`The guest identity ${identityId.id} has become the primary identity.`);
|
|
35
|
-
}
|
|
36
|
-
identityId = {
|
|
37
|
-
id: generatedIdentityId,
|
|
38
|
-
type: 'primary',
|
|
39
|
-
};
|
|
40
|
-
}
|
|
20
|
+
const identityId = await identityIdStore.loadIdentityId();
|
|
21
|
+
if (identityId) {
|
|
22
|
+
return identityId.id;
|
|
41
23
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
// Store in-memory or local storage depending on guest or primary identityId
|
|
55
|
-
identityIdStore.storeIdentityId(identityId);
|
|
56
|
-
return identityId.id;
|
|
24
|
+
const logins = tokens?.idToken
|
|
25
|
+
? formLoginsMap(tokens.idToken.toString())
|
|
26
|
+
: {};
|
|
27
|
+
const generatedIdentityId = await generateIdentityId(logins, authConfig);
|
|
28
|
+
// Store generated identityId
|
|
29
|
+
identityIdStore.storeIdentityId({
|
|
30
|
+
id: generatedIdentityId,
|
|
31
|
+
type: tokens ? 'primary' : 'guest',
|
|
32
|
+
});
|
|
33
|
+
return generatedIdentityId;
|
|
57
34
|
}
|
|
58
35
|
async function generateIdentityId(logins, authConfig) {
|
|
59
36
|
const identityPoolId = authConfig?.identityPoolId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IdentityIdProvider.mjs","sources":["../../../../../src/providers/cognito/credentialsProvider/IdentityIdProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport {
|
|
1
|
+
{"version":3,"file":"IdentityIdProvider.mjs","sources":["../../../../../src/providers/cognito/credentialsProvider/IdentityIdProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getId } from '@aws-amplify/core';\nimport { AuthError } from '../../../errors/AuthError';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers';\nimport { formLoginsMap } from './utils';\n/**\n * Provides a Cognito identityId\n *\n * @param tokens - The AuthTokens received after SignIn\n * @returns string\n * @throws configuration exceptions: `InvalidIdentityPoolIdException`\n * - Auth errors that may arise from misconfiguration.\n * @throws service exceptions: {@link GetIdException }\n */\nexport async function cognitoIdentityIdProvider({ tokens, authConfig, identityIdStore, }) {\n identityIdStore.setAuthConfig({ Cognito: authConfig });\n // will return null only if there is no identityId cached or if there is an error retrieving it\n const identityId = await identityIdStore.loadIdentityId();\n if (identityId) {\n return identityId.id;\n }\n const logins = tokens?.idToken\n ? formLoginsMap(tokens.idToken.toString())\n : {};\n const generatedIdentityId = await generateIdentityId(logins, authConfig);\n // Store generated identityId\n identityIdStore.storeIdentityId({\n id: generatedIdentityId,\n type: tokens ? 'primary' : 'guest',\n });\n return generatedIdentityId;\n}\nasync function generateIdentityId(logins, authConfig) {\n const identityPoolId = authConfig?.identityPoolId;\n const region = getRegionFromIdentityPoolId(identityPoolId);\n // IdentityId is absent so get it using IdentityPoolId with Cognito's GetId API\n const idResult = \n // for a first-time user, this will return a brand new identity\n // for a returning user, this will retrieve the previous identity assocaited with the logins\n (await getId({\n region,\n }, {\n IdentityPoolId: identityPoolId,\n Logins: logins,\n })).IdentityId;\n if (!idResult) {\n throw new AuthError({\n name: 'GetIdResponseException',\n message: 'Received undefined response from getId operation',\n recoverySuggestion: 'Make sure to pass a valid identityPoolId in the configuration.',\n });\n }\n return idResult;\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAe,yBAAyB,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe,GAAG,EAAE;AAC1F,IAAI,eAAe,CAAC,aAAa,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;AAC3D;AACA,IAAI,MAAM,UAAU,GAAG,MAAM,eAAe,CAAC,cAAc,EAAE,CAAC;AAC9D,IAAI,IAAI,UAAU,EAAE;AACpB,QAAQ,OAAO,UAAU,CAAC,EAAE,CAAC;AAC7B,KAAK;AACL,IAAI,MAAM,MAAM,GAAG,MAAM,EAAE,OAAO;AAClC,UAAU,aAAa,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;AAClD,UAAU,EAAE,CAAC;AACb,IAAI,MAAM,mBAAmB,GAAG,MAAM,kBAAkB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAC7E;AACA,IAAI,eAAe,CAAC,eAAe,CAAC;AACpC,QAAQ,EAAE,EAAE,mBAAmB;AAC/B,QAAQ,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO;AAC1C,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,mBAAmB,CAAC;AAC/B,CAAC;AACD,eAAe,kBAAkB,CAAC,MAAM,EAAE,UAAU,EAAE;AACtD,IAAI,MAAM,cAAc,GAAG,UAAU,EAAE,cAAc,CAAC;AACtD,IAAI,MAAM,MAAM,GAAG,2BAA2B,CAAC,cAAc,CAAC,CAAC;AAC/D;AACA,IAAI,MAAM,QAAQ;AAClB;AACA;AACA,IAAI,CAAC,MAAM,KAAK,CAAC;AACjB,QAAQ,MAAM;AACd,KAAK,EAAE;AACP,QAAQ,cAAc,EAAE,cAAc;AACtC,QAAQ,MAAM,EAAE,MAAM;AACtB,KAAK,CAAC,EAAE,UAAU,CAAC;AACnB,IAAI,IAAI,CAAC,QAAQ,EAAE;AACnB,QAAQ,MAAM,IAAI,SAAS,CAAC;AAC5B,YAAY,IAAI,EAAE,wBAAwB;AAC1C,YAAY,OAAO,EAAE,kDAAkD;AACvE,YAAY,kBAAkB,EAAE,gEAAgE;AAChG,SAAS,CAAC,CAAC;AACX,KAAK;AACL,IAAI,OAAO,QAAQ,CAAC;AACpB;;;;"}
|
|
@@ -89,11 +89,10 @@ class CognitoAWSCredentialsAndIdentityIdProvider {
|
|
|
89
89
|
},
|
|
90
90
|
identityId,
|
|
91
91
|
};
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
res.identityId = identityIdRes;
|
|
92
|
+
if (clientResult.IdentityId) {
|
|
93
|
+
res.identityId = clientResult.IdentityId;
|
|
95
94
|
this._identityIdStore.storeIdentityId({
|
|
96
|
-
id:
|
|
95
|
+
id: clientResult.IdentityId,
|
|
97
96
|
type: 'guest',
|
|
98
97
|
});
|
|
99
98
|
}
|
|
@@ -130,6 +129,7 @@ class CognitoAWSCredentialsAndIdentityIdProvider {
|
|
|
130
129
|
if (clientResult.Credentials &&
|
|
131
130
|
clientResult.Credentials.AccessKeyId &&
|
|
132
131
|
clientResult.Credentials.SecretKey) {
|
|
132
|
+
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
133
133
|
const res = {
|
|
134
134
|
credentials: {
|
|
135
135
|
accessKeyId: clientResult.Credentials.AccessKeyId,
|
|
@@ -139,21 +139,20 @@ class CognitoAWSCredentialsAndIdentityIdProvider {
|
|
|
139
139
|
},
|
|
140
140
|
identityId,
|
|
141
141
|
};
|
|
142
|
+
if (clientResult.IdentityId) {
|
|
143
|
+
res.identityId = clientResult.IdentityId;
|
|
144
|
+
// note: the following call removes guest identityId from the persistent store (localStorage)
|
|
145
|
+
this._identityIdStore.storeIdentityId({
|
|
146
|
+
id: clientResult.IdentityId,
|
|
147
|
+
type: 'primary',
|
|
148
|
+
});
|
|
149
|
+
}
|
|
142
150
|
// Store the credentials in-memory along with the expiration
|
|
143
151
|
this._credentialsAndIdentityId = {
|
|
144
152
|
...res,
|
|
145
153
|
isAuthenticatedCreds: true,
|
|
146
154
|
associatedIdToken: authTokens.idToken?.toString(),
|
|
147
155
|
};
|
|
148
|
-
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
149
|
-
const identityIdRes = clientResult.IdentityId;
|
|
150
|
-
if (identityIdRes) {
|
|
151
|
-
res.identityId = identityIdRes;
|
|
152
|
-
this._identityIdStore.storeIdentityId({
|
|
153
|
-
id: identityIdRes,
|
|
154
|
-
type: 'primary',
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
156
|
return res;
|
|
158
157
|
}
|
|
159
158
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credentialsProvider.mjs","sources":["../../../../../src/providers/cognito/credentialsProvider/credentialsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger, getCredentialsForIdentity, } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers';\nimport { assertIdTokenInAuthTokens } from '../utils/types';\nimport { cognitoIdentityIdProvider } from './IdentityIdProvider';\nimport { formLoginsMap } from './utils';\nconst logger = new ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nexport class CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n assertIdentityPoolIdConfig(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await cognitoIdentityIdProvider({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n assertIdTokenInAuthTokens(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? formLoginsMap(authTokens.idToken.toString())\n : {};\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'primary',\n });\n }\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAQA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,4BAA4B,CAAC,CAAC;AAC/D,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAChC,MAAM,0CAA0C,CAAC;AACxD,IAAI,WAAW,CAAC,eAAe,EAAE;AACjC,QAAQ,IAAI,CAAC,uBAAuB,GAAG,CAAC,CAAC;AACzC,QAAQ,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;AAChD,KAAK;AACL,IAAI,MAAM,6BAA6B,GAAG;AAC1C,QAAQ,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAC;AAChE,QAAQ,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;AACnD,QAAQ,MAAM,IAAI,CAA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ACrC,oBAAoB,IAAI,EAAE,SAAS;AACnC,iBAAiB,CAAC,CAAC;AACnB,aAAa;AACb,YAAY,OAAO,GAAG,CAAC;AACvB,SAAS;AACT,aAAa;AACb,YAAY,MAAM,IAAI,SAAS,CAAC;AAChC,gBAAgB,IAAI,EAAE,sBAAsB;AAC5C,gBAAgB,OAAO,EAAE,CAAC,0EAA0E,CAAC;AACrG,aAAa,CAAC,CAAC;AACf,SAAS;AACT,KAAK;AACL,IAAI,SAAS,GAAG;AAChB,QAAQ,OAAO,IAAI,CAAC,uBAAuB,KAAK,SAAS;AACzD,cAAc,IAAI;AAClB,cAAc,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AACzD,KAAK;AACL,IAAI,eAAe,CAAC,MAAM,EAAE;AAC5B,QAAQ,QAAQ,CAAC,CAAC,MAAM;AACxB,YAAY,CAAC,CAAC,IAAI,CAAC,yBAAyB,EAAE,iBAAiB;AAC/D,YAAY,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE;AACtC,gBAAgB,IAAI,CAAC,yBAAyB,CAAC,iBAAiB,EAAE;AAClE,KAAK;AACL;;;;"}
|
|
1
|
+
{"version":3,"file":"credentialsProvider.mjs","sources":["../../../../../src/providers/cognito/credentialsProvider/credentialsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger, getCredentialsForIdentity, } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers';\nimport { assertIdTokenInAuthTokens } from '../utils/types';\nimport { cognitoIdentityIdProvider } from './IdentityIdProvider';\nimport { formLoginsMap } from './utils';\nconst logger = new ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nexport class CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n assertIdentityPoolIdConfig(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await cognitoIdentityIdProvider({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n assertIdTokenInAuthTokens(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? formLoginsMap(authTokens.idToken.toString())\n : {};\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n // note: the following call removes guest identityId from the persistent store (localStorage)\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'primary',\n });\n }\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAQA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,4BAA4B,CAAC,CAAC;AAC/D,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAChC,MAAM,0CAA0C,CAAC;AACxD,IAAI,WAAW,CAAC,eAAe,EAAE;AACjC,QAAQ,IAAI,CAAC,uBAAuB,GAAG,CAAC,CAAC;AACzC,QAAQ,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;AAChD,KAAK;AACL,IAAI,MAAM,6BAA6B,GAAG;AAC1C,QAAQ,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAC;AAChE,QAAQ,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;AACnD,QAAQ,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,EAAE,CAAC;AACtD,KAAK;AACL,IAAI,MAAM,gBAAgB,GAAG;AAC7B,QAAQ,MAAM,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC;AAC3D,QAAQ,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC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0EAA0E,CAAC;AACrG,aAAa,CAAC,CAAC;AACf,SAAS;AACT,KAAK;AACL,IAAI,SAAS,GAAG;AAChB,QAAQ,OAAO,IAAI,CAAC,uBAAuB,KAAK,SAAS;AACzD,cAAc,IAAI;AAClB,cAAc,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AACzD,KAAK;AACL,IAAI,eAAe,CAAC,MAAM,EAAE;AAC5B,QAAQ,QAAQ,CAAC,CAAC,MAAM;AACxB,YAAY,CAAC,CAAC,IAAI,CAAC,yBAAyB,EAAE,iBAAiB;AAC/D,YAAY,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE;AACtC,gBAAgB,IAAI,CAAC,yBAAyB,CAAC,iBAAiB,EAAE;AAClE,KAAK;AACL;;;;"}
|
|
@@ -143,6 +143,8 @@ const completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {
|
|
|
143
143
|
// e.g. `getCurrentUser()` below, so it allows every inflight async calls to
|
|
144
144
|
// `fetchAuthSession` can be resolved
|
|
145
145
|
resolveAndClearInflightPromises();
|
|
146
|
+
// clear history before sending out final Hub events
|
|
147
|
+
clearHistory(redirectUri);
|
|
146
148
|
if (isCustomState(state)) {
|
|
147
149
|
Hub.dispatch('auth', {
|
|
148
150
|
event: 'customOAuthState',
|
|
@@ -151,7 +153,6 @@ const completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {
|
|
|
151
153
|
}
|
|
152
154
|
Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL);
|
|
153
155
|
await dispatchSignedInHubEvent();
|
|
154
|
-
clearHistory(redirectUri);
|
|
155
156
|
};
|
|
156
157
|
const isCustomState = (state) => {
|
|
157
158
|
return /-/.test(state);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"completeOAuthFlow.mjs","sources":["../../../../../../src/providers/cognito/utils/oauth/completeOAuthFlow.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AMPLIFY_SYMBOL, AmplifyUrl, USER_AGENT_HEADER, urlSafeDecode, } from '@aws-amplify/core/internals/utils';\nimport { Hub, decodeJWT } from '@aws-amplify/core';\nimport { cacheCognitoTokens } from '../../tokenProvider/cacheTokens';\nimport { dispatchSignedInHubEvent } from '../dispatchSignedInHubEvent';\nimport { tokenOrchestrator } from '../../tokenProvider';\nimport { createOAuthError } from './createOAuthError';\nimport { resolveAndClearInflightPromises } from './inflightPromise';\nimport { validateState } from './validateState';\nimport { oAuthStore } from './oAuthStore';\nexport const completeOAuthFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, responseType, domain, preferPrivateSession, }) => {\n const urlParams = new AmplifyUrl(currentUrl);\n const error = urlParams.searchParams.get('error');\n const errorMessage = urlParams.searchParams.get('error_description');\n if (error) {\n throw createOAuthError(errorMessage ?? error);\n }\n if (responseType === 'code') {\n return handleCodeFlow({\n currentUrl,\n userAgentValue,\n clientId,\n redirectUri,\n domain,\n preferPrivateSession,\n });\n }\n return handleImplicitFlow({\n currentUrl,\n redirectUri,\n preferPrivateSession,\n });\n};\nconst handleCodeFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, domain, preferPrivateSession, }) => {\n /* Convert URL into an object with parameters as keys\n{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */\n const url = new AmplifyUrl(currentUrl);\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n // if `code` or `state` is not presented in the redirect url, most likely\n // that the end user cancelled the inflight oauth flow by:\n // 1. clicking the back button of browser\n // 2. closing the provider hosted UI page and coming back to the app\n if (!code || !state) {\n throw createOAuthError('User cancelled OAuth flow.');\n }\n // may throw error is being caught in attemptCompleteOAuthFlow.ts\n const validatedState = await validateState(state);\n const oAuthTokenEndpoint = 'https://' + domain + '/oauth2/token';\n // TODO(v6): check hub events\n // dispatchAuthEvent(\n // \t'codeFlow',\n // \t{},\n // \t`Retrieving tokens from ${oAuthTokenEndpoint}`\n // );\n const codeVerifier = await oAuthStore.loadPKCE();\n const oAuthTokenBody = {\n grant_type: 'authorization_code',\n code,\n client_id: clientId,\n redirect_uri: redirectUri,\n ...(codeVerifier ? { code_verifier: codeVerifier } : {}),\n };\n const body = Object.entries(oAuthTokenBody)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n const { access_token, refresh_token: refreshToken, id_token, error, error_message: errorMessage, token_type, expires_in, } = await (await fetch(oAuthTokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n [USER_AGENT_HEADER]: userAgentValue,\n },\n body,\n })).json();\n if (error) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError(errorMessage ?? error);\n }\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n RefreshToken: refreshToken,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst handleImplicitFlow = async ({ currentUrl, redirectUri, preferPrivateSession, }) => {\n // hash is `null` if `#` doesn't exist on URL\n const url = new AmplifyUrl(currentUrl);\n const { id_token, access_token, state, token_type, expires_in, error_description, error, } = (url.hash ?? '#')\n .substring(1) // Remove # from returned code\n .split('&')\n .map(pairings => pairings.split('='))\n .reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {\n id_token: undefined,\n access_token: undefined,\n state: undefined,\n token_type: undefined,\n expires_in: undefined,\n error_description: undefined,\n error: undefined,\n });\n if (error) {\n throw createOAuthError(error_description ?? error);\n }\n if (!access_token) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError('No access token returned from OAuth flow.');\n }\n const validatedState = await validateState(state);\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {\n await tokenOrchestrator.setOAuthMetadata({\n oauthSignIn: true,\n });\n await oAuthStore.clearOAuthData();\n await oAuthStore.storeOAuthSignIn(true, preferPrivateSession);\n // this should be called before any call that involves `fetchAuthSession`\n // e.g. `getCurrentUser()` below, so it allows every inflight async calls to\n // `fetchAuthSession` can be resolved\n resolveAndClearInflightPromises();\n if (isCustomState(state)) {\n Hub.dispatch('auth', {\n event: 'customOAuthState',\n data: urlSafeDecode(getCustomState(state)),\n }, 'Auth', AMPLIFY_SYMBOL);\n }\n Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL);\n await dispatchSignedInHubEvent();\n clearHistory(redirectUri);\n};\nconst isCustomState = (state) => {\n return /-/.test(state);\n};\nconst getCustomState = (state) => {\n return state.split('-').splice(1).join('-');\n};\nconst clearHistory = (redirectUri) => {\n if (typeof window !== 'undefined' && typeof window.history !== 'undefined') {\n window.history.replaceState(window.history.state, '', redirectUri);\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;AACA;AAUY,MAAC,iBAAiB,GAAG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,EAAE,oBAAoB,GAAG,KAAK;AAC/I,IAAI,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;AACjD,IAAI,MAAM,KAAK,GAAG,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACtD,IAAI,MAAM,YAAY,GAAG,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;AACzE,IAAI,IAAI,KAAK,EAAE;AACf,QAAQ,MAAM,gBAAgB,CAAC,YAAY,IAAI,KAAK,C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AE,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC;AAClF,IAAI,MAAM,wBAAwB,EAAE,CAAC;AACrC,IAAI,YAAY,CAAC,WAAW,CAAC,CAAC;AAC9B,CAAC,CAAC;AACF,MAAM,aAAa,GAAG,CAAC,KAAK,KAAK;AACjC,IAAI,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC,CAAC;AACF,MAAM,cAAc,GAAG,CAAC,KAAK,KAAK;AAClC,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC,CAAC;AACF,MAAM,YAAY,GAAG,CAAC,WAAW,KAAK;AACtC,IAAI,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,WAAW,EAAE;AAChF,QAAQ,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,WAAW,CAAC,CAAC;AAC3E,KAAK;AACL,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"completeOAuthFlow.mjs","sources":["../../../../../../src/providers/cognito/utils/oauth/completeOAuthFlow.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AMPLIFY_SYMBOL, AmplifyUrl, USER_AGENT_HEADER, urlSafeDecode, } from '@aws-amplify/core/internals/utils';\nimport { Hub, decodeJWT } from '@aws-amplify/core';\nimport { cacheCognitoTokens } from '../../tokenProvider/cacheTokens';\nimport { dispatchSignedInHubEvent } from '../dispatchSignedInHubEvent';\nimport { tokenOrchestrator } from '../../tokenProvider';\nimport { createOAuthError } from './createOAuthError';\nimport { resolveAndClearInflightPromises } from './inflightPromise';\nimport { validateState } from './validateState';\nimport { oAuthStore } from './oAuthStore';\nexport const completeOAuthFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, responseType, domain, preferPrivateSession, }) => {\n const urlParams = new AmplifyUrl(currentUrl);\n const error = urlParams.searchParams.get('error');\n const errorMessage = urlParams.searchParams.get('error_description');\n if (error) {\n throw createOAuthError(errorMessage ?? error);\n }\n if (responseType === 'code') {\n return handleCodeFlow({\n currentUrl,\n userAgentValue,\n clientId,\n redirectUri,\n domain,\n preferPrivateSession,\n });\n }\n return handleImplicitFlow({\n currentUrl,\n redirectUri,\n preferPrivateSession,\n });\n};\nconst handleCodeFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, domain, preferPrivateSession, }) => {\n /* Convert URL into an object with parameters as keys\n{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */\n const url = new AmplifyUrl(currentUrl);\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n // if `code` or `state` is not presented in the redirect url, most likely\n // that the end user cancelled the inflight oauth flow by:\n // 1. clicking the back button of browser\n // 2. closing the provider hosted UI page and coming back to the app\n if (!code || !state) {\n throw createOAuthError('User cancelled OAuth flow.');\n }\n // may throw error is being caught in attemptCompleteOAuthFlow.ts\n const validatedState = await validateState(state);\n const oAuthTokenEndpoint = 'https://' + domain + '/oauth2/token';\n // TODO(v6): check hub events\n // dispatchAuthEvent(\n // \t'codeFlow',\n // \t{},\n // \t`Retrieving tokens from ${oAuthTokenEndpoint}`\n // );\n const codeVerifier = await oAuthStore.loadPKCE();\n const oAuthTokenBody = {\n grant_type: 'authorization_code',\n code,\n client_id: clientId,\n redirect_uri: redirectUri,\n ...(codeVerifier ? { code_verifier: codeVerifier } : {}),\n };\n const body = Object.entries(oAuthTokenBody)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n const { access_token, refresh_token: refreshToken, id_token, error, error_message: errorMessage, token_type, expires_in, } = await (await fetch(oAuthTokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n [USER_AGENT_HEADER]: userAgentValue,\n },\n body,\n })).json();\n if (error) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError(errorMessage ?? error);\n }\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n RefreshToken: refreshToken,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst handleImplicitFlow = async ({ currentUrl, redirectUri, preferPrivateSession, }) => {\n // hash is `null` if `#` doesn't exist on URL\n const url = new AmplifyUrl(currentUrl);\n const { id_token, access_token, state, token_type, expires_in, error_description, error, } = (url.hash ?? '#')\n .substring(1) // Remove # from returned code\n .split('&')\n .map(pairings => pairings.split('='))\n .reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {\n id_token: undefined,\n access_token: undefined,\n state: undefined,\n token_type: undefined,\n expires_in: undefined,\n error_description: undefined,\n error: undefined,\n });\n if (error) {\n throw createOAuthError(error_description ?? error);\n }\n if (!access_token) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError('No access token returned from OAuth flow.');\n }\n const validatedState = await validateState(state);\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {\n await tokenOrchestrator.setOAuthMetadata({\n oauthSignIn: true,\n });\n await oAuthStore.clearOAuthData();\n await oAuthStore.storeOAuthSignIn(true, preferPrivateSession);\n // this should be called before any call that involves `fetchAuthSession`\n // e.g. `getCurrentUser()` below, so it allows every inflight async calls to\n // `fetchAuthSession` can be resolved\n resolveAndClearInflightPromises();\n // clear history before sending out final Hub events\n clearHistory(redirectUri);\n if (isCustomState(state)) {\n Hub.dispatch('auth', {\n event: 'customOAuthState',\n data: urlSafeDecode(getCustomState(state)),\n }, 'Auth', AMPLIFY_SYMBOL);\n }\n Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL);\n await dispatchSignedInHubEvent();\n};\nconst isCustomState = (state) => {\n return /-/.test(state);\n};\nconst getCustomState = (state) => {\n return state.split('-').splice(1).join('-');\n};\nconst clearHistory = (redirectUri) => {\n if (typeof window !== 'undefined' && typeof window.history !== 'undefined') {\n window.history.replaceState(window.history.state, '', redirectUri);\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;AACA;AAUY,MAAC,iBAAiB,GAAG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,EAAE,oBAAoB,GAAG,KAAK;AAC/I,IAAI,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;AACjD,IAAI,MAAM,KAAK,GAAG,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACtD,IAAI,MAAM,YAAY,GAAG,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;AACzE,IAAI,IAAI,KAAK,EAAE;AACf,QAAQ,MAAM,gBAAgB,CAAC,YAAY,IAAI,KAAK,CAAC,CAAC;AACtD,KAAK;AACL,IAAI,IAAI,YAAY,KAAK,MAAM,EAAE;AACjC,QAAQ,OAAO,cAAc,CAAC;AAC9B,YAAY,UAAU;AACtB,YAAY,cAAc;AAC1B,YAAY,QAAQ;AACpB,YAAY,WAAW;AACvB,YAAY,MAAM;AAClB,YAAY,oBAAoB;AAChC,SAAS,CAAC,CAAC;AACX,KAAK;AACL,IAAI,OAAO,kBAAkB,CAAC;AAC9B,QAAQ,UAAU;AAClB,QAAQ,WAAW;AACnB,QAAQ,oBAAoB;AAC5B,KAAK,CAAC,CAAC;AACP,EAAE;AACF,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|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
2
|
+
"name": "@aws-amplify/auth",
|
|
3
|
+
"version": "6.11.4-unstable.a7df116.0+a7df116",
|
|
4
|
+
"description": "Auth category of aws-amplify",
|
|
5
|
+
"main": "./dist/cjs/index.js",
|
|
6
|
+
"module": "./dist/esm/index.mjs",
|
|
7
|
+
"typings": "./dist/esm/index.d.ts",
|
|
8
|
+
"react-native": "./src/index.ts",
|
|
9
|
+
"sideEffects": [
|
|
10
|
+
"./dist/cjs/providers/cognito/apis/signInWithRedirect.js",
|
|
11
|
+
"./dist/esm/providers/cognito/apis/signInWithRedirect.mjs",
|
|
12
|
+
"./dist/cjs/providers/cognito/utils/oauth/enableOAuthListener.js",
|
|
13
|
+
"./dist/esm/providers/cognito/utils/oauth/enableOAuthListener.mjs"
|
|
14
|
+
],
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "yarn lint --fix && jest -w 1 --coverage --logHeapUsage",
|
|
20
|
+
"build-with-test": "npm test && npm run build",
|
|
21
|
+
"build:umd": "webpack && webpack --config ./webpack.config.dev.js",
|
|
22
|
+
"build:esm-cjs": "rollup --forceExit -c rollup.config.mjs",
|
|
23
|
+
"build:watch": "npm run build:esm-cjs -- --watch",
|
|
24
|
+
"build": "npm run clean && npm run build:esm-cjs && npm run build:umd",
|
|
25
|
+
"clean": "npm run clean:size && rimraf lib-esm lib dist",
|
|
26
|
+
"clean:size": "rimraf dual-publish-tmp tmp*",
|
|
27
|
+
"format": "echo \"Not implemented\"",
|
|
28
|
+
"lint": "eslint '**/*.{ts,tsx}' && npm run ts-coverage",
|
|
29
|
+
"lint:fix": "eslint '**/*.{ts,tsx}' --fix",
|
|
30
|
+
"ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 91.18"
|
|
31
|
+
},
|
|
32
|
+
"typesVersions": {
|
|
33
|
+
">=4.2": {
|
|
34
|
+
"cognito": [
|
|
35
|
+
"./dist/esm/providers/cognito/index.d.ts"
|
|
36
|
+
],
|
|
37
|
+
"cognito/server": [
|
|
38
|
+
"./dist/esm/providers/cognito/apis/server/index.d.ts"
|
|
39
|
+
],
|
|
40
|
+
"server": [
|
|
41
|
+
"./dist/esm/server.d.ts"
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"exports": {
|
|
46
|
+
".": {
|
|
47
|
+
"types": "./dist/esm/index.d.ts",
|
|
48
|
+
"import": "./dist/esm/index.mjs",
|
|
49
|
+
"require": "./dist/cjs/index.js",
|
|
50
|
+
"react-native": "./src/index.ts"
|
|
51
|
+
},
|
|
52
|
+
"./cognito": {
|
|
53
|
+
"types": "./dist/esm/providers/cognito/index.d.ts",
|
|
54
|
+
"import": "./dist/esm/providers/cognito/index.mjs",
|
|
55
|
+
"require": "./dist/cjs/providers/cognito/index.js",
|
|
56
|
+
"react-native": "./src/providers/cognito/index.ts"
|
|
57
|
+
},
|
|
58
|
+
"./cognito/server": {
|
|
59
|
+
"types": "./dist/esm/providers/cognito/apis/server/index.d.ts",
|
|
60
|
+
"import": "./dist/esm/providers/cognito/apis/server/index.mjs",
|
|
61
|
+
"require": "./dist/cjs/providers/cognito/apis/server/index.js"
|
|
62
|
+
},
|
|
63
|
+
"./server": {
|
|
64
|
+
"types": "./dist/esm/server.d.ts",
|
|
65
|
+
"import": "./dist/esm/server.mjs",
|
|
66
|
+
"require": "./dist/cjs/server.js"
|
|
67
|
+
},
|
|
68
|
+
"./enable-oauth-listener": {
|
|
69
|
+
"types": "./dist/esm/providers/cognito/utils/oauth/enableOAuthListener.d.ts",
|
|
70
|
+
"import": "./dist/esm/providers/cognito/utils/oauth/enableOAuthListener.mjs",
|
|
71
|
+
"require": "./dist/cjs/providers/cognito/utils/oauth/enableOAuthListener.js"
|
|
72
|
+
},
|
|
73
|
+
"./package.json": "./package.json"
|
|
74
|
+
},
|
|
75
|
+
"repository": {
|
|
76
|
+
"type": "git",
|
|
77
|
+
"url": "https://github.com/aws-amplify/amplify-js.git"
|
|
78
|
+
},
|
|
79
|
+
"author": "Amazon Web Services",
|
|
80
|
+
"license": "Apache-2.0",
|
|
81
|
+
"bugs": {
|
|
82
|
+
"url": "https://github.com/aws/aws-amplify/issues"
|
|
83
|
+
},
|
|
84
|
+
"homepage": "https://aws-amplify.github.io/",
|
|
85
|
+
"files": [
|
|
86
|
+
"dist/cjs",
|
|
87
|
+
"dist/esm",
|
|
88
|
+
"src",
|
|
89
|
+
"cognito",
|
|
90
|
+
"server",
|
|
91
|
+
"enable-oauth-listener"
|
|
92
|
+
],
|
|
93
|
+
"dependencies": {
|
|
94
|
+
"@aws-crypto/sha256-js": "5.2.0",
|
|
95
|
+
"@smithy/types": "^3.3.0",
|
|
96
|
+
"tslib": "^2.5.0"
|
|
97
|
+
},
|
|
98
|
+
"peerDependencies": {
|
|
99
|
+
"@aws-amplify/core": "6.10.4-unstable.a7df116.0+a7df116"
|
|
100
|
+
},
|
|
101
|
+
"devDependencies": {
|
|
102
|
+
"@aws-amplify/core": "6.10.4-unstable.a7df116.0+a7df116",
|
|
103
|
+
"@aws-amplify/react-native": "1.1.8-unstable.a7df116.0+a7df116",
|
|
104
|
+
"@jest/test-sequencer": "^29.7.0",
|
|
105
|
+
"typescript": "5.0.2"
|
|
106
|
+
},
|
|
107
|
+
"gitHead": "a7df1165e5df4dbaf3fae9091483056323463c3e"
|
|
108
108
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
3
|
|
|
4
|
-
import { AuthTokens,
|
|
4
|
+
import { AuthTokens, Identity, getId } from '@aws-amplify/core';
|
|
5
5
|
import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils';
|
|
6
6
|
|
|
7
7
|
import { AuthError } from '../../../errors/AuthError';
|
|
@@ -11,7 +11,6 @@ import { GetIdException } from '../types/errors';
|
|
|
11
11
|
import { IdentityIdStore } from './types';
|
|
12
12
|
import { formLoginsMap } from './utils';
|
|
13
13
|
|
|
14
|
-
const logger = new ConsoleLogger('CognitoIdentityIdProvider');
|
|
15
14
|
/**
|
|
16
15
|
* Provides a Cognito identityId
|
|
17
16
|
*
|
|
@@ -33,46 +32,22 @@ export async function cognitoIdentityIdProvider({
|
|
|
33
32
|
identityIdStore.setAuthConfig({ Cognito: authConfig });
|
|
34
33
|
|
|
35
34
|
// will return null only if there is no identityId cached or if there is an error retrieving it
|
|
36
|
-
|
|
35
|
+
const identityId: Identity | null = await identityIdStore.loadIdentityId();
|
|
37
36
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
// If there is existing primary identityId in-memory return that
|
|
41
|
-
if (identityId && identityId.type === 'primary') {
|
|
42
|
-
return identityId.id;
|
|
43
|
-
} else {
|
|
44
|
-
const logins = tokens.idToken
|
|
45
|
-
? formLoginsMap(tokens.idToken.toString())
|
|
46
|
-
: {};
|
|
47
|
-
|
|
48
|
-
const generatedIdentityId = await generateIdentityId(logins, authConfig);
|
|
49
|
-
|
|
50
|
-
if (identityId && identityId.id === generatedIdentityId) {
|
|
51
|
-
logger.debug(
|
|
52
|
-
`The guest identity ${identityId.id} has become the primary identity.`,
|
|
53
|
-
);
|
|
54
|
-
}
|
|
55
|
-
identityId = {
|
|
56
|
-
id: generatedIdentityId,
|
|
57
|
-
type: 'primary',
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
} else {
|
|
61
|
-
// If there is existing guest identityId cached return that
|
|
62
|
-
if (identityId && identityId.type === 'guest') {
|
|
63
|
-
return identityId.id;
|
|
64
|
-
} else {
|
|
65
|
-
identityId = {
|
|
66
|
-
id: await generateIdentityId({}, authConfig),
|
|
67
|
-
type: 'guest',
|
|
68
|
-
};
|
|
69
|
-
}
|
|
37
|
+
if (identityId) {
|
|
38
|
+
return identityId.id;
|
|
70
39
|
}
|
|
40
|
+
const logins = tokens?.idToken
|
|
41
|
+
? formLoginsMap(tokens.idToken.toString())
|
|
42
|
+
: {};
|
|
43
|
+
const generatedIdentityId = await generateIdentityId(logins, authConfig);
|
|
44
|
+
// Store generated identityId
|
|
45
|
+
identityIdStore.storeIdentityId({
|
|
46
|
+
id: generatedIdentityId,
|
|
47
|
+
type: tokens ? 'primary' : 'guest',
|
|
48
|
+
});
|
|
71
49
|
|
|
72
|
-
|
|
73
|
-
identityIdStore.storeIdentityId(identityId);
|
|
74
|
-
|
|
75
|
-
return identityId.id;
|
|
50
|
+
return generatedIdentityId;
|
|
76
51
|
}
|
|
77
52
|
|
|
78
53
|
async function generateIdentityId(
|
|
@@ -129,6 +129,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
|
|
|
129
129
|
clientResult.Credentials.SecretKey
|
|
130
130
|
) {
|
|
131
131
|
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
132
|
+
|
|
132
133
|
const res: CredentialsAndIdentityId = {
|
|
133
134
|
credentials: {
|
|
134
135
|
accessKeyId: clientResult.Credentials.AccessKeyId,
|
|
@@ -138,11 +139,10 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
|
|
|
138
139
|
},
|
|
139
140
|
identityId,
|
|
140
141
|
};
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
res.identityId = identityIdRes;
|
|
142
|
+
if (clientResult.IdentityId) {
|
|
143
|
+
res.identityId = clientResult.IdentityId;
|
|
144
144
|
this._identityIdStore.storeIdentityId({
|
|
145
|
-
id:
|
|
145
|
+
id: clientResult.IdentityId,
|
|
146
146
|
type: 'guest',
|
|
147
147
|
});
|
|
148
148
|
}
|
|
@@ -199,6 +199,8 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
|
|
|
199
199
|
clientResult.Credentials.AccessKeyId &&
|
|
200
200
|
clientResult.Credentials.SecretKey
|
|
201
201
|
) {
|
|
202
|
+
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
203
|
+
|
|
202
204
|
const res: CredentialsAndIdentityId = {
|
|
203
205
|
credentials: {
|
|
204
206
|
accessKeyId: clientResult.Credentials.AccessKeyId,
|
|
@@ -208,22 +210,22 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
|
|
|
208
210
|
},
|
|
209
211
|
identityId,
|
|
210
212
|
};
|
|
213
|
+
|
|
214
|
+
if (clientResult.IdentityId) {
|
|
215
|
+
res.identityId = clientResult.IdentityId;
|
|
216
|
+
// note: the following call removes guest identityId from the persistent store (localStorage)
|
|
217
|
+
this._identityIdStore.storeIdentityId({
|
|
218
|
+
id: clientResult.IdentityId,
|
|
219
|
+
type: 'primary',
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
211
223
|
// Store the credentials in-memory along with the expiration
|
|
212
224
|
this._credentialsAndIdentityId = {
|
|
213
225
|
...res,
|
|
214
226
|
isAuthenticatedCreds: true,
|
|
215
227
|
associatedIdToken: authTokens.idToken?.toString(),
|
|
216
228
|
};
|
|
217
|
-
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
|
218
|
-
|
|
219
|
-
const identityIdRes = clientResult.IdentityId;
|
|
220
|
-
if (identityIdRes) {
|
|
221
|
-
res.identityId = identityIdRes;
|
|
222
|
-
this._identityIdStore.storeIdentityId({
|
|
223
|
-
id: identityIdRes,
|
|
224
|
-
type: 'primary',
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
229
|
|
|
228
230
|
return res;
|
|
229
231
|
} else {
|
|
@@ -239,6 +239,9 @@ const completeFlow = async ({
|
|
|
239
239
|
// `fetchAuthSession` can be resolved
|
|
240
240
|
resolveAndClearInflightPromises();
|
|
241
241
|
|
|
242
|
+
// clear history before sending out final Hub events
|
|
243
|
+
clearHistory(redirectUri);
|
|
244
|
+
|
|
242
245
|
if (isCustomState(state)) {
|
|
243
246
|
Hub.dispatch(
|
|
244
247
|
'auth',
|
|
@@ -252,7 +255,6 @@ const completeFlow = async ({
|
|
|
252
255
|
}
|
|
253
256
|
Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL);
|
|
254
257
|
await dispatchSignedInHubEvent();
|
|
255
|
-
clearHistory(redirectUri);
|
|
256
258
|
};
|
|
257
259
|
|
|
258
260
|
const isCustomState = (state: string): boolean => {
|