-
Notifications
You must be signed in to change notification settings - Fork 18
/
backendApi.ts
550 lines (483 loc) · 15.2 KB
/
backendApi.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import * as serverless from 'serverless-http'
import * as express from 'express'
import * as cors from 'cors'
import { v4 as uuidv4 } from 'uuid'
import { encode, decode } from 'js-base64'
import * as log from 'log'
import * as logger from 'log-aws-lambda'
import * as jwt from 'jsonwebtoken'
import Stripe from 'stripe'
import { fetchProfile, isProd, proactivelyUndiscoverDevices } from './helper'
import AWS = require('aws-sdk')
import caCert from './caCert'
import { deleteDevice, getDevicesOfUser, getUserRecord } from './db'
import { publish } from './mqtt'
import {
isAllowedClientVersion,
isFeatureSupportedByClient,
isLatestClientVersion,
} from './version'
import { Plan, PlanName } from './Plan'
import {
handleCheckoutSessionCompleted,
handleCustomerSubscriptionDeleted,
handleInvoicePaymentFailed,
handleInvoicePaymentSucceeded,
} from './subscription'
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: '2023-08-16',
})
interface AuthenticatedRequest extends express.Request {
userId: string
jwt?: { [key: string]: any }
}
logger()
AWS.config.update({ region: process.env.VSH_IOT_REGION })
const iot = new AWS.Iot()
async function createKeysAndCertificate(): Promise<any> {
const params = {
setAsActive: true,
}
return new Promise((resolve, reject) => {
iot.createKeysAndCertificate(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve({
certificateArn: data.certificateArn,
certificateId: data.certificateId,
certificatePem: data.certificatePem,
publicKey: data.keyPair.PublicKey,
privateKey: data.keyPair.PrivateKey,
})
}
})
})
}
async function createThing(userId: string, email: string): Promise<any> {
const params = {
thingName: 'vsht-' + uuidv4(),
attributePayload: {
attributes: {
userId: userId,
createdAt: '' + Math.floor(new Date().getTime() / 1000), //needs to be a string
},
},
billingGroupName: 'virtual-smart-home-billing-group',
thingTypeName: 'virtual-smart-home-type',
}
return new Promise((resolve, reject) => {
iot.createThing(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve({
thingName: data.thingName,
thingArn: data.thingArn,
thingId: data.thingId,
})
}
})
})
}
async function attachPremadePolicyToCertificate(
certificateArn: string
): Promise<any> {
const params = {
policyName: process.env.VSH_IOT_POLICY,
principal: certificateArn,
}
return new Promise((resolve, reject) => {
iot.attachPrincipalPolicy(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(true)
}
})
})
}
async function attachCertificateToThing(
certificateArn: string,
thingName: string
): Promise<any> {
const params = {
principal: certificateArn,
thingName: thingName,
}
return new Promise((resolve, reject) => {
iot.attachThingPrincipal(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(true)
}
})
})
}
async function addThingToThingGroup(
thingName: string,
thingGroupName: string
): Promise<any> {
const params = {
thingGroupName,
thingName,
}
return new Promise((resolve, reject) => {
iot.addThingToThingGroup(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(true)
}
})
})
}
const app = express()
app.post('/stripe_webhook', async function (req, res) {
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET
const sig = req.headers['stripe-signature']
let event: any
try {
event = stripe.webhooks.constructEvent(
(req as any).rawBody, //rawBody is important!
sig,
endpointSecret
)
} catch (err) {
res.status(400).send(`Webhook Error: ${err.message}`)
return
}
// Handle the event
try {
log.info('stripe_webhook received! %j', event)
switch (event.type) {
case 'checkout.session.completed': //https://stripe.com/docs/api/checkout/sessions/object
await handleCheckoutSessionCompleted(
event.data.object as Stripe.Checkout.Session
)
break
case 'customer.subscription.deleted': //https://stripe.com/docs/api/subscriptions/object
await handleCustomerSubscriptionDeleted(
event.data.object as Stripe.Subscription
)
break
case 'invoice.payment_succeeded': //https://stripe.com/docs/api/invoices/object
await handleInvoicePaymentSucceeded(event.data.object as Stripe.Invoice)
break
case 'invoice.payment_failed': //https://stripe.com/docs/api/invoices/object
await handleInvoicePaymentFailed(event.data.object as Stripe.Invoice)
break
// ... handle other event types
default:
log.warn(`Unhandled event type ${event.type}: %j`, event)
}
// Return a 200 response to acknowledge receipt of the event
res.send()
} catch (err) {
log.error('processing stripe_webhook failed! %j', err)
res.status(500).send(`Error: ${err.message}`)
}
})
//applying middlewares for all endpoints below these lines!
app.use(cors())
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.use(express.json()) // for parsing application/json
app.post('/provision', async function (req, res) {
if (!req.body.accessToken) {
return res.status(400).send({ error: 'invalid request structure' })
}
// vsh clients send version info since v1.15.1
const vshVersion = req.body.vshVersion || '0.0.0'
log.info('PROVISIONING REQUEST for client with version %s', vshVersion)
if (!isFeatureSupportedByClient('provision', vshVersion)) {
log.error(
'PROVISIONING FAILED: %s does not satisfy version constraints!',
vshVersion
)
res.status(400).send({
error: 'Outdated VSH version! Please update to latest version!',
})
}
try {
const profile = await fetchProfile(req.body.accessToken)
const { isBlocked } = await getUserRecord(profile.user_id)
if (isBlocked) {
throw new Error(
`found attribute 'isBlocked' for userId ${profile.user_id} / ${profile.email}`
)
}
const { thingName, thingArn, thingId } = await createThing(
profile.user_id,
profile.email
)
const {
certificateArn,
certificateId,
certificatePem,
publicKey,
privateKey,
} = await createKeysAndCertificate()
await attachPremadePolicyToCertificate(certificateArn)
await attachCertificateToThing(certificateArn, thingName)
await addThingToThingGroup(thingName, 'virtual-smart-home-things')
const vshJwt = jwt.sign(
{
thingId: thingName,
email: profile.email,
sub: profile.user_id,
},
process.env.HASH_SECRET
)
const response = {
server: process.env.VSH_IOT_ENDPOINT, //'a1pv0eq8s016ut-ats.iot.eu-west-1.amazonaws.com'
port: 8883,
cert: encode(certificatePem),
privateKey: encode(privateKey),
caCert: encode(caCert),
thingId: thingName, // we use the thingName as ID from here on...
email: profile.email,
vshJwt,
}
log.debug('PROVISIONING RESPONSE: %j', response)
res.send(response)
} catch (e) {
log.error('PROVISIONING FAILED: %s', e.message)
res.status(400).send({
error:
'provisioning failed! Try (re)-enabling the VSH skill in the Alexa app!',
})
}
})
app.get('/check_version', async function (req, res) {
log.debug('/check_version with query: %j', req.query)
const clientVersion: string = (req.query.version as string) || '0.0.0'
const nodeRedVersion: string = (req.query.nr_version as string) || '0.0.0'
const thingId: string = (req.query.thingId as string) || null
const isAllowedVersion = isAllowedClientVersion(clientVersion)
const isLatestVersion = isLatestClientVersion(clientVersion)
const updateHint = isLatestVersion
? ''
: 'Please update to the latest version of VSH!'
const freePlan = new Plan(PlanName.FREE)
const response = {
isAllowedVersion,
isLatestVersion,
updateHint,
allowedDeviceCount: freePlan.allowedDeviceCount, //deprecated as of v2.8.0. Leave here for backwards compatibility
}
log.debug('RESPONSE: %j', response)
res.send(response)
})
const needsAuth = async function (
req: AuthenticatedRequest,
res: express.Response,
next: express.NextFunction
) {
if (!req.header('Authorization')) {
return res
.status(400)
.send({ error: 'missing accessToken in Authorization header' })
}
const accessToken: string = req.header('Authorization')
try {
if (accessToken.startsWith('Bearer ')) {
//new way of authentication via vsh JWT!
const decodedJwt = jwt.verify(
accessToken.substring(7),
process.env.HASH_SECRET
) as jwt.JwtPayload
req.userId = decodedJwt.sub
next()
} else {
//deprecated way of authentication via Amazon access token!
const { user_id } = await fetchProfile(accessToken)
req.userId = user_id
next()
}
} catch (e) {
log.error('AUTHENTICATION FAILED: %s', e.message)
res.status(400).send({ error: 'authentication failed' })
}
}
const needsTokenForAudience = function (audience: string) {
return function (
req: AuthenticatedRequest,
res: express.Response,
next: express.NextFunction
) {
if (!req.query.token) {
return res.status(400).send({ error: 'missing query parameter: token' })
}
try {
const decodedJwt = jwt.verify(
req.query.token as string,
process.env.HASH_SECRET,
{
audience,
}
) as jwt.JwtPayload
req.userId = decodedJwt.sub
req.jwt = decodedJwt
next()
} catch (e) {
log.error('AUTHENTICATION FAILED: %s', e.message)
res.status(400).send({ error: 'authentication failed' })
}
}
}
app.get('/plan', needsAuth, async function (req: AuthenticatedRequest, res) {
try {
const { allowedDeviceCount, plan } = await getUserRecord(req.userId, false)
res.send({
allowedDeviceCount,
plan,
subcriptionToken: jwt.sign(
{
aud: 'subscription',
sub: req.userId,
},
process.env.HASH_SECRET,
{ expiresIn: '30m' }
),
availablePlans: [
{
name: 'VSH Pro',
features: [
'control up to 200 virtual devices',
'device status retrievable by Alexa',
'cancellable at any time',
],
priceTags: [
{
name: 'vsh-pro-yearly',
tag: '12 EUR per year',
checkoutToken: jwt.sign(
{
aud: 'checkout',
sub: req.userId,
priceId: isProd()
? 'price_1Li1C4C3eSYquofeqstbOGi9'
: 'price_1LgSpdC3eSYquofeNk3MClG1',
},
process.env.HASH_SECRET,
{ expiresIn: '30m' }
),
},
{
name: 'vsh-pro-monthly',
tag: '1.49 EUR per month',
checkoutToken: jwt.sign(
{
aud: 'checkout',
sub: req.userId,
priceId: isProd()
? 'price_1Li1C4C3eSYquofekuqBmkqk'
: 'price_1LgSpdC3eSYquofegmyiZdQv',
},
process.env.HASH_SECRET,
{ expiresIn: '30m' }
),
},
],
},
],
})
} catch (e) {
log.error('FETCHING PLAN INFO FAILED: %s', e.message)
res.status(400).send({ error: 'fetching plan info failed' })
}
})
app.get(
'/checkout',
needsTokenForAudience('checkout'),
async function (req: AuthenticatedRequest, res) {
const { stripeCustomerId, email } = await getUserRecord(req.userId)
//init Stripe checkout session and redirect to their checkout experience
const stripeSession = await stripe.checkout.sessions.create({
mode: 'subscription',
client_reference_id: req.userId,
...(stripeCustomerId && { customer: stripeCustomerId }), //include customer property if stripeCustomerId is truthy
...(!stripeCustomerId && { customer_email: email }), //include customer_email property if stripeCustomerId is falsy
line_items: [
{
price: req.jwt.priceId,
quantity: 1,
},
],
allow_promotion_codes: true,
// {CHECKOUT_SESSION_ID} is a string literal; do not change it!
// the actual Session ID is returned in the query parameter when your customer
// is redirected to the success page.
success_url: `https://${req.hostname}/dev/stripe_redirect?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `https://${req.hostname}/dev/stripe_redirect?cancelled=true`,
})
// Redirect to the URL returned on the Checkout Session.
res.redirect(303, stripeSession.url)
}
)
app.get(
'/subscription',
needsTokenForAudience('subscription'),
async function (req: AuthenticatedRequest, res) {
const { stripeCustomerId } = await getUserRecord(req.userId)
//init Stripe customer portal session and redirect to there
const portalSession = await stripe.billingPortal.sessions.create({
customer: stripeCustomerId,
return_url: `https://${req.hostname}/dev/stripe_redirect`,
})
// Redirect to the URL returned on the portal session.
res.redirect(303, portalSession.url)
}
)
app.get('/stripe_redirect', async function (req: AuthenticatedRequest, res) {
//users get redirected to this endpoint after completing or cancelling the Stripe checkout flow!
res.send(
'<html><h1>Thank you!</h1><h2>You can now close this window.</h2></html>'
)
})
app.get('/devices', needsAuth, async function (req: AuthenticatedRequest, res) {
try {
const devices = await getDevicesOfUser(req.userId)
res.send(devices)
} catch (e) {
log.error('FETCHING DEVICE LIST FAILED: %s', e.message)
res.status(400).send({ error: 'fetching list of devices failed' })
}
})
app.delete(
'/device',
needsAuth,
async function (req: AuthenticatedRequest, res) {
if (!req.body.thingId || !req.body.deviceId) {
return res
.status(400)
.send({ error: 'missing thingId or deviceId in body' })
}
try {
const deleteResult = await deleteDevice({
userId: req.userId,
deviceId: req.body.deviceId,
thingId: req.body.thingId,
})
//make sure that the device was really deleted from db (as this is guarded with userId)
if (deleteResult.Attributes.deviceId == req.body.deviceId) {
//..only then delete the shadow
await publish(
`$aws/things/${req.body.thingId}/shadow/name/${req.body.deviceId}/delete`,
{}
)
//tell Alexa that the device was deleted, too:
await proactivelyUndiscoverDevices(req.userId, [req.body.deviceId])
}
res.send({ status: 'OK' })
} catch (e) {
res.status(400).send({ error: 'operation failed' })
}
}
)
export const server = serverless(app, {
request(request, event, _context) {
request.rawBody = event.body
},
})