-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·263 lines (229 loc) · 7.62 KB
/
index.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
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
'use strict';
const unirest = require('unirest');
const path = require('path');
const crypto = require('crypto');
const tools = require('openssl-cert-tools');
const isUndefined = require('lodash').isUndefined;
const DEBUG = false;
function logDebug(...args) {
if (DEBUG) {
console.log.apply(null, args);
}
}
function SimpleAlexaSkill(skillId, messages, intents) {
let skill = {};
skill.intents = intents;
skill.messages = messages;
skill.skillId = skillId;
function handleError(message, obj) {
console.log(`ERROR: ${message}`);
if (obj) {
console.log(obj);
}
return false;
}
function howOld(timestamp) {
// Return seconds
let _timestamp = new Date(timestamp);
let serverTime = new Date();
return (serverTime.getTime() - _timestamp.getTime()) / 1000;
}
function validateRequest(req) {
let body = JSON.parse(req.body);
let headers = req.headers;
try {
let signed = new Promise((resolve) => {
if (isUndefined(headers)) {
resolve(handleError('No headers.'));
}
// Check for good signature url
if (isUndefined(headers.signaturecertchainurl)) {
resolve(handleError('No signature url.'));
} else {
// Returns https:/s3.amazonaws.com/echo.api/echo-api-cert-4.pem
// or https:/s3.amazonaws.com:443/echo.api/echo-api-cert-4.pem
// The protocol is equal to https (case insensitive).
// The hostname is equal to s3.amazonaws.com (case insensitive).
// The path starts with /echo.api/ (case sensitive).
let nPath = path.normalize(headers.signaturecertchainurl); // protocol missing second slash here
if (nPath.substring(0, 7).toLowerCase() !== 'https:/') {
resolve(handleError('Invalid signature protocol.'));
}
if (nPath.substring(7, 23).toLowerCase() !== 's3.amazonaws.com') {
resolve(handleError('Invalid signature domain.'));
}
if (nPath.substring(23, 27).toLowerCase() !== ':443') {
if (nPath.substring(23, 33).toLowerCase() !== '/echo.api/') {
resolve(handleError('Invalid signature path.'));
}
} else {
if (nPath.substring(27, 37).toLowerCase() !== '/echo.api/') {
resolve(handleError('Invalid secure signature path.'));
}
}
}
// Verify signature
if (isUndefined(headers.signature)) {
resolve(handleError('No signature.'));
} else {
// Certificate URL is already validated, so might as well validate the contents.
// 1. Fetch cert.
// 2. Validate cert.
// 3. Validate signature.
let getCertificate = new Promise((resolve) => {
unirest.get(headers.signaturecertchainurl).end((result) => {
resolve(result);
});
});
getCertificate.then((result) => {
if (result.status === 200) {
let certification = result.body;
let getCertificateInfo = new Promise((resolve, reject) => {
return tools.getCertificateInfo(certification, (err, info) => {
if (err) {
reject(err);
} else {
resolve(info);
}
});
});
getCertificateInfo.then((info) => {
if (info.subject.CN.indexOf('echo-api.amazon.com') === -1) {
resolve(handleError('Certificate missing required subjectAltName.'));
}
if (info.remainingDays < 1) {
resolve(handleError('Certificate expired.'));
}
logDebug('certificate current and from valid location.');
let verifier = crypto.createVerify('RSA-SHA1');
logDebug('verifier created');
verifier.update(req.rawBody);
logDebug('verifier updated', req.rawBody);
let verified = verifier.verify(certification, headers.signature, 'base64');
logDebug('verifying complete', verified);
if (!verified) {
resolve(handleError('Invalid signature.'));
}
resolve(true);
}, (err) => {
resolve(handleError('Error retrieving certificate info.', err));
});
} else {
resolve(handleError('Certificate not present at URL.'));
}
});
}
});
return signed.then((valid) => {
logDebug('signed correctly', valid);
if (!valid) {
return valid;
}
// Check for request as a whole
if (isUndefined(body)) {
return handleError('No request.');
}
// Make sure request exists
if (isUndefined(body.request)) {
return handleError('Missing request.');
}
// Check timestamp
if (isUndefined(body.request.timestamp)) {
return handleError('Missing timestamp.');
}
if (howOld(body.request.timestamp) > 100) {
return handleError('Old request.', howOld(body.request.timestamp));
}
// Check request type
if (isUndefined(body.request.type)) {
return handleError('Missing request type.');
}
// Check for valid request type
if (['LaunchRequest', 'IntentRequest', 'SessionEndedRequest'].indexOf(body.request.type) < 0) {
return handleError('Invalid request type.', body.request.type);
}
// CHeck for valid intents
if (body.request.type === 'IntentRequest' && (isUndefined(body.request.intent) || !skill.intents[body.request.intent.name])) {
return handleError('Invalid intent.', body.request.intent);
}
// Check for applicationId
if (isUndefined(body.session)) {
return handleError('Missing session.');
}
if (isUndefined(body.session.application) || isUndefined(body.session.application.applicationId)) {
return handleError('Missing applicationId.');
}
// Validate applicationId
if (body.session.application.applicationId !== skill.skillId) {
return handleError('Invalid applicationId.', body.session.application.applicationId);
}
// Validate version
if (body.version !== '1.0') {
return handleError('Invalid version.', body.version);
}
return true;
});
} catch(err) {
return new Promise((resolve) => {
resolve(handleError('JavaScript error.', err));
});
}
}
skill.formatResponse = function (output, reprompt, endSession) {
let data = {
'version': '1.0',
'response': {
'outputSpeech': {
'type': 'SSML',
'ssml': `<speak>${output}</speak>`
},
'shouldEndSession': !!endSession
},
'sessionAttributes': {}
};
if (reprompt) {
data.response.reprompt = {
'outputSpeech': {
'type': 'SSML',
'ssml': `<speak>${reprompt}</speak>`
}};
}
return data;
};
skill.handleAll = (method, req, res) => {
function errorHandler(requestBody, res) {
res.send(skill.formatResponse(skill.messages.error.output, skill.messages.error.reprompt));
}
validateRequest(req).then((valid) => {
if (valid) {
try {
let requestBody = JSON.parse(req.body);
// Get the request type "request":
let requestType = requestBody.request.type;
if (requestType === 'LaunchRequest') {
res.send(skill.formatResponse(skill.messages.launch.output));
} else if (requestType === 'IntentRequest') {
try {
skill.intents[requestBody.request.intent.name](requestBody, res);
} catch(err) {
handleError(`Intent handler for ${requestBody.request.intent.name} failed.`, err);
errorHandler(requestBody, res);
}
} else if (requestType === 'SessionEndedRequest') {
logDebug('Session ended', requestBody.reason);
res.send(formatResponse(skill.messages.endSession.output));
}
} catch (err) {
res.send(skill.formatResponse(skill.messages.error.output, skill.messages.error.reprompt));
}
} else {
// For security purposes
// return 400 Bad Request
// res.send(formatResponse(skill.messages.error.output, skill.messages.error.reprompt, true));
res.status(400).send();
}
});
};
return skill;
}
module.exports = SimpleAlexaSkill;