@lunora/mail 1.0.0-alpha.6 → 1.0.0-alpha.61

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.
Files changed (43) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/inbound/index.d.mts +370 -77
  3. package/dist/inbound/index.d.ts +370 -77
  4. package/dist/inbound/index.mjs +1 -2
  5. package/dist/index.d.mts +101 -94
  6. package/dist/index.d.ts +101 -94
  7. package/dist/index.mjs +1 -7
  8. package/dist/packem_shared/address-soPj2Z0j.mjs +3 -0
  9. package/dist/packem_shared/authenticatesFrom-xpKAFMRN.mjs +1 -0
  10. package/dist/packem_shared/capture-transport.d-8CDAv51Z.d.mts +126 -0
  11. package/dist/packem_shared/capture-transport.d-8CDAv51Z.d.ts +126 -0
  12. package/dist/packem_shared/consumeQueuedSend-CRfALnCU.mjs +1 -0
  13. package/dist/packem_shared/createCaptureSink-wbDNGuA-.mjs +1 -0
  14. package/dist/packem_shared/createCaptureTransport-CKc6NpZR.mjs +1 -0
  15. package/dist/packem_shared/createCloudflareTransport-DpfCxn16.mjs +1 -0
  16. package/dist/packem_shared/createInboundEmailHandler-vXSNL5mZ.mjs +1 -0
  17. package/dist/packem_shared/createMailer-CjQmT7Ln.mjs +1 -0
  18. package/dist/packem_shared/createResendTransport-DDkOitck.mjs +1 -0
  19. package/dist/packem_shared/provider-transport-CR4w-R0A.mjs +1 -0
  20. package/dist/packem_shared/renderEmail-BOUnr6i3.mjs +1 -0
  21. package/dist/packem_shared/shard-CRhAKK93.mjs +1 -0
  22. package/dist/packem_shared/shard.d-DVADjmEJ.d.mts +29 -0
  23. package/dist/packem_shared/shard.d-DVADjmEJ.d.ts +29 -0
  24. package/dist/testing.d.mts +9 -9
  25. package/dist/testing.d.ts +9 -9
  26. package/dist/testing.mjs +1 -63
  27. package/package.json +5 -5
  28. package/dist/packem_shared/address-vSUAVU2T.mjs +0 -64
  29. package/dist/packem_shared/capture-transport.d-ChnhdPO2.d.mts +0 -117
  30. package/dist/packem_shared/capture-transport.d-ChnhdPO2.d.ts +0 -117
  31. package/dist/packem_shared/consumeQueuedSend-B9hTDOZ6.mjs +0 -77
  32. package/dist/packem_shared/createCaptureSink-Di-5AJUs.mjs +0 -65
  33. package/dist/packem_shared/createCaptureTransport-Crz_8822.mjs +0 -11
  34. package/dist/packem_shared/createCloudflareTransport-DXh1nUNi.mjs +0 -28
  35. package/dist/packem_shared/createInboundEmailHandler-BW_s0-Vc.mjs +0 -84
  36. package/dist/packem_shared/createMailer-B4Z_Cgiu.mjs +0 -81
  37. package/dist/packem_shared/createResendTransport-CMQWjZoi.mjs +0 -16
  38. package/dist/packem_shared/parseInboundEmail-6lafQBT1.mjs +0 -72
  39. package/dist/packem_shared/provider-transport-C0xHi3oy.mjs +0 -48
  40. package/dist/packem_shared/renderEmail-hyS1bpVP.mjs +0 -8
  41. package/dist/packem_shared/shard-CJ-TvmfT.mjs +0 -13
  42. package/dist/packem_shared/shard.d-CL2Lmliv.d.mts +0 -39
  43. package/dist/packem_shared/shard.d-CL2Lmliv.d.ts +0 -39
package/LICENSE.md CHANGED
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+ <!-- /TYPE_DEPENDENCIES -->
@@ -1,5 +1,5 @@
1
- import { D as DurableObjectJurisdiction, S as ShardNamespaceLike } from "../packem_shared/shard.d-CL2Lmliv.mjs";
2
- export type { a as ShardStubLike } from "../packem_shared/shard.d-CL2Lmliv.mjs";
1
+ import { D as DurableObjectJurisdiction, S as ShardNamespaceLike } from "../packem_shared/shard.d-DVADjmEJ.mjs";
2
+ export type { a as ShardStubLike } from "../packem_shared/shard.d-DVADjmEJ.mjs";
3
3
  /** A raw RFC 822 message as accepted by the parser. */
4
4
  type RawInboundEmail = ArrayBuffer | ReadableStream<Uint8Array> | string | Uint8Array;
5
5
  /** One parsed attachment. `content` is preserved as the parser decoded it. */
@@ -15,34 +15,79 @@ interface InboundAttachment {
15
15
  /** Declared MIME type (e.g. `image/png`). */
16
16
  mimeType: string;
17
17
  }
18
+ /** One reported `method=result [ptype.property=value]` clause of an `Authentication-Results` header. */
19
+ interface InboundAuthResult {
20
+ /**
21
+ * The identifier the result is about, lowercased — DKIM's signing domain
22
+ * (`header.d=`), SPF's envelope `MAIL FROM` domain (`smtp.mailfrom=`, local
23
+ * part dropped) or DMARC's `header.from=`. `null` when the clause reported
24
+ * none, in which case it cannot be aligned and vouches for nothing.
25
+ */
26
+ domain: string | null;
27
+ /** The result token, lowercased (`"pass"`, `"fail"`, `"none"`, …). */
28
+ result: string;
29
+ }
18
30
  /**
19
- * Sender-authentication verdicts pulled from the `Authentication-Results` header
20
- * the receiving MX (e.g. Cloudflare Email Routing) stamped on the message.
21
- *
22
- * SECURITY: Cloudflare Email Routing authenticates only the *recipient* domain,
23
- * **not** the sender. The envelope `from` and message content are trivially
24
- * spoofable, so a downstream handler MUST NOT make trust/authorization decisions
25
- * on `email.from` alone — gate on these verdicts (or your own policy) instead.
26
- * Verdicts are best-effort: when the receiving MX did not stamp an
27
- * `Authentication-Results` header, every field is `null` ("unknown").
28
- */
31
+ * Sender-authentication verdicts pulled from the `Authentication-Results` header
32
+ * the receiving MX (e.g. Cloudflare Email Routing) stamped on the message.
33
+ *
34
+ * SECURITY: Cloudflare Email Routing authenticates only the *recipient* domain,
35
+ * **not** the sender. The envelope `from` and message content are trivially
36
+ * spoofable, so a downstream handler MUST NOT make trust/authorization decisions
37
+ * on `email.from` alone — gate on these verdicts (or your own policy) instead.
38
+ * Verdicts are best-effort: when the receiving MX did not stamp an
39
+ * `Authentication-Results` header, every list is empty ("unknown").
40
+ *
41
+ * Each method holds a LIST, because RFC 8601 lets one header report the same
42
+ * method more than once and real mail does. An ESP-relayed message carries two
43
+ * DKIM signatures — the relay's and the author domain's — and the MX stamps a
44
+ * clause per signature in whatever order it verified them. Keeping only the
45
+ * first threw the aligned one away whenever it was not the one that happened to
46
+ * come first, and the message was rejected as unauthenticated. A consumer
47
+ * therefore asks "does ANY reported clause pass and align?", not "did the first
48
+ * one?".
49
+ *
50
+ * SECURITY: a bare `"pass"` is NOT proof the `From` header is genuine. SPF
51
+ * authenticates the envelope `MAIL FROM` domain and DKIM the signing domain
52
+ * (`d=`), and an attacker controls both — `spf=pass smtp.mailfrom=evil.example;
53
+ * dkim=pass header.d=evil.example` is routine for a message whose `From` says
54
+ * `ceo@victim.example`. Each verdict therefore carries the identifier it is
55
+ * about ({@link InboundAuthResult.domain}): an SPF or DKIM pass only vouches for
56
+ * `from` when that domain equals the `From` address's domain (RFC 7489 strict
57
+ * alignment). Only a DMARC pass already checked alignment for you. A pass with
58
+ * no identifier reported cannot be aligned and must be treated as
59
+ * unauthenticated.
60
+ *
61
+ * SECURITY: verdicts are read from the **first/topmost** `Authentication-Results`
62
+ * header in document order. The receiving MX prepends its own genuine header per
63
+ * RFC 8601, so the topmost occurrence is the trustworthy one; any lower
64
+ * occurrences (which an untrusted sender can inject into the raw message) are
65
+ * ignored. As defense-in-depth a consumer may additionally verify the topmost
66
+ * header's `authserv-id` matches its receiving MX (e.g. Cloudflare) — that needs
67
+ * config this runtime-agnostic parser does not carry, so it is left to the host.
68
+ */
29
69
  interface InboundAuthentication {
30
- /** DKIM verdict (`"pass"`/`"fail"`/…), or `null` when not reported. */
31
- dkim: string | null;
32
- /** DMARC verdict (`"pass"`/`"fail"`/…), or `null` when not reported. */
33
- dmarc: string | null;
34
- /** SPF verdict (`"pass"`/`"fail"`/…), or `null` when not reported. */
35
- spf: string | null;
70
+ /** Every DKIM clause the header reported, in header order; empty when the method was not reported. */
71
+ dkim: InboundAuthResult[];
72
+ /** Every DMARC clause the header reported, in header order; empty when the method was not reported. */
73
+ dmarc: InboundAuthResult[];
74
+ /** Every SPF clause the header reported, in header order; empty when the method was not reported. */
75
+ spf: InboundAuthResult[];
36
76
  }
37
77
  /** Normalised, transport-agnostic view of a received message. */
38
78
  interface InboundEmail {
39
79
  /** Decoded attachments (empty array when none). */
40
80
  attachments: InboundAttachment[];
41
81
  /**
42
- * Sender-authentication verdicts (DKIM/SPF/DMARC) parsed from the receiving
43
- * MX's `Authentication-Results` header. SECURITY: see {@link InboundAuthentication}
44
- * `from` is spoofable; gate trust on these verdicts, not on `from`.
45
- */
82
+ * Sender-authentication verdicts (DKIM/SPF/DMARC) and the domain each is
83
+ * about, parsed from the receiving MX's **first/topmost**
84
+ * `Authentication-Results` header. SECURITY: see
85
+ * {@link InboundAuthentication} — `from` is spoofable, and an SPF/DKIM pass
86
+ * vouches for it only when that clause's `domain` equals the `From` domain (a
87
+ * DMARC pass checked that already). Reading the raw `headers["authentication-results"]`
88
+ * map instead exposes last-wins (a lower, potentially attacker-injected)
89
+ * value — trust `authentication`, not the raw map.
90
+ */
46
91
  authentication: InboundAuthentication;
47
92
  /** Sender mailbox (`from`), CR/LF-checked. Empty string when the message omitted it. SECURITY: spoofable — do not trust for authorization. */
48
93
  from: string;
@@ -64,17 +109,48 @@ interface InboundEmail {
64
109
  to: string[];
65
110
  }
66
111
  /**
67
- * Parse a raw RFC 822 message into a normalised {@link InboundEmail}. Accepts the
68
- * shapes a Cloudflare Email Worker can hand off — `ReadableStream`, `ArrayBuffer`,
69
- * `Uint8Array`, or a decoded string.
70
- */
112
+ * Parse a raw RFC 822 message into a normalised {@link InboundEmail}. Accepts the
113
+ * shapes a Cloudflare Email Worker can hand off — `ReadableStream`, `ArrayBuffer`,
114
+ * `Uint8Array`, or a decoded string.
115
+ */
71
116
  declare const parseInboundEmail: (raw: RawInboundEmail) => Promise<InboundEmail>;
72
117
  /**
73
- * Structural projection of Cloudflare's `ForwardableEmailMessage` (verified
74
- * against `@cloudflare/workers-types`' `ForwardableEmailMessage`). Only the
75
- * members the handler touches are modelled, so the host can pass the real
76
- * runtime object without `@lunora/mail` importing `cloudflare:email`.
77
- */
118
+ * THE inbound sender-authentication gate: does the receiving MX vouch for this
119
+ * message's `From` domain? Pass it as the `verify` hook of
120
+ * `createInboundEmailHandler` (or call it from your own) it is one exported
121
+ * helper precisely so the insecure variants cannot be hand-rolled again.
122
+ *
123
+ * True when ANY reported DMARC, SPF or DKIM clause both **passes** and names a
124
+ * `domain` equal to the `From` address's domain. False otherwise — including for
125
+ * an empty verdict list (the MX stamped no `Authentication-Results` header at
126
+ * all, which is "unknown", not "fine") and for a `From` with no single mailbox
127
+ * to align against.
128
+ *
129
+ * SECURITY — the two halves are each load-bearing.
130
+ *
131
+ * **Alignment.** A bare `pass` proves nothing about `From`. SPF authenticates the
132
+ * envelope `MAIL FROM` domain and DKIM the signing `d=`, both attacker-chosen, so
133
+ * `spf=pass`+`dkim=pass` for `evil.example` is routine on a message whose `From`
134
+ * says `ceo@victim.example`. Only a clause whose own `domain` equals the `From`
135
+ * domain vouches for it. Alignment is STRICT (RFC 7489): there is no
136
+ * public-suffix list here, so `mail.example.com` does not vouch for
137
+ * `example.com`. A pass reporting no domain (`null`) cannot be aligned and is
138
+ * rejected. A DMARC pass already checked alignment at the MX.
139
+ *
140
+ * **Every clause, not the first.** One header legitimately reports a method more
141
+ * than once (an ESP-relayed message is DKIM-signed by both the relay and the
142
+ * author domain), and the aligned clause is not reliably the first, so reading
143
+ * only the first bounced fully authenticated mail. "Any clause passes AND aligns"
144
+ * stays strictly narrower than a bare pass: a clause vouching for some other
145
+ * domain contributes nothing.
146
+ */
147
+ declare const authenticatesFrom: (email: InboundEmail) => boolean;
148
+ /**
149
+ * Structural projection of Cloudflare's `ForwardableEmailMessage` (verified
150
+ * against `@cloudflare/workers-types`' `ForwardableEmailMessage`). Only the
151
+ * members the handler touches are modelled, so the host can pass the real
152
+ * runtime object without `@lunora/mail` importing `cloudflare:email`.
153
+ */
78
154
  interface ForwardableEmailMessageLike {
79
155
  /** Forward this message to a verified destination address. */
80
156
  forward: (rcptTo: string, headers?: Headers) => Promise<unknown>;
@@ -90,7 +166,14 @@ interface ForwardableEmailMessageLike {
90
166
  raw: string;
91
167
  to: string;
92
168
  }) => Promise<unknown>;
93
- /** Reject the message with a permanent SMTP error (Cloudflare bounces/retries). */
169
+ /**
170
+ * Reject the message with a PERMANENT SMTP error — Cloudflare returns it to
171
+ * the connecting client with this reason, and it is never redelivered.
172
+ * Documented at https://developers.cloudflare.com/email-routing/email-workers/runtime-api/
173
+ * ("Reject this email message by returning a permanent SMTP error back to
174
+ * the connecting client, including the given reason") and mirrored in
175
+ * workerd's own `types/defines/email.d.ts`.
176
+ */
94
177
  setReject: (reason: string) => void;
95
178
  /** Envelope `To`. */
96
179
  readonly to: string;
@@ -107,43 +190,122 @@ interface InboundDispatchContext<TEnv = Record<string, unknown>> {
107
190
  /** Routes a parsed message into a Lunora function (or anywhere). */
108
191
  type InboundDispatch<TEnv = Record<string, unknown>> = (email: InboundEmail, context: InboundDispatchContext<TEnv>) => Promise<void>;
109
192
  /**
110
- * Opt-in sender-verification gate. Runs after `parse` and before `dispatch` with
111
- * the parsed message. Return `false` (or throw) to reject the message before it
112
- * reaches the privileged dispatch — use it to enforce DKIM/SPF/DMARC via
113
- * `email.authentication`, an allow-list, etc. Returning `true`/`undefined`
114
- * proceeds.
115
- */
193
+ * Opt-in sender-verification gate. Runs after `parse` and before `dispatch` with
194
+ * the parsed message. Return `false` (or throw) to reject the message before it
195
+ * reaches the privileged dispatch — use it to enforce DKIM/SPF/DMARC via
196
+ * `email.authentication`, an allow-list, etc. Returning `true`/`undefined`
197
+ * proceeds.
198
+ */
116
199
  type InboundVerify<TEnv = Record<string, unknown>> = (email: InboundEmail, context: InboundDispatchContext<TEnv>) => Promise<boolean | void> | boolean | void;
200
+ /**
201
+ * Opt-in durable sink for a failed `dispatch`. Hand the parsed message to
202
+ * something that owns the retry — a queue producer, a Durable Object, an alarm
203
+ * — and the handler ACCEPTS the SMTP session instead of bouncing, because the
204
+ * message is now owned rather than lost. Returning normally means "I have it";
205
+ * throwing means the hand-off itself failed and the message bounces with the
206
+ * generic reason (see {@link createInboundEmailHandler}).
207
+ *
208
+ * `error` is the dispatch failure, for classification/logging by the sink.
209
+ *
210
+ * NOTE: binary attachment `content` is an `ArrayBuffer`/`Uint8Array`, which
211
+ * survives structured clone (Cloudflare Queues, DO storage) but is corrupted by
212
+ * `JSON.stringify` — encode it yourself if the sink is JSON-bodied.
213
+ */
214
+ type InboundRetain<TEnv = Record<string, unknown>> = (email: InboundEmail, context: InboundDispatchContext<TEnv>, error: unknown) => Promise<void> | void;
117
215
  /** Options for {@link createInboundEmailHandler}. */
118
216
  interface InboundEmailHandlerOptions<TEnv = Record<string, unknown>> {
119
217
  /** Routes the parsed message onward (e.g. {@link dispatchToLunoraFunction}). */
120
218
  dispatch: InboundDispatch<TEnv>;
121
219
  /**
122
- * Called when `parse`/`verify`/`dispatch` throws. The default rejects the
123
- * message via `message.setReject` so Cloudflare bounces/retries rather than
124
- * silently dropping it. SECURITY: the reject reason is delivered to the
125
- * (attacker-controlled) sender as a bounce, so the default reason is a fixed,
126
- * generic string and the real error is logged server-side. Override to log,
127
- * forward, or swallow but never pass internal error text to `setReject`.
128
- */
220
+ * Called when `parse`, `verify`, or `dispatch` fails but with two DIFFERENT
221
+ * contracts, because only the first two decide the message's fate here:
222
+ *
223
+ * - `parse` / `verify` this hook DECIDES the outcome. The default
224
+ * ({@link rejectOnError}) rejects via `message.setReject`; supplying your own
225
+ * replaces that, so the message is accepted unless you reject it yourself.
226
+ * - `dispatch` — this hook is OBSERVABILITY ONLY. It is called for the side
227
+ * effect (log, alert, forward) and the outcome is then decided by `retain`
228
+ * (accept) or a generic reject, regardless of what it does; the built-in
229
+ * default is deliberately NOT applied there. A `setReject` from inside it
230
+ * still takes effect, which would bounce a message `retain` went on to
231
+ * accept — almost certainly not what you want. A throw from the hook itself
232
+ * is logged and swallowed so it cannot mask the original dispatch error.
233
+ *
234
+ * SECURITY: a reject reason is delivered to the (attacker-controlled) sender
235
+ * as a bounce, so the default reason is a fixed, generic string and the real
236
+ * error is logged server-side. Never pass internal error text to `setReject`.
237
+ */
129
238
  onError?: (error: unknown, context: InboundDispatchContext<TEnv>) => Promise<void> | void;
130
239
  /** Parses raw bytes into an {@link InboundEmail} (e.g. `parseInboundEmail`). */
131
240
  parse: (raw: RawInboundEmail) => Promise<InboundEmail>;
132
241
  /**
133
- * Opt-in sender-authentication gate run before `dispatch`. SECURITY: inbound
134
- * `from` is spoofable and dispatch is privileged supply this (gating on
135
- * `email.authentication`) when an inbound function makes any trust decision.
136
- */
242
+ * Opt-in: take durable ownership of a message whose `dispatch` failed, so a
243
+ * transient fault (a shard 502, a briefly-absent admin token) is retried
244
+ * instead of bounced. Omit it and a dispatch failure bounces, as it always
245
+ * has. See {@link InboundRetain}.
246
+ */
247
+ retain?: InboundRetain<TEnv>;
248
+ /**
249
+ * Opt-in sender-authentication gate run before `dispatch`. SECURITY: inbound
250
+ * `from` is spoofable and dispatch is privileged — supply this (gating on
251
+ * `email.authentication`) when an inbound function makes any trust decision.
252
+ */
137
253
  verify?: InboundVerify<TEnv>;
138
254
  }
139
255
  /** The `email(message, env, ctx)` callback the factory returns. */
140
256
  type InboundEmailHandler<TEnv = Record<string, unknown>> = (message: ForwardableEmailMessageLike, env: TEnv, context: unknown) => Promise<void>;
141
257
  /**
142
- * Build the `email(message, env, ctx)` handler. It (a) reads `message.raw`,
143
- * (b) parses it via `parse`, (c) runs the optional `verify` gate, then
144
- * (d) calls `dispatch(parsed, { message, env, ctx })`. Any throw (or a falsy
145
- * `verify`) routes through `onError` (default: a generic `message.setReject`).
146
- */
258
+ * Build the `email(message, env, ctx)` handler. It (a) reads `message.raw`,
259
+ * (b) parses it via `parse`, (c) runs the optional `verify` gate, then
260
+ * (d) calls `dispatch(parsed, { message, env, ctx })`.
261
+ *
262
+ * The two failure classes are routed differently:
263
+ *
264
+ * - `parse` / `verify` (including a falsy `verify`) → `onError` (default: a
265
+ * generic `message.setReject`). A malformed or unauthenticated message fails
266
+ * the same way on every redelivery, so bouncing it is the honest answer.
267
+ * - `dispatch` (or its transport) → a custom `onError` is called for
268
+ * observability, then the message is handed to `retain` if one is configured
269
+ * (SMTP ACCEPTs — the retry is now owned elsewhere) and otherwise bounced with
270
+ * the same generic reason. A `retain` that throws bounces too.
271
+ *
272
+ * WHY THE RETRY IS ABSORBED IN-WORKER RATHER THAN SIGNALLED OVER SMTP — there is
273
+ * no transient-reject API and no inbound redelivery to appeal to:
274
+ *
275
+ * - `setReject` is documented as a PERMANENT SMTP error
276
+ * (https://developers.cloudflare.com/email-routing/email-workers/runtime-api/),
277
+ * with no "try later" variant.
278
+ * - Cloudflare does not document what an uncaught throw from `email()` does. The
279
+ * full Email Routing and Email Service docs corpora
280
+ * (`developers.cloudflare.com/email-routing/llms-full.txt`,
281
+ * `.../email-service/llms-full.txt`) say nothing about an unhandled exception,
282
+ * and describe NO redelivery mechanism for inbound Email Workers at all. The
283
+ * documented lifecycle
284
+ * (https://developers.cloudflare.com/email-service/concepts/email-lifecycle/)
285
+ * lists exactly three worker outcomes — `forward()`, `reply()`, `setReject()` —
286
+ * with no branch for "the worker threw". (Its 4xx-retry prose is about OUTBOUND
287
+ * delivery to the destination MTA, not about invoking the worker.)
288
+ * - The behaviour reported in practice is a PERMANENT in-session rejection:
289
+ * `521 5.3.0 Upstream error`, i.e. the same permanence as `setReject` but with
290
+ * an opaque reason instead of ours. See
291
+ * https://community.cloudflare.com/t/is-it-possible-to-return-a-transient-failure-from-an-email-worker/599938
292
+ * ("If the email function raises an exception, a permanent failure is returned
293
+ * to the client after the DATA command") — a question Cloudflare never answered
294
+ * — and https://community.cloudflare.com/t/email-worker-upstream-error/457228.
295
+ * Email Routing also states it forwards upstream SMTP errors back to the sender
296
+ * in-session rather than generating a bounce later
297
+ * (https://developers.cloudflare.com/email-service/reference/postmaster/#smtp-errors).
298
+ *
299
+ * So every SMTP-visible outcome is permanent, and the only way not to lose a
300
+ * legitimate message to a two-second shard 502 is to accept it and take durable
301
+ * ownership: that is `retain`. It stays opt-in — with no `retain`, a dispatch
302
+ * failure bounces exactly as before.
303
+ *
304
+ * A dispatch that KNOWS one of its own failures is permanent should call
305
+ * `context.message.setReject(...)` and return normally rather than throw, so it
306
+ * bounces without being handed to `retain` (see `@lunora/agent`'s inbound
307
+ * handler for both cases).
308
+ */
147
309
  declare const createInboundEmailHandler: <TEnv = Record<string, unknown>>(options: InboundEmailHandlerOptions<TEnv>) => InboundEmailHandler<TEnv>;
148
310
  /** The `RpcEnvelope` shape the runtime's `/_lunora/rpc` path consumes. */
149
311
  interface RpcEnvelope {
@@ -154,23 +316,23 @@ interface RpcEnvelope {
154
316
  /** Options for {@link dispatchToLunoraFunction}. */
155
317
  interface DispatchToLunoraFunctionOptions<TEnv = Record<string, unknown>> {
156
318
  /**
157
- * Admin bearer authorizing the shard RPC. Defaults to reading
158
- * `env.LUNORA_ADMIN_TOKEN` at dispatch time.
159
- */
319
+ * Admin bearer authorizing the shard RPC. Defaults to reading
320
+ * `env.LUNORA_ADMIN_TOKEN` at dispatch time.
321
+ */
160
322
  adminToken?: string;
161
323
  /** `functionPath` of the target mutation/action (e.g. `"inbound:onEmail"`). */
162
324
  functionPath: string;
163
325
  /**
164
- * Pin inbound dispatch to a Cloudflare data-residency jurisdiction. Pass the
165
- * same value as the worker's `jurisdiction` so inbound mail routes to the
166
- * jurisdiction-pinned shard. Omit for the un-pinned global namespace.
167
- */
326
+ * Pin inbound dispatch to a Cloudflare data-residency jurisdiction. Pass the
327
+ * same value as the worker's `jurisdiction` so inbound mail routes to the
328
+ * jurisdiction-pinned shard. Omit for the un-pinned global namespace.
329
+ */
168
330
  jurisdiction?: DurableObjectJurisdiction;
169
331
  /**
170
- * Map the parsed message into the function's args. Defaults to passing the
171
- * whole {@link InboundEmail} with binary attachment `content` base64-encoded
172
- * (see {@link toJsonSafeEmail}) so it survives the JSON-serialised RPC body.
173
- */
332
+ * Map the parsed message into the function's args. Defaults to passing the
333
+ * whole {@link InboundEmail} with binary attachment `content` base64-encoded
334
+ * (see {@link toJsonSafeEmail}) so it survives the JSON-serialised RPC body.
335
+ */
174
336
  resolveArgs?: (email: InboundEmail, context: InboundDispatchContext<TEnv>) => unknown;
175
337
  /** The `SHARD` Durable Object namespace. */
176
338
  shard: ShardNamespaceLike;
@@ -178,16 +340,147 @@ interface DispatchToLunoraFunctionOptions<TEnv = Record<string, unknown>> {
178
340
  shardKey?: string;
179
341
  }
180
342
  /**
181
- * Build a {@link InboundDispatch} that posts an {@link RpcEnvelope} to the root
182
- * shard stub — the same admin-RPC-over-shard path the dev capture sink uses
183
- * (`from-env.ts`) — routing the parsed message into a named Lunora
184
- * mutation/action. Throws on a non-2xx RPC or a missing admin token so the
185
- * handler's `onError` (default `setReject`) bounces the message.
186
- *
187
- * SECURITY: the RPC carries the admin bearer, so the target function runs with
188
- * RLS bypassed over fully attacker-controlled, spoofable input — see the module
189
- * docstring. Verify the sender (`verify` hook / `email.authentication`) before
190
- * making any trust decision in the target function.
191
- */
343
+ * Build a {@link InboundDispatch} that posts an {@link RpcEnvelope} to the root
344
+ * shard stub — the same admin-RPC-over-shard path the dev capture sink uses
345
+ * (`from-env.ts`) — routing the parsed message into a named Lunora
346
+ * mutation/action. Throws on a non-2xx RPC or a missing admin token both
347
+ * transient in principle, so the handler reports it through a custom `onError`
348
+ * and then hands the message to `retain` if one is configured, bouncing only
349
+ * when there is nowhere durable to put it (see {@link createInboundEmailHandler}).
350
+ *
351
+ * SECURITY: the RPC is marked a trusted system dispatch, so `functionPath` may
352
+ * (and should) name an `internalMutation`/`internalAction` a public `mutation`
353
+ * target is callable by any browser client with a forged message. The input is
354
+ * fully attacker-controlled and spoofable; verify the sender (`verify` hook /
355
+ * `email.authentication`) before making any trust decision in the target.
356
+ */
192
357
  declare const dispatchToLunoraFunction: <TEnv extends Record<string, unknown> = Record<string, unknown>>(options: DispatchToLunoraFunctionOptions<TEnv>) => InboundDispatch<TEnv>;
193
- export { type DispatchToLunoraFunctionOptions, type ForwardableEmailMessageLike, type InboundAttachment, type InboundAuthentication, type InboundDispatch, type InboundDispatchContext, type InboundEmail, type InboundEmailHandler, type InboundEmailHandlerOptions, type InboundVerify, type RawInboundEmail, type RpcEnvelope, type ShardNamespaceLike, createInboundEmailHandler, dispatchToLunoraFunction, parseInboundEmail };
358
+ export {
359
+ /**
360
+ * `@lunora/mail/inbound` — inbound Email Routing support.
361
+ *
362
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
363
+ * mutation/action:
364
+ *
365
+ * ```ts
366
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
367
+ *
368
+ * export const email = createInboundEmailHandler({
369
+ * parse: parseInboundEmail,
370
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
371
+ * });
372
+ * ```
373
+ */
374
+ type DispatchToLunoraFunctionOptions,
375
+ /**
376
+ * `@lunora/mail/inbound` — inbound Email Routing support.
377
+ *
378
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
379
+ * mutation/action:
380
+ *
381
+ * ```ts
382
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
383
+ *
384
+ * export const email = createInboundEmailHandler({
385
+ * parse: parseInboundEmail,
386
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
387
+ * });
388
+ * ```
389
+ */
390
+ type ForwardableEmailMessageLike, type InboundAttachment, type InboundAuthResult, type InboundAuthentication,
391
+ /**
392
+ * `@lunora/mail/inbound` — inbound Email Routing support.
393
+ *
394
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
395
+ * mutation/action:
396
+ *
397
+ * ```ts
398
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
399
+ *
400
+ * export const email = createInboundEmailHandler({
401
+ * parse: parseInboundEmail,
402
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
403
+ * });
404
+ * ```
405
+ */
406
+ type InboundDispatch,
407
+ /**
408
+ * `@lunora/mail/inbound` — inbound Email Routing support.
409
+ *
410
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
411
+ * mutation/action:
412
+ *
413
+ * ```ts
414
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
415
+ *
416
+ * export const email = createInboundEmailHandler({
417
+ * parse: parseInboundEmail,
418
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
419
+ * });
420
+ * ```
421
+ */
422
+ type InboundDispatchContext, type InboundEmail,
423
+ /**
424
+ * `@lunora/mail/inbound` — inbound Email Routing support.
425
+ *
426
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
427
+ * mutation/action:
428
+ *
429
+ * ```ts
430
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
431
+ *
432
+ * export const email = createInboundEmailHandler({
433
+ * parse: parseInboundEmail,
434
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
435
+ * });
436
+ * ```
437
+ */
438
+ type InboundEmailHandler,
439
+ /**
440
+ * `@lunora/mail/inbound` — inbound Email Routing support.
441
+ *
442
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
443
+ * mutation/action:
444
+ *
445
+ * ```ts
446
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
447
+ *
448
+ * export const email = createInboundEmailHandler({
449
+ * parse: parseInboundEmail,
450
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
451
+ * });
452
+ * ```
453
+ */
454
+ type InboundEmailHandlerOptions,
455
+ /**
456
+ * `@lunora/mail/inbound` — inbound Email Routing support.
457
+ *
458
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
459
+ * mutation/action:
460
+ *
461
+ * ```ts
462
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
463
+ *
464
+ * export const email = createInboundEmailHandler({
465
+ * parse: parseInboundEmail,
466
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
467
+ * });
468
+ * ```
469
+ */
470
+ type InboundVerify, type RawInboundEmail,
471
+ /**
472
+ * `@lunora/mail/inbound` — inbound Email Routing support.
473
+ *
474
+ * Wire a Cloudflare Email Worker entry to route received mail into a Lunora
475
+ * mutation/action:
476
+ *
477
+ * ```ts
478
+ * import { createInboundEmailHandler, parseInboundEmail, dispatchToLunoraFunction } from "@lunora/mail/inbound";
479
+ *
480
+ * export const email = createInboundEmailHandler({
481
+ * parse: parseInboundEmail,
482
+ * dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
483
+ * });
484
+ * ```
485
+ */
486
+ type RpcEnvelope, type ShardNamespaceLike, authenticatesFrom, createInboundEmailHandler, dispatchToLunoraFunction, parseInboundEmail };