@curlew/smtp 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # @curlew/smtp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send one message, with attachments, over SMTP. A thin, checked layer on
4
+ [nodemailer](https://nodemailer.com) (pinned exactly): no `gi://`, runs on GJS and on Node.
5
+
6
+ **This is a library capability, not a tool.** curlew's index and its MCP server stay read-only
7
+ and fail-closed; nothing in `app/src/frontends/mcp` sends mail, and nothing here registers one.
8
+ The caller sends, and only with the human's explicit consent for that message.
9
+
10
+ ## API
11
+
12
+ ```ts
13
+ import { buildMessage, sendMessage, verifyAccount, SmtpError } from '@curlew/smtp';
14
+
15
+ const account: SmtpAccount = {
16
+ host: 'smtp.example.invalid',
17
+ port: 587,
18
+ security: 'starttls', // 'tls' | 'starttls' | 'none' (127.0.0.1 and localhost only)
19
+ username: 'user@example.invalid',
20
+ auth: { kind: 'password', password } /* or { kind: 'oauth2', accessToken } */,
21
+ tls: { ca: pem }, // optional: trust a private CA; rejectUnauthorized: false switches checking off
22
+ };
23
+
24
+ await verifyAccount(account); // connects and logs in; sends no MAIL FROM
25
+ const raw = await buildMessage(message); // RFC 5322 bytes, no network
26
+ const sent = await sendMessage(account, message); // { messageId, accepted, rejected, response }
27
+ ```
28
+
29
+ `OutgoingMessage` is `{ from, to[], cc?[], subject, text, html?, attachments?, messageId? }`;
30
+ an attachment is `{ filename, content: Uint8Array, contentType? }`. Without a `messageId` one is
31
+ generated on the domain of `from`.
32
+
33
+ - Addresses are plain `local@host`. No display names, no groups, no further validation.
34
+ - A line break or other control character in the subject, an address, a filename, a content
35
+ type or the Message-ID is refused, not stripped (header injection).
36
+ - `sendMessage` returns the recipients the server refused while taking others in `rejected`;
37
+ when it takes none it throws. `MAIL FROM` is sent by `sendMessage` only.
38
+ - Attachments are bytes. File and URL access are off, so a message can never name a path.
39
+
40
+ ## Errors
41
+
42
+ Every failure is an `SmtpError` with a `code`: `auth`, `tls`, `connect`, `rejected` or `config`
43
+ (nothing was sent), and the numeric `responseCode` of a server refusal. The message is fixed text
44
+ plus the server's reply with the account's secrets cut out, and the library error is not kept.
45
+
46
+ ## What it does not do
47
+
48
+ - No MCP tool, no CLI command: sending is not exposed to an agent.
49
+ - No secret in a log, an error text or a result. Credentials are parameters of the call; the
50
+ package reads no file, no environment, no store, and turns the library's loggers off.
51
+ - No `security: 'none'` beyond the loopback, because that sends the password in the clear.
52
+
53
+ ## Tests
54
+
55
+ `app/tests/unit/smtp/`, on GJS and Node: message building and validation, errors without
56
+ secrets, and a plaintext dummy server on 127.0.0.1 (no TLS) that records what the client sent:
57
+ `AUTH PLAIN` / `XOAUTH2` arrived, the attachments are the MIME parts, `verifyAccount` sent no
58
+ `MAIL FROM`.
59
+
60
+ **TLS and STARTTLS are not tested, and have not been run against a real server here.** On GJS they
61
+ need gjsify#2071 (peer verification after the handshake, the socket under a TLS connection),
62
+ which is not released at 0.55.0. Three cases in `send.test.ts` are marked skipped with that
63
+ reference; enable them with the release that carries it. Nothing in this package works around it.
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@curlew/smtp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "type": "module",
6
+ "description": "Sending one message with attachments over SMTP (nodemailer): message building, account validation, verify and send. A library capability only — no MCP tool, no credentials in logs, errors or DTOs. No gi://.",
7
+ "exports": {
8
+ ".": "./src/index.ts"
9
+ },
10
+ "scripts": {
11
+ "check": "tsc --noEmit --project tsconfig.json"
12
+ },
13
+ "files": [
14
+ "src"
15
+ ],
16
+ "dependencies": {
17
+ "nodemailer": "10.0.15"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/JumpLink/curlew.git",
22
+ "directory": "packages/smtp"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ }
27
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * SMTP errors.
3
+ *
4
+ * The message never carries a credential: it is built from fixed text and, for a server refusal,
5
+ * the numeric reply code. Nothing of the underlying library error is kept (no `cause`), because
6
+ * its fields are not ours to vouch for.
7
+ *
8
+ * Note: no TypeScript parameter properties — Node's --experimental-strip-types rejects them.
9
+ */
10
+
11
+ /** What went wrong, coarse enough to branch on. */
12
+ export type SmtpErrorCode =
13
+ /** The server refused the login, or no usable credential was given. */
14
+ | 'auth'
15
+ /** The TLS handshake or the STARTTLS upgrade failed (certificate included). */
16
+ | 'tls'
17
+ /** No connection, a dropped one, a timeout, or a reply that is not SMTP. */
18
+ | 'connect'
19
+ /** The server refused the sender, a recipient, or the message. */
20
+ | 'rejected'
21
+ /** The account or message is invalid; nothing was sent over the network. */
22
+ | 'config';
23
+
24
+ export class SmtpError extends Error {
25
+ readonly name = 'SmtpError';
26
+ readonly code: SmtpErrorCode;
27
+ /** Numeric SMTP reply code of a server refusal, when there was one. */
28
+ readonly responseCode?: number;
29
+
30
+ constructor(code: SmtpErrorCode, message: string, responseCode?: number) {
31
+ super(message);
32
+ this.code = code;
33
+ this.responseCode = responseCode;
34
+ }
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { SmtpError } from './errors.ts';
2
+ export type { SmtpErrorCode } from './errors.ts';
3
+ export { buildMessage } from './message.ts';
4
+ export { sendMessage, verifyAccount } from './transport.ts';
5
+ export type { OutgoingAttachment, OutgoingMessage, SendResult, SmtpAccount } from './types.ts';
6
+ export { validateAccount, validateMessage } from './validate.ts';
package/src/message.ts ADDED
@@ -0,0 +1,51 @@
1
+ import MailComposer from 'nodemailer/lib/mail-composer';
2
+ import type { MailComposerOptions } from 'nodemailer/lib/mail-composer';
3
+
4
+ import type { OutgoingMessage } from './types.ts';
5
+ import { validateMessage } from './validate.ts';
6
+
7
+ function randomId(): string {
8
+ const bytes = new Uint8Array(16);
9
+ globalThis.crypto.getRandomValues(bytes);
10
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
11
+ }
12
+
13
+ /** The message's own id, or a fresh `<random@domain-of-from>`. Validates the message first. */
14
+ export function resolveMessageId(message: OutgoingMessage): string {
15
+ validateMessage(message);
16
+ if (message.messageId) return message.messageId;
17
+ return `<${randomId()}@${message.from.slice(message.from.lastIndexOf('@') + 1)}>`;
18
+ }
19
+
20
+ /**
21
+ * What goes to nodemailer: file and URL access are off, so no attachment can name a path or a
22
+ * URL — content is bytes the caller handed over, nothing else.
23
+ */
24
+ export function composerOptions(message: OutgoingMessage, messageId: string): MailComposerOptions {
25
+ return {
26
+ from: message.from,
27
+ to: message.to,
28
+ cc: message.cc,
29
+ subject: message.subject,
30
+ text: message.text,
31
+ html: message.html,
32
+ messageId,
33
+ attachments: (message.attachments ?? []).map((attachment) => ({
34
+ filename: attachment.filename,
35
+ content: Buffer.from(attachment.content),
36
+ contentType: attachment.contentType,
37
+ })),
38
+ disableFileAccess: true,
39
+ disableUrlAccess: true,
40
+ };
41
+ }
42
+
43
+ /**
44
+ * The RFC 5322 message as bytes, without any network: for a preview, a log of what WOULD go out,
45
+ * or a test. An invalid message throws a `config` SmtpError.
46
+ */
47
+ export async function buildMessage(message: OutgoingMessage): Promise<Uint8Array> {
48
+ const messageId = resolveMessageId(message);
49
+ const raw = await new MailComposer(composerOptions(message, messageId)).compile().build();
50
+ return new Uint8Array(raw);
51
+ }
@@ -0,0 +1,126 @@
1
+ import { createTransport } from 'nodemailer';
2
+ import type { NodemailerError } from 'nodemailer/lib/errors';
3
+ import type SMTPTransport from 'nodemailer/lib/smtp-transport';
4
+
5
+ import { SmtpError } from './errors.ts';
6
+ import type { SmtpErrorCode } from './errors.ts';
7
+ import { composerOptions, resolveMessageId } from './message.ts';
8
+ import type { OutgoingMessage, SendResult, SmtpAccount } from './types.ts';
9
+ import { validateAccount } from './validate.ts';
10
+
11
+ /** A dead server must end as an error, not as a hang. */
12
+ const CONNECTION_TIMEOUT_MS = 15_000;
13
+ const SOCKET_TIMEOUT_MS = 60_000;
14
+
15
+ /** Longest server reply text that goes into an error message. */
16
+ const MAX_REPLY_LENGTH = 200;
17
+
18
+ const BY_LIBRARY_CODE: Record<string, SmtpErrorCode> = {
19
+ EAUTH: 'auth',
20
+ ENOAUTH: 'auth',
21
+ EOAUTH2: 'auth',
22
+ ETLS: 'tls',
23
+ EREQUIRETLS: 'tls',
24
+ EENVELOPE: 'rejected',
25
+ EMESSAGE: 'rejected',
26
+ EMAXRECIPIENTS: 'rejected',
27
+ ECONFIG: 'config',
28
+ };
29
+
30
+ const SUMMARY: Record<SmtpErrorCode, string> = {
31
+ auth: 'SMTP login failed',
32
+ tls: 'SMTP TLS handshake failed',
33
+ connect: 'SMTP connection failed',
34
+ rejected: 'SMTP server rejected the message',
35
+ config: 'SMTP configuration is invalid',
36
+ };
37
+
38
+ function secretsOf(account: SmtpAccount): string[] {
39
+ return account.auth.kind === 'password' ? [account.auth.password] : [account.auth.accessToken];
40
+ }
41
+
42
+ /** The reply text with every form of a secret removed, flattened to one bounded line. */
43
+ function scrub(text: string, secrets: string[]): string {
44
+ let out = text;
45
+ for (const secret of secrets) {
46
+ for (const form of [secret, btoa(secret)]) out = out.split(form).join('[redacted]');
47
+ }
48
+ return out.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, MAX_REPLY_LENGTH);
49
+ }
50
+
51
+ /**
52
+ * What the caller sees of a library error: a code, fixed text, the numeric reply code, and the
53
+ * server's reply text with the account's secrets cut out. The original error is dropped.
54
+ */
55
+ function toSmtpError(err: unknown, account: SmtpAccount): SmtpError {
56
+ const failure = (err ?? {}) as NodemailerError;
57
+ const code = BY_LIBRARY_CODE[failure.code ?? ''] ?? (failure.responseCode === 535 ? 'auth' : 'connect');
58
+ const reply = typeof failure.response === 'string' ? scrub(failure.response, secretsOf(account)) : '';
59
+ const message = reply ? `${SUMMARY[code]}: ${reply}` : SUMMARY[code];
60
+ return new SmtpError(code, message, failure.responseCode);
61
+ }
62
+
63
+ function transportFor(account: SmtpAccount) {
64
+ const options: SMTPTransport.Options = {
65
+ host: account.host,
66
+ port: account.port,
67
+ secure: account.security === 'tls',
68
+ requireTLS: account.security === 'starttls',
69
+ ignoreTLS: account.security === 'none',
70
+ auth:
71
+ account.auth.kind === 'password'
72
+ ? { user: account.username, pass: account.auth.password }
73
+ : { type: 'OAuth2', user: account.username, accessToken: account.auth.accessToken },
74
+ connectionTimeout: CONNECTION_TIMEOUT_MS,
75
+ greetingTimeout: CONNECTION_TIMEOUT_MS,
76
+ socketTimeout: SOCKET_TIMEOUT_MS,
77
+ // The libraries' loggers print whole SMTP dialogues, AUTH lines included.
78
+ logger: false,
79
+ debug: false,
80
+ };
81
+ if (account.tls) {
82
+ options.tls = {};
83
+ if (account.tls.ca !== undefined) options.tls.ca = account.tls.ca;
84
+ if (account.tls.rejectUnauthorized !== undefined) {
85
+ options.tls.rejectUnauthorized = account.tls.rejectUnauthorized;
86
+ }
87
+ }
88
+ return createTransport(options);
89
+ }
90
+
91
+ /**
92
+ * Connects and logs in, then hangs up: no MAIL FROM, nothing is sent. Resolves when the server
93
+ * accepted the credentials; otherwise throws an SmtpError.
94
+ */
95
+ export async function verifyAccount(account: SmtpAccount): Promise<void> {
96
+ validateAccount(account);
97
+ const transport = transportFor(account);
98
+ try {
99
+ await transport.verify();
100
+ } catch (err) {
101
+ throw toSmtpError(err, account);
102
+ } finally {
103
+ transport.close();
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Sends one message. The caller decides whether to; this never asks anyone. `rejected` lists the
109
+ * recipients the server refused while taking the rest — when it took none, that is an
110
+ * SmtpError('rejected').
111
+ */
112
+ export async function sendMessage(account: SmtpAccount, message: OutgoingMessage): Promise<SendResult> {
113
+ validateAccount(account);
114
+ const messageId = resolveMessageId(message);
115
+ const transport = transportFor(account);
116
+ try {
117
+ const info = await transport.sendMail(composerOptions(message, messageId));
118
+ const accepted = info.accepted.map(String);
119
+ if (accepted.length === 0) throw new SmtpError('rejected', SUMMARY.rejected);
120
+ return { messageId, accepted, rejected: info.rejected.map(String), response: scrub(info.response, secretsOf(account)) };
121
+ } catch (err) {
122
+ throw err instanceof SmtpError ? err : toSmtpError(err, account);
123
+ } finally {
124
+ transport.close();
125
+ }
126
+ }
package/src/types.ts ADDED
@@ -0,0 +1,43 @@
1
+ /** Where and how to reach an SMTP server. Credentials are parameters, never read from anywhere. */
2
+ export interface SmtpAccount {
3
+ host: string;
4
+ port: number;
5
+ /** `tls`: TLS from the first byte. `starttls`: upgrade is required. `none`: loopback only. */
6
+ security: 'tls' | 'starttls' | 'none';
7
+ /** Required with either `auth` kind; it is the login name. */
8
+ username: string;
9
+ auth: { kind: 'password'; password: string } | { kind: 'oauth2'; accessToken: string };
10
+ tls?: {
11
+ /** PEM of the certificate authority to trust, e.g. a self-signed server. */
12
+ ca?: string;
13
+ /** `false` switches the certificate check off. Do not. */
14
+ rejectUnauthorized?: boolean;
15
+ };
16
+ }
17
+
18
+ export interface OutgoingAttachment {
19
+ filename: string;
20
+ content: Uint8Array;
21
+ contentType?: string;
22
+ }
23
+
24
+ /** Addresses are plain `local@host`: no display names, no groups. */
25
+ export interface OutgoingMessage {
26
+ from: string;
27
+ to: string[];
28
+ cc?: string[];
29
+ subject: string;
30
+ text: string;
31
+ html?: string;
32
+ attachments?: OutgoingAttachment[];
33
+ /** `<id@host>`. Generated from the domain of `from` when absent. */
34
+ messageId?: string;
35
+ }
36
+
37
+ export interface SendResult {
38
+ messageId: string;
39
+ accepted: string[];
40
+ rejected: string[];
41
+ /** The server's final reply to the message. */
42
+ response: string;
43
+ }
@@ -0,0 +1,96 @@
1
+ import { SmtpError } from './errors.ts';
2
+ import type { OutgoingMessage, SmtpAccount } from './types.ts';
3
+
4
+ /** `none` sends the password in the clear, so it is for a server on this machine only. */
5
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost']);
6
+
7
+ /** CR, LF, NUL and the rest of C0/C1: any of them in a header value is an injection attempt. */
8
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
9
+
10
+ /** Deliberately simple: one `@`, no whitespace, no quoting, no display name. */
11
+ const ADDRESS = /^[^\s@<>()[\]\\,;:"]+@[^\s@<>()[\]\\,;:"]+$/;
12
+
13
+ const MESSAGE_ID = /^<[^\s<>@]+@[^\s<>@]+>$/;
14
+
15
+ function config(message: string): SmtpError {
16
+ return new SmtpError('config', message);
17
+ }
18
+
19
+ function nonEmptyString(value: unknown): value is string {
20
+ return typeof value === 'string' && value.length > 0;
21
+ }
22
+
23
+ /** Throws a `config` error for anything that must not reach the network. */
24
+ export function validateAccount(account: SmtpAccount): void {
25
+ if (!account || typeof account !== 'object') throw config('SMTP account is missing');
26
+ const { host, port, security, username, auth, tls } = account;
27
+
28
+ if (!nonEmptyString(host) || /\s/.test(host) || CONTROL.test(host)) throw config('SMTP host is missing or invalid');
29
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw config('SMTP port must be 1-65535');
30
+ if (security !== 'tls' && security !== 'starttls' && security !== 'none') {
31
+ throw config("SMTP security must be 'tls', 'starttls' or 'none'");
32
+ }
33
+ if (security === 'none' && !LOOPBACK_HOSTS.has(host)) {
34
+ throw config("security 'none' is allowed for 127.0.0.1 and localhost only");
35
+ }
36
+ if (!nonEmptyString(username) || CONTROL.test(username)) throw config('SMTP username is missing or invalid');
37
+
38
+ const credential = auth as Partial<{ kind: string; password: string; accessToken: string }> | undefined;
39
+ if (credential?.kind === 'password') {
40
+ if (!nonEmptyString(credential.password)) throw config('SMTP password is missing');
41
+ } else if (credential?.kind === 'oauth2') {
42
+ if (!nonEmptyString(credential.accessToken)) throw config('SMTP access token is missing');
43
+ } else {
44
+ throw config("SMTP auth must be of kind 'password' or 'oauth2'");
45
+ }
46
+
47
+ if (tls !== undefined) {
48
+ if (tls === null || typeof tls !== 'object') throw config('SMTP tls must be an object');
49
+ if (tls.ca !== undefined && !nonEmptyString(tls.ca)) throw config('SMTP tls.ca must be a PEM string');
50
+ if (tls.rejectUnauthorized !== undefined && typeof tls.rejectUnauthorized !== 'boolean') {
51
+ throw config('SMTP tls.rejectUnauthorized must be a boolean');
52
+ }
53
+ }
54
+ }
55
+
56
+ function validateAddress(address: unknown, what: string): void {
57
+ if (!nonEmptyString(address) || CONTROL.test(address) || !ADDRESS.test(address)) {
58
+ throw config(`${what} is not a plain address (local@host)`);
59
+ }
60
+ }
61
+
62
+ /** Throws a `config` error. Header values are checked for line breaks, not rewritten. */
63
+ export function validateMessage(message: OutgoingMessage): void {
64
+ if (!message || typeof message !== 'object') throw config('message is missing');
65
+
66
+ validateAddress(message.from, 'from');
67
+ if (!Array.isArray(message.to) || message.to.length === 0) throw config('to needs at least one recipient');
68
+ for (const address of message.to) validateAddress(address, 'to');
69
+ if (message.cc !== undefined) {
70
+ if (!Array.isArray(message.cc)) throw config('cc must be a list');
71
+ for (const address of message.cc) validateAddress(address, 'cc');
72
+ }
73
+
74
+ if (typeof message.subject !== 'string' || CONTROL.test(message.subject)) {
75
+ throw config('subject is missing or contains a line break or control character');
76
+ }
77
+ if (typeof message.text !== 'string') throw config('text is missing');
78
+ if (message.html !== undefined && typeof message.html !== 'string') throw config('html must be a string');
79
+
80
+ if (message.messageId !== undefined && !MESSAGE_ID.test(message.messageId)) {
81
+ throw config('messageId must look like <id@host>');
82
+ }
83
+
84
+ for (const attachment of message.attachments ?? []) {
85
+ if (!nonEmptyString(attachment?.filename) || CONTROL.test(attachment.filename)) {
86
+ throw config('attachment filename is missing or contains a control character');
87
+ }
88
+ if (!(attachment.content instanceof Uint8Array)) throw config('attachment content must be a Uint8Array');
89
+ if (
90
+ attachment.contentType !== undefined &&
91
+ (!nonEmptyString(attachment.contentType) || CONTROL.test(attachment.contentType))
92
+ ) {
93
+ throw config('attachment contentType is invalid');
94
+ }
95
+ }
96
+ }