-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
408 lines (379 loc) · 10.8 KB
/
Copy pathindex.js
File metadata and controls
408 lines (379 loc) · 10.8 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// SLACK_TOKEN is used to authenticate requests are from Slack.
// Keep this value secret.
import _get from 'lodash/get'
import _isEmpty from 'lodash/isEmpty'
import _groupBy from 'lodash/groupBy'
import _flatten from 'lodash/flatten'
import _map from 'lodash/map'
import { setCache, getCache } from './cache'
const BOT_NAME = 'GoodDollar Support'
const slackValidChannels = ['development', 'goodlabs']
const passwords = {
dev: DEV_DB_PASS,
prod: PROD_DB_PASS,
next: NEXT_DB_PASS,
qa: QA_DB_PASS,
}
const hosts = {
dev: 'good-server',
prod: 'goodserver-prod',
next: 'goodserver-next',
qa: 'goodserver-qa',
}
addEventListener('fetch', event => {
const url = event.request.url
const toMatch = `key=${AMPLITUDE_SECRET}`
console.log('fetch event', { url, event })
return event.respondWith(slackWebhookHandler(event.request))
})
const sentryEvent = async (exOrMsg, extra) => {
let data
if (typeof exOrMsg === 'string') {
data = {
message: exOrMsg,
level: 'info',
extra,
}
} else {
data = {
exception: {
type: exOrMsg.message,
value: exOrMsg.message,
stacktrace: exOrMsg.stacktrace,
},
extra,
}
}
console.log('sentry req', data, { SENTRY_PROJECT, SENTRY_KEY })
// const sentryUrl = 'https://webhook.site/feaf92f9-cf45-4358-a904-ec1acd40afbb'
const sentryUrl = `https://sentry.io/api/${SENTRY_PROJECT}/store/`
// const sentryUrl = 'https://postman-echo.com/post'
const res = await fetch(sentryUrl, {
headers: {
'Content-Type': 'application/json',
'X-Sentry-Auth': `Sentry sentry_version=7,sentry_key=${SENTRY_KEY},sentry_client=raven-bash/1.0`,
'User-Agent': 'curl/7.54.0',
Accept: '*/*',
},
body: JSON.stringify(data),
method: 'POST',
}).then(r => r.text())
console.log('sentry res:', res)
}
const goodserverPost = async (cmd, data, env) => {
let server = `https://${hosts[env]}.herokuapp.com`
const response = await fetch(server + cmd, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
return response.json()
}
const githubPost = async (
releaseType,
sourceBranch,
targetBranch,
repo,
workflowId,
) => {
console.log(
'slack release github action:',
JSON.stringify({
releaseType,
sourceBranch,
targetBranch,
repo,
workflowId,
}),
)
const authToken = btoa(GITHUB_USERNAME + ':' + GITHUB_TOKEN)
const body = {
ref: sourceBranch,
inputs: {
release: releaseType,
targetbranch: targetBranch,
},
}
const res = await fetch(
`https://api.github.com/repos/${GITHUB_ORGANIZATION}/${repo}/actions/workflows/${workflowId}/dispatches`,
{
method: 'POST',
headers: {
accept: 'application/vnd.github.v3+json',
Authorization: `Basic ${authToken}`,
'User-Agent': 'simple-worker-slack-bot',
},
body: JSON.stringify(body),
},
)
return res
}
const amplitudePost = async events => {
const data = {
api_key: process.env.AMPLITUDE_KEY,
events,
}
const response = await fetch('https://api.amplitude.com/2/httpapi', {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
return response.json()
}
const handleCommand = async (cmd, msg) => {
let payload
let password
console.log({ cmd, msg })
switch (cmd) {
case '/queue':
let [queueEnv, op, allow] = msg.split(' ')
password = passwords[queueEnv]
let serverHost = hosts[queueEnv]
const params = {
method: op === 'approve' ? 'POST' : 'GET',
headers: {
'Content-Type': 'application/json',
},
}
if (op === 'approve')
params.body = JSON.stringify({
password,
allow: Number(allow),
})
const res = await fetch(
`https://${serverHost}.herokuapp.com/admin/queue`,
params,
).then(response => response.json())
console.log('/queue command result:', { res, msg, serverHost })
return res
break
case '/release':
let [ENV, DEPLOY_FROM, DEPLOY_TO] = msg.split(' ')
console.log(
'slack release:',
JSON.stringify({ ENV, DEPLOY_FROM, DEPLOY_TO }),
)
let repo = 'GoodDapp'
const dappPromise = githubPost(
ENV,
DEPLOY_FROM,
DEPLOY_TO,
repo,
GITHUB_DAPP_WORKFLOW_ID,
)
repo = 'GoodServer'
const serverPromise = githubPost(
ENV,
DEPLOY_FROM,
DEPLOY_TO,
repo,
GITHUB_SERVER_WORKFLOW_ID,
)
return Promise.all([serverPromise, dappPromise])
break
case '/getuser':
let [emailOrMobile, env = 'dev'] = msg.split(/\s+/)
password = passwords[env]
console.log('getuser', { msg, emailOrMobile, env })
payload = {
password,
email: emailOrMobile,
}
if (emailOrMobile.match(/^\+?[0-9]+$/)) {
payload.mobile =
emailOrMobile.indexOf('+') == 0 ? emailOrMobile : `+${emailOrMobile}`
delete payload.email
}
if (emailOrMobile.match(/^0x[0-9a-f]+$/)) {
payload.identifierHash = emailOrMobile
delete payload.email
}
console.log('getuser', { payload })
return await goodserverPost('/admin/user/get', payload, env)
break
case '/deleteuser':
let [identifier, delenv = 'etoro'] = msg.split(/\s+/)
password = passwords[delenv]
payload = {
password,
email: identifier,
}
if (identifier.match(/^\+?[0-9]+$/)) {
payload.mobile =
identifier.indexOf('+') == 0 ? identifier : `+${identifier}`
delete payload.email
}
if (identifier.match(/^0x[0-9a-f]+$/)) {
payload.identifierHash = identifier
delete payload.email
}
console.log({ payload })
return await goodserverPost('/admin/user/delete', payload, delenv)
break
default:
throw new Error(`unknown command ${cmd}`)
}
}
let jsonHeaders = new Headers([['Content-Type', 'application/json']])
/**
* simpleResponse generates a simple JSON response
* with the given status code and message.
*
* @param {Number} statusCode
* @param {String} message
*/
function simpleResponse(statusCode, message) {
let resp = {
response_type: 'ephemeral',
text: message,
}
return new Response(JSON.stringify(resp), {
headers: jsonHeaders,
status: statusCode,
})
}
/**
* slackResponse builds a message for Slack with the given text
* and optional attachment text
*
* @param {string} text - the message text to return
*/
function slackResponse(text) {
let content = {
text: text,
attachments: [],
}
return new Response(JSON.stringify(content), {
headers: jsonHeaders,
status: 200,
})
}
/**
* slackWebhookHandler handles an incoming Slack
* webhook and generates a response.
* @param {Request} request
*/
async function slackWebhookHandler(request) {
// As per: https://api.slack.com/slash-commands
// - Slash commands are outgoing webhooks (POST requests)
// - Slack authenticates via a verification token.
// - The webhook payload is provided as POST form data
if (request.method !== 'POST') {
return simpleResponse(
200,
`Hi, I'm ${BOT_NAME}, a Slack bot for GoodDollar`,
)
}
try {
let formData = await request.formData()
console.log(
'slackWebhookHandler formData:',
JSON.stringify([...formData.entries()]),
)
if (formData.get('token') !== SLACK_TOKEN) {
return simpleResponse(403, 'invalid Slack verification token')
}
if (slackValidChannels.includes(formData.get('channel_name')) === false) {
return simpleResponse(403, 'unauthorized channel')
}
const command = formData.get('command')
const msg = formData.get('text') || ''
// const args = await command.parse(msg)
// const result = args.result
const result = await handleCommand(command, msg)
console.log('handleCommand:', JSON.stringify({ result }))
const asText = `\`\`\`${JSON.stringify(result, null, ' ')}\`\`\``
return slackResponse(asText)
} catch (e) {
return simpleResponse(200, `Sorry, couldn't perform your request: ${e}`)
}
}
const handleEmailOpenEvent = events => {
const eventsData = events.map(event => {
const user_id =
_get(event, 'stat.lead.fields.core.email.value') ||
_get(event, 'stat.email')
const mauticId = _get(event, 'stat.lead.id')
const emailKey = _get(event, 'stat.email.name', '')
.toUpperCase()
.replace(/\s+/g, '_')
const emailId = _get(event, 'stat.email.id', 0)
const event_type = 'MAUTIC_EMAIL_OPEN'
const eventData = {
user_id,
event_type,
event_properties: {
emailId,
emailKey,
},
user_properties: {
mauticId,
},
}
console.log({ eventData })
return eventData
})
return amplitudePost(eventsData)
}
/**
* alertsWebhookHandler handles an incoming alibaba cloud monitoring alerts
* and post message to slack
* @param {Request} request
*/
async function alertsWebhookHandler(request) {
if (request.method !== 'POST') {
return simpleResponse(400, `Hi, I'm ${BOT_NAME}, expecting post request`)
}
let res
try {
let text = ''
await request
.clone()
.formData()
.then(formData => {
const alibabaAlertCode = Number(formData.get('curValue'))
const alibabaAlertState = String(formData.get('alertState'))
//filter 6xx error codes
if (alibabaAlertCode >= 600) return
//filter return to normal ok
if (alibabaAlertState === 'OK') return
for (let e of formData.entries()) text += e.join(':') + '\n'
})
.catch(async e => (text = await request.clone().text()))
// await sentryEvent('alertsWebhookHandler incoming', {
// text: request.text(),
// })
if (text !== '') {
const response = await postToSlack(text).catch(e => e)
// await sentryEvent('alertsWebhookHandler slack response', {
// response,
// })
}
return simpleResponse(200, `ok`)
} catch (e) {
await sentryEvent('alertsWebhookHandler failed', {
e,
})
return simpleResponse(400, `Sorry, couldn't perform your request: ${e}`)
}
}
const postToSlack = async text => {
const data = {
text,
}
console.log({ data })
const response = await fetch(SLACK_MONITORING_WEBHOOK, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
return response.text()
}