@hogsend/plugin-postmark 0.10.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,93 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ Copyright 2025 Doug Silkstone and Hogsend contributors
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor's trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising out
70
+ of these terms or the use or nature of the software, under any kind of legal
71
+ claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that organization.
84
+ **control** means ownership of substantially all the assets of an entity, or the
85
+ power to direct its management and policies by vote, contract, or otherwise.
86
+ Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # @hogsend/plugin-postmark
2
+
3
+ Postmark email delivery for [Hogsend](https://github.com/dougwithseismic/hogsend):
4
+ single + batch sends and webhook parsing/verification, normalized into the
5
+ provider-neutral `EmailEvent` the engine consumes.
6
+
7
+ `createPostmarkProvider` implements the `EmailProvider` contract — the contract
8
+ itself lives in `@hogsend/core` (canonical author import `@hogsend/engine`). It is
9
+ an **opt-in** provider: Resend stays the default. Register it explicitly (see
10
+ below) or via the `POSTMARK_SERVER_TOKEN` env preset, then make it active with
11
+ `EMAIL_PROVIDER=postmark` (or `email.defaultProvider: "postmark"`).
12
+
13
+ Two sovereign invariants Hogsend enforces through this provider:
14
+
15
+ - **First-party open/click tracking is the single source of truth.** Postmark's
16
+ native tracking is forced OFF on every send (`TrackOpens: false`,
17
+ `TrackLinks: "None"`) — `capabilities.nativeTracking` is `false` and the engine
18
+ trusts it.
19
+ - **The engine renders React → HTML itself** before the wire; this provider only
20
+ ever sees HTML (`HtmlBody`).
21
+
22
+ ## Opt-in usage
23
+
24
+ ```ts
25
+ import { createPostmarkProvider } from "@hogsend/plugin-postmark";
26
+ import { createHogsendClient } from "@hogsend/engine";
27
+
28
+ const client = createHogsendClient({
29
+ email: {
30
+ providers: [
31
+ createPostmarkProvider({
32
+ serverToken: process.env.POSTMARK_SERVER_TOKEN!,
33
+ // Postmark has no HMAC — webhook auth is HTTP Basic creds baked into the
34
+ // webhook URL. Unconfigured = fail-closed (status updates rejected).
35
+ webhookBasicAuth: { user: "hogsend", pass: process.env.POSTMARK_WEBHOOK_PASS! },
36
+ }),
37
+ ],
38
+ defaultProvider: "postmark",
39
+ },
40
+ });
41
+ ```
42
+
43
+ Postmark has no native scheduled send (`capabilities.scheduledSend` is `false`):
44
+ a `scheduledAt` is logged + dropped by the engine — use `ctx.sleepUntil` instead.
45
+
46
+ This package ships raw TypeScript source; consumers bundle it via their own build
47
+ (tsup `noExternal`). See the
48
+ [release model](https://github.com/dougwithseismic/hogsend/blob/main/docs/RELEASING.md).
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@hogsend/plugin-postmark",
3
+ "version": "0.10.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/dougwithseismic/hogsend.git",
9
+ "directory": "packages/plugin-postmark"
10
+ },
11
+ "sideEffects": false,
12
+ "main": "./src/index.ts",
13
+ "types": "./src/index.ts",
14
+ "exports": {
15
+ ".": "./src/index.ts"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "postmark": "^4.0.7",
26
+ "@hogsend/core": "^0.10.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^22.0.0",
30
+ "tsup": "^8.0.0",
31
+ "typescript": "^5.7.0",
32
+ "vitest": "^4.1.7",
33
+ "@repo/typescript-config": "^0.0.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup",
37
+ "check-types": "tsc --noEmit",
38
+ "test": "vitest run",
39
+ "test:watch": "vitest watch"
40
+ }
41
+ }
@@ -0,0 +1,335 @@
1
+ import { WebhookHandshakeSignal } from "@hogsend/core";
2
+ import { Models } from "postmark";
3
+ import { beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+ // Capture the args every ServerClient method is called with, so we can assert on
6
+ // the wire mapping without hitting the network.
7
+ const sendEmail = vi.fn();
8
+ const sendEmailBatch = vi.fn();
9
+
10
+ vi.mock("postmark", async () => {
11
+ const actual = await vi.importActual<typeof import("postmark")>("postmark");
12
+ class MockServerClient {
13
+ sendEmail = sendEmail;
14
+ sendEmailBatch = sendEmailBatch;
15
+ }
16
+ return {
17
+ ...actual,
18
+ ServerClient: MockServerClient,
19
+ };
20
+ });
21
+
22
+ // Imported AFTER the mock so the provider picks up the mocked ServerClient.
23
+ const { classifyPostmarkBounce, createPostmarkProvider, parsePostmarkWebhook } =
24
+ await import("../index.js");
25
+
26
+ const SEND_OK = { ErrorCode: 0, Message: "OK", MessageID: "pm_msg_1" };
27
+
28
+ beforeEach(() => {
29
+ sendEmail.mockReset();
30
+ sendEmailBatch.mockReset();
31
+ });
32
+
33
+ describe("send → Postmark message mapping", () => {
34
+ it("forces native tracking OFF and maps neutral fields to Postmark", async () => {
35
+ sendEmail.mockResolvedValue(SEND_OK);
36
+ const provider = createPostmarkProvider({ serverToken: "pm_token" });
37
+
38
+ const result = await provider.send({
39
+ from: "from@hogsend.com",
40
+ to: ["a@example.com", "b@example.com"],
41
+ cc: "cc@example.com",
42
+ subject: "Hello",
43
+ html: "<p>hi</p>",
44
+ text: "hi",
45
+ replyTo: "reply@hogsend.com",
46
+ tags: [
47
+ { name: "welcome", value: "onboarding" },
48
+ { name: "userId", value: "u_1" },
49
+ ],
50
+ headers: { "X-Custom": "v" },
51
+ });
52
+
53
+ expect(result).toEqual({ id: "pm_msg_1" });
54
+ // biome-ignore lint/style/noNonNullAssertion: the mock was just invoked.
55
+ const msg = sendEmail.mock.calls[0]![0];
56
+ // Sovereign invariant: native open/click tracking is forced off per-send.
57
+ expect(msg.TrackOpens).toBe(false);
58
+ expect(msg.TrackLinks).toBe(Models.LinkTrackingOptions.None);
59
+ // HTML-only wire — no React ever reaches Postmark.
60
+ expect(msg.HtmlBody).toBe("<p>hi</p>");
61
+ expect(msg.TextBody).toBe("hi");
62
+ expect("react" in msg).toBe(false);
63
+ // Recipient lists are joined into Postmark's comma string format.
64
+ expect(msg.To).toBe("a@example.com,b@example.com");
65
+ expect(msg.Cc).toBe("cc@example.com");
66
+ expect(msg.From).toBe("from@hogsend.com");
67
+ expect(msg.ReplyTo).toBe("reply@hogsend.com");
68
+ expect(msg.Subject).toBe("Hello");
69
+ // First tag's value → Postmark `Tag`; ALL tags → `Metadata` name→value.
70
+ expect(msg.Tag).toBe("onboarding");
71
+ expect(msg.Metadata).toEqual({ welcome: "onboarding", userId: "u_1" });
72
+ expect(msg.Headers).toEqual([{ Name: "X-Custom", Value: "v" }]);
73
+ expect(msg.MessageStream).toBe("outbound");
74
+ });
75
+
76
+ it("honors a custom message stream", async () => {
77
+ sendEmail.mockResolvedValue(SEND_OK);
78
+ const provider = createPostmarkProvider({
79
+ serverToken: "pm_token",
80
+ messageStream: "broadcasts",
81
+ });
82
+ await provider.send({
83
+ from: "f@h.com",
84
+ to: "t@h.com",
85
+ subject: "s",
86
+ html: "<p>x</p>",
87
+ });
88
+ // biome-ignore lint/style/noNonNullAssertion: the mock was just invoked.
89
+ expect(sendEmail.mock.calls[0]![0].MessageStream).toBe("broadcasts");
90
+ });
91
+
92
+ it("throws on a non-zero Postmark ErrorCode", async () => {
93
+ sendEmail.mockResolvedValue({
94
+ ErrorCode: 406,
95
+ Message: "Inactive recipient",
96
+ MessageID: "",
97
+ });
98
+ const provider = createPostmarkProvider({ serverToken: "pm_token" });
99
+ await expect(
100
+ provider.send({
101
+ from: "f@h.com",
102
+ to: "t@h.com",
103
+ subject: "s",
104
+ html: "<p>x</p>",
105
+ }),
106
+ ).rejects.toThrow("Postmark 406: Inactive recipient");
107
+ });
108
+
109
+ it("sendBatch forces tracking off on every item and maps ids", async () => {
110
+ sendEmailBatch.mockResolvedValue([
111
+ { ErrorCode: 0, Message: "OK", MessageID: "pm_a" },
112
+ { ErrorCode: 0, Message: "OK", MessageID: "pm_b" },
113
+ ]);
114
+ const provider = createPostmarkProvider({ serverToken: "pm_token" });
115
+ const { results } = await provider.sendBatch([
116
+ { from: "f@h.com", to: "a@h.com", subject: "s", html: "<p>a</p>" },
117
+ { from: "f@h.com", to: "b@h.com", subject: "s", html: "<p>b</p>" },
118
+ ]);
119
+ expect(results).toEqual([{ id: "pm_a" }, { id: "pm_b" }]);
120
+ // biome-ignore lint/style/noNonNullAssertion: the mock was just invoked.
121
+ const messages = sendEmailBatch.mock.calls[0]![0];
122
+ for (const m of messages) {
123
+ expect(m.TrackOpens).toBe(false);
124
+ expect(m.TrackLinks).toBe(Models.LinkTrackingOptions.None);
125
+ }
126
+ });
127
+ });
128
+
129
+ describe("verifyWebhook fail-closed auth", () => {
130
+ const payload = JSON.stringify({
131
+ RecordType: "Delivery",
132
+ MessageID: "pm_msg_1",
133
+ Recipient: "user@example.com",
134
+ DeliveredAt: "2024-01-01T00:00:00Z",
135
+ });
136
+ const basicAuth = { user: "hogsend", pass: "secret" };
137
+ const goodHeader = `Basic ${Buffer.from("hogsend:secret").toString("base64")}`;
138
+
139
+ it("FAILS CLOSED when webhook auth is unconfigured", () => {
140
+ const provider = createPostmarkProvider({ serverToken: "pm_token" });
141
+ expect(() =>
142
+ provider.verifyWebhook({
143
+ payload,
144
+ headers: { authorization: goodHeader },
145
+ }),
146
+ ).toThrow("Postmark webhook auth not configured");
147
+ });
148
+
149
+ it("rejects a missing Authorization header", () => {
150
+ const provider = createPostmarkProvider({
151
+ serverToken: "pm_token",
152
+ webhookBasicAuth: basicAuth,
153
+ });
154
+ expect(() => provider.verifyWebhook({ payload, headers: {} })).toThrow(
155
+ "Postmark webhook auth failed",
156
+ );
157
+ });
158
+
159
+ it("rejects a mismatched Authorization header", () => {
160
+ const provider = createPostmarkProvider({
161
+ serverToken: "pm_token",
162
+ webhookBasicAuth: basicAuth,
163
+ });
164
+ const wrong = `Basic ${Buffer.from("hogsend:wrong").toString("base64")}`;
165
+ expect(() =>
166
+ provider.verifyWebhook({ payload, headers: { authorization: wrong } }),
167
+ ).toThrow("Postmark webhook auth failed");
168
+ });
169
+
170
+ it("accepts the correct Basic creds and returns a normalized event", async () => {
171
+ const provider = createPostmarkProvider({
172
+ serverToken: "pm_token",
173
+ webhookBasicAuth: basicAuth,
174
+ });
175
+ // verifyWebhook may be sync OR async per the contract — await covers both.
176
+ const event = await provider.verifyWebhook({
177
+ payload,
178
+ headers: { authorization: goodHeader },
179
+ });
180
+ expect(event.type).toBe("email.delivered");
181
+ expect(event.messageId).toBe("pm_msg_1");
182
+ expect(event.recipients).toEqual(["user@example.com"]);
183
+ });
184
+ });
185
+
186
+ describe("parsePostmarkWebhook RecordType → EmailEvent", () => {
187
+ it("maps Delivery → email.delivered", () => {
188
+ const event = parsePostmarkWebhook(
189
+ JSON.stringify({
190
+ RecordType: "Delivery",
191
+ MessageID: "pm_1",
192
+ Recipient: "u@example.com",
193
+ DeliveredAt: "2024-01-01T00:00:00Z",
194
+ }),
195
+ );
196
+ expect(event.type).toBe("email.delivered");
197
+ expect(event.occurredAt).toBe("2024-01-01T00:00:00Z");
198
+ });
199
+
200
+ it("maps Open → email.opened (native echo, status no-op)", () => {
201
+ const event = parsePostmarkWebhook(
202
+ JSON.stringify({
203
+ RecordType: "Open",
204
+ MessageID: "pm_1",
205
+ Recipient: "u@example.com",
206
+ ReceivedAt: "2024-01-01T00:01:00Z",
207
+ }),
208
+ );
209
+ expect(event.type).toBe("email.opened");
210
+ });
211
+
212
+ it("maps Click → email.clicked with the click payload", () => {
213
+ const event = parsePostmarkWebhook(
214
+ JSON.stringify({
215
+ RecordType: "Click",
216
+ MessageID: "pm_1",
217
+ Recipient: "u@example.com",
218
+ ReceivedAt: "2024-01-01T00:02:00Z",
219
+ OriginalLink: "https://hogsend.com/x",
220
+ UserAgent: "Mozilla",
221
+ }),
222
+ );
223
+ expect(event.type).toBe("email.clicked");
224
+ expect(event.click).toEqual({
225
+ url: "https://hogsend.com/x",
226
+ at: "2024-01-01T00:02:00Z",
227
+ ua: "Mozilla",
228
+ });
229
+ });
230
+
231
+ it("maps SpamComplaint → email.complained (class: complaint)", () => {
232
+ const event = parsePostmarkWebhook(
233
+ JSON.stringify({
234
+ RecordType: "SpamComplaint",
235
+ MessageID: "pm_1",
236
+ Email: "u@example.com",
237
+ BouncedAt: "2024-01-01T00:00:00Z",
238
+ Description: "User marked as spam",
239
+ }),
240
+ );
241
+ expect(event.type).toBe("email.complained");
242
+ expect(event.bounce).toEqual({
243
+ class: "complaint",
244
+ code: "SpamComplaint",
245
+ reason: "User marked as spam",
246
+ });
247
+ expect(event.recipients).toEqual(["u@example.com"]);
248
+ });
249
+
250
+ it("throws WebhookHandshakeSignal for a non-status RecordType", () => {
251
+ expect(() =>
252
+ parsePostmarkWebhook(
253
+ JSON.stringify({
254
+ RecordType: "SubscriptionChange",
255
+ MessageID: "pm_1",
256
+ Recipient: "u@example.com",
257
+ }),
258
+ ),
259
+ ).toThrow(WebhookHandshakeSignal);
260
+ });
261
+ });
262
+
263
+ describe("Bounce TypeCode → class mapping", () => {
264
+ // The spec table: HardBounce=1, Transient=2, DnsError=256,
265
+ // SpamNotification=512, SoftBounce=4096, BadEmailAddress=100000,
266
+ // SpamComplaint=100001, Blocked=100006.
267
+ const cases: Array<[number, string, string]> = [
268
+ [1, "HardBounce", "permanent"],
269
+ [2, "Transient", "transient"],
270
+ [256, "DnsError", "transient"],
271
+ [512, "SpamNotification", "complaint"],
272
+ [4096, "SoftBounce", "transient"],
273
+ [100000, "BadEmailAddress", "permanent"],
274
+ [100001, "SpamComplaint", "complaint"],
275
+ [100006, "Blocked", "permanent"],
276
+ ];
277
+
278
+ for (const [typeCode, , expected] of cases) {
279
+ it(`TypeCode ${typeCode} → ${expected}`, () => {
280
+ expect(classifyPostmarkBounce(typeCode)).toBe(expected);
281
+ });
282
+ }
283
+
284
+ it("maps a permanent Bounce → email.bounced class:permanent", () => {
285
+ const event = parsePostmarkWebhook(
286
+ JSON.stringify({
287
+ RecordType: "Bounce",
288
+ MessageID: "pm_1",
289
+ Email: "u@example.com",
290
+ TypeCode: 1,
291
+ Type: "HardBounce",
292
+ BouncedAt: "2024-01-01T00:00:00Z",
293
+ Description: "Mailbox not found",
294
+ }),
295
+ );
296
+ expect(event.type).toBe("email.bounced");
297
+ expect(event.bounce).toEqual({
298
+ class: "permanent",
299
+ code: "HardBounce",
300
+ reason: "Mailbox not found",
301
+ });
302
+ });
303
+
304
+ it("maps a transient (soft) Bounce → email.bounced class:transient", () => {
305
+ const event = parsePostmarkWebhook(
306
+ JSON.stringify({
307
+ RecordType: "Bounce",
308
+ MessageID: "pm_1",
309
+ Email: "u@example.com",
310
+ TypeCode: 4096,
311
+ Type: "SoftBounce",
312
+ BouncedAt: "2024-01-01T00:00:00Z",
313
+ }),
314
+ );
315
+ // Recorded as bounced, carrying transient class — the engine records but
316
+ // does NOT increment the suppression counter for these.
317
+ expect(event.type).toBe("email.bounced");
318
+ expect(event.bounce?.class).toBe("transient");
319
+ });
320
+
321
+ it("routes a complaint-class Bounce → email.complained", () => {
322
+ const event = parsePostmarkWebhook(
323
+ JSON.stringify({
324
+ RecordType: "Bounce",
325
+ MessageID: "pm_1",
326
+ Email: "u@example.com",
327
+ TypeCode: 100001,
328
+ Type: "SpamComplaint",
329
+ BouncedAt: "2024-01-01T00:00:00Z",
330
+ }),
331
+ );
332
+ expect(event.type).toBe("email.complained");
333
+ expect(event.bounce?.class).toBe("complaint");
334
+ });
335
+ });
package/src/index.ts ADDED
@@ -0,0 +1,253 @@
1
+ import {
2
+ type BatchEmailItem,
3
+ type BounceClass,
4
+ defineEmailProvider,
5
+ type EmailEvent,
6
+ type EmailEventType,
7
+ type EmailProvider,
8
+ joinRecipients,
9
+ type SendEmailOptions,
10
+ type SendResult,
11
+ WebhookHandshakeSignal,
12
+ } from "@hogsend/core";
13
+ import { type Message, Models, ServerClient } from "postmark";
14
+
15
+ /**
16
+ * Construction config for {@link createPostmarkProvider}.
17
+ *
18
+ * Postmark has no svix/HMAC webhook signature, so webhook authenticity is HTTP
19
+ * Basic creds baked into the webhook URL. `webhookBasicAuth` is OPTIONAL only so
20
+ * a send-only deploy can skip it — but `verifyWebhook` FAILS CLOSED when it is
21
+ * unset, so an unauthenticated status update is always rejected.
22
+ */
23
+ export interface PostmarkConfig {
24
+ /** Postmark Server API token (per-server, not the account token). */
25
+ serverToken: string;
26
+ /** Outbound message stream id. Defaults to Postmark's `"outbound"`. */
27
+ messageStream?: string;
28
+ /** HTTP Basic creds the webhook URL must present. Unset → webhooks rejected. */
29
+ webhookBasicAuth?: { user: string; pass: string };
30
+ }
31
+
32
+ /** Postmark wants comma-joined recipient strings; omit the field when empty. */
33
+ const join = (v?: string | string[]): string | undefined =>
34
+ joinRecipients(v) || undefined;
35
+
36
+ /**
37
+ * The Postmark implementation of the engine's {@link EmailProvider} contract: a
38
+ * dumb delivery + webhook parse/verify layer. All tracking, DB, preference, and
39
+ * render logic lives in the engine's `createTrackedMailer`, not here.
40
+ *
41
+ * Two sovereign invariants are enforced here:
42
+ *
43
+ * - **First-party open/click tracking is the source of truth.** Every send
44
+ * forces `TrackOpens: false` + `TrackLinks: "None"`, so `capabilities`
45
+ * declares `nativeTracking: false` and the engine trusts it.
46
+ * - **HTML-only wire.** The engine renders React → HTML itself before calling
47
+ * `send`; Postmark only ever sees `HtmlBody`.
48
+ *
49
+ * Opt-in only — Resend stays the default. Register it explicitly via
50
+ * `email.providers` (or the `POSTMARK_SERVER_TOKEN` env preset) and activate it
51
+ * with `EMAIL_PROVIDER=postmark` / `email.defaultProvider: "postmark"`.
52
+ */
53
+ export function createPostmarkProvider(cfg: PostmarkConfig): EmailProvider {
54
+ const client = new ServerClient(cfg.serverToken);
55
+ const stream = cfg.messageStream ?? "outbound";
56
+
57
+ const toMessage = (o: SendEmailOptions | BatchEmailItem): Message => {
58
+ // Postmark has a single `Tag` (first tag's value) + a `Metadata` record (all
59
+ // tags as name→value). Omit each when there are no tags.
60
+ const tags = o.tags ?? [];
61
+ const message: Message = {
62
+ From: o.from,
63
+ To: join(o.to),
64
+ Cc: join(o.cc),
65
+ Bcc: join(o.bcc),
66
+ Subject: o.subject,
67
+ // The engine ALWAYS renders React → HTML before the wire — no React here.
68
+ HtmlBody: o.html,
69
+ TextBody: o.text,
70
+ ReplyTo: join(o.replyTo),
71
+ Tag: tags[0]?.value,
72
+ Metadata:
73
+ tags.length > 0
74
+ ? Object.fromEntries(tags.map((t) => [t.name, t.value]))
75
+ : undefined,
76
+ Headers: o.headers
77
+ ? Object.entries(o.headers).map(([Name, Value]) => ({ Name, Value }))
78
+ : undefined,
79
+ // NATIVE TRACKING OFF — first-party open/click tracking is sovereign.
80
+ TrackOpens: false,
81
+ TrackLinks: Models.LinkTrackingOptions.None,
82
+ MessageStream: stream,
83
+ };
84
+ return message;
85
+ };
86
+
87
+ return defineEmailProvider({
88
+ meta: { id: "postmark", name: "Postmark" },
89
+ capabilities: {
90
+ // Forced off per-send above → the engine TRUSTS native tracking is off.
91
+ nativeTracking: false,
92
+ // No native scheduled send — the engine drops `scheduledAt` with a WARN.
93
+ scheduledSend: false,
94
+ // No HMAC scheme — webhooks fail-closed on HTTP Basic creds instead.
95
+ signedWebhooks: false,
96
+ },
97
+
98
+ async send(o: SendEmailOptions): Promise<SendResult> {
99
+ const r = await client.sendEmail(toMessage(o));
100
+ if (r.ErrorCode !== 0) {
101
+ throw new Error(`Postmark ${r.ErrorCode}: ${r.Message}`);
102
+ }
103
+ return { id: r.MessageID } satisfies SendResult;
104
+ },
105
+
106
+ async sendBatch(
107
+ items: BatchEmailItem[],
108
+ ): Promise<{ results: SendResult[] }> {
109
+ const r = await client.sendEmailBatch(items.map(toMessage));
110
+ return { results: r.map((x) => ({ id: x.MessageID })) };
111
+ },
112
+
113
+ /**
114
+ * Postmark has no svix/HMAC — webhook authenticity is HTTP Basic creds in
115
+ * the webhook URL. FAIL CLOSED when creds are unconfigured or mismatched so
116
+ * an unauthenticated status update is always rejected.
117
+ */
118
+ verifyWebhook(opts: {
119
+ payload: string;
120
+ headers: Record<string, string>;
121
+ }): EmailEvent {
122
+ if (!cfg.webhookBasicAuth) {
123
+ throw new Error("Postmark webhook auth not configured");
124
+ }
125
+ const expected = `Basic ${Buffer.from(
126
+ `${cfg.webhookBasicAuth.user}:${cfg.webhookBasicAuth.pass}`,
127
+ ).toString("base64")}`;
128
+ if (opts.headers.authorization !== expected) {
129
+ throw new Error("Postmark webhook auth failed");
130
+ }
131
+ return parsePostmarkWebhook(opts.payload);
132
+ },
133
+
134
+ parseWebhook(payload: string): EmailEvent {
135
+ return parsePostmarkWebhook(payload);
136
+ },
137
+ });
138
+ }
139
+
140
+ /**
141
+ * Postmark `Bounce.TypeCode` values, mapped to provider-neutral bounce classes.
142
+ * The raw string `Type` is preserved in `bounce.code` so nothing is lost.
143
+ *
144
+ * - `complaint` → immediate suppress via the complaint path.
145
+ * - `transient` → recorded as `email.bounced` but does NOT suppress.
146
+ * - `permanent` → auto-suppress (the engine increments `bounceCount`).
147
+ *
148
+ * @see https://postmarkapp.com/developer/api/bounce-api#bounce-types
149
+ */
150
+ const COMPLAINT_TYPE_CODES = new Set<number>([
151
+ 512, // SpamNotification
152
+ 100001, // SpamComplaint
153
+ ]);
154
+ const TRANSIENT_TYPE_CODES = new Set<number>([
155
+ 2, // Transient
156
+ 256, // DnsError
157
+ 4096, // SoftBounce
158
+ ]);
159
+
160
+ /** Map a Postmark `Bounce.TypeCode` → provider-neutral bounce class. */
161
+ export function classifyPostmarkBounce(typeCode: number): BounceClass {
162
+ if (COMPLAINT_TYPE_CODES.has(typeCode)) return "complaint";
163
+ if (TRANSIENT_TYPE_CODES.has(typeCode)) return "transient";
164
+ // Default conservative for a delivery-status Bounce record is `permanent`
165
+ // (HardBounce=1, BadEmailAddress=100000, Blocked=100006, …) — these are the
166
+ // states that SHOULD auto-suppress.
167
+ return "permanent";
168
+ }
169
+
170
+ /**
171
+ * Adapt Postmark's verbatim webhook payload into the provider-neutral
172
+ * {@link EmailEvent}. Maps `RecordType` → event type, `MessageID` →
173
+ * `messageId`, `Recipient`/`Email` → `recipients`, and the `Bounce.TypeCode`
174
+ * table → `bounce.class`. Non-delivery-status records (e.g. SubscriptionChange)
175
+ * throw {@link WebhookHandshakeSignal} — the engine's webhook route 200s those.
176
+ */
177
+ export function parsePostmarkWebhook(payload: string): EmailEvent {
178
+ const p = JSON.parse(payload) as Record<string, unknown>;
179
+ const recipients = [p.Recipient ?? p.Email].filter(
180
+ (x): x is string => typeof x === "string" && x.length > 0,
181
+ );
182
+ const base = {
183
+ messageId: (p.MessageID as string) ?? "",
184
+ recipients,
185
+ raw: p,
186
+ };
187
+
188
+ switch (p.RecordType as string) {
189
+ case "Delivery":
190
+ return {
191
+ ...base,
192
+ type: "email.delivered" as EmailEventType,
193
+ occurredAt: (p.DeliveredAt as string) ?? new Date().toISOString(),
194
+ };
195
+ case "Open":
196
+ // Only arrives if native tracking is on — we keep it off, so this is a
197
+ // status no-op echo at most. First-party tracking owns opens.
198
+ return {
199
+ ...base,
200
+ type: "email.opened" as EmailEventType,
201
+ occurredAt: (p.ReceivedAt as string) ?? new Date().toISOString(),
202
+ };
203
+ case "Click":
204
+ // Same as Open — first-party owns clicks; native echo only.
205
+ return {
206
+ ...base,
207
+ type: "email.clicked" as EmailEventType,
208
+ occurredAt: (p.ReceivedAt as string) ?? new Date().toISOString(),
209
+ click: {
210
+ url: (p.OriginalLink as string) ?? "",
211
+ ...(p.ReceivedAt ? { at: p.ReceivedAt as string } : {}),
212
+ ...(p.UserAgent ? { ua: p.UserAgent as string } : {}),
213
+ },
214
+ };
215
+ case "SpamComplaint":
216
+ return {
217
+ ...base,
218
+ type: "email.complained" as EmailEventType,
219
+ occurredAt: (p.BouncedAt as string) ?? new Date().toISOString(),
220
+ bounce: {
221
+ class: "complaint",
222
+ code: "SpamComplaint",
223
+ ...(p.Description ? { reason: p.Description as string } : {}),
224
+ },
225
+ };
226
+ case "Bounce": {
227
+ const typeCode = Number(p.TypeCode ?? 0);
228
+ const cls = classifyPostmarkBounce(typeCode);
229
+ // Map BOTH transient + permanent → email.bounced, carrying bounce.class so
230
+ // the ENGINE decides suppression (only `permanent` increments bounceCount;
231
+ // `transient` is recorded but never suppresses). Do NOT map transient →
232
+ // email.delivery_delayed (the engine no-ops that).
233
+ return {
234
+ ...base,
235
+ type: (cls === "complaint"
236
+ ? "email.complained"
237
+ : "email.bounced") as EmailEventType,
238
+ occurredAt: (p.BouncedAt as string) ?? new Date().toISOString(),
239
+ bounce: {
240
+ class: cls,
241
+ code: (p.Type as string) ?? String(typeCode),
242
+ ...(p.Description ? { reason: p.Description as string } : {}),
243
+ },
244
+ };
245
+ }
246
+ default:
247
+ // SubscriptionChange and other non-delivery-status records are NOT email
248
+ // events. Throw the typed handshake skip — the engine route 200s it.
249
+ throw new WebhookHandshakeSignal(
250
+ `ignored RecordType ${String(p.RecordType)}`,
251
+ );
252
+ }
253
+ }