@blamejs/core 0.7.4 → 0.7.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/CHANGELOG.md +423 -395
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -284
  5. package/lib/api-key.js +660 -663
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -256
  27. package/lib/cache.js +1206 -1206
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/file-upload.js +213 -10
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -215
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -936
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -264
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -612
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -488
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -519
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -903
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -167
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -745
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -519
  146. package/lib/request-helpers.js +340 -340
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -618
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +184 -4
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -319
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -595
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -1,528 +1,528 @@
1
- "use strict";
2
- /**
3
- * mail-bounce — vendor-shaped intake for outbound-mail bounces /
4
- * complaints / delivery callbacks.
5
- *
6
- * Outbound mail can come back as:
7
- * - a hard or soft bounce (delivery failure)
8
- * - a spam / abuse complaint
9
- * - a delivered confirmation
10
- * - a list-unsubscribe complaint
11
- *
12
- * Vendors (Postmark, SES via SNS, Resend) ship these as HTTP webhooks
13
- * with payload shapes that all carry the same information dressed up
14
- * differently. This module owns the translation: each vendor parser
15
- * normalizes its payload into one shape so operators don't write
16
- * vendor-specific reconciliation code per environment.
17
- *
18
- * Public API:
19
- *
20
- * mailBounce.parse(payload, { vendor })
21
- * Pure synchronous parser. Returns the normalized event:
22
- * {
23
- * vendor: "postmark" | "ses" | "resend",
24
- * type: "bounce" | "complaint" | "delivery",
25
- * subType: "hard" | "soft" | "abuse" | ... | null,
26
- * recipient: "user@example.com",
27
- * messageId: "<framework-emitted Message-ID>" | null,
28
- * reason: "smtp 550 ..." | null,
29
- * timestamp: "2026-04-28T..." (ISO 8601),
30
- * raw: <input payload, untouched>,
31
- * }
32
- *
33
- * mailBounce.handler({ vendor, verify?, onBounce?, audit?, ... })
34
- * Returns an Express-style middleware (req, res). Buffers + parses
35
- * the request body, calls verify(req, body) if supplied, runs the
36
- * parser, emits system.mail.bounce, calls onBounce(event), and
37
- * responds 200. Validation errors land as 400 with a JSON error.
38
- * Verification failures land as 401.
39
- *
40
- * Operator example (Postmark):
41
- *
42
- * var bounce = b.mailBounce.handler({
43
- * vendor: "postmark",
44
- * verify: function (req) {
45
- * // Postmark recommends Basic Auth on the webhook URL.
46
- * return req.headers.authorization === expectedBasic;
47
- * },
48
- * onBounce: function (event) {
49
- * // Mark the recipient as bounced in your data store.
50
- * return repo.users.markBounced(event.recipient, event.subType);
51
- * },
52
- * });
53
- * r.post("/webhooks/postmark", bounce);
54
- *
55
- * Audit: every parsed bounce/complaint/delivery emits one
56
- * `system.mail.bounce` row carrying the normalized fields. Audit is on
57
- * by default and disabled per-instance via { audit: false }.
58
- *
59
- * Generic DSN (RFC 3464 multipart/report) is intentionally NOT included
60
- * as a built-in vendor: parsing arbitrary email-back-from-MTA reports
61
- * needs a full email parser, which the framework does not vendor for
62
- * this surface. Operators with raw DSN inflow plug a custom parser via
63
- * the { vendor: 'custom', parser } shape (see _customParser below).
64
- */
65
-
66
- var lazyRequire = require("./lazy-require");
67
- var numericBounds = require("./numeric-bounds");
68
- var audit = lazyRequire(function () { return require("./audit"); });
69
- var safeBuffer = require("./safe-buffer");
70
- var safeJson = require("./safe-json");
71
- var C = require("./constants");
72
- var requestHelpers = require("./request-helpers");
73
- var { defineClass } = require("./framework-error");
74
-
75
- var HTTP = requestHelpers.HTTP_STATUS;
76
-
77
- var MailBounceError = defineClass("MailBounceError", { withStatusCode: true });
78
-
79
- // Cap on inbound webhook bodies — any vendor bigger than this is
80
- // pathological and likely an attack surface. 256 KiB covers the
81
- // largest realistic SES SNS notification with verbose diagnostic info.
82
- var MAX_BODY_BYTES = C.BYTES.kib(256);
83
-
84
- function _err(code, message, statusCode) {
85
- return new MailBounceError(code, message, true, statusCode || 400);
86
- }
87
-
88
- // ---- Postmark ----
89
- //
90
- // Webhook payload (JSON):
91
- // {
92
- // "RecordType": "Bounce" | "SpamComplaint" | "Delivery",
93
- // "Type": "HardBounce" | "SoftBounce" | "Transient" | ...,
94
- // "Email": "...",
95
- // "MessageID": "...",
96
- // "Description": "...",
97
- // "Details": "...",
98
- // "BouncedAt": "2026-04-28T..." (Bounce / SpamComplaint)
99
- // "DeliveredAt": "..." (Delivery)
100
- // }
101
-
102
- var POSTMARK_TYPE_TO_NORMAL = {
103
- "HardBounce": { type: "bounce", subType: "hard" },
104
- "SoftBounce": { type: "bounce", subType: "soft" },
105
- "Transient": { type: "bounce", subType: "soft" },
106
- "Unknown": { type: "bounce", subType: "unknown" },
107
- "Subscribe": { type: "complaint", subType: "subscribe-fail" },
108
- "AutoResponder": { type: "bounce", subType: "auto-reply" },
109
- "AddressChange": { type: "bounce", subType: "address-change" },
110
- "DnsError": { type: "bounce", subType: "soft" },
111
- "SpamNotification": { type: "complaint", subType: "spam" },
112
- "OpenRelayTest": { type: "bounce", subType: "policy" },
113
- "Unsubscribe": { type: "complaint", subType: "unsubscribe" },
114
- "Blocked": { type: "bounce", subType: "blocked" },
115
- "SMTPApiError": { type: "bounce", subType: "api" },
116
- "InboundError": { type: "bounce", subType: "inbound" },
117
- "DMARCPolicy": { type: "bounce", subType: "policy" },
118
- "TemplateRenderingFailed": { type: "bounce", subType: "template" },
119
- "ManuallyDeactivated": { type: "bounce", subType: "deactivated" },
120
- };
121
-
122
- function _parsePostmark(p) {
123
- if (!p || typeof p !== "object") {
124
- throw _err("postmark/empty", "postmark webhook payload must be an object");
125
- }
126
- var record = p.RecordType;
127
- var email = p.Email;
128
- if (typeof email !== "string" || email.length === 0) {
129
- throw _err("postmark/missing-email", "postmark payload missing 'Email'");
130
- }
131
-
132
- if (record === "Delivery") {
133
- return {
134
- vendor: "postmark",
135
- type: "delivery",
136
- subType: null,
137
- recipient: email,
138
- messageId: typeof p.MessageID === "string" ? p.MessageID : null,
139
- reason: null,
140
- timestamp: p.DeliveredAt || new Date().toISOString(),
141
- raw: p,
142
- };
143
- }
144
- if (record === "SpamComplaint") {
145
- return {
146
- vendor: "postmark",
147
- type: "complaint",
148
- subType: "spam",
149
- recipient: email,
150
- messageId: typeof p.MessageID === "string" ? p.MessageID : null,
151
- reason: p.Details || p.Description || null,
152
- timestamp: p.BouncedAt || new Date().toISOString(),
153
- raw: p,
154
- };
155
- }
156
- if (record === "Bounce" || record === "SubscriptionChange" || !record) {
157
- var mapping = POSTMARK_TYPE_TO_NORMAL[p.Type] ||
158
- { type: "bounce", subType: typeof p.Type === "string" ? p.Type.toLowerCase() : "unknown" };
159
- return {
160
- vendor: "postmark",
161
- type: mapping.type,
162
- subType: mapping.subType,
163
- recipient: email,
164
- messageId: typeof p.MessageID === "string" ? p.MessageID : null,
165
- reason: p.Details || p.Description || null,
166
- timestamp: p.BouncedAt || p.DeliveredAt || new Date().toISOString(),
167
- raw: p,
168
- };
169
- }
170
- throw _err("postmark/unknown-record",
171
- "postmark RecordType '" + String(record) + "' not recognised");
172
- }
173
-
174
- // ---- SES via SNS ----
175
- //
176
- // Outer envelope (SNS notification):
177
- // { "Type": "Notification", "MessageId": "...",
178
- // "Message": "<json string>", "Signature": "...", ... }
179
- //
180
- // After JSON.parse(Message):
181
- // { "notificationType": "Bounce" | "Complaint" | "Delivery",
182
- // "mail": { "messageId": "...", "destination": ["..."], ... },
183
- // "bounce": { "bounceType": "Permanent" | "Transient" | "Undetermined",
184
- // "bounceSubType": "General" | ...,
185
- // "bouncedRecipients": [
186
- // { "emailAddress": "...", "diagnosticCode": "...",
187
- // "action": "...", "status": "..." }
188
- // ],
189
- // "timestamp": "..." },
190
- // "complaint": { ... }, "delivery": { ... } }
191
-
192
- function _parseSes(p) {
193
- if (!p || typeof p !== "object") {
194
- throw _err("ses/empty", "SES payload must be an object");
195
- }
196
- // Accept either the SNS envelope or the unwrapped Message payload —
197
- // operators may strip the SNS layer at their LB / handler.
198
- var msg = p;
199
- if (p.Type === "Notification" && typeof p.Message === "string") {
200
- try { msg = safeJson.parse(p.Message); }
201
- catch (e) {
202
- throw _err("ses/bad-message-json",
203
- "SES SNS Message field is not valid JSON: " + (e && e.message));
204
- }
205
- }
206
- var notificationType = msg.notificationType || msg.eventType;
207
- if (!notificationType) {
208
- throw _err("ses/missing-notification-type",
209
- "SES payload missing notificationType / eventType");
210
- }
211
- var mailMeta = msg.mail || {};
212
- var messageId = (typeof mailMeta.messageId === "string") ? mailMeta.messageId : null;
213
-
214
- if (notificationType === "Bounce" || notificationType === "bounce") {
215
- var b = msg.bounce || {};
216
- var recip = (b.bouncedRecipients && b.bouncedRecipients[0]) || {};
217
- var subType = b.bounceType === "Permanent" ? "hard"
218
- : b.bounceType === "Transient" ? "soft"
219
- : "unknown";
220
- return {
221
- vendor: "ses",
222
- type: "bounce",
223
- subType: subType,
224
- recipient: recip.emailAddress || (mailMeta.destination && mailMeta.destination[0]) || null,
225
- messageId: messageId,
226
- reason: recip.diagnosticCode || (b.bounceSubType ? "bounceSubType: " + b.bounceSubType : null),
227
- timestamp: b.timestamp || new Date().toISOString(),
228
- raw: p,
229
- };
230
- }
231
- if (notificationType === "Complaint" || notificationType === "complaint") {
232
- var c = msg.complaint || {};
233
- var crecip = (c.complainedRecipients && c.complainedRecipients[0]) || {};
234
- return {
235
- vendor: "ses",
236
- type: "complaint",
237
- subType: c.complaintFeedbackType || "abuse",
238
- recipient: crecip.emailAddress || (mailMeta.destination && mailMeta.destination[0]) || null,
239
- messageId: messageId,
240
- reason: c.userAgent || null,
241
- timestamp: c.timestamp || new Date().toISOString(),
242
- raw: p,
243
- };
244
- }
245
- if (notificationType === "Delivery" || notificationType === "delivery") {
246
- var d = msg.delivery || {};
247
- return {
248
- vendor: "ses",
249
- type: "delivery",
250
- subType: null,
251
- recipient: (d.recipients && d.recipients[0]) || (mailMeta.destination && mailMeta.destination[0]) || null,
252
- messageId: messageId,
253
- reason: null,
254
- timestamp: d.timestamp || new Date().toISOString(),
255
- raw: p,
256
- };
257
- }
258
- throw _err("ses/unknown-notification-type",
259
- "SES notificationType '" + String(notificationType) + "' not recognised");
260
- }
261
-
262
- // ---- Resend ----
263
- //
264
- // Webhook payload (JSON):
265
- // {
266
- // "type": "email.bounced" | "email.complained" | "email.delivered" | ...,
267
- // "created_at": "2026-04-28T...",
268
- // "data": {
269
- // "id": "...",
270
- // "to": ["user@example.com"] | "user@example.com",
271
- // "from": "...",
272
- // "bounce": { "type": "Permanent", "subType": "General",
273
- // "message": "..." } (bounced events only)
274
- // }
275
- // }
276
-
277
- function _parseResend(p) {
278
- if (!p || typeof p !== "object") {
279
- throw _err("resend/empty", "resend payload must be an object");
280
- }
281
- var type = p.type;
282
- if (typeof type !== "string") {
283
- throw _err("resend/missing-type", "resend payload missing 'type'");
284
- }
285
- var data = p.data || {};
286
- var to = Array.isArray(data.to) ? data.to[0] : data.to;
287
- var messageId = (typeof data.id === "string") ? data.id : null;
288
- var ts = p.created_at || new Date().toISOString();
289
-
290
- if (type === "email.bounced") {
291
- var bounce = data.bounce || {};
292
- var subType = bounce.type === "Permanent" ? "hard"
293
- : bounce.type === "Transient" ? "soft"
294
- : "unknown";
295
- return {
296
- vendor: "resend",
297
- type: "bounce",
298
- subType: subType,
299
- recipient: to || null,
300
- messageId: messageId,
301
- reason: bounce.message || null,
302
- timestamp: ts,
303
- raw: p,
304
- };
305
- }
306
- if (type === "email.complained") {
307
- return {
308
- vendor: "resend",
309
- type: "complaint",
310
- subType: "abuse",
311
- recipient: to || null,
312
- messageId: messageId,
313
- reason: null,
314
- timestamp: ts,
315
- raw: p,
316
- };
317
- }
318
- if (type === "email.delivered") {
319
- return {
320
- vendor: "resend",
321
- type: "delivery",
322
- subType: null,
323
- recipient: to || null,
324
- messageId: messageId,
325
- reason: null,
326
- timestamp: ts,
327
- raw: p,
328
- };
329
- }
330
- throw _err("resend/unknown-type",
331
- "resend type '" + type + "' not recognised");
332
- }
333
-
334
- // ---- Custom parser hook ----
335
- //
336
- // Operators with bespoke vendor inflow (DSN, vendor-X, internal MTA)
337
- // supply a function that takes the parsed body and returns the
338
- // normalized event shape. The framework runs the function then
339
- // validates the returned shape so a misbehaving custom parser can't
340
- // emit malformed audit rows.
341
- function _customParser(parser) {
342
- return function (payload) {
343
- var event = parser(payload);
344
- _validateNormalized(event);
345
- return event;
346
- };
347
- }
348
-
349
- function _validateNormalized(event) {
350
- if (!event || typeof event !== "object") {
351
- throw _err("custom/bad-shape", "parser returned non-object");
352
- }
353
- if (typeof event.vendor !== "string") {
354
- throw _err("custom/missing-vendor", "parser result missing 'vendor'");
355
- }
356
- if (["bounce", "complaint", "delivery"].indexOf(event.type) === -1) {
357
- throw _err("custom/bad-type",
358
- "parser result.type must be 'bounce' | 'complaint' | 'delivery'");
359
- }
360
- if (typeof event.recipient !== "string" || event.recipient.length === 0) {
361
- throw _err("custom/missing-recipient", "parser result missing 'recipient'");
362
- }
363
- }
364
-
365
- var VENDORS = {
366
- postmark: _parsePostmark,
367
- ses: _parseSes,
368
- resend: _parseResend,
369
- };
370
-
371
- function parse(payload, opts) {
372
- opts = opts || {};
373
- if (typeof opts.parser === "function") {
374
- return _customParser(opts.parser)(payload);
375
- }
376
- var vendor = opts.vendor;
377
- if (typeof vendor !== "string" || vendor.length === 0) {
378
- throw _err("missing-vendor",
379
- "mailBounce.parse requires { vendor } (one of 'postmark', 'ses', 'resend') or { parser }");
380
- }
381
- var fn = VENDORS[vendor];
382
- if (!fn) {
383
- throw _err("unknown-vendor",
384
- "mailBounce.parse: unknown vendor '" + vendor +
385
- "' (built-ins: postmark, ses, resend; supply { parser } for others)");
386
- }
387
- return fn(payload);
388
- }
389
-
390
- // ---- Webhook handler middleware ----
391
- //
392
- // Buffers the request body (JSON), runs verify() if supplied, parses
393
- // via the configured vendor / custom parser, emits the audit event,
394
- // invokes onBounce, and responds 200. Errors map to 400 (bad payload),
395
- // 401 (verify rejected), 413 (body too large), 500 (onBounce threw).
396
- function handler(opts) {
397
- opts = opts || {};
398
- var vendor = opts.vendor;
399
- var customParser = typeof opts.parser === "function" ? opts.parser : null;
400
- if (!customParser && (typeof vendor !== "string" || !VENDORS[vendor])) {
401
- throw _err("handler/bad-config",
402
- "mailBounce.handler requires { vendor } (one of " +
403
- Object.keys(VENDORS).join(", ") + ") or { parser }");
404
- }
405
- var verify = typeof opts.verify === "function" ? opts.verify : null;
406
- var onBounce = typeof opts.onBounce === "function" ? opts.onBounce : null;
407
- var auditOn = opts.audit !== false;
408
- // maxBytes must be a positive finite integer (Infinity / NaN /
409
- // negative / non-integer all bypass the body cap). See
410
- // lib/numeric-bounds for the rationale shared with every other
411
- // numeric-opt site swept in v0.6.69.
412
- var maxBytes;
413
- if (opts.maxBytes === undefined) {
414
- maxBytes = MAX_BODY_BYTES;
415
- } else if (!numericBounds.isPositiveFiniteInt(opts.maxBytes)) {
416
- throw new MailBounceError("mail-bounce/bad-opt",
417
- "mailBounce.handler: opts.maxBytes must be a positive finite " +
418
- "integer; got " + numericBounds.shape(opts.maxBytes), true);
419
- } else {
420
- maxBytes = opts.maxBytes;
421
- }
422
-
423
- function _emit(event) {
424
- if (!auditOn) return;
425
- audit().safeEmit({
426
- action: "system.mail.bounce",
427
- outcome: event.type === "delivery" ? "success" : "denied",
428
- metadata: {
429
- vendor: event.vendor,
430
- type: event.type,
431
- subType: event.subType,
432
- recipient: event.recipient,
433
- messageId: event.messageId,
434
- reason: event.reason,
435
- timestamp: event.timestamp,
436
- },
437
- });
438
- }
439
-
440
- function _send(res, status, body) {
441
- if (typeof res.writeHead === "function") {
442
- res.writeHead(status, { "Content-Type": "application/json" });
443
- res.end(JSON.stringify(body));
444
- }
445
- }
446
-
447
- return function mailBounceMiddleware(req, res) {
448
- var collector = safeBuffer.boundedChunkCollector({
449
- maxBytes: maxBytes,
450
- errorClass: MailBounceError,
451
- sizeCode: "mailBounce/too-large",
452
- sizeMessage: "payload exceeds maxBytes",
453
- });
454
- var aborted = false;
455
-
456
- req.on("data", function (chunk) {
457
- if (aborted) return;
458
- try { collector.push(chunk); }
459
- catch (_e) {
460
- aborted = true;
461
- return _send(res, HTTP.PAYLOAD_TOO_LARGE, { error: "payload too large" });
462
- }
463
- });
464
-
465
- req.on("end", function () {
466
- if (aborted) return;
467
- var raw = collector.result();
468
- var body;
469
- try { body = safeJson.parse(raw, { maxBytes: maxBytes }); }
470
- catch (e) {
471
- return _send(res, HTTP.BAD_REQUEST, { error: "invalid JSON: " + e.message });
472
- }
473
-
474
- // Verification hook — operator decides what counts as authentic.
475
- // Common shapes: HMAC of body against a shared secret, Basic
476
- // Auth header, SNS Signature verification, X-Webhook-Signature
477
- // svix header. The hook receives the request + the parsed body
478
- // so it can sign over either form.
479
- if (verify) {
480
- var ok;
481
- try { ok = verify(req, body, raw); }
482
- catch { return _send(res, HTTP.UNAUTHORIZED, { error: "verification error" }); }
483
- if (!ok) return _send(res, HTTP.UNAUTHORIZED, { error: "verification failed" });
484
- }
485
-
486
- var event;
487
- try {
488
- event = customParser ? _customParser(customParser)(body) : VENDORS[vendor](body);
489
- } catch (e) {
490
- return _send(res, HTTP.BAD_REQUEST, {
491
- error: e.message || "parse failed",
492
- code: e.code || "parse-failed",
493
- });
494
- }
495
-
496
- _emit(event);
497
-
498
- if (!onBounce) return _send(res, HTTP.OK, { ok: true });
499
-
500
- Promise.resolve()
501
- .then(function () { return onBounce(event); })
502
- .then(function () { _send(res, HTTP.OK, { ok: true }); },
503
- function (e) {
504
- _send(res, HTTP.INTERNAL_SERVER_ERROR, {
505
- error: "onBounce threw: " + (e && e.message),
506
- });
507
- });
508
- });
509
-
510
- req.on("error", function () {
511
- if (!aborted) _send(res, HTTP.BAD_REQUEST, { error: "request error" });
512
- });
513
- };
514
- }
515
-
516
- module.exports = {
517
- parse: parse,
518
- handler: handler,
519
- MailBounceError: MailBounceError,
520
- // Vendor parsers exposed for tests + advanced operator wiring (e.g.
521
- // operators who want to call _parsePostmark inside a custom verify
522
- // step before deciding whether to accept the webhook).
523
- vendors: {
524
- postmark: _parsePostmark,
525
- ses: _parseSes,
526
- resend: _parseResend,
527
- },
528
- };
1
+ "use strict";
2
+ /**
3
+ * mail-bounce — vendor-shaped intake for outbound-mail bounces /
4
+ * complaints / delivery callbacks.
5
+ *
6
+ * Outbound mail can come back as:
7
+ * - a hard or soft bounce (delivery failure)
8
+ * - a spam / abuse complaint
9
+ * - a delivered confirmation
10
+ * - a list-unsubscribe complaint
11
+ *
12
+ * Vendors (Postmark, SES via SNS, Resend) ship these as HTTP webhooks
13
+ * with payload shapes that all carry the same information dressed up
14
+ * differently. This module owns the translation: each vendor parser
15
+ * normalizes its payload into one shape so operators don't write
16
+ * vendor-specific reconciliation code per environment.
17
+ *
18
+ * Public API:
19
+ *
20
+ * mailBounce.parse(payload, { vendor })
21
+ * Pure synchronous parser. Returns the normalized event:
22
+ * {
23
+ * vendor: "postmark" | "ses" | "resend",
24
+ * type: "bounce" | "complaint" | "delivery",
25
+ * subType: "hard" | "soft" | "abuse" | ... | null,
26
+ * recipient: "user@example.com",
27
+ * messageId: "<framework-emitted Message-ID>" | null,
28
+ * reason: "smtp 550 ..." | null,
29
+ * timestamp: "2026-04-28T..." (ISO 8601),
30
+ * raw: <input payload, untouched>,
31
+ * }
32
+ *
33
+ * mailBounce.handler({ vendor, verify?, onBounce?, audit?, ... })
34
+ * Returns an Express-style middleware (req, res). Buffers + parses
35
+ * the request body, calls verify(req, body) if supplied, runs the
36
+ * parser, emits system.mail.bounce, calls onBounce(event), and
37
+ * responds 200. Validation errors land as 400 with a JSON error.
38
+ * Verification failures land as 401.
39
+ *
40
+ * Operator example (Postmark):
41
+ *
42
+ * var bounce = b.mailBounce.handler({
43
+ * vendor: "postmark",
44
+ * verify: function (req) {
45
+ * // Postmark recommends Basic Auth on the webhook URL.
46
+ * return req.headers.authorization === expectedBasic;
47
+ * },
48
+ * onBounce: function (event) {
49
+ * // Mark the recipient as bounced in your data store.
50
+ * return repo.users.markBounced(event.recipient, event.subType);
51
+ * },
52
+ * });
53
+ * r.post("/webhooks/postmark", bounce);
54
+ *
55
+ * Audit: every parsed bounce/complaint/delivery emits one
56
+ * `system.mail.bounce` row carrying the normalized fields. Audit is on
57
+ * by default and disabled per-instance via { audit: false }.
58
+ *
59
+ * Generic DSN (RFC 3464 multipart/report) is intentionally NOT included
60
+ * as a built-in vendor: parsing arbitrary email-back-from-MTA reports
61
+ * needs a full email parser, which the framework does not vendor for
62
+ * this surface. Operators with raw DSN inflow plug a custom parser via
63
+ * the { vendor: 'custom', parser } shape (see _customParser below).
64
+ */
65
+
66
+ var lazyRequire = require("./lazy-require");
67
+ var numericBounds = require("./numeric-bounds");
68
+ var audit = lazyRequire(function () { return require("./audit"); });
69
+ var safeBuffer = require("./safe-buffer");
70
+ var safeJson = require("./safe-json");
71
+ var C = require("./constants");
72
+ var requestHelpers = require("./request-helpers");
73
+ var { defineClass } = require("./framework-error");
74
+
75
+ var HTTP = requestHelpers.HTTP_STATUS;
76
+
77
+ var MailBounceError = defineClass("MailBounceError", { withStatusCode: true });
78
+
79
+ // Cap on inbound webhook bodies — any vendor bigger than this is
80
+ // pathological and likely an attack surface. 256 KiB covers the
81
+ // largest realistic SES SNS notification with verbose diagnostic info.
82
+ var MAX_BODY_BYTES = C.BYTES.kib(256);
83
+
84
+ function _err(code, message, statusCode) {
85
+ return new MailBounceError(code, message, true, statusCode || 400);
86
+ }
87
+
88
+ // ---- Postmark ----
89
+ //
90
+ // Webhook payload (JSON):
91
+ // {
92
+ // "RecordType": "Bounce" | "SpamComplaint" | "Delivery",
93
+ // "Type": "HardBounce" | "SoftBounce" | "Transient" | ...,
94
+ // "Email": "...",
95
+ // "MessageID": "...",
96
+ // "Description": "...",
97
+ // "Details": "...",
98
+ // "BouncedAt": "2026-04-28T..." (Bounce / SpamComplaint)
99
+ // "DeliveredAt": "..." (Delivery)
100
+ // }
101
+
102
+ var POSTMARK_TYPE_TO_NORMAL = {
103
+ "HardBounce": { type: "bounce", subType: "hard" },
104
+ "SoftBounce": { type: "bounce", subType: "soft" },
105
+ "Transient": { type: "bounce", subType: "soft" },
106
+ "Unknown": { type: "bounce", subType: "unknown" },
107
+ "Subscribe": { type: "complaint", subType: "subscribe-fail" },
108
+ "AutoResponder": { type: "bounce", subType: "auto-reply" },
109
+ "AddressChange": { type: "bounce", subType: "address-change" },
110
+ "DnsError": { type: "bounce", subType: "soft" },
111
+ "SpamNotification": { type: "complaint", subType: "spam" },
112
+ "OpenRelayTest": { type: "bounce", subType: "policy" },
113
+ "Unsubscribe": { type: "complaint", subType: "unsubscribe" },
114
+ "Blocked": { type: "bounce", subType: "blocked" },
115
+ "SMTPApiError": { type: "bounce", subType: "api" },
116
+ "InboundError": { type: "bounce", subType: "inbound" },
117
+ "DMARCPolicy": { type: "bounce", subType: "policy" },
118
+ "TemplateRenderingFailed": { type: "bounce", subType: "template" },
119
+ "ManuallyDeactivated": { type: "bounce", subType: "deactivated" },
120
+ };
121
+
122
+ function _parsePostmark(p) {
123
+ if (!p || typeof p !== "object") {
124
+ throw _err("postmark/empty", "postmark webhook payload must be an object");
125
+ }
126
+ var record = p.RecordType;
127
+ var email = p.Email;
128
+ if (typeof email !== "string" || email.length === 0) {
129
+ throw _err("postmark/missing-email", "postmark payload missing 'Email'");
130
+ }
131
+
132
+ if (record === "Delivery") {
133
+ return {
134
+ vendor: "postmark",
135
+ type: "delivery",
136
+ subType: null,
137
+ recipient: email,
138
+ messageId: typeof p.MessageID === "string" ? p.MessageID : null,
139
+ reason: null,
140
+ timestamp: p.DeliveredAt || new Date().toISOString(),
141
+ raw: p,
142
+ };
143
+ }
144
+ if (record === "SpamComplaint") {
145
+ return {
146
+ vendor: "postmark",
147
+ type: "complaint",
148
+ subType: "spam",
149
+ recipient: email,
150
+ messageId: typeof p.MessageID === "string" ? p.MessageID : null,
151
+ reason: p.Details || p.Description || null,
152
+ timestamp: p.BouncedAt || new Date().toISOString(),
153
+ raw: p,
154
+ };
155
+ }
156
+ if (record === "Bounce" || record === "SubscriptionChange" || !record) {
157
+ var mapping = POSTMARK_TYPE_TO_NORMAL[p.Type] ||
158
+ { type: "bounce", subType: typeof p.Type === "string" ? p.Type.toLowerCase() : "unknown" };
159
+ return {
160
+ vendor: "postmark",
161
+ type: mapping.type,
162
+ subType: mapping.subType,
163
+ recipient: email,
164
+ messageId: typeof p.MessageID === "string" ? p.MessageID : null,
165
+ reason: p.Details || p.Description || null,
166
+ timestamp: p.BouncedAt || p.DeliveredAt || new Date().toISOString(),
167
+ raw: p,
168
+ };
169
+ }
170
+ throw _err("postmark/unknown-record",
171
+ "postmark RecordType '" + String(record) + "' not recognised");
172
+ }
173
+
174
+ // ---- SES via SNS ----
175
+ //
176
+ // Outer envelope (SNS notification):
177
+ // { "Type": "Notification", "MessageId": "...",
178
+ // "Message": "<json string>", "Signature": "...", ... }
179
+ //
180
+ // After JSON.parse(Message):
181
+ // { "notificationType": "Bounce" | "Complaint" | "Delivery",
182
+ // "mail": { "messageId": "...", "destination": ["..."], ... },
183
+ // "bounce": { "bounceType": "Permanent" | "Transient" | "Undetermined",
184
+ // "bounceSubType": "General" | ...,
185
+ // "bouncedRecipients": [
186
+ // { "emailAddress": "...", "diagnosticCode": "...",
187
+ // "action": "...", "status": "..." }
188
+ // ],
189
+ // "timestamp": "..." },
190
+ // "complaint": { ... }, "delivery": { ... } }
191
+
192
+ function _parseSes(p) {
193
+ if (!p || typeof p !== "object") {
194
+ throw _err("ses/empty", "SES payload must be an object");
195
+ }
196
+ // Accept either the SNS envelope or the unwrapped Message payload —
197
+ // operators may strip the SNS layer at their LB / handler.
198
+ var msg = p;
199
+ if (p.Type === "Notification" && typeof p.Message === "string") {
200
+ try { msg = safeJson.parse(p.Message); }
201
+ catch (e) {
202
+ throw _err("ses/bad-message-json",
203
+ "SES SNS Message field is not valid JSON: " + (e && e.message));
204
+ }
205
+ }
206
+ var notificationType = msg.notificationType || msg.eventType;
207
+ if (!notificationType) {
208
+ throw _err("ses/missing-notification-type",
209
+ "SES payload missing notificationType / eventType");
210
+ }
211
+ var mailMeta = msg.mail || {};
212
+ var messageId = (typeof mailMeta.messageId === "string") ? mailMeta.messageId : null;
213
+
214
+ if (notificationType === "Bounce" || notificationType === "bounce") {
215
+ var b = msg.bounce || {};
216
+ var recip = (b.bouncedRecipients && b.bouncedRecipients[0]) || {};
217
+ var subType = b.bounceType === "Permanent" ? "hard"
218
+ : b.bounceType === "Transient" ? "soft"
219
+ : "unknown";
220
+ return {
221
+ vendor: "ses",
222
+ type: "bounce",
223
+ subType: subType,
224
+ recipient: recip.emailAddress || (mailMeta.destination && mailMeta.destination[0]) || null,
225
+ messageId: messageId,
226
+ reason: recip.diagnosticCode || (b.bounceSubType ? "bounceSubType: " + b.bounceSubType : null),
227
+ timestamp: b.timestamp || new Date().toISOString(),
228
+ raw: p,
229
+ };
230
+ }
231
+ if (notificationType === "Complaint" || notificationType === "complaint") {
232
+ var c = msg.complaint || {};
233
+ var crecip = (c.complainedRecipients && c.complainedRecipients[0]) || {};
234
+ return {
235
+ vendor: "ses",
236
+ type: "complaint",
237
+ subType: c.complaintFeedbackType || "abuse",
238
+ recipient: crecip.emailAddress || (mailMeta.destination && mailMeta.destination[0]) || null,
239
+ messageId: messageId,
240
+ reason: c.userAgent || null,
241
+ timestamp: c.timestamp || new Date().toISOString(),
242
+ raw: p,
243
+ };
244
+ }
245
+ if (notificationType === "Delivery" || notificationType === "delivery") {
246
+ var d = msg.delivery || {};
247
+ return {
248
+ vendor: "ses",
249
+ type: "delivery",
250
+ subType: null,
251
+ recipient: (d.recipients && d.recipients[0]) || (mailMeta.destination && mailMeta.destination[0]) || null,
252
+ messageId: messageId,
253
+ reason: null,
254
+ timestamp: d.timestamp || new Date().toISOString(),
255
+ raw: p,
256
+ };
257
+ }
258
+ throw _err("ses/unknown-notification-type",
259
+ "SES notificationType '" + String(notificationType) + "' not recognised");
260
+ }
261
+
262
+ // ---- Resend ----
263
+ //
264
+ // Webhook payload (JSON):
265
+ // {
266
+ // "type": "email.bounced" | "email.complained" | "email.delivered" | ...,
267
+ // "created_at": "2026-04-28T...",
268
+ // "data": {
269
+ // "id": "...",
270
+ // "to": ["user@example.com"] | "user@example.com",
271
+ // "from": "...",
272
+ // "bounce": { "type": "Permanent", "subType": "General",
273
+ // "message": "..." } (bounced events only)
274
+ // }
275
+ // }
276
+
277
+ function _parseResend(p) {
278
+ if (!p || typeof p !== "object") {
279
+ throw _err("resend/empty", "resend payload must be an object");
280
+ }
281
+ var type = p.type;
282
+ if (typeof type !== "string") {
283
+ throw _err("resend/missing-type", "resend payload missing 'type'");
284
+ }
285
+ var data = p.data || {};
286
+ var to = Array.isArray(data.to) ? data.to[0] : data.to;
287
+ var messageId = (typeof data.id === "string") ? data.id : null;
288
+ var ts = p.created_at || new Date().toISOString();
289
+
290
+ if (type === "email.bounced") {
291
+ var bounce = data.bounce || {};
292
+ var subType = bounce.type === "Permanent" ? "hard"
293
+ : bounce.type === "Transient" ? "soft"
294
+ : "unknown";
295
+ return {
296
+ vendor: "resend",
297
+ type: "bounce",
298
+ subType: subType,
299
+ recipient: to || null,
300
+ messageId: messageId,
301
+ reason: bounce.message || null,
302
+ timestamp: ts,
303
+ raw: p,
304
+ };
305
+ }
306
+ if (type === "email.complained") {
307
+ return {
308
+ vendor: "resend",
309
+ type: "complaint",
310
+ subType: "abuse",
311
+ recipient: to || null,
312
+ messageId: messageId,
313
+ reason: null,
314
+ timestamp: ts,
315
+ raw: p,
316
+ };
317
+ }
318
+ if (type === "email.delivered") {
319
+ return {
320
+ vendor: "resend",
321
+ type: "delivery",
322
+ subType: null,
323
+ recipient: to || null,
324
+ messageId: messageId,
325
+ reason: null,
326
+ timestamp: ts,
327
+ raw: p,
328
+ };
329
+ }
330
+ throw _err("resend/unknown-type",
331
+ "resend type '" + type + "' not recognised");
332
+ }
333
+
334
+ // ---- Custom parser hook ----
335
+ //
336
+ // Operators with bespoke vendor inflow (DSN, vendor-X, internal MTA)
337
+ // supply a function that takes the parsed body and returns the
338
+ // normalized event shape. The framework runs the function then
339
+ // validates the returned shape so a misbehaving custom parser can't
340
+ // emit malformed audit rows.
341
+ function _customParser(parser) {
342
+ return function (payload) {
343
+ var event = parser(payload);
344
+ _validateNormalized(event);
345
+ return event;
346
+ };
347
+ }
348
+
349
+ function _validateNormalized(event) {
350
+ if (!event || typeof event !== "object") {
351
+ throw _err("custom/bad-shape", "parser returned non-object");
352
+ }
353
+ if (typeof event.vendor !== "string") {
354
+ throw _err("custom/missing-vendor", "parser result missing 'vendor'");
355
+ }
356
+ if (["bounce", "complaint", "delivery"].indexOf(event.type) === -1) {
357
+ throw _err("custom/bad-type",
358
+ "parser result.type must be 'bounce' | 'complaint' | 'delivery'");
359
+ }
360
+ if (typeof event.recipient !== "string" || event.recipient.length === 0) {
361
+ throw _err("custom/missing-recipient", "parser result missing 'recipient'");
362
+ }
363
+ }
364
+
365
+ var VENDORS = {
366
+ postmark: _parsePostmark,
367
+ ses: _parseSes,
368
+ resend: _parseResend,
369
+ };
370
+
371
+ function parse(payload, opts) {
372
+ opts = opts || {};
373
+ if (typeof opts.parser === "function") {
374
+ return _customParser(opts.parser)(payload);
375
+ }
376
+ var vendor = opts.vendor;
377
+ if (typeof vendor !== "string" || vendor.length === 0) {
378
+ throw _err("missing-vendor",
379
+ "mailBounce.parse requires { vendor } (one of 'postmark', 'ses', 'resend') or { parser }");
380
+ }
381
+ var fn = VENDORS[vendor];
382
+ if (!fn) {
383
+ throw _err("unknown-vendor",
384
+ "mailBounce.parse: unknown vendor '" + vendor +
385
+ "' (built-ins: postmark, ses, resend; supply { parser } for others)");
386
+ }
387
+ return fn(payload);
388
+ }
389
+
390
+ // ---- Webhook handler middleware ----
391
+ //
392
+ // Buffers the request body (JSON), runs verify() if supplied, parses
393
+ // via the configured vendor / custom parser, emits the audit event,
394
+ // invokes onBounce, and responds 200. Errors map to 400 (bad payload),
395
+ // 401 (verify rejected), 413 (body too large), 500 (onBounce threw).
396
+ function handler(opts) {
397
+ opts = opts || {};
398
+ var vendor = opts.vendor;
399
+ var customParser = typeof opts.parser === "function" ? opts.parser : null;
400
+ if (!customParser && (typeof vendor !== "string" || !VENDORS[vendor])) {
401
+ throw _err("handler/bad-config",
402
+ "mailBounce.handler requires { vendor } (one of " +
403
+ Object.keys(VENDORS).join(", ") + ") or { parser }");
404
+ }
405
+ var verify = typeof opts.verify === "function" ? opts.verify : null;
406
+ var onBounce = typeof opts.onBounce === "function" ? opts.onBounce : null;
407
+ var auditOn = opts.audit !== false;
408
+ // maxBytes must be a positive finite integer (Infinity / NaN /
409
+ // negative / non-integer all bypass the body cap). See
410
+ // lib/numeric-bounds for the rationale shared with every other
411
+ // numeric-opt site swept in v0.6.69.
412
+ var maxBytes;
413
+ if (opts.maxBytes === undefined) {
414
+ maxBytes = MAX_BODY_BYTES;
415
+ } else if (!numericBounds.isPositiveFiniteInt(opts.maxBytes)) {
416
+ throw new MailBounceError("mail-bounce/bad-opt",
417
+ "mailBounce.handler: opts.maxBytes must be a positive finite " +
418
+ "integer; got " + numericBounds.shape(opts.maxBytes), true);
419
+ } else {
420
+ maxBytes = opts.maxBytes;
421
+ }
422
+
423
+ function _emit(event) {
424
+ if (!auditOn) return;
425
+ audit().safeEmit({
426
+ action: "system.mail.bounce",
427
+ outcome: event.type === "delivery" ? "success" : "denied",
428
+ metadata: {
429
+ vendor: event.vendor,
430
+ type: event.type,
431
+ subType: event.subType,
432
+ recipient: event.recipient,
433
+ messageId: event.messageId,
434
+ reason: event.reason,
435
+ timestamp: event.timestamp,
436
+ },
437
+ });
438
+ }
439
+
440
+ function _send(res, status, body) {
441
+ if (typeof res.writeHead === "function") {
442
+ res.writeHead(status, { "Content-Type": "application/json" });
443
+ res.end(JSON.stringify(body));
444
+ }
445
+ }
446
+
447
+ return function mailBounceMiddleware(req, res) {
448
+ var collector = safeBuffer.boundedChunkCollector({
449
+ maxBytes: maxBytes,
450
+ errorClass: MailBounceError,
451
+ sizeCode: "mailBounce/too-large",
452
+ sizeMessage: "payload exceeds maxBytes",
453
+ });
454
+ var aborted = false;
455
+
456
+ req.on("data", function (chunk) {
457
+ if (aborted) return;
458
+ try { collector.push(chunk); }
459
+ catch (_e) {
460
+ aborted = true;
461
+ return _send(res, HTTP.PAYLOAD_TOO_LARGE, { error: "payload too large" });
462
+ }
463
+ });
464
+
465
+ req.on("end", function () {
466
+ if (aborted) return;
467
+ var raw = collector.result();
468
+ var body;
469
+ try { body = safeJson.parse(raw, { maxBytes: maxBytes }); }
470
+ catch (e) {
471
+ return _send(res, HTTP.BAD_REQUEST, { error: "invalid JSON: " + e.message });
472
+ }
473
+
474
+ // Verification hook — operator decides what counts as authentic.
475
+ // Common shapes: HMAC of body against a shared secret, Basic
476
+ // Auth header, SNS Signature verification, X-Webhook-Signature
477
+ // svix header. The hook receives the request + the parsed body
478
+ // so it can sign over either form.
479
+ if (verify) {
480
+ var ok;
481
+ try { ok = verify(req, body, raw); }
482
+ catch { return _send(res, HTTP.UNAUTHORIZED, { error: "verification error" }); }
483
+ if (!ok) return _send(res, HTTP.UNAUTHORIZED, { error: "verification failed" });
484
+ }
485
+
486
+ var event;
487
+ try {
488
+ event = customParser ? _customParser(customParser)(body) : VENDORS[vendor](body);
489
+ } catch (e) {
490
+ return _send(res, HTTP.BAD_REQUEST, {
491
+ error: e.message || "parse failed",
492
+ code: e.code || "parse-failed",
493
+ });
494
+ }
495
+
496
+ _emit(event);
497
+
498
+ if (!onBounce) return _send(res, HTTP.OK, { ok: true });
499
+
500
+ Promise.resolve()
501
+ .then(function () { return onBounce(event); })
502
+ .then(function () { _send(res, HTTP.OK, { ok: true }); },
503
+ function (e) {
504
+ _send(res, HTTP.INTERNAL_SERVER_ERROR, {
505
+ error: "onBounce threw: " + (e && e.message),
506
+ });
507
+ });
508
+ });
509
+
510
+ req.on("error", function () {
511
+ if (!aborted) _send(res, HTTP.BAD_REQUEST, { error: "request error" });
512
+ });
513
+ };
514
+ }
515
+
516
+ module.exports = {
517
+ parse: parse,
518
+ handler: handler,
519
+ MailBounceError: MailBounceError,
520
+ // Vendor parsers exposed for tests + advanced operator wiring (e.g.
521
+ // operators who want to call _parsePostmark inside a custom verify
522
+ // step before deciding whether to accept the webhook).
523
+ vendors: {
524
+ postmark: _parsePostmark,
525
+ ses: _parseSes,
526
+ resend: _parseResend,
527
+ },
528
+ };