@krizaka/mail 0.0.0-stage → 0.1.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,201 @@
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
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @krizaka/mail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Mail for every Krizaka product: queued in the caller's transaction through `@krizaka/outbox`, delivered once per idempotency key, never to a suppressed address, with the provider the admin chose. No vendor SDK, no environment variable, no wall clock, no database client.
4
+
5
+ - **It takes mail already rendered.** Templates are `@krizaka/email`'s (a UI package this one never imports). `emailPorts(store, clock)` gives `@krizaka/email` its three ports (`DeliveryLog`, `SuppressionList`, `IdempotencyStore`) over the same tables, so a direct `sendEmail` and the queue share one log, one suppression list and one set of keys.
6
+ - **At least once, never lost.** `deliver` checks the suppression list, checks the key, sends, and only then claims the key: a crash between the send and the claim sends again (a duplicate reset mail beats a lost one); a redelivery after the claim is a no-op.
7
+ - **Addresses are hashed** (SHA-256 of the normal form) in the suppression list and in the delivery log. The queued message holds the address until the outbox purges it.
8
+ - **Providers** are adapters over an injected `fetch`: `mailgunProvider`, `resendProvider`, `logProvider` (development, writes no body). `providerFor(settings.provider, keys, fetch, write)` picks the one the admin chose and refuses a provider without its key instead of falling back to `log`.
9
+ - **Bounces and complaints** come back through the provider's signed webhook: `parseMailgunWebhook` and `parseResendWebhook` verify the signature and the age, and answer the addresses to suppress (a permanent failure or hard bounce, a complaint, an unsubscribe). A transient bounce is ignored.
10
+ - **The admin's settings** (`@krizaka/mail/settings`): `mail.provider` (`log`, `mailgun`, `resend`), `mail.from`, `mail.replyTo`, `mail.retentionDays`. Keys, the Mailgun domain and the webhook signing keys stay in the environment (`MAIL_PROVIDER`-style names, read by the product and passed in).
11
+
12
+ ```ts
13
+ import { createOutbox, runWorker } from "@krizaka/outbox";
14
+ import { createMail, dbMailStore, MAIL_TOPIC, providerFor } from "@krizaka/mail";
15
+ import { mailSettings, readMailSettings } from "@krizaka/mail/settings";
16
+
17
+ const mail = createMail({
18
+ clock,
19
+ outbox: createOutbox({ clock, settings: outboxSettings }),
20
+ settings: () => readMailSettings((key) => settings.get(key)),
21
+ store: dbMailStore(query),
22
+ provider: (s) => providerFor(s.provider, { apiKey: env.MAIL_API_KEY, domain: env.MAIL_DOMAIN }, fetch, console.log),
23
+ });
24
+
25
+ // in the use case's transaction: the mail leaves only if the transaction commits
26
+ await mail.queue(tx, { to, subject, text, category: "transactional", template: "password-reset", locale: "fr", idempotencyKey: `reset:${resetId}` });
27
+
28
+ // in the worker process
29
+ await runWorker({ outbox, query, owner, topic: MAIL_TOPIC, deliver: (m) => mail.deliver(m).then(() => undefined), sleep });
30
+
31
+ // in the webhook route
32
+ const suppression = parseMailgunWebhook(rawBody, env.MAIL_WEBHOOK_SIGNING_KEY, nowSeconds);
33
+ if (suppression) await mail.suppress(suppression);
34
+ ```
35
+
36
+ Tables (schema `mail`, `mailSchema`): `delivery`, `suppression`, `idempotency`. Event: `evt.mail.requested.v1` on topic `mail`. `mailStoreContract` (`@krizaka/mail/testkit`) is the contract every store runs.
37
+
38
+ Apache-2.0.
@@ -0,0 +1,80 @@
1
+ // src/port.ts
2
+ var SUPPRESSION_REASON = { bounce: "bounce", complaint: "complaint", unsubscribed: "unsubscribed" };
3
+ var DELIVERY_STATUS = { sent: "sent", failed: "failed", suppressed: "suppressed", duplicate: "duplicate" };
4
+ var MAIL_CODE = {
5
+ badAddress: "MAIL_BAD_ADDRESS",
6
+ badMessage: "MAIL_BAD_MESSAGE",
7
+ badSettings: "MAIL_BAD_SETTINGS",
8
+ provider: "MAIL_PROVIDER_FAILED",
9
+ badWebhook: "MAIL_BAD_WEBHOOK"
10
+ };
11
+ var MailError = class extends Error {
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = "MailError";
16
+ }
17
+ code;
18
+ };
19
+
20
+ // src/rules.ts
21
+ import { createHash } from "crypto";
22
+ var MAIL_BOUNDS = { retentionDays: [1, 3650] };
23
+ var MAIL_DEFAULTS = { provider: "log", from: "Krizaka <no-reply@krizaka.com>", replyTo: "", retentionDays: 90 };
24
+ var ADDRESS = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
25
+ var TOKEN = /^[a-z][a-z0-9_.-]{0,39}$/;
26
+ var MAX_ADDRESS = 254;
27
+ var MAX_SUBJECT = 200;
28
+ var MAX_BODY = 5e5;
29
+ var MAX_KEY = 200;
30
+ var normalizeAddress = (email) => email.trim().toLowerCase();
31
+ var hashAddress = (email) => createHash("sha256").update(normalizeAddress(email)).digest("hex");
32
+ function uuidOf(seed) {
33
+ const h = createHash("sha256").update(`krizaka.mail:${seed}`).digest();
34
+ h[6] = h[6] & 15 | 80;
35
+ h[8] = h[8] & 63 | 128;
36
+ const x = h.subarray(0, 16).toString("hex");
37
+ return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;
38
+ }
39
+ function bareAddress(from) {
40
+ const match = /<([^<>]+)>\s*$/.exec(from);
41
+ return (match?.[1] ?? from).trim();
42
+ }
43
+ var oneLine = (value) => !/[\r\n]/.test(value);
44
+ function checkAddress(address, what = "address") {
45
+ if (typeof address !== "string" || address.length > MAX_ADDRESS || !oneLine(address) || !ADDRESS.test(bareAddress(address))) throw new MailError(MAIL_CODE.badAddress, `${what} is not a valid address`);
46
+ }
47
+ function checkMessage(message) {
48
+ checkAddress(message.to, "to");
49
+ if (message.replyTo !== void 0 && message.replyTo !== "") checkAddress(message.replyTo, "replyTo");
50
+ if (typeof message.subject !== "string" || message.subject.trim() === "" || message.subject.length > MAX_SUBJECT || !oneLine(message.subject)) throw new MailError(MAIL_CODE.badMessage, "subject must be one line of 1 to 200 characters");
51
+ if (typeof message.text !== "string" || message.text.trim() === "" || message.text.length > MAX_BODY) throw new MailError(MAIL_CODE.badMessage, "text is required");
52
+ if (message.html !== void 0 && (typeof message.html !== "string" || message.html.length > MAX_BODY)) throw new MailError(MAIL_CODE.badMessage, "html is too long");
53
+ if (!TOKEN.test(message.category) || !TOKEN.test(message.template)) throw new MailError(MAIL_CODE.badMessage, "category and template are lower-case tokens");
54
+ if (typeof message.locale !== "string" || !/^[a-z]{2}(-[A-Z]{2})?$/.test(message.locale)) throw new MailError(MAIL_CODE.badMessage, "locale is a language tag like fr or en-CA");
55
+ if (typeof message.idempotencyKey !== "string" || message.idempotencyKey === "" || message.idempotencyKey.length > MAX_KEY) throw new MailError(MAIL_CODE.badMessage, "idempotencyKey is required (1 to 200 characters)");
56
+ }
57
+ function checkSettings(s) {
58
+ const [min, max] = MAIL_BOUNDS.retentionDays;
59
+ if (!Number.isInteger(s.retentionDays) || s.retentionDays < min || s.retentionDays > max) throw new MailError(MAIL_CODE.badSettings, `retentionDays must be ${min} to ${max}`);
60
+ checkAddress(s.from, "from");
61
+ if (s.replyTo !== "") checkAddress(s.replyTo, "replyTo");
62
+ return s;
63
+ }
64
+
65
+ export {
66
+ SUPPRESSION_REASON,
67
+ DELIVERY_STATUS,
68
+ MAIL_CODE,
69
+ MailError,
70
+ MAIL_BOUNDS,
71
+ MAIL_DEFAULTS,
72
+ normalizeAddress,
73
+ hashAddress,
74
+ uuidOf,
75
+ bareAddress,
76
+ checkAddress,
77
+ checkMessage,
78
+ checkSettings
79
+ };
80
+ //# sourceMappingURL=chunk-YDSARDFP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/port.ts","../src/rules.ts"],"sourcesContent":["/**\n * The ports of « mail »: a message queued in the caller's transaction and delivered after the commit, once per idempotency key,\n * never to a suppressed address. Generic: no vendor SDK (providers are adapters over an injected `fetch`), no environment variable\n * (keys come in as parameters), no wall clock, no database client. The module takes mail ALREADY RENDERED: templates are\n * `@krizaka/email`'s (a UI package this one never imports), and its three ports are satisfied structurally by `emailPorts`.\n */\nexport type { Clock, Query } from \"@krizaka/db\";\n\n/** Why an address is never mailed again. The same values as `@krizaka/email`'s `SuppressionReason`. */\nexport const SUPPRESSION_REASON = { bounce: \"bounce\", complaint: \"complaint\", unsubscribed: \"unsubscribed\" } as const;\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON];\n\n/** The mail a product queues. */\nexport interface MailMessage {\n to: string;\n subject: string;\n text: string;\n html?: string;\n /** What kind of mail it is (`transactional`, `notification`, `digest`…): lower-case token, kept in the delivery log. */\n category: string;\n /** The template that rendered it, for the log (never the body). */\n template: string;\n locale: string;\n /** One key sends once: queueing it twice is one message, and delivering it twice sends one mail. */\n idempotencyKey: string;\n /** Overrides `mail.replyTo` for this message. */\n replyTo?: string;\n}\n\n/** A mail the provider receives: the message with the sender the settings give. */\nexport interface OutgoingMail extends MailMessage {\n from: string;\n}\n\n/** What the provider answered. */\nexport interface Sent {\n messageId: string | null;\n}\n\n/** One provider of mail (an adapter over `fetch`). It resolves on acceptance and throws on any failure: the outbox retries. */\nexport interface MailProvider {\n readonly name: string;\n send(mail: OutgoingMail): Promise<Sent>;\n}\n\nexport const DELIVERY_STATUS = { sent: \"sent\", failed: \"failed\", suppressed: \"suppressed\", duplicate: \"duplicate\" } as const;\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS];\n\n/** One line of the delivery log: what, to whom (a hash, never the address), how it went. The shape of `@krizaka/email`'s `DeliveryLogEntry`. */\nexport interface DeliveryEntry {\n at?: string;\n template: string;\n category: string;\n locale: string;\n to: string;\n status: DeliveryStatus;\n messageId?: string | undefined;\n idempotencyKey?: string | undefined;\n detail?: string | undefined;\n}\n\n/** A line to write: the instant is a `Date`. */\nexport type DeliveryInput = Omit<DeliveryEntry, \"at\"> & { at: Date };\n\n/** A line as read back. */\nexport interface DeliveryRecord extends DeliveryEntry {\n id: number;\n at: string;\n}\n\n/** Where the module keeps its state. Every adapter runs `mailStoreContract` (`@krizaka/mail/testkit`). Addresses arrive hashed. */\nexport interface MailStore {\n record(entry: DeliveryInput): Promise<void>;\n recent(limit: number): Promise<DeliveryRecord[]>;\n isSuppressed(addressHash: string): Promise<boolean>;\n /** `false` when the address was already suppressed (the first reason stays). */\n suppress(addressHash: string, reason: SuppressionReason, now: Date): Promise<boolean>;\n /** Lifts a suppression (the person re-subscribed, or it was a mistake). */\n unsuppress(addressHash: string): Promise<boolean>;\n hasKey(key: string): Promise<boolean>;\n /** `true` the first time a key is claimed. */\n claimKey(key: string, now: Date): Promise<boolean>;\n releaseKey(key: string): Promise<void>;\n /** Removes the keys and log lines older than `before` (suppressions are kept for good). Returns how many. */\n purgeBefore(before: Date): Promise<number>;\n}\n\nexport interface MailSettings {\n provider: \"log\" | \"mailgun\" | \"resend\";\n /** The sender, `Name <address>` or an address. */\n from: string;\n /** Where replies go; empty for none. */\n replyTo: string;\n /** Days the delivery log and the idempotency keys are kept. */\n retentionDays: number;\n}\n\nexport const MAIL_CODE = {\n badAddress: \"MAIL_BAD_ADDRESS\",\n badMessage: \"MAIL_BAD_MESSAGE\",\n badSettings: \"MAIL_BAD_SETTINGS\",\n provider: \"MAIL_PROVIDER_FAILED\",\n badWebhook: \"MAIL_BAD_WEBHOOK\",\n} as const;\nexport type MailCode = (typeof MAIL_CODE)[keyof typeof MAIL_CODE];\n\nexport class MailError extends Error {\n constructor(\n readonly code: MailCode,\n message: string,\n ) {\n super(message);\n this.name = \"MailError\";\n }\n}\n","import { createHash } from \"node:crypto\";\n\nimport { MAIL_CODE, MailError, type MailMessage, type MailSettings } from \"./port\";\n\nexport const MAIL_BOUNDS = { retentionDays: [1, 3650] } as const;\nexport const MAIL_DEFAULTS: MailSettings = { provider: \"log\", from: \"Krizaka <no-reply@krizaka.com>\", replyTo: \"\", retentionDays: 90 };\n\nconst ADDRESS = /^[^\\s@<>]+@[^\\s@<>]+\\.[^\\s@<>]+$/;\nconst TOKEN = /^[a-z][a-z0-9_.-]{0,39}$/;\n// @fixed: RFC 5321's longest forward path\nconst MAX_ADDRESS = 254;\n// @fixed: a subject is one short line; a body past this is not a transactional mail\nconst MAX_SUBJECT = 200;\nconst MAX_BODY = 500_000;\nconst MAX_KEY = 200;\n\nexport const normalizeAddress = (email: string) => email.trim().toLowerCase();\n\n/** The full SHA-256 of an address: suppressions and the log never hold the address itself (Loi 25). */\nexport const hashAddress = (email: string) => createHash(\"sha256\").update(normalizeAddress(email)).digest(\"hex\");\n\n/** A stable UUID (version 5 shaped) from a seed: the same key queued twice is one outbox message. */\nexport function uuidOf(seed: string): string {\n const h = createHash(\"sha256\").update(`krizaka.mail:${seed}`).digest();\n h[6] = (h[6]! & 0x0f) | 0x50;\n h[8] = (h[8]! & 0x3f) | 0x80;\n const x = h.subarray(0, 16).toString(\"hex\");\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;\n}\n\n/** The bare address of `Name <address>` or `address`. */\nexport function bareAddress(from: string): string {\n const match = /<([^<>]+)>\\s*$/.exec(from);\n return (match?.[1] ?? from).trim();\n}\n\nconst oneLine = (value: string) => !/[\\r\\n]/.test(value);\n\n/** @throws MailError when the address is not one mailbox on one line (no header injection). */\nexport function checkAddress(address: string, what = \"address\"): void {\n if (typeof address !== \"string\" || address.length > MAX_ADDRESS || !oneLine(address) || !ADDRESS.test(bareAddress(address))) throw new MailError(MAIL_CODE.badAddress, `${what} is not a valid address`);\n}\n\n/** @throws MailError on the first thing wrong with a message. */\nexport function checkMessage(message: MailMessage): void {\n checkAddress(message.to, \"to\");\n if (message.replyTo !== undefined && message.replyTo !== \"\") checkAddress(message.replyTo, \"replyTo\");\n if (typeof message.subject !== \"string\" || message.subject.trim() === \"\" || message.subject.length > MAX_SUBJECT || !oneLine(message.subject)) throw new MailError(MAIL_CODE.badMessage, \"subject must be one line of 1 to 200 characters\");\n if (typeof message.text !== \"string\" || message.text.trim() === \"\" || message.text.length > MAX_BODY) throw new MailError(MAIL_CODE.badMessage, \"text is required\");\n if (message.html !== undefined && (typeof message.html !== \"string\" || message.html.length > MAX_BODY)) throw new MailError(MAIL_CODE.badMessage, \"html is too long\");\n if (!TOKEN.test(message.category) || !TOKEN.test(message.template)) throw new MailError(MAIL_CODE.badMessage, \"category and template are lower-case tokens\");\n if (typeof message.locale !== \"string\" || !/^[a-z]{2}(-[A-Z]{2})?$/.test(message.locale)) throw new MailError(MAIL_CODE.badMessage, \"locale is a language tag like fr or en-CA\");\n if (typeof message.idempotencyKey !== \"string\" || message.idempotencyKey === \"\" || message.idempotencyKey.length > MAX_KEY) throw new MailError(MAIL_CODE.badMessage, \"idempotencyKey is required (1 to 200 characters)\");\n}\n\n/** @throws MailError when the settings are out of bounds. */\nexport function checkSettings(s: MailSettings): MailSettings {\n const [min, max] = MAIL_BOUNDS.retentionDays;\n if (!Number.isInteger(s.retentionDays) || s.retentionDays < min || s.retentionDays > max) throw new MailError(MAIL_CODE.badSettings, `retentionDays must be ${min} to ${max}`);\n checkAddress(s.from, \"from\");\n if (s.replyTo !== \"\") checkAddress(s.replyTo, \"replyTo\");\n return s;\n}\n"],"mappings":";AASO,IAAM,qBAAqB,EAAE,QAAQ,UAAU,WAAW,aAAa,cAAc,eAAe;AAoCpG,IAAM,kBAAkB,EAAE,MAAM,QAAQ,QAAQ,UAAU,YAAY,cAAc,WAAW,YAAY;AAoD3G,IAAM,YAAY;AAAA,EACvB,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AAAA,EACV,YAAY;AACd;AAGO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACW,MACT,SACA;AACA,UAAM,OAAO;AAHJ;AAIT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAMb;;;AClHA,SAAS,kBAAkB;AAIpB,IAAM,cAAc,EAAE,eAAe,CAAC,GAAG,IAAI,EAAE;AAC/C,IAAM,gBAA8B,EAAE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as DeliveryEntry, S as SuppressionReason, a as MailMessage, b as MailSettings, c as MailProvider } from './port-Pk4TboMq.js';
2
+ export { d as DELIVERY_STATUS, e as DeliveryInput, f as DeliveryRecord, g as DeliveryStatus, h as MAIL_CODE, i as MailCode, j as MailError, O as OutgoingMail, k as SUPPRESSION_REASON, l as Sent } from './port-Pk4TboMq.js';
3
+ import * as _krizaka_db from '@krizaka/db';
4
+ import { Clock, Query } from '@krizaka/db';
5
+ export { Clock, Query } from '@krizaka/db';
6
+
7
+ /**
8
+ * The three ports of `@krizaka/email` (`DeliveryLog`, `SuppressionList`, `IdempotencyStore`) over this module's store, so a product
9
+ * that calls `sendEmail` directly writes to the same tables as the queue. Structural: this package never imports `@krizaka/email`.
10
+ */
11
+ declare function emailPorts(store: MailStore, clock: Clock): {
12
+ log: {
13
+ record: (entry: Omit<DeliveryEntry, "at"> & {
14
+ at?: string;
15
+ }) => Promise<void>;
16
+ };
17
+ suppression: {
18
+ has: (email: string) => Promise<boolean>;
19
+ add: (email: string, reason: SuppressionReason) => Promise<void>;
20
+ };
21
+ idempotency: {
22
+ claim: (key: string) => Promise<boolean>;
23
+ release: (key: string) => Promise<void>;
24
+ };
25
+ };
26
+
27
+ /** What a provider's webhook tells us about one address. */
28
+ interface Suppression {
29
+ address: string;
30
+ reason: SuppressionReason;
31
+ }
32
+ /**
33
+ * A Mailgun webhook (JSON body): checks the signature (HMAC-SHA256 of `timestamp + token` with the webhook signing key, hex) and
34
+ * its age, then answers the address to suppress, or `null` for an event that is not a permanent bounce, a complaint or an unsubscribe.
35
+ * @throws MailError when the body is not Mailgun's, the signature is wrong or the timestamp is stale
36
+ */
37
+ declare function parseMailgunWebhook(rawBody: string, signingKey: string, nowSeconds: number): Suppression | null;
38
+ interface SvixHeaders {
39
+ id: string | null | undefined;
40
+ timestamp: string | null | undefined;
41
+ signature: string | null | undefined;
42
+ }
43
+ /**
44
+ * A Resend webhook (signed the Svix way): HMAC-SHA256 over `id.timestamp.body` with the base64 secret that follows `whsec_`, any of
45
+ * the space-separated `v1,<base64>` signatures matching. Answers the addresses to suppress (a hard bounce or a complaint).
46
+ * @throws MailError when the headers are missing, the signature is wrong or the timestamp is stale
47
+ */
48
+ declare function parseResendWebhook(rawBody: string, headers: SvixHeaders, secret: string, nowSeconds: number): Suppression[];
49
+
50
+ /** The topic the mail is queued on, and the event that names it: the outbox routes by these. */
51
+ declare const MAIL_TOPIC = "mail";
52
+ declare const MAIL_EVENT: {
53
+ readonly requested: "evt.mail.requested.v1";
54
+ };
55
+ /** What the module needs of `@krizaka/outbox` (its `Outbox` satisfies it): append in the caller's transaction. */
56
+ interface MailOutbox {
57
+ append(tx: Query, message: {
58
+ topic: string;
59
+ type: string;
60
+ payload: unknown;
61
+ id: string;
62
+ }): Promise<{
63
+ id: string;
64
+ appended: boolean;
65
+ }>;
66
+ }
67
+ /** The part of an outbox message the deliverer reads (`OutboxMessage` satisfies it). */
68
+ interface QueuedMail {
69
+ id: string;
70
+ payload: unknown;
71
+ }
72
+ interface MailDeps {
73
+ clock: Clock;
74
+ outbox: MailOutbox;
75
+ /** The settings, read at each call so the admin's change applies at once. */
76
+ settings: MailSettings | (() => MailSettings | Promise<MailSettings>);
77
+ /** The state of the module over a query (a pool; a transaction is never needed). */
78
+ store: MailStore;
79
+ /** The provider the admin chose: a function so a change of `mail.provider` applies at once. */
80
+ provider: MailProvider | ((settings: MailSettings) => MailProvider);
81
+ }
82
+ interface Mail {
83
+ /** Queues a mail INSIDE the caller's transaction: it is sent after the commit, and only if the transaction commits. `queued` is `false` when the same key was already queued. */
84
+ queue(tx: Query, message: MailMessage): Promise<{
85
+ id: string;
86
+ queued: boolean;
87
+ }>;
88
+ /** Delivers one queued mail: skipped if its address is suppressed or its key was already sent, thrown (for a retry) if the provider fails. Give it to `runWorker` / `drainOnce` as `deliver`. */
89
+ deliver(message: QueuedMail): Promise<DeliveryEntry["status"]>;
90
+ /** A provider's webhook said this address bounced, complained or unsubscribed: it is never mailed again. */
91
+ suppress(suppression: Suppression): Promise<boolean>;
92
+ /** Lifts a suppression. */
93
+ unsuppress(address: string): Promise<boolean>;
94
+ isSuppressed(address: string): Promise<boolean>;
95
+ /** Removes the log and the keys older than the retention. */
96
+ purge(): Promise<number>;
97
+ }
98
+ /**
99
+ * The mail of a product.
100
+ *
101
+ * The guarantee is AT LEAST ONCE: a mail is sent, THEN its key is claimed, so a crash in between sends it again rather than never
102
+ * (a duplicate reset mail beats a lost one). A second delivery after the claim is a no-op.
103
+ * @param deps the clock, the outbox, the settings, the store and the provider
104
+ * @returns the mail functions
105
+ */
106
+ declare function createMail(deps: MailDeps): Mail;
107
+
108
+ /** An in-memory store, for unit tests and demos: the behaviour of the database's (the contract kit runs on both). */
109
+ declare function memoryMailStore(): MailStore;
110
+
111
+ /**
112
+ * The PostgreSQL store of « mail » over a `Query`, in schema `mail` (or the one the product renamed it to).
113
+ * @param query a pool-level query
114
+ * @param schema the Postgres schema, default `mail`
115
+ */
116
+ declare function dbMailStore(query: Query, schema?: string): MailStore;
117
+
118
+ /** The part of `fetch` the providers use: inject the global one (`fetch`), or a fake in a test. */
119
+ type FetchLike = (url: string, init: {
120
+ method: "POST";
121
+ headers: Record<string, string>;
122
+ body: string;
123
+ }) => Promise<{
124
+ ok: boolean;
125
+ status: number;
126
+ text(): Promise<string>;
127
+ }>;
128
+ interface MailgunOptions {
129
+ apiKey: string;
130
+ /** The sending domain. */
131
+ domain: string;
132
+ /** `https://api.mailgun.net` (default) or `https://api.eu.mailgun.net`. */
133
+ apiUrl?: string;
134
+ fetch: FetchLike;
135
+ }
136
+ /** Mailgun's messages API (form-encoded, basic auth). */
137
+ declare function mailgunProvider(options: MailgunOptions): MailProvider;
138
+ interface ResendOptions {
139
+ apiKey: string;
140
+ /** Default `https://api.resend.com`. */
141
+ apiUrl?: string;
142
+ fetch: FetchLike;
143
+ }
144
+ /** Resend's emails API (JSON, bearer key, its own `Idempotency-Key`). */
145
+ declare function resendProvider(options: ResendOptions): MailProvider;
146
+ /** The development provider: writes one JSON line per mail (without its body) and sends nothing. */
147
+ declare function logProvider(write: (line: string) => void): MailProvider;
148
+ /** The keys a provider needs: they stay in the environment, the product reads them and passes them here. */
149
+ interface ProviderKeys {
150
+ apiKey?: string;
151
+ domain?: string;
152
+ apiUrl?: string;
153
+ }
154
+ /**
155
+ * The provider the admin chose (`mail.provider`). A provider chosen without its key is refused loudly, never replaced by `log`:
156
+ * a reset mail must not vanish silently.
157
+ * @throws MailError when the chosen provider lacks its key (or its domain, for Mailgun)
158
+ */
159
+ declare function providerFor(kind: MailSettings["provider"], keys: ProviderKeys, fetch: FetchLike, write: (line: string) => void): MailProvider;
160
+
161
+ declare const MAIL_BOUNDS: {
162
+ readonly retentionDays: readonly [1, 3650];
163
+ };
164
+ declare const MAIL_DEFAULTS: MailSettings;
165
+ declare const normalizeAddress: (email: string) => string;
166
+ /** The full SHA-256 of an address: suppressions and the log never hold the address itself (Loi 25). */
167
+ declare const hashAddress: (email: string) => string;
168
+ /** A stable UUID (version 5 shaped) from a seed: the same key queued twice is one outbox message. */
169
+ declare function uuidOf(seed: string): string;
170
+ /** The bare address of `Name <address>` or `address`. */
171
+ declare function bareAddress(from: string): string;
172
+ /** @throws MailError when the address is not one mailbox on one line (no header injection). */
173
+ declare function checkAddress(address: string, what?: string): void;
174
+ /** @throws MailError on the first thing wrong with a message. */
175
+ declare function checkMessage(message: MailMessage): void;
176
+ /** @throws MailError when the settings are out of bounds. */
177
+ declare function checkSettings(s: MailSettings): MailSettings;
178
+
179
+ /**
180
+ * The tables of « mail », in their own Postgres schema: `delivery` (the log, with the recipient as a hash, never a body),
181
+ * `suppression` (the addresses never mailed again, as a SHA-256 hash: the list holds no address) and `idempotency` (the keys
182
+ * already sent). They reference no product table. Version 1 is frozen once released: a change is version 2.
183
+ */
184
+ declare const mailSchema: _krizaka_db.ModuleSchema;
185
+
186
+ export { DeliveryEntry, type FetchLike, MAIL_BOUNDS, MAIL_DEFAULTS, MAIL_EVENT, MAIL_TOPIC, type Mail, type MailDeps, MailMessage, type MailOutbox, MailProvider, MailSettings, MailStore, type MailgunOptions, type ProviderKeys, type QueuedMail, type ResendOptions, type Suppression, SuppressionReason, type SvixHeaders, bareAddress, checkAddress, checkMessage, checkSettings, createMail, dbMailStore, emailPorts, hashAddress, logProvider, mailSchema, mailgunProvider, memoryMailStore, normalizeAddress, parseMailgunWebhook, parseResendWebhook, providerFor, resendProvider, uuidOf };