@upyo/smtp 0.5.0-dev.119 → 0.5.0-dev.128

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/dist/index.js CHANGED
@@ -30,15 +30,334 @@ function createSmtpConfig(config) {
30
30
  };
31
31
  }
32
32
 
33
+ //#endregion
34
+ //#region src/oauth2.ts
35
+ /**
36
+ * An error thrown when SMTP authentication fails, including OAuth 2.0 token
37
+ * acquisition and SASL exchange failures.
38
+ *
39
+ * @since 0.5.0
40
+ */
41
+ var SmtpAuthError = class extends Error {
42
+ /**
43
+ * Creates a new {@link SmtpAuthError}.
44
+ * @param message A human-readable description of the failure.
45
+ */
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "SmtpAuthError";
49
+ }
50
+ };
51
+ /**
52
+ * Encodes a string as Base64 in a cross-runtime, UTF-8-safe manner.
53
+ *
54
+ * Unlike calling `btoa()` directly, this first encodes the input as UTF-8 so
55
+ * that non-ASCII characters (e.g., in an internationalized address) do not
56
+ * throw.
57
+ *
58
+ * @param input The string to encode.
59
+ * @returns The Base64-encoded representation of the UTF-8 bytes of `input`.
60
+ */
61
+ function toBase64(input) {
62
+ const bytes = new TextEncoder().encode(input);
63
+ let binary = "";
64
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
65
+ return btoa(binary);
66
+ }
67
+ /**
68
+ * Builds the SASL `XOAUTH2` initial client response for SMTP authentication.
69
+ *
70
+ * The unencoded payload follows Google's XOAUTH2 format
71
+ * (`user=<user>^Aauth=Bearer <token>^A^A`, where `^A` is the `0x01` control
72
+ * character) and is returned Base64-encoded, ready to be sent as the argument
73
+ * of `AUTH XOAUTH2`.
74
+ *
75
+ * @param user The user (email address) to authenticate as.
76
+ * @param accessToken The OAuth 2.0 access token.
77
+ * @returns The Base64-encoded XOAUTH2 initial client response.
78
+ * @since 0.5.0
79
+ */
80
+ function formatXoauth2(user, accessToken) {
81
+ return toBase64(`user=${user}\x01auth=Bearer ${accessToken}\x01\x01`);
82
+ }
83
+ /**
84
+ * Builds the SASL `OAUTHBEARER` initial client response for SMTP
85
+ * authentication, as defined by [RFC 7628].
86
+ *
87
+ * The unencoded payload is
88
+ * `n,a=<user>,^A[host=<host>^A][port=<port>^A]auth=Bearer <token>^A^A`
89
+ * (where `^A` is the `0x01` control character) and is returned Base64-encoded,
90
+ * ready to be sent as the argument of `AUTH OAUTHBEARER`.
91
+ *
92
+ * [RFC 7628]: https://www.rfc-editor.org/rfc/rfc7628
93
+ *
94
+ * @param user The user (email address) to authenticate as.
95
+ * @param accessToken The OAuth 2.0 access token.
96
+ * @param host The server host to include as the `host` key/value, if any.
97
+ * @param port The server port to include as the `port` key/value, if any.
98
+ * @returns The Base64-encoded OAUTHBEARER initial client response.
99
+ * @since 0.5.0
100
+ */
101
+ function formatOauthbearer(user, accessToken, host, port) {
102
+ let response = `n,a=${escapeSaslName(user)},\x01`;
103
+ if (host != null) response += `host=${host}\x01`;
104
+ if (port != null) response += `port=${port}\x01`;
105
+ response += `auth=Bearer ${accessToken}\x01\x01`;
106
+ return toBase64(response);
107
+ }
108
+ /**
109
+ * Escapes a SASL name (GS2 `authzid`) per RFC 5801, encoding `,` as `=2C` and
110
+ * `=` as `=3D` so that identities containing those characters do not corrupt
111
+ * the GS2 header.
112
+ *
113
+ * @param name The SASL name to escape.
114
+ * @returns The escaped SASL name.
115
+ */
116
+ function escapeSaslName(name) {
117
+ return name.replace(/=/g, "=3D").replace(/,/g, "=2C");
118
+ }
119
+ /**
120
+ * Chooses an OAuth 2.0 SASL mechanism based on the mechanisms advertised by the
121
+ * server in its `AUTH` capability line.
122
+ *
123
+ * `XOAUTH2` is preferred when available (it is the de-facto standard supported
124
+ * by Gmail and Outlook); otherwise `OAUTHBEARER` is used when advertised. When
125
+ * neither is advertised, `xoauth2` is returned as a best-effort default.
126
+ *
127
+ * @param capabilities The capability lines parsed from the server's EHLO
128
+ * response.
129
+ * @returns The selected mechanism, either `"xoauth2"` or `"oauthbearer"`.
130
+ * @since 0.5.0
131
+ */
132
+ function selectOAuth2Mechanism(capabilities) {
133
+ const authLine = capabilities.find((cap) => cap.toUpperCase().startsWith("AUTH"));
134
+ const mechanisms = authLine == null ? [] : authLine.toUpperCase().split(/\s+/).slice(1);
135
+ if (mechanisms.includes("XOAUTH2")) return "xoauth2";
136
+ if (mechanisms.includes("OAUTHBEARER")) return "oauthbearer";
137
+ return "xoauth2";
138
+ }
139
+ /**
140
+ * Validates that an OAuth 2.0 token endpoint is safe to send client credentials
141
+ * to, requiring HTTPS except for loopback addresses (for local testing).
142
+ *
143
+ * @param endpoint The token endpoint URL to validate.
144
+ * @throws {TypeError} If the URL is malformed or uses an insecure scheme.
145
+ */
146
+ function assertSecureTokenEndpoint(endpoint) {
147
+ let url;
148
+ try {
149
+ url = new URL(endpoint);
150
+ } catch {
151
+ throw new TypeError(`Invalid OAuth 2.0 token endpoint URL: ${endpoint}`);
152
+ }
153
+ if (url.protocol === "https:") return;
154
+ const isLoopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "::1";
155
+ if (url.protocol === "http:" && isLoopback) return;
156
+ throw new TypeError("OAuth 2.0 token endpoint must use HTTPS to protect client credentials: " + endpoint);
157
+ }
158
+ /**
159
+ * The number of milliseconds before a cached access token's expiry at which it
160
+ * is considered stale and eligible for refresh.
161
+ */
162
+ const REFRESH_SAFETY_MARGIN_MS = 6e4;
163
+ /**
164
+ * The default access token lifetime (in seconds) assumed when the token
165
+ * endpoint omits `expires_in`.
166
+ */
167
+ const DEFAULT_EXPIRES_IN = 3600;
168
+ /**
169
+ * How long to wait for the token endpoint before aborting the request, so a
170
+ * stalled endpoint cannot block authentication indefinitely.
171
+ */
172
+ const TOKEN_REQUEST_TIMEOUT_MS = 6e4;
173
+ /** Maximum number of response-body characters to include in error messages. */
174
+ const MAX_ERROR_BODY_LENGTH = 500;
175
+ /**
176
+ * Truncates a token-endpoint response body so an oversized payload (e.g. a
177
+ * large proxy/CDN error page) does not bloat error messages and logs.
178
+ *
179
+ * @param text The response body text.
180
+ * @returns The text, truncated with an ellipsis if it exceeds the limit.
181
+ */
182
+ function truncateErrorBody(text) {
183
+ return text.length > MAX_ERROR_BODY_LENGTH ? `${text.slice(0, MAX_ERROR_BODY_LENGTH)}…` : text;
184
+ }
185
+ /**
186
+ * Mirrors a promise but rejects early if the given abort signal fires, without
187
+ * cancelling the underlying promise. This lets a single waiter abort its own
188
+ * wait on a shared operation without affecting other waiters.
189
+ *
190
+ * @param promise The promise to await.
191
+ * @param signal An optional abort signal that rejects the returned promise.
192
+ * @returns A promise that settles with `promise`, or rejects when `signal`
193
+ * aborts.
194
+ */
195
+ function abortable(promise, signal) {
196
+ if (signal == null) return promise;
197
+ return new Promise((resolve, reject) => {
198
+ const onAbort = () => reject(signal.reason);
199
+ if (signal.aborted) reject(signal.reason);
200
+ else signal.addEventListener("abort", onAbort, { once: true });
201
+ promise.then((value) => {
202
+ signal.removeEventListener("abort", onAbort);
203
+ resolve(value);
204
+ }, (error) => {
205
+ signal.removeEventListener("abort", onAbort);
206
+ reject(error);
207
+ });
208
+ });
209
+ }
210
+ /**
211
+ * Acquires and caches OAuth 2.0 access tokens for SMTP authentication.
212
+ *
213
+ * Depending on the {@link SmtpOAuth2Auth} configuration, the manager either
214
+ * returns a static token, invokes a provider callback on every request, or
215
+ * exchanges a refresh token for an access token at the configured token
216
+ * endpoint and caches it until shortly before it expires. A single manager is
217
+ * shared across all pooled connections of a transport so that the refresh-token
218
+ * exchange happens at most once per token lifetime.
219
+ *
220
+ * @since 0.5.0
221
+ */
222
+ var OAuth2TokenManager = class {
223
+ auth;
224
+ fetchFn;
225
+ cached;
226
+ pending;
227
+ /**
228
+ * Creates a new {@link OAuth2TokenManager}.
229
+ *
230
+ * @param auth The OAuth 2.0 authentication configuration.
231
+ * @param fetchFn The `fetch` implementation to use for the refresh-token
232
+ * exchange. Defaults to the global `fetch`; primarily
233
+ * overridden in tests.
234
+ * @throws {TypeError} If a refresh-token configuration has an insecure
235
+ * (non-HTTPS) token endpoint.
236
+ */
237
+ constructor(auth, fetchFn = fetch) {
238
+ if ("refreshToken" in auth) assertSecureTokenEndpoint(auth.tokenEndpoint);
239
+ this.auth = auth;
240
+ this.fetchFn = fetchFn;
241
+ }
242
+ /**
243
+ * Returns a valid OAuth 2.0 access token, acquiring or refreshing it as
244
+ * needed.
245
+ *
246
+ * @param signal An optional {@link AbortSignal} to cancel token acquisition.
247
+ * @returns The current access token.
248
+ * @throws {SmtpAuthError} If a refresh-token exchange fails or returns an
249
+ * unexpected response.
250
+ */
251
+ async getAccessToken(signal) {
252
+ signal?.throwIfAborted();
253
+ const auth = this.auth;
254
+ if ("accessToken" in auth) return typeof auth.accessToken === "function" ? await auth.accessToken(signal) : auth.accessToken;
255
+ const cached = this.cached;
256
+ if (cached != null && cached.expiresAt - REFRESH_SAFETY_MARGIN_MS > Date.now()) return cached.accessToken;
257
+ this.pending ??= this.refresh(auth).then((result) => {
258
+ this.cached = {
259
+ accessToken: result.accessToken,
260
+ expiresAt: Date.now() + result.expiresIn * 1e3
261
+ };
262
+ return result;
263
+ }).finally(() => {
264
+ this.pending = void 0;
265
+ });
266
+ const { accessToken } = await abortable(this.pending, signal);
267
+ return accessToken;
268
+ }
269
+ /**
270
+ * Exchanges the configured refresh token for a fresh access token.
271
+ *
272
+ * The request deliberately runs without a caller-specific abort signal; it is
273
+ * shared across concurrent callers, each of which applies its own
274
+ * cancellation separately (see {@link getAccessToken}).
275
+ *
276
+ * @param auth The refresh-token authentication configuration.
277
+ * @returns The new access token and its lifetime in seconds.
278
+ * @throws {SmtpAuthError} If the request fails or the response is invalid.
279
+ */
280
+ async refresh(auth) {
281
+ const body = new URLSearchParams({
282
+ grant_type: "refresh_token",
283
+ client_id: auth.clientId,
284
+ refresh_token: auth.refreshToken
285
+ });
286
+ if (auth.clientSecret != null) body.set("client_secret", auth.clientSecret);
287
+ if (auth.scope != null) body.set("scope", auth.scope);
288
+ const controller = new AbortController();
289
+ const timeout = setTimeout(() => {
290
+ controller.abort(/* @__PURE__ */ new Error("OAuth 2.0 token request timed out"));
291
+ }, TOKEN_REQUEST_TIMEOUT_MS);
292
+ let response;
293
+ let text;
294
+ try {
295
+ response = await this.fetchFn(auth.tokenEndpoint, {
296
+ method: "POST",
297
+ headers: {
298
+ "content-type": "application/x-www-form-urlencoded",
299
+ "accept": "application/json"
300
+ },
301
+ body,
302
+ signal: controller.signal
303
+ });
304
+ text = await response.text();
305
+ } catch (cause) {
306
+ throw new SmtpAuthError(`Failed to request an OAuth 2.0 access token from ${auth.tokenEndpoint}: ${cause instanceof Error ? cause.message : String(cause)}`);
307
+ } finally {
308
+ clearTimeout(timeout);
309
+ }
310
+ const safeText = truncateErrorBody(text);
311
+ if (!response.ok) throw new SmtpAuthError(`OAuth 2.0 token endpoint responded with HTTP ${response.status}: ${safeText}`);
312
+ let json;
313
+ try {
314
+ json = JSON.parse(text);
315
+ } catch {
316
+ throw new SmtpAuthError(`OAuth 2.0 token endpoint returned a non-JSON response: ${safeText}`);
317
+ }
318
+ if (typeof json !== "object" || json == null || typeof json.access_token !== "string") throw new SmtpAuthError(`OAuth 2.0 token endpoint response did not include an access_token: ${safeText}`);
319
+ const record = json;
320
+ let expiresIn = DEFAULT_EXPIRES_IN;
321
+ if (typeof record.expires_in === "number") expiresIn = record.expires_in;
322
+ else if (typeof record.expires_in === "string") {
323
+ const parsed = Number.parseInt(record.expires_in, 10);
324
+ if (Number.isFinite(parsed)) expiresIn = parsed;
325
+ }
326
+ return {
327
+ accessToken: record.access_token,
328
+ expiresIn
329
+ };
330
+ }
331
+ };
332
+
33
333
  //#endregion
34
334
  //#region src/smtp-connection.ts
335
+ /**
336
+ * The maximum length of an SMTP command line, including the terminating CRLF,
337
+ * as specified by RFC 5321 §4.5.3.1.4.
338
+ */
339
+ const MAX_COMMAND_LINE_LENGTH = 512;
340
+ /** The length of the CRLF terminator appended to every command. */
341
+ const CRLF_LENGTH = 2;
342
+ /**
343
+ * Whether a host refers to the local loopback interface, for which cleartext
344
+ * OAuth 2.0 authentication is permitted (e.g. local testing and development).
345
+ *
346
+ * @param host The host to check.
347
+ * @returns `true` if the host is a loopback address.
348
+ */
349
+ function isLoopbackHost(host) {
350
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
351
+ }
35
352
  var SmtpConnection = class {
36
353
  socket = null;
37
354
  config;
38
355
  authenticated = false;
39
356
  capabilities = [];
40
- constructor(config) {
357
+ tokenManager;
358
+ constructor(config, tokenManager) {
41
359
  this.config = createSmtpConfig(config);
360
+ this.tokenManager = tokenManager ?? null;
42
361
  }
43
362
  connect(signal) {
44
363
  if (this.socket) throw new Error("Connection already established");
@@ -208,29 +527,44 @@ var SmtpConnection = class {
208
527
  });
209
528
  }
210
529
  async authenticate(signal) {
211
- if (!this.config.auth) return;
530
+ const auth = this.config.auth;
531
+ if (!auth) return;
212
532
  if (this.authenticated) return;
213
- const authMethod = this.config.auth.method ?? "plain";
214
- if (!this.capabilities.some((cap) => cap.toUpperCase().startsWith("AUTH"))) throw new Error("Server does not support authentication");
215
- switch (authMethod) {
216
- case "plain":
217
- await this.authPlain(signal);
218
- break;
219
- case "login":
220
- await this.authLogin(signal);
221
- break;
222
- default: throw new Error(`Unsupported authentication method: ${authMethod}`);
533
+ if (!this.capabilities.some((cap) => cap.toUpperCase().startsWith("AUTH"))) throw new SmtpAuthError("Server does not support authentication.");
534
+ if ("accessToken" in auth || "refreshToken" in auth) {
535
+ if (!(this.socket instanceof TLSSocket) && !isLoopbackHost(this.config.host)) throw new SmtpAuthError("OAuth 2.0 authentication requires a TLS-secured connection to protect the access token; use `secure: true` or STARTTLS.");
536
+ const mechanism = auth.method ?? selectOAuth2Mechanism(this.capabilities);
537
+ switch (mechanism) {
538
+ case "xoauth2":
539
+ await this.authXoauth2(auth, signal);
540
+ break;
541
+ case "oauthbearer":
542
+ await this.authOauthbearer(auth, signal);
543
+ break;
544
+ default: throw new SmtpAuthError(`Unsupported authentication method: ${mechanism}`);
545
+ }
546
+ } else {
547
+ const method = auth.method ?? "plain";
548
+ switch (method) {
549
+ case "plain":
550
+ await this.authPlain(auth, signal);
551
+ break;
552
+ case "login":
553
+ await this.authLogin(auth, signal);
554
+ break;
555
+ default: throw new Error(`Unsupported authentication method: ${method}`);
556
+ }
223
557
  }
224
558
  this.authenticated = true;
225
559
  }
226
- async authPlain(signal) {
227
- const { user, pass } = this.config.auth;
560
+ async authPlain(auth, signal) {
561
+ const { user, pass } = auth;
228
562
  const credentials = btoa(`\0${user}\0${pass}`);
229
563
  const response = await this.sendCommand(`AUTH PLAIN ${credentials}`, signal);
230
564
  if (response.code !== 235) throw new Error(`Authentication failed: ${response.message}`);
231
565
  }
232
- async authLogin(signal) {
233
- const { user, pass } = this.config.auth;
566
+ async authLogin(auth, signal) {
567
+ const { user, pass } = auth;
234
568
  let response = await this.sendCommand("AUTH LOGIN", signal);
235
569
  if (response.code !== 334) throw new Error(`AUTH LOGIN failed: ${response.message}`);
236
570
  response = await this.sendCommand(btoa(user), signal);
@@ -238,6 +572,67 @@ var SmtpConnection = class {
238
572
  response = await this.sendCommand(btoa(pass), signal);
239
573
  if (response.code !== 235) throw new Error(`Password authentication failed: ${response.message}`);
240
574
  }
575
+ /**
576
+ * Resolves an OAuth 2.0 access token via the connection's token manager,
577
+ * creating a standalone manager from the auth config if none was injected.
578
+ */
579
+ async getOAuth2Token(auth, signal) {
580
+ this.tokenManager ??= new OAuth2TokenManager(auth);
581
+ return await this.tokenManager.getAccessToken(signal);
582
+ }
583
+ async authXoauth2(auth, signal) {
584
+ const token = await this.getOAuth2Token(auth, signal);
585
+ const initialResponse = formatXoauth2(auth.user, token);
586
+ const response = await this.sendSaslAuth("XOAUTH2", initialResponse, signal);
587
+ await this.finishOAuth2(response, "XOAUTH2", "", signal);
588
+ }
589
+ async authOauthbearer(auth, signal) {
590
+ const token = await this.getOAuth2Token(auth, signal);
591
+ const initialResponse = formatOauthbearer(auth.user, token, this.config.host, this.config.port);
592
+ const response = await this.sendSaslAuth("OAUTHBEARER", initialResponse, signal);
593
+ await this.finishOAuth2(response, "OAUTHBEARER", "AQ==", signal);
594
+ }
595
+ /**
596
+ * Sends a SASL `AUTH` command with its Base64 initial response.
597
+ *
598
+ * When the resulting command line would exceed the SMTP command-line length
599
+ * limit (e.g. a long Outlook JWT access token), RFC 4954 requires the client
600
+ * to omit the initial response and send it on its own line after the server's
601
+ * `334` challenge. This method transparently falls back to that two-step
602
+ * form, since some servers reject the over-long single-line command outright.
603
+ *
604
+ * @param mechanism The SASL mechanism name (e.g. `XOAUTH2`).
605
+ * @param initialResponse The Base64-encoded initial client response.
606
+ * @param signal An optional {@link AbortSignal}.
607
+ * @returns The server's response to the initial response.
608
+ */
609
+ async sendSaslAuth(mechanism, initialResponse, signal) {
610
+ const inlineCommand = `AUTH ${mechanism} ${initialResponse}`;
611
+ if (inlineCommand.length + CRLF_LENGTH <= MAX_COMMAND_LINE_LENGTH) return await this.sendCommand(inlineCommand, signal);
612
+ const challenge = await this.sendCommand(`AUTH ${mechanism}`, signal);
613
+ if (challenge.code !== 334) return challenge;
614
+ return await this.sendCommand(initialResponse, signal);
615
+ }
616
+ /**
617
+ * Interprets the server's reply to an OAuth SASL initial response, draining
618
+ * the failure challenge continuation when authentication is rejected.
619
+ *
620
+ * @throws {SmtpAuthError} If authentication did not succeed.
621
+ */
622
+ async finishOAuth2(response, mechanism, continuation, signal) {
623
+ if (response.code === 235) return;
624
+ if (response.code === 334) {
625
+ let finalMessage = "";
626
+ try {
627
+ const final = await this.sendCommand(continuation, signal);
628
+ finalMessage = ` (${final.message})`;
629
+ } catch {
630
+ signal?.throwIfAborted();
631
+ }
632
+ throw new SmtpAuthError(`${mechanism} authentication failed: ${decodeOAuth2Challenge(response.message)}${finalMessage}`);
633
+ }
634
+ throw new SmtpAuthError(`${mechanism} authentication failed: ${response.message}`);
635
+ }
241
636
  async sendMessage(message, signal) {
242
637
  const mailResponse = await this.sendCommand(`MAIL FROM:<${message.envelope.from}>`, signal);
243
638
  if (mailResponse.code !== 250) throw new Error(`MAIL FROM failed: ${mailResponse.message}`);
@@ -259,11 +654,14 @@ var SmtpConnection = class {
259
654
  return match ? match[1] : `smtp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
260
655
  }
261
656
  async quit() {
262
- if (!this.socket) return;
263
- try {
657
+ const socket = this.socket;
658
+ if (!socket) return;
659
+ if (socket.writable) try {
264
660
  await this.sendCommand("QUIT");
265
661
  } catch {}
266
- this.socket.destroy();
662
+ try {
663
+ socket.destroy();
664
+ } catch {}
267
665
  this.socket = null;
268
666
  this.authenticated = false;
269
667
  this.capabilities = [];
@@ -274,6 +672,20 @@ var SmtpConnection = class {
274
672
  if (response.code !== 250) throw new Error(`RESET failed: ${response.message}`);
275
673
  }
276
674
  };
675
+ /**
676
+ * Decodes the Base64 JSON error challenge a server sends after a failed OAuth
677
+ * SASL exchange, falling back to the raw message when it is not valid Base64.
678
+ *
679
+ * @param message The challenge text from the server's 334 response.
680
+ * @returns A human-readable description of the failure.
681
+ */
682
+ function decodeOAuth2Challenge(message) {
683
+ try {
684
+ return atob(message.trim());
685
+ } catch {
686
+ return message;
687
+ }
688
+ }
277
689
 
278
690
  //#endregion
279
691
  //#region src/dkim/canonicalize.ts
@@ -771,6 +1183,13 @@ var SmtpTransport = class {
771
1183
  poolSize;
772
1184
  connectionPool = [];
773
1185
  /**
1186
+ * A token manager shared across all pooled connections, present only when the
1187
+ * configured authentication uses OAuth 2.0. Sharing it ensures the
1188
+ * refresh-token exchange happens at most once per token lifetime instead of
1189
+ * once per connection.
1190
+ */
1191
+ tokenManager;
1192
+ /**
774
1193
  * Creates a new SMTP transport instance.
775
1194
  *
776
1195
  * @param config SMTP configuration including server details, authentication,
@@ -779,6 +1198,8 @@ var SmtpTransport = class {
779
1198
  constructor(config) {
780
1199
  this.config = config;
781
1200
  this.poolSize = config.poolSize ?? 5;
1201
+ const auth = config.auth;
1202
+ this.tokenManager = auth != null && ("accessToken" in auth || "refreshToken" in auth) ? new OAuth2TokenManager(auth) : void 0;
782
1203
  }
783
1204
  /**
784
1205
  * Sends a single email message via SMTP.
@@ -808,8 +1229,9 @@ var SmtpTransport = class {
808
1229
  */
809
1230
  async send(message, options) {
810
1231
  options?.signal?.throwIfAborted();
811
- const connection = await this.getConnection(options?.signal);
1232
+ let connection;
812
1233
  try {
1234
+ connection = await this.getConnection(options?.signal);
813
1235
  options?.signal?.throwIfAborted();
814
1236
  const smtpMessage = await convertMessage(message, this.config.dkim);
815
1237
  options?.signal?.throwIfAborted();
@@ -820,7 +1242,8 @@ var SmtpTransport = class {
820
1242
  messageId
821
1243
  };
822
1244
  } catch (error) {
823
- await this.discardConnection(connection);
1245
+ if (connection != null) await this.discardConnection(connection);
1246
+ options?.signal?.throwIfAborted();
824
1247
  return {
825
1248
  successful: false,
826
1249
  errorMessages: [error instanceof Error ? error.message : String(error)]
@@ -857,7 +1280,21 @@ var SmtpTransport = class {
857
1280
  */
858
1281
  async *sendMany(messages, options) {
859
1282
  options?.signal?.throwIfAborted();
860
- const connection = await this.getConnection(options?.signal);
1283
+ let connection;
1284
+ try {
1285
+ connection = await this.getConnection(options?.signal);
1286
+ } catch (error) {
1287
+ options?.signal?.throwIfAborted();
1288
+ const errorMessage = error instanceof Error ? error.message : String(error);
1289
+ for await (const _ of messages) {
1290
+ options?.signal?.throwIfAborted();
1291
+ yield {
1292
+ successful: false,
1293
+ errorMessages: [errorMessage]
1294
+ };
1295
+ }
1296
+ return;
1297
+ }
861
1298
  let connectionValid = true;
862
1299
  try {
863
1300
  const isAsyncIterable = Symbol.asyncIterator in messages;
@@ -879,6 +1316,7 @@ var SmtpTransport = class {
879
1316
  messageId
880
1317
  };
881
1318
  } catch (error) {
1319
+ options?.signal?.throwIfAborted();
882
1320
  connectionValid = false;
883
1321
  yield {
884
1322
  successful: false,
@@ -904,6 +1342,7 @@ var SmtpTransport = class {
904
1342
  messageId
905
1343
  };
906
1344
  } catch (error) {
1345
+ options?.signal?.throwIfAborted();
907
1346
  connectionValid = false;
908
1347
  yield {
909
1348
  successful: false,
@@ -921,8 +1360,13 @@ var SmtpTransport = class {
921
1360
  async getConnection(signal) {
922
1361
  signal?.throwIfAborted();
923
1362
  if (this.connectionPool.length > 0) return this.connectionPool.pop();
924
- const connection = new SmtpConnection(this.config);
925
- await this.connectAndSetup(connection, signal);
1363
+ const connection = new SmtpConnection(this.config, this.tokenManager);
1364
+ try {
1365
+ await this.connectAndSetup(connection, signal);
1366
+ } catch (error) {
1367
+ await this.discardConnection(connection);
1368
+ throw error;
1369
+ }
926
1370
  return connection;
927
1371
  }
928
1372
  async connectAndSetup(connection, signal) {
@@ -998,4 +1442,4 @@ var SmtpTransport = class {
998
1442
  };
999
1443
 
1000
1444
  //#endregion
1001
- export { SmtpTransport };
1445
+ export { SmtpAuthError, SmtpTransport };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@upyo/smtp",
3
- "version": "0.5.0-dev.119",
3
+ "version": "0.5.0-dev.128",
4
4
  "description": "SMTP transport for Upyo email library",
5
5
  "keywords": [
6
6
  "email",
@@ -53,7 +53,7 @@
53
53
  },
54
54
  "sideEffects": false,
55
55
  "peerDependencies": {
56
- "@upyo/core": "0.5.0-dev.119+b190ca07"
56
+ "@upyo/core": "0.5.0-dev.128+6e126027"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@dotenvx/dotenvx": "^1.47.3",