@remit/smtp-service 0.0.18 → 0.0.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/smtp-service",
3
- "version": "0.0.18",
3
+ "version": "0.0.20",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "exports": {
@@ -11,6 +11,10 @@
11
11
  "./message-builder": {
12
12
  "types": "./src/message-builder.ts",
13
13
  "default": "./src/message-builder.ts"
14
+ },
15
+ "./test-fake-smtp": {
16
+ "types": "./src/test-fake-smtp.ts",
17
+ "default": "./src/test-fake-smtp.ts"
14
18
  }
15
19
  },
16
20
  "scripts": {
@@ -5,17 +5,17 @@ import nodemailer, { type SendMailOptions } from "nodemailer";
5
5
  export interface MailMessage {
6
6
  from: string;
7
7
  to: string[];
8
- cc?: string[];
9
- bcc?: string[];
10
- replyTo?: string;
11
- subject?: string;
12
- text?: string;
13
- html?: string;
8
+ cc?: string[] | undefined;
9
+ bcc?: string[] | undefined;
10
+ replyTo?: string | undefined;
11
+ subject?: string | undefined;
12
+ text?: string | undefined;
13
+ html?: string | undefined;
14
14
  messageId: string;
15
- inReplyTo?: string;
16
- references?: string;
17
- date?: Date;
18
- attachments?: MailAttachment[];
15
+ inReplyTo?: string | undefined;
16
+ references?: string | undefined;
17
+ date?: Date | undefined;
18
+ attachments?: MailAttachment[] | undefined;
19
19
  }
20
20
 
21
21
  export interface MailAttachment {
@@ -3,81 +3,24 @@ import net from "node:net";
3
3
  import { after, describe, it } from "node:test";
4
4
  import type { MailMessage } from "./message-builder.js";
5
5
  import {
6
+ directSmtpSocket,
6
7
  type SmtpConfig,
7
8
  SmtpConnectionError,
8
9
  type SmtpCredentials,
9
10
  sendMail,
11
+ verifySmtpConnection,
10
12
  } from "./smtp-client.js";
11
-
12
- interface FakeSmtpOptions {
13
- authResponse?: string;
14
- dataFinalResponse?: string;
15
- dropAfterGreeting?: boolean;
16
- }
17
-
18
- interface FakeSmtp {
19
- port: number;
20
- authCommands: string[];
21
- close: () => void;
13
+ import {
14
+ type FakeSmtp,
15
+ type FakeSmtpOptions,
16
+ startFakeSmtp,
17
+ } from "./test-fake-smtp.js";
18
+
19
+ interface SocketRequest {
20
+ host: string | undefined;
21
+ port: string | number | undefined;
22
22
  }
23
23
 
24
- const startFakeSmtp = (opts: FakeSmtpOptions = {}): Promise<FakeSmtp> =>
25
- new Promise((resolve) => {
26
- const authCommands: string[] = [];
27
- const server = net.createServer((socket) => {
28
- if (opts.dropAfterGreeting) {
29
- socket.destroy();
30
- return;
31
- }
32
- socket.write("220 fake ESMTP\r\n");
33
- let inData = false;
34
- socket.on("data", (buffer) => {
35
- const line = buffer.toString();
36
- if (inData) {
37
- if (line.includes("\r\n.\r\n")) {
38
- inData = false;
39
- socket.write(opts.dataFinalResponse ?? "250 2.0.0 Ok\r\n");
40
- }
41
- return;
42
- }
43
- const command = line.slice(0, 4).toUpperCase();
44
- if (command.startsWith("EHLO") || command.startsWith("HELO")) {
45
- socket.write("250-fake\r\n250 AUTH PLAIN LOGIN XOAUTH2\r\n");
46
- return;
47
- }
48
- if (command.startsWith("AUTH")) {
49
- authCommands.push(line.trim());
50
- socket.write(opts.authResponse ?? "235 2.7.0 Accepted\r\n");
51
- return;
52
- }
53
- if (command.startsWith("MAIL") || command.startsWith("RCPT")) {
54
- socket.write("250 2.1.0 Ok\r\n");
55
- return;
56
- }
57
- if (command.startsWith("DATA")) {
58
- socket.write("354 End data\r\n");
59
- inData = true;
60
- return;
61
- }
62
- if (command.startsWith("QUIT")) {
63
- socket.write("221 Bye\r\n");
64
- socket.end();
65
- return;
66
- }
67
- socket.write("250 Ok\r\n");
68
- });
69
- });
70
- server.listen(0, "127.0.0.1", () => {
71
- const address = server.address();
72
- const port = typeof address === "object" && address ? address.port : 0;
73
- resolve({
74
- port,
75
- authCommands,
76
- close: () => server.close(),
77
- });
78
- });
79
- });
80
-
81
24
  const configFor = (
82
25
  port: number,
83
26
  credentials: SmtpCredentials = { kind: "password", password: "secret" },
@@ -88,6 +31,7 @@ const configFor = (
88
31
  user: "user@example.com",
89
32
  credentials,
90
33
  connectionTimeout: 2000,
34
+ getSocket: directSmtpSocket,
91
35
  });
92
36
 
93
37
  const testMessage: MailMessage = {
@@ -121,6 +65,28 @@ describe("sendMail", () => {
121
65
  assert.ok(result.response);
122
66
  });
123
67
 
68
+ it("talks to the server over the socket the host's factory opens", async () => {
69
+ const server = await spawn();
70
+ const requests: SocketRequest[] = [];
71
+ const result = await sendMail(
72
+ {
73
+ ...configFor(server.port),
74
+ host: "smtp.invalid",
75
+ port: 2525,
76
+ getSocket: (request, callback) => {
77
+ requests.push({ host: request.host, port: request.port });
78
+ const connection = net.connect(server.port, "127.0.0.1", () =>
79
+ callback(null, { connection }),
80
+ );
81
+ },
82
+ },
83
+ testMessage,
84
+ );
85
+
86
+ assert.equal(result.success, true);
87
+ assert.deepEqual(requests, [{ host: "smtp.invalid", port: 2525 }]);
88
+ });
89
+
124
90
  it("sends attachments through the transport", async () => {
125
91
  const server = await spawn();
126
92
  const result = await sendMail(configFor(server.port), {
@@ -211,3 +177,40 @@ describe("sendMail", () => {
211
177
  assert.ok(result.error);
212
178
  });
213
179
  });
180
+
181
+ describe("verifySmtpConnection", () => {
182
+ const servers: FakeSmtp[] = [];
183
+ const spawn = async (opts?: FakeSmtpOptions): Promise<FakeSmtp> => {
184
+ const server = await startFakeSmtp(opts);
185
+ servers.push(server);
186
+ return server;
187
+ };
188
+
189
+ after(() => {
190
+ for (const server of servers) {
191
+ server.close();
192
+ }
193
+ });
194
+
195
+ it("succeeds when the server accepts the login", async () => {
196
+ const server = await spawn();
197
+
198
+ const result = await verifySmtpConnection(configFor(server.port));
199
+
200
+ assert.deepEqual(result, { success: true });
201
+ });
202
+
203
+ it("reports a rejected login as an authentication failure", async () => {
204
+ const server = await spawn({
205
+ authResponse: "535 5.7.8 Authentication credentials invalid\r\n",
206
+ });
207
+
208
+ const result = await verifySmtpConnection(configFor(server.port));
209
+
210
+ assert.deepEqual(result, {
211
+ success: false,
212
+ error:
213
+ "SMTP authentication failed: 535 5.7.8 Authentication credentials invalid",
214
+ });
215
+ });
216
+ });
@@ -1,4 +1,6 @@
1
+ import type { TestResult } from "@remit/data-ports";
1
2
  import nodemailer from "nodemailer";
3
+ import type { SMTPTransportGetSocket } from "nodemailer/lib/smtp-transport";
2
4
  import { type MailMessage, toNodemailerOptions } from "./message-builder.js";
3
5
 
4
6
  /**
@@ -31,7 +33,9 @@ export class SmtpConnectionError extends Error {
31
33
  }
32
34
  }
33
35
 
34
- export interface SmtpConfig {
36
+ export type SmtpGetSocket = SMTPTransportGetSocket;
37
+
38
+ export interface SmtpServerConfig {
35
39
  host: string;
36
40
  port: number;
37
41
  secure: boolean; // true for TLS (465), false for STARTTLS (587)
@@ -43,12 +47,20 @@ export interface SmtpConfig {
43
47
  connectionTimeout?: number; // milliseconds, default 30000
44
48
  }
45
49
 
50
+ export const directSmtpSocket: SmtpGetSocket = (_request, callback) => {
51
+ queueMicrotask(() => callback(null, false));
52
+ };
53
+
54
+ export interface SmtpConfig extends SmtpServerConfig {
55
+ getSocket: SmtpGetSocket;
56
+ }
57
+
46
58
  export interface SendResult {
47
59
  success: boolean;
48
- messageId?: string;
49
- response?: string;
50
- error?: Error;
51
- smtpCode?: number;
60
+ messageId?: string | undefined;
61
+ response?: string | undefined;
62
+ error?: Error | undefined;
63
+ smtpCode?: number | undefined;
52
64
  isTransient: boolean;
53
65
  }
54
66
 
@@ -78,15 +90,26 @@ const buildSmtpAuth = (
78
90
  throw new Error(`Unknown credential kind: ${JSON.stringify(_exhaustive)}`);
79
91
  };
80
92
 
81
- /**
82
- * Send email via SMTP using Nodemailer
83
- */
84
- export const sendMail = async (
85
- config: SmtpConfig,
86
- message: MailMessage,
87
- ): Promise<SendResult> => {
93
+ type SmtpFailure = Error & {
94
+ responseCode?: number;
95
+ code?: string;
96
+ command?: string;
97
+ response?: string;
98
+ };
99
+
100
+ const NETWORK_ERROR_CODES = new Set([
101
+ "ECONNREFUSED",
102
+ "ETIMEDOUT",
103
+ "ENOTFOUND",
104
+ "ECONNRESET",
105
+ "EHOSTUNREACH",
106
+ ]);
107
+
108
+ const VERIFY_TIMEOUT_MS = 12_000;
109
+
110
+ const transporterFor = (config: SmtpConfig, socketTimeout: number) => {
88
111
  const timeout = config.connectionTimeout ?? 30_000;
89
- const transporter = nodemailer.createTransport({
112
+ return nodemailer.createTransport({
90
113
  host: config.host,
91
114
  port: config.port,
92
115
  secure: config.secure,
@@ -94,8 +117,50 @@ export const sendMail = async (
94
117
  tls: config.tls,
95
118
  connectionTimeout: timeout,
96
119
  greetingTimeout: timeout,
97
- socketTimeout: 300_000,
120
+ socketTimeout,
121
+ getSocket: config.getSocket,
98
122
  });
123
+ };
124
+
125
+ const classifySmtpError = (error: SmtpFailure): SmtpConnectionError | null => {
126
+ const smtpCode = error.responseCode;
127
+
128
+ if (
129
+ error.code === "EAUTH" ||
130
+ (smtpCode !== undefined && smtpCode >= 500 && error.command === "AUTH")
131
+ ) {
132
+ // The server's own words, when it gave any: a 535 reading
133
+ // "SmtpClientAuthentication is disabled for the Tenant" is not a
134
+ // failure signing in again clears, and the account card can only
135
+ // say so if the text survives the classification.
136
+ return new SmtpConnectionError(
137
+ "auth",
138
+ error.response
139
+ ? `SMTP authentication failed: ${error.response.trim()}`
140
+ : "SMTP authentication failed",
141
+ error,
142
+ );
143
+ }
144
+
145
+ if (error.code !== undefined && NETWORK_ERROR_CODES.has(error.code)) {
146
+ return new SmtpConnectionError(
147
+ "network",
148
+ `SMTP connection failed: ${error.code}`,
149
+ error,
150
+ );
151
+ }
152
+
153
+ return null;
154
+ };
155
+
156
+ /**
157
+ * Send email via SMTP using Nodemailer
158
+ */
159
+ export const sendMail = async (
160
+ config: SmtpConfig,
161
+ message: MailMessage,
162
+ ): Promise<SendResult> => {
163
+ const transporter = transporterFor(config, 300_000);
99
164
 
100
165
  return transporter
101
166
  .sendMail(toNodemailerOptions(message))
@@ -105,62 +170,45 @@ export const sendMail = async (
105
170
  response: info.response,
106
171
  isTransient: false,
107
172
  }))
173
+ .catch((error: SmtpFailure) => {
174
+ const classified = classifySmtpError(error);
175
+ if (classified) {
176
+ throw classified;
177
+ }
178
+
179
+ // 4xx = transient (retry), 5xx = permanent (no retry)
180
+ const smtpCode = error.responseCode;
181
+ const isTransient =
182
+ smtpCode !== undefined && smtpCode >= 400 && smtpCode < 500;
183
+ return {
184
+ success: false,
185
+ error,
186
+ smtpCode,
187
+ isTransient,
188
+ };
189
+ })
190
+ .finally(() => transporter.close());
191
+ };
192
+
193
+ export const verifySmtpConnection = async (
194
+ config: SmtpConfig,
195
+ ): Promise<TestResult> => {
196
+ const transporter = transporterFor(
197
+ {
198
+ ...config,
199
+ connectionTimeout: config.connectionTimeout ?? VERIFY_TIMEOUT_MS,
200
+ },
201
+ VERIFY_TIMEOUT_MS,
202
+ );
203
+
204
+ return transporter
205
+ .verify()
206
+ .then((): TestResult => ({ success: true }))
108
207
  .catch(
109
- (
110
- error: Error & {
111
- responseCode?: number;
112
- code?: string;
113
- command?: string;
114
- response?: string;
115
- },
116
- ) => {
117
- const smtpCode = error.responseCode;
118
-
119
- // Classify auth errors — EAUTH or 5xx on AUTH command
120
- if (
121
- error.code === "EAUTH" ||
122
- (smtpCode !== undefined &&
123
- smtpCode >= 500 &&
124
- error.command === "AUTH")
125
- ) {
126
- // The server's own words, when it gave any: a 535 reading
127
- // "SmtpClientAuthentication is disabled for the Tenant" is not a
128
- // failure signing in again clears, and the account card can only
129
- // say so if the text survives the classification.
130
- throw new SmtpConnectionError(
131
- "auth",
132
- error.response
133
- ? `SMTP authentication failed: ${error.response.trim()}`
134
- : "SMTP authentication failed",
135
- error,
136
- );
137
- }
138
-
139
- // Classify network errors
140
- if (
141
- error.code === "ECONNREFUSED" ||
142
- error.code === "ETIMEDOUT" ||
143
- error.code === "ENOTFOUND" ||
144
- error.code === "ECONNRESET" ||
145
- error.code === "EHOSTUNREACH"
146
- ) {
147
- throw new SmtpConnectionError(
148
- "network",
149
- `SMTP connection failed: ${error.code}`,
150
- error,
151
- );
152
- }
153
-
154
- // 4xx = transient (retry), 5xx = permanent (no retry)
155
- const isTransient =
156
- smtpCode !== undefined && smtpCode >= 400 && smtpCode < 500;
157
- return {
158
- success: false,
159
- error,
160
- smtpCode,
161
- isTransient,
162
- };
163
- },
208
+ (error: SmtpFailure): TestResult => ({
209
+ success: false,
210
+ error: (classifySmtpError(error) ?? error).message,
211
+ }),
164
212
  )
165
213
  .finally(() => transporter.close());
166
214
  };
@@ -0,0 +1,74 @@
1
+ import net from "node:net";
2
+
3
+ export interface FakeSmtpOptions {
4
+ authResponse?: string;
5
+ dataFinalResponse?: string;
6
+ dropAfterGreeting?: boolean;
7
+ }
8
+
9
+ export interface FakeSmtp {
10
+ port: number;
11
+ authCommands: string[];
12
+ received: string[];
13
+ close: () => void;
14
+ }
15
+
16
+ export const startFakeSmtp = (opts: FakeSmtpOptions = {}): Promise<FakeSmtp> =>
17
+ new Promise((resolve) => {
18
+ const authCommands: string[] = [];
19
+ const received: string[] = [];
20
+ const server = net.createServer((socket) => {
21
+ if (opts.dropAfterGreeting) {
22
+ socket.destroy();
23
+ return;
24
+ }
25
+ socket.write("220 fake ESMTP\r\n");
26
+ let inData = false;
27
+ socket.on("data", (buffer) => {
28
+ const line = buffer.toString();
29
+ if (inData) {
30
+ received.push(line);
31
+ if (line.includes("\r\n.\r\n")) {
32
+ inData = false;
33
+ socket.write(opts.dataFinalResponse ?? "250 2.0.0 Ok\r\n");
34
+ }
35
+ return;
36
+ }
37
+ const command = line.slice(0, 4).toUpperCase();
38
+ if (command.startsWith("EHLO") || command.startsWith("HELO")) {
39
+ socket.write("250-fake\r\n250 AUTH PLAIN LOGIN XOAUTH2\r\n");
40
+ return;
41
+ }
42
+ if (command.startsWith("AUTH")) {
43
+ authCommands.push(line.trim());
44
+ socket.write(opts.authResponse ?? "235 2.7.0 Accepted\r\n");
45
+ return;
46
+ }
47
+ if (command.startsWith("MAIL") || command.startsWith("RCPT")) {
48
+ socket.write("250 2.1.0 Ok\r\n");
49
+ return;
50
+ }
51
+ if (command.startsWith("DATA")) {
52
+ socket.write("354 End data\r\n");
53
+ inData = true;
54
+ return;
55
+ }
56
+ if (command.startsWith("QUIT")) {
57
+ socket.write("221 Bye\r\n");
58
+ socket.end();
59
+ return;
60
+ }
61
+ socket.write("250 Ok\r\n");
62
+ });
63
+ });
64
+ server.listen(0, "127.0.0.1", () => {
65
+ const address = server.address();
66
+ const port = typeof address === "object" && address ? address.port : 0;
67
+ resolve({
68
+ port,
69
+ authCommands,
70
+ received,
71
+ close: () => server.close(),
72
+ });
73
+ });
74
+ });