JavaScript (Express)
const crypto = require('crypto');
const express = require('express');
const app = express();
app.post('/webhook/mailbrew', express.raw({ type: 'application/json' }), (req, res) => {
const timestamp = req.get('X-Mailbrew-Timestamp') || '';
if (!/^\d+$/.test(timestamp)) return res.status(401).end();
if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) return res.status(401).end();
const expected = 'sha256=' + crypto.createHmac('sha256', process.env.MAILBREW_WEBHOOK_SECRET)
.update(`${timestamp}.${req.body}`)
.digest('hex');
const signature = req.get('X-Mailbrew-Signature') ?? '';
if (signature.length !== expected.length
|| !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
return res.status(401).end();
}
const { address, email } = JSON.parse(req.body);
const subject = email.subject ?? '';
console.log(`New email at ${address}: ${subject}`);
if (subject.includes('注文確認')) {
processOrder(email);
} else if (subject.includes('サポート')) {
createTicket(email);
}
res.status(200).json({ received: true });
});
app.listen(3000);