@molecule/api-emails-inbound-mailgun 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-emails-inbound-mailgun` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-emails-inbound-mailgun is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
19
+ //# sourceMappingURL=browser-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.js","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,GAAG,UAIT,CAAA;AACD,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IACrF,MAAM,IAAI,KAAK,CACb,+GAA+G;QAC7G,sFAAsF;QACtF,iFAAiF;QACjF,0CAA0C,CAC7C,CAAA;AACH,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Mailgun Routes inbound-email provider for molecule.dev.
3
+ *
4
+ * Implements `@molecule/api-emails-inbound`'s `InboundEmailProvider`
5
+ * interface against Mailgun's parsed-email POST format. Verifies the
6
+ * `timestamp`/`token`/`signature` triple via HMAC-SHA256 against
7
+ * `MAILGUN_API_KEY`, rejecting payloads older than the configured replay
8
+ * window.
9
+ *
10
+ * Outbound replies compose onto the bonded `@molecule/api-emails`
11
+ * transport (typically `@molecule/api-emails-mailgun`) — this package does
12
+ * not reimplement the SMTP path.
13
+ *
14
+ * @remarks
15
+ * `verifySignature` THROWS the tagged `config.notConfigured` error (→ 503
16
+ * via the API error middleware) when `MAILGUN_API_KEY` is unset, instead of
17
+ * returning `false` like every other verification failure. Wire your
18
+ * webhook handler to let that throw propagate to the error middleware —
19
+ * catching it and mapping to the same 401 as a forged/stale webhook
20
+ * re-introduces the "every failure looks the same" ambiguity this was
21
+ * fixed to remove.
22
+ *
23
+ * When an inbound message has no `Message-Id`, `id` is a deterministic
24
+ * hash of the sender/original-Date-header/subject (NOT the per-request
25
+ * Mailgun signing token, which changes on every retry) — so retries of an
26
+ * id-less message still dedupe to the same id.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { setProvider } from '@molecule/api-emails-inbound'
31
+ * import { provider as mailgunRoutes } from '@molecule/api-emails-inbound-mailgun'
32
+ *
33
+ * setProvider(mailgunRoutes)
34
+ * ```
35
+ *
36
+ * @module
37
+ */
38
+ export * from './browser-guard.js';
39
+ export * from './provider.js';
40
+ export * from './secrets.js';
41
+ export * from './types.js';
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Mailgun Routes inbound-email provider for molecule.dev.
3
+ *
4
+ * Implements `@molecule/api-emails-inbound`'s `InboundEmailProvider`
5
+ * interface against Mailgun's parsed-email POST format. Verifies the
6
+ * `timestamp`/`token`/`signature` triple via HMAC-SHA256 against
7
+ * `MAILGUN_API_KEY`, rejecting payloads older than the configured replay
8
+ * window.
9
+ *
10
+ * Outbound replies compose onto the bonded `@molecule/api-emails`
11
+ * transport (typically `@molecule/api-emails-mailgun`) — this package does
12
+ * not reimplement the SMTP path.
13
+ *
14
+ * @remarks
15
+ * `verifySignature` THROWS the tagged `config.notConfigured` error (→ 503
16
+ * via the API error middleware) when `MAILGUN_API_KEY` is unset, instead of
17
+ * returning `false` like every other verification failure. Wire your
18
+ * webhook handler to let that throw propagate to the error middleware —
19
+ * catching it and mapping to the same 401 as a forged/stale webhook
20
+ * re-introduces the "every failure looks the same" ambiguity this was
21
+ * fixed to remove.
22
+ *
23
+ * When an inbound message has no `Message-Id`, `id` is a deterministic
24
+ * hash of the sender/original-Date-header/subject (NOT the per-request
25
+ * Mailgun signing token, which changes on every retry) — so retries of an
26
+ * id-less message still dedupe to the same id.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { setProvider } from '@molecule/api-emails-inbound'
31
+ * import { provider as mailgunRoutes } from '@molecule/api-emails-inbound-mailgun'
32
+ *
33
+ * setProvider(mailgunRoutes)
34
+ * ```
35
+ *
36
+ * @module
37
+ */
38
+ export * from './browser-guard.js';
39
+ export * from './provider.js';
40
+ export * from './secrets.js';
41
+ export * from './types.js';
42
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Mailgun Routes inbound-email provider implementation.
3
+ *
4
+ * Mailgun parses inbound mail upstream and POSTs the result to a configured
5
+ * Route as `application/x-www-form-urlencoded`. Each request also carries
6
+ * three signing fields — `timestamp`, `token`, `signature` — that this
7
+ * module verifies via HMAC-SHA256 against the account's API key.
8
+ *
9
+ * Reply dispatch is composed onto the outbound `@molecule/api-emails` bond
10
+ * (the standard `EmailTransport`); we never reimplement the SMTP path here.
11
+ *
12
+ * @see https://documentation.mailgun.com/en/latest/user_manual.html#routes
13
+ *
14
+ * @module
15
+ */
16
+ import { Buffer } from 'node:buffer';
17
+ import './secrets.js';
18
+ import type { InboundEmail, InboundEmailProvider, InboundEmailReply, InboundEmailReplyResult } from '@molecule/api-emails-inbound';
19
+ /**
20
+ * Verifies a Mailgun inbound webhook signature. Mailgun computes the
21
+ * signature as `HMAC-SHA256(key=api_key, msg=timestamp + token)`, where
22
+ * `+` is string concatenation (no separator). Implementations MUST be
23
+ * constant-time and MUST reject stale timestamps.
24
+ *
25
+ * The `body` parameter is the raw form-encoded body that carries the
26
+ * signing fields. Header-only signing schemes are not supported by Mailgun
27
+ * Routes.
28
+ *
29
+ * Distinguishes SERVER MISCONFIGURATION from a genuinely invalid webhook:
30
+ * an unset `MAILGUN_API_KEY` THROWS the tagged `config.notConfigured` error
31
+ * (mapped by the API error middleware to a clean 503) instead of returning
32
+ * `false`. Stale timestamps, missing signing fields, and a tampered
33
+ * signature all still resolve to `false` (401) — those ARE the "this
34
+ * request is not from Mailgun" class. Collapsing every failure mode into
35
+ * the same `false` made a misconfigured server indistinguishable from
36
+ * active forgery, with no trace either way (see
37
+ * integration-audit-findings.md → [email] ambiguous-failure).
38
+ *
39
+ * @param _headers - HTTP headers (unused — Mailgun signs via form fields).
40
+ * @param body - Raw HTTP request body (form-encoded).
41
+ * @returns `true` when the signature verifies and the timestamp is fresh;
42
+ * `false` for a malformed/stale/forged webhook.
43
+ * @throws {Error} The tagged `config.notConfigured` error when
44
+ * `MAILGUN_API_KEY` is unset — a caller MUST NOT treat this as `false`
45
+ * (that would 401-with-no-trace every inbound webhook instead of
46
+ * surfacing the actionable 503).
47
+ */
48
+ export declare const verifySignature: (_headers: Record<string, string | string[] | undefined>, body: Buffer | string) => Promise<boolean>;
49
+ /**
50
+ * Parses a Mailgun Routes inbound webhook payload into a normalized
51
+ * {@link InboundEmail}.
52
+ *
53
+ * Mailgun POSTs `application/x-www-form-urlencoded` data with keys such as
54
+ * `From`, `To`, `Cc`, `subject`, `body-plain`, `body-html`, `Message-Id`,
55
+ * `In-Reply-To`, `References`, `attachment-count`, `attachment-N`, plus
56
+ * the signing triple. We only extract domain-relevant fields here;
57
+ * verification is done separately by {@link verifySignature}.
58
+ *
59
+ * When `Message-Id` is absent, `id` falls back to
60
+ * {@link deriveStableFallbackId} rather than the per-request signing
61
+ * `token` — see that function's docs for why.
62
+ *
63
+ * @param _headers - HTTP headers (unused — Mailgun puts everything in the body).
64
+ * @param body - The raw form-encoded body, a string, or an already-parsed object.
65
+ * @returns The normalized inbound email.
66
+ */
67
+ export declare const parseWebhookPayload: (_headers: Record<string, string | string[] | undefined>, body: Buffer | string | Record<string, unknown>) => Promise<InboundEmail>;
68
+ /**
69
+ * Dispatches an outbound reply through the bonded `@molecule/api-emails`
70
+ * transport. Mailgun's outbound API is already exposed via
71
+ * `@molecule/api-emails-mailgun`, so we compose rather than reimplement.
72
+ *
73
+ * The reply's `In-Reply-To` and `References` headers are populated from
74
+ * the original message when present, so threading works in the recipient's
75
+ * mail client.
76
+ *
77
+ * @param email - The original inbound email being replied to.
78
+ * @param reply - The reply payload.
79
+ * @returns The reply dispatch result.
80
+ */
81
+ export declare const replyTo: (email: InboundEmail, reply: InboundEmailReply) => Promise<InboundEmailReplyResult>;
82
+ /**
83
+ * Indicates that this provider supports outbound reply dispatch via
84
+ * {@link replyTo}. The reply path requires the outbound
85
+ * `@molecule/api-emails` bond to be wired with a transport — typically
86
+ * `@molecule/api-emails-mailgun`.
87
+ *
88
+ * @returns Always `true`.
89
+ */
90
+ export declare const supportsReply: () => boolean;
91
+ /**
92
+ * The Mailgun Routes inbound-email provider implementing the
93
+ * {@link InboundEmailProvider} interface.
94
+ */
95
+ export declare const provider: InboundEmailProvider;
96
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAMpC,OAAO,cAAc,CAAA;AAGrB,OAAO,KAAK,EACV,YAAY,EAEZ,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACxB,MAAM,8BAA8B,CAAA;AA4DrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,eAAe,GAC1B,UAAU,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,EACvD,MAAM,MAAM,GAAG,MAAM,KACpB,OAAO,CAAC,OAAO,CA0BjB,CAAA;AA8FD;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,GAC9B,UAAU,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,EACvD,MAAM,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC9C,OAAO,CAAC,YAAY,CAiDtB,CAAA;AAWD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,GAClB,OAAO,YAAY,EACnB,OAAO,iBAAiB,KACvB,OAAO,CAAC,uBAAuB,CAoDjC,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,QAAO,OAAe,CAAA;AAEhD;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,oBAKtB,CAAA"}
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Mailgun Routes inbound-email provider implementation.
3
+ *
4
+ * Mailgun parses inbound mail upstream and POSTs the result to a configured
5
+ * Route as `application/x-www-form-urlencoded`. Each request also carries
6
+ * three signing fields — `timestamp`, `token`, `signature` — that this
7
+ * module verifies via HMAC-SHA256 against the account's API key.
8
+ *
9
+ * Reply dispatch is composed onto the outbound `@molecule/api-emails` bond
10
+ * (the standard `EmailTransport`); we never reimplement the SMTP path here.
11
+ *
12
+ * @see https://documentation.mailgun.com/en/latest/user_manual.html#routes
13
+ *
14
+ * @module
15
+ */
16
+ import { Buffer } from 'node:buffer';
17
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
18
+ // Side-effect import: registers this bond's secret definitions so the
19
+ // runtime registry is populated even when provider.js is imported directly
20
+ // (not through the package barrel).
21
+ import './secrets.js';
22
+ import { sendMail } from '@molecule/api-emails';
23
+ import { configNotConfiguredError } from '@molecule/api-secrets';
24
+ import { DEFAULT_REPLAY_WINDOW_SECONDS, parseFormBody, parseMailgunMessageHeaders, splitAddressList, splitReferences, unwrapMessageId, } from './utilities.js';
25
+ /**
26
+ * Reads the Mailgun API key from the environment, throwing a generic
27
+ * configuration error (without revealing any value) when it is unset.
28
+ *
29
+ * @returns The Mailgun API key string.
30
+ */
31
+ const getApiKey = () => {
32
+ const apiKey = process.env.MAILGUN_API_KEY;
33
+ if (!apiKey) {
34
+ // Tagged config-missing error → clean 503 + 'config.notConfigured', with the
35
+ // registered definition's description + setup URL (see classifyTaggedError).
36
+ throw configNotConfiguredError('MAILGUN_API_KEY', 'inbound email');
37
+ }
38
+ return apiKey;
39
+ };
40
+ /**
41
+ * Reads the configured replay window (seconds) for inbound webhooks. Falls
42
+ * back to {@link DEFAULT_REPLAY_WINDOW_SECONDS} when unset or invalid.
43
+ *
44
+ * @returns The replay window in seconds.
45
+ */
46
+ const getReplayWindowSeconds = () => {
47
+ const raw = process.env.MAILGUN_INBOUND_REPLAY_WINDOW_SECONDS;
48
+ if (!raw)
49
+ return DEFAULT_REPLAY_WINDOW_SECONDS;
50
+ const parsed = Number.parseInt(raw, 10);
51
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_REPLAY_WINDOW_SECONDS;
52
+ };
53
+ /**
54
+ * Constant-time comparison of two equal-length hex digests.
55
+ *
56
+ * @param a - The first digest.
57
+ * @param b - The second digest.
58
+ * @returns `true` when the digests are byte-equal.
59
+ */
60
+ const safeEqualHex = (a, b) => {
61
+ if (a.length !== b.length)
62
+ return false;
63
+ try {
64
+ return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
65
+ }
66
+ catch (_error) {
67
+ // timingSafeEqual throws if the two Buffers have different byte lengths,
68
+ // which cannot happen here after the length guard above. Any other failure
69
+ // (e.g. invalid hex encoding) also means the signature is invalid.
70
+ return false;
71
+ }
72
+ };
73
+ /**
74
+ * Verifies a Mailgun inbound webhook signature. Mailgun computes the
75
+ * signature as `HMAC-SHA256(key=api_key, msg=timestamp + token)`, where
76
+ * `+` is string concatenation (no separator). Implementations MUST be
77
+ * constant-time and MUST reject stale timestamps.
78
+ *
79
+ * The `body` parameter is the raw form-encoded body that carries the
80
+ * signing fields. Header-only signing schemes are not supported by Mailgun
81
+ * Routes.
82
+ *
83
+ * Distinguishes SERVER MISCONFIGURATION from a genuinely invalid webhook:
84
+ * an unset `MAILGUN_API_KEY` THROWS the tagged `config.notConfigured` error
85
+ * (mapped by the API error middleware to a clean 503) instead of returning
86
+ * `false`. Stale timestamps, missing signing fields, and a tampered
87
+ * signature all still resolve to `false` (401) — those ARE the "this
88
+ * request is not from Mailgun" class. Collapsing every failure mode into
89
+ * the same `false` made a misconfigured server indistinguishable from
90
+ * active forgery, with no trace either way (see
91
+ * integration-audit-findings.md → [email] ambiguous-failure).
92
+ *
93
+ * @param _headers - HTTP headers (unused — Mailgun signs via form fields).
94
+ * @param body - Raw HTTP request body (form-encoded).
95
+ * @returns `true` when the signature verifies and the timestamp is fresh;
96
+ * `false` for a malformed/stale/forged webhook.
97
+ * @throws {Error} The tagged `config.notConfigured` error when
98
+ * `MAILGUN_API_KEY` is unset — a caller MUST NOT treat this as `false`
99
+ * (that would 401-with-no-trace every inbound webhook instead of
100
+ * surfacing the actionable 503).
101
+ */
102
+ export const verifySignature = async (_headers, body) => {
103
+ // Deliberately NOT caught here: an unconfigured key is a server
104
+ // misconfiguration, not "signature invalid," and must propagate as the
105
+ // tagged config error so the caller (the API error middleware) can 503
106
+ // instead of silently 401ing every webhook. See @throws above.
107
+ const apiKey = getApiKey();
108
+ const fields = parseFormBody(body);
109
+ const timestamp = fields.timestamp;
110
+ const token = fields.token;
111
+ const signature = fields.signature;
112
+ if (!timestamp || !token || !signature)
113
+ return false;
114
+ // Reject stale timestamps to defend against replay (Mailgun tokens are
115
+ // single-use, but the time bound is belt-and-suspenders).
116
+ const ts = Number.parseInt(timestamp, 10);
117
+ if (!Number.isFinite(ts))
118
+ return false;
119
+ const nowSeconds = Math.floor(Date.now() / 1000);
120
+ if (Math.abs(nowSeconds - ts) > getReplayWindowSeconds())
121
+ return false;
122
+ const expected = createHmac('sha256', apiKey)
123
+ .update(timestamp + token)
124
+ .digest('hex');
125
+ return safeEqualHex(expected, signature.toLowerCase());
126
+ };
127
+ /**
128
+ * Builds the {@link InboundEmailAttachment} list from Mailgun's
129
+ * form-encoded `attachment-N` and `attachment-count` fields.
130
+ *
131
+ * Mailgun in form-only mode encodes each attachment as JSON in the
132
+ * `attachment-N` field (`{"name","content-type","size","content"}`), where
133
+ * `content` is the base64-encoded payload. We map this onto the normalized
134
+ * shape and skip any entry that fails to parse.
135
+ *
136
+ * @param fields - Parsed form fields.
137
+ * @returns Array of attachments (empty when none are present).
138
+ */
139
+ const parseFormAttachments = (fields) => {
140
+ const out = [];
141
+ const countRaw = fields['attachment-count'];
142
+ const count = Number.parseInt(countRaw ?? '0', 10);
143
+ if (!Number.isFinite(count) || count <= 0)
144
+ return out;
145
+ for (let i = 1; i <= count; i += 1) {
146
+ const raw = fields[`attachment-${String(i)}`];
147
+ if (!raw)
148
+ continue;
149
+ let parsed;
150
+ try {
151
+ const candidate = JSON.parse(raw);
152
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
153
+ parsed = candidate;
154
+ }
155
+ }
156
+ catch (_error) {
157
+ // Mailgun sent a malformed attachment JSON field — skip this entry rather
158
+ // than aborting the whole parse; other attachments and the email body are
159
+ // still valid.
160
+ continue;
161
+ }
162
+ if (!parsed)
163
+ continue;
164
+ const name = typeof parsed.name === 'string' ? parsed.name : `attachment-${String(i)}`;
165
+ const contentType = typeof parsed['content-type'] === 'string'
166
+ ? parsed['content-type']
167
+ : 'application/octet-stream';
168
+ const sizeRaw = parsed.size;
169
+ const sizeBytes = typeof sizeRaw === 'number' ? sizeRaw : undefined;
170
+ const contentRaw = parsed.content;
171
+ const contentBase64 = typeof contentRaw === 'string'
172
+ ? // Mailgun documents the `content` as already base64-encoded.
173
+ contentRaw
174
+ : '';
175
+ const contentId = typeof parsed['content-id'] === 'string' ? parsed['content-id'] : undefined;
176
+ const attachment = {
177
+ name,
178
+ contentType,
179
+ contentBase64,
180
+ };
181
+ if (sizeBytes !== undefined)
182
+ attachment.sizeBytes = sizeBytes;
183
+ if (contentId !== undefined)
184
+ attachment.contentId = contentId;
185
+ out.push(attachment);
186
+ }
187
+ return out;
188
+ };
189
+ /**
190
+ * Derives a stable fallback identifier for an inbound email that has no
191
+ * `Message-Id` (some senders omit it). Hashes the sender, the ORIGINAL
192
+ * message's `Date` header, and the subject — deliberately NOT the webhook
193
+ * delivery `timestamp`/`token` fields, which Mailgun regenerates on every
194
+ * retry of the SAME message. A retry-stable input keeps retries of an
195
+ * id-less message hashing to the same id, so the core contract's "used for
196
+ * deduplication when the same webhook is retried" still holds (see
197
+ * integration-audit-findings.md → [email] doc-drift).
198
+ *
199
+ * @param from - The normalized sender address.
200
+ * @param dateHeader - The original message's `Date` header, if present in
201
+ * `message-headers` (absent for form-only, non-MIME deliveries).
202
+ * @param subject - The normalized subject line.
203
+ * @returns A `mailgun-`-prefixed, deterministic fallback id.
204
+ */
205
+ const deriveStableFallbackId = (from, dateHeader, subject) => {
206
+ const digest = createHash('sha256')
207
+ .update(`${from}${dateHeader ?? ''}${subject}`)
208
+ .digest('hex');
209
+ return `mailgun-${digest.slice(0, 32)}`;
210
+ };
211
+ /**
212
+ * Parses a Mailgun Routes inbound webhook payload into a normalized
213
+ * {@link InboundEmail}.
214
+ *
215
+ * Mailgun POSTs `application/x-www-form-urlencoded` data with keys such as
216
+ * `From`, `To`, `Cc`, `subject`, `body-plain`, `body-html`, `Message-Id`,
217
+ * `In-Reply-To`, `References`, `attachment-count`, `attachment-N`, plus
218
+ * the signing triple. We only extract domain-relevant fields here;
219
+ * verification is done separately by {@link verifySignature}.
220
+ *
221
+ * When `Message-Id` is absent, `id` falls back to
222
+ * {@link deriveStableFallbackId} rather than the per-request signing
223
+ * `token` — see that function's docs for why.
224
+ *
225
+ * @param _headers - HTTP headers (unused — Mailgun puts everything in the body).
226
+ * @param body - The raw form-encoded body, a string, or an already-parsed object.
227
+ * @returns The normalized inbound email.
228
+ */
229
+ export const parseWebhookPayload = async (_headers, body) => {
230
+ const fields = parseFormBody(body);
231
+ const messageHeaders = parseMailgunMessageHeaders(fields['message-headers']);
232
+ const messageId = unwrapMessageId(fields['Message-Id'] ?? fields['message-id']);
233
+ const inReplyTo = unwrapMessageId(fields['In-Reply-To'] ?? fields['in-reply-to']);
234
+ const references = splitReferences(fields.References ?? fields.references).map((ref) => {
235
+ const unwrapped = unwrapMessageId(ref);
236
+ return unwrapped ?? ref;
237
+ });
238
+ const timestampRaw = fields.timestamp;
239
+ const timestampSeconds = Number.parseInt(timestampRaw ?? '', 10);
240
+ const receivedAt = Number.isFinite(timestampSeconds)
241
+ ? new Date(timestampSeconds * 1000)
242
+ : new Date();
243
+ const from = fields.From ?? fields.from ?? fields.sender ?? '';
244
+ const subject = fields.Subject ?? fields.subject ?? '';
245
+ const dateHeaderRaw = messageHeaders.date;
246
+ const dateHeader = Array.isArray(dateHeaderRaw) ? dateHeaderRaw[0] : dateHeaderRaw;
247
+ const email = {
248
+ id: messageId ?? deriveStableFallbackId(from, dateHeader, subject),
249
+ from,
250
+ to: splitAddressList(fields.To ?? fields.to ?? fields.recipient),
251
+ subject,
252
+ headers: messageHeaders,
253
+ receivedAt,
254
+ };
255
+ const cc = splitAddressList(fields.Cc ?? fields.cc);
256
+ if (cc.length > 0)
257
+ email.cc = cc;
258
+ const textBody = fields['body-plain'];
259
+ if (textBody !== undefined)
260
+ email.textBody = textBody;
261
+ const htmlBody = fields['body-html'];
262
+ if (htmlBody !== undefined)
263
+ email.htmlBody = htmlBody;
264
+ const attachments = parseFormAttachments(fields);
265
+ if (attachments.length > 0)
266
+ email.attachments = attachments;
267
+ if (messageId)
268
+ email.messageId = messageId;
269
+ if (inReplyTo)
270
+ email.inReplyTo = inReplyTo;
271
+ if (references.length > 0)
272
+ email.references = references;
273
+ return email;
274
+ };
275
+ /**
276
+ * Decodes a base64 string into a Node `Buffer`. Defined inline so the
277
+ * provider does not pull in extra dependencies for a one-line operation.
278
+ *
279
+ * @param value - The base64 string.
280
+ * @returns The decoded buffer.
281
+ */
282
+ const base64ToBuffer = (value) => Buffer.from(value, 'base64');
283
+ /**
284
+ * Dispatches an outbound reply through the bonded `@molecule/api-emails`
285
+ * transport. Mailgun's outbound API is already exposed via
286
+ * `@molecule/api-emails-mailgun`, so we compose rather than reimplement.
287
+ *
288
+ * The reply's `In-Reply-To` and `References` headers are populated from
289
+ * the original message when present, so threading works in the recipient's
290
+ * mail client.
291
+ *
292
+ * @param email - The original inbound email being replied to.
293
+ * @param reply - The reply payload.
294
+ * @returns The reply dispatch result.
295
+ */
296
+ export const replyTo = async (email, reply) => {
297
+ const fromAddress = reply.from ?? (email.to.length > 0 ? email.to[0] : undefined);
298
+ if (!fromAddress) {
299
+ throw new Error('Cannot dispatch inbound reply: no `from` address was supplied and the original email has no recipient to fall back to.');
300
+ }
301
+ const subject = reply.subject ?? `Re: ${email.subject}`;
302
+ // Build threading headers from the original message so the recipient's
303
+ // mail client groups the reply into the existing thread. We pass them
304
+ // alongside the normalized EmailMessage shape via a structural cast —
305
+ // every concrete EmailTransport (nodemailer, SES, etc.) honours a
306
+ // `headers` field, and the cast keeps the core EmailMessage type lean.
307
+ const threadingHeaders = {};
308
+ if (email.messageId) {
309
+ threadingHeaders['In-Reply-To'] = `<${email.messageId}>`;
310
+ const refs = email.references ? [...email.references] : [];
311
+ refs.push(email.messageId);
312
+ threadingHeaders.References = refs.map((id) => `<${id}>`).join(' ');
313
+ }
314
+ const headers = {
315
+ ...threadingHeaders,
316
+ ...(reply.headers ?? {}),
317
+ };
318
+ const message = {
319
+ from: fromAddress,
320
+ to: email.from,
321
+ subject,
322
+ ...(reply.textBody !== undefined ? { text: reply.textBody } : {}),
323
+ ...(reply.htmlBody !== undefined ? { html: reply.htmlBody } : {}),
324
+ ...(reply.attachments && reply.attachments.length > 0
325
+ ? {
326
+ attachments: reply.attachments.map((a) => ({
327
+ filename: a.name,
328
+ content: base64ToBuffer(a.contentBase64),
329
+ contentType: a.contentType,
330
+ ...(a.contentId !== undefined ? { cid: a.contentId } : {}),
331
+ })),
332
+ }
333
+ : {}),
334
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
335
+ };
336
+ const result = await sendMail(message);
337
+ return {
338
+ id: result.messageId ?? '',
339
+ };
340
+ };
341
+ /**
342
+ * Indicates that this provider supports outbound reply dispatch via
343
+ * {@link replyTo}. The reply path requires the outbound
344
+ * `@molecule/api-emails` bond to be wired with a transport — typically
345
+ * `@molecule/api-emails-mailgun`.
346
+ *
347
+ * @returns Always `true`.
348
+ */
349
+ export const supportsReply = () => true;
350
+ /**
351
+ * The Mailgun Routes inbound-email provider implementing the
352
+ * {@link InboundEmailProvider} interface.
353
+ */
354
+ export const provider = {
355
+ parseWebhookPayload,
356
+ verifySignature,
357
+ replyTo,
358
+ supportsReply,
359
+ };
360
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAErE,sEAAsE;AACtE,2EAA2E;AAC3E,oCAAoC;AACpC,OAAO,cAAc,CAAA;AAErB,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAQ/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAA;AAEhE,OAAO,EACL,6BAA6B,EAC7B,aAAa,EACb,0BAA0B,EAC1B,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,gBAAgB,CAAA;AAEvB;;;;;GAKG;AACH,MAAM,SAAS,GAAG,GAAW,EAAE;IAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAA;IAC1C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,6EAA6E;QAC7E,6EAA6E;QAC7E,MAAM,wBAAwB,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAAA;IACpE,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAED;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,GAAW,EAAE;IAC1C,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,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,CAAC,EAAE,EAAE,CAAC,CAAC;oBACzC,QAAQ,EAAE,CAAC,CAAC,IAAI;oBAChB,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,aAAa,CAAC;oBACxC,WAAW,EAAE,CAAC,CAAC,WAAW;oBAC1B,GAAG,CAAC,CAAC,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC3D,CAAC,CAAC;aACJ;YACH,CAAC,CAAC,EAAE,CAAC;QACP,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACxD,CAAA;IAED,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAyC,CAAC,CAAA;IAExE,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,SAAS,IAAI,EAAE;KAC3B,CAAA;AACH,CAAC,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,GAAY,EAAE,CAAC,IAAI,CAAA;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAyB;IAC5C,mBAAmB;IACnB,eAAe;IACf,OAAO;IACP,aAAa;CACd,CAAA"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Mailgun secret definitions (inbound routes) — self-registered at import
3
+ * time so the runtime secrets registry (`@molecule/api-secrets`) can drive
4
+ * boot-time configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key (MAILGUN_API_KEY/MAILGUN_DOMAIN with the outbound
9
+ * bond) register byte-identical definitions and registration order never
10
+ * matters.
11
+ *
12
+ * @module
13
+ */
14
+ import type { SecretDefinition } from '@molecule/api-secrets';
15
+ /** Secret definitions required by the Mailgun inbound-email bond. */
16
+ export declare const mailgunInboundSecretDefinitions: SecretDefinition[];
17
+ //# sourceMappingURL=secrets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,qEAAqE;AACrE,eAAO,MAAM,+BAA+B,EAAE,gBAAgB,EAuB7D,CAAA"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Mailgun secret definitions (inbound routes) — self-registered at import
3
+ * time so the runtime secrets registry (`@molecule/api-secrets`) can drive
4
+ * boot-time configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key (MAILGUN_API_KEY/MAILGUN_DOMAIN with the outbound
9
+ * bond) register byte-identical definitions and registration order never
10
+ * matters.
11
+ *
12
+ * @module
13
+ */
14
+ import { registerSecrets } from '@molecule/api-secrets';
15
+ /** Secret definitions required by the Mailgun inbound-email bond. */
16
+ export const mailgunInboundSecretDefinitions = [
17
+ {
18
+ key: 'MAILGUN_API_KEY',
19
+ description: 'Mailgun API key — Mailgun dashboard → Settings → API Security → create/copy a sending API key.',
20
+ helpUrl: 'https://app.mailgun.com/settings/api_security',
21
+ required: true,
22
+ },
23
+ {
24
+ key: 'MAILGUN_DOMAIN',
25
+ description: 'Mailgun sending domain — Add and verify a sending domain in Mailgun (sandbox domains work for testing to authorized recipients).',
26
+ helpUrl: 'https://app.mailgun.com/mg/sending/domains',
27
+ required: true,
28
+ example: 'mg.example.com',
29
+ },
30
+ {
31
+ key: 'MAILGUN_INBOUND_REPLAY_WINDOW_SECONDS',
32
+ description: 'Mailgun inbound replay window — Max age (seconds) of accepted inbound webhook signatures — replay protection; the default is fine.',
33
+ required: false,
34
+ example: '300',
35
+ },
36
+ ];
37
+ registerSecrets(mailgunInboundSecretDefinitions);
38
+ //# sourceMappingURL=secrets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.js","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAEvD,qEAAqE;AACrE,MAAM,CAAC,MAAM,+BAA+B,GAAuB;IACjE;QACE,GAAG,EAAE,iBAAiB;QACtB,WAAW,EACT,gGAAgG;QAClG,OAAO,EAAE,+CAA+C;QACxD,QAAQ,EAAE,IAAI;KACf;IACD;QACE,GAAG,EAAE,gBAAgB;QACrB,WAAW,EACT,kIAAkI;QACpI,OAAO,EAAE,4CAA4C;QACrD,QAAQ,EAAE,IAAI;QACd,OAAO,EAAE,gBAAgB;KAC1B;IACD;QACE,GAAG,EAAE,uCAAuC;QAC5C,WAAW,EACT,oIAAoI;QACtI,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf;CACF,CAAA;AAED,eAAe,CAAC,+BAA+B,CAAC,CAAA"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Type definitions for the Mailgun Routes inbound-emails provider.
3
+ *
4
+ * @module
5
+ */
6
+ export type { InboundEmail, InboundEmailAttachment, InboundEmailProvider, InboundEmailReply, InboundEmailReplyResult, } from '@molecule/api-emails-inbound';
7
+ declare global {
8
+ namespace NodeJS {
9
+ /**
10
+ * Process Env interface — Mailgun Routes shares the same credentials as
11
+ * the outbound `@molecule/api-emails-mailgun` bond. The HMAC signing key
12
+ * used to verify inbound webhooks is the Mailgun API key.
13
+ */
14
+ interface ProcessEnv {
15
+ /**
16
+ * Mailgun API key. Used as the HMAC-SHA256 signing key when verifying
17
+ * inbound webhook signatures, and as the auth token when dispatching
18
+ * outbound replies.
19
+ */
20
+ MAILGUN_API_KEY?: string;
21
+ /**
22
+ * Mailgun sending domain. Used as the default `From:` domain when
23
+ * dispatching outbound replies.
24
+ */
25
+ MAILGUN_DOMAIN?: string;
26
+ /**
27
+ * Maximum age in seconds for an inbound webhook timestamp before the
28
+ * provider rejects it as a replay. Defaults to `300` (5 minutes) when
29
+ * unset.
30
+ */
31
+ MAILGUN_INBOUND_REPLAY_WINDOW_SECONDS?: string;
32
+ }
33
+ }
34
+ }
35
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,YAAY,EACV,YAAY,EACZ,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,8BAA8B,CAAA;AAErC,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,MAAM,CAAC;QACf;;;;WAIG;QACH,UAAiB,UAAU;YACzB;;;;eAIG;YACH,eAAe,CAAC,EAAE,MAAM,CAAA;YAExB;;;eAGG;YACH,cAAc,CAAC,EAAE,MAAM,CAAA;YAEvB;;;;eAIG;YACH,qCAAqC,CAAC,EAAE,MAAM,CAAA;SAC/C;KACF;CACF"}
package/dist/types.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Type definitions for the Mailgun Routes inbound-emails provider.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Internal utilities for the Mailgun Routes inbound-emails provider.
3
+ *
4
+ * Kept out of `provider.ts` so the parsing helpers can be unit-tested in
5
+ * isolation without touching the bond singleton.
6
+ *
7
+ * @module
8
+ */
9
+ import { Buffer } from 'node:buffer';
10
+ /**
11
+ * Default replay window for inbound webhook timestamps, in seconds.
12
+ *
13
+ * Mailgun signs every inbound POST with `timestamp`, `token`, and
14
+ * `signature`. Tokens are single-use, but to defend against replay we also
15
+ * reject any payload whose `timestamp` is older than this window.
16
+ */
17
+ export declare const DEFAULT_REPLAY_WINDOW_SECONDS = 300;
18
+ /**
19
+ * Coerces an HTTP header value (which may be `string`, `string[]`, or
20
+ * `undefined`) to a single string. Multi-value headers are joined with
21
+ * `, ` per RFC 9110 §5.2.
22
+ *
23
+ * @param value - The header value to coerce.
24
+ * @returns The header value as a single string, or `undefined` when the
25
+ * header was not present.
26
+ */
27
+ export declare const headerToString: (value: string | string[] | undefined) => string | undefined;
28
+ /**
29
+ * Returns the value of `headers[name]` (case-insensitive) coerced to a
30
+ * single string.
31
+ *
32
+ * @param headers - The headers object.
33
+ * @param name - The header name (case-insensitive).
34
+ * @returns The header value as a single string, or `undefined` if absent.
35
+ */
36
+ export declare const getHeader: (headers: Record<string, string | string[] | undefined>, name: string) => string | undefined;
37
+ /**
38
+ * Coerces the request body into a UTF-8 string. Buffers are decoded as
39
+ * UTF-8 (Mailgun POSTs `application/x-www-form-urlencoded` ASCII), strings
40
+ * are returned as-is.
41
+ *
42
+ * @param body - The raw body.
43
+ * @returns The body as a UTF-8 string.
44
+ */
45
+ export declare const bodyToString: (body: Buffer | string) => string;
46
+ /**
47
+ * Parses a `application/x-www-form-urlencoded` body into a flat
48
+ * `Record<string, string>`. Fields that appear more than once keep their
49
+ * first value (Mailgun does not duplicate fields).
50
+ *
51
+ * Accepts either a raw form-encoded string or an already-parsed object
52
+ * (Express's `body-parser` middleware gives us the latter when a JSON
53
+ * route accidentally captures the webhook). The pre-parsed-object branch
54
+ * coerces every value to a string for consistent downstream parsing.
55
+ *
56
+ * @param body - Raw body or pre-parsed form object.
57
+ * @returns Flat record of form fields.
58
+ */
59
+ export declare const parseFormBody: (body: Buffer | string | Record<string, unknown>) => Record<string, string>;
60
+ /**
61
+ * Splits a Mailgun recipient list (comma-separated mailbox list, possibly
62
+ * with display names like `'Alice <a@x>, "Bob, Jr." <b@y>'`) into trimmed
63
+ * RFC 5322 mailbox strings.
64
+ *
65
+ * Mailgun forwards the original `To:` and `Cc:` headers verbatim, so the
66
+ * implementation needs to respect quoted-string commas.
67
+ *
68
+ * @param value - The raw header value.
69
+ * @returns Array of trimmed mailbox strings (empty when `value` is empty).
70
+ */
71
+ export declare const splitAddressList: (value: string | undefined) => string[];
72
+ /**
73
+ * Splits a `References:` header (whitespace-separated `<message-id>`
74
+ * tokens) into individual values, including the angle brackets.
75
+ *
76
+ * @param value - The raw header value.
77
+ * @returns Array of message-id tokens (with angle brackets) or empty.
78
+ */
79
+ export declare const splitReferences: (value: string | undefined) => string[];
80
+ /**
81
+ * Recovers a normalized headers map from Mailgun's `message-headers` form
82
+ * field (a JSON-encoded array of `[name, value]` tuples, e.g.
83
+ * `[["Received","by ..."],["From","alice@example.com"]]`).
84
+ *
85
+ * Field names are lowercased; multi-value headers are returned as arrays.
86
+ * Falls back to an empty record when the field is absent or invalid JSON.
87
+ *
88
+ * @param raw - The raw `message-headers` form field value.
89
+ * @returns Normalized headers map.
90
+ */
91
+ export declare const parseMailgunMessageHeaders: (raw: string | undefined) => Record<string, string | string[]>;
92
+ /**
93
+ * Strips surrounding angle brackets from a `Message-ID` value.
94
+ *
95
+ * @param value - The raw value (with or without angle brackets).
96
+ * @returns The value without angle brackets, or `undefined` if input was empty.
97
+ */
98
+ export declare const unwrapMessageId: (value: string | undefined) => string | undefined;
99
+ //# sourceMappingURL=utilities.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../src/utilities.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,MAAM,CAAA;AAEhD;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,KAAG,MAAM,GAAG,SAG9E,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,SAAS,GACpB,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,EACtD,MAAM,MAAM,KACX,MAAM,GAAG,SAQX,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,MAAM,GAAG,MAAM,KAAG,MAEpD,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,aAAa,GACxB,MAAM,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC9C,MAAM,CAAC,MAAM,EAAE,MAAM,CAiBvB,CAAA;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,gBAAgB,GAAI,OAAO,MAAM,GAAG,SAAS,KAAG,MAAM,EAgClE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,MAAM,GAAG,SAAS,KAAG,MAAM,EAMjE,CAAA;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,0BAA0B,GACrC,KAAK,MAAM,GAAG,SAAS,KACtB,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CA6BlC,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,MAAM,GAAG,SAAS,KAAG,MAAM,GAAG,SAKpE,CAAA"}
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Internal utilities for the Mailgun Routes inbound-emails provider.
3
+ *
4
+ * Kept out of `provider.ts` so the parsing helpers can be unit-tested in
5
+ * isolation without touching the bond singleton.
6
+ *
7
+ * @module
8
+ */
9
+ import { Buffer } from 'node:buffer';
10
+ /**
11
+ * Default replay window for inbound webhook timestamps, in seconds.
12
+ *
13
+ * Mailgun signs every inbound POST with `timestamp`, `token`, and
14
+ * `signature`. Tokens are single-use, but to defend against replay we also
15
+ * reject any payload whose `timestamp` is older than this window.
16
+ */
17
+ export const DEFAULT_REPLAY_WINDOW_SECONDS = 300;
18
+ /**
19
+ * Coerces an HTTP header value (which may be `string`, `string[]`, or
20
+ * `undefined`) to a single string. Multi-value headers are joined with
21
+ * `, ` per RFC 9110 §5.2.
22
+ *
23
+ * @param value - The header value to coerce.
24
+ * @returns The header value as a single string, or `undefined` when the
25
+ * header was not present.
26
+ */
27
+ export const headerToString = (value) => {
28
+ if (value === undefined)
29
+ return undefined;
30
+ return Array.isArray(value) ? value.join(', ') : value;
31
+ };
32
+ /**
33
+ * Returns the value of `headers[name]` (case-insensitive) coerced to a
34
+ * single string.
35
+ *
36
+ * @param headers - The headers object.
37
+ * @param name - The header name (case-insensitive).
38
+ * @returns The header value as a single string, or `undefined` if absent.
39
+ */
40
+ export const getHeader = (headers, name) => {
41
+ const target = name.toLowerCase();
42
+ for (const key of Object.keys(headers)) {
43
+ if (key.toLowerCase() === target) {
44
+ return headerToString(headers[key]);
45
+ }
46
+ }
47
+ return undefined;
48
+ };
49
+ /**
50
+ * Coerces the request body into a UTF-8 string. Buffers are decoded as
51
+ * UTF-8 (Mailgun POSTs `application/x-www-form-urlencoded` ASCII), strings
52
+ * are returned as-is.
53
+ *
54
+ * @param body - The raw body.
55
+ * @returns The body as a UTF-8 string.
56
+ */
57
+ export const bodyToString = (body) => {
58
+ return Buffer.isBuffer(body) ? body.toString('utf8') : body;
59
+ };
60
+ /**
61
+ * Parses a `application/x-www-form-urlencoded` body into a flat
62
+ * `Record<string, string>`. Fields that appear more than once keep their
63
+ * first value (Mailgun does not duplicate fields).
64
+ *
65
+ * Accepts either a raw form-encoded string or an already-parsed object
66
+ * (Express's `body-parser` middleware gives us the latter when a JSON
67
+ * route accidentally captures the webhook). The pre-parsed-object branch
68
+ * coerces every value to a string for consistent downstream parsing.
69
+ *
70
+ * @param body - Raw body or pre-parsed form object.
71
+ * @returns Flat record of form fields.
72
+ */
73
+ export const parseFormBody = (body) => {
74
+ if (typeof body === 'string' || Buffer.isBuffer(body)) {
75
+ const params = new URLSearchParams(bodyToString(body));
76
+ const out = {};
77
+ for (const [key, value] of params.entries()) {
78
+ if (!(key in out))
79
+ out[key] = value;
80
+ }
81
+ return out;
82
+ }
83
+ // Already-parsed object: coerce every leaf to string.
84
+ const out = {};
85
+ for (const [key, value] of Object.entries(body)) {
86
+ if (value === undefined || value === null)
87
+ continue;
88
+ out[key] = typeof value === 'string' ? value : String(value);
89
+ }
90
+ return out;
91
+ };
92
+ /**
93
+ * Splits a Mailgun recipient list (comma-separated mailbox list, possibly
94
+ * with display names like `'Alice <a@x>, "Bob, Jr." <b@y>'`) into trimmed
95
+ * RFC 5322 mailbox strings.
96
+ *
97
+ * Mailgun forwards the original `To:` and `Cc:` headers verbatim, so the
98
+ * implementation needs to respect quoted-string commas.
99
+ *
100
+ * @param value - The raw header value.
101
+ * @returns Array of trimmed mailbox strings (empty when `value` is empty).
102
+ */
103
+ export const splitAddressList = (value) => {
104
+ if (!value)
105
+ return [];
106
+ const out = [];
107
+ let depth = 0;
108
+ let inQuotes = false;
109
+ let current = '';
110
+ for (let i = 0; i < value.length; i += 1) {
111
+ const ch = value[i];
112
+ if (ch === '"' && value[i - 1] !== '\\') {
113
+ inQuotes = !inQuotes;
114
+ current += ch;
115
+ continue;
116
+ }
117
+ if (!inQuotes) {
118
+ if (ch === '<')
119
+ depth += 1;
120
+ else if (ch === '>')
121
+ depth = Math.max(0, depth - 1);
122
+ else if (ch === ',' && depth === 0) {
123
+ const trimmed = current.trim();
124
+ if (trimmed)
125
+ out.push(trimmed);
126
+ current = '';
127
+ continue;
128
+ }
129
+ }
130
+ current += ch;
131
+ }
132
+ const trimmed = current.trim();
133
+ if (trimmed)
134
+ out.push(trimmed);
135
+ return out;
136
+ };
137
+ /**
138
+ * Splits a `References:` header (whitespace-separated `<message-id>`
139
+ * tokens) into individual values, including the angle brackets.
140
+ *
141
+ * @param value - The raw header value.
142
+ * @returns Array of message-id tokens (with angle brackets) or empty.
143
+ */
144
+ export const splitReferences = (value) => {
145
+ if (!value)
146
+ return [];
147
+ return value
148
+ .split(/\s+/u)
149
+ .map((token) => token.trim())
150
+ .filter((token) => token.length > 0);
151
+ };
152
+ /**
153
+ * Recovers a normalized headers map from Mailgun's `message-headers` form
154
+ * field (a JSON-encoded array of `[name, value]` tuples, e.g.
155
+ * `[["Received","by ..."],["From","alice@example.com"]]`).
156
+ *
157
+ * Field names are lowercased; multi-value headers are returned as arrays.
158
+ * Falls back to an empty record when the field is absent or invalid JSON.
159
+ *
160
+ * @param raw - The raw `message-headers` form field value.
161
+ * @returns Normalized headers map.
162
+ */
163
+ export const parseMailgunMessageHeaders = (raw) => {
164
+ if (!raw)
165
+ return {};
166
+ let parsed;
167
+ try {
168
+ parsed = JSON.parse(raw);
169
+ }
170
+ catch (_error) {
171
+ // Intentional noop: invalid JSON in message-headers is a Mailgun data
172
+ // anomaly; falling back to an empty record is safe because callers treat
173
+ // a missing headers map as degraded-but-recoverable.
174
+ return {};
175
+ }
176
+ if (!Array.isArray(parsed))
177
+ return {};
178
+ const out = {};
179
+ for (const entry of parsed) {
180
+ if (!Array.isArray(entry) || entry.length < 2)
181
+ continue;
182
+ const [nameRaw, valueRaw] = entry;
183
+ if (typeof nameRaw !== 'string' || typeof valueRaw !== 'string')
184
+ continue;
185
+ const name = nameRaw.toLowerCase();
186
+ const existing = out[name];
187
+ if (existing === undefined) {
188
+ out[name] = valueRaw;
189
+ }
190
+ else if (Array.isArray(existing)) {
191
+ existing.push(valueRaw);
192
+ }
193
+ else {
194
+ out[name] = [existing, valueRaw];
195
+ }
196
+ }
197
+ return out;
198
+ };
199
+ /**
200
+ * Strips surrounding angle brackets from a `Message-ID` value.
201
+ *
202
+ * @param value - The raw value (with or without angle brackets).
203
+ * @returns The value without angle brackets, or `undefined` if input was empty.
204
+ */
205
+ export const unwrapMessageId = (value) => {
206
+ if (!value)
207
+ return undefined;
208
+ const trimmed = value.trim();
209
+ if (trimmed.length === 0)
210
+ return undefined;
211
+ return trimmed.replace(/^<|>$/gu, '');
212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AC,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAA;QAClC,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,KAAyB,EAAsB,EAAE;IAC/E,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAA;IAC5B,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAA;IAC5B,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAA;IAC1C,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;AACvC,CAAC,CAAA"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@molecule/api-emails-inbound-mailgun",
3
+ "version": "1.0.0",
4
+ "description": "Mailgun Routes inbound email provider — parses inbound email webhook payloads into normalized InboundEmail.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "emails",
25
+ "inbound",
26
+ "mailgun",
27
+ "routes",
28
+ "webhook"
29
+ ],
30
+ "license": "Apache-2.0",
31
+ "devDependencies": {
32
+ "@molecule/api-emails": "1.0.0",
33
+ "@molecule/api-emails-inbound": "1.0.0",
34
+ "@types/node": "26.1.2",
35
+ "typescript": "6.0.3",
36
+ "vitest": "4.1.10"
37
+ },
38
+ "peerDependencies": {
39
+ "@molecule/api-emails": "^1.0.0",
40
+ "@molecule/api-emails-inbound": "^1.0.0",
41
+ "@molecule/api-secrets": "^1.0.0"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/molecule-dev/molecule.git",
46
+ "directory": "packages/api/bonds/emails-inbound/mailgun"
47
+ },
48
+ "homepage": "https://github.com/molecule-dev/molecule/tree/main/packages/api/bonds/emails-inbound/mailgun",
49
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }