@neon-pixels/inbound-email 0.0.0 → 0.4.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neon Pixels Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # @neon-pixels/inbound-email
2
+
3
+ Receive email through [Resend](https://resend.com/docs/dashboard/receiving/introduction) without framework glue: verify the webhook, fetch the message, and get one normalized `InboundEmail`. Zero runtime dependencies; signatures are checked with Node's built-in `crypto`, and nothing is read from `process.env`.
4
+
5
+ Routing a message to a user and deciding what to do with it stay in your app.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @neon-pixels/inbound-email
11
+ ```
12
+
13
+ ## How it works
14
+
15
+ Resend's `email.received` webhook carries **metadata only** (ids, addresses, subject, attachment list). The body and headers are fetched with a second API call. Deliveries are signed with Svix (`svix-id`, `svix-timestamp`, `svix-signature` over the raw body), so an unverified request must never reach the fetch step.
16
+
17
+ Follow this order in your route:
18
+
19
+ 1. **Verify.** `verifyInboundWebhook` on the raw body. Answer 400 for the three request errors; answer 5xx for a missing secret so Resend retries.
20
+ 2. **De-duplicate** on the delivery id (`svix-id`, reused by retries) and skip work already done.
21
+ 3. **Fetch** the message with `fetchReceivedEmail`. Retry later (answer 5xx) when `error.retryable` is true.
22
+ 4. **Route** with `findRecipient`.
23
+ 5. **Store** the result.
24
+
25
+ ```ts
26
+ import {
27
+ FetchReceivedEmailError,
28
+ InboundWebhookError,
29
+ MissingWebhookSecretError,
30
+ fetchReceivedEmail,
31
+ findRecipient,
32
+ parseInboundEvent,
33
+ verifyInboundWebhook,
34
+ } from "@neon-pixels/inbound-email";
35
+
36
+ export async function handle(
37
+ request: Request,
38
+ config: { secret: string; apiKey: string },
39
+ ) {
40
+ const rawBody = await request.text();
41
+
42
+ let verified;
43
+ try {
44
+ verified = verifyInboundWebhook({
45
+ rawBody,
46
+ headers: request.headers,
47
+ secret: config.secret,
48
+ });
49
+ } catch (error) {
50
+ if (error instanceof MissingWebhookSecretError) {
51
+ return new Response("misconfigured", { status: 503 });
52
+ }
53
+ if (error instanceof InboundWebhookError) {
54
+ return new Response(error.code, { status: 400 });
55
+ }
56
+ throw error;
57
+ }
58
+
59
+ const parsed = parseInboundEvent(verified.event, verified.deliveryId);
60
+ if (parsed.kind === "ignored") {
61
+ return new Response("ignored", { status: 200 });
62
+ }
63
+
64
+ // De-duplicate on parsed.deliveryId here.
65
+
66
+ try {
67
+ const email = await fetchReceivedEmail(parsed.emailId, {
68
+ apiKey: config.apiKey,
69
+ });
70
+ const recipient = findRecipient(email, { domain: "inbound.example.com" });
71
+ // Map recipient.local to a user, then store the email.
72
+ } catch (error) {
73
+ const misconfigured =
74
+ error instanceof FetchReceivedEmailError &&
75
+ (error.status === 401 || error.status === 403);
76
+ if (misconfigured) {
77
+ return new Response("misconfigured", { status: 503 });
78
+ }
79
+ if (error instanceof FetchReceivedEmailError && !error.retryable) {
80
+ return new Response("unfetchable", { status: 200 });
81
+ }
82
+ throw error;
83
+ }
84
+ return new Response("ok");
85
+ }
86
+ ```
87
+
88
+ ## API
89
+
90
+ - `verifyInboundWebhook({ rawBody, headers, secret, now?, toleranceSeconds? })` returns `{ deliveryId, event }` or throws. `headers` is a `Headers` object or a plain object (names are matched case-insensitively). The tolerance defaults to 300 seconds, in both directions. The signature is checked first, so a stale error means the request is authentic but old. The error classes, all extending `InboundWebhookError` with a `code`:
91
+ - `MissingWebhookHeadersError` (`missing-headers`)
92
+ - `InvalidWebhookSignatureError` (`invalid-signature`; also a body that is not JSON)
93
+ - `StaleWebhookTimestampError` (`stale-timestamp`)
94
+ - `MissingWebhookSecretError` (`missing-secret`; checked first)
95
+ - `parseInboundEvent(event, deliveryId?)` returns `{ kind: "received", emailId, deliveryId, messageId, from, to, cc, bcc, receivedFor, subject, attachments, receivedAt }`, or `{ kind: "ignored", reason, type }` for any other event type or a malformed one. It never throws.
96
+ - `fetchReceivedEmail(emailId, { apiKey, fetch?, timeoutMs? })` returns an `InboundEmail`. The timeout defaults to 10 seconds. Failures throw `FetchReceivedEmailError` with `reason` (`http`, `timeout`, `network`, `invalid-response`), `status` (`null` when no response arrived), and `retryable` (true for 408, 429, 5xx, timeouts, and network failures; false for 404 and other 4xx; a 401 or 403 means the API key is wrong, which your app may prefer to answer with a 5xx so deliveries are retried after you fix it). Messages never contain the API key.
97
+ - `findRecipient(email, { domain })` returns `{ address, local, tag, domain }` for the first address at `domain` (exact match, case-insensitive), looking at `receivedFor`, then `to`, `cc`, `bcc`; or `null`. The tag is whatever follows the first `+` in the local part.
98
+ - Types: `InboundEmail`, `InboundAttachment`, `EmailAddress`, `InboundEmailMetadata`, `ParsedInboundEvent`, `InboundRecipient`, and more.
99
+
100
+ `InboundEmail` fields: `id`, `messageId`, `from` (`{ address, name }`), `to`, `cc`, `bcc`, `replyTo`, `receivedFor`, `subject`, `html`, `text`, `headers` (lower-cased names; a header that appears more than once is joined with a newline), `authentication` (`spf`, `dkim`, `dmarc`), `attachments` (metadata only), `receivedAt`. Missing optional values are `null`, never `undefined` or an empty string.
101
+
102
+ Attachment contents, HTML sanitizing, and de-duplication storage are not part of this package.
103
+
104
+ ## Testing your route
105
+
106
+ `@neon-pixels/inbound-email/testing` builds signed requests and Resend-shaped payloads so a route can be tested without the network:
107
+
108
+ ```ts
109
+ import {
110
+ buildReceivedEmailResponse,
111
+ buildSignedWebhookRequest,
112
+ } from "@neon-pixels/inbound-email/testing";
113
+
114
+ // Any base64 value after the "whsec_" prefix works as a test secret.
115
+ const testSecret = `whsec_${Buffer.from("test-signing-key").toString("base64")}`;
116
+ const { rawBody, headers } = buildSignedWebhookRequest({
117
+ secret: testSecret,
118
+ });
119
+ const apiResponse = buildReceivedEmailResponse({ subject: "Custom" });
120
+ ```
121
+
122
+ Also exported: `buildReceivedEmailEvent(data?)`. Pass a custom `fetch` to `fetchReceivedEmail` to return `apiResponse`.
123
+
124
+ ## Resend setup
125
+
126
+ 1. Add and verify a receiving domain in Resend (Emails > Receiving) and add its MX record.
127
+ 2. Create a webhook for the `email.received` event pointing at your route. Copy its signing secret (`whsec_...`).
128
+ 3. Create an API key that can read received emails.
129
+ 4. Store the secret and API key in your app's configuration and pass them in; this package reads no environment variables.
130
+
131
+ Documentation used: Resend [webhook verification](https://resend.com/docs/webhooks/verify-webhooks-requests), [received event](https://resend.com/docs/webhooks/emails/received), and [retrieve received email](https://resend.com/docs/api-reference/emails/retrieve-received-email) (`GET /emails/receiving/{id}`); Svix [manual verification](https://docs.svix.com/receiving/verifying-payloads/how-manual).
@@ -0,0 +1,88 @@
1
+ import { a as InboundEmail, c as ParsedInboundEvent, i as InboundAttachment, l as ReceivedEmailEvent, n as EmailAddress, o as InboundEmailMetadata, r as IgnoredInboundEvent, s as InboundRecipient, t as AuthenticationResult } from "./types-LLg9yoZK.js";
2
+ export declare const DEFAULT_TOLERANCE_SECONDS = 300;
3
+ type HeaderValue = string | string[] | null | undefined;
4
+ type WebhookHeaders = Headers | Record<string, HeaderValue>;
5
+ interface VerifyInboundWebhookOptions {
6
+ /** The request body exactly as received. Never re-serialize parsed JSON. */
7
+ rawBody: string | Uint8Array;
8
+ headers: WebhookHeaders;
9
+ /** The webhook signing secret (`whsec_...`). */
10
+ secret: string | null | undefined;
11
+ /** Current time, for tests. Defaults to now. */
12
+ now?: Date | number;
13
+ toleranceSeconds?: number;
14
+ }
15
+ interface VerifiedWebhook {
16
+ /** The `svix-id` header. Retries reuse it, so de-duplicate on it. */
17
+ deliveryId: string;
18
+ event: unknown;
19
+ }
20
+ /**
21
+ * Verifies a Resend (Svix) webhook with Node's crypto only. Signature is
22
+ * checked before freshness, so a stale error means "authentic but old".
23
+ */
24
+ export declare function verifyInboundWebhook(options: VerifyInboundWebhookOptions): VerifiedWebhook;
25
+ export declare const RECEIVED_EVENT_TYPE = "email.received";
26
+ /**
27
+ * Reads an `email.received` event. Any other event type, or a malformed one,
28
+ * returns an "ignored" result instead of throwing.
29
+ */
30
+ export declare function parseInboundEvent(event: unknown, deliveryId?: string | null): ParsedInboundEvent;
31
+ export declare const DEFAULT_TIMEOUT_MS = 10000;
32
+ interface FetchReceivedEmailOptions {
33
+ apiKey: string;
34
+ /** Injected for tests. Defaults to the global `fetch`. */
35
+ fetch?: typeof fetch;
36
+ timeoutMs?: number;
37
+ }
38
+ /** Fetches a received email from Resend and normalizes it. Throws `FetchReceivedEmailError`. */
39
+ export declare function fetchReceivedEmail(emailId: string, options: FetchReceivedEmailOptions): Promise<InboundEmail>;
40
+ interface FindRecipientOptions {
41
+ /** The app's inbound domain, such as `inbound.example.com`. Matched exactly. */
42
+ domain: string;
43
+ }
44
+ /**
45
+ * Returns the address at the inbound domain the message was delivered to.
46
+ * Received-for addresses come first so forwarded and blind-copied mail resolves.
47
+ */
48
+ export declare function findRecipient(email: Pick<InboundEmail, "receivedFor" | "to" | "cc" | "bcc">, options: FindRecipientOptions): InboundRecipient | null;
49
+ type WebhookErrorCode = "missing-headers" | "invalid-signature" | "stale-timestamp" | "missing-secret";
50
+ /** Base class for webhook verification failures. Messages are fixed text. */
51
+ export declare class InboundWebhookError extends Error {
52
+ name: string;
53
+ readonly code: WebhookErrorCode;
54
+ constructor(code: WebhookErrorCode, message: string);
55
+ }
56
+ /** One of the three svix headers is absent. Answer 400. */
57
+ export declare class MissingWebhookHeadersError extends InboundWebhookError {
58
+ name: string;
59
+ constructor();
60
+ }
61
+ /** The signature does not match the body. Answer 400 or 401. */
62
+ export declare class InvalidWebhookSignatureError extends InboundWebhookError {
63
+ name: string;
64
+ constructor(message?: string);
65
+ }
66
+ /** The signature is valid but the timestamp is outside the tolerance. */
67
+ export declare class StaleWebhookTimestampError extends InboundWebhookError {
68
+ name: string;
69
+ constructor();
70
+ }
71
+ /** The signing secret is not configured. Answer 5xx so the delivery is retried. */
72
+ export declare class MissingWebhookSecretError extends InboundWebhookError {
73
+ name: string;
74
+ constructor();
75
+ }
76
+ type FetchFailureReason = "http" | "timeout" | "network" | "invalid-response";
77
+ /**
78
+ * A failed received-email fetch. `status` is the HTTP status, or null when no
79
+ * response arrived. Messages never include the API key or response bodies.
80
+ */
81
+ export declare class FetchReceivedEmailError extends Error {
82
+ name: string;
83
+ readonly reason: FetchFailureReason;
84
+ readonly status: number | null;
85
+ readonly retryable: boolean;
86
+ constructor(reason: FetchFailureReason, status: number | null, retryable: boolean, message: string);
87
+ }
88
+ export type { AuthenticationResult, EmailAddress, FetchFailureReason, FetchReceivedEmailOptions, FindRecipientOptions, IgnoredInboundEvent, InboundAttachment, InboundEmail, InboundEmailMetadata, InboundRecipient, ParsedInboundEvent, ReceivedEmailEvent, VerifiedWebhook, VerifyInboundWebhookOptions, WebhookErrorCode, WebhookHeaders };
package/dist/index.js ADDED
@@ -0,0 +1,219 @@
1
+ import { a as InboundWebhookError, c as MissingWebhookSecretError, i as FetchReceivedEmailError, l as StaleWebhookTimestampError, o as InvalidWebhookSignatureError, r as verifyInboundWebhook, s as MissingWebhookHeadersError, t as DEFAULT_TOLERANCE_SECONDS } from "./verify-0N_laF4W.js";
2
+ // src/normalize.ts
3
+ function asRecord(value) {
4
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) return value;
5
+ return {};
6
+ }
7
+ function textOrNull(value) {
8
+ if (typeof value !== "string" || value === "") return null;
9
+ return value;
10
+ }
11
+ function stringList(value) {
12
+ if (typeof value === "string") return value === "" ? [] : [value];
13
+ if (!Array.isArray(value)) return [];
14
+ return value.filter((item) => typeof item === "string" && item !== "");
15
+ }
16
+ /** Parses `Name <a@b.c>`, `"Name" <a@b.c>`, or a bare address. */
17
+ function parseAddress(value) {
18
+ const raw = textOrNull(value)?.trim();
19
+ if (!raw) return null;
20
+ const match = /^(.*)<([^<>]+)>\s*$/.exec(raw);
21
+ if (!match) return {
22
+ address: raw,
23
+ name: null
24
+ };
25
+ const name = (match[1] ?? "").trim().replace(/^"(.*)"$/, "$1").trim();
26
+ const address = (match[2] ?? "").trim();
27
+ if (address === "") return null;
28
+ return {
29
+ address,
30
+ name: name === "" ? null : name
31
+ };
32
+ }
33
+ function normalizeHeaders(value) {
34
+ const headers = Object.create(null);
35
+ const entries = Array.isArray(value) ? value.map((item) => [asRecord(item).name, asRecord(item).value]) : Object.entries(asRecord(value));
36
+ for (const [name, headerValue] of entries) {
37
+ if (typeof name !== "string" || name === "") continue;
38
+ const text = Array.isArray(headerValue) ? headerValue.join("\n") : headerValue;
39
+ const lowerName = name.toLowerCase();
40
+ const headerText = text === void 0 || text === null ? "" : String(text);
41
+ headers[lowerName] = Object.hasOwn(headers, lowerName) ? `${headers[lowerName]}\n${headerText}` : headerText;
42
+ }
43
+ return headers;
44
+ }
45
+ const AUTHENTICATION_RESULTS = [
46
+ "pass",
47
+ "fail",
48
+ "gray",
49
+ "processing_failed",
50
+ "unknown"
51
+ ];
52
+ function authenticationResult(value) {
53
+ if (typeof value !== "string" || value === "") return null;
54
+ return AUTHENTICATION_RESULTS.includes(value) ? value : "unknown";
55
+ }
56
+ function normalizeAttachments(value) {
57
+ if (!Array.isArray(value)) return [];
58
+ return value.flatMap((item) => {
59
+ const record = asRecord(item);
60
+ const id = textOrNull(record.id);
61
+ if (id === null) return [];
62
+ return [{
63
+ id,
64
+ filename: textOrNull(record.filename),
65
+ contentType: textOrNull(record.content_type),
66
+ contentDisposition: textOrNull(record.content_disposition),
67
+ contentId: textOrNull(record.content_id),
68
+ size: typeof record.size === "number" ? record.size : null
69
+ }];
70
+ });
71
+ }
72
+ // src/parse.ts
73
+ const RECEIVED_EVENT_TYPE = "email.received";
74
+ /**
75
+ * Reads an `email.received` event. Any other event type, or a malformed one,
76
+ * returns an "ignored" result instead of throwing.
77
+ */
78
+ function parseInboundEvent(event, deliveryId) {
79
+ const record = asRecord(event);
80
+ const type = textOrNull(record.type);
81
+ if (type !== "email.received") return {
82
+ kind: "ignored",
83
+ reason: "unsupported-type",
84
+ type
85
+ };
86
+ const data = asRecord(record.data);
87
+ const emailId = textOrNull(data.email_id);
88
+ if (emailId === null) return {
89
+ kind: "ignored",
90
+ reason: "malformed",
91
+ type
92
+ };
93
+ return {
94
+ kind: "received",
95
+ emailId,
96
+ deliveryId: deliveryId ? deliveryId : null,
97
+ messageId: textOrNull(data.message_id),
98
+ from: parseAddress(data.from),
99
+ to: stringList(data.to),
100
+ cc: stringList(data.cc),
101
+ bcc: stringList(data.bcc),
102
+ receivedFor: stringList(data.received_for),
103
+ subject: textOrNull(data.subject),
104
+ attachments: normalizeAttachments(data.attachments),
105
+ receivedAt: textOrNull(data.created_at) ?? textOrNull(record.created_at)
106
+ };
107
+ }
108
+ // src/fetch-email.ts
109
+ const RESEND_RECEIVED_EMAIL_URL = "https://api.resend.com/emails/receiving/";
110
+ const DEFAULT_TIMEOUT_MS = 1e4;
111
+ const REQUEST_TIMEOUT = 408;
112
+ const TOO_MANY_REQUESTS = 429;
113
+ const SERVER_ERROR_FLOOR = 500;
114
+ function isRetryableStatus(status) {
115
+ return status === REQUEST_TIMEOUT || status === TOO_MANY_REQUESTS || status >= SERVER_ERROR_FLOOR;
116
+ }
117
+ async function request(emailId, options) {
118
+ const { apiKey, fetch: fetchFunction = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
119
+ const signal = AbortSignal.timeout(timeoutMs);
120
+ try {
121
+ return await fetchFunction(`${RESEND_RECEIVED_EMAIL_URL}${encodeURIComponent(emailId)}`, {
122
+ method: "GET",
123
+ headers: {
124
+ authorization: `Bearer ${apiKey}`,
125
+ accept: "application/json"
126
+ },
127
+ signal
128
+ });
129
+ } catch (error) {
130
+ throw transportFailure(error);
131
+ }
132
+ }
133
+ function transportFailure(error) {
134
+ const timedOut = error instanceof Error && error.name === "TimeoutError";
135
+ return new FetchReceivedEmailError(timedOut ? "timeout" : "network", null, true, timedOut ? "Resend request timed out." : "Resend request failed before a response arrived.");
136
+ }
137
+ async function readJson(response) {
138
+ try {
139
+ return asRecord(await response.json());
140
+ } catch (error) {
141
+ throw bodyReadFailure(error, response.status);
142
+ }
143
+ }
144
+ function bodyReadFailure(error, status) {
145
+ if (!(error instanceof SyntaxError)) return transportFailure(error);
146
+ return new FetchReceivedEmailError("invalid-response", status, false, "Resend returned a response that is not valid JSON.");
147
+ }
148
+ function normalizeReceivedEmail(payload) {
149
+ const id = textOrNull(payload.id);
150
+ if (id === null) return null;
151
+ const authentication = asRecord(payload.authentication);
152
+ return {
153
+ id,
154
+ messageId: textOrNull(payload.message_id),
155
+ from: parseAddress(payload.from),
156
+ to: stringList(payload.to),
157
+ cc: stringList(payload.cc),
158
+ bcc: stringList(payload.bcc),
159
+ replyTo: stringList(payload.reply_to),
160
+ receivedFor: stringList(payload.received_for),
161
+ subject: textOrNull(payload.subject),
162
+ html: textOrNull(payload.html),
163
+ text: textOrNull(payload.text),
164
+ headers: normalizeHeaders(payload.headers),
165
+ authentication: {
166
+ spf: authenticationResult(authentication.spf),
167
+ dkim: authenticationResult(authentication.dkim),
168
+ dmarc: authenticationResult(authentication.dmarc)
169
+ },
170
+ attachments: normalizeAttachments(payload.attachments),
171
+ receivedAt: textOrNull(payload.created_at)
172
+ };
173
+ }
174
+ /** Fetches a received email from Resend and normalizes it. Throws `FetchReceivedEmailError`. */
175
+ async function fetchReceivedEmail(emailId, options) {
176
+ if (emailId.trim() === "") throw new TypeError("fetchReceivedEmail requires an email id.");
177
+ if (options.timeoutMs !== void 0 && !(options.timeoutMs > 0)) throw new RangeError("fetchReceivedEmail timeoutMs must be positive.");
178
+ if (!options.apiKey?.trim()) throw new TypeError("fetchReceivedEmail requires an API key.");
179
+ const response = await request(emailId, options);
180
+ if (!response.ok) {
181
+ await response.body?.cancel().catch(() => void 0);
182
+ throw new FetchReceivedEmailError("http", response.status, isRetryableStatus(response.status), `Resend responded with HTTP ${response.status}.`);
183
+ }
184
+ const email = normalizeReceivedEmail(await readJson(response));
185
+ if (email === null) throw new FetchReceivedEmailError("invalid-response", response.status, false, "Resend response did not include an email id.");
186
+ return email;
187
+ }
188
+ // src/recipient.ts
189
+ function splitAddress(raw, domain) {
190
+ const address = parseAddress(raw)?.address.toLowerCase();
191
+ const separator = address?.lastIndexOf("@") ?? -1;
192
+ if (!address || separator < 1 || address.slice(separator + 1) !== domain) return null;
193
+ const localWithTag = address.slice(0, separator);
194
+ const plusIndex = localWithTag.indexOf("+");
195
+ const local = plusIndex === -1 ? localWithTag : localWithTag.slice(0, plusIndex);
196
+ const tag = plusIndex === -1 ? "" : localWithTag.slice(plusIndex + 1);
197
+ if (local === "") return null;
198
+ return {
199
+ address,
200
+ local,
201
+ tag: tag === "" ? null : tag,
202
+ domain
203
+ };
204
+ }
205
+ /**
206
+ * Returns the address at the inbound domain the message was delivered to.
207
+ * Received-for addresses come first so forwarded and blind-copied mail resolves.
208
+ */
209
+ function findRecipient(email, options) {
210
+ const domain = options.domain.trim().toLowerCase();
211
+ if (domain === "" || domain.includes("@") || domain.endsWith(".")) throw new TypeError("findRecipient requires a bare host name as domain.");
212
+ return [
213
+ ...email.receivedFor,
214
+ ...email.to,
215
+ ...email.cc,
216
+ ...email.bcc
217
+ ].map((raw) => splitAddress(raw, domain)).find((recipient) => recipient !== null) ?? null;
218
+ }
219
+ export { DEFAULT_TIMEOUT_MS, DEFAULT_TOLERANCE_SECONDS, FetchReceivedEmailError, InboundWebhookError, InvalidWebhookSignatureError, MissingWebhookHeadersError, MissingWebhookSecretError, RECEIVED_EVENT_TYPE, StaleWebhookTimestampError, fetchReceivedEmail, findRecipient, parseInboundEvent, verifyInboundWebhook };
@@ -0,0 +1,19 @@
1
+ import { l as ReceivedEmailEvent } from "./types-LLg9yoZK.js";
2
+ export interface SignedWebhookRequest {
3
+ rawBody: string;
4
+ headers: Record<string, string>;
5
+ }
6
+ export interface BuildSignedWebhookRequestOptions {
7
+ secret: string;
8
+ /** Object to serialize, or a string used verbatim. Defaults to a received-email event. */
9
+ body?: unknown;
10
+ id?: string;
11
+ /** Seconds since the epoch. Defaults to now. */
12
+ timestamp?: number;
13
+ }
14
+ /** Builds a request signed the way Resend (Svix) signs deliveries. */
15
+ export declare function buildSignedWebhookRequest(options: BuildSignedWebhookRequestOptions): SignedWebhookRequest;
16
+ /** A webhook `email.received` event in Resend's wire format. */
17
+ export declare function buildReceivedEmailEvent(data?: Record<string, unknown>): ReceivedEmailEvent;
18
+ /** A received-email API response in Resend's wire format. */
19
+ export declare function buildReceivedEmailResponse(overrides?: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,70 @@
1
+ import { createHmac, randomUUID } from "node:crypto";
2
+ import { n as decodeSecret } from "./verify-0N_laF4W.js";
3
+ // src/testing.ts
4
+ /** Builds a request signed the way Resend (Svix) signs deliveries. */
5
+ function buildSignedWebhookRequest(options) {
6
+ const id = options.id ?? `msg_${randomUUID()}`;
7
+ const timestamp = String(options.timestamp ?? Math.floor(Date.now() / 1e3));
8
+ const body = options.body ?? buildReceivedEmailEvent();
9
+ const rawBody = typeof body === "string" ? body : JSON.stringify(body);
10
+ const key = decodeSecret(options.secret);
11
+ return {
12
+ rawBody,
13
+ headers: {
14
+ "svix-id": id,
15
+ "svix-timestamp": timestamp,
16
+ "svix-signature": `v1,${createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64")}`
17
+ }
18
+ };
19
+ }
20
+ /** A webhook `email.received` event in Resend's wire format. */
21
+ function buildReceivedEmailEvent(data = {}) {
22
+ return {
23
+ type: "email.received",
24
+ created_at: "2026-01-02T03:04:05.000Z",
25
+ data: {
26
+ email_id: "4ef9a417-02e9-4d39-ad75-9611e0fcc33c",
27
+ created_at: "2026-01-02T03:04:04.000Z",
28
+ from: "Sender <sender@example.net>",
29
+ to: ["inbox+news@inbound.example.com"],
30
+ cc: [],
31
+ bcc: [],
32
+ message_id: "<message-1@example.net>",
33
+ subject: "Hello",
34
+ received_for: ["inbox+news@inbound.example.com"],
35
+ attachments: [],
36
+ ...data
37
+ }
38
+ };
39
+ }
40
+ /** A received-email API response in Resend's wire format. */
41
+ function buildReceivedEmailResponse(overrides = {}) {
42
+ return {
43
+ object: "email",
44
+ id: "4ef9a417-02e9-4d39-ad75-9611e0fcc33c",
45
+ to: ["inbox+news@inbound.example.com"],
46
+ from: "Sender <sender@example.net>",
47
+ created_at: "2026-01-02T03:04:04.000Z",
48
+ subject: "Hello",
49
+ html: "<p>Hello</p>",
50
+ text: "Hello",
51
+ headers: {
52
+ "Message-ID": "<message-1@example.net>",
53
+ "X-Mailer": "Example"
54
+ },
55
+ message_id: "<message-1@example.net>",
56
+ bcc: [],
57
+ cc: [],
58
+ reply_to: [],
59
+ received_for: ["inbox+news@inbound.example.com"],
60
+ authentication: {
61
+ spf: "pass",
62
+ dkim: "pass",
63
+ dmarc: "pass"
64
+ },
65
+ raw: null,
66
+ attachments: [],
67
+ ...overrides
68
+ };
69
+ }
70
+ export { buildReceivedEmailEvent, buildReceivedEmailResponse, buildSignedWebhookRequest };
@@ -0,0 +1,72 @@
1
+ type AuthenticationResult = "pass" | "fail" | "gray" | "processing_failed" | "unknown";
2
+ interface EmailAddress {
3
+ address: string;
4
+ name: string | null;
5
+ }
6
+ interface InboundAttachment {
7
+ id: string;
8
+ filename: string | null;
9
+ contentType: string | null;
10
+ contentDisposition: string | null;
11
+ contentId: string | null;
12
+ size: number | null;
13
+ }
14
+ interface InboundEmail {
15
+ id: string;
16
+ messageId: string | null;
17
+ from: EmailAddress | null;
18
+ to: string[];
19
+ cc: string[];
20
+ bcc: string[];
21
+ replyTo: string[];
22
+ /** Addresses from the `for` clause of the Received headers (the envelope recipients). */
23
+ receivedFor: string[];
24
+ subject: string | null;
25
+ html: string | null;
26
+ text: string | null;
27
+ /** Header names are lower-cased. */
28
+ headers: Record<string, string>;
29
+ authentication: {
30
+ spf: AuthenticationResult | null;
31
+ dkim: AuthenticationResult | null;
32
+ dmarc: AuthenticationResult | null;
33
+ };
34
+ /** Metadata only; contents are not downloaded. */
35
+ attachments: InboundAttachment[];
36
+ receivedAt: string | null;
37
+ }
38
+ /** The Resend `email.received` event as it arrives on the wire. */
39
+ interface ReceivedEmailEvent {
40
+ type: "email.received";
41
+ created_at?: string;
42
+ data: Record<string, unknown>;
43
+ }
44
+ interface InboundEmailMetadata {
45
+ kind: "received";
46
+ emailId: string;
47
+ /** The `svix-id` of the delivery. Retries reuse it, so de-duplicate on it. */
48
+ deliveryId: string | null;
49
+ messageId: string | null;
50
+ from: EmailAddress | null;
51
+ to: string[];
52
+ cc: string[];
53
+ bcc: string[];
54
+ receivedFor: string[];
55
+ subject: string | null;
56
+ attachments: InboundAttachment[];
57
+ receivedAt: string | null;
58
+ }
59
+ interface IgnoredInboundEvent {
60
+ kind: "ignored";
61
+ reason: "unsupported-type" | "malformed";
62
+ type: string | null;
63
+ }
64
+ type ParsedInboundEvent = InboundEmailMetadata | IgnoredInboundEvent;
65
+ interface InboundRecipient {
66
+ /** Lower-cased full address as delivered, including any plus tag. */
67
+ address: string;
68
+ local: string;
69
+ tag: string | null;
70
+ domain: string;
71
+ }
72
+ export { InboundEmail as a, ParsedInboundEvent as c, InboundAttachment as i, ReceivedEmailEvent as l, EmailAddress as n, InboundEmailMetadata as o, IgnoredInboundEvent as r, InboundRecipient as s, AuthenticationResult as t };
@@ -0,0 +1,121 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ // src/errors.ts
3
+ /** Base class for webhook verification failures. Messages are fixed text. */
4
+ var InboundWebhookError = class extends Error {
5
+ name = "InboundWebhookError";
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ }
11
+ };
12
+ /** One of the three svix headers is absent. Answer 400. */
13
+ var MissingWebhookHeadersError = class extends InboundWebhookError {
14
+ name = "MissingWebhookHeadersError";
15
+ constructor() {
16
+ super("missing-headers", "Missing svix-id, svix-timestamp, or svix-signature header.");
17
+ }
18
+ };
19
+ /** The signature does not match the body. Answer 400 or 401. */
20
+ var InvalidWebhookSignatureError = class extends InboundWebhookError {
21
+ name = "InvalidWebhookSignatureError";
22
+ constructor(message = "Webhook signature is invalid.") {
23
+ super("invalid-signature", message);
24
+ }
25
+ };
26
+ /** The signature is valid but the timestamp is outside the tolerance. */
27
+ var StaleWebhookTimestampError = class extends InboundWebhookError {
28
+ name = "StaleWebhookTimestampError";
29
+ constructor() {
30
+ super("stale-timestamp", "Webhook timestamp is outside the allowed tolerance.");
31
+ }
32
+ };
33
+ /** The signing secret is not configured. Answer 5xx so the delivery is retried. */
34
+ var MissingWebhookSecretError = class extends InboundWebhookError {
35
+ name = "MissingWebhookSecretError";
36
+ constructor() {
37
+ super("missing-secret", "Webhook signing secret is not configured.");
38
+ }
39
+ };
40
+ /**
41
+ * A failed received-email fetch. `status` is the HTTP status, or null when no
42
+ * response arrived. Messages never include the API key or response bodies.
43
+ */
44
+ var FetchReceivedEmailError = class extends Error {
45
+ name = "FetchReceivedEmailError";
46
+ reason;
47
+ status;
48
+ retryable;
49
+ constructor(reason, status, retryable, message) {
50
+ super(message);
51
+ this.reason = reason;
52
+ this.status = status;
53
+ this.retryable = retryable;
54
+ }
55
+ };
56
+ // src/verify.ts
57
+ const DEFAULT_TOLERANCE_SECONDS = 300;
58
+ const SECRET_PREFIX = "whsec_";
59
+ const SIGNATURE_VERSION = "v1";
60
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
61
+ function readHeader(headers, name) {
62
+ if (typeof headers.get === "function") return headers.get(name);
63
+ const plain = headers;
64
+ const key = Object.keys(plain).find((candidate) => candidate.toLowerCase() === name);
65
+ const value = key === void 0 ? void 0 : plain[key];
66
+ const text = Array.isArray(value) ? value[0] : value;
67
+ return text ? text : null;
68
+ }
69
+ function decodeSecret(secret) {
70
+ const trimmed = (secret ?? "").trim();
71
+ const encoded = trimmed.startsWith(SECRET_PREFIX) ? trimmed.slice(6) : trimmed;
72
+ if (!BASE64_PATTERN.test(encoded)) throw new MissingWebhookSecretError();
73
+ const key = Buffer.from(encoded, "base64");
74
+ if (key.length === 0) throw new MissingWebhookSecretError();
75
+ return key;
76
+ }
77
+ function sign(key, id, timestamp, body) {
78
+ return createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
79
+ }
80
+ function matchesAnySignature(header, expected) {
81
+ let matched = false;
82
+ for (const entry of header.split(" ")) {
83
+ const [version, encoded] = entry.split(",");
84
+ const candidate = Buffer.from(encoded ?? "", "base64");
85
+ const equal = candidate.length === expected.length && timingSafeEqual(candidate, expected);
86
+ matched = matched || version === SIGNATURE_VERSION && equal;
87
+ }
88
+ return matched;
89
+ }
90
+ function assertFresh(timestamp, now, toleranceSeconds) {
91
+ const nowSeconds = Math.floor((typeof now === "number" ? now : now.getTime()) / 1e3);
92
+ if (!(Math.abs(nowSeconds - Number(timestamp)) <= toleranceSeconds)) throw new StaleWebhookTimestampError();
93
+ }
94
+ function parseBody(body) {
95
+ try {
96
+ return JSON.parse(Buffer.from(body).toString("utf8"));
97
+ } catch {
98
+ throw new InvalidWebhookSignatureError("Webhook body is not valid JSON.");
99
+ }
100
+ }
101
+ /**
102
+ * Verifies a Resend (Svix) webhook with Node's crypto only. Signature is
103
+ * checked before freshness, so a stale error means "authentic but old".
104
+ */
105
+ function verifyInboundWebhook(options) {
106
+ const { rawBody, headers, now = Date.now(), toleranceSeconds = 300 } = options;
107
+ const key = decodeSecret(options.secret);
108
+ const id = readHeader(headers, "svix-id");
109
+ const timestamp = readHeader(headers, "svix-timestamp");
110
+ const signatures = readHeader(headers, "svix-signature");
111
+ if (!id || !timestamp || !signatures) throw new MissingWebhookHeadersError();
112
+ if (!/^\d+$/.test(timestamp)) throw new InvalidWebhookSignatureError();
113
+ const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
114
+ if (!matchesAnySignature(signatures, sign(key, id, timestamp, body))) throw new InvalidWebhookSignatureError();
115
+ assertFresh(timestamp, now, toleranceSeconds);
116
+ return {
117
+ deliveryId: id,
118
+ event: parseBody(body)
119
+ };
120
+ }
121
+ export { InboundWebhookError as a, MissingWebhookSecretError as c, FetchReceivedEmailError as i, StaleWebhookTimestampError as l, decodeSecret as n, InvalidWebhookSignatureError as o, verifyInboundWebhook as r, MissingWebhookHeadersError as s, DEFAULT_TOLERANCE_SECONDS as t };
package/package.json CHANGED
@@ -1 +1,39 @@
1
- {"name":"@neon-pixels/inbound-email","version":"0.0.0","description":"Placeholder. The first real release follows.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/neonpixels-studio/packages.git"}}
1
+ {
2
+ "name": "@neon-pixels/inbound-email",
3
+ "version": "0.4.0",
4
+ "description": "Verify Resend inbound email webhooks and fetch the received message as one normalized object.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/inbound-email"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./testing": {
18
+ "types": "./dist/testing.d.ts",
19
+ "default": "./dist/testing.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "engines": {
30
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "svix": "^1.0.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "typecheck": "tsc --noEmit -p tsconfig.json"
38
+ }
39
+ }