@vardario/cognito-client 0.1.3 → 0.1.5

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.
@@ -1,67 +1,14 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __importDefault = (this && this.__importDefault) || function (mod) {
50
- return (mod && mod.__esModule) ? mod : { "default": mod };
51
- };
52
- Object.defineProperty(exports, "__esModule", { value: true });
53
- exports.CognitoClient = exports.CognitoIdentityProvider = exports.CognitoServiceTarget = void 0;
54
- var addSeconds_1 = __importDefault(require("date-fns/addSeconds"));
55
- var hash_js_1 = require("hash.js");
56
- var jsbn_1 = require("jsbn");
57
- var randombytes_1 = __importDefault(require("randombytes"));
58
- var error_1 = require("./error");
59
- var utils_1 = require("./utils");
1
+ import addSeconds from 'date-fns/addSeconds';
2
+ import { sha256 } from 'hash.js';
3
+ import { BigInteger } from 'jsbn';
4
+ import randomBytes from 'randombytes';
5
+ import { AuthError, AuthException, getAuthError } from './error.js';
6
+ import { calculateSignature, calculateU, decodeJwt, generateA, generateSmallA, getPasswordAuthenticationKey, } from './utils.js';
60
7
  /**
61
8
  * List of used and supported Cognito API calls.
62
9
  * @see https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_Operations.html for more details
63
10
  */
64
- var CognitoServiceTarget;
11
+ export var CognitoServiceTarget;
65
12
  (function (CognitoServiceTarget) {
66
13
  CognitoServiceTarget["InitiateAuth"] = "InitiateAuth";
67
14
  CognitoServiceTarget["RespondToAuthChallenge"] = "RespondToAuthChallenge";
@@ -74,73 +21,62 @@ var CognitoServiceTarget;
74
21
  CognitoServiceTarget["ResendConfirmationCode"] = "ResendConfirmationCode";
75
22
  CognitoServiceTarget["UpdateUserAttributes"] = "UpdateUserAttributes";
76
23
  CognitoServiceTarget["VerifyUserAttribute"] = "VerifyUserAttribute";
77
- })(CognitoServiceTarget = exports.CognitoServiceTarget || (exports.CognitoServiceTarget = {}));
24
+ })(CognitoServiceTarget || (CognitoServiceTarget = {}));
78
25
  /**
79
26
  * Cognito supported federated identities public providers.
80
27
  * @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html for more information.
81
28
  */
82
- var CognitoIdentityProvider;
29
+ export var CognitoIdentityProvider;
83
30
  (function (CognitoIdentityProvider) {
84
31
  CognitoIdentityProvider["Cognito"] = "COGNITO";
85
32
  CognitoIdentityProvider["Google"] = "Google";
86
33
  CognitoIdentityProvider["Facebook"] = "Facebook";
87
34
  CognitoIdentityProvider["Amazon"] = "LoginWithAmazon";
88
35
  CognitoIdentityProvider["Apple"] = "SignInWithApple";
89
- })(CognitoIdentityProvider = exports.CognitoIdentityProvider || (exports.CognitoIdentityProvider = {}));
36
+ })(CognitoIdentityProvider || (CognitoIdentityProvider = {}));
90
37
  /**
91
38
  * Lightweight AWS Cogito client without any AWS SDK dependencies.
92
39
  */
93
- var CognitoClient = /** @class */ (function () {
94
- function CognitoClient(_a) {
95
- var userPoolId = _a.userPoolId, userPoolClientId = _a.userPoolClientId, endpoint = _a.endpoint, sessionStorage = _a.sessionStorage, oAuth = _a.oAuth2;
96
- var _b = userPoolId.split('_'), cognitoPoolRegion = _b[0], cognitoPoolName = _b[1];
97
- this.cognitoEndpoint = (endpoint || "https://cognito-idp.".concat(cognitoPoolRegion, ".amazonaws.com")).replace(/\/$/, '');
40
+ export class CognitoClient {
41
+ constructor({ userPoolId, userPoolClientId, endpoint, sessionStorage, oAuth2: oAuth }) {
42
+ const [cognitoPoolRegion, cognitoPoolName] = userPoolId.split('_');
43
+ this.cognitoEndpoint = (endpoint || `https://cognito-idp.${cognitoPoolRegion}.amazonaws.com`).replace(/\/$/, '');
98
44
  this.cognitoPoolName = cognitoPoolName;
99
45
  this.userPoolClientId = userPoolClientId;
100
46
  this.sessionStorage = sessionStorage;
101
47
  this.oAuth = oAuth;
102
48
  }
103
- CognitoClient.getDecodedTokenFromSession = function (session) {
104
- var idToken = (0, utils_1.decodeJwt)(session.idToken).payload;
105
- var accessToken = (0, utils_1.decodeJwt)(session.accessToken).payload;
49
+ static getDecodedTokenFromSession(session) {
50
+ const { payload: idToken } = decodeJwt(session.idToken);
51
+ const { payload: accessToken } = decodeJwt(session.accessToken);
106
52
  return {
107
- idToken: idToken,
108
- accessToken: accessToken,
53
+ idToken,
54
+ accessToken,
109
55
  };
110
- };
111
- CognitoClient.prototype.cognitoRequest = function (body, serviceTarget) {
112
- return __awaiter(this, void 0, void 0, function () {
113
- var respondToAuthChallenge, errorMessage;
114
- return __generator(this, function (_a) {
115
- switch (_a.label) {
116
- case 0: return [4 /*yield*/, fetch(this.cognitoEndpoint, {
117
- headers: {
118
- 'x-amz-target': "AWSCognitoIdentityProviderService.".concat(serviceTarget),
119
- 'content-type': 'application/x-amz-json-1.1',
120
- },
121
- method: 'POST',
122
- body: JSON.stringify(body),
123
- })];
124
- case 1:
125
- respondToAuthChallenge = _a.sent();
126
- if (!(respondToAuthChallenge.status < 200 || respondToAuthChallenge.status > 299)) return [3 /*break*/, 3];
127
- return [4 /*yield*/, respondToAuthChallenge.json()];
128
- case 2:
129
- errorMessage = (_a.sent());
130
- throw (0, error_1.getAuthError)(errorMessage);
131
- case 3: return [2 /*return*/, respondToAuthChallenge.json()];
132
- }
133
- });
56
+ }
57
+ async cognitoRequest(body, serviceTarget) {
58
+ const respondToAuthChallenge = await fetch(this.cognitoEndpoint, {
59
+ headers: {
60
+ 'x-amz-target': `AWSCognitoIdentityProviderService.${serviceTarget}`,
61
+ 'content-type': 'application/x-amz-json-1.1',
62
+ },
63
+ method: 'POST',
64
+ body: JSON.stringify(body),
134
65
  });
135
- };
136
- CognitoClient.authResultToSession = function (authenticationResult) {
66
+ if (respondToAuthChallenge.status < 200 || respondToAuthChallenge.status > 299) {
67
+ const errorMessage = (await respondToAuthChallenge.json());
68
+ throw getAuthError(errorMessage);
69
+ }
70
+ return respondToAuthChallenge.json();
71
+ }
72
+ static authResultToSession(authenticationResult) {
137
73
  return {
138
74
  accessToken: authenticationResult.AccessToken,
139
75
  idToken: authenticationResult.IdToken,
140
- expiresIn: (0, addSeconds_1.default)(new Date(), authenticationResult.ExpiresIn).getTime(),
76
+ expiresIn: addSeconds(new Date(), authenticationResult.ExpiresIn).getTime(),
141
77
  refreshToken: authenticationResult.RefreshToken,
142
78
  };
143
- };
79
+ }
144
80
  /**
145
81
  *
146
82
  * Performs user authentication with username and password through ALLOW_USER_SRP_AUTH .
@@ -150,52 +86,40 @@ var CognitoClient = /** @class */ (function () {
150
86
  * @param password Password
151
87
  * @throws {AuthException}
152
88
  */
153
- CognitoClient.prototype.authenticateUserSrp = function (username, password) {
154
- return __awaiter(this, void 0, void 0, function () {
155
- var smallA, A, initiateAuthPayload, challenge, B, salt, U, hkdf, _a, signature, timeStamp, respondToAuthChallengePayload, AuthenticationResult, session;
156
- return __generator(this, function (_b) {
157
- switch (_b.label) {
158
- case 0:
159
- smallA = (0, utils_1.generateSmallA)();
160
- A = (0, utils_1.generateA)(smallA);
161
- initiateAuthPayload = {
162
- AuthFlow: 'USER_SRP_AUTH',
163
- ClientId: this.userPoolClientId,
164
- AuthParameters: {
165
- USERNAME: username,
166
- SRP_A: A.toString(16),
167
- },
168
- ClientMetadata: {},
169
- };
170
- return [4 /*yield*/, this.cognitoRequest(initiateAuthPayload, CognitoServiceTarget.InitiateAuth)];
171
- case 1:
172
- challenge = (_b.sent());
173
- B = new jsbn_1.BigInteger(challenge.ChallengeParameters.SRP_B, 16);
174
- salt = new jsbn_1.BigInteger(challenge.ChallengeParameters.SALT, 16);
175
- U = (0, utils_1.calculateU)(A, B);
176
- hkdf = (0, utils_1.getPasswordAuthenticationKey)(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, password, B, U, smallA, salt);
177
- _a = (0, utils_1.calculateSignature)(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, challenge.ChallengeParameters.SECRET_BLOCK, hkdf), signature = _a.signature, timeStamp = _a.timeStamp;
178
- respondToAuthChallengePayload = {
179
- ChallengeName: 'PASSWORD_VERIFIER',
180
- ClientId: this.userPoolClientId,
181
- ChallengeResponses: {
182
- PASSWORD_CLAIM_SECRET_BLOCK: challenge.ChallengeParameters.SECRET_BLOCK,
183
- PASSWORD_CLAIM_SIGNATURE: signature,
184
- USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP,
185
- TIMESTAMP: timeStamp,
186
- },
187
- ClientMetadata: {},
188
- };
189
- return [4 /*yield*/, this.cognitoRequest(respondToAuthChallengePayload, CognitoServiceTarget.RespondToAuthChallenge)];
190
- case 2:
191
- AuthenticationResult = (_b.sent()).AuthenticationResult;
192
- session = CognitoClient.authResultToSession(AuthenticationResult);
193
- this.sessionStorage.setSession(session);
194
- return [2 /*return*/, session];
195
- }
196
- });
197
- });
198
- };
89
+ async authenticateUserSrp(username, password) {
90
+ const smallA = generateSmallA();
91
+ const A = generateA(smallA);
92
+ const initiateAuthPayload = {
93
+ AuthFlow: 'USER_SRP_AUTH',
94
+ ClientId: this.userPoolClientId,
95
+ AuthParameters: {
96
+ USERNAME: username,
97
+ SRP_A: A.toString(16),
98
+ },
99
+ ClientMetadata: {},
100
+ };
101
+ const challenge = (await this.cognitoRequest(initiateAuthPayload, CognitoServiceTarget.InitiateAuth));
102
+ const B = new BigInteger(challenge.ChallengeParameters.SRP_B, 16);
103
+ const salt = new BigInteger(challenge.ChallengeParameters.SALT, 16);
104
+ const U = calculateU(A, B);
105
+ const hkdf = getPasswordAuthenticationKey(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, password, B, U, smallA, salt);
106
+ const { signature, timeStamp } = calculateSignature(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, challenge.ChallengeParameters.SECRET_BLOCK, hkdf);
107
+ const respondToAuthChallengePayload = {
108
+ ChallengeName: 'PASSWORD_VERIFIER',
109
+ ClientId: this.userPoolClientId,
110
+ ChallengeResponses: {
111
+ PASSWORD_CLAIM_SECRET_BLOCK: challenge.ChallengeParameters.SECRET_BLOCK,
112
+ PASSWORD_CLAIM_SIGNATURE: signature,
113
+ USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP,
114
+ TIMESTAMP: timeStamp,
115
+ },
116
+ ClientMetadata: {},
117
+ };
118
+ const { AuthenticationResult } = await this.cognitoRequest(respondToAuthChallengePayload, CognitoServiceTarget.RespondToAuthChallenge);
119
+ const session = CognitoClient.authResultToSession(AuthenticationResult);
120
+ this.sessionStorage.setSession(session);
121
+ return session;
122
+ }
199
123
  /**
200
124
  *
201
125
  * Performs user authentication with username and password through USER_PASSWORD_AUTH .
@@ -205,55 +129,38 @@ var CognitoClient = /** @class */ (function () {
205
129
  * @param password Password
206
130
  * @throws {AuthException}
207
131
  */
208
- CognitoClient.prototype.authenticateUser = function (username, password) {
209
- return __awaiter(this, void 0, void 0, function () {
210
- var initiateAuthPayload, AuthenticationResult, session;
211
- return __generator(this, function (_a) {
212
- switch (_a.label) {
213
- case 0:
214
- initiateAuthPayload = {
215
- AuthFlow: 'USER_PASSWORD_AUTH',
216
- ClientId: this.userPoolClientId,
217
- AuthParameters: {
218
- USERNAME: username,
219
- PASSWORD: password,
220
- },
221
- ClientMetadata: {},
222
- };
223
- return [4 /*yield*/, this.cognitoRequest(initiateAuthPayload, CognitoServiceTarget.InitiateAuth)];
224
- case 1:
225
- AuthenticationResult = (_a.sent()).AuthenticationResult;
226
- session = CognitoClient.authResultToSession(AuthenticationResult);
227
- this.sessionStorage.setSession(session);
228
- return [2 /*return*/, session];
229
- }
230
- });
231
- });
232
- };
233
- CognitoClient.prototype.refreshSession = function (session) {
234
- return __awaiter(this, void 0, void 0, function () {
235
- var refreshTokenPayload, AuthenticationResult, newSession;
236
- return __generator(this, function (_a) {
237
- switch (_a.label) {
238
- case 0:
239
- refreshTokenPayload = {
240
- AuthFlow: 'REFRESH_TOKEN_AUTH',
241
- ClientId: this.userPoolClientId,
242
- AuthParameters: {
243
- REFRESH_TOKEN: session.refreshToken,
244
- },
245
- ClientMetadata: {},
246
- };
247
- return [4 /*yield*/, this.cognitoRequest(refreshTokenPayload, CognitoServiceTarget.InitiateAuth)];
248
- case 1:
249
- AuthenticationResult = (_a.sent()).AuthenticationResult;
250
- newSession = CognitoClient.authResultToSession(__assign(__assign({}, AuthenticationResult), { RefreshToken: session.refreshToken }));
251
- this.sessionStorage.setSession(newSession);
252
- return [2 /*return*/, newSession];
253
- }
254
- });
132
+ async authenticateUser(username, password) {
133
+ const initiateAuthPayload = {
134
+ AuthFlow: 'USER_PASSWORD_AUTH',
135
+ ClientId: this.userPoolClientId,
136
+ AuthParameters: {
137
+ USERNAME: username,
138
+ PASSWORD: password,
139
+ },
140
+ ClientMetadata: {},
141
+ };
142
+ const { AuthenticationResult } = (await this.cognitoRequest(initiateAuthPayload, CognitoServiceTarget.InitiateAuth));
143
+ const session = CognitoClient.authResultToSession(AuthenticationResult);
144
+ this.sessionStorage.setSession(session);
145
+ return session;
146
+ }
147
+ async refreshSession(session) {
148
+ const refreshTokenPayload = {
149
+ AuthFlow: 'REFRESH_TOKEN_AUTH',
150
+ ClientId: this.userPoolClientId,
151
+ AuthParameters: {
152
+ REFRESH_TOKEN: session.refreshToken,
153
+ },
154
+ ClientMetadata: {},
155
+ };
156
+ const { AuthenticationResult } = (await this.cognitoRequest(refreshTokenPayload, CognitoServiceTarget.InitiateAuth));
157
+ const newSession = CognitoClient.authResultToSession({
158
+ ...AuthenticationResult,
159
+ RefreshToken: session.refreshToken,
255
160
  });
256
- };
161
+ this.sessionStorage.setSession(newSession);
162
+ return newSession;
163
+ }
257
164
  /**
258
165
  * Returns the current auth session.
259
166
  * The auth session is only defined when we previously had a successful user authentication.
@@ -262,20 +169,15 @@ var CognitoClient = /** @class */ (function () {
262
169
  *
263
170
  * @throws {AuthException}
264
171
  */
265
- CognitoClient.prototype.getSession = function () {
266
- return __awaiter(this, void 0, void 0, function () {
267
- var session;
268
- return __generator(this, function (_a) {
269
- session = this.sessionStorage.getSession();
270
- if (session) {
271
- if (new Date().getTime() >= session.expiresIn) {
272
- return [2 /*return*/, this.refreshSession(session)];
273
- }
274
- }
275
- return [2 /*return*/, session];
276
- });
277
- });
278
- };
172
+ async getSession() {
173
+ const session = this.sessionStorage.getSession();
174
+ if (session) {
175
+ if (new Date().getTime() >= session.expiresIn) {
176
+ return this.refreshSession(session);
177
+ }
178
+ }
179
+ return session;
180
+ }
279
181
  /**
280
182
  *
281
183
  * @param username Username
@@ -283,29 +185,19 @@ var CognitoClient = /** @class */ (function () {
283
185
  *
284
186
  * @throws {AuthException}
285
187
  */
286
- CognitoClient.prototype.signUp = function (username, password, userAttributes) {
287
- return __awaiter(this, void 0, void 0, function () {
288
- var signUpPayload, data;
289
- return __generator(this, function (_a) {
290
- switch (_a.label) {
291
- case 0:
292
- signUpPayload = {
293
- ClientId: this.userPoolClientId,
294
- Username: username,
295
- Password: password,
296
- UserAttributes: userAttributes,
297
- };
298
- return [4 /*yield*/, this.cognitoRequest(signUpPayload, CognitoServiceTarget.SignUp)];
299
- case 1:
300
- data = _a.sent();
301
- return [2 /*return*/, {
302
- id: data.UserSub,
303
- confirmed: data.UserConfirmed,
304
- }];
305
- }
306
- });
307
- });
308
- };
188
+ async signUp(username, password, userAttributes) {
189
+ const signUpPayload = {
190
+ ClientId: this.userPoolClientId,
191
+ Username: username,
192
+ Password: password,
193
+ UserAttributes: userAttributes,
194
+ };
195
+ const data = await this.cognitoRequest(signUpPayload, CognitoServiceTarget.SignUp);
196
+ return {
197
+ id: data.UserSub,
198
+ confirmed: data.UserConfirmed,
199
+ };
200
+ }
309
201
  /**
310
202
  * Confirms the user registration via verification code.
311
203
  *
@@ -314,25 +206,14 @@ var CognitoClient = /** @class */ (function () {
314
206
  *
315
207
  * @throws {AuthException}
316
208
  */
317
- CognitoClient.prototype.confirmSignUp = function (username, code) {
318
- return __awaiter(this, void 0, void 0, function () {
319
- var confirmSignUpPayload, result;
320
- return __generator(this, function (_a) {
321
- switch (_a.label) {
322
- case 0:
323
- confirmSignUpPayload = {
324
- ClientId: this.userPoolClientId,
325
- ConfirmationCode: code,
326
- Username: username,
327
- };
328
- return [4 /*yield*/, this.cognitoRequest(confirmSignUpPayload, CognitoServiceTarget.ConfirmSignUp)];
329
- case 1:
330
- result = _a.sent();
331
- return [2 /*return*/];
332
- }
333
- });
334
- });
335
- };
209
+ async confirmSignUp(username, code) {
210
+ const confirmSignUpPayload = {
211
+ ClientId: this.userPoolClientId,
212
+ ConfirmationCode: code,
213
+ Username: username,
214
+ };
215
+ const result = await this.cognitoRequest(confirmSignUpPayload, CognitoServiceTarget.ConfirmSignUp);
216
+ }
336
217
  /**
337
218
  *
338
219
  * @param currentPassword Current user password.
@@ -340,130 +221,71 @@ var CognitoClient = /** @class */ (function () {
340
221
  *
341
222
  * @throws {AuthException}
342
223
  */
343
- CognitoClient.prototype.changePassword = function (currentPassword, newPassword) {
344
- return __awaiter(this, void 0, void 0, function () {
345
- var session, changePasswordPayload, result;
346
- return __generator(this, function (_a) {
347
- switch (_a.label) {
348
- case 0: return [4 /*yield*/, this.getSession()];
349
- case 1:
350
- session = _a.sent();
351
- if (session === undefined) {
352
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
353
- }
354
- changePasswordPayload = {
355
- PreviousPassword: currentPassword,
356
- ProposedPassword: newPassword,
357
- AccessToken: session.accessToken,
358
- };
359
- return [4 /*yield*/, this.cognitoRequest(changePasswordPayload, CognitoServiceTarget.ChangePassword)];
360
- case 2:
361
- result = _a.sent();
362
- return [2 /*return*/];
363
- }
364
- });
365
- });
366
- };
367
- CognitoClient.prototype.updateUserAttributes = function (userAttributes) {
368
- return __awaiter(this, void 0, void 0, function () {
369
- var session, updateUserAttributesPayload, result;
370
- return __generator(this, function (_a) {
371
- switch (_a.label) {
372
- case 0: return [4 /*yield*/, this.getSession()];
373
- case 1:
374
- session = _a.sent();
375
- if (session === undefined) {
376
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
377
- }
378
- updateUserAttributesPayload = {
379
- UserAttributes: userAttributes,
380
- AccessToken: session.accessToken,
381
- };
382
- return [4 /*yield*/, this.cognitoRequest(updateUserAttributesPayload, CognitoServiceTarget.UpdateUserAttributes)];
383
- case 2:
384
- result = _a.sent();
385
- return [2 /*return*/];
386
- }
387
- });
388
- });
389
- };
390
- CognitoClient.prototype.verifyUserAttribute = function (attributeName, code) {
391
- return __awaiter(this, void 0, void 0, function () {
392
- var session, verifyUserAttributePayload, result;
393
- return __generator(this, function (_a) {
394
- switch (_a.label) {
395
- case 0: return [4 /*yield*/, this.getSession()];
396
- case 1:
397
- session = _a.sent();
398
- if (session === undefined) {
399
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
400
- }
401
- verifyUserAttributePayload = {
402
- AttributeName: attributeName,
403
- Code: code,
404
- AccessToken: session.accessToken,
405
- };
406
- return [4 /*yield*/, this.cognitoRequest(verifyUserAttributePayload, CognitoServiceTarget.VerifyUserAttribute)];
407
- case 2:
408
- result = _a.sent();
409
- return [2 /*return*/];
410
- }
411
- });
412
- });
413
- };
224
+ async changePassword(currentPassword, newPassword) {
225
+ const session = await this.getSession();
226
+ if (session === undefined) {
227
+ throw new AuthException('User must be authenticated', AuthError.UserNotAuthenticated);
228
+ }
229
+ const changePasswordPayload = {
230
+ PreviousPassword: currentPassword,
231
+ ProposedPassword: newPassword,
232
+ AccessToken: session.accessToken,
233
+ };
234
+ const result = await this.cognitoRequest(changePasswordPayload, CognitoServiceTarget.ChangePassword);
235
+ }
236
+ async updateUserAttributes(userAttributes) {
237
+ const session = await this.getSession();
238
+ if (session === undefined) {
239
+ throw new AuthException('User must be authenticated', AuthError.UserNotAuthenticated);
240
+ }
241
+ const updateUserAttributesPayload = {
242
+ UserAttributes: userAttributes,
243
+ AccessToken: session.accessToken,
244
+ };
245
+ const result = await this.cognitoRequest(updateUserAttributesPayload, CognitoServiceTarget.UpdateUserAttributes);
246
+ }
247
+ async verifyUserAttribute(attributeName, code) {
248
+ const session = await this.getSession();
249
+ if (session === undefined) {
250
+ throw new AuthException('User must be authenticated', AuthError.UserNotAuthenticated);
251
+ }
252
+ const verifyUserAttributePayload = {
253
+ AttributeName: attributeName,
254
+ Code: code,
255
+ AccessToken: session.accessToken,
256
+ };
257
+ const result = await this.cognitoRequest(verifyUserAttributePayload, CognitoServiceTarget.VerifyUserAttribute);
258
+ }
414
259
  /**
415
260
  * Sign out the user and remove the current user session.
416
261
  *
417
262
  * @throws {AuthException}
418
263
  */
419
- CognitoClient.prototype.signOut = function () {
420
- return __awaiter(this, void 0, void 0, function () {
421
- var session, revokeTokenPayload;
422
- return __generator(this, function (_a) {
423
- switch (_a.label) {
424
- case 0: return [4 /*yield*/, this.getSession()];
425
- case 1:
426
- session = _a.sent();
427
- if (session === undefined) {
428
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
429
- }
430
- revokeTokenPayload = {
431
- Token: session.refreshToken,
432
- ClientId: this.userPoolClientId,
433
- };
434
- this.sessionStorage.setSession(undefined);
435
- return [4 /*yield*/, this.cognitoRequest(revokeTokenPayload, CognitoServiceTarget.RevokeToken)];
436
- case 2:
437
- _a.sent();
438
- return [2 /*return*/];
439
- }
440
- });
441
- });
442
- };
264
+ async signOut() {
265
+ const session = await this.getSession();
266
+ if (session === undefined) {
267
+ throw new AuthException('User must be authenticated', AuthError.UserNotAuthenticated);
268
+ }
269
+ const revokeTokenPayload = {
270
+ Token: session.refreshToken,
271
+ ClientId: this.userPoolClientId,
272
+ };
273
+ this.sessionStorage.setSession(undefined);
274
+ await this.cognitoRequest(revokeTokenPayload, CognitoServiceTarget.RevokeToken);
275
+ }
443
276
  /**
444
277
  * Request forgot password.
445
278
  * @param username Username
446
279
  *
447
280
  * @throws {AuthException}
448
281
  */
449
- CognitoClient.prototype.forgotPassword = function (username) {
450
- return __awaiter(this, void 0, void 0, function () {
451
- var forgotPasswordPayload;
452
- return __generator(this, function (_a) {
453
- switch (_a.label) {
454
- case 0:
455
- forgotPasswordPayload = {
456
- ClientId: this.userPoolClientId,
457
- Username: username,
458
- };
459
- return [4 /*yield*/, this.cognitoRequest(forgotPasswordPayload, CognitoServiceTarget.ForgotPassword)];
460
- case 1:
461
- _a.sent();
462
- return [2 /*return*/];
463
- }
464
- });
465
- });
466
- };
282
+ async forgotPassword(username) {
283
+ const forgotPasswordPayload = {
284
+ ClientId: this.userPoolClientId,
285
+ Username: username,
286
+ };
287
+ await this.cognitoRequest(forgotPasswordPayload, CognitoServiceTarget.ForgotPassword);
288
+ }
467
289
  /**
468
290
  * Confirms the new password via the given code send via cognito triggered by @see forgotPassword .
469
291
  *
@@ -473,48 +295,26 @@ var CognitoClient = /** @class */ (function () {
473
295
  *
474
296
  * @throws {AuthException}
475
297
  */
476
- CognitoClient.prototype.confirmForgotPassword = function (username, newPassword, confirmationCode) {
477
- return __awaiter(this, void 0, void 0, function () {
478
- var confirmForgotPasswordPayload;
479
- return __generator(this, function (_a) {
480
- switch (_a.label) {
481
- case 0:
482
- confirmForgotPasswordPayload = {
483
- ClientId: this.userPoolClientId,
484
- Username: username,
485
- ConfirmationCode: confirmationCode,
486
- Password: newPassword,
487
- };
488
- return [4 /*yield*/, this.cognitoRequest(confirmForgotPasswordPayload, CognitoServiceTarget.ConfirmForgotPassword)];
489
- case 1:
490
- _a.sent();
491
- return [2 /*return*/];
492
- }
493
- });
494
- });
495
- };
298
+ async confirmForgotPassword(username, newPassword, confirmationCode) {
299
+ const confirmForgotPasswordPayload = {
300
+ ClientId: this.userPoolClientId,
301
+ Username: username,
302
+ ConfirmationCode: confirmationCode,
303
+ Password: newPassword,
304
+ };
305
+ await this.cognitoRequest(confirmForgotPasswordPayload, CognitoServiceTarget.ConfirmForgotPassword);
306
+ }
496
307
  /**
497
308
  * Triggers cognito to resend the confirmation code
498
309
  * @param username Username
499
310
  */
500
- CognitoClient.prototype.resendConfirmationCode = function (username) {
501
- return __awaiter(this, void 0, void 0, function () {
502
- var resendConfirmationCodePayLoad;
503
- return __generator(this, function (_a) {
504
- switch (_a.label) {
505
- case 0:
506
- resendConfirmationCodePayLoad = {
507
- ClientId: this.userPoolClientId,
508
- Username: username,
509
- };
510
- return [4 /*yield*/, this.cognitoRequest(resendConfirmationCodePayLoad, CognitoServiceTarget.ResendConfirmationCode)];
511
- case 1:
512
- _a.sent();
513
- return [2 /*return*/];
514
- }
515
- });
516
- });
517
- };
311
+ async resendConfirmationCode(username) {
312
+ const resendConfirmationCodePayLoad = {
313
+ ClientId: this.userPoolClientId,
314
+ Username: username,
315
+ };
316
+ await this.cognitoRequest(resendConfirmationCodePayLoad, CognitoServiceTarget.ResendConfirmationCode);
317
+ }
518
318
  /**
519
319
  * Returns a link to Cognito`s Hosted UI for OAuth2 authentication.
520
320
  * This method works in conjunction with @see handleCodeFlow .
@@ -524,18 +324,18 @@ var CognitoClient = /** @class */ (function () {
524
324
  *
525
325
  * @throws {Error}
526
326
  */
527
- CognitoClient.prototype.generateOAuthSignInUrl = function (identityProvider) {
327
+ generateOAuthSignInUrl(identityProvider) {
528
328
  if (this.oAuth === undefined) {
529
329
  throw Error('You have to define oAuth options to use generateFederatedSignUrl');
530
330
  }
531
- var state = (0, randombytes_1.default)(32).toString('hex');
532
- var pkce = (0, randombytes_1.default)(128).toString('hex');
533
- var code_challenge = Buffer.from((0, hash_js_1.sha256)().update(pkce).digest())
331
+ const state = randomBytes(32).toString('hex');
332
+ const pkce = randomBytes(128).toString('hex');
333
+ const code_challenge = Buffer.from(sha256().update(pkce).digest())
534
334
  .toString('base64')
535
335
  .replace(/\+/g, '-')
536
336
  .replace(/\//g, '_')
537
337
  .replace(/=+$/, '');
538
- var queryParams = new URLSearchParams();
338
+ const queryParams = new URLSearchParams();
539
339
  queryParams.append('redirect_uri', this.oAuth.redirectUrl);
540
340
  queryParams.append('response_type', this.oAuth.responseType);
541
341
  queryParams.append('client_id', this.userPoolClientId);
@@ -545,11 +345,11 @@ var CognitoClient = /** @class */ (function () {
545
345
  queryParams.append('code_challenge', code_challenge);
546
346
  queryParams.append('code_challenge_method', 'S256');
547
347
  this.sessionStorage.setOauthVerificationParams({
548
- state: state,
549
- pkce: pkce,
348
+ state,
349
+ pkce,
550
350
  });
551
- return "".concat(this.oAuth.cognitoDomain, "/oauth2/authorize?").concat(queryParams.toString());
552
- };
351
+ return `${this.oAuth.cognitoDomain}/oauth2/authorize?${queryParams.toString()}`;
352
+ }
553
353
  /**
554
354
  *
555
355
  * Handles Cognito`s OAuth2 code flow after redirection from Cognito`s Hosted UI.
@@ -561,63 +361,49 @@ var CognitoClient = /** @class */ (function () {
561
361
  *
562
362
  * @throws {Error}
563
363
  */
564
- CognitoClient.prototype.handleCodeFlow = function (returnUrl) {
565
- return __awaiter(this, void 0, void 0, function () {
566
- var url, code, state, oAuthVerificationParams, urlParams, tokenEndpoint, response, _a, access_token, refresh_token, id_token, expires_in, token_type, error, session;
567
- return __generator(this, function (_b) {
568
- switch (_b.label) {
569
- case 0:
570
- if (this.oAuth === undefined) {
571
- throw Error('You have to define oAuth options to use handleCodeFlow');
572
- }
573
- url = new URL(returnUrl);
574
- code = url.searchParams.get('code');
575
- state = url.searchParams.get('state');
576
- if (code === null || state === null) {
577
- throw Error('code or state parameter is missing from return url.');
578
- }
579
- oAuthVerificationParams = this.sessionStorage.getOauthVerificationParams();
580
- if (oAuthVerificationParams === undefined) {
581
- throw new Error('OAuth verification parameters are missing, did you forgot to call generateOAuthSignInUrl ?');
582
- }
583
- if (oAuthVerificationParams.state !== state) {
584
- throw new Error('state parameter does not match with previous value generated by previous call of generateOAuthSignInUrl .');
585
- }
586
- urlParams = new URLSearchParams();
587
- urlParams.append('grant_type', 'authorization_code');
588
- urlParams.append('code', code);
589
- urlParams.append('client_id', this.userPoolClientId);
590
- urlParams.append('redirect_uri', this.oAuth.redirectUrl);
591
- urlParams.append('code_verifier', oAuthVerificationParams.pkce);
592
- tokenEndpoint = "".concat(this.oAuth.cognitoDomain, "/oauth2/token");
593
- return [4 /*yield*/, fetch(tokenEndpoint, {
594
- method: 'POST',
595
- headers: {
596
- 'Content-Type': 'application/x-www-form-urlencoded',
597
- },
598
- body: urlParams.toString(),
599
- })];
600
- case 1:
601
- response = _b.sent();
602
- return [4 /*yield*/, response.json()];
603
- case 2:
604
- _a = _b.sent(), access_token = _a.access_token, refresh_token = _a.refresh_token, id_token = _a.id_token, expires_in = _a.expires_in, token_type = _a.token_type, error = _a.error;
605
- if (error) {
606
- throw new Error(error);
607
- }
608
- session = CognitoClient.authResultToSession({
609
- AccessToken: access_token,
610
- RefreshToken: refresh_token,
611
- IdToken: id_token,
612
- ExpiresIn: expires_in,
613
- TokenType: token_type,
614
- });
615
- this.sessionStorage.setSession(session);
616
- return [2 /*return*/, session];
617
- }
618
- });
364
+ async handleCodeFlow(returnUrl) {
365
+ if (this.oAuth === undefined) {
366
+ throw Error('You have to define oAuth options to use handleCodeFlow');
367
+ }
368
+ const url = new URL(returnUrl);
369
+ const code = url.searchParams.get('code');
370
+ const state = url.searchParams.get('state');
371
+ if (code === null || state === null) {
372
+ throw Error('code or state parameter is missing from return url.');
373
+ }
374
+ const oAuthVerificationParams = this.sessionStorage.getOauthVerificationParams();
375
+ if (oAuthVerificationParams === undefined) {
376
+ throw new Error('OAuth verification parameters are missing, did you forgot to call generateOAuthSignInUrl ?');
377
+ }
378
+ if (oAuthVerificationParams.state !== state) {
379
+ throw new Error('state parameter does not match with previous value generated by previous call of generateOAuthSignInUrl .');
380
+ }
381
+ const urlParams = new URLSearchParams();
382
+ urlParams.append('grant_type', 'authorization_code');
383
+ urlParams.append('code', code);
384
+ urlParams.append('client_id', this.userPoolClientId);
385
+ urlParams.append('redirect_uri', this.oAuth.redirectUrl);
386
+ urlParams.append('code_verifier', oAuthVerificationParams.pkce);
387
+ const tokenEndpoint = `${this.oAuth.cognitoDomain}/oauth2/token`;
388
+ const response = await fetch(tokenEndpoint, {
389
+ method: 'POST',
390
+ headers: {
391
+ 'Content-Type': 'application/x-www-form-urlencoded',
392
+ },
393
+ body: urlParams.toString(),
619
394
  });
620
- };
621
- return CognitoClient;
622
- }());
623
- exports.CognitoClient = CognitoClient;
395
+ const { access_token, refresh_token, id_token, expires_in, token_type, error } = await response.json();
396
+ if (error) {
397
+ throw new Error(error);
398
+ }
399
+ const session = CognitoClient.authResultToSession({
400
+ AccessToken: access_token,
401
+ RefreshToken: refresh_token,
402
+ IdToken: id_token,
403
+ ExpiresIn: expires_in,
404
+ TokenType: token_type,
405
+ });
406
+ this.sessionStorage.setSession(session);
407
+ return session;
408
+ }
409
+ }