@upyo/smtp 0.5.0-dev.120 → 0.5.0-dev.136
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 +72 -0
- package/dist/index.cjs +497 -24
- package/dist/index.d.cts +189 -5
- package/dist/index.d.ts +189 -5
- package/dist/index.js +497 -25
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -53,15 +53,344 @@ function createSmtpConfig(config) {
|
|
|
53
53
|
};
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/oauth2.ts
|
|
58
|
+
/**
|
|
59
|
+
* An error thrown when SMTP authentication fails, including OAuth 2.0 token
|
|
60
|
+
* acquisition and SASL exchange failures.
|
|
61
|
+
*
|
|
62
|
+
* @since 0.5.0
|
|
63
|
+
*/
|
|
64
|
+
var SmtpAuthError = class extends Error {
|
|
65
|
+
/**
|
|
66
|
+
* Creates a new {@link SmtpAuthError}.
|
|
67
|
+
* @param message A human-readable description of the failure.
|
|
68
|
+
*/
|
|
69
|
+
constructor(message) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.name = "SmtpAuthError";
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Encodes a string as Base64 in a cross-runtime, UTF-8-safe manner.
|
|
76
|
+
*
|
|
77
|
+
* Unlike calling `btoa()` directly, this first encodes the input as UTF-8 so
|
|
78
|
+
* that non-ASCII characters (e.g., in an internationalized address) do not
|
|
79
|
+
* throw.
|
|
80
|
+
*
|
|
81
|
+
* @param input The string to encode.
|
|
82
|
+
* @returns The Base64-encoded representation of the UTF-8 bytes of `input`.
|
|
83
|
+
*/
|
|
84
|
+
function toBase64(input) {
|
|
85
|
+
const bytes = new TextEncoder().encode(input);
|
|
86
|
+
let binary = "";
|
|
87
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
88
|
+
return btoa(binary);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Builds the SASL `XOAUTH2` initial client response for SMTP authentication.
|
|
92
|
+
*
|
|
93
|
+
* The unencoded payload follows Google's XOAUTH2 format
|
|
94
|
+
* (`user=<user>^Aauth=Bearer <token>^A^A`, where `^A` is the `0x01` control
|
|
95
|
+
* character) and is returned Base64-encoded, ready to be sent as the argument
|
|
96
|
+
* of `AUTH XOAUTH2`.
|
|
97
|
+
*
|
|
98
|
+
* @param user The user (email address) to authenticate as.
|
|
99
|
+
* @param accessToken The OAuth 2.0 access token.
|
|
100
|
+
* @returns The Base64-encoded XOAUTH2 initial client response.
|
|
101
|
+
* @since 0.5.0
|
|
102
|
+
*/
|
|
103
|
+
function formatXoauth2(user, accessToken) {
|
|
104
|
+
return toBase64(`user=${user}\x01auth=Bearer ${accessToken}\x01\x01`);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Builds the SASL `OAUTHBEARER` initial client response for SMTP
|
|
108
|
+
* authentication, as defined by [RFC 7628].
|
|
109
|
+
*
|
|
110
|
+
* The unencoded payload is
|
|
111
|
+
* `n,a=<user>,^A[host=<host>^A][port=<port>^A]auth=Bearer <token>^A^A`
|
|
112
|
+
* (where `^A` is the `0x01` control character) and is returned Base64-encoded,
|
|
113
|
+
* ready to be sent as the argument of `AUTH OAUTHBEARER`.
|
|
114
|
+
*
|
|
115
|
+
* [RFC 7628]: https://www.rfc-editor.org/rfc/rfc7628
|
|
116
|
+
*
|
|
117
|
+
* @param user The user (email address) to authenticate as.
|
|
118
|
+
* @param accessToken The OAuth 2.0 access token.
|
|
119
|
+
* @param host The server host to include as the `host` key/value, if any.
|
|
120
|
+
* @param port The server port to include as the `port` key/value, if any.
|
|
121
|
+
* @returns The Base64-encoded OAUTHBEARER initial client response.
|
|
122
|
+
* @since 0.5.0
|
|
123
|
+
*/
|
|
124
|
+
function formatOauthbearer(user, accessToken, host, port) {
|
|
125
|
+
let response = `n,a=${escapeSaslName(user)},\x01`;
|
|
126
|
+
if (host != null) response += `host=${host}\x01`;
|
|
127
|
+
if (port != null) response += `port=${port}\x01`;
|
|
128
|
+
response += `auth=Bearer ${accessToken}\x01\x01`;
|
|
129
|
+
return toBase64(response);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Escapes a SASL name (GS2 `authzid`) per RFC 5801, encoding `,` as `=2C` and
|
|
133
|
+
* `=` as `=3D` so that identities containing those characters do not corrupt
|
|
134
|
+
* the GS2 header.
|
|
135
|
+
*
|
|
136
|
+
* @param name The SASL name to escape.
|
|
137
|
+
* @returns The escaped SASL name.
|
|
138
|
+
*/
|
|
139
|
+
function escapeSaslName(name) {
|
|
140
|
+
return name.replace(/=/g, "=3D").replace(/,/g, "=2C");
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Chooses an OAuth 2.0 SASL mechanism based on the mechanisms advertised by the
|
|
144
|
+
* server in its `AUTH` capability line.
|
|
145
|
+
*
|
|
146
|
+
* `XOAUTH2` is preferred when available (it is the de-facto standard supported
|
|
147
|
+
* by Gmail and Outlook); otherwise `OAUTHBEARER` is used when advertised. When
|
|
148
|
+
* neither is advertised, `xoauth2` is returned as a best-effort default.
|
|
149
|
+
*
|
|
150
|
+
* @param capabilities The capability lines parsed from the server's EHLO
|
|
151
|
+
* response.
|
|
152
|
+
* @returns The selected mechanism, either `"xoauth2"` or `"oauthbearer"`.
|
|
153
|
+
* @since 0.5.0
|
|
154
|
+
*/
|
|
155
|
+
function selectOAuth2Mechanism(capabilities) {
|
|
156
|
+
const authLine = capabilities.find((cap) => cap.toUpperCase().startsWith("AUTH"));
|
|
157
|
+
const mechanisms = authLine == null ? [] : authLine.toUpperCase().replace(/=/g, " ").split(/\s+/).slice(1);
|
|
158
|
+
if (mechanisms.includes("XOAUTH2")) return "xoauth2";
|
|
159
|
+
if (mechanisms.includes("OAUTHBEARER")) return "oauthbearer";
|
|
160
|
+
return "xoauth2";
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Validates that an OAuth 2.0 token endpoint is safe to send client credentials
|
|
164
|
+
* to, requiring HTTPS except for loopback addresses (for local testing).
|
|
165
|
+
*
|
|
166
|
+
* @param endpoint The token endpoint URL to validate.
|
|
167
|
+
* @throws {TypeError} If the URL is malformed or uses an insecure scheme.
|
|
168
|
+
*/
|
|
169
|
+
function assertSecureTokenEndpoint(endpoint) {
|
|
170
|
+
let url;
|
|
171
|
+
try {
|
|
172
|
+
url = new URL(endpoint);
|
|
173
|
+
} catch {
|
|
174
|
+
throw new TypeError(`Invalid OAuth 2.0 token endpoint URL: ${endpoint}`);
|
|
175
|
+
}
|
|
176
|
+
if (url.protocol === "https:") return;
|
|
177
|
+
const isLoopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "::1";
|
|
178
|
+
if (url.protocol === "http:" && isLoopback) return;
|
|
179
|
+
throw new TypeError("OAuth 2.0 token endpoint must use HTTPS to protect client credentials: " + endpoint);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The number of milliseconds before a cached access token's expiry at which it
|
|
183
|
+
* is considered stale and eligible for refresh.
|
|
184
|
+
*/
|
|
185
|
+
const REFRESH_SAFETY_MARGIN_MS = 6e4;
|
|
186
|
+
/**
|
|
187
|
+
* The default access token lifetime (in seconds) assumed when the token
|
|
188
|
+
* endpoint omits `expires_in`.
|
|
189
|
+
*/
|
|
190
|
+
const DEFAULT_EXPIRES_IN = 3600;
|
|
191
|
+
/**
|
|
192
|
+
* How long to wait for the token endpoint before aborting the request, so a
|
|
193
|
+
* stalled endpoint cannot block authentication indefinitely.
|
|
194
|
+
*/
|
|
195
|
+
const TOKEN_REQUEST_TIMEOUT_MS = 6e4;
|
|
196
|
+
/** Maximum number of response-body characters to include in error messages. */
|
|
197
|
+
const MAX_ERROR_BODY_LENGTH = 500;
|
|
198
|
+
/**
|
|
199
|
+
* Truncates a token-endpoint response body so an oversized payload (e.g. a
|
|
200
|
+
* large proxy/CDN error page) does not bloat error messages and logs.
|
|
201
|
+
*
|
|
202
|
+
* @param text The response body text.
|
|
203
|
+
* @returns The text, truncated with an ellipsis if it exceeds the limit.
|
|
204
|
+
*/
|
|
205
|
+
function truncateErrorBody(text) {
|
|
206
|
+
return text.length > MAX_ERROR_BODY_LENGTH ? `${text.slice(0, MAX_ERROR_BODY_LENGTH)}…` : text;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Mirrors a promise but rejects early if the given abort signal fires, without
|
|
210
|
+
* cancelling the underlying promise. This lets a single waiter abort its own
|
|
211
|
+
* wait on a shared operation without affecting other waiters.
|
|
212
|
+
*
|
|
213
|
+
* @param promise The promise to await.
|
|
214
|
+
* @param signal An optional abort signal that rejects the returned promise.
|
|
215
|
+
* @returns A promise that settles with `promise`, or rejects when `signal`
|
|
216
|
+
* aborts.
|
|
217
|
+
*/
|
|
218
|
+
function abortable(promise, signal) {
|
|
219
|
+
if (signal == null) return promise;
|
|
220
|
+
return new Promise((resolve, reject) => {
|
|
221
|
+
const abortReason = () => signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
222
|
+
const onAbort = () => reject(abortReason());
|
|
223
|
+
if (signal.aborted) reject(abortReason());
|
|
224
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
225
|
+
promise.then((value) => {
|
|
226
|
+
signal.removeEventListener("abort", onAbort);
|
|
227
|
+
resolve(value);
|
|
228
|
+
}, (error) => {
|
|
229
|
+
signal.removeEventListener("abort", onAbort);
|
|
230
|
+
reject(error);
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Acquires and caches OAuth 2.0 access tokens for SMTP authentication.
|
|
236
|
+
*
|
|
237
|
+
* Depending on the {@link SmtpOAuth2Auth} configuration, the manager either
|
|
238
|
+
* returns a static token, invokes a provider callback on every request, or
|
|
239
|
+
* exchanges a refresh token for an access token at the configured token
|
|
240
|
+
* endpoint and caches it until shortly before it expires. A single manager is
|
|
241
|
+
* shared across all pooled connections of a transport so that the refresh-token
|
|
242
|
+
* exchange happens at most once per token lifetime.
|
|
243
|
+
*
|
|
244
|
+
* @since 0.5.0
|
|
245
|
+
*/
|
|
246
|
+
var OAuth2TokenManager = class {
|
|
247
|
+
auth;
|
|
248
|
+
fetchFn;
|
|
249
|
+
cached;
|
|
250
|
+
pending;
|
|
251
|
+
/**
|
|
252
|
+
* Creates a new {@link OAuth2TokenManager}.
|
|
253
|
+
*
|
|
254
|
+
* @param auth The OAuth 2.0 authentication configuration.
|
|
255
|
+
* @param fetchFn The `fetch` implementation to use for the refresh-token
|
|
256
|
+
* exchange. Defaults to the global `fetch`; primarily
|
|
257
|
+
* overridden in tests.
|
|
258
|
+
* @throws {TypeError} If a refresh-token configuration has an insecure
|
|
259
|
+
* (non-HTTPS) token endpoint.
|
|
260
|
+
*/
|
|
261
|
+
constructor(auth, fetchFn = fetch) {
|
|
262
|
+
if ("refreshToken" in auth) assertSecureTokenEndpoint(auth.tokenEndpoint);
|
|
263
|
+
this.auth = auth;
|
|
264
|
+
this.fetchFn = fetchFn;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Returns a valid OAuth 2.0 access token, acquiring or refreshing it as
|
|
268
|
+
* needed.
|
|
269
|
+
*
|
|
270
|
+
* @param signal An optional {@link AbortSignal} to cancel token acquisition.
|
|
271
|
+
* @returns The current access token.
|
|
272
|
+
* @throws {SmtpAuthError} If a refresh-token exchange fails or returns an
|
|
273
|
+
* unexpected response.
|
|
274
|
+
*/
|
|
275
|
+
async getAccessToken(signal) {
|
|
276
|
+
signal?.throwIfAborted();
|
|
277
|
+
const auth = this.auth;
|
|
278
|
+
if ("accessToken" in auth) return typeof auth.accessToken === "function" ? await auth.accessToken(signal) : auth.accessToken;
|
|
279
|
+
const cached = this.cached;
|
|
280
|
+
if (cached != null && cached.expiresAt > Date.now()) return cached.accessToken;
|
|
281
|
+
this.pending ??= this.refresh(auth).then((result) => {
|
|
282
|
+
const lifetimeMs = result.expiresIn * 1e3;
|
|
283
|
+
const safetyMargin = Math.min(REFRESH_SAFETY_MARGIN_MS, lifetimeMs / 2);
|
|
284
|
+
this.cached = {
|
|
285
|
+
accessToken: result.accessToken,
|
|
286
|
+
expiresAt: Date.now() + lifetimeMs - safetyMargin
|
|
287
|
+
};
|
|
288
|
+
return result;
|
|
289
|
+
}).finally(() => {
|
|
290
|
+
this.pending = void 0;
|
|
291
|
+
});
|
|
292
|
+
const { accessToken } = await abortable(this.pending, signal);
|
|
293
|
+
return accessToken;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Exchanges the configured refresh token for a fresh access token.
|
|
297
|
+
*
|
|
298
|
+
* The request deliberately runs without a caller-specific abort signal; it is
|
|
299
|
+
* shared across concurrent callers, each of which applies its own
|
|
300
|
+
* cancellation separately (see {@link getAccessToken}).
|
|
301
|
+
*
|
|
302
|
+
* @param auth The refresh-token authentication configuration.
|
|
303
|
+
* @returns The new access token and its lifetime in seconds.
|
|
304
|
+
* @throws {SmtpAuthError} If the request fails or the response is invalid.
|
|
305
|
+
*/
|
|
306
|
+
async refresh(auth) {
|
|
307
|
+
const body = new URLSearchParams({
|
|
308
|
+
grant_type: "refresh_token",
|
|
309
|
+
client_id: auth.clientId,
|
|
310
|
+
refresh_token: auth.refreshToken
|
|
311
|
+
});
|
|
312
|
+
if (auth.clientSecret != null) body.set("client_secret", auth.clientSecret);
|
|
313
|
+
if (auth.scope != null) body.set("scope", auth.scope);
|
|
314
|
+
const controller = new AbortController();
|
|
315
|
+
const timeout = setTimeout(() => {
|
|
316
|
+
controller.abort(/* @__PURE__ */ new Error("OAuth 2.0 token request timed out"));
|
|
317
|
+
}, TOKEN_REQUEST_TIMEOUT_MS);
|
|
318
|
+
let response;
|
|
319
|
+
let text;
|
|
320
|
+
const fetchFn = this.fetchFn;
|
|
321
|
+
try {
|
|
322
|
+
response = await fetchFn(auth.tokenEndpoint, {
|
|
323
|
+
method: "POST",
|
|
324
|
+
headers: {
|
|
325
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
326
|
+
"accept": "application/json"
|
|
327
|
+
},
|
|
328
|
+
body,
|
|
329
|
+
signal: controller.signal
|
|
330
|
+
});
|
|
331
|
+
text = await response.text();
|
|
332
|
+
} catch (cause) {
|
|
333
|
+
throw new SmtpAuthError(`Failed to request an OAuth 2.0 access token from ${auth.tokenEndpoint}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
334
|
+
} finally {
|
|
335
|
+
clearTimeout(timeout);
|
|
336
|
+
}
|
|
337
|
+
const safeText = truncateErrorBody(text);
|
|
338
|
+
if (!response.ok) throw new SmtpAuthError(`OAuth 2.0 token endpoint responded with HTTP ${response.status}: ${safeText}`);
|
|
339
|
+
let json;
|
|
340
|
+
try {
|
|
341
|
+
json = JSON.parse(text);
|
|
342
|
+
} catch {
|
|
343
|
+
throw new SmtpAuthError(`OAuth 2.0 token endpoint returned a non-JSON response: ${safeText}`);
|
|
344
|
+
}
|
|
345
|
+
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}`);
|
|
346
|
+
const record = json;
|
|
347
|
+
const rawExpiresIn = record.expires_in;
|
|
348
|
+
let parsedExpiresIn;
|
|
349
|
+
if (typeof rawExpiresIn === "number") parsedExpiresIn = rawExpiresIn;
|
|
350
|
+
else if (typeof rawExpiresIn === "string" && rawExpiresIn.trim() !== "") parsedExpiresIn = Number(rawExpiresIn);
|
|
351
|
+
else parsedExpiresIn = NaN;
|
|
352
|
+
const expiresIn = Number.isFinite(parsedExpiresIn) && parsedExpiresIn >= 0 ? parsedExpiresIn : DEFAULT_EXPIRES_IN;
|
|
353
|
+
return {
|
|
354
|
+
accessToken: record.access_token,
|
|
355
|
+
expiresIn
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
56
360
|
//#endregion
|
|
57
361
|
//#region src/smtp-connection.ts
|
|
362
|
+
/**
|
|
363
|
+
* The maximum length of an SMTP command line, including the terminating CRLF,
|
|
364
|
+
* as specified by RFC 5321 §4.5.3.1.4.
|
|
365
|
+
*/
|
|
366
|
+
const MAX_COMMAND_LINE_LENGTH = 512;
|
|
367
|
+
/** The length of the CRLF terminator appended to every command. */
|
|
368
|
+
const CRLF_LENGTH = 2;
|
|
369
|
+
/**
|
|
370
|
+
* How long, in milliseconds, to wait for the graceful `QUIT` to flush during
|
|
371
|
+
* teardown before giving up, so an unresponsive server cannot block shutdown
|
|
372
|
+
* for the full socket timeout.
|
|
373
|
+
*/
|
|
374
|
+
const QUIT_TIMEOUT_MS = 5e3;
|
|
375
|
+
/**
|
|
376
|
+
* Whether a host refers to the local loopback interface, for which cleartext
|
|
377
|
+
* OAuth 2.0 authentication is permitted (e.g. local testing and development).
|
|
378
|
+
*
|
|
379
|
+
* @param host The host to check.
|
|
380
|
+
* @returns `true` if the host is a loopback address.
|
|
381
|
+
*/
|
|
382
|
+
function isLoopbackHost(host) {
|
|
383
|
+
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
|
|
384
|
+
}
|
|
58
385
|
var SmtpConnection = class {
|
|
59
386
|
socket = null;
|
|
60
387
|
config;
|
|
61
388
|
authenticated = false;
|
|
62
389
|
capabilities = [];
|
|
63
|
-
|
|
390
|
+
tokenManager;
|
|
391
|
+
constructor(config, tokenManager) {
|
|
64
392
|
this.config = createSmtpConfig(config);
|
|
393
|
+
this.tokenManager = tokenManager ?? null;
|
|
65
394
|
}
|
|
66
395
|
connect(signal) {
|
|
67
396
|
if (this.socket) throw new Error("Connection already established");
|
|
@@ -231,29 +560,44 @@ var SmtpConnection = class {
|
|
|
231
560
|
});
|
|
232
561
|
}
|
|
233
562
|
async authenticate(signal) {
|
|
234
|
-
|
|
563
|
+
const auth = this.config.auth;
|
|
564
|
+
if (!auth) return;
|
|
235
565
|
if (this.authenticated) return;
|
|
236
|
-
|
|
237
|
-
if (
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
566
|
+
if (!this.capabilities.some((cap) => cap.toUpperCase().startsWith("AUTH"))) throw new SmtpAuthError("Server does not support authentication.");
|
|
567
|
+
if ("accessToken" in auth || "refreshToken" in auth) {
|
|
568
|
+
if (!(this.socket instanceof node_tls.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.");
|
|
569
|
+
const mechanism = auth.method ?? selectOAuth2Mechanism(this.capabilities);
|
|
570
|
+
switch (mechanism) {
|
|
571
|
+
case "xoauth2":
|
|
572
|
+
await this.authXoauth2(auth, signal);
|
|
573
|
+
break;
|
|
574
|
+
case "oauthbearer":
|
|
575
|
+
await this.authOauthbearer(auth, signal);
|
|
576
|
+
break;
|
|
577
|
+
default: throw new SmtpAuthError(`Unsupported authentication method: ${mechanism}`);
|
|
578
|
+
}
|
|
579
|
+
} else {
|
|
580
|
+
const method = auth.method ?? "plain";
|
|
581
|
+
switch (method) {
|
|
582
|
+
case "plain":
|
|
583
|
+
await this.authPlain(auth, signal);
|
|
584
|
+
break;
|
|
585
|
+
case "login":
|
|
586
|
+
await this.authLogin(auth, signal);
|
|
587
|
+
break;
|
|
588
|
+
default: throw new Error(`Unsupported authentication method: ${method}`);
|
|
589
|
+
}
|
|
246
590
|
}
|
|
247
591
|
this.authenticated = true;
|
|
248
592
|
}
|
|
249
|
-
async authPlain(signal) {
|
|
250
|
-
const { user, pass } =
|
|
593
|
+
async authPlain(auth, signal) {
|
|
594
|
+
const { user, pass } = auth;
|
|
251
595
|
const credentials = btoa(`\0${user}\0${pass}`);
|
|
252
596
|
const response = await this.sendCommand(`AUTH PLAIN ${credentials}`, signal);
|
|
253
597
|
if (response.code !== 235) throw new Error(`Authentication failed: ${response.message}`);
|
|
254
598
|
}
|
|
255
|
-
async authLogin(signal) {
|
|
256
|
-
const { user, pass } =
|
|
599
|
+
async authLogin(auth, signal) {
|
|
600
|
+
const { user, pass } = auth;
|
|
257
601
|
let response = await this.sendCommand("AUTH LOGIN", signal);
|
|
258
602
|
if (response.code !== 334) throw new Error(`AUTH LOGIN failed: ${response.message}`);
|
|
259
603
|
response = await this.sendCommand(btoa(user), signal);
|
|
@@ -261,6 +605,67 @@ var SmtpConnection = class {
|
|
|
261
605
|
response = await this.sendCommand(btoa(pass), signal);
|
|
262
606
|
if (response.code !== 235) throw new Error(`Password authentication failed: ${response.message}`);
|
|
263
607
|
}
|
|
608
|
+
/**
|
|
609
|
+
* Resolves an OAuth 2.0 access token via the connection's token manager,
|
|
610
|
+
* creating a standalone manager from the auth config if none was injected.
|
|
611
|
+
*/
|
|
612
|
+
async getOAuth2Token(auth, signal) {
|
|
613
|
+
this.tokenManager ??= new OAuth2TokenManager(auth);
|
|
614
|
+
return await this.tokenManager.getAccessToken(signal);
|
|
615
|
+
}
|
|
616
|
+
async authXoauth2(auth, signal) {
|
|
617
|
+
const token = await this.getOAuth2Token(auth, signal);
|
|
618
|
+
const initialResponse = formatXoauth2(auth.user, token);
|
|
619
|
+
const response = await this.sendSaslAuth("XOAUTH2", initialResponse, signal);
|
|
620
|
+
await this.finishOAuth2(response, "XOAUTH2", "", signal);
|
|
621
|
+
}
|
|
622
|
+
async authOauthbearer(auth, signal) {
|
|
623
|
+
const token = await this.getOAuth2Token(auth, signal);
|
|
624
|
+
const initialResponse = formatOauthbearer(auth.user, token, this.config.host, this.config.port);
|
|
625
|
+
const response = await this.sendSaslAuth("OAUTHBEARER", initialResponse, signal);
|
|
626
|
+
await this.finishOAuth2(response, "OAUTHBEARER", "AQ==", signal);
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Sends a SASL `AUTH` command with its Base64 initial response.
|
|
630
|
+
*
|
|
631
|
+
* When the resulting command line would exceed the SMTP command-line length
|
|
632
|
+
* limit (e.g. a long Outlook JWT access token), RFC 4954 requires the client
|
|
633
|
+
* to omit the initial response and send it on its own line after the server's
|
|
634
|
+
* `334` challenge. This method transparently falls back to that two-step
|
|
635
|
+
* form, since some servers reject the over-long single-line command outright.
|
|
636
|
+
*
|
|
637
|
+
* @param mechanism The SASL mechanism name (e.g. `XOAUTH2`).
|
|
638
|
+
* @param initialResponse The Base64-encoded initial client response.
|
|
639
|
+
* @param signal An optional {@link AbortSignal}.
|
|
640
|
+
* @returns The server's response to the initial response.
|
|
641
|
+
*/
|
|
642
|
+
async sendSaslAuth(mechanism, initialResponse, signal) {
|
|
643
|
+
const inlineCommand = `AUTH ${mechanism} ${initialResponse}`;
|
|
644
|
+
if (inlineCommand.length + CRLF_LENGTH <= MAX_COMMAND_LINE_LENGTH) return await this.sendCommand(inlineCommand, signal);
|
|
645
|
+
const challenge = await this.sendCommand(`AUTH ${mechanism}`, signal);
|
|
646
|
+
if (challenge.code !== 334) return challenge;
|
|
647
|
+
return await this.sendCommand(initialResponse, signal);
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Interprets the server's reply to an OAuth SASL initial response, draining
|
|
651
|
+
* the failure challenge continuation when authentication is rejected.
|
|
652
|
+
*
|
|
653
|
+
* @throws {SmtpAuthError} If authentication did not succeed.
|
|
654
|
+
*/
|
|
655
|
+
async finishOAuth2(response, mechanism, continuation, signal) {
|
|
656
|
+
if (response.code === 235) return;
|
|
657
|
+
if (response.code === 334) {
|
|
658
|
+
let finalMessage = "";
|
|
659
|
+
try {
|
|
660
|
+
const final = await this.sendCommand(continuation, signal);
|
|
661
|
+
finalMessage = ` (${final.message})`;
|
|
662
|
+
} catch {
|
|
663
|
+
signal?.throwIfAborted();
|
|
664
|
+
}
|
|
665
|
+
throw new SmtpAuthError(`${mechanism} authentication failed: ${decodeOAuth2Challenge(response.message)}${finalMessage}`);
|
|
666
|
+
}
|
|
667
|
+
throw new SmtpAuthError(`${mechanism} authentication failed: ${response.message}`);
|
|
668
|
+
}
|
|
264
669
|
async sendMessage(message, signal) {
|
|
265
670
|
const mailResponse = await this.sendCommand(`MAIL FROM:<${message.envelope.from}>`, signal);
|
|
266
671
|
if (mailResponse.code !== 250) throw new Error(`MAIL FROM failed: ${mailResponse.message}`);
|
|
@@ -282,11 +687,27 @@ var SmtpConnection = class {
|
|
|
282
687
|
return match ? match[1] : `smtp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
283
688
|
}
|
|
284
689
|
async quit() {
|
|
285
|
-
|
|
690
|
+
const socket = this.socket;
|
|
691
|
+
if (!socket) return;
|
|
692
|
+
if (socket.writable) await new Promise((resolve) => {
|
|
693
|
+
const done = () => {
|
|
694
|
+
clearTimeout(timer);
|
|
695
|
+
socket.off("error", done);
|
|
696
|
+
socket.off("close", done);
|
|
697
|
+
resolve();
|
|
698
|
+
};
|
|
699
|
+
const timer = setTimeout(done, QUIT_TIMEOUT_MS);
|
|
700
|
+
socket.once("error", done);
|
|
701
|
+
socket.once("close", done);
|
|
702
|
+
try {
|
|
703
|
+
socket.write("QUIT\r\n", done);
|
|
704
|
+
} catch {
|
|
705
|
+
done();
|
|
706
|
+
}
|
|
707
|
+
});
|
|
286
708
|
try {
|
|
287
|
-
|
|
709
|
+
socket.destroy();
|
|
288
710
|
} catch {}
|
|
289
|
-
this.socket.destroy();
|
|
290
711
|
this.socket = null;
|
|
291
712
|
this.authenticated = false;
|
|
292
713
|
this.capabilities = [];
|
|
@@ -297,6 +718,25 @@ var SmtpConnection = class {
|
|
|
297
718
|
if (response.code !== 250) throw new Error(`RESET failed: ${response.message}`);
|
|
298
719
|
}
|
|
299
720
|
};
|
|
721
|
+
/**
|
|
722
|
+
* Decodes the Base64 JSON error challenge a server sends after a failed OAuth
|
|
723
|
+
* SASL exchange, falling back to the raw message when it is not valid Base64.
|
|
724
|
+
*
|
|
725
|
+
* The bytes are decoded as UTF-8 (via `TextDecoder`) so non-ASCII challenge
|
|
726
|
+
* messages are not corrupted, unlike decoding `atob`'s Latin-1 output directly.
|
|
727
|
+
*
|
|
728
|
+
* @param message The challenge text from the server's 334 response.
|
|
729
|
+
* @returns A human-readable description of the failure.
|
|
730
|
+
*/
|
|
731
|
+
function decodeOAuth2Challenge(message) {
|
|
732
|
+
try {
|
|
733
|
+
const binary = atob(message.trim());
|
|
734
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
735
|
+
return new TextDecoder().decode(bytes);
|
|
736
|
+
} catch {
|
|
737
|
+
return message;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
300
740
|
|
|
301
741
|
//#endregion
|
|
302
742
|
//#region src/dkim/canonicalize.ts
|
|
@@ -794,6 +1234,13 @@ var SmtpTransport = class {
|
|
|
794
1234
|
poolSize;
|
|
795
1235
|
connectionPool = [];
|
|
796
1236
|
/**
|
|
1237
|
+
* A token manager shared across all pooled connections, present only when the
|
|
1238
|
+
* configured authentication uses OAuth 2.0. Sharing it ensures the
|
|
1239
|
+
* refresh-token exchange happens at most once per token lifetime instead of
|
|
1240
|
+
* once per connection.
|
|
1241
|
+
*/
|
|
1242
|
+
tokenManager;
|
|
1243
|
+
/**
|
|
797
1244
|
* Creates a new SMTP transport instance.
|
|
798
1245
|
*
|
|
799
1246
|
* @param config SMTP configuration including server details, authentication,
|
|
@@ -802,6 +1249,8 @@ var SmtpTransport = class {
|
|
|
802
1249
|
constructor(config) {
|
|
803
1250
|
this.config = config;
|
|
804
1251
|
this.poolSize = config.poolSize ?? 5;
|
|
1252
|
+
const auth = config.auth;
|
|
1253
|
+
this.tokenManager = auth != null && ("accessToken" in auth || "refreshToken" in auth) ? new OAuth2TokenManager(auth) : void 0;
|
|
805
1254
|
}
|
|
806
1255
|
/**
|
|
807
1256
|
* Sends a single email message via SMTP.
|
|
@@ -831,8 +1280,9 @@ var SmtpTransport = class {
|
|
|
831
1280
|
*/
|
|
832
1281
|
async send(message, options) {
|
|
833
1282
|
options?.signal?.throwIfAborted();
|
|
834
|
-
|
|
1283
|
+
let connection;
|
|
835
1284
|
try {
|
|
1285
|
+
connection = await this.getConnection(options?.signal);
|
|
836
1286
|
options?.signal?.throwIfAborted();
|
|
837
1287
|
const smtpMessage = await convertMessage(message, this.config.dkim);
|
|
838
1288
|
options?.signal?.throwIfAborted();
|
|
@@ -843,7 +1293,8 @@ var SmtpTransport = class {
|
|
|
843
1293
|
messageId
|
|
844
1294
|
};
|
|
845
1295
|
} catch (error) {
|
|
846
|
-
await this.discardConnection(connection);
|
|
1296
|
+
if (connection != null) await this.discardConnection(connection);
|
|
1297
|
+
options?.signal?.throwIfAborted();
|
|
847
1298
|
return {
|
|
848
1299
|
successful: false,
|
|
849
1300
|
errorMessages: [error instanceof Error ? error.message : String(error)]
|
|
@@ -880,7 +1331,21 @@ var SmtpTransport = class {
|
|
|
880
1331
|
*/
|
|
881
1332
|
async *sendMany(messages, options) {
|
|
882
1333
|
options?.signal?.throwIfAborted();
|
|
883
|
-
|
|
1334
|
+
let connection;
|
|
1335
|
+
try {
|
|
1336
|
+
connection = await this.getConnection(options?.signal);
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
options?.signal?.throwIfAborted();
|
|
1339
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1340
|
+
for await (const _ of messages) {
|
|
1341
|
+
options?.signal?.throwIfAborted();
|
|
1342
|
+
yield {
|
|
1343
|
+
successful: false,
|
|
1344
|
+
errorMessages: [errorMessage]
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
884
1349
|
let connectionValid = true;
|
|
885
1350
|
try {
|
|
886
1351
|
const isAsyncIterable = Symbol.asyncIterator in messages;
|
|
@@ -902,6 +1367,7 @@ var SmtpTransport = class {
|
|
|
902
1367
|
messageId
|
|
903
1368
|
};
|
|
904
1369
|
} catch (error) {
|
|
1370
|
+
options?.signal?.throwIfAborted();
|
|
905
1371
|
connectionValid = false;
|
|
906
1372
|
yield {
|
|
907
1373
|
successful: false,
|
|
@@ -927,6 +1393,7 @@ var SmtpTransport = class {
|
|
|
927
1393
|
messageId
|
|
928
1394
|
};
|
|
929
1395
|
} catch (error) {
|
|
1396
|
+
options?.signal?.throwIfAborted();
|
|
930
1397
|
connectionValid = false;
|
|
931
1398
|
yield {
|
|
932
1399
|
successful: false,
|
|
@@ -944,8 +1411,13 @@ var SmtpTransport = class {
|
|
|
944
1411
|
async getConnection(signal) {
|
|
945
1412
|
signal?.throwIfAborted();
|
|
946
1413
|
if (this.connectionPool.length > 0) return this.connectionPool.pop();
|
|
947
|
-
const connection = new SmtpConnection(this.config);
|
|
948
|
-
|
|
1414
|
+
const connection = new SmtpConnection(this.config, this.tokenManager);
|
|
1415
|
+
try {
|
|
1416
|
+
await this.connectAndSetup(connection, signal);
|
|
1417
|
+
} catch (error) {
|
|
1418
|
+
await this.discardConnection(connection);
|
|
1419
|
+
throw error;
|
|
1420
|
+
}
|
|
949
1421
|
return connection;
|
|
950
1422
|
}
|
|
951
1423
|
async connectAndSetup(connection, signal) {
|
|
@@ -1021,4 +1493,5 @@ var SmtpTransport = class {
|
|
|
1021
1493
|
};
|
|
1022
1494
|
|
|
1023
1495
|
//#endregion
|
|
1496
|
+
exports.SmtpAuthError = SmtpAuthError;
|
|
1024
1497
|
exports.SmtpTransport = SmtpTransport;
|