-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathwebhook_integration_example.js
More file actions
451 lines (379 loc) · 13.3 KB
/
webhook_integration_example.js
File metadata and controls
451 lines (379 loc) · 13.3 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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/**
* Webhook Monitor Integration Example
*
* This file shows how to integrate the webhook monitor with your backend.
* Choose one of the three methods below based on your infrastructure.
*/
// ============================================================================
// METHOD 1: WebSocket (Recommended for Real-Time)
// ============================================================================
class WebhookMonitorWebSocket {
/**
* @param {string} wsUrl - WebSocket server URL
* @param {object} [options]
* @param {number} [options.maxReconnectAttempts=10] - Max reconnect attempts before giving up
*/
constructor(wsUrl, options = {}) {
this.wsUrl = wsUrl;
this.ws = null;
this.reconnectCount = 0;
this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10;
this._listeners = {};
}
// Minimal EventEmitter interface (avoids a Node.js-only dependency in browser contexts)
on(event, listener) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push(listener);
return this;
}
emit(event, ...args) {
(this._listeners[event] || []).forEach(fn => fn(...args));
}
connect() {
this.ws = new WebSocket(this.wsUrl);
this.ws.onopen = () => {
console.log('✅ WebSocket connected');
this.reconnectCount = 0; // reset budget on every successful connection
};
this.ws.onmessage = (event) => {
try {
const webhookData = JSON.parse(event.data);
this.handleWebhookEvent(webhookData);
} catch (error) {
console.error('Failed to parse webhook event:', error);
}
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.ws.onclose = () => {
console.log('WebSocket closed');
this.attemptReconnect();
};
}
attemptReconnect() {
if (this.reconnectCount >= this.maxReconnectAttempts) {
// Only emit the event on the first time we hit the limit
if (this.reconnectCount === this.maxReconnectAttempts) {
console.error(
`WebSocket reconnect limit reached (${this.maxReconnectAttempts} attempts). Giving up.`
);
this.emit('max_reconnects_exceeded', { attempts: this.reconnectCount });
// Sentinel: increment past the limit so subsequent onclose calls are silent no-ops
this.reconnectCount++;
}
return;
}
this.reconnectCount++;
const delay = Math.min(1000 * Math.pow(2, this.reconnectCount), 30000);
console.log(`Reconnecting in ${delay}ms... (attempt ${this.reconnectCount}/${this.maxReconnectAttempts})`);
setTimeout(() => this.connect(), delay);
}
handleWebhookEvent(webhookData) {
// Add to monitor (assumes addEvent function exists in webhook_monitor.html)
if (typeof addEvent === 'function') {
addEvent({
id: ++eventCounter,
type: webhookData.type,
timestamp: webhookData.timestamp || new Date().toISOString(),
payload: webhookData.payload
});
}
}
disconnect() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
}
// Usage:
// const monitor = new WebhookMonitorWebSocket('ws://localhost:8080/webhooks');
// monitor.connect();
// ============================================================================
// METHOD 2: Server-Sent Events (SSE)
// ============================================================================
class WebhookMonitorSSE {
constructor(sseUrl) {
this.sseUrl = sseUrl;
this.eventSource = null;
}
connect() {
this.eventSource = new EventSource(this.sseUrl);
this.eventSource.onopen = () => {
console.log('✅ SSE connected');
};
this.eventSource.onmessage = (event) => {
try {
const webhookData = JSON.parse(event.data);
this.handleWebhookEvent(webhookData);
} catch (error) {
console.error('Failed to parse SSE event:', error);
}
};
this.eventSource.onerror = (error) => {
console.error('SSE error:', error);
// SSE automatically reconnects
};
}
handleWebhookEvent(webhookData) {
if (typeof addEvent === 'function') {
addEvent({
id: ++eventCounter,
type: webhookData.type,
timestamp: webhookData.timestamp || new Date().toISOString(),
payload: webhookData.payload
});
}
}
disconnect() {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
}
}
// Usage:
// const monitor = new WebhookMonitorSSE('/api/webhook-stream');
// monitor.connect();
// ============================================================================
// METHOD 3: HTTP Polling (Fallback)
// ============================================================================
class WebhookMonitorPolling {
/**
* @param {string} apiUrl
* @param {object} [options]
* @param {number} [options.baseIntervalMs=2000] - Base polling interval
* @param {number} [options.maxIntervalMs=30000] - Maximum backoff interval
*/
constructor(apiUrl, options = {}) {
// Support legacy positional signature: new WebhookMonitorPolling(url, 3000)
if (typeof options === 'number') {
options = { baseIntervalMs: options };
}
this.apiUrl = apiUrl;
this.baseIntervalMs = options.baseIntervalMs ?? 2000;
this.maxIntervalMs = options.maxIntervalMs ?? 30000;
this._timeoutId = null;
this._running = false;
this._failures = 0;
this.lastEventId = 0;
}
start() {
this._running = true;
this.poll();
}
async poll() {
if (!this._running) return;
try {
const response = await fetch(`${this.apiUrl}?since=${this.lastEventId}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const events = await response.json();
this._failures = 0; // reset backoff on success
events.forEach(webhookData => {
this.handleWebhookEvent(webhookData);
if (webhookData.id > this.lastEventId) {
this.lastEventId = webhookData.id;
}
});
} catch (error) {
this._failures++;
console.error('Polling error:', error);
}
if (this._running) {
const delay = Math.min(
this.baseIntervalMs * Math.pow(2, this._failures),
this.maxIntervalMs
);
this._timeoutId = setTimeout(() => this.poll(), delay);
}
}
handleWebhookEvent(webhookData) {
if (typeof addEvent === 'function') {
addEvent({
id: ++eventCounter,
type: webhookData.type,
timestamp: webhookData.timestamp || new Date().toISOString(),
payload: webhookData.payload
});
}
}
stop() {
this._running = false;
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
}
}
// Usage:
// const monitor = new WebhookMonitorPolling('/api/webhooks/recent', 3000);
// monitor.start();
// ============================================================================
// BACKEND EXAMPLES
// ============================================================================
// Express.js + WebSocket Example
/*
const express = require('express');
const WebSocket = require('ws');
const app = express();
const wss = new WebSocket.Server({ port: 8080 });
// Webhook endpoint
app.post('/webhook', express.json(), (req, res) => {
const event = {
id: Date.now(),
type: req.body.type,
timestamp: new Date().toISOString(),
payload: req.body.data
};
// Broadcast to all connected clients
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(event));
}
});
res.status(200).json({ success: true });
});
app.listen(3000, () => console.log('Server running on port 3000'));
*/
// Express.js + SSE Example
/*
const express = require('express');
const app = express();
const clients = [];
// SSE endpoint
app.get('/api/webhook-stream', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
clients.push(res);
req.on('close', () => {
clients.splice(clients.indexOf(res), 1);
});
});
// Webhook endpoint
app.post('/webhook', express.json(), (req, res) => {
const event = {
id: Date.now(),
type: req.body.type,
timestamp: new Date().toISOString(),
payload: req.body.data
};
// Send to all SSE clients
clients.forEach(client => {
client.write(`data: ${JSON.stringify(event)}\n\n`);
});
res.status(200).json({ success: true });
});
app.listen(3000, () => console.log('Server running on port 3000'));
*/
// ============================================================================
// SECURITY MIDDLEWARE EXAMPLE
// ============================================================================
// Allowlist of known, expected fields in a webhook payload.
// Only these fields will pass through to downstream logic.
const WEBHOOK_PAYLOAD_ALLOWLIST = new Set([
'id',
'type',
'timestamp',
'status',
'amount',
'asset',
'user',
'email',
'memo',
'transaction_id',
'account',
'network',
'fee',
'message',
]);
function sanitizeWebhookPayload(payload) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return {};
}
const sanitized = {};
for (const key of Object.keys(payload)) {
if (!WEBHOOK_PAYLOAD_ALLOWLIST.has(key)) {
// Log field name only — never log the value to avoid leaking sensitive data
console.warn(`WARN: Unknown field detected in webhook payload: "${key}"`);
continue;
}
let value = payload[key];
// Redact email addresses
if (key === 'email' && typeof value === 'string' && value.includes('@')) {
const [local, domain] = value.split('@');
value = `${local.substring(0, 2)}***@${domain}`;
}
// Truncate Stellar account addresses
if (key === 'user' && typeof value === 'string' && value.length > 11) {
value = `${value.substring(0, 8)}...${value.substring(value.length - 3)}`;
}
sanitized[key] = value;
}
return sanitized;
}
// ============================================================================
// STELLAR HORIZON INTEGRATION EXAMPLE
// ============================================================================
/*
const StellarSdk = require('stellar-sdk');
function monitorStellarAccount(accountId) {
const server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server.operations()
.forAccount(accountId)
.cursor('now')
.stream({
onmessage: (operation) => {
const event = {
id: operation.id,
type: mapOperationType(operation.type),
timestamp: operation.created_at,
payload: {
operation_type: operation.type,
from: operation.from,
to: operation.to,
amount: operation.amount,
asset: operation.asset_type
}
};
// Send to webhook monitor
broadcastEvent(event);
},
onerror: (error) => {
console.error('Stellar stream error:', error);
}
});
}
function mapOperationType(stellarType) {
const typeMap = {
'payment': 'transfer',
'create_account': 'deposit',
'path_payment_strict_receive': 'transfer',
'path_payment_strict_send': 'transfer'
};
return typeMap[stellarType] || 'other';
}
*/
// ============================================================================
// USAGE IN webhook_monitor.html
// ============================================================================
/*
Replace the simulation code in webhook_monitor.html with:
<script>
// Choose your integration method
const monitor = new WebhookMonitorWebSocket('ws://localhost:8080/webhooks');
// OR
// const monitor = new WebhookMonitorSSE('/api/webhook-stream');
// OR
// const monitor = new WebhookMonitorPolling('/api/webhooks/recent', 3000);
// Start monitoring
monitor.connect(); // or monitor.start() for polling
// Clean up on page unload
window.addEventListener('beforeunload', () => {
monitor.disconnect(); // or monitor.stop() for polling
});
</script>
*/