@ultimat3/mail 30.9.0 → 31.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/CLAUDE.md CHANGED
@@ -7,11 +7,11 @@
7
7
  | File | Single responsibility |
8
8
  |---|---|
9
9
  | `mail.ts` | `defineMail`, the registry, `send` / `sendById` / `renderMessage` |
10
- | `templates/` | the six framework mails, as data |
11
10
  | `blocks.ts` | the template vocabulary: `MailBlock`, `blocks`, `MailTemplate`, `TemplateArgs` |
12
11
  | `render.ts` | blocks → HTML **and** text, plus the layout call and the footer slots |
13
12
  | `layout.ts` | `MAIL_TOKENS` (light + dark), the 600px table shell, layout registry |
14
- | `driver.ts` | `MailDriver` + memory/log/unconfigured + `resultFor` + the `setMailDriver` seam |
13
+ | `adapter.ts` | `@ultimat3/mail/adapter`: `installMailDriver` + reset, the `MailDriver` port, `MailError`/`sendFailed` — never on the `.` barrel; an app's line is `mail:` in `apps/<app>/runtime.ts` |
14
+ | `driver.ts` | `MailDriver` + memory/log/unconfigured + `resultFor` + the `installMailDriver` seam (on `./adapter`) |
15
15
  | `driver-env.ts` | `selectMailDriver`: which transport an environment installs, and nothing else |
16
16
  | `header-safety.ts` | `assertHeaderSafe`: the CR/LF gate on a `MailMessage`, so every driver refuses the same one |
17
17
  | `driver-smtp.ts` | `smtpMailDriver`: `SMTP_URL` parsing, the pool ceiling, one send |
@@ -23,7 +23,7 @@
23
23
  | `delivery-event-errors.ts` | the three receiver refusals (`X_MAIL_EVENT_*`) |
24
24
  | `sns-signature.ts` | SNS message verification: topic allow-list, pinned cert URL, canonical string, RSA v1/v2 |
25
25
  | `sns-certificate-cache.ts` | the downloaded SNS certificates, bounded against forgery floods |
26
- | `x509-spki.ts` | the public key out of a PEM certificate (Web Crypto imports no certificate) |
26
+ | `x509-spki.ts` | PEM → SPKI over core's `x509Spki` (Web Crypto imports no certificate) |
27
27
  | `ses-event-receiver.ts` | `sesEventReceiver`: body → verify → normalise; SubscriptionConfirmation |
28
28
  | `delivery-event-ses.ts` | SES notification JSON (`notificationType` or `eventType`) → events |
29
29
  | `resend-signature.ts` | Svix verification: HMAC over `id.timestamp.body`, constant-time, then the window |
@@ -35,6 +35,7 @@
35
35
  | `mime.ts` | `MailMessage` → RFC 5322: header order, RFC 2047, folding, quoted-printable |
36
36
  | `base64.ts` | base64 over UTF-8 bytes, shared by RFC 2047 and SMTP AUTH |
37
37
  | `job.ts` | `sendMailJob` and the envelope schema |
38
+ | `deliver.ts` | `deliverMail`: the ONE hand-off to the transport, inline and queued — a `mail.deliver` client span and bus event, a recipient count, never an address |
38
39
  | `transform.ts` | `setMailTransform`: the app's outbound hook, run once per `send()` before the key |
39
40
  | `idempotency.ts` | `mailIdempotencyKey` — apart from `job.ts` because the transports need it too |
40
41
  | `catalog.ts` | English source strings for `mail.*`. Data, not code |
@@ -48,8 +49,8 @@
48
49
  result is re-checked by `assertHeaderSafe`; a throw or a malformed result is
49
50
  `X_MAIL_TRANSFORM_FAILED` and nothing is sent. None installed ⇒ the same object, byte-identical.
50
51
 
51
- - **`send()` enqueues through `jobsFacade().enqueue(sendMailJob, message)`, never `jobDriver().enqueue`**
52
- (`As of 2026-10-02`). The driver call published on the pool, autocommitted, so a handler that
52
+ - **`send()` enqueues through `sendMailJob.enqueue(message)` — the facade under the handle's
53
+ producer span and `job.enqueue` (`As of 2026-11-09`) — never `jobDriver().enqueue`** (`As of 2026-10-02`). The driver call published on the pool, autocommitted, so a handler that
53
54
  rolled back after `send()` still mailed — and under `{ retry }` each re-run could mail again.
54
55
  Through the facade an ambient transaction STAGES the row and the relay publishes it after COMMIT.
55
56
  `send-outbox.job.test.ts` proves a rollback delivers nothing, on the memory pair and on Postgres.
@@ -67,7 +68,8 @@
67
68
  every access, and a copy would freeze the provider at import time. `index.test.ts` asserts identity.
68
69
  - `SendOptions.locale` is non-optional in the type. Never relax it, never default it.
69
70
  - Text part is derived from blocks and must be non-empty (`X_MAIL_TEXT_MISSING`).
70
- - No literal user-facing string in `templates/` or `layout.ts` — keys only.
71
+ - No literal user-facing string in a template or `layout.ts` — keys only. The package ships no mails
72
+ (v31 deleted the six framework ones); `catalog.ts` holds the footer keys alone.
71
73
  - No hex outside `MAIL_TOKENS`. Base styling is inlined (clients strip `<style>`); dark mode is
72
74
  one `prefers-color-scheme` block keyed on short `data-x` role codes.
73
75
  - Never format a date without `options.tz`. The `Date:` header is UTC, stated as `+0000`.
@@ -115,7 +117,7 @@
115
117
  capability. `staging` refuses too, because staging exists to fail the way production fails —
116
118
  which is `isLocal()`'s own rule, read from **core** rather than restated here, so mail and storage
117
119
  cannot disagree about which deploy this is. And it is its **own code**: `X_MAIL_DRIVER_UNAVAILABLE`
118
- is a developer who never called `setMailDriver`, this is an operator who set no variable, and one
120
+ is a developer who installed no driver, this is an operator who set no variable, and one
119
121
  code for two audiences is a `fix:` that is wrong half the time.
120
122
  - **The CR/LF header rule is a property of the MESSAGE, checked at `renderMessage` and again in
121
123
  `sendMailJob`** (`As of 2026-08`). `mime.ts` held the only copy, so a subject an SMTP deploy
@@ -134,11 +136,12 @@
134
136
  enforced by the provider. That asymmetry is a transport DIFFERENCE and is pinned as one.
135
137
  `mailMessageIdToken` is a one-way digest of `mailIdempotencyKey`, never the key itself: the key
136
138
  holds the recipient list, bcc included, and a `Message-ID` is visible to all of them.
137
- - **`driver-parity.test.ts` asserts every driver's behaviour in ONE test.** Both production drivers
138
- run for real — SMTP over a fake `SmtpStream`, Resend over an injected `fetch` — so a case compares
139
- what each did rather than a proxy for it, and neither side can move alone. The memory driver joins
140
- the cases about the MESSAGE and none about a wire: it dials nothing, maps no status and carries no
141
- idempotency header, and that is documented difference, not defect.
139
+ - **`mailDriverConformance` (`@ultimat3/testing/conformance`) asks every driver one contract.**
140
+ memory and log in `mail-driver-conformance.test.ts`; smtp, resend and ses run for real over fake
141
+ wires in `mail-driver-conformance-transports.test.ts`, which also pins the wire facts the port
142
+ cannot ask: `send()` refuses a header break before any transport dials, a retry carries one
143
+ identity, the `Message-ID` is a digest of the key. A driver of your own:
144
+ `behavesLike(mailDriverConformance, () => yours)`.
142
145
  - **`assertHeaderSafe` gates the ADDRESS LISTS too — `to` and `cc`** (`As of 2026-08-23`). It
143
146
  checked `subject` and `Object.entries(messageHeaders(message))`, and `messageHeaders` emits only
144
147
  `Auto-Submitted`, `Reply-To` and the two `List-Unsubscribe` lines — while `to` and `cc` become
@@ -148,7 +151,7 @@
148
151
  Exactly the three-answers split this rule was lifted out of `mime.ts` to close.
149
152
  - **`registerLayout` refuses a second claim on a name** (`X_MAIL_DUPLICATE`, `mailLayoutDuplicate`).
150
153
  `layouts.set` answered whichever registration ran LAST, `base` included, so a dependency that
151
- registered `base` silently re-shelled every framework mail with no error anywhere and nothing to
154
+ registered `base` silently re-shelled every mail with no error anywhere and nothing to
152
155
  grep for. `defineMail` refuses a duplicate id one file over for the identical reason, and
153
156
  `@ultimat3/mcp`'s `ResourceRegistry.register` states the general rule. **Breaking for an app that
154
157
  registered one name twice** — the old behaviour was pinned by a test called "last writer wins",
@@ -238,7 +241,7 @@
238
241
  ## Commands
239
242
 
240
243
  ```bash
241
- bun test packages/mail
244
+ bun test ./packages/mail/
242
245
  bun run --filter @ultimat3/mail typecheck
243
246
  ```
244
247
 
package/README.md CHANGED
@@ -57,6 +57,7 @@ setMailTransform(async (rendered, meta) =>
57
57
  |---|---|
58
58
  | `locale` is required by the **type** | a mail is read hours later; there is no ambient request locale to fall back to. `X_MAIL_LOCALE_MISSING` is the backstop for JS callers |
59
59
  | An unresolved key is never sent | `send()` refuses a key the locale lacks, a catalog value still holding `⟦…⟧`, or a `{slot}` with no value (`X_MAIL_KEY_MISSING`, terminal), before the transform and the queue. `renderMessage()` keeps the `⟦…⟧` for a preview, and `renderMail()` reports it as `misses` (`TranslationMiss[]`, recorded by `@ultimat3/i18n`'s `recordingTranslator`). It reads what the renderer resolved, never the bytes: a `⟦` from data sends |
60
+ | One hand-off, observed | inline and queued sends both reach the transport through `deliverMail`: one `mail.deliver` client span and bus event (`{ transport, recipients, durationMs, error? }`) — a recipient COUNT, never an address |
60
61
  | Text part is mandatory | HTML-only mail scores as spam and is unreadable to screen readers. Empty text ⇒ `X_MAIL_TEXT_MISSING` |
61
62
  | Text is derived from blocks | never scraped out of the HTML, so the two parts cannot drift |
62
63
  | Every string is a key | `mail.<id>.<slot>`; English lives in `src/catalog.ts` and app catalogs override it |
@@ -70,8 +71,11 @@ setMailTransform(async (rendered, meta) =>
70
71
 
71
72
  ## Drivers
72
73
 
73
- `setMailDriver(driver)` once at boot. Asking for one that was never set is
74
- `X_MAIL_DRIVER_UNAVAILABLE`.
74
+ The boot installs one from the environment; an app swaps it with `mail:` in
75
+ `apps/<app>/runtime.ts` (`export const runtime = { mail: memoryMailDriver() }`). Asking for one
76
+ that was never installed is `X_MAIL_DRIVER_UNAVAILABLE`. A driver's author imports the
77
+ interface, `MailError`/`sendFailed` and the installer from `@ultimat3/mail/adapter` — never the
78
+ `.` barrel.
75
79
 
76
80
  | Driver | Use | Behaviour |
77
81
  |---|---|---|
@@ -104,8 +108,8 @@ own a second reading of it.
104
108
 
105
109
  Both credentials at once is `X_CONFIG_INVALID` rather than a winner picked for you, and a
106
110
  transport with no `MAIL_FROM` is refused at boot instead of on the first send. A host that is not
107
- `x dev` calls `selectMailDriver` itself, or constructs a driver directly — `setMailDriver` is the
108
- only seam either way.
111
+ `x dev` calls `selectMailDriver` itself, or constructs a driver directly — `installMailDriver`
112
+ (`@ultimat3/mail/adapter`) is the only seam either way.
109
113
 
110
114
  ### SMTP
111
115
 
@@ -192,10 +196,11 @@ export const resend = resendEventReceiver({ secret: env['RESEND_WEBHOOK_SECRET']
192
196
  | `sesEventReceiver` | SNS: the topic is in `topicArns`, the cert URL is `https://sns.<topic region>.amazonaws.com/…pem`, `SignatureVersion` 1 (RSA-SHA1) or 2 (RSA-SHA256) over AWS's canonical string, `Timestamp` within `toleranceMs` (1 h). A `SubscriptionConfirmation` returns its `confirmUrl`; it is fetched only with `confirmSubscriptions: true` |
193
197
  | `resendEventReceiver` | Svix: HMAC-SHA256 over `svix-id.svix-timestamp.body` under the `whsec_` secret, constant-time, any `v1,` entry, within `toleranceMs` (5 min) |
194
198
 
195
- ## Framework mails
199
+ ## No framework mails
196
200
 
197
- Registered by importing them — the import IS the registration. `FRAMEWORK_MAILS` is the list, and
198
- `registeredMails()` / `registeredMailIds()` answer for an app's own mails as well.
201
+ The package ships none (v31). Every mail is an app's own `defineMail`; `@ultimat3/auth` sends
202
+ `auth.<purpose>` templates whose words live in the app catalog. `registeredMails()` /
203
+ `registeredMailIds()` list what the app declared, and nothing else.
199
204
 
200
205
  ## Previews — `defineMail({ preview })`
201
206
 
@@ -206,17 +211,6 @@ and never production rows. A value is parsed by `input` at definition (`X_MAIL_P
206
211
  it on the command line, and `x verify`'s `i18n` step renders every declared preview in every
207
212
  locale, so a miss a `send` would refuse is red at the gate. No preview: `X_MAIL_PREVIEW_MISSING`.
208
213
 
209
- | id | Input |
210
- |---|---|
211
- | `welcome` | `{ name, appName, url }` |
212
- | `verify-email` | `{ name, url, expiresMinutes }` |
213
- | `reset-password` | `{ name, url, expiresMinutes }` |
214
- | `invite` | `{ inviterName, orgName, url, expiresHours }` |
215
- | `mfa-enrolled` | `{ name, method, at }` |
216
- | `security-alert` | `{ name, event, ip, at }` |
217
-
218
- Translating them = shipping `mail.*` keys in an app catalog. Never edit a template.
219
-
220
214
  ## Errors
221
215
 
222
216
  | Code | Fix |
@@ -226,7 +220,7 @@ Translating them = shipping `mail.*` keys in an app catalog. Never edit a templa
226
220
  | `X_MAIL_DUPLICATE` | rename one of two `defineMail({ id })` declarations |
227
221
  | `X_MAIL_KEY_MISSING` | `x i18n sync <locale>`, then translate `meta.keys`; pass the vars `meta.slots` names |
228
222
  | `X_MAIL_TEXT_MISSING` | add a text-bearing block to the template |
229
- | `X_MAIL_DRIVER_UNAVAILABLE` | `setMailDriver(memoryMailDriver())` at boot — a wiring bug |
223
+ | `X_MAIL_DRIVER_UNAVAILABLE` | `mail: memoryMailDriver()` in `apps/<app>/runtime.ts` — a wiring bug |
230
224
  | `X_MAIL_CREDENTIAL_MISSING` | set `SMTP_URL` (or `RESEND_API_KEY`) and `MAIL_FROM` in the deployment — an operations one |
231
225
  | `X_MAIL_HEADER_INVALID` | strip CR/LF from the interpolated value before it reaches a header |
232
226
  | `X_MAIL_ADDRESS_INVALID` | a recipient may hold no control character, its mailbox no `<`/`>` and no non-ASCII byte (`meta.reason`); `Jane Doe <jane@x.test>` is fine |
@@ -243,11 +237,11 @@ a job boundary the class is gone and the `code` is what survives — match on th
243
237
 
244
238
  | Class | Code | Declared in |
245
239
  |---|---|---|
246
- | `MailError` | any `MailErrorCode` — `MAIL_ERROR_CODES` | `src/errors.ts` (the `X_MAIL_EVENT_*` factories export from `@ultimat3/mail/events`) |
240
+ | `MailError` | any `MailErrorCode` | `src/errors.ts` (the `X_MAIL_EVENT_*` factories export from `@ultimat3/mail/events`) |
247
241
 
248
242
  ## Commands
249
243
 
250
244
  ```bash
251
- bun test packages/mail
245
+ bun test ./packages/mail/
252
246
  bun run --filter @ultimat3/mail typecheck
253
247
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/mail",
3
- "version": "30.9.0",
3
+ "version": "31.1.0",
4
4
  "description": "Transactional email as data: one template renders HTML and text, sent through a job.",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -24,6 +24,7 @@
24
24
  },
25
25
  "exports": {
26
26
  ".": "./src/index.ts",
27
+ "./adapter": "./src/adapter.ts",
27
28
  "./events": "./src/events.ts"
28
29
  },
29
30
  "files": [
@@ -42,10 +43,10 @@
42
43
  "test": "bun test"
43
44
  },
44
45
  "dependencies": {
45
- "@ultimat3/core": "30.9.0",
46
- "@ultimat3/i18n": "30.9.0",
47
- "@ultimat3/jobs": "30.9.0",
48
- "@ultimat3/schema": "30.9.0",
49
- "@ultimat3/time": "30.9.0"
46
+ "@ultimat3/core": "31.1.0",
47
+ "@ultimat3/i18n": "31.1.0",
48
+ "@ultimat3/jobs": "31.1.0",
49
+ "@ultimat3/schema": "31.1.0",
50
+ "@ultimat3/time": "31.1.0"
50
51
  }
51
52
  }
package/src/adapter.ts ADDED
@@ -0,0 +1,9 @@
1
+ // `@ultimat3/mail/adapter` — what a mail driver is built and installed from: the port interface,
2
+ // the errors a driver throws, and the boot's installer with its reset. Never the `.` barrel: an app
3
+ // swaps the driver with `mail:` in `apps/<app>/runtime.ts`, so the only callers here are the cli
4
+ // boot, `@ultimat3/testing`, and a driver's own author.
5
+
6
+ export type { MailDriver, MailMessage, SendResult } from './driver';
7
+ export { installMailDriver, resetMailDriver } from './driver';
8
+ export type { SendFailure, SendStage } from './errors';
9
+ export { MailError, sendFailed } from './errors';
package/src/catalog.ts CHANGED
@@ -1,7 +1,7 @@
1
- // Single responsibility: the English source strings for the keys this package's templates
2
- // emit. Templates carry keys only; the words live here (and in an app's own catalogs, which
3
- // are registered after this one and therefore win). Translating a framework mail means
4
- // shipping `mail.*` in an app catalog — never editing a template.
1
+ // Single responsibility: the English source strings for the keys this package's layout emits —
2
+ // the footer every mail carries. An app's own mails carry their keys in the app's catalogs, which
3
+ // are registered after this one and therefore win; translating the footer means shipping
4
+ // `mail.footer.*` in an app catalog.
5
5
 
6
6
  import { DEFAULT_LOCALE } from '@ultimat3/core';
7
7
  import { type Catalog, loadCatalog, type NestedCatalog, registerBaseCatalog } from '@ultimat3/i18n';
@@ -13,64 +13,6 @@ export const MAIL_CATALOG_SOURCE: NestedCatalog = {
13
13
  help: 'Questions? Reply to this email and a human will answer.',
14
14
  unsubscribe: 'Unsubscribe',
15
15
  },
16
- welcome: {
17
- subject: 'Welcome to {appName}',
18
- preheader: 'Your {appName} account is ready.',
19
- heading: 'Welcome, {name}',
20
- body: 'Your {appName} account is ready. Pick up where you left off any time.',
21
- cta: 'Open {appName}',
22
- },
23
- 'verify-email': {
24
- subject: 'Verify your email address',
25
- preheader: 'One click and this address is confirmed.',
26
- heading: 'Verify your email, {name}',
27
- body: 'Confirm this address so we can secure your account and reach you when it matters.',
28
- cta: 'Verify email address',
29
- expiry_one: 'This link expires in {count} minute.',
30
- expiry_other: 'This link expires in {count} minutes.',
31
- ignore: 'If you did not create this account, ignore this message.',
32
- },
33
- 'reset-password': {
34
- subject: 'Reset your password',
35
- preheader: 'A link to choose a new password.',
36
- heading: 'Reset your password, {name}',
37
- body: 'Choose a new password. Existing sessions stay signed in until you sign them out.',
38
- cta: 'Choose a new password',
39
- expiry_one: 'This link expires in {count} minute.',
40
- expiry_other: 'This link expires in {count} minutes.',
41
- ignore: 'If you did not ask for this, no action is needed — your password is unchanged.',
42
- },
43
- invite: {
44
- subject: '{inviterName} invited you to {orgName}',
45
- preheader: 'Your invitation to {orgName}.',
46
- heading: 'Join {orgName}',
47
- body: '{inviterName} invited you to collaborate in {orgName}.',
48
- cta: 'Accept invitation',
49
- expiry_one: 'This invitation expires in {count} hour.',
50
- expiry_other: 'This invitation expires in {count} hours.',
51
- },
52
- 'mfa-enrolled': {
53
- subject: 'Two-factor authentication is on',
54
- preheader: 'A new second factor now protects your account.',
55
- heading: 'Two-factor is on, {name}',
56
- body: 'Every sign-in now needs a second factor as well as your password.',
57
- 'method-label': 'Method',
58
- 'method-totp': 'Authenticator app',
59
- 'method-webauthn': 'Passkey or security key',
60
- 'method-sms': 'Text message',
61
- 'at-label': 'Enabled',
62
- help: 'If this was not you, remove the factor and change your password immediately.',
63
- },
64
- 'security-alert': {
65
- subject: 'Security alert on your account',
66
- preheader: 'Confirm recent activity on your account.',
67
- heading: 'Security alert, {name}',
68
- alert: 'We noticed activity on your account that we want you to confirm.',
69
- 'event-label': 'Event',
70
- 'ip-label': 'IP address',
71
- 'at-label': 'When',
72
- help: 'If this was not you, change your password and sign out every other session.',
73
- },
74
16
  },
75
17
  };
76
18
 
package/src/deliver.ts ADDED
@@ -0,0 +1,41 @@
1
+ // Single responsibility: hand one rendered message to the installed transport — the ONE place a
2
+ // mail leaves the process, inline or from the queue — inside a client span, reported on core's
3
+ // instrumentation bus as `mail.deliver` (a recipient COUNT: addresses never ride an event).
4
+
5
+ import { instrument, subscribed, withSpan } from '@ultimat3/core';
6
+ import type { MailMessage, SendResult } from './driver';
7
+ import { envelopeRecipients, mailDriver } from './driver';
8
+
9
+ export async function deliverMail(message: MailMessage): Promise<SendResult> {
10
+ const driver = mailDriver();
11
+ const recipients = envelopeRecipients(message).length;
12
+ const started = performance.now();
13
+ try {
14
+ const result = await withSpan('mail.deliver', () => driver.send(message), {
15
+ kind: 'client',
16
+ attributes: {
17
+ 'ultimate.mail.id': message.mailId,
18
+ 'ultimate.mail.transport': driver.name,
19
+ 'ultimate.mail.recipients': recipients,
20
+ },
21
+ });
22
+ if (subscribed('mail.deliver')) {
23
+ instrument('mail.deliver', {
24
+ transport: driver.name,
25
+ recipients,
26
+ durationMs: performance.now() - started,
27
+ });
28
+ }
29
+ return result;
30
+ } catch (error) {
31
+ if (subscribed('mail.deliver')) {
32
+ instrument('mail.deliver', {
33
+ transport: driver.name,
34
+ recipients,
35
+ durationMs: performance.now() - started,
36
+ error,
37
+ });
38
+ }
39
+ throw error;
40
+ }
41
+ }
package/src/driver-ses.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  EnvMissingError,
11
11
  finiteCount,
12
12
  isUltimateError,
13
+ liveClock,
13
14
  nanoid,
14
15
  renderFixShellArg,
15
16
  renderThrowable,
@@ -133,7 +134,8 @@ export function sesMailDriver(options: SesDriverOptions): MailDriver {
133
134
  1,
134
135
  );
135
136
  const retain = resolveRetainMime('sesMailDriver', options.retainMime);
136
- const clock = options.clock ?? systemClock;
137
+ // AWS signing stays on real time (core's rule): SES checks the signature's date against its own.
138
+ const signingClock = options.clock ?? systemClock;
137
139
  // `outbound()` always hands it the attempt's signal.
138
140
  const doFetch: MailFetch =
139
141
  options.fetch ??
@@ -148,7 +150,7 @@ export function sesMailDriver(options: SesDriverOptions): MailDriver {
148
150
  const raw = buildMimeMessage(message, {
149
151
  from,
150
152
  messageId: `<${message.mailId}.${mailMessageIdToken(message)}@${addressDomain(from)}>`,
151
- date: clock.now(),
153
+ date: (options.clock ?? liveClock).now(),
152
154
  boundary: `x-ultimate-${nanoid(20)}`,
153
155
  });
154
156
  const body = bodyFor(message, from, raw, options.configurationSet);
@@ -163,7 +165,7 @@ export function sesMailDriver(options: SesDriverOptions): MailDriver {
163
165
  credentials,
164
166
  region,
165
167
  service: 'ses',
166
- clock,
168
+ clock: signingClock,
167
169
  });
168
170
  // Through core's `outbound()`: `timeoutMs` bounds the send, the ambient job's signal ends it,
169
171
  // and it is ONE attempt — a signed POST with no idempotency header is never replayed.
@@ -7,10 +7,10 @@ import {
7
7
  ConfigInvalidError,
8
8
  finiteCount,
9
9
  isUltimateError,
10
+ liveClock,
10
11
  nanoid,
11
12
  renderFixShellArg,
12
13
  renderThrowable,
13
- systemClock,
14
14
  } from '@ultimat3/core';
15
15
  import type { SendResult } from './driver';
16
16
  import { envelopeRecipients, type MailDriver, type MailMessage, resultFor } from './driver';
@@ -160,7 +160,6 @@ export function smtpMailDriver(options: SmtpDriverOptions): MailDriver {
160
160
  fix: 'set mail.from in app.config.ts to an address the SMTP server will relay for',
161
161
  });
162
162
  }
163
- const clock = options.clock ?? systemClock;
164
163
  const connect = options.connect ?? bunSmtpStream;
165
164
  // Refused where `poolSize` already is. The deadline reaches `setTimeout(fn, timeoutMs)` in the
166
165
  // conversation and in the socket, and `setTimeout(fn, NaN)` is `setTimeout(fn, 0)` — so a
@@ -206,7 +205,7 @@ export function smtpMailDriver(options: SmtpDriverOptions): MailDriver {
206
205
  const data = buildMimeMessage(message, {
207
206
  from: options.from,
208
207
  messageId,
209
- date: clock.now(),
208
+ date: (options.clock ?? liveClock).now(),
210
209
  boundary: `x-ultimate-${nanoid(20)}`,
211
210
  });
212
211
 
package/src/driver.ts CHANGED
@@ -7,10 +7,11 @@
7
7
  import {
8
8
  type Clock,
9
9
  type Environment,
10
+ liveClock,
10
11
  nanoid,
11
12
  logger as rootLogger,
12
- systemClock,
13
13
  } from '@ultimat3/core';
14
+ import { adapterSlot } from '@ultimat3/core/adapter';
14
15
  import { driverUnavailable, mailCredentialMissing } from './errors';
15
16
  import { mailIdempotencyKey, mailMessageIdToken } from './idempotency';
16
17
  import type { RetainedMime } from './retain-mime';
@@ -148,14 +149,13 @@ export interface MemoryMailDriverOptions {
148
149
  * clock — two sends inside one millisecond tie, and nothing could state the intended order.
149
150
  */
150
151
  export function memoryMailDriver(options: MemoryMailDriverOptions = {}): MemoryMailDriver {
151
- const clock = options.clock ?? systemClock;
152
152
  const sent: SentMail[] = [];
153
153
  return {
154
154
  name: 'memory',
155
155
  sent,
156
156
  send(message: MailMessage): Promise<SendResult> {
157
157
  const result = resultFor('memory', message, `mem_${nanoid(12)}`);
158
- sent.push({ at: clock.now(), message, result });
158
+ sent.push({ at: (options.clock ?? liveClock).now(), message, result });
159
159
  return Promise.resolve(result);
160
160
  },
161
161
  outbox: () => [...sent].reverse(),
@@ -236,23 +236,29 @@ export function logMailDriver(logger = rootLogger): MailDriver {
236
236
  };
237
237
  }
238
238
 
239
- let ambient: MailDriver | undefined;
239
+ /** The installed driver: a stack, so boots and tests release in any order (`adapterSlot`). */
240
+ const slot = adapterSlot<MailDriver | undefined>(() => undefined);
240
241
 
241
- /** Set once at boot from the environment (`selectMailDriver`). One per process, like the job driver. */
242
- export function setMailDriver(driver: MailDriver): void {
243
- ambient = driver;
242
+ /**
243
+ * The boot's installer (its release removes THIS install only, in any order — `adapterSlot`), on `@ultimat3/mail/adapter` and never the `.` barrel: the boot selects from
244
+ * the environment (`selectMailDriver`), and an app swaps it with `mail:` in `apps/<app>/runtime.ts`.
245
+ * One per process, like the job driver.
246
+ */
247
+ export function installMailDriver(driver: MailDriver): () => void {
248
+ return slot.install(driver);
244
249
  }
245
250
 
246
251
  export function tryMailDriver(): MailDriver | undefined {
247
- return ambient;
252
+ return slot.current();
248
253
  }
249
254
 
250
255
  /** Throws `X_MAIL_DRIVER_UNAVAILABLE` rather than silently dropping mail on the floor. */
251
256
  export function mailDriver(): MailDriver {
252
- if (ambient === undefined) throw driverUnavailable('setMailDriver() was never called');
253
- return ambient;
257
+ const driver = slot.current();
258
+ if (driver === undefined) throw driverUnavailable('no mail driver was installed');
259
+ return driver;
254
260
  }
255
261
 
256
262
  export function resetMailDriver(): void {
257
- ambient = undefined;
263
+ slot.reset();
258
264
  }
package/src/errors.ts CHANGED
@@ -204,13 +204,13 @@ export const driverUnavailable = (what: string): MailError =>
204
204
  new MailError({
205
205
  code: 'X_MAIL_DRIVER_UNAVAILABLE',
206
206
  cause: `${what} — nothing can deliver the message`,
207
- fix: 'setMailDriver(memoryMailDriver()) in dev, smtpMailDriver({ url: env.SMTP_URL }) live',
207
+ fix: 'export const runtime = { mail: memoryMailDriver() } in apps/<app>/runtime.ts for dev, or set SMTP_URL (or RESEND_API_KEY) in .env so the boot selects a live driver',
208
208
  meta: { what },
209
209
  });
210
210
 
211
211
  /**
212
212
  * A DEPLOYMENT set neither credential, where `X_MAIL_DRIVER_UNAVAILABLE` is a WIRING bug — one is
213
- * fixed by an operator setting a variable, the other by a developer calling `setMailDriver`, so
213
+ * fixed by an operator setting a variable, the other by a developer's `mail:` line in `apps/<app>/runtime.ts`, so
214
214
  * they are two codes and not one cause string.
215
215
  *
216
216
  * Raised on the send rather than at boot, deliberately: a boot refusal turns a working deploy of an
package/src/index.ts CHANGED
@@ -9,12 +9,7 @@ export { blocks } from './blocks';
9
9
  export { MAIL_CATALOG } from './catalog';
10
10
  // Type-only, so a sender can name an event without loading a receiver; the receivers are
11
11
  // `@ultimat3/mail/events`, kept off the barrel every serving role evaluates.
12
- export type {
13
- DeliveryEvent,
14
- DeliveryEventKind,
15
- DeliveryOutcome,
16
- DeliveryReceiver,
17
- } from './delivery-event';
12
+ export type { DeliveryEvent } from './delivery-event';
18
13
  export type {
19
14
  MailDriver,
20
15
  MailMessage,
@@ -30,8 +25,6 @@ export {
30
25
  mailDriver,
31
26
  memoryMailDriver,
32
27
  messageHeaders,
33
- resetMailDriver,
34
- setMailDriver,
35
28
  tryMailDriver,
36
29
  unconfiguredMailDriver,
37
30
  } from './driver';
@@ -40,65 +33,19 @@ export { selectMailDriver } from './driver-env';
40
33
  export type { MailFetch, ResendDriverOptions } from './driver-resend';
41
34
  export { resendMailDriver } from './driver-resend';
42
35
  export type { SesDriverOptions } from './driver-ses';
43
- export { sesEndpoint, sesMailDriver } from './driver-ses';
36
+ export { sesMailDriver } from './driver-ses';
44
37
  export type { SmtpDriverOptions } from './driver-smtp';
45
38
  export { smtpMailDriver } from './driver-smtp';
46
39
  export { assertEnvelopeAddress } from './envelope-address';
47
- export type {
48
- AddressRefusal,
49
- EnvelopeAddressField,
50
- MailErrorCode,
51
- MailErrorInit,
52
- SendFailure,
53
- SendStage,
54
- } from './errors';
55
- export {
56
- addressInvalid,
57
- driverUnavailable,
58
- layoutUnknown,
59
- localeMissing,
60
- MAIL_ERROR_CODES,
61
- MAIL_ERROR_RETRY,
62
- MAIL_ERROR_TITLES,
63
- MailError,
64
- mailCredentialMissing,
65
- mailDuplicate,
66
- mailKeyMissing,
67
- mailLayoutDuplicate,
68
- sendFailed,
69
- templateUnknown,
70
- textMissing,
71
- transformFailed,
72
- } from './errors';
40
+ export type { EnvelopeAddressField, MailErrorCode, MailErrorInit, SendStage } from './errors';
41
+ export { driverUnavailable, MailError, mailKeyMissing, sendFailed } from './errors';
73
42
  export { assertHeaderSafe } from './header-safety';
74
43
  export { safeMailHref } from './html';
75
-
76
44
  export { mailIdempotencyKey, mailMessageIdToken } from './idempotency';
77
45
  export { mailMessageSchema, sendMailJob } from './job';
78
- export type {
79
- ColorScheme,
80
- DarkRule,
81
- LayoutInput,
82
- MailLayout,
83
- MailToken,
84
- UnsubscribeSlot,
85
- } from './layout';
86
- export {
87
- BASE_LAYOUT,
88
- baseLayout,
89
- layoutFor,
90
- MAIL_TOKENS,
91
- registeredLayouts,
92
- registerLayout,
93
- token,
94
- } from './layout';
95
- export type {
96
- AnyMailDefinition,
97
- MailDefinition,
98
- MailInit,
99
- MailPreview,
100
- SendOptions,
101
- } from './mail';
46
+ export type { ColorScheme, LayoutInput, MailLayout, MailToken, UnsubscribeSlot } from './layout';
47
+ export { MAIL_TOKENS, registeredLayouts, registerLayout, token } from './layout';
48
+ export type { AnyMailDefinition, MailDefinition, MailInit, MailPreview, SendOptions } from './mail';
102
49
  export {
103
50
  defineMail,
104
51
  mailFor,
@@ -107,37 +54,13 @@ export {
107
54
  renderMessage,
108
55
  resetMails,
109
56
  send,
110
- sendById,
111
57
  } from './mail';
112
58
  export type { MailPreviewResult, PreviewOptions } from './preview';
113
- export { PREVIEW_RECIPIENT, previewableMailIds, previewMail } from './preview';
114
- export { previewMissing } from './preview-check';
59
+ export { previewableMailIds, previewMail } from './preview';
115
60
  export type { RenderableMail, RenderedMail, RenderOptions } from './render';
116
61
  export { renderMail, textOf } from './render';
117
62
  export type { RetainedMime, RetainedMimeEntry, RetainMimeOptions } from './retain-mime';
118
63
  export { DEFAULT_RETAIN_MIME_MAX_BYTES, RETAIN_MIME_CEILING_BYTES } from './retain-mime';
119
64
  export type { SmtpConnector, SmtpStream } from './smtp-client';
120
- export {
121
- FRAMEWORK_MAILS,
122
- type InviteInput,
123
- inviteInput,
124
- inviteMail,
125
- MFA_METHODS,
126
- type MfaEnrolledInput,
127
- mfaEnrolledInput,
128
- mfaEnrolledMail,
129
- type ResetPasswordInput,
130
- resetPasswordInput,
131
- resetPasswordMail,
132
- type SecurityAlertInput,
133
- securityAlertInput,
134
- securityAlertMail,
135
- type VerifyEmailInput,
136
- verifyEmailInput,
137
- verifyEmailMail,
138
- type WelcomeInput,
139
- welcomeInput,
140
- welcomeMail,
141
- } from './templates';
142
65
  export type { MailRendered, MailTransform, MailTransformMeta } from './transform';
143
- export { mailTransform, setMailTransform } from './transform';
66
+ export { setMailTransform } from './transform';
package/src/job.ts CHANGED
@@ -4,7 +4,8 @@
4
4
 
5
5
  import { type JobHandle, job } from '@ultimat3/jobs';
6
6
  import { type StandardSchemaV1, t } from '@ultimat3/schema';
7
- import { type MailMessage, mailDriver, type SendResult } from './driver';
7
+ import { deliverMail } from './deliver';
8
+ import type { MailMessage, SendResult } from './driver';
8
9
  import { addressRefusal } from './envelope-address';
9
10
  import { assertHeaderSafe } from './header-safety';
10
11
  import { mailIdempotencyKey } from './idempotency';
@@ -60,6 +61,6 @@ export const sendMailJob: JobHandle<MailMessage> = job<MailMessage>({
60
61
  // A step, so a worker that dies after the provider accepted the message and before the ack
61
62
  // replays the recorded result instead of sending the mail a second time (the exercise pass's
62
63
  // crash proof found the double send: `X_JOB_CRASH_DIVERGED`).
63
- return await step.run('send', () => mailDriver().send(input));
64
+ return await step.run('send', () => deliverMail(input));
64
65
  },
65
66
  });
package/src/mail.ts CHANGED
@@ -5,10 +5,11 @@
5
5
 
6
6
  import { assert, DEFAULT_TIME_ZONE, tryUseContext } from '@ultimat3/core';
7
7
  import type { TranslationMiss } from '@ultimat3/i18n';
8
- import { jobDriver, jobsFacade } from '@ultimat3/jobs';
8
+ import { jobDriver } from '@ultimat3/jobs';
9
9
  import { parse, type StandardSchemaV1, t } from '@ultimat3/schema';
10
10
  import type { MailTemplate } from './blocks';
11
- import { envelopeRecipients, type MailMessage, mailDriver, type SendResult } from './driver';
11
+ import { deliverMail } from './deliver';
12
+ import { envelopeRecipients, type MailMessage, type SendResult } from './driver';
12
13
  import { assertRecipientAddress } from './envelope-address';
13
14
  import { localeMissing, mailDuplicate, mailKeyMissing, templateUnknown } from './errors';
14
15
  import { assertHeaderSafe } from './header-safety';
@@ -228,14 +229,15 @@ export async function send<I>(
228
229
 
229
230
  if (options.sync === true || jobDriver() === undefined) {
230
231
  // The key is reported even inline, so a caller can dedupe its own retries either way.
231
- return { ...(await mailDriver().send(message)), idempotencyKey: key };
232
+ return { ...(await deliverMail(message)), idempotencyKey: key };
232
233
  }
233
234
 
234
- // Through the facade, never `queue.enqueue`: inside a transaction the row is STAGED on the
235
- // caller's connection and published after COMMIT, so a handler that rolls back after sending
236
- // mails nobody (`s1-con #3`). Outside one, the facade publishes straight to the same driver.
237
- // The key is the handle's own `mailIdempotencyKey`, and the driver dedupes on it by default.
238
- const enqueued = await jobsFacade().enqueue(sendMailJob, message);
235
+ // Through the handle, which is the facade under the producer span — never `queue.enqueue`:
236
+ // inside a transaction the row is STAGED on the caller's connection and published after COMMIT,
237
+ // so a handler that rolls back after sending mails nobody (`s1-con #3`). Outside one, the facade
238
+ // publishes straight to the same driver. The handle adds the `job.enqueue` event and the span a
239
+ // bare `jobsFacade().enqueue` skipped. The key is `mailIdempotencyKey`; the driver dedupes on it.
240
+ const enqueued = await sendMailJob.enqueue(message);
239
241
 
240
242
  return {
241
243
  id: enqueued.id,
@@ -3,7 +3,7 @@
3
3
  // or more `v1,<mac>` entries in `svix-signature` (more than one while a secret rotates). The mac is
4
4
  // compared in constant time, and checked BEFORE the window, so "stale" always means authentic.
5
5
 
6
- import { type Clock, ConfigInvalidError, systemClock, timingSafeEqual } from '@ultimat3/core';
6
+ import { type Clock, ConfigInvalidError, liveClock, timingSafeEqual } from '@ultimat3/core';
7
7
  import { deliveryEventUnverified } from './delivery-event-errors';
8
8
 
9
9
  /** Svix's own default, and the replay bound every Svix sender already assumes. */
@@ -85,7 +85,7 @@ export async function verifySvix(
85
85
  if (timingSafeEqual(candidate, expected)) matched = true;
86
86
  }
87
87
  if (!matched) throw deliveryEventUnverified('resend', 'signature');
88
- const now = (options.clock ?? systemClock).now().getTime();
88
+ const now = (options.clock ?? liveClock).now().getTime();
89
89
  if (Math.abs(now - Number(timestamp) * 1000) > options.toleranceMs) {
90
90
  throw deliveryEventUnverified('resend', 'stale');
91
91
  }
@@ -3,9 +3,9 @@
3
3
  // and an allowed topic ARN is not a secret, so a forger can name a fresh path per request. Four
4
4
  // bounds hold that to a fixed cost: LRU positives, a negative TTL, an in-flight cap, coalescing.
5
5
 
6
- import { type Clock, isUltimateError, renderThrowable, systemClock } from '@ultimat3/core';
6
+ import { type Clock, isUltimateError, liveClock, renderThrowable } from '@ultimat3/core';
7
7
  import { deliveryProviderUnreachable } from './delivery-event-errors';
8
- import { certificateSpki, pemCertificateDer } from './x509-spki';
8
+ import { pemCertificateSpki } from './x509-spki';
9
9
 
10
10
  /** PEM text for a certificate URL. Injected in tests; production GETs it over pinned https. */
11
11
  export type SnsCertificateFetch = (url: string) => Promise<string>;
@@ -32,7 +32,7 @@ export interface SnsCertificateCacheOptions {
32
32
  export function createSnsCertificateCache(
33
33
  options: SnsCertificateCacheOptions,
34
34
  ): SnsCertificateCache {
35
- const clock = options.clock ?? systemClock;
35
+ const clock: Clock = options.clock ?? liveClock;
36
36
  // Insertion order is recency order: a hit is deleted and re-set, so the first key is the LRU.
37
37
  const verified = new Map<string, Uint8Array<ArrayBuffer>>();
38
38
  const failedUntil = new Map<string, number>();
@@ -56,8 +56,7 @@ export function createSnsCertificateCache(
56
56
  if (isUltimateError(error)) throw error;
57
57
  throw deliveryProviderUnreachable('certificate', renderThrowable(error));
58
58
  }
59
- const der = pemCertificateDer(pem);
60
- const spki = der === undefined ? undefined : certificateSpki(der);
59
+ const spki = pemCertificateSpki(pem);
61
60
  if (spki === undefined) {
62
61
  throw deliveryProviderUnreachable(
63
62
  'certificate',
@@ -3,7 +3,7 @@
3
3
  // ITS topic), the certificate URL pinned to `https://sns.<topic region>.amazonaws.com`, the
4
4
  // canonical string per message type, RSA-SHA1 (v1) or RSA-SHA256 (v2) through Web Crypto.
5
5
 
6
- import { type Clock, systemClock } from '@ultimat3/core';
6
+ import { type Clock, liveClock } from '@ultimat3/core';
7
7
  import { t, validate } from '@ultimat3/schema';
8
8
  import { deliveryInstant } from './delivery-event';
9
9
  import { deliveryEventInvalid, deliveryEventUnverified } from './delivery-event-errors';
@@ -157,7 +157,7 @@ export async function verifySnsMessage(
157
157
  }
158
158
  // After the signature, like `@ultimat3/http`'s receiver: "stale" then always means authentic.
159
159
  const sentAt = deliveryInstant('ses', fields.Timestamp).getTime();
160
- const now = (options.clock ?? systemClock).now().getTime();
160
+ const now = (options.clock ?? liveClock).now().getTime();
161
161
  if (Math.abs(now - sentAt) > options.toleranceMs) {
162
162
  throw deliveryEventUnverified('ses', 'stale');
163
163
  }
package/src/transform.ts CHANGED
@@ -41,7 +41,7 @@ export type MailTransform = (
41
41
 
42
42
  let ambient: MailTransform | undefined;
43
43
 
44
- /** Install the app's transform; `undefined` removes it. One per process, like `setMailDriver`. */
44
+ /** Install the app's transform; `undefined` removes it. One per process, like the mail driver. */
45
45
  export function setMailTransform(transform: MailTransform | undefined): void {
46
46
  ambient = transform;
47
47
  }
package/src/x509-spki.ts CHANGED
@@ -1,41 +1,8 @@
1
1
  // Single responsibility: the public key out of a PEM X.509 certificate, as the SubjectPublicKeyInfo
2
- // bytes Web Crypto imports (`importKey('spki', …)`). Web Crypto takes no certificate, so this walks
3
- // just enough DER to find the seventh field of `tbsCertificate` (RFC 5280 §4.1). Malformed input is
4
- // `undefined`, never a throw: the bytes came off a network.
2
+ // bytes Web Crypto imports (`importKey('spki', …)`). The PEM armour is SNS's and read here; the DER
3
+ // walk is core's `x509Spki`. Malformed input is `undefined`, never a throw.
5
4
 
6
- interface Tlv {
7
- readonly tag: number;
8
- /** Offset of the tag byte. */
9
- readonly start: number;
10
- /** Offset of the first content byte. */
11
- readonly body: number;
12
- /** Offset one past the last content byte. */
13
- readonly end: number;
14
- }
15
-
16
- const SEQUENCE = 0x30;
17
- const VERSION = 0xa0;
18
- /** `serialNumber`, `signature`, `issuer`, `validity`, `subject` — skipped to reach the key. */
19
- const FIELDS_BEFORE_KEY = 5;
20
-
21
- /** One DER tag-length-value at `at`, bounded by `limit`. Definite lengths only, as DER requires. */
22
- function readTlv(bytes: Uint8Array, at: number, limit: number): Tlv | undefined {
23
- if (at + 2 > limit) return undefined;
24
- const tag = bytes[at] ?? 0;
25
- const first = bytes[at + 1] ?? 0;
26
- let body = at + 2;
27
- let length = first;
28
- if (first & 0x80) {
29
- const count = first & 0x7f;
30
- if (count === 0 || count > 4 || body + count > limit) return undefined;
31
- length = 0;
32
- for (let index = 0; index < count; index += 1)
33
- length = length * 256 + (bytes[body + index] ?? 0);
34
- body += count;
35
- }
36
- const end = body + length;
37
- return end > limit ? undefined : { tag, start: at, body, end };
38
- }
5
+ import { x509Spki } from '@ultimat3/core';
39
6
 
40
7
  /** The DER inside the first `CERTIFICATE` block, or `undefined` for anything else. */
41
8
  export function pemCertificateDer(pem: string): Uint8Array | undefined {
@@ -49,19 +16,8 @@ export function pemCertificateDer(pem: string): Uint8Array | undefined {
49
16
  }
50
17
  }
51
18
 
52
- /** `Certificate → tbsCertificate → subjectPublicKeyInfo`, the whole element, tag included. */
53
- export function certificateSpki(der: Uint8Array): Uint8Array | undefined {
54
- const certificate = readTlv(der, 0, der.byteLength);
55
- if (certificate?.tag !== SEQUENCE) return undefined;
56
- const tbs = readTlv(der, certificate.body, certificate.end);
57
- if (tbs?.tag !== SEQUENCE) return undefined;
58
- let field = readTlv(der, tbs.body, tbs.end);
59
- // `[0] EXPLICIT version` is absent on a v1 certificate and present on every v3 one.
60
- if (field?.tag === VERSION) field = readTlv(der, field.end, tbs.end);
61
- for (let skipped = 0; skipped < FIELDS_BEFORE_KEY; skipped += 1) {
62
- if (field === undefined) return undefined;
63
- field = readTlv(der, field.end, tbs.end);
64
- }
65
- if (field?.tag !== SEQUENCE) return undefined;
66
- return der.slice(field.start, field.end);
19
+ /** The `subjectPublicKeyInfo` of the first `CERTIFICATE` block, or `undefined`. */
20
+ export function pemCertificateSpki(pem: string): Uint8Array<ArrayBuffer> | undefined {
21
+ const der = pemCertificateDer(pem);
22
+ return der === undefined ? undefined : x509Spki(der);
67
23
  }
@@ -1,41 +0,0 @@
1
- // Single responsibility: the framework's own transactional mails, gathered. `FRAMEWORK_MAILS` is
2
- // the list a host projects them from — there is no `x mail` command, and the header claimed one.
3
- // `templates.test.ts` holds every entry to a rendered case, so a mail added here and left
4
- // untranslated is a failing test rather than a template nobody notices.
5
-
6
- import type { AnyMailDefinition } from '../mail';
7
- import { inviteMail } from './invite';
8
- import { mfaEnrolledMail } from './mfa-enrolled';
9
- import { resetPasswordMail } from './reset-password';
10
- import { securityAlertMail } from './security-alert';
11
- import { verifyEmailMail } from './verify-email';
12
- import { welcomeMail } from './welcome';
13
-
14
- export { type InviteInput, inviteInput, inviteMail } from './invite';
15
- export {
16
- MFA_METHODS,
17
- type MfaEnrolledInput,
18
- mfaEnrolledInput,
19
- mfaEnrolledMail,
20
- } from './mfa-enrolled';
21
- export {
22
- type ResetPasswordInput,
23
- resetPasswordInput,
24
- resetPasswordMail,
25
- } from './reset-password';
26
- export {
27
- type SecurityAlertInput,
28
- securityAlertInput,
29
- securityAlertMail,
30
- } from './security-alert';
31
- export { type VerifyEmailInput, verifyEmailInput, verifyEmailMail } from './verify-email';
32
- export { type WelcomeInput, welcomeInput, welcomeMail } from './welcome';
33
-
34
- export const FRAMEWORK_MAILS: readonly AnyMailDefinition[] = [
35
- welcomeMail,
36
- verifyEmailMail,
37
- resetPasswordMail,
38
- inviteMail,
39
- mfaEnrolledMail,
40
- securityAlertMail,
41
- ];
@@ -1,29 +0,0 @@
1
- // Single responsibility: the org-invitation mail.
2
-
3
- import { type Infer, t } from '@ultimat3/schema';
4
- import { blocks } from '../blocks';
5
- import { defineMail } from '../mail';
6
-
7
- export const inviteInput = t.object({
8
- inviterName: t.string,
9
- orgName: t.string,
10
- url: t.url,
11
- expiresHours: t.number.int().min(1),
12
- });
13
-
14
- export type InviteInput = Infer<typeof inviteInput>;
15
-
16
- export const inviteMail = defineMail<InviteInput>({
17
- id: 'invite',
18
- subject: 'mail.invite.subject',
19
- input: inviteInput,
20
- template: ({ data }) => [
21
- blocks.heading('mail.invite.heading', { orgName: data.orgName }),
22
- blocks.paragraph('mail.invite.body', {
23
- inviterName: data.inviterName,
24
- orgName: data.orgName,
25
- }),
26
- blocks.button('mail.invite.cta', data.url),
27
- blocks.paragraph('mail.invite.expiry', { count: data.expiresHours }),
28
- ],
29
- });
@@ -1,37 +0,0 @@
1
- // Single responsibility: the "a second factor was added" notice. The enrolment time is
2
- // formatted in the recipient's zone — "at 03:12" is only useful if it is their 03:12.
3
-
4
- import { type Infer, t } from '@ultimat3/schema';
5
- import { formatDateTime, instant } from '@ultimat3/time';
6
- import { blocks } from '../blocks';
7
- import { defineMail } from '../mail';
8
-
9
- export const MFA_METHODS = ['totp', 'webauthn', 'sms'] as const;
10
-
11
- export const mfaEnrolledInput = t.object({
12
- name: t.string,
13
- method: t.enum(MFA_METHODS),
14
- at: t.date,
15
- });
16
-
17
- export type MfaEnrolledInput = Infer<typeof mfaEnrolledInput>;
18
-
19
- export const mfaEnrolledMail = defineMail<MfaEnrolledInput>({
20
- id: 'mfa-enrolled',
21
- subject: 'mail.mfa-enrolled.subject',
22
- input: mfaEnrolledInput,
23
- template: ({ data, t: translate, locale, tz }) => [
24
- blocks.heading('mail.mfa-enrolled.heading', { name: data.name }),
25
- blocks.paragraph('mail.mfa-enrolled.body'),
26
- blocks.detail(
27
- 'mail.mfa-enrolled.method-label',
28
- translate(`mail.mfa-enrolled.method-${data.method}`),
29
- ),
30
- blocks.detail(
31
- 'mail.mfa-enrolled.at-label',
32
- formatDateTime(instant(data.at), { locale, zone: tz, style: 'medium' }),
33
- ),
34
- blocks.divider(),
35
- blocks.paragraph('mail.mfa-enrolled.help'),
36
- ],
37
- });
@@ -1,27 +0,0 @@
1
- // Single responsibility: the password-reset mail. The "you did not ask for this" line is not
2
- // optional politeness — it is how a targeted reset attempt gets reported.
3
-
4
- import { type Infer, t } from '@ultimat3/schema';
5
- import { blocks } from '../blocks';
6
- import { defineMail } from '../mail';
7
-
8
- export const resetPasswordInput = t.object({
9
- name: t.string,
10
- url: t.url,
11
- expiresMinutes: t.number.int().min(1),
12
- });
13
-
14
- export type ResetPasswordInput = Infer<typeof resetPasswordInput>;
15
-
16
- export const resetPasswordMail = defineMail<ResetPasswordInput>({
17
- id: 'reset-password',
18
- subject: 'mail.reset-password.subject',
19
- input: resetPasswordInput,
20
- template: ({ data }) => [
21
- blocks.heading('mail.reset-password.heading', { name: data.name }),
22
- blocks.paragraph('mail.reset-password.body'),
23
- blocks.button('mail.reset-password.cta', data.url),
24
- blocks.paragraph('mail.reset-password.expiry', { count: data.expiresMinutes }),
25
- blocks.paragraph('mail.reset-password.ignore'),
26
- ],
27
- });
@@ -1,36 +0,0 @@
1
- // Single responsibility: the security-alert mail — the one transactional mail that is allowed
2
- // to alarm. Event, IP and time are rendered as details, never woven into a sentence, so they
3
- // survive translation intact.
4
-
5
- import { type Infer, t } from '@ultimat3/schema';
6
- import { formatDateTime, instant } from '@ultimat3/time';
7
- import { blocks } from '../blocks';
8
- import { defineMail } from '../mail';
9
-
10
- export const securityAlertInput = t.object({
11
- name: t.string,
12
- /** A machine event id (`session.new-device`), not prose. */
13
- event: t.string,
14
- ip: t.string,
15
- at: t.date,
16
- });
17
-
18
- export type SecurityAlertInput = Infer<typeof securityAlertInput>;
19
-
20
- export const securityAlertMail = defineMail<SecurityAlertInput>({
21
- id: 'security-alert',
22
- subject: 'mail.security-alert.subject',
23
- input: securityAlertInput,
24
- template: ({ data, locale, tz }) => [
25
- blocks.heading('mail.security-alert.heading', { name: data.name }),
26
- blocks.callout('mail.security-alert.alert', 'danger'),
27
- blocks.detail('mail.security-alert.event-label', data.event),
28
- blocks.detail('mail.security-alert.ip-label', data.ip),
29
- blocks.detail(
30
- 'mail.security-alert.at-label',
31
- formatDateTime(instant(data.at), { locale, zone: tz, style: 'medium' }),
32
- ),
33
- blocks.divider(),
34
- blocks.paragraph('mail.security-alert.help'),
35
- ],
36
- });
@@ -1,27 +0,0 @@
1
- // Single responsibility: the email-verification mail. The expiry line is a plural key, so a
2
- // 1-minute link never reads "1 minutes".
3
-
4
- import { type Infer, t } from '@ultimat3/schema';
5
- import { blocks } from '../blocks';
6
- import { defineMail } from '../mail';
7
-
8
- export const verifyEmailInput = t.object({
9
- name: t.string,
10
- url: t.url,
11
- expiresMinutes: t.number.int().min(1),
12
- });
13
-
14
- export type VerifyEmailInput = Infer<typeof verifyEmailInput>;
15
-
16
- export const verifyEmailMail = defineMail<VerifyEmailInput>({
17
- id: 'verify-email',
18
- subject: 'mail.verify-email.subject',
19
- input: verifyEmailInput,
20
- template: ({ data }) => [
21
- blocks.heading('mail.verify-email.heading', { name: data.name }),
22
- blocks.paragraph('mail.verify-email.body'),
23
- blocks.button('mail.verify-email.cta', data.url),
24
- blocks.paragraph('mail.verify-email.expiry', { count: data.expiresMinutes }),
25
- blocks.paragraph('mail.verify-email.ignore'),
26
- ],
27
- });
@@ -1,24 +0,0 @@
1
- // Single responsibility: the welcome mail, as data. Keys only — the words live in a catalog.
2
-
3
- import { type Infer, t } from '@ultimat3/schema';
4
- import { blocks } from '../blocks';
5
- import { defineMail } from '../mail';
6
-
7
- export const welcomeInput = t.object({
8
- name: t.string,
9
- appName: t.string,
10
- url: t.url,
11
- });
12
-
13
- export type WelcomeInput = Infer<typeof welcomeInput>;
14
-
15
- export const welcomeMail = defineMail<WelcomeInput>({
16
- id: 'welcome',
17
- subject: 'mail.welcome.subject',
18
- input: welcomeInput,
19
- template: ({ data }) => [
20
- blocks.heading('mail.welcome.heading', { name: data.name }),
21
- blocks.paragraph('mail.welcome.body', { appName: data.appName }),
22
- blocks.button('mail.welcome.cta', data.url, { appName: data.appName }),
23
- ],
24
- });