forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookService.js
More file actions
245 lines (214 loc) · 7.16 KB
/
Copy pathwebhookService.js
File metadata and controls
245 lines (214 loc) · 7.16 KB
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
/**
* Webhook Service
*
* - HMAC-SHA256 signature generation & verification
* - HTTP delivery with timeout
* - Exponential-backoff retry scheduling
* - Event dispatch to all subscribed webhooks
*/
const crypto = require('crypto');
const https = require('https');
const http = require('http');
const {
getActiveWebhooksForEvent,
createDelivery,
updateDelivery,
} = require('../db/webhookRepository');
// ---------------------------------------------------------------------------
// Supported event types
// ---------------------------------------------------------------------------
const EVENT_TYPES = [
'reward.distributed',
'reward.redeemed',
'campaign.created',
'campaign.updated',
'campaign.expired',
'user.registered',
'user.referral_bonus',
'drop.claimed',
'transaction.recorded',
'*', // wildcard — receive all events
];
// ---------------------------------------------------------------------------
// Signature
// ---------------------------------------------------------------------------
const SIGNATURE_HEADER = 'x-nova-signature';
const TIMESTAMP_HEADER = 'x-nova-timestamp';
const DELIVERY_ID_HEADER = 'x-nova-delivery-id';
const TOLERANCE_MS = 5 * 60 * 1000; // 5 minutes
/**
* Generates a signing secret (32 random bytes, hex-encoded).
*/
function generateSecret() {
return crypto.randomBytes(32).toString('hex');
}
/**
* Builds the HMAC-SHA256 signature for a payload.
* Format: HMAC(secret, `${timestamp}.${deliveryId}.${rawBody}`)
*/
function signPayload(secret, timestamp, deliveryId, rawBody) {
return crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${deliveryId}.${rawBody}`)
.digest('hex');
}
/**
* Verifies an incoming webhook signature.
* Returns true if valid and within the replay-attack tolerance window.
*
* @param {string} secret
* @param {string} receivedSig - value of x-nova-signature header
* @param {string} timestamp - value of x-nova-timestamp header
* @param {string} deliveryId - value of x-nova-delivery-id header
* @param {string} rawBody - raw request body string
*/
function verifySignature(secret, receivedSig, timestamp, deliveryId, rawBody) {
const ts = parseInt(timestamp, 10);
if (isNaN(ts) || Math.abs(Date.now() - ts) > TOLERANCE_MS) return false;
const expected = signPayload(secret, timestamp, deliveryId, rawBody);
try {
return crypto.timingSafeEqual(
Buffer.from(expected, 'hex'),
Buffer.from(receivedSig, 'hex')
);
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// HTTP delivery
// ---------------------------------------------------------------------------
const DELIVERY_TIMEOUT_MS = parseInt(process.env.WEBHOOK_TIMEOUT_MS) || 10_000;
/**
* Sends a single HTTP POST to the webhook URL.
*
* @param {string} url
* @param {object} payload
* @param {string} secret
* @param {string} deliveryId - stable per-delivery-attempt UUID
* @returns {Promise<{ httpStatus: number, responseBody: string }>}
*/
function deliverHttp(url, payload, secret, deliveryId) {
return new Promise((resolve, reject) => {
const rawBody = JSON.stringify(payload);
const timestamp = String(Date.now());
const signature = signPayload(secret, timestamp, deliveryId, rawBody);
const parsed = new URL(url);
const options = {
hostname: parsed.hostname,
port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
path: parsed.pathname + parsed.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(rawBody),
[TIMESTAMP_HEADER]: timestamp,
[SIGNATURE_HEADER]: signature,
[DELIVERY_ID_HEADER]: deliveryId,
'User-Agent': 'NovaRewards-Webhook/1.0',
},
};
const transport = parsed.protocol === 'https:' ? https : http;
const req = transport.request(options, (res) => {
let body = '';
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => resolve({ httpStatus: res.statusCode, responseBody: body.slice(0, 1000) }));
});
req.setTimeout(DELIVERY_TIMEOUT_MS, () => {
req.destroy();
reject(new Error('Webhook delivery timed out'));
});
req.on('error', reject);
req.write(rawBody);
req.end();
});
}
// ---------------------------------------------------------------------------
// Retry schedule — exponential backoff: 1m, 5m, 30m, 2h, 8h
// ---------------------------------------------------------------------------
const RETRY_DELAYS_MS = [
1 * 60 * 1000,
5 * 60 * 1000,
30 * 60 * 1000,
2 * 60 * 60 * 1000,
8 * 60 * 60 * 1000,
];
function nextRetryAt(attempt) {
const delay = RETRY_DELAYS_MS[attempt - 1];
if (!delay) return null;
return new Date(Date.now() + delay);
}
// ---------------------------------------------------------------------------
// Core delivery logic (used by dispatch and retry job)
// ---------------------------------------------------------------------------
/**
* Attempts delivery for an existing delivery row.
* Updates the row with the result.
*/
async function attemptDelivery(delivery) {
const { id, webhook_id, payload, attempt, url, secret } = delivery;
try {
const { httpStatus, responseBody } = await deliverHttp(url, payload, secret, delivery.delivery_id);
const success = httpStatus >= 200 && httpStatus < 300;
await updateDelivery(id, {
status: success ? 'success' : 'failed',
httpStatus,
responseBody,
nextRetryAt: success ? null : nextRetryAt(attempt + 1),
deliveredAt: success ? new Date() : null,
attempt: attempt + 1,
});
return success;
} catch (err) {
await updateDelivery(id, {
status: 'failed',
responseBody: err.message,
nextRetryAt: nextRetryAt(attempt + 1),
attempt: attempt + 1,
});
return false;
}
}
// ---------------------------------------------------------------------------
// Dispatch — fan-out to all subscribed webhooks for an event
// ---------------------------------------------------------------------------
/**
* Dispatches an event to all active webhooks subscribed to it.
* Creates delivery rows and fires them concurrently (fire-and-forget safe).
*
* @param {string} eventType - one of EVENT_TYPES
* @param {object} data - event payload data
*/
async function dispatch(eventType, data) {
const webhooks = await getActiveWebhooksForEvent(eventType);
if (!webhooks.length) return;
const payload = {
event: eventType,
timestamp: new Date().toISOString(),
data,
};
await Promise.allSettled(
webhooks.map(async (webhook) => {
const delivery = await createDelivery({
webhookId: webhook.id,
eventType,
payload,
});
// Attach url/secret for attemptDelivery
delivery.url = webhook.url;
delivery.secret = webhook.secret;
await attemptDelivery(delivery);
})
);
}
module.exports = {
EVENT_TYPES,
SIGNATURE_HEADER,
TIMESTAMP_HEADER,
DELIVERY_ID_HEADER,
generateSecret,
signPayload,
verifySignature,
dispatch,
attemptDelivery,
};