@ultimat3/mail 31.47.1 → 31.49.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/README.md CHANGED
@@ -101,7 +101,7 @@ the app changes between environments; the credential does.
101
101
  |---|---|
102
102
  | *(nothing set)*, `development` / `test` | `memoryMailDriver()` — caught, never sent |
103
103
  | *(nothing set)*, `staging` / `production` | `unconfiguredMailDriver(...)` — every send is `X_MAIL_CREDENTIAL_MISSING` |
104
- | `SMTP_URL` + `MAIL_FROM` | `smtpMailDriver(...)`, `MAIL_POOL_SIZE` optional |
104
+ | `SMTP_URL` + `MAIL_FROM` | `smtpMailDriver(...)`, `MAIL_POOL_SIZE` and `MAIL_TIMEOUT_MS` (read/write deadline, default `30000`) optional |
105
105
  | `RESEND_API_KEY` + `MAIL_FROM` | `resendMailDriver(...)` |
106
106
  | `SES_REGION` + `SES_ACCESS_KEY_ID` + `SES_SECRET_ACCESS_KEY` + `MAIL_FROM` | `sesMailDriver(...)`; `SES_SESSION_TOKEN`, `SES_ENDPOINT`, `SES_CONFIGURATION_SET` optional |
107
107
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/mail",
3
- "version": "31.47.1",
3
+ "version": "31.49.0",
4
4
  "description": "Transactional email as data: one template renders HTML and text, sent through a job.",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -44,11 +44,11 @@
44
44
  "test": "bun test"
45
45
  },
46
46
  "dependencies": {
47
- "@ultimat3/core": "31.47.1",
48
- "@ultimat3/i18n": "31.47.1",
49
- "@ultimat3/jobs": "31.47.1",
50
- "@ultimat3/schema": "31.47.1",
51
- "@ultimat3/storage": "31.47.1",
52
- "@ultimat3/time": "31.47.1"
47
+ "@ultimat3/core": "31.49.0",
48
+ "@ultimat3/i18n": "31.49.0",
49
+ "@ultimat3/jobs": "31.49.0",
50
+ "@ultimat3/schema": "31.49.0",
51
+ "@ultimat3/storage": "31.49.0",
52
+ "@ultimat3/time": "31.49.0"
53
53
  }
54
54
  }
package/src/driver-env.ts CHANGED
@@ -22,6 +22,7 @@ export const MAIL_ENV_KEYS = [
22
22
  'RESEND_API_KEY',
23
23
  'MAIL_FROM',
24
24
  'MAIL_POOL_SIZE',
25
+ 'MAIL_TIMEOUT_MS',
25
26
  'SES_REGION',
26
27
  'SES_ACCESS_KEY_ID',
27
28
  'SES_SECRET_ACCESS_KEY',
@@ -97,6 +98,27 @@ function poolSizeFrom(env: MailEnvironment): number | undefined {
97
98
  return parsed;
98
99
  }
99
100
 
101
+ /** The longest delay `setTimeout` holds: one past it overflows to 1 ms and fires at once. */
102
+ const MAX_TIMER_MS = 2_147_483_647;
103
+
104
+ /**
105
+ * `MAIL_POOL_SIZE`'s rule, plus a ceiling: the deadline reaches `setTimeout`, so a value past
106
+ * `MAX_TIMER_MS` — written to wait LONGER — would expire every read on the next tick.
107
+ */
108
+ function timeoutMsFrom(env: MailEnvironment): number | undefined {
109
+ const raw = nonEmpty(env['MAIL_TIMEOUT_MS']);
110
+ if (raw === undefined) return undefined;
111
+ const parsed = Number(raw);
112
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_TIMER_MS) {
113
+ throw new ConfigInvalidError({
114
+ cause: `MAIL_TIMEOUT_MS is "${raw}", which is not a whole number of milliseconds from 1 to ${MAX_TIMER_MS}`,
115
+ fix: 'MAIL_TIMEOUT_MS=60000 — in .env.production, or unset it to keep the 30000 default',
116
+ meta: { MAIL_TIMEOUT_MS: raw },
117
+ });
118
+ }
119
+ return parsed;
120
+ }
121
+
100
122
  /**
101
123
  * A credential selects its transport. Two credentials is the one case that cannot be answered by
102
124
  * picking a winner — whichever this chose would be the one an operator did not mean half the time,
@@ -130,11 +152,13 @@ export function selectMailDriver(
130
152
  const smtpUrl = nonEmpty(env['SMTP_URL']);
131
153
  if (smtpUrl !== undefined) {
132
154
  const poolSize = poolSizeFrom(env);
155
+ const timeoutMs = timeoutMsFrom(env);
133
156
  return {
134
157
  driver: smtpMailDriver({
135
158
  url: smtpUrl,
136
159
  from: requireFrom(env, 'SMTP_URL'),
137
160
  ...(poolSize === undefined ? {} : { poolSize }),
161
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
138
162
  retainMime: options.retainMime,
139
163
  }),
140
164
  detail: 'SMTP_URL',
package/src/driver-ses.ts CHANGED
@@ -25,7 +25,7 @@ import { resultFor } from './driver';
25
25
  import type { MailFetch } from './driver-resend';
26
26
  import { sendFailed } from './errors';
27
27
  import { mailMessageIdToken } from './idempotency';
28
- import { addressDomain, buildMimeMessage } from './mime';
28
+ import { addressDomain, addressSpec, buildMimeMessage, encodeAddressPhrase } from './mime';
29
29
  import { type RetainMimeOptions, resolveRetainMime, withRetainedMime } from './retain-mime';
30
30
  import { sesFailure } from './ses-failure';
31
31
 
@@ -104,15 +104,17 @@ function requireFrom(from: string): string {
104
104
 
105
105
  /**
106
106
  * `Destination` is the envelope, and it is sent even though the raw message holds `To:` and `Cc:`
107
- * — `Bcc` is never a header (`mime.ts`), so without it the blind list would receive nothing.
107
+ * — `Bcc` is never a header (`mime.ts`), so without it the blind list would receive nothing. SES
108
+ * takes envelope addresses as 7-bit ASCII only (its raw-email guide, "MIME Encoding"): the
109
+ * destinations go as bare mailboxes, and the friendly-from name as an RFC 2047 encoded word.
108
110
  */
109
111
  function bodyFor(message: MailMessage, from: string, raw: string, set: string | undefined): string {
110
112
  return JSON.stringify({
111
- FromEmailAddress: from,
113
+ FromEmailAddress: encodeAddressPhrase(from),
112
114
  Destination: {
113
- ToAddresses: message.to,
114
- ...(message.cc === undefined ? {} : { CcAddresses: message.cc }),
115
- ...(message.bcc === undefined ? {} : { BccAddresses: message.bcc }),
115
+ ToAddresses: message.to.map(addressSpec),
116
+ ...(message.cc === undefined ? {} : { CcAddresses: message.cc.map(addressSpec) }),
117
+ ...(message.bcc === undefined ? {} : { BccAddresses: message.bcc.map(addressSpec) }),
116
118
  },
117
119
  Content: { Raw: { Data: base64Utf8(raw) } },
118
120
  ...(set === undefined ? {} : { ConfigurationSetName: set }),
@@ -82,18 +82,25 @@ const unquote = (text: string): string => {
82
82
  };
83
83
 
84
84
  /**
85
- * Where a group's display name ends: the first colon outside quotes and encoded words, before
86
- * any `<` or `@` — or -1. A scan, never `(?:"[^"]*"|=\?…\?=|[^"<@:])*:`, whose overlapping
87
- * alternatives backtrack exponentially on a long value with no colon.
85
+ * Where a group's display name ends: the first colon outside quotes, comments and encoded words,
86
+ * before any `<` or `@` — or -1. Quotes, comments and `\` are tracked as `entries` tracks them: a
87
+ * comment is CFWS, so `(sent via: phone) jane@x.test` names no group. A scan, never
88
+ * `(?:"[^"]*"|=\?…\?=|[^"<@:])*:`, whose overlapping alternatives backtrack exponentially on a
89
+ * long value with no colon.
88
90
  */
89
91
  function groupColon(text: string): number {
90
92
  let quoted = false;
93
+ let comment = 0;
91
94
  for (let at = 0; at < text.length; at += 1) {
92
95
  const char = text.charAt(at);
93
- if (char === '"') quoted = !quoted;
94
- if (quoted) continue;
95
96
  const word = encodedWordAt(text, at);
96
97
  if (word !== undefined) at += word.length - 1;
98
+ else if (char === '\\') at += 1;
99
+ else if (char === '"' && comment === 0) quoted = !quoted;
100
+ else if (quoted) continue;
101
+ else if (char === '(') comment += 1;
102
+ else if (char === ')' && comment > 0) comment -= 1;
103
+ else if (comment > 0) continue;
97
104
  else if (char === ':') return at;
98
105
  else if (char === '<' || char === '@') return -1;
99
106
  }
@@ -164,7 +164,7 @@ class Conversation {
164
164
  stage,
165
165
  detail: `the server sent nothing for ${timeoutMs}ms, so the read deadline expired`,
166
166
  retryable: true,
167
- fix: 'smtpMailDriver({ url, from, timeoutMs: 60_000 }) // where the driver is built',
167
+ fix: 'MAIL_TIMEOUT_MS=60000 # in .env.production — or smtpMailDriver({ url, from, timeoutMs: 60_000 })',
168
168
  }),
169
169
  );
170
170
  }, timeoutMs);
@@ -213,12 +213,18 @@ export function smtpStreamOver(runtime: BunConnect, target: SmtpTarget): Promise
213
213
  // Registered on the TLS socket at `upgradeTLS`; every event on it is real, so no guard.
214
214
  const tlsHandlers = makeHandlers(() => true);
215
215
 
216
- const opening = runtime.connect({
217
- hostname: target.host,
218
- port: target.port,
219
- tls: target.tls,
220
- socket: handlers,
221
- });
216
+ const opening = connectWithin(
217
+ runtime.connect({
218
+ hostname: target.host,
219
+ port: target.port,
220
+ tls: target.tls,
221
+ socket: handlers,
222
+ }),
223
+ target,
224
+ target.tls
225
+ ? `openssl s_client -connect ${endpoint}`
226
+ : `openssl s_client -starttls smtp -connect ${endpoint}`,
227
+ );
222
228
 
223
229
  return opening.then((opened): SmtpStream => {
224
230
  let socket = opened;
@@ -233,7 +239,7 @@ export function smtpStreamOver(runtime: BunConnect, target: SmtpTarget): Promise
233
239
  stage: 'data',
234
240
  detail: `the socket stopped accepting bytes for ${target.timeoutMs}ms`,
235
241
  retryable: true,
236
- fix: 'smtpMailDriver({ url, from, timeoutMs: 60_000 }) // where the driver is built',
242
+ fix: 'MAIL_TIMEOUT_MS=60000 # in .env.production — or smtpMailDriver({ url, from, timeoutMs: 60_000 })',
237
243
  }),
238
244
  );
239
245
  }, target.timeoutMs);
@@ -302,3 +308,41 @@ export function smtpStreamOver(runtime: BunConnect, target: SmtpTarget): Promise
302
308
  };
303
309
  });
304
310
  }
311
+
312
+ /**
313
+ * The dial, bounded by the same deadline as every read and write: a host that swallows the SYN
314
+ * would otherwise hold the pool slot for the kernel's own timeout. A socket that lands after the
315
+ * deadline is closed at once — nobody holds it.
316
+ */
317
+ function connectWithin(
318
+ dialing: Promise<SocketLike>,
319
+ target: SmtpTarget,
320
+ fix: string,
321
+ ): Promise<SocketLike> {
322
+ return new Promise((resolve, reject) => {
323
+ let late = false;
324
+ const timer = setTimeout(() => {
325
+ late = true;
326
+ reject(
327
+ sendFailed({
328
+ driver: 'smtp',
329
+ stage: 'connect',
330
+ detail: `${target.host}:${String(target.port)} did not accept a connection within ${String(target.timeoutMs)}ms`,
331
+ retryable: true,
332
+ fix,
333
+ }),
334
+ );
335
+ }, target.timeoutMs);
336
+ dialing.then(
337
+ (socket) => {
338
+ clearTimeout(timer);
339
+ if (late) socket.end();
340
+ else resolve(socket);
341
+ },
342
+ (error: unknown) => {
343
+ clearTimeout(timer);
344
+ reject(error);
345
+ },
346
+ );
347
+ });
348
+ }