Twilio developer evangelist here.
You can't hook into the validation failure with the webhook
function, but you could write your own middleware function that takes inspiration from the webhook
function.
Something like this might work:
const { validateExpressRequest } = require("twilio");
function webhook() {
var opts = {
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 {
opts = _.extend(opts, arg);
}
}
// set auth token from input or environment variable
opts.authToken = tokenString ? tokenString : process.env.TWILIO_AUTH_TOKEN;
// Create middleware function
return function hook(request, response, next) {
// Do validation if requested
if (opts.validate) {
// Check if the 'X-Twilio-Signature' header exists or not
if (!request.header('X-Twilio-Signature')) {
// Log error here
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 (!opts.authToken) {
// Log error here
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, opts.authToken, {
url: opts.url,
host: opts.host,
protocol: opts.protocol,
});
if (valid) {
next();
} else {
// Log error here
return response
.type('text/plain')
.status(403)
.send('Twilio Request Validation Failed.');
}
}
} else {
next();
}
};
}