/
webhooks.ts
426 lines (386 loc) · 12.3 KB
/
webhooks.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
const scmp = require("scmp");
import crypto from "crypto";
import urllib from "url";
import { IncomingHttpHeaders } from "http2";
export interface Request {
protocol: string;
header(name: string): string | undefined;
headers: IncomingHttpHeaders;
originalUrl: string;
rawBody?: any;
body: any;
}
export interface RequestValidatorOptions {
/**
* The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options
*/
url?: string;
/**
* Manually specify the host name used by Twilio in a number's webhook config
*/
host?: string;
/**
* Manually specify the protocol used by Twilio in a number's webhook config
*/
protocol?: string;
}
export interface WebhookOptions {
/**
* Whether or not the middleware should validate the request
* came from Twilio. Default true. If the request does not originate from
* Twilio, we will return a text body and a 403. If there is no configured
* auth token and validate=true, this is an error condition, so we will return
* a 500.
*/
validate?: boolean;
/**
* Add helpers to the response object to improve support for XML (TwiML) rendering. Default true.
*/
includeHelpers?: boolean;
/**
* The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options
*/
url?: string;
/**
* Manually specify the host name used by Twilio in a number's webhook config
*/
host?: string;
/**
* Manually specify the protocol used by Twilio in a number's webhook config
*/
protocol?: string;
/**
* Authentication token
*/
authToken?: string;
}
/**
* Utility function to construct the URL string, since Node.js url library won't include standard port numbers
*
* @param parsedUrl - The parsed url object that Twilio requested on your server
* @returns URL with standard port number included
*/
function buildUrlWithStandardPort(parsedUrl: URL): string {
let url = "";
const port = parsedUrl.protocol === "https:" ? ":443" : ":80";
url += parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
url += parsedUrl.username;
url += parsedUrl.password ? ":" + parsedUrl.password : "";
url += parsedUrl.username || parsedUrl.password ? "@" : "";
url += parsedUrl.host ? parsedUrl.host + port : "";
url += parsedUrl.pathname + parsedUrl.search + parsedUrl.hash;
return url;
}
/**
Utility function to add a port number to a URL
@param parsedUrl - The parsed url object that Twilio requested on your server
@returns URL with port
*/
function addPort(parsedUrl: URL): string {
if (!parsedUrl.port) {
return buildUrlWithStandardPort(parsedUrl);
}
return parsedUrl.toString();
}
/**
Utility function to remove a port number from a URL
@param parsedUrl - The parsed url object that Twilio requested on your server
@returns URL without port
*/
function removePort(parsedUrl: URL): string {
parsedUrl.port = "";
return parsedUrl.toString();
}
/**
Utility function to convert request parameter to a string format
@param paramName - The request parameter name
@param paramValue - The request parameter value
@returns Formatted parameter string
*/
function toFormUrlEncodedParam(
paramName: string,
paramValue: string | Array<string>
): string {
if (paramValue instanceof Array) {
return Array.from(new Set(paramValue))
.sort()
.map((val) => toFormUrlEncodedParam(paramName, val))
.reduce((acc, val) => acc + val, "");
}
return paramName + paramValue;
}
/**
Utility function to get the expected signature for a given request
@param authToken - The auth token, as seen in the Twilio portal
@param url - The full URL (with query string) you configured to handle
this request
@param params - the parameters sent with this request
@returns signature
*/
export function getExpectedTwilioSignature(
authToken: string,
url: string,
params: Record<string, any>
): string {
if (url.indexOf("bodySHA256") !== -1 && params === null) {
params = {};
}
var data = Object.keys(params)
.sort()
.reduce((acc, key) => acc + toFormUrlEncodedParam(key, params[key]), url);
return crypto
.createHmac("sha1", authToken)
.update(Buffer.from(data, "utf-8"))
.digest("base64");
}
/**
Utility function to get the expected body hash for a given request's body
@param body - The plain-text body of the request
*/
export function getExpectedBodyHash(body: string): string {
return crypto
.createHash("sha256")
.update(Buffer.from(body, "utf-8"))
.digest("hex");
}
/**
Utility function to validate an incoming request is indeed from Twilio
@param authToken - The auth token, as seen in the Twilio portal
@param twilioHeader - The value of the X-Twilio-Signature header from the request
@param url - The full URL (with query string) you configured to handle this request
@param params - the parameters sent with this request
@returns valid
*/
export function validateRequest(
authToken: string,
twilioHeader: string,
url: string,
params: Record<string, any>
): boolean {
twilioHeader = twilioHeader || "";
const urlObject = new URL(url);
const urlWithPort = addPort(urlObject);
const urlWithoutPort = removePort(urlObject);
/*
* Check signature of the url with and without the port number
* since signature generation on the back end is inconsistent
*/
const signatureWithPort = getExpectedTwilioSignature(
authToken,
urlWithPort,
params
);
const signatureWithoutPort = getExpectedTwilioSignature(
authToken,
urlWithoutPort,
params
);
const validSignatureWithPort = scmp(
Buffer.from(twilioHeader),
Buffer.from(signatureWithPort)
);
const validSignatureWithoutPort = scmp(
Buffer.from(twilioHeader),
Buffer.from(signatureWithoutPort)
);
return validSignatureWithoutPort || validSignatureWithPort;
}
export function validateBody(
body: string,
bodyHash: any[] | string | Buffer
): boolean {
var expectedHash = getExpectedBodyHash(body);
return scmp(Buffer.from(bodyHash), Buffer.from(expectedHash));
}
/**
Utility function to validate an incoming request is indeed from Twilio. This also validates
the request body against the bodySHA256 post parameter.
@param authToken - The auth token, as seen in the Twilio portal
@param twilioHeader - The value of the X-Twilio-Signature header from the request
@param url - The full URL (with query string) you configured to handle this request
@param body - The body of the request
@returns valid
*/
export function validateRequestWithBody(
authToken: string,
twilioHeader: string,
url: string,
body: string
): boolean {
const urlObject = new URL(url);
return (
validateRequest(authToken, twilioHeader, url, {}) &&
validateBody(body, urlObject.searchParams.get("bodySHA256") || "")
);
}
/**
Utility function to validate an incoming request is indeed from Twilio.
adapted from https://github.com/crabasa/twiliosig
@param request - A request object (based on Express implementation http://expressjs.com/api.html#req.params)
@param authToken - The auth token, as seen in the Twilio portal
@param opts - options for request validation:
-> url: The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options
-> host: manually specify the host name used by Twilio in a number's webhook config
-> protocol: manually specify the protocol used by Twilio in a number's webhook config
*/
export function validateIncomingRequest(
request: Request,
authToken: string,
opts?: RequestValidatorOptions
): boolean {
var options = opts || {};
var webhookUrl;
if (options.url) {
// Let the user specify the full URL
webhookUrl = options.url;
} else {
// Use configured host/protocol, or infer based on request
var protocol = options.protocol || request.protocol;
var host = options.host || request.headers.host;
webhookUrl = urllib.format({
protocol: protocol,
host: host,
pathname: request.originalUrl,
});
if (request.originalUrl.search(/\?/) >= 0) {
webhookUrl = webhookUrl.replace(/%3F/g, "?");
}
}
if (webhookUrl.indexOf("bodySHA256") > 0) {
return validateRequestWithBody(
authToken,
request.header("X-Twilio-Signature") || "",
webhookUrl,
request.rawBody || "{}"
);
} else {
return validateRequest(
authToken,
request.header("X-Twilio-Signature") || "",
webhookUrl,
request.body || {}
);
}
}
export function validateExpressRequest(
request: Request,
authToken: string,
opts?: RequestValidatorOptions
): boolean {
return validateIncomingRequest(request, authToken, opts);
}
/**
Express middleware to accompany a Twilio webhook. Provides Twilio
request validation, and makes the response a little more friendly for our
TwiML generator. Request validation requires the express.urlencoded middleware
to have been applied (e.g. app.use(express.urlencoded()); in your app config).
Options:
- validate: {Boolean} whether or not the middleware should validate the request
came from Twilio. Default true. If the request does not originate from
Twilio, we will return a text body and a 403. If there is no configured
auth token and validate=true, this is an error condition, so we will return
a 500.
- host: manually specify the host name used by Twilio in a number's webhook config
- protocol: manually specify the protocol used by Twilio in a number's webhook config
- url: The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options
Returns a middleware function.
Examples:
var webhookMiddleware = twilio.webhook();
var webhookMiddleware = twilio.webhook('asdha9dhjasd'); //init with auth token
var webhookMiddleware = twilio.webhook({
validate:false // don't attempt request validation
});
var webhookMiddleware = twilio.webhook({
host: 'hook.twilio.com',
protocol: 'https'
});
*/
export function webhook(
opts?: string | WebhookOptions,
authToken?: string | WebhookOptions
): (req: any, res: any, next: any) => void {
let token: string;
let options: WebhookOptions | undefined = undefined;
// Narrowing the args
if (opts) {
if (typeof opts === "string") {
token = opts;
}
if (typeof opts === "object") {
options = opts;
}
}
if (authToken) {
if (typeof authToken === "string") {
token = authToken;
}
if (typeof authToken === "object") {
options = authToken;
}
}
if (!options) {
options = {
validate: true,
};
}
// Process arguments
var tokenString;
for (var i = 0, l = arguments.length; i < l; i++) {
var arg = arguments[i];
if (typeof arg === "string") {
tokenString = arg;
} else {
options = Object.assign(options || {}, arg);
}
}
// set auth token from input or environment variable
if (options) {
options.authToken = tokenString
? tokenString
: process.env.TWILIO_AUTH_TOKEN;
}
// Create middleware function
return function hook(request, response, next) {
// Do validation if requested
if (options?.validate) {
// Check if the 'X-Twilio-Signature' header exists or not
if (!request.header("X-Twilio-Signature")) {
return response
.type("text/plain")
.status(400)
.send(
"No signature header error - X-Twilio-Signature header does not exist, maybe this request is not coming from Twilio."
);
}
// Check for a valid auth token
if (!options?.authToken) {
console.error(
"[Twilio]: Error - Twilio auth token is required for webhook request validation."
);
response
.type("text/plain")
.status(500)
.send(
"Webhook Error - we attempted to validate this request without first configuring our auth token."
);
} else {
// Check that the request originated from Twilio
var valid = validateExpressRequest(request, options?.authToken, {
url: options?.url,
host: options?.host,
protocol: options?.protocol,
});
if (valid) {
next();
} else {
return response
.type("text/plain")
.status(403)
.send("Twilio Request Validation Failed.");
}
}
} else {
next();
}
};
}