-
Notifications
You must be signed in to change notification settings - Fork 18
/
admin.ts
377 lines (336 loc) · 9.12 KB
/
admin.ts
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
import * as serverless from 'serverless-http'
import * as express from 'express'
import * as logger from 'log-aws-lambda'
import AWS = require('aws-sdk')
import { getDevicesOfUser, getThingsOfUser, getUserRecord } from './db'
import { proactivelyRediscoverAllDevices } from './helper'
import { publish } from './mqtt'
import { switchToPlan } from './subscription'
import { PlanName } from './Plan'
logger()
AWS.config.update({ region: process.env.VSH_IOT_REGION })
const iot = new AWS.Iot()
const iotdata = new AWS.IotData({
endpoint: process.env.VSH_IOT_ENDPOINT,
})
const cloudwatchlogs = new AWS.CloudWatchLogs()
async function describeThing(
thingName
): Promise<AWS.Iot.DescribeThingResponse> {
const params = {
thingName,
}
return new Promise((resolve, reject) => {
iot.describeThing(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
async function getThingShadow(
thingName
): Promise<AWS.IotData.GetThingShadowResponse> {
const params = {
thingName,
}
return new Promise((resolve, reject) => {
iotdata.getThingShadow(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(JSON.parse(data.payload as string))
}
})
})
}
async function listViolationEvents(
thingName
): Promise<AWS.Iot.ViolationEvent[]> {
const params = {
endTime: new Date() /* required */,
startTime: new Date(
new Date().getTime() - 1000 * 60 * 60 * 24 * 7
) /* required */, // 1000*60*60*24*7 == 7 days
maxResults: 50,
thingName,
}
return new Promise((resolve, reject) => {
iot.listViolationEvents(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data.violationEvents)
}
})
})
}
async function startQuery(
queryString: string,
minutesBack: number,
logGroupName: string
): Promise<string> {
const now = Math.ceil(new Date().valueOf() / 1000)
const startTime = now - minutesBack * 60
const params = {
endTime: now,
queryString,
startTime,
limit: 500,
logGroupName,
}
return new Promise((resolve, reject) => {
cloudwatchlogs.startQuery(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data.queryId)
}
})
})
}
async function getQueryResult(
queryId: string
): Promise<AWS.CloudWatchLogs.GetQueryResultsResponse> {
const params = {
queryId,
}
return new Promise((resolve, reject) => {
cloudwatchlogs.getQueryResults(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
function makeTimestampsReadable(obj) {
let newObj = {}
for (var ogKey in obj) {
if (ogKey === 'timestamp') {
newObj[ogKey] = new Date(obj[ogKey] * 1000).toISOString()
} else if (typeof obj[ogKey] === 'object') {
newObj[ogKey] = makeTimestampsReadable(obj[ogKey])
} else {
newObj[ogKey] = obj[ogKey]
}
}
return newObj
}
async function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms)
})
}
// --------
const app = express()
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.use(express.json()) // for parsing application/json
app.use((req, res, next) => {
if (req.headers['authorization'] !== process.env.VSH_ADMIN_API_KEY) {
return res.sendStatus(401)
}
next()
})
app.get('/thing/:thingName/info', async function (req, res) {
let thingDetails: AWS.Iot.DescribeThingResponse
let thingShadow: AWS.IotData.Types.GetThingShadowResponse
let account
let devicesOfUser
let devices
let violations
try {
thingDetails = await describeThing(req.params.thingName)
thingShadow = await getThingShadow(req.params.thingName)
account = await getUserRecord(thingDetails.attributes['userId'])
devicesOfUser = await getDevicesOfUser(thingDetails.attributes['userId'])
devices = devicesOfUser.reduce((acc, device) => {
const key =
device.thingId == req.params.thingName ? '_THIS_' : device.thingId
if (!acc[key]) {
acc[key] = []
}
acc[key].push({
...device,
SK: undefined,
PK: undefined,
thingId: undefined,
})
return acc
}, {})
violations = (await listViolationEvents(req.params.thingName)).map(
(violation) => {
return {
alert: violation.behavior.name,
time: violation.violationEventTime.toISOString(),
type: violation.violationEventType,
value: violation.metricValue.count,
}
}
)
} catch (e) {
return res.sendStatus(404)
}
res.send({
thingName: req.params.thingName,
createdAt: new Date(
parseInt(thingDetails.attributes['createdAt']) * 1000
).toISOString(),
shadow: makeTimestampsReadable(thingShadow),
account: {
...account,
userId: thingDetails.attributes['userId'],
SK: undefined,
PK: undefined,
accessToken: undefined,
refreshToken: undefined,
deleteAtUnixTime: new Date(account.deleteAtUnixTime * 1000).toISOString(),
},
deviceCount: devicesOfUser.length,
devices,
violations_7d: violations,
})
})
app.get('/thing/:thingName/stats', async function (req, res) {
const query = `stats count() as count by rule, endpointId, template, causeType
| filter thingId = '${req.params.thingName}'
| sort count desc
| limit 250`
try {
const queryId = await startQuery(
query,
60 * 24, //1 day
'/aws/lambda/virtual-smart-home-dev-backchannel'
)
type QueryStatusType =
| 'Scheduled'
| 'Running'
| 'Complete'
| 'Failed'
| 'Cancelled'
| 'Timeout'
| 'Unknown'
let queryStatus: QueryStatusType
let queryResult: AWS.CloudWatchLogs.GetQueryResultsResponse
do {
await wait(1000)
queryResult = await getQueryResult(queryId)
queryStatus = (queryResult.status as QueryStatusType) ?? 'Unknown'
} while (queryStatus == 'Running' || queryStatus == 'Scheduled')
if (queryStatus !== 'Complete') {
throw new Error('Query did not complete successfully')
}
const rows = queryResult.results.map((row) =>
row.reduce((acc, item) => {
acc[item.field] =
item.field == 'count' ? parseInt(item.value) : item.value
return acc
}, {})
)
res.send({
results: rows,
matches: queryResult.statistics.recordsMatched,
})
} catch (err) {
console.log(err)
res.status(500).send(err.message)
}
})
app.post('/thing/:thingName/rediscover', async function (req, res) {
try {
const thingDetails = await describeThing(req.params.thingName)
const userId = thingDetails.attributes['userId']
await proactivelyRediscoverAllDevices(userId)
res.send({ result: 'ok' })
} catch (err) {
console.log(err)
res.status(500).send(err.message)
}
})
app.post('/thing/:thingName/restart', async function (req, res) {
try {
await publish(`vsh/${req.params.thingName}/service`, {
operation: 'restart',
})
res.send({ result: 'ok' })
} catch (err) {
console.log(err)
res.status(500).send(err.message)
}
})
app.post('/thing/:thingName/kill', async function (req, res) {
try {
await publish(`vsh/${req.params.thingName}/service`, {
operation: 'kill',
reason: req.query.reason ?? 'killed by admin',
})
res.send({ result: 'ok' })
} catch (err) {
console.log(err)
res.status(500).send(err.message)
}
})
app.get('/user/:userId/info', async function (req, res) {
try {
const userRecord = await getUserRecord(req.params.userId)
const account = {
...userRecord,
userId: req.params.userId,
SK: undefined,
PK: undefined,
accessToken: undefined,
refreshToken: undefined,
deleteAtUnixTime: new Date(
userRecord.deleteAtUnixTime * 1000
).toISOString(),
}
const devices = (await getDevicesOfUser(req.params.userId)).reduce(
(acc, device) => {
const key = device.thingId
if (!acc[key]) {
acc[key] = []
}
acc[key].push({
...device,
SK: undefined,
PK: undefined,
thingId: undefined,
})
return acc
},
{}
)
res.send({
account,
devices,
})
} catch (err) {
console.log(err)
res.status(500).send(err.message)
}
})
app.post('/user/:userId/restartThings', async function (req, res) {
try {
const thingIds = await getThingsOfUser(req.params.userId)
for (const thingId of thingIds) {
await publish(`vsh/${thingId}/service`, {
operation: 'restart',
})
}
res.send({ result: 'ok', thingIds })
} catch (err) {
console.log(err)
res.status(500).send(err.message)
}
})
app.post('/user/:userId/switchToPlan/:planName', async function (req, res) {
await switchToPlan(req.params.userId, req.params.planName as PlanName)
res.send({ result: 'ok' })
})
app.post('/thing/:thingName/blockUser', async function (req, res) {
res.status(500).send('not yet implemented')
})
export const admin = serverless(app)