@blamejs/core 0.4.1

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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
@@ -0,0 +1,507 @@
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 audit = lazyRequire(function () { return require("./audit"); });
68
+ var safeJson = require("./safe-json");
69
+ var C = require("./constants");
70
+ var { defineClass } = require("./framework-error");
71
+
72
+ var MailBounceError = defineClass("MailBounceError", { withStatusCode: true });
73
+
74
+ // Cap on inbound webhook bodies — any vendor bigger than this is
75
+ // pathological and likely an attack surface. 256 KiB covers the
76
+ // largest realistic SES SNS notification with verbose diagnostic info.
77
+ var MAX_BODY_BYTES = C.BYTES.kib(256);
78
+
79
+ function _err(code, message, statusCode) {
80
+ return new MailBounceError(code, message, true, statusCode || 400);
81
+ }
82
+
83
+ // ---- Postmark ----
84
+ //
85
+ // Webhook payload (JSON):
86
+ // {
87
+ // "RecordType": "Bounce" | "SpamComplaint" | "Delivery",
88
+ // "Type": "HardBounce" | "SoftBounce" | "Transient" | ...,
89
+ // "Email": "...",
90
+ // "MessageID": "...",
91
+ // "Description": "...",
92
+ // "Details": "...",
93
+ // "BouncedAt": "2026-04-28T..." (Bounce / SpamComplaint)
94
+ // "DeliveredAt": "..." (Delivery)
95
+ // }
96
+
97
+ var POSTMARK_TYPE_TO_NORMAL = {
98
+ "HardBounce": { type: "bounce", subType: "hard" },
99
+ "SoftBounce": { type: "bounce", subType: "soft" },
100
+ "Transient": { type: "bounce", subType: "soft" },
101
+ "Unknown": { type: "bounce", subType: "unknown" },
102
+ "Subscribe": { type: "complaint", subType: "subscribe-fail" },
103
+ "AutoResponder": { type: "bounce", subType: "auto-reply" },
104
+ "AddressChange": { type: "bounce", subType: "address-change" },
105
+ "DnsError": { type: "bounce", subType: "soft" },
106
+ "SpamNotification": { type: "complaint", subType: "spam" },
107
+ "OpenRelayTest": { type: "bounce", subType: "policy" },
108
+ "Unsubscribe": { type: "complaint", subType: "unsubscribe" },
109
+ "Blocked": { type: "bounce", subType: "blocked" },
110
+ "SMTPApiError": { type: "bounce", subType: "api" },
111
+ "InboundError": { type: "bounce", subType: "inbound" },
112
+ "DMARCPolicy": { type: "bounce", subType: "policy" },
113
+ "TemplateRenderingFailed": { type: "bounce", subType: "template" },
114
+ "ManuallyDeactivated": { type: "bounce", subType: "deactivated" },
115
+ };
116
+
117
+ function _parsePostmark(p) {
118
+ if (!p || typeof p !== "object") {
119
+ throw _err("postmark/empty", "postmark webhook payload must be an object");
120
+ }
121
+ var record = p.RecordType;
122
+ var email = p.Email;
123
+ if (typeof email !== "string" || email.length === 0) {
124
+ throw _err("postmark/missing-email", "postmark payload missing 'Email'");
125
+ }
126
+
127
+ if (record === "Delivery") {
128
+ return {
129
+ vendor: "postmark",
130
+ type: "delivery",
131
+ subType: null,
132
+ recipient: email,
133
+ messageId: typeof p.MessageID === "string" ? p.MessageID : null,
134
+ reason: null,
135
+ timestamp: p.DeliveredAt || new Date().toISOString(),
136
+ raw: p,
137
+ };
138
+ }
139
+ if (record === "SpamComplaint") {
140
+ return {
141
+ vendor: "postmark",
142
+ type: "complaint",
143
+ subType: "spam",
144
+ recipient: email,
145
+ messageId: typeof p.MessageID === "string" ? p.MessageID : null,
146
+ reason: p.Details || p.Description || null,
147
+ timestamp: p.BouncedAt || new Date().toISOString(),
148
+ raw: p,
149
+ };
150
+ }
151
+ if (record === "Bounce" || record === "SubscriptionChange" || !record) {
152
+ var mapping = POSTMARK_TYPE_TO_NORMAL[p.Type] ||
153
+ { type: "bounce", subType: typeof p.Type === "string" ? p.Type.toLowerCase() : "unknown" };
154
+ return {
155
+ vendor: "postmark",
156
+ type: mapping.type,
157
+ subType: mapping.subType,
158
+ recipient: email,
159
+ messageId: typeof p.MessageID === "string" ? p.MessageID : null,
160
+ reason: p.Details || p.Description || null,
161
+ timestamp: p.BouncedAt || p.DeliveredAt || new Date().toISOString(),
162
+ raw: p,
163
+ };
164
+ }
165
+ throw _err("postmark/unknown-record",
166
+ "postmark RecordType '" + String(record) + "' not recognised");
167
+ }
168
+
169
+ // ---- SES via SNS ----
170
+ //
171
+ // Outer envelope (SNS notification):
172
+ // { "Type": "Notification", "MessageId": "...",
173
+ // "Message": "<json string>", "Signature": "...", ... }
174
+ //
175
+ // After JSON.parse(Message):
176
+ // { "notificationType": "Bounce" | "Complaint" | "Delivery",
177
+ // "mail": { "messageId": "...", "destination": ["..."], ... },
178
+ // "bounce": { "bounceType": "Permanent" | "Transient" | "Undetermined",
179
+ // "bounceSubType": "General" | ...,
180
+ // "bouncedRecipients": [
181
+ // { "emailAddress": "...", "diagnosticCode": "...",
182
+ // "action": "...", "status": "..." }
183
+ // ],
184
+ // "timestamp": "..." },
185
+ // "complaint": { ... }, "delivery": { ... } }
186
+
187
+ function _parseSes(p) {
188
+ if (!p || typeof p !== "object") {
189
+ throw _err("ses/empty", "SES payload must be an object");
190
+ }
191
+ // Accept either the SNS envelope or the unwrapped Message payload —
192
+ // operators may strip the SNS layer at their LB / handler.
193
+ var msg = p;
194
+ if (p.Type === "Notification" && typeof p.Message === "string") {
195
+ try { msg = safeJson.parse(p.Message); }
196
+ catch (e) {
197
+ throw _err("ses/bad-message-json",
198
+ "SES SNS Message field is not valid JSON: " + (e && e.message));
199
+ }
200
+ }
201
+ var notificationType = msg.notificationType || msg.eventType;
202
+ if (!notificationType) {
203
+ throw _err("ses/missing-notification-type",
204
+ "SES payload missing notificationType / eventType");
205
+ }
206
+ var mailMeta = msg.mail || {};
207
+ var messageId = (typeof mailMeta.messageId === "string") ? mailMeta.messageId : null;
208
+
209
+ if (notificationType === "Bounce" || notificationType === "bounce") {
210
+ var b = msg.bounce || {};
211
+ var recip = (b.bouncedRecipients && b.bouncedRecipients[0]) || {};
212
+ var subType = b.bounceType === "Permanent" ? "hard"
213
+ : b.bounceType === "Transient" ? "soft"
214
+ : "unknown";
215
+ return {
216
+ vendor: "ses",
217
+ type: "bounce",
218
+ subType: subType,
219
+ recipient: recip.emailAddress || (mailMeta.destination && mailMeta.destination[0]) || null,
220
+ messageId: messageId,
221
+ reason: recip.diagnosticCode || (b.bounceSubType ? "bounceSubType: " + b.bounceSubType : null),
222
+ timestamp: b.timestamp || new Date().toISOString(),
223
+ raw: p,
224
+ };
225
+ }
226
+ if (notificationType === "Complaint" || notificationType === "complaint") {
227
+ var c = msg.complaint || {};
228
+ var crecip = (c.complainedRecipients && c.complainedRecipients[0]) || {};
229
+ return {
230
+ vendor: "ses",
231
+ type: "complaint",
232
+ subType: c.complaintFeedbackType || "abuse",
233
+ recipient: crecip.emailAddress || (mailMeta.destination && mailMeta.destination[0]) || null,
234
+ messageId: messageId,
235
+ reason: c.userAgent || null,
236
+ timestamp: c.timestamp || new Date().toISOString(),
237
+ raw: p,
238
+ };
239
+ }
240
+ if (notificationType === "Delivery" || notificationType === "delivery") {
241
+ var d = msg.delivery || {};
242
+ return {
243
+ vendor: "ses",
244
+ type: "delivery",
245
+ subType: null,
246
+ recipient: (d.recipients && d.recipients[0]) || (mailMeta.destination && mailMeta.destination[0]) || null,
247
+ messageId: messageId,
248
+ reason: null,
249
+ timestamp: d.timestamp || new Date().toISOString(),
250
+ raw: p,
251
+ };
252
+ }
253
+ throw _err("ses/unknown-notification-type",
254
+ "SES notificationType '" + String(notificationType) + "' not recognised");
255
+ }
256
+
257
+ // ---- Resend ----
258
+ //
259
+ // Webhook payload (JSON):
260
+ // {
261
+ // "type": "email.bounced" | "email.complained" | "email.delivered" | ...,
262
+ // "created_at": "2026-04-28T...",
263
+ // "data": {
264
+ // "id": "...",
265
+ // "to": ["user@example.com"] | "user@example.com",
266
+ // "from": "...",
267
+ // "bounce": { "type": "Permanent", "subType": "General",
268
+ // "message": "..." } (bounced events only)
269
+ // }
270
+ // }
271
+
272
+ function _parseResend(p) {
273
+ if (!p || typeof p !== "object") {
274
+ throw _err("resend/empty", "resend payload must be an object");
275
+ }
276
+ var type = p.type;
277
+ if (typeof type !== "string") {
278
+ throw _err("resend/missing-type", "resend payload missing 'type'");
279
+ }
280
+ var data = p.data || {};
281
+ var to = Array.isArray(data.to) ? data.to[0] : data.to;
282
+ var messageId = (typeof data.id === "string") ? data.id : null;
283
+ var ts = p.created_at || new Date().toISOString();
284
+
285
+ if (type === "email.bounced") {
286
+ var bounce = data.bounce || {};
287
+ var subType = bounce.type === "Permanent" ? "hard"
288
+ : bounce.type === "Transient" ? "soft"
289
+ : "unknown";
290
+ return {
291
+ vendor: "resend",
292
+ type: "bounce",
293
+ subType: subType,
294
+ recipient: to || null,
295
+ messageId: messageId,
296
+ reason: bounce.message || null,
297
+ timestamp: ts,
298
+ raw: p,
299
+ };
300
+ }
301
+ if (type === "email.complained") {
302
+ return {
303
+ vendor: "resend",
304
+ type: "complaint",
305
+ subType: "abuse",
306
+ recipient: to || null,
307
+ messageId: messageId,
308
+ reason: null,
309
+ timestamp: ts,
310
+ raw: p,
311
+ };
312
+ }
313
+ if (type === "email.delivered") {
314
+ return {
315
+ vendor: "resend",
316
+ type: "delivery",
317
+ subType: null,
318
+ recipient: to || null,
319
+ messageId: messageId,
320
+ reason: null,
321
+ timestamp: ts,
322
+ raw: p,
323
+ };
324
+ }
325
+ throw _err("resend/unknown-type",
326
+ "resend type '" + type + "' not recognised");
327
+ }
328
+
329
+ // ---- Custom parser hook ----
330
+ //
331
+ // Operators with bespoke vendor inflow (DSN, vendor-X, internal MTA)
332
+ // supply a function that takes the parsed body and returns the
333
+ // normalized event shape. The framework runs the function then
334
+ // validates the returned shape so a misbehaving custom parser can't
335
+ // emit malformed audit rows.
336
+ function _customParser(parser) {
337
+ return function (payload) {
338
+ var event = parser(payload);
339
+ _validateNormalized(event);
340
+ return event;
341
+ };
342
+ }
343
+
344
+ function _validateNormalized(event) {
345
+ if (!event || typeof event !== "object") {
346
+ throw _err("custom/bad-shape", "parser returned non-object");
347
+ }
348
+ if (typeof event.vendor !== "string") {
349
+ throw _err("custom/missing-vendor", "parser result missing 'vendor'");
350
+ }
351
+ if (["bounce", "complaint", "delivery"].indexOf(event.type) === -1) {
352
+ throw _err("custom/bad-type",
353
+ "parser result.type must be 'bounce' | 'complaint' | 'delivery'");
354
+ }
355
+ if (typeof event.recipient !== "string" || event.recipient.length === 0) {
356
+ throw _err("custom/missing-recipient", "parser result missing 'recipient'");
357
+ }
358
+ }
359
+
360
+ var VENDORS = {
361
+ postmark: _parsePostmark,
362
+ ses: _parseSes,
363
+ resend: _parseResend,
364
+ };
365
+
366
+ function parse(payload, opts) {
367
+ opts = opts || {};
368
+ if (typeof opts.parser === "function") {
369
+ return _customParser(opts.parser)(payload);
370
+ }
371
+ var vendor = opts.vendor;
372
+ if (typeof vendor !== "string" || vendor.length === 0) {
373
+ throw _err("missing-vendor",
374
+ "mailBounce.parse requires { vendor } (one of 'postmark', 'ses', 'resend') or { parser }");
375
+ }
376
+ var fn = VENDORS[vendor];
377
+ if (!fn) {
378
+ throw _err("unknown-vendor",
379
+ "mailBounce.parse: unknown vendor '" + vendor +
380
+ "' (built-ins: postmark, ses, resend; supply { parser } for others)");
381
+ }
382
+ return fn(payload);
383
+ }
384
+
385
+ // ---- Webhook handler middleware ----
386
+ //
387
+ // Buffers the request body (JSON), runs verify() if supplied, parses
388
+ // via the configured vendor / custom parser, emits the audit event,
389
+ // invokes onBounce, and responds 200. Errors map to 400 (bad payload),
390
+ // 401 (verify rejected), 413 (body too large), 500 (onBounce threw).
391
+ function handler(opts) {
392
+ opts = opts || {};
393
+ var vendor = opts.vendor;
394
+ var customParser = typeof opts.parser === "function" ? opts.parser : null;
395
+ if (!customParser && (typeof vendor !== "string" || !VENDORS[vendor])) {
396
+ throw _err("handler/bad-config",
397
+ "mailBounce.handler requires { vendor } (one of " +
398
+ Object.keys(VENDORS).join(", ") + ") or { parser }");
399
+ }
400
+ var verify = typeof opts.verify === "function" ? opts.verify : null;
401
+ var onBounce = typeof opts.onBounce === "function" ? opts.onBounce : null;
402
+ var auditOn = opts.audit !== false;
403
+ var maxBytes = typeof opts.maxBytes === "number" ? opts.maxBytes : MAX_BODY_BYTES;
404
+
405
+ function _emit(event) {
406
+ if (!auditOn) return;
407
+ audit().safeEmit({
408
+ action: "system.mail.bounce",
409
+ outcome: event.type === "delivery" ? "success" : "denied",
410
+ metadata: {
411
+ vendor: event.vendor,
412
+ type: event.type,
413
+ subType: event.subType,
414
+ recipient: event.recipient,
415
+ messageId: event.messageId,
416
+ reason: event.reason,
417
+ timestamp: event.timestamp,
418
+ },
419
+ });
420
+ }
421
+
422
+ function _send(res, status, body) {
423
+ if (typeof res.writeHead === "function") {
424
+ res.writeHead(status, { "Content-Type": "application/json" });
425
+ res.end(JSON.stringify(body));
426
+ }
427
+ }
428
+
429
+ return function mailBounceMiddleware(req, res) {
430
+ var chunks = [];
431
+ var size = 0;
432
+ var aborted = false;
433
+
434
+ req.on("data", function (chunk) {
435
+ if (aborted) return;
436
+ size += chunk.length;
437
+ if (size > maxBytes) {
438
+ aborted = true;
439
+ return _send(res, 413, { error: "payload too large" });
440
+ }
441
+ chunks.push(chunk);
442
+ });
443
+
444
+ req.on("end", function () {
445
+ if (aborted) return;
446
+ var raw = Buffer.concat(chunks);
447
+ var body;
448
+ try { body = safeJson.parse(raw, { maxBytes: maxBytes }); }
449
+ catch (e) {
450
+ return _send(res, 400, { error: "invalid JSON: " + e.message });
451
+ }
452
+
453
+ // Verification hook — operator decides what counts as authentic.
454
+ // Common shapes: HMAC of body against a shared secret, Basic
455
+ // Auth header, SNS Signature verification, X-Webhook-Signature
456
+ // svix header. The hook receives the request + the parsed body
457
+ // so it can sign over either form.
458
+ if (verify) {
459
+ var ok;
460
+ try { ok = verify(req, body, raw); }
461
+ catch { return _send(res, 401, { error: "verification error" }); }
462
+ if (!ok) return _send(res, 401, { error: "verification failed" });
463
+ }
464
+
465
+ var event;
466
+ try {
467
+ event = customParser ? _customParser(customParser)(body) : VENDORS[vendor](body);
468
+ } catch (e) {
469
+ return _send(res, 400, {
470
+ error: e.message || "parse failed",
471
+ code: e.code || "parse-failed",
472
+ });
473
+ }
474
+
475
+ _emit(event);
476
+
477
+ if (!onBounce) return _send(res, 200, { ok: true });
478
+
479
+ Promise.resolve()
480
+ .then(function () { return onBounce(event); })
481
+ .then(function () { _send(res, 200, { ok: true }); },
482
+ function (e) {
483
+ _send(res, 500, {
484
+ error: "onBounce threw: " + (e && e.message),
485
+ });
486
+ });
487
+ });
488
+
489
+ req.on("error", function () {
490
+ if (!aborted) _send(res, 400, { error: "request error" });
491
+ });
492
+ };
493
+ }
494
+
495
+ module.exports = {
496
+ parse: parse,
497
+ handler: handler,
498
+ MailBounceError: MailBounceError,
499
+ // Vendor parsers exposed for tests + advanced operator wiring (e.g.
500
+ // operators who want to call _parsePostmark inside a custom verify
501
+ // step before deciding whether to accept the webhook).
502
+ vendors: {
503
+ postmark: _parsePostmark,
504
+ ses: _parseSes,
505
+ resend: _parseResend,
506
+ },
507
+ };