@ultimat3/mail 31.25.0 → 31.27.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 +13 -1
- package/README.md +57 -0
- package/package.json +9 -7
- package/src/errors.ts +7 -0
- package/src/inbound-attachments.ts +109 -0
- package/src/inbound-mail.ts +95 -0
- package/src/inbound-message.ts +82 -0
- package/src/inbound-resend.ts +140 -0
- package/src/inbound-ses.ts +138 -0
- package/src/inbound-types.ts +151 -0
- package/src/inbound.ts +29 -0
- package/src/mime-parse-address.ts +144 -0
- package/src/mime-parse-decode.ts +113 -0
- package/src/mime-parse-errors.ts +72 -0
- package/src/mime-parse-headers.ts +202 -0
- package/src/mime-parse.ts +169 -0
package/CLAUDE.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @ultimat3/mail — agent notes
|
|
2
2
|
|
|
3
|
-
**Tier 4** (`scripts/lib/tiers.ts`). May import `core`, `schema`, `i18n`, `time`, `money`, `jobs
|
|
3
|
+
**Tier 4** (`scripts/lib/tiers.ts`). May import `core`, `schema`, `i18n`, `time`, `money`, `jobs`, `storage` (inbound attachments); never `auth`, `http`, `ui`, `render`. **Zero external deps** — no nodemailer, no MJML, no CSS library.
|
|
4
4
|
|
|
5
5
|
## Boundary
|
|
6
6
|
|
|
@@ -29,6 +29,10 @@
|
|
|
29
29
|
| `resend-signature.ts` | Svix verification: HMAC over `id.timestamp.body`, constant-time, then the window |
|
|
30
30
|
| `resend-event-receiver.ts` | `resendEventReceiver` + the Resend payload → events |
|
|
31
31
|
| `events.ts` | the `@ultimat3/mail/events` subpath: the receivers, kept off the barrel |
|
|
32
|
+
| `inbound.ts` · `inbound-mail.ts` | `@ultimat3/mail/inbound` · `inboundMail()`, a factory over jobs' `webhookReceiver()` |
|
|
33
|
+
| `inbound-ses.ts` · `inbound-resend.ts` | the two providers: door (verify, then envelope → row) + the raw MIME for the job |
|
|
34
|
+
| `inbound-message.ts` · `inbound-attachments.ts` · `inbound-types.ts` | row → `InboundMessage`; attachments via storage's `validateUpload` + `put`; the shapes |
|
|
35
|
+
| `mime-parse*.ts` | the bounded inbound MIME parser (tree, decodes, headers, addresses, `X_MAIL_INBOUND_*`) |
|
|
32
36
|
| `smtp-client.ts` | the conversation: greeting → EHLO → STARTTLS → AUTH → envelope → DATA |
|
|
33
37
|
| `smtp-protocol.ts` | pure protocol: reply framing, capabilities, AUTH payloads, dot-stuffing |
|
|
34
38
|
| `smtp-socket.ts` | the one production `SmtpStream`, over `Bun.connect` |
|
|
@@ -238,6 +242,14 @@
|
|
|
238
242
|
`openssl x509 -pubkey` gave the SPKI `x509-spki.ts` extracts).
|
|
239
243
|
- **`send()` refuses on the renderer's record, never on the bytes** (`X_MAIL_KEY_MISSING`, terminal, before the transform). A `⟦` may be user data. `recordingTranslator` (`@ultimat3/i18n`) selects through `selectMessageKey`, the selector `t()` uses, because `has()` says yes for a plural family read without a `count`, where `t()` renders `⟦key⟧`. A catalog value that is a marker is a miss: it is what `x i18n sync` seeds, so the refusal's fix must not turn it into a delivery. Templates get the recording `t` too. `renderMessage` drops `misses` (previews show the brackets); nothing on `MailMessage` carries them.
|
|
240
244
|
|
|
245
|
+
- **Inbound mail verifies with the delivery receivers' verifiers, never a copy** (`As of 2026-11-15`):
|
|
246
|
+
SES's door IS `sesEventReceiver.receive` (signature + subscription protocol), then the same bytes
|
|
247
|
+
are read for `Message`; Resend's is `verifySvix`. A forgery is `X_MAIL_EVENT_UNVERIFIED`. The job
|
|
248
|
+
parses the MIME, never the door; every parse/bound refusal is `X_MAIL_INBOUND_MALFORMED`/`_TOO_LARGE`.
|
|
249
|
+
- **The inbound parser is linear in sender bytes**: scan by index, never a regex with overlapping or
|
|
250
|
+
lookahead-retried quantifiers over a sender's value. `mime-parse-redos.test.ts` holds each shape
|
|
251
|
+
that was quadratic or exponential (50 KB of spaces froze a worker 11 s) to a time bound.
|
|
252
|
+
|
|
241
253
|
## Commands
|
|
242
254
|
|
|
243
255
|
```bash
|
package/README.md
CHANGED
|
@@ -196,6 +196,61 @@ export const resend = resendEventReceiver({ secret: env['RESEND_WEBHOOK_SECRET']
|
|
|
196
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` |
|
|
197
197
|
| `resendEventReceiver` | Svix: HMAC-SHA256 over `svix-id.svix-timestamp.body` under the `whsec_` secret, constant-time, any `v1,` entry, within `toleranceMs` (5 min) |
|
|
198
198
|
|
|
199
|
+
### Inbound mail
|
|
200
|
+
|
|
201
|
+
`As of 2026-11-15`. Imported from **`@ultimat3/mail/inbound`**, never the barrel. `inboundMail()` is
|
|
202
|
+
a factory over jobs' `webhookReceiver()` (itself a factory over `job`): declaring it in
|
|
203
|
+
`defineApi({ jobs })` mounts its `POST` route. The door verifies the provider's signature over the
|
|
204
|
+
exact bytes, reads the envelope and queues a durable row; the job reads the raw MIME, parses it under
|
|
205
|
+
`limits`, stores the attachments and calls `handle` with ONE typed `InboundMessage`.
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
import { inboundMail, sesInbound } from '@ultimat3/mail/inbound';
|
|
209
|
+
|
|
210
|
+
declare const env: Record<string, string>;
|
|
211
|
+
|
|
212
|
+
export const supportInbox = inboundMail({
|
|
213
|
+
name: 'support.inbound',
|
|
214
|
+
path: '/hooks/mail/inbound',
|
|
215
|
+
// A thunk, built on the first delivery: the worker and the scheduler import this too.
|
|
216
|
+
provider: () => sesInbound({ topicArns: [env['SES_INBOUND_TOPIC_ARN'] ?? ''] }),
|
|
217
|
+
tenant: 'none',
|
|
218
|
+
handle: async ({ message }) => ({ from: message.from?.address, files: message.attachments.length }),
|
|
219
|
+
});
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`provider` is a thunk, called on the first delivery and kept: a provider refuses a missing secret
|
|
223
|
+
when it is BUILT (`X_CONFIG_INVALID`), and a role that never receives must still boot. The door's
|
|
224
|
+
body ceiling is `maxBodyBytes` (default 1 MiB).
|
|
225
|
+
|
|
226
|
+
| Provider | Door proves | The job reads the MIME from |
|
|
227
|
+
|---|---|---|
|
|
228
|
+
| `sesInbound({ topicArns })` | SNS, through `sesEventReceiver` (one verifier); a `SubscriptionConfirmation` is that receiver's | the notification's `content` (receipt rule SNS action, `BASE64` or `UTF8`); none is `X_MAIL_INBOUND_MALFORMED` `content-missing` |
|
|
229
|
+
| `resendInbound({ secret, apiKey })` | Svix over the `email.received` body; any other type answers 200 and queues nothing | `GET /emails/receiving/:id` with the key, then `raw.download_url` WITHOUT it (a public dial) |
|
|
230
|
+
|
|
231
|
+
| `InboundMessage` field | |
|
|
232
|
+
|---|---|
|
|
233
|
+
| `eventId` | the provider's message id: the dedupe key, and the attachment folder (hashed) |
|
|
234
|
+
| `recipients` | from the provider's signed payload, never a header: SES's SMTP envelope (Bcc included); Resend's `to` (not documented as the envelope — route only on your receiving domain). `tenant(recipients)` picks the org |
|
|
235
|
+
| `from` · `to` · `cc` · `replyTo` | `{ address, name }`, RFC 2047 decoded |
|
|
236
|
+
| `subject` · `date` · `messageId` · `headers` | decoded; `headers` ordered, `Received` repeats |
|
|
237
|
+
| `text` · `html` | the inline bodies, charset-decoded. `html`, `filename` and `contentId` are sender-controlled and unsanitised: never render `html` on your origin |
|
|
238
|
+
| `attachments` | `stored: true` + `key`/`contentType`/`checksum`, or `stored: false` + `refusal` (storage's code, `X_MAIL_INBOUND_MALFORMED` for a part whose transfer encoding did not decode, `'verdict'` for an SES virus FAIL, or `'disabled'`) |
|
|
239
|
+
| `verdicts` | SES spam/virus/SPF/DKIM/DMARC, as SES spells them; deciding on them is the app's |
|
|
240
|
+
|
|
241
|
+
| Bound (`limits`) | Default | Over it |
|
|
242
|
+
|---|---|---|
|
|
243
|
+
| `maxBytes` · `maxParts` · `maxDepth` · `maxAttachments` · `maxHeaderBytes` | 10 MiB · 100 · 8 · 20 · 64 KiB | `X_MAIL_INBOUND_TOO_LARGE`, refused whole |
|
|
244
|
+
|
|
245
|
+
Attachments go through storage's `validateUpload` (size, allowlist, magic-byte sniff) and `put`, at
|
|
246
|
+
`<prefix>/<sha256(eventId)>/<index>` (`org/<id>/…` when tenanted), so a retry rewrites the same
|
|
247
|
+
keys. Default allowlist `INBOUND_ATTACHMENT_TYPES`: images, documents, `text/plain`, `text/csv` —
|
|
248
|
+
never HTML or SVG. A file the policy refuses, or one that does not decode, arrives `stored: false`;
|
|
249
|
+
the message still arrives. A part with no `Content-Type` that is a file is `application/octet-stream`.
|
|
250
|
+
`attachments: false` stores nothing. An SES virus verdict of `FAIL` stores none either (`refusal:
|
|
251
|
+
'verdict'`) unless `attachments: { keepOnVirusFail: true }`. Unscanned: run the app's `uploadScanner` over `key` if you
|
|
252
|
+
need a verdict.
|
|
253
|
+
|
|
199
254
|
## No framework mails
|
|
200
255
|
|
|
201
256
|
The package ships none (v31). Every mail is an app's own `defineMail`; `@ultimat3/auth` sends
|
|
@@ -230,6 +285,8 @@ locale, so a miss a `send` would refuse is red at the gate. No preview: `X_MAIL_
|
|
|
230
285
|
| `X_MAIL_EVENT_UNVERIFIED` | a delivery notification failed its signature check — `meta.reason` names which (`unsigned`, `signature`, `stale`, `topic`, `certificate-url`, `signature-version`); answer 401 |
|
|
231
286
|
| `X_MAIL_EVENT_INVALID` | authentic or not, the body is not the provider's notification shape (`meta.problem`); answer 400 |
|
|
232
287
|
| `X_MAIL_EVENT_PROVIDER_UNREACHABLE` | the SNS certificate or confirm URL did not answer; answer 503 so SNS redelivers |
|
|
288
|
+
| `X_MAIL_INBOUND_MALFORMED` | the message is not MIME the parser reads (`meta.problem`); terminal, the dead-letter row is the record — except `raw-unavailable`, which retries |
|
|
289
|
+
| `X_MAIL_INBOUND_TOO_LARGE` | the message crossed `limits.<meta.limit>`; raise it only for mail you expect |
|
|
233
290
|
| `X_MAIL_SEND_FAILED` | the `cause` names the stage, the provider's status and whether a retry can help — and so does `error.retry`, which is what `sendMailJob` acts on: `terminal` dead-letters a 550 or a rejected credential at attempt 1 instead of sending it four more times |
|
|
234
291
|
|
|
235
292
|
### Error classes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/mail",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.27.0",
|
|
4
4
|
"description": "Transactional email as data: one template renders HTML and text, sent through a job.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"exports": {
|
|
26
26
|
".": "./src/index.ts",
|
|
27
27
|
"./adapter": "./src/adapter.ts",
|
|
28
|
-
"./events": "./src/events.ts"
|
|
28
|
+
"./events": "./src/events.ts",
|
|
29
|
+
"./inbound": "./src/inbound.ts"
|
|
29
30
|
},
|
|
30
31
|
"files": [
|
|
31
32
|
"src",
|
|
@@ -43,10 +44,11 @@
|
|
|
43
44
|
"test": "bun test"
|
|
44
45
|
},
|
|
45
46
|
"dependencies": {
|
|
46
|
-
"@ultimat3/core": "31.
|
|
47
|
-
"@ultimat3/i18n": "31.
|
|
48
|
-
"@ultimat3/jobs": "31.
|
|
49
|
-
"@ultimat3/schema": "31.
|
|
50
|
-
"@ultimat3/
|
|
47
|
+
"@ultimat3/core": "31.27.0",
|
|
48
|
+
"@ultimat3/i18n": "31.27.0",
|
|
49
|
+
"@ultimat3/jobs": "31.27.0",
|
|
50
|
+
"@ultimat3/schema": "31.27.0",
|
|
51
|
+
"@ultimat3/storage": "31.27.0",
|
|
52
|
+
"@ultimat3/time": "31.27.0"
|
|
51
53
|
}
|
|
52
54
|
}
|
package/src/errors.ts
CHANGED
|
@@ -29,6 +29,8 @@ export const MAIL_ERROR_CODES = [
|
|
|
29
29
|
'X_MAIL_KEY_MISSING',
|
|
30
30
|
'X_MAIL_PREVIEW_INVALID',
|
|
31
31
|
'X_MAIL_PREVIEW_MISSING',
|
|
32
|
+
'X_MAIL_INBOUND_MALFORMED',
|
|
33
|
+
'X_MAIL_INBOUND_TOO_LARGE',
|
|
32
34
|
] as const;
|
|
33
35
|
|
|
34
36
|
export type MailErrorCode = (typeof MAIL_ERROR_CODES)[number];
|
|
@@ -50,6 +52,8 @@ export const MAIL_ERROR_TITLES: Readonly<Record<MailErrorCode, string>> = {
|
|
|
50
52
|
X_MAIL_KEY_MISSING: 'a mail rendered a key or slot with no value in its locale',
|
|
51
53
|
X_MAIL_PREVIEW_INVALID: "a mail's declared preview fails its own input schema",
|
|
52
54
|
X_MAIL_PREVIEW_MISSING: 'this mail declares no preview',
|
|
55
|
+
X_MAIL_INBOUND_MALFORMED: 'an inbound message is not MIME this parser reads',
|
|
56
|
+
X_MAIL_INBOUND_TOO_LARGE: 'an inbound message crosses a declared bound',
|
|
53
57
|
};
|
|
54
58
|
|
|
55
59
|
// Titles must be registered for `format()` to render the contract's first line. Every code above is
|
|
@@ -75,6 +79,9 @@ registerErrorCodes(
|
|
|
75
79
|
export const MAIL_ERROR_RETRY = {
|
|
76
80
|
X_MAIL_SEND_FAILED: 'retryable',
|
|
77
81
|
X_MAIL_KEY_MISSING: 'terminal',
|
|
82
|
+
// Terminal as a class; `raw-unavailable` alone is retryable, per instance (`mime-parse-errors.ts`).
|
|
83
|
+
X_MAIL_INBOUND_MALFORMED: 'terminal',
|
|
84
|
+
X_MAIL_INBOUND_TOO_LARGE: 'terminal',
|
|
78
85
|
} as const satisfies Readonly<Partial<Record<MailErrorCode, ErrorRetry>>>;
|
|
79
86
|
|
|
80
87
|
registerErrorRetry(MAIL_ERROR_RETRY);
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Single responsibility: a parsed message's attachments → storage, through storage's own upload
|
|
2
|
+
// gate (`validateUpload`: size, allowlist, magic-byte sniff) and `put`. Keys are opaque and
|
|
3
|
+
// derived from the message id, so a retried job writes the same keys — never a second copy.
|
|
4
|
+
|
|
5
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
6
|
+
import {
|
|
7
|
+
DOCUMENT_CONTENT_TYPES,
|
|
8
|
+
disk as defaultDisk,
|
|
9
|
+
IMAGE_CONTENT_TYPES,
|
|
10
|
+
isStorageError,
|
|
11
|
+
scopedKey,
|
|
12
|
+
type UploadPolicy,
|
|
13
|
+
uploadPolicy,
|
|
14
|
+
validateUpload,
|
|
15
|
+
} from '@ultimat3/storage';
|
|
16
|
+
import type { InboundAttachment, InboundAttachmentOptions } from './inbound-types';
|
|
17
|
+
import type { MimeAttachment } from './mime-parse';
|
|
18
|
+
|
|
19
|
+
/** What mail carries and nothing executes: images, documents, plain text and CSV. Never HTML/SVG. */
|
|
20
|
+
export const INBOUND_ATTACHMENT_TYPES: readonly string[] = Object.freeze([
|
|
21
|
+
...IMAGE_CONTENT_TYPES,
|
|
22
|
+
...DOCUMENT_CONTENT_TYPES,
|
|
23
|
+
'text/plain',
|
|
24
|
+
'text/csv',
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
export const DEFAULT_INBOUND_PREFIX = 'inbound-mail';
|
|
28
|
+
|
|
29
|
+
let defaultPolicy: UploadPolicy | undefined;
|
|
30
|
+
const policyOf = (options: InboundAttachmentOptions): UploadPolicy => {
|
|
31
|
+
if (options.policy !== undefined) return options.policy;
|
|
32
|
+
defaultPolicy ??= uploadPolicy({
|
|
33
|
+
maxBytes: 10 * 1024 * 1024,
|
|
34
|
+
allowedContentTypes: INBOUND_ATTACHMENT_TYPES,
|
|
35
|
+
});
|
|
36
|
+
return defaultPolicy;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** A digest, never the id itself: a provider id may hold characters no storage key takes. */
|
|
40
|
+
const folderOf = (eventId: string): string =>
|
|
41
|
+
new Bun.CryptoHasher('sha256').update(eventId).digest('hex').slice(0, 32);
|
|
42
|
+
|
|
43
|
+
export interface StoreAttachmentsInput {
|
|
44
|
+
readonly attachments: readonly MimeAttachment[];
|
|
45
|
+
readonly options: InboundAttachmentOptions | false;
|
|
46
|
+
readonly eventId: string;
|
|
47
|
+
readonly orgId: string | undefined;
|
|
48
|
+
/** Store none, each refused with this: the provider's virus verdict was FAIL (`'verdict'`). */
|
|
49
|
+
readonly withheld?: string | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function storeAttachments(
|
|
53
|
+
input: StoreAttachmentsInput,
|
|
54
|
+
): Promise<readonly InboundAttachment[]> {
|
|
55
|
+
const { options } = input;
|
|
56
|
+
const base = (attachment: MimeAttachment) => ({
|
|
57
|
+
filename: attachment.filename,
|
|
58
|
+
declaredType: attachment.contentType,
|
|
59
|
+
size: attachment.bytes.byteLength,
|
|
60
|
+
contentId: attachment.contentId,
|
|
61
|
+
inline: attachment.inline,
|
|
62
|
+
});
|
|
63
|
+
if (options === false || input.withheld !== undefined) {
|
|
64
|
+
const why = options === false ? 'disabled' : (input.withheld ?? 'disabled');
|
|
65
|
+
return input.attachments.map((a) => ({ ...base(a), stored: false, refusal: a.refusal ?? why }));
|
|
66
|
+
}
|
|
67
|
+
if (input.attachments.length === 0) return [];
|
|
68
|
+
const target = options.disk?.() ?? defaultDisk();
|
|
69
|
+
const policy = policyOf(options);
|
|
70
|
+
const prefix = options.prefix ?? DEFAULT_INBOUND_PREFIX;
|
|
71
|
+
const folder = folderOf(input.eventId);
|
|
72
|
+
const out: InboundAttachment[] = [];
|
|
73
|
+
for (const [index, attachment] of input.attachments.entries()) {
|
|
74
|
+
// A part whose transfer encoding did not decode has no bytes to store: its refusal travels.
|
|
75
|
+
if (attachment.refusal !== undefined) {
|
|
76
|
+
out.push({ ...base(attachment), stored: false, refusal: attachment.refusal });
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const key =
|
|
80
|
+
input.orgId === undefined
|
|
81
|
+
? `${prefix}/${folder}/${index}`
|
|
82
|
+
: scopedKey(input.orgId, prefix, folder, String(index));
|
|
83
|
+
let validated: ReturnType<typeof validateUpload>;
|
|
84
|
+
try {
|
|
85
|
+
validated = validateUpload(
|
|
86
|
+
{ key, declaredContentType: attachment.contentType, bytes: attachment.bytes },
|
|
87
|
+
policy,
|
|
88
|
+
);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
// The policy's verdict on THIS file: the prefix was screened at `inboundMail()`, so a
|
|
91
|
+
// storage refusal here is about the bytes, the size or the type.
|
|
92
|
+
if (!isStorageError(error) || !isUltimateError(error)) throw error;
|
|
93
|
+
out.push({ ...base(attachment), stored: false, refusal: error.code });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
await target.put(validated.key, validated.bytes, {
|
|
97
|
+
contentType: validated.contentType,
|
|
98
|
+
checksum: validated.checksum,
|
|
99
|
+
});
|
|
100
|
+
out.push({
|
|
101
|
+
...base(attachment),
|
|
102
|
+
stored: true,
|
|
103
|
+
key: validated.key,
|
|
104
|
+
contentType: validated.contentType,
|
|
105
|
+
checksum: validated.checksum,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Single responsibility: `inboundMail()` — received email as a factory over jobs'
|
|
2
|
+
// `webhookReceiver()` (itself a factory over `job`), never a ninth primitive. The door is the
|
|
3
|
+
// provider's: signature first, then the envelope, then a durable row. The job reads the raw MIME,
|
|
4
|
+
// parses it under bounds, stores the attachments and hands the app ONE typed `InboundMessage`.
|
|
5
|
+
|
|
6
|
+
import { ConfigInvalidError, finiteCount } from '@ultimat3/core';
|
|
7
|
+
import { type WebhookReceiver, webhookReceiver } from '@ultimat3/jobs';
|
|
8
|
+
import { assertSafeKey } from '@ultimat3/storage';
|
|
9
|
+
import { DEFAULT_INBOUND_PREFIX } from './inbound-attachments';
|
|
10
|
+
import { readInbound } from './inbound-message';
|
|
11
|
+
import type {
|
|
12
|
+
InboundMailDefinition,
|
|
13
|
+
InboundProvider,
|
|
14
|
+
InboundRow,
|
|
15
|
+
WebhookInbound,
|
|
16
|
+
} from './inbound-types';
|
|
17
|
+
import { DEFAULT_MIME_LIMITS, type MimeLimits } from './mime-parse';
|
|
18
|
+
|
|
19
|
+
/** SNS caps a notification at 256 KiB; Resend's metadata is far smaller. */
|
|
20
|
+
export const DEFAULT_INBOUND_BODY_BYTES = 1_048_576;
|
|
21
|
+
|
|
22
|
+
const LIMIT_NAMES = [
|
|
23
|
+
'maxBytes',
|
|
24
|
+
'maxParts',
|
|
25
|
+
'maxDepth',
|
|
26
|
+
'maxAttachments',
|
|
27
|
+
'maxHeaderBytes',
|
|
28
|
+
] as const;
|
|
29
|
+
|
|
30
|
+
/** Every bound screened where it is declared: `size > NaN` is false, so NaN would bound nothing. */
|
|
31
|
+
function limitsOf(declared: Partial<MimeLimits> | undefined): MimeLimits {
|
|
32
|
+
const out: Record<(typeof LIMIT_NAMES)[number], number> = { ...DEFAULT_MIME_LIMITS };
|
|
33
|
+
for (const name of LIMIT_NAMES) {
|
|
34
|
+
const value = declared?.[name];
|
|
35
|
+
if (value !== undefined) out[name] = finiteCount('inboundMail', `limits.${name}`, value, 1);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function inboundMail(definition: InboundMailDefinition): WebhookReceiver {
|
|
41
|
+
const { tenant } = definition;
|
|
42
|
+
if (typeof definition.provider !== 'function') {
|
|
43
|
+
throw new ConfigInvalidError({
|
|
44
|
+
cause: `inboundMail '${String(definition.name)}' has no provider thunk`,
|
|
45
|
+
fix: "inboundMail({ provider: () => sesInbound({ topicArns }) }) — or () => resendInbound({ secret, apiKey }), from '@ultimat3/mail/inbound'",
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const limits = limitsOf(definition.limits);
|
|
49
|
+
const maxBytes = finiteCount(
|
|
50
|
+
'inboundMail',
|
|
51
|
+
'maxBodyBytes',
|
|
52
|
+
definition.maxBodyBytes === undefined ? DEFAULT_INBOUND_BODY_BYTES : definition.maxBodyBytes,
|
|
53
|
+
1,
|
|
54
|
+
);
|
|
55
|
+
const attachments = definition.attachments ?? {};
|
|
56
|
+
// Screened at boot: a prefix storage refuses must not read, per file, as a policy refusal.
|
|
57
|
+
if (attachments !== false) assertSafeKey(attachments.prefix ?? DEFAULT_INBOUND_PREFIX);
|
|
58
|
+
// Built on first use and kept; a throw is not kept, so the next delivery asks again.
|
|
59
|
+
let built: InboundProvider | undefined;
|
|
60
|
+
const provider = (): InboundProvider => {
|
|
61
|
+
built ??= definition.provider();
|
|
62
|
+
return built;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
return webhookReceiver<InboundRow>({
|
|
66
|
+
name: definition.name,
|
|
67
|
+
path: definition.path,
|
|
68
|
+
tenant: tenant === 'none' ? 'none' : (facts) => facts.orgId,
|
|
69
|
+
maxBytes,
|
|
70
|
+
...(definition.retry === undefined ? {} : { retry: definition.retry }),
|
|
71
|
+
...(definition.queue === undefined ? {} : { queue: definition.queue }),
|
|
72
|
+
...(definition.rateLimit === undefined ? {} : { rateLimit: definition.rateLimit }),
|
|
73
|
+
async verify(inbound: WebhookInbound) {
|
|
74
|
+
const door = await provider().door(inbound);
|
|
75
|
+
if ('answer' in door) return door;
|
|
76
|
+
const orgId = tenant === 'none' ? undefined : tenant(door.row.recipients);
|
|
77
|
+
return {
|
|
78
|
+
eventId: door.eventId,
|
|
79
|
+
payload: door.row,
|
|
80
|
+
...(orgId === undefined ? {} : { orgId }),
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
async handle({ eventId, orgId, payload, ctx, step, attempt }) {
|
|
84
|
+
const message = await readInbound({
|
|
85
|
+
provider: provider(),
|
|
86
|
+
eventId,
|
|
87
|
+
orgId,
|
|
88
|
+
payload,
|
|
89
|
+
limits,
|
|
90
|
+
attachments,
|
|
91
|
+
});
|
|
92
|
+
return definition.handle({ message, orgId, ctx, step, attempt });
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Single responsibility: one verified queue row → the typed `InboundMessage` a handler receives —
|
|
2
|
+
// the provider hands over the raw MIME, the bounded parser reads it, storage takes the
|
|
3
|
+
// attachments. The row is re-parsed here: the queue holds JSON, and a row is not proof of shape.
|
|
4
|
+
|
|
5
|
+
import { t, validate } from '@ultimat3/schema';
|
|
6
|
+
import { storeAttachments } from './inbound-attachments';
|
|
7
|
+
import type {
|
|
8
|
+
InboundAttachmentOptions,
|
|
9
|
+
InboundMessage,
|
|
10
|
+
InboundProvider,
|
|
11
|
+
InboundRow,
|
|
12
|
+
} from './inbound-types';
|
|
13
|
+
import { type MimeLimits, parseMime } from './mime-parse';
|
|
14
|
+
import { parseAddressList } from './mime-parse-address';
|
|
15
|
+
import { inboundMalformed } from './mime-parse-errors';
|
|
16
|
+
import { headerOf, rawHeaderOf } from './mime-parse-headers';
|
|
17
|
+
|
|
18
|
+
const rowSchema = t.discriminatedUnion(
|
|
19
|
+
'provider',
|
|
20
|
+
t.object({
|
|
21
|
+
provider: t.literal('ses'),
|
|
22
|
+
recipients: t.array(t.string),
|
|
23
|
+
content: t.string,
|
|
24
|
+
encoding: t.enum(['BASE64', 'UTF8']),
|
|
25
|
+
verdicts: t.record(t.string),
|
|
26
|
+
}),
|
|
27
|
+
t.object({ provider: t.literal('resend'), recipients: t.array(t.string), emailId: t.string }),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
export interface ReadInboundInput {
|
|
31
|
+
readonly provider: InboundProvider;
|
|
32
|
+
readonly eventId: string;
|
|
33
|
+
readonly orgId: string | undefined;
|
|
34
|
+
readonly payload: unknown;
|
|
35
|
+
readonly limits: MimeLimits;
|
|
36
|
+
readonly attachments: InboundAttachmentOptions | false;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function dateOf(value: string | undefined): Date | undefined {
|
|
40
|
+
if (value === undefined) return undefined;
|
|
41
|
+
const at = new Date(value);
|
|
42
|
+
return Number.isNaN(at.getTime()) ? undefined : at;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function readInbound(input: ReadInboundInput): Promise<InboundMessage> {
|
|
46
|
+
const parsedRow = validate(rowSchema, input.payload);
|
|
47
|
+
if (parsedRow.issues !== undefined) throw inboundMalformed('row');
|
|
48
|
+
const row: InboundRow = parsedRow.value;
|
|
49
|
+
const raw = await input.provider.mime(row, input.limits.maxBytes);
|
|
50
|
+
const parsed = parseMime(raw, input.limits);
|
|
51
|
+
const infected =
|
|
52
|
+
row.provider === 'ses' &&
|
|
53
|
+
row.verdicts['virus'] === 'FAIL' &&
|
|
54
|
+
(input.attachments === false || input.attachments.keepOnVirusFail !== true);
|
|
55
|
+
const attachments = await storeAttachments({
|
|
56
|
+
attachments: parsed.attachments,
|
|
57
|
+
options: input.attachments,
|
|
58
|
+
eventId: input.eventId,
|
|
59
|
+
orgId: input.orgId,
|
|
60
|
+
withheld: infected ? 'verdict' : undefined,
|
|
61
|
+
});
|
|
62
|
+
const header = (name: string) => headerOf(parsed.headers, name);
|
|
63
|
+
// Address lists are split on the RAW header: a decoded comma in a name is text.
|
|
64
|
+
const addresses = (name: string) => parseAddressList(rawHeaderOf(parsed.headers, name));
|
|
65
|
+
return {
|
|
66
|
+
provider: row.provider,
|
|
67
|
+
eventId: input.eventId,
|
|
68
|
+
recipients: row.recipients,
|
|
69
|
+
messageId: header('message-id'),
|
|
70
|
+
from: addresses('from')[0],
|
|
71
|
+
to: addresses('to'),
|
|
72
|
+
cc: addresses('cc'),
|
|
73
|
+
replyTo: addresses('reply-to'),
|
|
74
|
+
subject: header('subject') ?? '',
|
|
75
|
+
date: dateOf(header('date')),
|
|
76
|
+
text: parsed.text,
|
|
77
|
+
html: parsed.html,
|
|
78
|
+
headers: parsed.headers,
|
|
79
|
+
attachments,
|
|
80
|
+
verdicts: row.provider === 'ses' ? row.verdicts : {},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Single responsibility: Resend receiving, as an `inboundMail()` provider. The `email.received`
|
|
2
|
+
// webhook is Svix-signed (`resend-signature.ts`, proven before any parse) and carries metadata
|
|
3
|
+
// only, so the door queues the email id; the job then reads the message from Resend's API and
|
|
4
|
+
// downloads its raw MIME — one parser for every provider, never Resend's pre-parsed JSON.
|
|
5
|
+
|
|
6
|
+
import { type Clock, ConfigInvalidError, finiteCount, isUltimateError } from '@ultimat3/core';
|
|
7
|
+
import { type DialResolve, outbound } from '@ultimat3/core/outbound';
|
|
8
|
+
import { t, validate } from '@ultimat3/schema';
|
|
9
|
+
import { parseDeliveryJson } from './delivery-event';
|
|
10
|
+
import { deliveryEventInvalid } from './delivery-event-errors';
|
|
11
|
+
import type { MailFetch } from './driver-resend';
|
|
12
|
+
import type { InboundDoor, InboundProvider, InboundRow, WebhookInbound } from './inbound-types';
|
|
13
|
+
import { inboundMalformed, inboundTooLarge } from './mime-parse-errors';
|
|
14
|
+
import {
|
|
15
|
+
DEFAULT_SVIX_TOLERANCE_MS,
|
|
16
|
+
svixKey,
|
|
17
|
+
svixSecretBytes,
|
|
18
|
+
verifySvix,
|
|
19
|
+
} from './resend-signature';
|
|
20
|
+
|
|
21
|
+
export const RESEND_API_ORIGIN = 'https://api.resend.com';
|
|
22
|
+
const DEADLINE_MS = 30_000;
|
|
23
|
+
/** Resend's ids are UUIDs; anything else never reaches a URL. */
|
|
24
|
+
const EMAIL_ID = /^[A-Za-z0-9-]{1,128}$/;
|
|
25
|
+
|
|
26
|
+
export interface ResendInboundOptions {
|
|
27
|
+
/** The receiving webhook's `whsec_…` signing secret. Never logged. */
|
|
28
|
+
readonly secret: string;
|
|
29
|
+
/** A Resend API key with receiving access, for `GET /emails/receiving/:id`. Never logged. */
|
|
30
|
+
readonly apiKey: string;
|
|
31
|
+
/** Default `DEFAULT_SVIX_TOLERANCE_MS`. */
|
|
32
|
+
readonly toleranceMs?: number | undefined;
|
|
33
|
+
readonly clock?: Clock | undefined;
|
|
34
|
+
/** Both GETs. Default: the platform fetch, through core's `outbound()`. */
|
|
35
|
+
readonly fetch?: MailFetch | undefined;
|
|
36
|
+
/** The raw download's host is Resend's choice, so it is a public dial: screened and pinned. */
|
|
37
|
+
readonly resolve?: DialResolve | undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const webhook = t.object({
|
|
41
|
+
type: t.string,
|
|
42
|
+
data: t
|
|
43
|
+
.object({
|
|
44
|
+
email_id: t.string,
|
|
45
|
+
to: t.array(t.string),
|
|
46
|
+
})
|
|
47
|
+
.optional(),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const receivedEmail = t.object({
|
|
51
|
+
raw: t.object({ download_url: t.url }).nullable().optional(),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
55
|
+
|
|
56
|
+
/** `X_OUTBOUND_TOO_LARGE` is the message's bound, in this receiver's words; the rest pass through. */
|
|
57
|
+
function sized(error: unknown, maxBytes: number): unknown {
|
|
58
|
+
return isUltimateError(error) && error.code === 'X_OUTBOUND_TOO_LARGE'
|
|
59
|
+
? inboundTooLarge('maxBytes', maxBytes)
|
|
60
|
+
: error;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function resendInbound(options: ResendInboundOptions): InboundProvider {
|
|
64
|
+
const secret = svixSecretBytes(options.secret);
|
|
65
|
+
if (typeof options.apiKey !== 'string' || options.apiKey.trim() === '') {
|
|
66
|
+
throw new ConfigInvalidError({
|
|
67
|
+
cause: 'resendInbound has no Resend API key, and the webhook carries no message body',
|
|
68
|
+
fix: 'resendInbound({ secret: env.RESEND_WEBHOOK_SECRET, apiKey: env.RESEND_API_KEY }) — a key from https://resend.com/api-keys with receiving access',
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const toleranceMs = finiteCount(
|
|
72
|
+
'resendInbound',
|
|
73
|
+
'toleranceMs',
|
|
74
|
+
options.toleranceMs ?? DEFAULT_SVIX_TOLERANCE_MS,
|
|
75
|
+
1,
|
|
76
|
+
);
|
|
77
|
+
let key: Promise<CryptoKey> | undefined;
|
|
78
|
+
const deps = { fetch: options.fetch, resolve: options.resolve };
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
name: 'resend',
|
|
82
|
+
async door(inbound: WebhookInbound): Promise<InboundDoor> {
|
|
83
|
+
let body: string;
|
|
84
|
+
try {
|
|
85
|
+
body = decoder.decode(inbound.bytes);
|
|
86
|
+
} catch {
|
|
87
|
+
throw deliveryEventInvalid('resend', 'not-utf8');
|
|
88
|
+
}
|
|
89
|
+
key ??= svixKey(secret);
|
|
90
|
+
await verifySvix(
|
|
91
|
+
{
|
|
92
|
+
id: inbound.headers.get('svix-id'),
|
|
93
|
+
timestamp: inbound.headers.get('svix-timestamp'),
|
|
94
|
+
signature: inbound.headers.get('svix-signature'),
|
|
95
|
+
},
|
|
96
|
+
body,
|
|
97
|
+
{ key: await key, toleranceMs, clock: options.clock },
|
|
98
|
+
);
|
|
99
|
+
const parsed = validate(webhook, parseDeliveryJson('resend', body));
|
|
100
|
+
if (parsed.issues !== undefined) throw deliveryEventInvalid('resend', 'envelope');
|
|
101
|
+
const { type, data } = parsed.value;
|
|
102
|
+
// Authentic, and not a received email (a delivery event on the same endpoint): no row.
|
|
103
|
+
if (type !== 'email.received') return { answer: Response.json({ ok: true, ignored: type }) };
|
|
104
|
+
if (data === undefined || !EMAIL_ID.test(data.email_id)) {
|
|
105
|
+
throw deliveryEventInvalid('resend', 'notification');
|
|
106
|
+
}
|
|
107
|
+
const row: InboundRow = {
|
|
108
|
+
provider: 'resend',
|
|
109
|
+
// Resend's own `to`. Never `received_for`: Resend documents it as read from the message's
|
|
110
|
+
// `Received` headers, which the sender writes — routing a tenant on it is the sender's call.
|
|
111
|
+
recipients: data.to,
|
|
112
|
+
emailId: data.email_id,
|
|
113
|
+
};
|
|
114
|
+
return { eventId: data.email_id, row };
|
|
115
|
+
},
|
|
116
|
+
async mime(row, maxBytes) {
|
|
117
|
+
if (row.provider !== 'resend') throw inboundMalformed('row');
|
|
118
|
+
const email = await outbound(
|
|
119
|
+
{
|
|
120
|
+
url: `${RESEND_API_ORIGIN}/emails/receiving/${row.emailId}`,
|
|
121
|
+
vendor: 'resend',
|
|
122
|
+
dial: 'named',
|
|
123
|
+
deadlineMs: DEADLINE_MS,
|
|
124
|
+
headers: { authorization: `Bearer ${options.apiKey}`, accept: 'application/json' },
|
|
125
|
+
// The JSON repeats html and text beside the raw link: bounded by the message's own bound.
|
|
126
|
+
maxBytes: maxBytes * 3,
|
|
127
|
+
},
|
|
128
|
+
deps,
|
|
129
|
+
).catch((error: unknown) => Promise.reject(sized(error, maxBytes)));
|
|
130
|
+
const download = email.json(receivedEmail).raw?.download_url;
|
|
131
|
+
if (download === undefined) throw inboundMalformed('raw-unavailable');
|
|
132
|
+
// A signed URL: the API key never travels to it.
|
|
133
|
+
const raw = await outbound(
|
|
134
|
+
{ url: download, vendor: 'resend-raw', dial: 'public', deadlineMs: DEADLINE_MS, maxBytes },
|
|
135
|
+
deps,
|
|
136
|
+
).catch((error: unknown) => Promise.reject(sized(error, maxBytes)));
|
|
137
|
+
return raw.bytes;
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|