idea-aws 4.4.1 → 4.4.2

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.
Files changed (48) hide show
  1. package/dist/src/attachments.d.ts +27 -0
  2. package/dist/src/attachments.js +39 -0
  3. package/dist/src/cognito.d.ts +177 -0
  4. package/dist/src/cognito.js +412 -0
  5. package/dist/src/comprehend.d.ts +34 -0
  6. package/dist/src/comprehend.js +58 -0
  7. package/dist/src/dynamoDB.d.ts +108 -0
  8. package/dist/src/dynamoDB.js +296 -0
  9. package/dist/src/genericController.d.ts +60 -0
  10. package/dist/src/genericController.js +89 -0
  11. package/dist/src/lambdaLogger.d.ts +13 -0
  12. package/dist/src/lambdaLogger.js +43 -0
  13. package/dist/src/logger.d.ts +10 -0
  14. package/dist/src/logger.js +16 -0
  15. package/dist/src/metrics.d.ts +31 -0
  16. package/dist/src/metrics.js +45 -0
  17. package/dist/src/resourceController.d.ts +232 -0
  18. package/dist/src/resourceController.js +561 -0
  19. package/dist/src/s3.d.ts +225 -0
  20. package/dist/src/s3.js +180 -0
  21. package/dist/src/secretsManager.d.ts +15 -0
  22. package/dist/src/secretsManager.js +48 -0
  23. package/dist/src/ses.d.ts +161 -0
  24. package/dist/src/ses.js +196 -0
  25. package/dist/src/sns.d.ts +60 -0
  26. package/dist/src/sns.js +94 -0
  27. package/dist/src/ssm.d.ts +22 -0
  28. package/dist/src/ssm.js +54 -0
  29. package/dist/src/streamController.d.ts +11 -0
  30. package/dist/src/streamController.js +20 -0
  31. package/dist/src/translate.d.ts +61 -0
  32. package/dist/src/translate.js +155 -0
  33. package/package.json +2 -2
  34. package/src/attachments.ts +41 -0
  35. package/src/cognito.ts +511 -0
  36. package/src/comprehend.ts +52 -0
  37. package/src/dynamoDB.ts +311 -0
  38. package/src/genericController.ts +103 -0
  39. package/src/lambdaLogger.ts +39 -0
  40. package/src/metrics.ts +45 -0
  41. package/src/resourceController.ts +645 -0
  42. package/src/s3.ts +334 -0
  43. package/src/secretsManager.ts +24 -0
  44. package/src/ses.ts +313 -0
  45. package/src/sns.ts +118 -0
  46. package/src/ssm.ts +33 -0
  47. package/src/streamController.ts +25 -0
  48. package/src/translate.ts +174 -0
@@ -0,0 +1,27 @@
1
+ import { SignedURL } from 'idea-toolbox';
2
+ import { DynamoDB } from './dynamoDB';
3
+ import { S3 } from './s3';
4
+ /**
5
+ * A custom class that takes advantage of DynamoDB and S3 to easily manage attachments.
6
+ */
7
+ export declare class Attachments {
8
+ protected ddb: DynamoDB;
9
+ protected s3: S3;
10
+ /**
11
+ * The bucket where from to retrieve the attachments. Fallback to IDEA's default one.
12
+ */
13
+ protected S3_ATTACHMENTS_BUCKET: string;
14
+ /**
15
+ * The prefix for attachment IDs. Fallback to IDEA's default one.
16
+ */
17
+ protected IUID_ATTACHMENTS_PREFIX: string;
18
+ constructor(ddb: DynamoDB, s3: S3);
19
+ /**
20
+ * Get a signedURL to put an attachment.
21
+ */
22
+ put(project: string, teamId: string): Promise<SignedURL>;
23
+ /**
24
+ * Get a signedURL to retrieve an attachment.
25
+ */
26
+ get(attachmentId: string): Promise<SignedURL>;
27
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Attachments = void 0;
4
+ /**
5
+ * A custom class that takes advantage of DynamoDB and S3 to easily manage attachments.
6
+ */
7
+ class Attachments {
8
+ constructor(ddb, s3) {
9
+ this.ddb = ddb;
10
+ this.s3 = s3;
11
+ /**
12
+ * The bucket where from to retrieve the attachments. Fallback to IDEA's default one.
13
+ */
14
+ this.S3_ATTACHMENTS_BUCKET = process.env.S3_ATTACHMENTS_BUCKET ?? 'idea-attachments';
15
+ /**
16
+ * The prefix for attachment IDs. Fallback to IDEA's default one.
17
+ */
18
+ this.IUID_ATTACHMENTS_PREFIX = process.env.IUID_ATTACHMENTS_PREFIX ?? 'ATT';
19
+ }
20
+ /**
21
+ * Get a signedURL to put an attachment.
22
+ */
23
+ async put(project, teamId) {
24
+ const attachmentIdPrefix = this.IUID_ATTACHMENTS_PREFIX.concat('_', project, '_', teamId);
25
+ const attachmentId = await this.ddb.IUNID(attachmentIdPrefix);
26
+ const signedURL = await this.s3.signedURLPut(this.S3_ATTACHMENTS_BUCKET, attachmentId);
27
+ signedURL.id = attachmentId;
28
+ return signedURL;
29
+ }
30
+ /**
31
+ * Get a signedURL to retrieve an attachment.
32
+ */
33
+ async get(attachmentId) {
34
+ const signedURL = await this.s3.signedURLGet(this.S3_ATTACHMENTS_BUCKET, attachmentId);
35
+ signedURL.id = attachmentId;
36
+ return signedURL;
37
+ }
38
+ }
39
+ exports.Attachments = Attachments;
@@ -0,0 +1,177 @@
1
+ import * as CognitoIP from '@aws-sdk/client-cognito-identity-provider';
2
+ import { CognitoUser } from 'idea-toolbox';
3
+ /**
4
+ * A wrapper for AWS Cognito.
5
+ */
6
+ export declare class Cognito {
7
+ protected cognito: CognitoIP.CognitoIdentityProviderClient;
8
+ constructor(options?: {
9
+ region?: string;
10
+ });
11
+ /**
12
+ * Change the region in which to find the user pool.
13
+ * Default: the runner's (e.g. Lambda function) region.
14
+ */
15
+ setRegion(region: string): void;
16
+ /**
17
+ * Get the attributes of the user, from the authorizer claims.
18
+ * @param claims authorizer claims
19
+ * @return user's data
20
+ * @deprecated use idea-toolbox's CognitoUser instead
21
+ */
22
+ getUserByClaims(claims: Record<string, any>): CognitoUserGeneric;
23
+ /**
24
+ * Map the complex structure returned by Cognito for a user's attributes in a simple key-value object.
25
+ */
26
+ private mapCognitoUserAttributesAsPlainObject;
27
+ /**
28
+ * Identify a user by its email address, returning its attributes.
29
+ */
30
+ getUserByEmail(email: string, userPoolId: string): Promise<CognitoUserGeneric>;
31
+ /**
32
+ * Identify a user by its userId (sub), returning its attributes.
33
+ */
34
+ getUserBySub(sub: string, userPoolId: string): Promise<CognitoUserGeneric>;
35
+ /**
36
+ * List all the users of the pool.
37
+ */
38
+ listUsers(userPoolId: string, options?: {
39
+ pagination?: string;
40
+ users: CognitoUser[];
41
+ }): Promise<CognitoUser[]>;
42
+ /**
43
+ * List all the users of the pool, including the information about the groups they're in.
44
+ * Note: it's slower than the alternative `getAllUsers`: use it only when needed.
45
+ */
46
+ listUsersWithGroupsDetail(cognitoUserPoolId: string): Promise<CognitoUser[]>;
47
+ /**
48
+ * Create a new user (by its email) in the pool specified.
49
+ * @return userId of the new user
50
+ */
51
+ createUser(cognitoUserOrEmail: CognitoUser | string, userPoolId: string, options?: CreateUserOptions): Promise<string>;
52
+ /**
53
+ * Resend the password to a user who never logged in.
54
+ */
55
+ resendPassword(email: string, userPoolId: string, options?: CreateUserOptions): Promise<void>;
56
+ /**
57
+ * Set a new password for a specific user identified by its email (admin-only).
58
+ * If not specified, the password is generated randomly, and the user must change it at the first login.
59
+ */
60
+ setPassword(email: string, userPoolId: string, options?: {
61
+ password?: string;
62
+ permanent?: boolean;
63
+ }): Promise<void>;
64
+ /**
65
+ * Delete a user by its email (username), in the pool specified.
66
+ */
67
+ deleteUser(email: string, userPoolId: string): Promise<void>;
68
+ /**
69
+ * Sign in a user of a specific pool through username and password.
70
+ */
71
+ signIn(email: string, password: string, userPoolId: string, userPoolClientId: string): Promise<CognitoIP.AuthenticationResultType>;
72
+ /**
73
+ * Given a username and a refresh token (and pool data), refresh the session and return the new tokens.
74
+ */
75
+ refreshSession(email: string, refreshToken: string, userPoolId: string, userPoolClientId: string): Promise<CognitoIP.AuthenticationResultType>;
76
+ /**
77
+ * Change the email address (== username) associated to a user.
78
+ */
79
+ updateEmail(email: string, newEmail: string, userPoolId: string): Promise<void>;
80
+ /**
81
+ * Change the password to sign in for a user.
82
+ */
83
+ updatePassword(email: string, oldPassword: string, newPassword: string, userPoolId: string, userPoolClientId: string): Promise<void>;
84
+ /**
85
+ * Send to a user the instructions to change the password.
86
+ */
87
+ forgotPassword(email: string, userPoolClientId: string): Promise<CognitoIP.CodeDeliveryDetailsType>;
88
+ /**
89
+ * Complete the flow of a password forgot.
90
+ */
91
+ confirmForgotPassword(email: string, newPassword: string, confirmationCode: string, userPoolClientId: string): Promise<void>;
92
+ /**
93
+ * Update a (Cognito)User's attributes, excluding the attributes that require specific methods.
94
+ */
95
+ updateUser(user: CognitoUser, userPoolId: string): Promise<void>;
96
+ /**
97
+ * Sign out the user from all devices.
98
+ */
99
+ globalSignOut(email: string, userPoolId: string): Promise<void>;
100
+ /**
101
+ * Confirm and conclude a registration, usign a confirmation code.
102
+ */
103
+ confirmSignUp(email: string, confirmationCode: string, userPoolClientId: string): Promise<void>;
104
+ /**
105
+ * List the groups of the user pool.
106
+ */
107
+ listGroups(userPoolId: string, options?: {
108
+ pagination?: string;
109
+ groups: CognitoGroup[];
110
+ }): Promise<CognitoGroup[]>;
111
+ /**
112
+ * Create a new group in the user pool.
113
+ */
114
+ createGroup(groupName: string, userPoolId: string): Promise<void>;
115
+ /**
116
+ * Delete a group from the user pool.
117
+ */
118
+ deleteGroup(groupName: string, userPoolId: string): Promise<void>;
119
+ /**
120
+ * List the users part of a group in the user pool.
121
+ */
122
+ listUsersInGroup(group: string, userPoolId: string, options?: {
123
+ pagination?: string;
124
+ users: CognitoUser[];
125
+ }): Promise<CognitoUser[]>;
126
+ /**
127
+ * Add a user (by email) to a group in the user pool.
128
+ */
129
+ addUserToGroup(email: string, group: string, userPoolId: string): Promise<void>;
130
+ /**
131
+ * Remove a user (by email) from a group in the user pool.
132
+ */
133
+ removeUserFromGroup(email: string, group: string, userPoolId: string): Promise<void>;
134
+ }
135
+ /**
136
+ * The attributes of a generic Cognito user of which we don't know the custom attributes.
137
+ */
138
+ export interface CognitoUserGeneric {
139
+ /**
140
+ * The user id (sub).
141
+ */
142
+ userId: string;
143
+ /**
144
+ * The email (=== username).
145
+ */
146
+ email: string;
147
+ /**
148
+ * Cognito can have custom attributes.
149
+ */
150
+ [attribute: string]: string;
151
+ }
152
+ /**
153
+ * Options when creating a new user.
154
+ */
155
+ export interface CreateUserOptions {
156
+ /**
157
+ * Uf true, don't send the default Cognito email notification
158
+ */
159
+ skipNotification?: boolean;
160
+ /**
161
+ * If null, randomly generated
162
+ */
163
+ temporaryPassword?: string;
164
+ }
165
+ /**
166
+ * The attributes of a Cognito group.
167
+ */
168
+ export interface CognitoGroup {
169
+ /**
170
+ * The name (and id) of the group.
171
+ */
172
+ name: string;
173
+ /**
174
+ * The description of the group.
175
+ */
176
+ description: string;
177
+ }
@@ -0,0 +1,412 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.Cognito = void 0;
27
+ const CognitoIP = __importStar(require("@aws-sdk/client-cognito-identity-provider"));
28
+ const idea_toolbox_1 = require("idea-toolbox");
29
+ /**
30
+ * A wrapper for AWS Cognito.
31
+ */
32
+ class Cognito {
33
+ constructor(options = {}) {
34
+ this.cognito = new CognitoIP.CognitoIdentityProviderClient({ region: options.region });
35
+ }
36
+ /**
37
+ * Change the region in which to find the user pool.
38
+ * Default: the runner's (e.g. Lambda function) region.
39
+ */
40
+ setRegion(region) {
41
+ // there is no quick way to change the region without re-creating the object
42
+ this.cognito = new CognitoIP.CognitoIdentityProviderClient({ region });
43
+ }
44
+ /**
45
+ * Get the attributes of the user, from the authorizer claims.
46
+ * @param claims authorizer claims
47
+ * @return user's data
48
+ * @deprecated use idea-toolbox's CognitoUser instead
49
+ */
50
+ getUserByClaims(claims) {
51
+ if (!claims)
52
+ return null;
53
+ const user = {};
54
+ // add any additional cognito attribute available in cognito
55
+ for (const p in claims)
56
+ if (p.startsWith('cognito:'))
57
+ user[p.slice(8)] = claims[p];
58
+ // map the important attributes with reserved names
59
+ user.userId = claims.sub;
60
+ user.email = claims.email;
61
+ return user;
62
+ }
63
+ /**
64
+ * Map the complex structure returned by Cognito for a user's attributes in a simple key-value object.
65
+ */
66
+ mapCognitoUserAttributesAsPlainObject(user) {
67
+ const userAttributes = {};
68
+ (user.Attributes ?? user.UserAttributes ?? []).forEach((a) => (userAttributes[a.Name] = a.Value));
69
+ if (!userAttributes.userId)
70
+ userAttributes.userId = userAttributes.sub;
71
+ return userAttributes;
72
+ }
73
+ //
74
+ // ADMIN
75
+ //
76
+ /**
77
+ * Identify a user by its email address, returning its attributes.
78
+ */
79
+ async getUserByEmail(email, userPoolId) {
80
+ const command = new CognitoIP.AdminGetUserCommand({ UserPoolId: userPoolId, Username: email });
81
+ try {
82
+ const user = await this.cognito.send(command);
83
+ return this.mapCognitoUserAttributesAsPlainObject(user);
84
+ }
85
+ catch (error) {
86
+ if (error.name === 'UserNotFoundException')
87
+ throw new Error('User not found');
88
+ throw error;
89
+ }
90
+ }
91
+ /**
92
+ * Identify a user by its userId (sub), returning its attributes.
93
+ */
94
+ async getUserBySub(sub, userPoolId) {
95
+ // as of today, there is no a direct way to find a user by its sub: we need to run a query against the users base
96
+ const command = new CognitoIP.ListUsersCommand({ UserPoolId: userPoolId, Filter: `sub = "${sub}"`, Limit: 1 });
97
+ const { Users } = await this.cognito.send(command);
98
+ if (Users.length < 1)
99
+ throw new Error('User not found');
100
+ return this.mapCognitoUserAttributesAsPlainObject(Users[0]);
101
+ }
102
+ /**
103
+ * List all the users of the pool.
104
+ */
105
+ async listUsers(userPoolId, options = { users: [] }) {
106
+ const params = { UserPoolId: userPoolId };
107
+ if (options.pagination)
108
+ params.PaginationToken = options.pagination;
109
+ const { Users, PaginationToken: pagination } = await this.cognito.send(new CognitoIP.ListUsersCommand(params));
110
+ const users = options.users.concat(Users.map(u => new idea_toolbox_1.CognitoUser(this.mapCognitoUserAttributesAsPlainObject(u))));
111
+ if (pagination)
112
+ return await this.listUsers(userPoolId, { pagination, users });
113
+ else
114
+ return users;
115
+ }
116
+ /**
117
+ * List all the users of the pool, including the information about the groups they're in.
118
+ * Note: it's slower than the alternative `getAllUsers`: use it only when needed.
119
+ */
120
+ async listUsersWithGroupsDetail(cognitoUserPoolId) {
121
+ const groups = await this.listGroups(cognitoUserPoolId);
122
+ const users = [];
123
+ for (const group of groups) {
124
+ const usersOfGroup = await this.listUsersInGroup(group.name, cognitoUserPoolId);
125
+ usersOfGroup.forEach(userInGroup => {
126
+ const userAlreadyInOutputList = users.find(u => u.userId === userInGroup.userId);
127
+ if (userAlreadyInOutputList)
128
+ userAlreadyInOutputList.groups.push(group.name);
129
+ else {
130
+ userInGroup.groups.push(group.name);
131
+ users.push(userInGroup);
132
+ }
133
+ });
134
+ }
135
+ return users;
136
+ }
137
+ /**
138
+ * Create a new user (by its email) in the pool specified.
139
+ * @return userId of the new user
140
+ */
141
+ async createUser(cognitoUserOrEmail, userPoolId, options = {}) {
142
+ const email = typeof cognitoUserOrEmail === 'string'
143
+ ? cognitoUserOrEmail
144
+ : cognitoUserOrEmail.email;
145
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
146
+ throw new Error('INVALID_EMAIL');
147
+ const UserAttributes = [
148
+ { Name: 'email', Value: email },
149
+ { Name: 'email_verified', Value: 'true' }
150
+ ];
151
+ if (typeof cognitoUserOrEmail === 'object') {
152
+ const user = cognitoUserOrEmail;
153
+ UserAttributes.push({ Name: 'name', Value: user.name });
154
+ UserAttributes.push({ Name: 'picture', Value: user.picture || '' });
155
+ Object.keys(user.attributes).forEach(a => UserAttributes.push({ Name: 'custom:'.concat(a), Value: String(user.attributes[a]) }));
156
+ }
157
+ const params = { UserPoolId: userPoolId, Username: email, UserAttributes };
158
+ if (options.skipNotification)
159
+ params.MessageAction = 'SUPPRESS';
160
+ if (options.temporaryPassword)
161
+ params.TemporaryPassword = options.temporaryPassword;
162
+ const { User } = await this.cognito.send(new CognitoIP.AdminCreateUserCommand(params));
163
+ const userId = this.mapCognitoUserAttributesAsPlainObject(User).sub;
164
+ if (!userId)
165
+ throw new Error('Creation failed');
166
+ return userId;
167
+ }
168
+ /**
169
+ * Resend the password to a user who never logged in.
170
+ */
171
+ async resendPassword(email, userPoolId, options = {}) {
172
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
173
+ throw new Error('Invalid email');
174
+ const params = {
175
+ UserPoolId: userPoolId,
176
+ Username: email,
177
+ MessageAction: 'RESEND'
178
+ };
179
+ if (options.temporaryPassword)
180
+ params.TemporaryPassword = options.temporaryPassword;
181
+ await this.cognito.send(new CognitoIP.AdminCreateUserCommand(params));
182
+ }
183
+ /**
184
+ * Set a new password for a specific user identified by its email (admin-only).
185
+ * If not specified, the password is generated randomly, and the user must change it at the first login.
186
+ */
187
+ async setPassword(email, userPoolId, options = {}) {
188
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
189
+ throw new Error('Invalid email');
190
+ const RANDOM_PASSWORD_LENGTH = 8;
191
+ const password = options.password ??
192
+ Math.random()
193
+ .toString(36)
194
+ .slice(2, 2 + RANDOM_PASSWORD_LENGTH);
195
+ const params = {
196
+ UserPoolId: userPoolId,
197
+ Username: email,
198
+ Password: password,
199
+ Permanent: options.permanent
200
+ };
201
+ await this.cognito.send(new CognitoIP.AdminSetUserPasswordCommand(params));
202
+ }
203
+ /**
204
+ * Delete a user by its email (username), in the pool specified.
205
+ */
206
+ async deleteUser(email, userPoolId) {
207
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
208
+ throw new Error('Invalid email');
209
+ const command = new CognitoIP.AdminDeleteUserCommand({ UserPoolId: userPoolId, Username: email });
210
+ await this.cognito.send(command);
211
+ }
212
+ //
213
+ // USER
214
+ //
215
+ /**
216
+ * Sign in a user of a specific pool through username and password.
217
+ */
218
+ async signIn(email, password, userPoolId, userPoolClientId) {
219
+ const command = new CognitoIP.AdminInitiateAuthCommand({
220
+ UserPoolId: userPoolId,
221
+ ClientId: userPoolClientId,
222
+ AuthFlow: 'ADMIN_NO_SRP_AUTH',
223
+ AuthParameters: { USERNAME: email, PASSWORD: password }
224
+ });
225
+ const { AuthenticationResult } = await this.cognito.send(command);
226
+ if (!AuthenticationResult)
227
+ throw new Error('Sign-in failed');
228
+ return AuthenticationResult;
229
+ }
230
+ /**
231
+ * Given a username and a refresh token (and pool data), refresh the session and return the new tokens.
232
+ */
233
+ async refreshSession(email, refreshToken, userPoolId, userPoolClientId) {
234
+ const command = new CognitoIP.AdminInitiateAuthCommand({
235
+ UserPoolId: userPoolId,
236
+ ClientId: userPoolClientId,
237
+ AuthFlow: 'REFRESH_TOKEN_AUTH',
238
+ AuthParameters: { USERNAME: email, REFRESH_TOKEN: refreshToken }
239
+ });
240
+ const { AuthenticationResult } = await this.cognito.send(command);
241
+ if (!AuthenticationResult)
242
+ throw new Error('Refresh failed');
243
+ return AuthenticationResult;
244
+ }
245
+ /**
246
+ * Change the email address (== username) associated to a user.
247
+ */
248
+ async updateEmail(email, newEmail, userPoolId) {
249
+ if ((0, idea_toolbox_1.isEmpty)(newEmail, 'email'))
250
+ throw new Error('Invalid new email');
251
+ const command = new CognitoIP.AdminUpdateUserAttributesCommand({
252
+ UserPoolId: userPoolId,
253
+ Username: email,
254
+ UserAttributes: [
255
+ { Name: 'email', Value: newEmail },
256
+ { Name: 'email_verified', Value: 'true' }
257
+ ]
258
+ });
259
+ await this.cognito.send(command);
260
+ // sign out the user from all its devices and resolve
261
+ await this.globalSignOut(newEmail, userPoolId);
262
+ }
263
+ /**
264
+ * Change the password to sign in for a user.
265
+ */
266
+ async updatePassword(email, oldPassword, newPassword, userPoolId, userPoolClientId) {
267
+ if (newPassword.length < 8)
268
+ throw new Error('Invalid new password');
269
+ const tokensForPasswordChange = await this.signIn(email, oldPassword, userPoolId, userPoolClientId);
270
+ const command = new CognitoIP.ChangePasswordCommand({
271
+ AccessToken: tokensForPasswordChange.AccessToken,
272
+ PreviousPassword: oldPassword,
273
+ ProposedPassword: newPassword
274
+ });
275
+ await this.cognito.send(command);
276
+ }
277
+ /**
278
+ * Send to a user the instructions to change the password.
279
+ */
280
+ async forgotPassword(email, userPoolClientId) {
281
+ const command = new CognitoIP.ForgotPasswordCommand({ Username: email, ClientId: userPoolClientId });
282
+ const { CodeDeliveryDetails } = await this.cognito.send(command);
283
+ return CodeDeliveryDetails;
284
+ }
285
+ /**
286
+ * Complete the flow of a password forgot.
287
+ */
288
+ async confirmForgotPassword(email, newPassword, confirmationCode, userPoolClientId) {
289
+ const command = new CognitoIP.ConfirmForgotPasswordCommand({
290
+ ClientId: userPoolClientId,
291
+ Username: email,
292
+ ConfirmationCode: confirmationCode,
293
+ Password: newPassword
294
+ });
295
+ await this.cognito.send(command);
296
+ }
297
+ /**
298
+ * Update a (Cognito)User's attributes, excluding the attributes that require specific methods.
299
+ */
300
+ async updateUser(user, userPoolId) {
301
+ const UserAttributes = [
302
+ { Name: 'name', Value: user.name },
303
+ { Name: 'picture', Value: user.picture ?? '' }
304
+ ];
305
+ Object.keys(user.attributes).forEach(customAttribute => UserAttributes.push({
306
+ Name: 'custom:'.concat(customAttribute),
307
+ Value: String(user.attributes[customAttribute])
308
+ }));
309
+ const command = new CognitoIP.AdminUpdateUserAttributesCommand({
310
+ UserPoolId: userPoolId,
311
+ Username: user.email,
312
+ UserAttributes
313
+ });
314
+ await this.cognito.send(command);
315
+ }
316
+ /**
317
+ * Sign out the user from all devices.
318
+ */
319
+ async globalSignOut(email, userPoolId) {
320
+ const command = new CognitoIP.AdminUserGlobalSignOutCommand({ Username: email, UserPoolId: userPoolId });
321
+ await this.cognito.send(command);
322
+ }
323
+ /**
324
+ * Confirm and conclude a registration, usign a confirmation code.
325
+ */
326
+ async confirmSignUp(email, confirmationCode, userPoolClientId) {
327
+ if (!email)
328
+ throw new Error('Invalid email');
329
+ if (!confirmationCode)
330
+ throw new Error('Invalid confirmation code');
331
+ if (!userPoolClientId)
332
+ throw new Error('Invalid client ID');
333
+ const command = new CognitoIP.ConfirmSignUpCommand({
334
+ Username: email,
335
+ ConfirmationCode: confirmationCode,
336
+ ClientId: userPoolClientId
337
+ });
338
+ await this.cognito.send(command);
339
+ }
340
+ /**
341
+ * List the groups of the user pool.
342
+ */
343
+ async listGroups(userPoolId, options = { groups: [] }) {
344
+ const params = { UserPoolId: userPoolId };
345
+ if (options.pagination)
346
+ params.NextToken = options.pagination;
347
+ const res = await this.cognito.send(new CognitoIP.ListGroupsCommand(params));
348
+ const pagination = res.NextToken;
349
+ const groups = options.groups.concat(res.Groups.map(g => ({ name: g.GroupName, description: g.Description })));
350
+ if (pagination)
351
+ return await this.listGroups(userPoolId, { pagination, groups });
352
+ else
353
+ return groups;
354
+ }
355
+ /**
356
+ * Create a new group in the user pool.
357
+ */
358
+ async createGroup(groupName, userPoolId) {
359
+ const command = new CognitoIP.CreateGroupCommand({ GroupName: groupName, UserPoolId: userPoolId });
360
+ await this.cognito.send(command);
361
+ }
362
+ /**
363
+ * Delete a group from the user pool.
364
+ */
365
+ async deleteGroup(groupName, userPoolId) {
366
+ const command = new CognitoIP.DeleteGroupCommand({ GroupName: groupName, UserPoolId: userPoolId });
367
+ await this.cognito.send(command);
368
+ }
369
+ /**
370
+ * List the users part of a group in the user pool.
371
+ */
372
+ async listUsersInGroup(group, userPoolId, options = { users: [] }) {
373
+ const params = {
374
+ UserPoolId: userPoolId,
375
+ GroupName: group
376
+ };
377
+ if (options.pagination)
378
+ params.NextToken = options.pagination;
379
+ const res = await this.cognito.send(new CognitoIP.ListUsersInGroupCommand(params));
380
+ const pagination = res.NextToken;
381
+ const users = options.users.concat(res.Users.map(u => new idea_toolbox_1.CognitoUser(this.mapCognitoUserAttributesAsPlainObject(u))));
382
+ if (pagination)
383
+ return await this.listUsersInGroup(group, userPoolId, { pagination, users });
384
+ else
385
+ return users;
386
+ }
387
+ /**
388
+ * Add a user (by email) to a group in the user pool.
389
+ */
390
+ async addUserToGroup(email, group, userPoolId) {
391
+ const user = new idea_toolbox_1.CognitoUser(await this.getUserByEmail(email, userPoolId));
392
+ const command = new CognitoIP.AdminAddUserToGroupCommand({
393
+ UserPoolId: userPoolId,
394
+ GroupName: group,
395
+ Username: user.userId
396
+ });
397
+ await this.cognito.send(command);
398
+ }
399
+ /**
400
+ * Remove a user (by email) from a group in the user pool.
401
+ */
402
+ async removeUserFromGroup(email, group, userPoolId) {
403
+ const user = new idea_toolbox_1.CognitoUser(await this.getUserByEmail(email, userPoolId));
404
+ const command = new CognitoIP.AdminRemoveUserFromGroupCommand({
405
+ UserPoolId: userPoolId,
406
+ GroupName: group,
407
+ Username: user.userId
408
+ });
409
+ await this.cognito.send(command);
410
+ }
411
+ }
412
+ exports.Cognito = Cognito;
@@ -0,0 +1,34 @@
1
+ import * as AmazonComprehend from '@aws-sdk/client-comprehend';
2
+ import { Sentiment } from 'idea-toolbox';
3
+ /**
4
+ * A wrapper for Amazon Comprehend.
5
+ */
6
+ export declare class Comprehend {
7
+ protected comprehend: AmazonComprehend.ComprehendClient;
8
+ constructor(options?: {
9
+ region?: string;
10
+ });
11
+ /**
12
+ * Inspects text and returns an inference of the prevailing sentiment (POSITIVE, NEUTRAL, MIXED, or NEGATIVE).
13
+ */
14
+ detectSentiment(params: DetectSentimentParameters): Promise<Sentiment>;
15
+ /**
16
+ * Determines the dominant language of the input text.
17
+ */
18
+ detectDominantLanguage(params: {
19
+ text: string;
20
+ }): Promise<string>;
21
+ }
22
+ export interface DetectSentimentParameters {
23
+ /**
24
+ * The language of the input contents. You can specify any of the primary languages supported by Amazon Comprehend.
25
+ * All contents must be in the same language. Required.
26
+ * Valid Values: en | es | fr | de | it | pt | ar | hi | ja | ko | zh | zh-TW
27
+ */
28
+ language: string;
29
+ /**
30
+ * The text to analyze. Required.
31
+ * A UTF-8 text string. Each string must contain fewer that 5,000 bytes of UTF-8 encoded characters.
32
+ */
33
+ text: string;
34
+ }