forked from clientIO/appmixer-connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-commons.js
211 lines (172 loc) · 6.85 KB
/
aws-commons.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
'use strict';
const AWS = require('aws-sdk');
const crypto = require('crypto');
module.exports = {
init(context) {
const region = context.messages.in?.content?.region || context.properties.region;
AWS.config.update({
signatureVersion: 'v4',
region: region || 'us-east-1'
});
const { accessKeyId, secretKey } = context.auth;
const credentials = new AWS.Credentials(accessKeyId, secretKey);
const lambda = new AWS.Lambda({ apiVersion: '2015-03-31', credentials });
const s3 = new AWS.S3({ apiVersion: '2006-03-01', credentials });
const sns = new AWS.SNS({ apiVersion: '2010-03-31', credentials });
return {
lambda,
s3,
sns
};
},
/**
* Process items to find newly added.
* @param {Set} knownItems
* @param {Set} actualItems
* @param {Set} newItems
* @param {String} key
* @param {Object} item
*/
processItems(knownItems, actualItems, newItems, key, item) {
if (knownItems && !knownItems.has(item[key])) {
newItems.add(item);
}
actualItems.add(item[key]);
},
/**
* Create and subscribe topic to AWS SNS.
* @param {Context} context
* @param {Object} payload
* @param {string} payload.topicPrefix
* @param {string} payload.eventPrefix
* @param {string} payload.eventType
* @return {Promise}
*/
async registerWebhook(context, payload) {
await this.unregisterWebhook(context);
const { sns, s3 } = this.init(context);
const { bucket } = context.properties;
const url = context.getWebhookUrl();
let topicARN;
let lock;
try {
lock = await context.lock(context.auth.userId.toString(), {
ttl: 1000 * 60,
retryDelay: 500,
maxRetryCount: 60
});
const { TopicConfigurations } = await s3.getBucketNotificationConfiguration({ Bucket: bucket }).promise();
const filteredTopics = TopicConfigurations.filter(topic => topic.TopicArn.includes(payload.topicPrefix));
if (filteredTopics.length > 0) {
topicARN = filteredTopics[0].TopicArn;
const state = await context.loadState();
state.notificationInBucket = true;
await context.saveState(state);
} else {
const response = await sns.createTopic({
Name: `${payload.topicPrefix}${crypto.randomBytes(10).toString('hex')}`
}).promise();
topicARN = response.TopicArn;
await sns.setTopicAttributes({
TopicArn: topicARN,
AttributeName: 'Policy',
AttributeValue: `{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{"Sid":"__console_pub_0",
"Effect":"Allow","Principal":{"AWS":"*"},"Action":"SNS:Publish","Resource":"${topicARN}"},
{"Sid":"__console_sub_0","Effect":"Allow","Principal":{"AWS":"*"},"Action":["SNS:Subscribe","SNS:Receive"],
"Resource":"${topicARN}"}]}`
}).promise();
const topicConfigurations = TopicConfigurations.filter(topic => {
const events = topic.Events.filter(arr => !arr.includes(payload.eventPrefix));
return events.length > 0;
});
topicConfigurations.push({
TopicArn: topicARN,
Events: [
payload.eventType
]
});
await s3.putBucketNotificationConfiguration({
Bucket: bucket,
NotificationConfiguration: {
TopicConfigurations: topicConfigurations
}
}).promise();
}
} finally {
if (lock) {
await lock.unlock();
}
}
return sns.subscribe({ TopicArn: topicARN, Protocol: 'https', Endpoint: url }).promise();
},
/**
* Delete registered notification and topicARN. If there is no topicARN in state, do nothing.
* @param {Context} context
* @return {Promise}
*/
async unregisterWebhook(context) {
const { topicARN, subscriptionArn, notificationInBucket } = await context.loadState();
if (!topicARN || !subscriptionArn) {
return Promise.resolve();
}
const { bucket } = context.properties;
const { s3, sns } = this.init(context);
let promises = [
sns.unsubscribe({ SubscriptionArn: subscriptionArn }).promise()
];
if (!notificationInBucket) {
let lock;
try {
lock = await context.lock(context.auth.userId.toString(), {
ttl: 1000 * 60,
retryDelay: 500,
maxRetryCount: 60
});
// eslint-disable-next-line max-len
const { TopicConfigurations } = await s3.getBucketNotificationConfiguration({ Bucket: bucket }).promise();
const filteredTopics = TopicConfigurations.filter(topic => topic.TopicArn !== topicARN);
await s3.putBucketNotificationConfiguration({
Bucket: bucket,
NotificationConfiguration: {
TopicConfigurations: filteredTopics
}
}).promise();
} finally {
if (lock) {
await lock.unlock();
}
}
promises.push(sns.deleteTopic({ TopicArn: topicARN }).promise());
}
return Promise.all(promises);
},
/**
* Verifies an endpoint owner's intent to receive messages by validating the token sent to the endpoint.
* @param {Context} context
* @param {Object} payload
* @return {Promise}
*/
async confirmSubscription(context, payload) {
const { sns } = this.init(context);
const { TopicArn, Token } = payload;
const { SubscriptionArn } = await sns.confirmSubscription({ TopicArn, Token }).promise();
const state = await context.loadState();
state.topicARN = TopicArn;
state.subscriptionArn = SubscriptionArn;
await context.saveState(state);
return context.response();
},
/**
* There is no SDK method for getting object URL, but we can put it together.
* @param {string} bucket
* @param {string} key
* @param {?string} [region]
* @return {string}
*/
getObjectUrl(bucket, key, region = null) {
if (!region) {
return `https://${bucket}.s3.amazonaws.com/${key}`;
}
return `https://${bucket}.s3.${region}.amazonaws.com/${key}`;
}
};