-
Notifications
You must be signed in to change notification settings - Fork 18
/
handler.ts
450 lines (393 loc) · 11.6 KB
/
handler.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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import 'source-map-support/register'
import * as log from 'log'
import * as logger from 'log-aws-lambda'
import * as crypto from 'crypto'
import {
extractAccessTokenFromEvent,
createErrorResponse,
fetchProfile,
describeThing,
proactivelyDiscoverDevices,
proactivelyUndiscoverDevices,
pushAsyncChangeReportToAlexa,
pushAsyncResponseToAlexa,
pushAsyncStateReportToAlexa,
VshClientBackchannelEvent,
pushDoorbellPressEventToAlexa,
} from './helper'
import handleDiscover from './handlers/discover'
import handleAcceptGrant from './handlers/acceptGrant'
import { handleDirective, handleReportState } from './handlers/updateState'
import {
deleteDevice,
getDeviceCountOfUser,
getUserRecord,
upsertDevice,
} from './db'
import { Device } from './Device'
import { publish } from './mqtt'
import { isAllowedClientVersion, isFeatureSupportedByClient } from './version'
import { deleteDevicePropsFromCache } from './cache'
logger()
function minifyDirectiveEvent(event) {
const result = {
directive: {
header: {
name: event.directive.header.name,
},
},
}
if (event.directive.endpoint) {
result.directive['endpoint'] = {
endpointId: event.directive.endpoint.endpointId,
cookie: {
template: event.directive.endpoint.cookie.template,
thingId: event.directive.endpoint.cookie.thingId,
},
}
}
return result
}
function minifyBackchannelEvent(event: VshClientBackchannelEvent) {
return {
rule: event.rule,
template: event.template, //optional
thingId: event.thingId,
endpointId: event.endpointId, //optional
causeType: event.causeType, //optional
vshVersion: event.vshVersion || '?.?.?',
}
}
/**
* This function gets invoked by Alexa with Directives
* @param event
* @param context
*/
export const skill = async function (event, context) {
try {
const accessToken = extractAccessTokenFromEvent(event)
event.profile = await fetchProfile(accessToken)
} catch (e) {
const response = createErrorResponse(
event,
'EXPIRED_AUTHORIZATION_CREDENTIAL',
'invalid token'
)
log.notice(
'REQUEST: %j \n EXCEPTION: %o \n RESPONSE: %j',
event,
e,
response
)
return response
}
log.info('REQUEST STUB: %j', minifyDirectiveEvent(event))
log.debug('REQ: %j', event)
const directive: string = event.directive.header.name
let response
switch (directive) {
case 'AcceptGrant':
response = await handleAcceptGrant(event)
log.debug('RESPONSE: %j', response)
return response
case 'Discover':
response = await handleDiscover(event)
log.debug('RESPONSE: %j', response)
return response
case 'ReportState':
response = await handleReportState(event)
log.debug('RESPONSE: %j', response)
return response
default:
response = await handleDirective(event)
log.debug('RESPONSE: %j', response)
return response
}
}
export const backchannel = async function (event, context) {
log.info('REQUEST STUB: %j', minifyBackchannelEvent(event))
log.debug('REQ: %j', event)
let result
switch (event.rule) {
case 'discover': //deprecated
result = await killDeviceDueToOutdatedVersion(event)
break
case 'bulkdiscover':
result = await handleBackchannelBulkDiscover(event)
break
case 'bulkundiscover':
result = await handleBackchannelBulkUndiscover(event)
break
case 'changeReport':
result = await handleChangeReport(event)
break
case 'requestConfig':
result = await handleRequestConfig(event)
break
}
log.debug('RESULT: %o', result)
}
async function killDeviceDueToOutdatedVersion({ thingId }) {
return await killDeviceWithMessage({
thingId,
message:
"OUTDATED VERSION! Please update 'virtual smart home' package for Node-RED",
})
}
async function killDeviceWithMessage({ thingId, message }) {
await publish(`vsh/${thingId}/service`, {
operation: 'kill',
reason: message,
})
//for clients < v2.x.x
await publish(`vsh/${thingId}/kill`, {
reason: message,
})
log.notice('killed thing %s with message: %s', thingId, message)
return true
}
async function handleBackchannelBulkDiscover(event) {
const userId = await lookupUserIdForThing(event.thingId)
const devicesToDiscover: Device[] = []
if (!userId) {
return false
}
for (const deviceStub of event.devices) {
const device = {
deviceId: deviceStub['deviceId'],
userId,
thingId: event.thingId,
friendlyName: deviceStub['friendlyName'],
template: deviceStub['template'],
retrievable: deviceStub['retrievable'] ?? false,
}
devicesToDiscover.push(device)
await upsertDevice(device)
//delete cached device props:
await deleteDevicePropsFromCache(device.thingId, device.deviceId)
}
try {
return await proactivelyDiscoverDevices(userId, devicesToDiscover)
} catch (e) {
log.error('proactivelyDiscoverDevices FAILED! %s', e.message)
await publish(`vsh/${devicesToDiscover[0].thingId}/service`, {
operation: 'setDeviceStatus',
status: 'proactive discovery failed',
color: 'yellow',
devices: devicesToDiscover.map((device) => device.deviceId),
})
return false
}
}
export async function handleBackchannelBulkUndiscover({ thingId, devices }) {
const userId = await lookupUserIdForThing(thingId)
const devicesToUndiscover: Device[] = []
const deviceIDsToUndiscover: string[] = []
if (!userId) {
return false
}
for (const deviceStub of devices) {
const device = {
deviceId: deviceStub['deviceId'],
userId,
thingId: thingId,
friendlyName: deviceStub['friendlyName'],
template: deviceStub['template'],
retrievable: deviceStub['retrievable'] ?? false,
}
devicesToUndiscover.push(device)
deviceIDsToUndiscover.push(device.deviceId)
try {
await deleteDevice({
userId,
deviceId: device.deviceId,
thingId: device.thingId,
})
} catch (err) {
log.error(
'deleteDevice for userId %s, thingId %s, deviceId %s FAILED! %j',
userId,
device.thingId,
device.deviceId,
err
)
}
}
return await proactivelyUndiscoverDevices(userId, deviceIDsToUndiscover)
}
async function handleChangeReport(event: VshClientBackchannelEvent) {
const { template, thingId, causeType, correlationToken, userIdToken } = event
let userId: string
if (userIdToken) {
const extractedUserId = userIdToken.match(/^(.*)#.*/)[1]
if (userIdToken === makeUserIdToken({ thingId, userId: extractedUserId })) {
userId = extractedUserId
}
} else {
//fallback for < v2.8.0
userId = await lookupUserIdForThing(thingId)
}
if (!userId) {
return false
}
if (template === 'DOORBELL_EVENT_SOURCE') {
try {
return await pushDoorbellPressEventToAlexa(userId, event)
} catch (e) {
log.error('pushDoorbellPressEventToAlexa FAILED! %j', e.response.data)
return false
}
}
if (causeType === 'VOICE_INTERACTION' && correlationToken) {
try {
return await pushAsyncResponseToAlexa(userId, event)
} catch (e) {
log.error('pushAsyncResponseToAlexa FAILED! %s', e.message)
return false
}
}
if (causeType === 'STATE_REPORT' && correlationToken) {
try {
return await pushAsyncStateReportToAlexa(userId, event)
} catch (e) {
log.error('pushAsyncStateReportToAlexa FAILED! %s', e.message)
return false
}
}
try {
return await pushAsyncChangeReportToAlexa(userId, event)
} catch (e) {
log.error('pushAsyncChangeReportToAlexa FAILED! %s', e.message)
return false
}
}
async function handleRequestConfig({
thingId,
vshVersion,
}: {
thingId: string
vshVersion: string
}) {
if (!isAllowedClientVersion(vshVersion)) {
await killDeviceDueToOutdatedVersion({ thingId })
return false
}
const userId = await lookupUserIdForThing(thingId)
if (!userId) {
await killDeviceWithMessage({
thingId,
message: 'No User ID found for thing',
})
return false
}
try {
const { isBlocked, allowedDeviceCount, plan } = await getUserRecord(userId)
if (isBlocked) {
await killDeviceWithMessage({
thingId,
message: 'User account is blocked',
})
return false
}
// calculate count of devices connected via _other_ thingIDs
const deviceCountOfOtherThings = await getDeviceCountOfUser({
userId,
excludeThingId: thingId,
})
const allowedDeviceCountForThisThing =
allowedDeviceCount - deviceCountOfOtherThings < 0
? 0
: allowedDeviceCount - deviceCountOfOtherThings
const payload = {
operation: 'overrideConfig',
userIdToken: makeUserIdToken({ thingId, userId }),
allowedDeviceCount: allowedDeviceCountForThisThing,
plan,
}
if (isFeatureSupportedByClient('msgRateLimiter', vshVersion)) {
//>= v2.12.0
payload['msgRateLimiter'] = {
profiles: {
DEFAULT: {
maxConcurrent: 1,
minTime: 1000, //1 sec
highWater: 0,
strategy: 'BLOCK',
penalty: 30 * 1000, //30 sec
reservoir: 60,
reservoirIncreaseInterval: 60 * 1000, //60 sec
reservoirIncreaseAmount: 1,
reservoirIncreaseMaximum: 60,
},
PHYSICAL_INTERACTION_DEFAULT: {
maxConcurrent: 1,
minTime: 2500, //2.5 sec
highWater: 1,
strategy: 'LEAK',
reservoir: 30,
reservoirIncreaseInterval: 15 * 60 * 1000, //15 min
reservoirIncreaseAmount: 1,
reservoirIncreaseMaximum: 15,
},
VOICE_INTERACTION_DEFAULT: {
maxConcurrent: 1,
minTime: 0,
highWater: 0,
strategy: 'OVERFLOW',
reservoir: 20,
reservoirIncreaseInterval: 5 * 60 * 1000, //5 min
reservoirIncreaseAmount: 2,
reservoirIncreaseMaximum: 10,
},
STATE_REPORT_DEFAULT: {
maxConcurrent: 1,
minTime: 0,
highWater: 0,
strategy: 'BLOCK',
penalty: 60 * 1000, //60 sec
reservoir: 60,
reservoirIncreaseInterval: 5 * 60 * 1000, //5 min
reservoirIncreaseAmount: 15,
reservoirIncreaseMaximum: 60,
},
},
profileMapping: {
//PHYSICAL_INTERACTION_DIMMER_SWITCH: 'DIMMER_SWITCH', //example of a template/device specific override
PHYSICAL_INTERACTION_DEFAULT: 'PHYSICAL_INTERACTION_DEFAULT',
VOICE_INTERACTION_DEFAULT: 'VOICE_INTERACTION_DEFAULT',
STATE_REPORT_DEFAULT: 'STATE_REPORT_DEFAULT',
},
}
} else {
//<= v2.11.0:
payload['rateLimiter'] = [
{ period: 1 * 60 * 1000, limit: 12, penalty: 0, repeat: 10 }, //for 10 min: Limit to 12 req / min
{ period: 10 * 60 * 1000, limit: 5, penalty: 1 }, //afterward: Limit to 5 req / 10 min
]
}
await publish(`vsh/${thingId}/service`, payload)
return true
} catch (e) {
await killDeviceWithMessage({
thingId,
message: 'User not found! VSH Alexa skill enabled?',
})
return false
}
}
function makeUserIdToken({
thingId,
userId,
}: {
thingId: string
userId: string
}) {
return `${userId}#${crypto
.createHash('sha1')
.update(`${userId}-${thingId}-${process.env.HASH_SECRET}`)
.digest('hex')}`
}
async function lookupUserIdForThing(thingId: string) {
const thingDetails = await describeThing(thingId)
return thingDetails.attributes.userId || false
}