@tsdmarc/smtp 0.0.0-stage → 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @tsdmarc/smtp
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - a1c5fad: First release: a 1:1 TypeScript port of parsedmarc 11.2.1 and of the parts of mailsuite 2.3.4 it uses, for Node.js 24+, Bun and Deno.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [a1c5fad]
12
+ - tsdmarc@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,61 @@
1
+ tsdmarc
2
+ Copyright 2026 tsdmarc contributors
3
+
4
+ This product is a TypeScript port of parsedmarc
5
+ (https://github.com/domainaware/parsedmarc), Copyright Sean Whalen and
6
+ parsedmarc contributors, licensed under the Apache License, Version 2.0.
7
+ Ported from parsedmarc 11.2.1, commit 7bbc405c01a1c4c37811b2a3746e8881c00cda39.
8
+
9
+ The mailbox connection and SMTP code is a port of mailsuite
10
+ (https://github.com/seanthegeek/mailsuite), Copyright Sean Whalen,
11
+ licensed under the Apache License, Version 2.0.
12
+ Ported from mailsuite 2.3.4, commit 3bd62831d137c9aa7884be33b83323ca3a1bd1de.
13
+
14
+ All source files were translated from Python to TypeScript; this is a
15
+ modification of the original works within the meaning of section 4(b) of
16
+ the Apache License.
17
+
18
+ Third-party data files in resources/:
19
+ - ipinfo_lite.mmdb: IPinfo Lite, (c) IPinfo (https://ipinfo.io/lite),
20
+ licensed under CC BY-SA 4.0.
21
+ - base_reverse_dns_map.csv: from parsedmarc, derived in part from IPinfo
22
+ Lite data, licensed under CC BY-SA 4.0.
23
+
24
+ Ported third-party code in packages/tsdmarc/src (behavior reimplemented in
25
+ TypeScript to reproduce parsedmarc's output exactly):
26
+ - xml/expat.ts, xml/expat-names.ts: port of parts of Expat 2.9.0
27
+ (https://libexpat.github.io/), Copyright (c) 1997-2000 Thai Open Source
28
+ Software Center Ltd and Copyright (c) 2000-2026 Expat development team,
29
+ licensed under the MIT License.
30
+ - xml/xmltodict.ts: port of xmltodict (https://github.com/martinblech/xmltodict),
31
+ Copyright (c) 2012 Martin Blech, licensed under the MIT License.
32
+ - xml/recover.ts: emulates the observable recovery behavior of libxml2
33
+ (https://gitlab.gnome.org/GNOME/libxml2), MIT License.
34
+ - utils/py-email/, utils/py-codecs*.ts, utils/py-binascii.ts, utils/py-str.ts,
35
+ csv.ts, utils/csv-reader.ts, utils/url-split.ts: ports of parts of the
36
+ CPython standard library (https://github.com/python/cpython), Copyright (c)
37
+ 2001 Python Software Foundation, licensed under the PSF License Agreement.
38
+ - utils/mailparser/: port of mail-parser 4.8.0
39
+ (https://github.com/SpamScope/mail-parser), Copyright Fedele Mantuano,
40
+ licensed under the Apache License, Version 2.0.
41
+ - utils/dns*.ts: port of parts of dnspython (https://www.dnspython.org/),
42
+ Copyright (c) Dnspython Contributors, licensed under the ISC License.
43
+ - utils/timestamps.ts: date parsing compatible with python-dateutil
44
+ (https://github.com/dateutil/dateutil), Apache License 2.0 / BSD 3-Clause.
45
+ - internal/zipfile.ts and the decompressor wrappers in internal/bz2.ts,
46
+ internal/lzma.ts, internal/zstd.ts and internal/zlib.ts: ports of parts of
47
+ the CPython standard library (zipfile, bz2, lzma, compression.zstd, zlib
48
+ modules), Copyright (c) 2001 Python Software Foundation, licensed under the
49
+ PSF License Agreement.
50
+ - internal/zlib.ts: port of the inflate code of zlib 1.3 (https://zlib.net/),
51
+ Copyright (C) 1995-2023 Jean-loup Gailly and Mark Adler, licensed under the
52
+ zlib License.
53
+ - internal/bz2.ts: port of the libbzip2 1.0.8 decompressor
54
+ (https://sourceware.org/bzip2/), Copyright (C) 1996-2019 Julian R Seward,
55
+ licensed under the bzip2 license (BSD-style).
56
+ - internal/lzma.ts: port of the LZMA1 decoder of liblzma 5.8
57
+ (https://tukaani.org/xz/), by Igor Pavlov and Lasse Collin, licensed under
58
+ the BSD Zero Clause License (0BSD).
59
+ - internal/zstd.ts: port of the libzstd 1.5.7 decoder
60
+ (https://github.com/facebook/zstd), Copyright (c) Meta Platforms, Inc. and
61
+ affiliates, licensed under the BSD 3-Clause License.
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # @tsdmarc/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 [tsdmarc](https://github.com/helixnebulatech/tsdmarc#readme) results by email over SMTP, built on [nodemailer](https://nodemailer.com). Port of `mailsuite.smtp.send_email` and parsedmarc's `email_results()`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install tsdmarc @tsdmarc/smtp
9
+ ```
10
+
11
+ `tsdmarc` is a peer dependency. With pnpm or Bun: `pnpm add tsdmarc @tsdmarc/smtp` / `bun add tsdmarc @tsdmarc/smtp`. Requires Node 24 or later (Bun and Deno also work).
12
+
13
+ ## Usage
14
+
15
+ Email parsing results as a zip file (the same JSON and CSV files that `saveOutput()` writes):
16
+
17
+ ```ts
18
+ import { emailResults } from '@tsdmarc/smtp';
19
+ import { getDmarcReportsFromMailbox, getReportZip } from 'tsdmarc';
20
+
21
+ const results = await getDmarcReportsFromMailbox(connection, {
22
+ reportsFolder: 'INBOX',
23
+ });
24
+
25
+ await emailResults(
26
+ results,
27
+ 'smtp.example.com', // host
28
+ 'dmarc@example.com', // from
29
+ ['dmarc-team@example.com'], // to
30
+ {
31
+ reportZip: getReportZip,
32
+ port: 587,
33
+ username: 'dmarc@example.com',
34
+ password: process.env.SMTP_PASSWORD,
35
+ },
36
+ );
37
+ ```
38
+
39
+ `connection` is any mailbox connection, for example from [`@tsdmarc/imap`](https://www.npmjs.com/package/@tsdmarc/imap). Any `ParsingResults` object works.
40
+
41
+ Send an arbitrary message:
42
+
43
+ ```ts
44
+ import { readFile } from 'node:fs/promises';
45
+
46
+ import { sendEmail } from '@tsdmarc/smtp';
47
+
48
+ await sendEmail('smtp.example.com', 'dmarc@example.com', {
49
+ messageTo: ['dmarc-team@example.com'],
50
+ requireEncryption: true, // SMTPS on port 465
51
+ username: 'dmarc@example.com',
52
+ password: process.env.SMTP_PASSWORD,
53
+ subject: 'Weekly DMARC summary',
54
+ plainMessage: 'See the attachment.',
55
+ attachments: [['summary.csv', await readFile('summary.csv')]],
56
+ });
57
+ ```
58
+
59
+ ## Options
60
+
61
+ `emailResults(results, host, mailFrom, mailTo, options)`. `EmailResultsOptions`:
62
+
63
+ | Option | Type | Default | Description |
64
+ | --- | --- | --- | --- |
65
+ | `reportZip` | `Uint8Array \| (results) => Uint8Array \| Promise<Uint8Array>` | required | The zip attachment, or how to build it. Pass the core's `getReportZip`. |
66
+ | `subject` | `string \| null` | `DMARC results for YYYY-MM-DD` | Subject. |
67
+ | `message` | `string \| null` | `DMARC results for YYYY-MM-DD` | Plain text body. |
68
+ | `attachmentFilename` | `string \| null` | `DMARC-YYYY-MM-DD.zip` | Attachment filename. `.zip` is appended if missing. |
69
+ | `mailCc` | `string[] \| null` | `null` | Cc addresses. |
70
+ | `mailBcc` | `string[] \| null` | `null` | Bcc addresses. |
71
+ | `port` | `number` | `0` | `0` means 465 with `requireEncryption`, else 25. |
72
+ | `requireEncryption` | `boolean` | `false` | Use TLS from the start (SMTPS). Otherwise the connection starts in plain text and `starttls` decides whether it is upgraded. |
73
+ | `verify` | `boolean` | `true` | Verify the server's TLS certificate. |
74
+ | `starttls` | `boolean \| null` | `null` | Without `requireEncryption`: `null` upgrades when the server advertises STARTTLS and refuses to send credentials otherwise, `true` requires the upgrade, `false` never upgrades (credentials are sent in plain text, with a warning). |
75
+ | `username` | `string \| null` | `null` | SMTP username. |
76
+ | `password` | `string \| null` | `null` | SMTP password. |
77
+
78
+ `sendEmail(host, messageFrom, options)`. `SendEmailOptions`:
79
+
80
+ | Option | Type | Default | Description |
81
+ | --- | --- | --- | --- |
82
+ | `messageTo` | `string[] \| null` | required | Recipients. A missing value throws `TypeError`. |
83
+ | `messageCc` | `string[] \| null` | `null` | Cc addresses. |
84
+ | `messageBcc` | `string[] \| null` | `null` | Bcc addresses (SMTP envelope only, never in the headers). |
85
+ | `port` | `number` | `0` | `0` means 465 with `requireEncryption`, else 25, like smtplib. |
86
+ | `requireEncryption` | `boolean` | `false` | Use TLS from the start (SMTPS). |
87
+ | `starttls` | `boolean \| null` | `null` | As in `EmailResultsOptions`. |
88
+ | `verify` | `boolean` | `true` | Verify the server's TLS certificate. |
89
+ | `username` | `string \| null` | `null` | SMTP username. Credentials are sent only when both `username` and `password` are set. |
90
+ | `password` | `string \| null` | `null` | SMTP password. |
91
+ | `subject` | `string \| null` | `null` | Subject. |
92
+ | `plainMessage` | `string \| null` | `null` | Plain text body. |
93
+ | `attachments` | `[filename, Uint8Array][] \| null` | `null` | Attached as `application/octet-stream`. |
94
+
95
+ `EmailResultsOptions` also takes `starttls`, like parsedmarc 11.2.1's `email_results()`.
96
+
97
+ Connection and protocol failures throw `SMTPError`.
98
+
99
+ ## Notes
100
+
101
+ - **No credentials over plain text** (mailsuite 2.3.4, GHSA-2x4j-7g3q-wr6f). `starttls` is ignored with `requireEncryption`:
102
+ - `null` (default) upgrades when STARTTLS is advertised. When it is not, a username and password make it throw `SMTPError("The SMTP server does not advertise STARTTLS, so credentials would be sent in plain text. ...")` before `AUTH`; without credentials the mail is sent in plain text with a warning.
103
+ - `true` requires the upgrade and throws `SMTPError("STARTTLS required but not supported by the server")`.
104
+ - `false` never upgrades: credentials and mail are sent in plain text, with the warning `Sending SMTP credentials unencrypted because starttls=False` when there are credentials. Only for local or otherwise trusted servers.
105
+ - **CLI:** the `[smtp]` section of [`@tsdmarc/cli`](https://www.npmjs.com/package/@tsdmarc/cli) configures `emailResults()`. Its `starttls` key (or `TSDMARC_SMTP_STARTTLS`), as in parsedmarc 11.2.1, is passed as `starttls`; with `starttls = False` and `ssl = False` a warning is logged at startup.
106
+
107
+ All deliberate differences from parsedmarc are listed in [Differences from parsedmarc](https://github.com/helixnebulatech/tsdmarc/blob/main/architecture/README.md#differences-from-parsedmarc).
108
+
109
+ ---
110
+
111
+ Part of [tsdmarc](https://github.com/helixnebulatech/tsdmarc#readme), a TypeScript port of [parsedmarc](https://github.com/domainaware/parsedmarc). Licensed under Apache-2.0.
112
+
113
+ Created by [HelixNebula](https://helixnebula.tech).
@@ -0,0 +1,121 @@
1
+ import { ParsingResults } from "tsdmarc";
2
+ /**
3
+ * The zip attachment: its bytes, or a function that builds them from the
4
+ * results. Pass the core's `getReportZip` (parsedmarc's `get_report_zip()`).
5
+ */
6
+ type ReportZip = Uint8Array | ((results: ParsingResults) => Promise<Uint8Array> | Uint8Array);
7
+ interface ReportEmailContentOptions {
8
+ /** Overrides the default subject (`DMARC results for YYYY-MM-DD`). */
9
+ subject?: string | null;
10
+ /** Overrides the default attachment filename; `.zip` is appended if missing. */
11
+ attachmentFilename?: string | null;
12
+ /** Overrides the default plain text body. */
13
+ message?: string | null;
14
+ /** The zip attachment, or how to build it. */
15
+ reportZip: ReportZip;
16
+ }
17
+ interface ReportEmailContent {
18
+ subject: string;
19
+ message: string;
20
+ attachments: [string, Uint8Array][];
21
+ }
22
+ interface EmailResultsOptions extends ReportEmailContentOptions {
23
+ mailCc?: string[] | null;
24
+ mailBcc?: string[] | null;
25
+ /** 0 (default): 465 with `requireEncryption`, else 25. */
26
+ port?: number;
27
+ /**
28
+ * Connect with implicit SSL/TLS from the start (usually port 465). When
29
+ * false, the connection starts in plain text and `starttls` decides
30
+ * whether it is upgraded.
31
+ */
32
+ requireEncryption?: boolean;
33
+ /**
34
+ * Whether to upgrade a plain-text (`requireEncryption: false`) connection
35
+ * with STARTTLS (parsedmarc 11.2.1). `null`/`undefined` (default)
36
+ * upgrades when the server advertises STARTTLS; when it does not,
37
+ * `SMTPError` is thrown before authenticating if `username` and
38
+ * `password` are given, and without credentials the message is sent in
39
+ * plain text with a warning. `true` requires the upgrade. `false` never
40
+ * upgrades, so any credentials and the message are sent in plain text (a
41
+ * warning is logged when credentials are sent). Ignored with
42
+ * `requireEncryption`. See `SendEmailOptions.starttls`.
43
+ */
44
+ starttls?: boolean | null;
45
+ /** Verify the TLS certificate. Default: true. */
46
+ verify?: boolean;
47
+ username?: string | null;
48
+ password?: string | null;
49
+ }
50
+ /**
51
+ * Build the subject, plain text body and zip attachment shared by every
52
+ * report-summary email transport (SMTP here, Microsoft Graph in
53
+ * `@tsdmarc/msgraph`).
54
+ */
55
+ export declare function buildReportEmailContent(results: ParsingResults, options: ReportEmailContentOptions): Promise<ReportEmailContent>;
56
+ /**
57
+ * Email parsing results as a zip file.
58
+ *
59
+ * `options.reportZip` provides the attachment: pass the core's
60
+ * `getReportZip` (or bytes already built). parsedmarc calls
61
+ * `get_report_zip()` itself; taking it as an argument keeps this package
62
+ * independent of the output module.
63
+ */
64
+ export declare function emailResults(results: ParsingResults, host: string, mailFrom: string, mailTo: string[] | null, options: EmailResultsOptions): Promise<void>;
65
+ /** Raised when a SMTP error occurs. */
66
+ export declare class SMTPError extends Error {
67
+ override name: string;
68
+ }
69
+ interface SendEmailOptions {
70
+ /** Addresses to send mail to. Required (mailsuite raises when it is missing). */
71
+ messageTo?: string[] | null;
72
+ /** Addresses to Carbon Copy. */
73
+ messageCc?: string[] | null;
74
+ /** Addresses to Blind Carbon Copy (envelope only, never in the headers). */
75
+ messageBcc?: string[] | null;
76
+ /** Port. 0 (the default) means 465 with `requireEncryption`, else 25, like smtplib. */
77
+ port?: number;
78
+ /**
79
+ * Use TLS from the start (SMTPS). Otherwise the connection starts in
80
+ * plain text and `starttls` decides whether it is upgraded.
81
+ */
82
+ requireEncryption?: boolean;
83
+ /**
84
+ * Whether to upgrade a plain-text (`requireEncryption: false`) connection
85
+ * with STARTTLS (mailsuite 2.3.4). `null`/`undefined` (default) upgrades
86
+ * when the server advertises STARTTLS. When it does not, it throws
87
+ * `SMTPError` before authenticating if credentials (`username` and
88
+ * `password`) were given, so they are never sent in plain text; without
89
+ * credentials the message is sent in plain text and a warning is logged.
90
+ * `false` never upgrades, so the connection stays plain text even when
91
+ * STARTTLS is advertised, and any credentials are sent unencrypted (a
92
+ * warning is logged when they are). `true` requires the upgrade and
93
+ * throws `SMTPError("STARTTLS required but not supported by the server")`
94
+ * if the server does not advertise STARTTLS. Ignored with
95
+ * `requireEncryption`, because the connection is already TLS.
96
+ */
97
+ starttls?: boolean | null;
98
+ /** Verify the server's TLS certificate. Default: true. */
99
+ verify?: boolean;
100
+ username?: string | null;
101
+ password?: string | null;
102
+ subject?: string | null;
103
+ /** `[filename, content]` pairs, attached as `application/octet-stream`. */
104
+ attachments?: [string, Uint8Array][] | null;
105
+ /** The plain text body. */
106
+ plainMessage?: string | null;
107
+ }
108
+ /**
109
+ * Send an email using a SMTP relay.
110
+ *
111
+ * Without `requireEncryption` the connection starts in plain text and is
112
+ * upgraded with STARTTLS when the server offers it (see `starttls` to never
113
+ * or always upgrade). When it is not offered, credentials are refused with
114
+ * `SMTPError` before they are sent, and a message without credentials goes
115
+ * out unencrypted with a warning, as with mailsuite. Every
116
+ * recipient (To, Cc and Bcc) is in the SMTP envelope; Bcc is never in the
117
+ * headers. Connection and protocol failures raise `SMTPError`.
118
+ */
119
+ export declare function sendEmail(host: string, messageFrom: string, options?: SendEmailOptions): Promise<void>;
120
+ export type { EmailResultsOptions, ReportEmailContent, ReportEmailContentOptions, ReportZip, SendEmailOptions };
121
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,211 @@
1
+ import { AssertionError } from "node:assert";
2
+ import { createEmail, logger } from "tsdmarc";
3
+ import addressparser from "nodemailer/lib/addressparser";
4
+ import SMTPConnection from "nodemailer/lib/smtp-connection";
5
+ // src/send-email.ts
6
+ /** Raised when a SMTP error occurs. */
7
+ var SMTPError = class extends Error {
8
+ name = "SMTPError";
9
+ };
10
+ const SMTP_PORT = 25;
11
+ const SMTPS_PORT = 465;
12
+ const PLAINTEXT_REFUSAL = "The SMTP server does not advertise STARTTLS, so credentials would be sent in plain text. Use require_encryption=True for implicit TLS, or pass starttls=False to allow plain-text authentication";
13
+ /**
14
+ * Build the message with the core's port of mailsuite's `create_email()`,
15
+ * with CRLF line endings as smtplib's `sendmail()` sends it.
16
+ */
17
+ function buildMessage(messageFrom, options) {
18
+ return createEmail({
19
+ attachments: options.attachments ?? null,
20
+ messageCc: options.messageCc ?? null,
21
+ messageFrom,
22
+ messageTo: options.messageTo ?? null,
23
+ plainMessage: options.plainMessage ?? null,
24
+ subject: options.subject ?? null
25
+ }).replaceAll(/\r?\n/gu, "\r\n");
26
+ }
27
+ /** smtplib's `quoteaddr()`: the bare address of `Name <user@host>`. */
28
+ function envelopeAddress(address) {
29
+ const [parsed] = addressparser(address, { flatten: true });
30
+ return parsed?.address || address;
31
+ }
32
+ const DNS_CODES = /* @__PURE__ */ new Set([
33
+ "EAI_AGAIN",
34
+ "EAI_FAIL",
35
+ "EAI_NONAME",
36
+ "EDNS",
37
+ "ENOTFOUND"
38
+ ]);
39
+ const CERTIFICATE_CODE = /^(?:CERT_|ERR_TLS_CERT|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|UNABLE_TO_(?:GET_ISSUER_CERT|VERIFY_LEAF_SIGNATURE)|HOSTNAME_MISMATCH)/u;
40
+ const CERTIFICATE_MESSAGE = /certificate|self[- ]signed/iu;
41
+ /** mailsuite's `str(error).lstrip("b'").rstrip("'").rstrip(".")`. */
42
+ function stripErrorText(text) {
43
+ return text.replace(/^[b']+/u, "").replace(/'+$/u, "").replace(/\.+$/u, "");
44
+ }
45
+ /**
46
+ * Translate a nodemailer/socket error into mailsuite's `SMTPError`
47
+ * messages. Errors that don't come from the connection (no `code`) are
48
+ * returned unchanged, as Python lets non-SMTP exceptions propagate.
49
+ */
50
+ function toSMTPError(error) {
51
+ if (!(error instanceof Error) || error instanceof SMTPError) return error;
52
+ const fields = error;
53
+ const code = typeof fields.code === "string" ? fields.code : "";
54
+ const originalCode = typeof fields.originalCode === "string" ? fields.originalCode : code;
55
+ if (code === "") return error;
56
+ const options = { cause: error };
57
+ if (DNS_CODES.has(originalCode) || code === "EDNS") return new SMTPError("DNS resolution failed", options);
58
+ if (originalCode === "ECONNREFUSED") return new SMTPError("Connection refused", options);
59
+ if (originalCode === "ECONNRESET") return new SMTPError("Connection reset", options);
60
+ if (originalCode === "ECONNABORTED") return new SMTPError("Connection aborted", options);
61
+ if (originalCode === "ETIMEDOUT" || code === "ETIMEDOUT") return new SMTPError("Connection timed out", options);
62
+ if (CERTIFICATE_CODE.test(originalCode) || code === "ETLS" && CERTIFICATE_MESSAGE.test(error.message)) return new SMTPError(`Certificate error: ${error.message}`, options);
63
+ if (code === "ETLS" || originalCode.startsWith("ERR_SSL_")) return new SMTPError(`SSL error: ${error.message}`, options);
64
+ return new SMTPError(stripErrorText(error.message), options);
65
+ }
66
+ /**
67
+ * Whether the server's (plain-text) EHLO reply advertised STARTTLS. With
68
+ * `ignoreTLS`, nodemailer keeps that reply in `_ehloLines` (it has no public
69
+ * accessor); without it, the answer is false.
70
+ */
71
+ function advertisesStartTls(connection) {
72
+ const lines = connection._ehloLines;
73
+ return Array.isArray(lines) && lines.some((line) => typeof line === "string" && /^STARTTLS\b/iu.test(line.trim()));
74
+ }
75
+ /** Run one callback-style SMTPConnection step, failing on an 'error' event too. */
76
+ function step(connection, start) {
77
+ return new Promise((resolve, reject) => {
78
+ const onError = (error) => reject(error);
79
+ connection.once("error", onError);
80
+ start((error, value) => {
81
+ connection.removeListener("error", onError);
82
+ if (error) reject(error);
83
+ else resolve(value);
84
+ });
85
+ });
86
+ }
87
+ /**
88
+ * Send an email using a SMTP relay.
89
+ *
90
+ * Without `requireEncryption` the connection starts in plain text and is
91
+ * upgraded with STARTTLS when the server offers it (see `starttls` to never
92
+ * or always upgrade). When it is not offered, credentials are refused with
93
+ * `SMTPError` before they are sent, and a message without credentials goes
94
+ * out unencrypted with a warning, as with mailsuite. Every
95
+ * recipient (To, Cc and Bcc) is in the SMTP envelope; Bcc is never in the
96
+ * headers. Connection and protocol failures raise `SMTPError`.
97
+ */
98
+ async function sendEmail(host, messageFrom, options = {}) {
99
+ const message = buildMessage(messageFrom, options);
100
+ const requireEncryption = options.requireEncryption ?? false;
101
+ const starttls = requireEncryption ? null : options.starttls ?? null;
102
+ const { username, password } = options;
103
+ const auth = username && password ? {
104
+ user: username,
105
+ pass: password
106
+ } : null;
107
+ let connection = null;
108
+ try {
109
+ connection = new SMTPConnection({
110
+ host,
111
+ port: options.port || (requireEncryption ? SMTPS_PORT : SMTP_PORT),
112
+ secure: requireEncryption,
113
+ ...starttls === false ? { ignoreTLS: true } : {},
114
+ tls: options.verify === false ? { rejectUnauthorized: false } : {},
115
+ logger: false
116
+ });
117
+ connection.on("error", () => void 0);
118
+ const active = connection;
119
+ await step(active, (done) => active.connect((error) => done(error)));
120
+ if (!(requireEncryption || active.secure)) {
121
+ if (starttls === false) {
122
+ if (advertisesStartTls(active)) logger.info("SMTP server supports STARTTLS, but it is disabled ... staying in plain text");
123
+ if (auth !== null) logger.warning("Sending SMTP credentials unencrypted because starttls=False");
124
+ } else if (starttls === true) throw new SMTPError("STARTTLS required but not supported by the server");
125
+ else if (auth === null) logger.warning("SMTP server does not support STARTTLS. Proceeding in plain text!");
126
+ else throw new SMTPError(PLAINTEXT_REFUSAL);
127
+ }
128
+ if (auth !== null) await step(active, (done) => active.login(auth, done));
129
+ const messageTo = options.messageTo ?? null;
130
+ if (messageTo === null) throw new TypeError("message_to cannot be None");
131
+ const envelopeTo = [.../* @__PURE__ */ new Set([
132
+ ...messageTo,
133
+ ...options.messageCc ?? [],
134
+ ...options.messageBcc ?? []
135
+ ])].map(envelopeAddress);
136
+ const envelope = {
137
+ from: envelopeAddress(messageFrom),
138
+ to: envelopeTo
139
+ };
140
+ await step(active, (done) => active.send(envelope, message, done));
141
+ } catch (error) {
142
+ throw toSMTPError(error);
143
+ } finally {
144
+ connection?.quit();
145
+ }
146
+ }
147
+ // src/email-results.ts
148
+ function pad(value) {
149
+ return String(value).padStart(2, "0");
150
+ }
151
+ /** `datetime.now().strftime("%Y-%m-%d")`: today's local date. */
152
+ function localDateString(now = /* @__PURE__ */ new Date()) {
153
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
154
+ }
155
+ /**
156
+ * Build the subject, plain text body and zip attachment shared by every
157
+ * report-summary email transport (SMTP here, Microsoft Graph in
158
+ * `@tsdmarc/msgraph`).
159
+ */
160
+ async function buildReportEmailContent(results, options) {
161
+ const dateString = localDateString();
162
+ let filename;
163
+ if (options.attachmentFilename) {
164
+ filename = options.attachmentFilename;
165
+ if (!filename.toLowerCase().endsWith(".zip")) filename += ".zip";
166
+ } else filename = `DMARC-${dateString}.zip`;
167
+ const subject = options.subject ?? `DMARC results for ${dateString}`;
168
+ const message = options.message ?? `DMARC results for ${dateString}`;
169
+ const { reportZip } = options;
170
+ const zipBytes = typeof reportZip === "function" ? await reportZip(results) : reportZip;
171
+ return {
172
+ subject,
173
+ message,
174
+ attachments: [[filename, zipBytes]]
175
+ };
176
+ }
177
+ /**
178
+ * Email parsing results as a zip file.
179
+ *
180
+ * `options.reportZip` provides the attachment: pass the core's
181
+ * `getReportZip` (or bytes already built). parsedmarc calls
182
+ * `get_report_zip()` itself; taking it as an argument keeps this package
183
+ * independent of the output module.
184
+ */
185
+ async function emailResults(results, host, mailFrom, mailTo, options) {
186
+ logger.debug("Emailing report");
187
+ if (!Array.isArray(mailTo)) throw new AssertionError({
188
+ message: "mail_to must be a list",
189
+ actual: mailTo,
190
+ expected: "an array",
191
+ operator: "Array.isArray"
192
+ });
193
+ const { subject, message, attachments } = await buildReportEmailContent(results, options);
194
+ await sendEmail(host, mailFrom, {
195
+ messageTo: mailTo,
196
+ messageCc: options.mailCc ?? null,
197
+ messageBcc: options.mailBcc ?? null,
198
+ port: options.port ?? 0,
199
+ requireEncryption: options.requireEncryption ?? false,
200
+ verify: options.verify ?? true,
201
+ username: options.username ?? null,
202
+ password: options.password ?? null,
203
+ subject,
204
+ attachments,
205
+ plainMessage: message,
206
+ starttls: options.starttls ?? null
207
+ });
208
+ }
209
+ export { SMTPError, buildReportEmailContent, emailResults, sendEmail };
210
+
211
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/send-email.ts","../src/email-results.ts"],"sourcesContent":["// Send an email over SMTP, ported from mailsuite.smtp.send_email.\n//\n// Only the arguments parsedmarc passes are ported (see `email_results()`):\n// DKIM signing, OAuth2, `envelope_from`, custom headers and HTML bodies are\n// mailsuite features parsedmarc never uses. The message is built with\n// the core's createEmail() and sent with nodemailer's SMTPConnection, which gives\n// the same control smtplib does: implicit TLS or opportunistic STARTTLS,\n// optional login, and an explicit envelope.\n\nimport addressparser from 'nodemailer/lib/addressparser';\nimport SMTPConnection from 'nodemailer/lib/smtp-connection';\nimport { createEmail, logger } from 'tsdmarc';\n\n/** Raised when a SMTP error occurs. */\nexport class SMTPError extends Error {\n override name = 'SMTPError';\n}\n\nexport interface SendEmailOptions {\n /** Addresses to send mail to. Required (mailsuite raises when it is missing). */\n messageTo?: string[] | null;\n /** Addresses to Carbon Copy. */\n messageCc?: string[] | null;\n /** Addresses to Blind Carbon Copy (envelope only, never in the headers). */\n messageBcc?: string[] | null;\n /** Port. 0 (the default) means 465 with `requireEncryption`, else 25, like smtplib. */\n port?: number;\n /**\n * Use TLS from the start (SMTPS). Otherwise the connection starts in\n * plain text and `starttls` decides whether it is upgraded.\n */\n requireEncryption?: boolean;\n /**\n * Whether to upgrade a plain-text (`requireEncryption: false`) connection\n * with STARTTLS (mailsuite 2.3.4). `null`/`undefined` (default) upgrades\n * when the server advertises STARTTLS. When it does not, it throws\n * `SMTPError` before authenticating if credentials (`username` and\n * `password`) were given, so they are never sent in plain text; without\n * credentials the message is sent in plain text and a warning is logged.\n * `false` never upgrades, so the connection stays plain text even when\n * STARTTLS is advertised, and any credentials are sent unencrypted (a\n * warning is logged when they are). `true` requires the upgrade and\n * throws `SMTPError(\"STARTTLS required but not supported by the server\")`\n * if the server does not advertise STARTTLS. Ignored with\n * `requireEncryption`, because the connection is already TLS.\n */\n starttls?: boolean | null;\n /** Verify the server's TLS certificate. Default: true. */\n verify?: boolean;\n username?: string | null;\n password?: string | null;\n subject?: string | null;\n /** `[filename, content]` pairs, attached as `application/octet-stream`. */\n attachments?: [string, Uint8Array][] | null;\n /** The plain text body. */\n plainMessage?: string | null;\n}\n\nconst SMTP_PORT = 25;\nconst SMTPS_PORT = 465;\nconst PLAINTEXT_REFUSAL =\n 'The SMTP server does not advertise STARTTLS, so credentials would be sent in plain text. Use require_encryption=True for implicit TLS, or pass starttls=False to allow plain-text authentication';\n\n/**\n * Build the message with the core's port of mailsuite's `create_email()`,\n * with CRLF line endings as smtplib's `sendmail()` sends it.\n */\nfunction buildMessage(messageFrom: string, options: SendEmailOptions): string {\n return createEmail({\n attachments: options.attachments ?? null,\n messageCc: options.messageCc ?? null,\n messageFrom,\n messageTo: options.messageTo ?? null,\n plainMessage: options.plainMessage ?? null,\n subject: options.subject ?? null,\n }).replaceAll(/\\r?\\n/gu, '\\r\\n');\n}\n\n/** smtplib's `quoteaddr()`: the bare address of `Name <user@host>`. */\nfunction envelopeAddress(address: string): string {\n const [parsed] = addressparser(address, { flatten: true });\n return parsed?.address || address;\n}\n\ninterface NodemailerErrorFields {\n code?: unknown;\n originalCode?: unknown;\n}\n\nconst DNS_CODES: ReadonlySet<string> = new Set([\n 'EAI_AGAIN',\n 'EAI_FAIL',\n 'EAI_NONAME',\n 'EDNS',\n 'ENOTFOUND',\n]);\nconst CERTIFICATE_CODE =\n /^(?:CERT_|ERR_TLS_CERT|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|UNABLE_TO_(?:GET_ISSUER_CERT|VERIFY_LEAF_SIGNATURE)|HOSTNAME_MISMATCH)/u;\nconst CERTIFICATE_MESSAGE = /certificate|self[- ]signed/iu;\n\n/** mailsuite's `str(error).lstrip(\"b'\").rstrip(\"'\").rstrip(\".\")`. */\nfunction stripErrorText(text: string): string {\n return text\n .replace(/^[b']+/u, '')\n .replace(/'+$/u, '')\n .replace(/\\.+$/u, '');\n}\n\n/**\n * Translate a nodemailer/socket error into mailsuite's `SMTPError`\n * messages. Errors that don't come from the connection (no `code`) are\n * returned unchanged, as Python lets non-SMTP exceptions propagate.\n */\nfunction toSMTPError(error: unknown): unknown {\n if (!(error instanceof Error) || error instanceof SMTPError) {\n return error;\n }\n const fields = error as NodemailerErrorFields;\n const code = typeof fields.code === 'string' ? fields.code : '';\n const originalCode =\n typeof fields.originalCode === 'string' ? fields.originalCode : code;\n if (code === '') {\n return error;\n }\n const options = { cause: error };\n if (DNS_CODES.has(originalCode) || code === 'EDNS') {\n return new SMTPError('DNS resolution failed', options);\n }\n if (originalCode === 'ECONNREFUSED') {\n return new SMTPError('Connection refused', options);\n }\n if (originalCode === 'ECONNRESET') {\n return new SMTPError('Connection reset', options);\n }\n if (originalCode === 'ECONNABORTED') {\n return new SMTPError('Connection aborted', options);\n }\n if (originalCode === 'ETIMEDOUT' || code === 'ETIMEDOUT') {\n return new SMTPError('Connection timed out', options);\n }\n if (\n CERTIFICATE_CODE.test(originalCode) ||\n (code === 'ETLS' && CERTIFICATE_MESSAGE.test(error.message))\n ) {\n return new SMTPError(`Certificate error: ${error.message}`, options);\n }\n if (code === 'ETLS' || originalCode.startsWith('ERR_SSL_')) {\n return new SMTPError(`SSL error: ${error.message}`, options);\n }\n return new SMTPError(stripErrorText(error.message), options);\n}\n\n/**\n * Whether the server's (plain-text) EHLO reply advertised STARTTLS. With\n * `ignoreTLS`, nodemailer keeps that reply in `_ehloLines` (it has no public\n * accessor); without it, the answer is false.\n */\nfunction advertisesStartTls(connection: SMTPConnection): boolean {\n const lines = (connection as unknown as { _ehloLines?: unknown })._ehloLines;\n return (\n Array.isArray(lines) &&\n lines.some(\n line => typeof line === 'string' && /^STARTTLS\\b/iu.test(line.trim()),\n )\n );\n}\n\n/** Run one callback-style SMTPConnection step, failing on an 'error' event too. */\nfunction step<T>(\n connection: SMTPConnection,\n start: (done: (error: Error | null | undefined, value?: T) => void) => void,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const onError = (error: Error): void => reject(error);\n connection.once('error', onError);\n start((error, value) => {\n connection.removeListener('error', onError);\n if (error) {\n reject(error);\n } else {\n resolve(value as T);\n }\n });\n });\n}\n\n/**\n * Send an email using a SMTP relay.\n *\n * Without `requireEncryption` the connection starts in plain text and is\n * upgraded with STARTTLS when the server offers it (see `starttls` to never\n * or always upgrade). When it is not offered, credentials are refused with\n * `SMTPError` before they are sent, and a message without credentials goes\n * out unencrypted with a warning, as with mailsuite. Every\n * recipient (To, Cc and Bcc) is in the SMTP envelope; Bcc is never in the\n * headers. Connection and protocol failures raise `SMTPError`.\n */\nexport async function sendEmail(\n host: string,\n messageFrom: string,\n options: SendEmailOptions = {},\n): Promise<void> {\n const message = buildMessage(messageFrom, options);\n const requireEncryption = options.requireEncryption ?? false;\n // Ignored with implicit TLS, like mailsuite.\n const starttls = requireEncryption ? null : (options.starttls ?? null);\n const { username, password } = options;\n const auth = username && password ? { user: username, pass: password } : null;\n let connection: SMTPConnection | null = null;\n try {\n connection = new SMTPConnection({\n host,\n port: options.port || (requireEncryption ? SMTPS_PORT : SMTP_PORT),\n secure: requireEncryption,\n // starttls: false never upgrades; otherwise nodemailer upgrades when\n // STARTTLS is advertised (a failed upgrade is an error).\n ...(starttls === false ? { ignoreTLS: true } : {}),\n tls: options.verify === false ? { rejectUnauthorized: false } : {},\n logger: false,\n });\n // Late errors (after a step settled) must not crash the process.\n connection.on('error', () => undefined);\n const active = connection;\n await step<void>(active, done => active.connect(error => done(error)));\n if (!(requireEncryption || active.secure)) {\n if (starttls === false) {\n if (advertisesStartTls(active)) {\n logger.info(\n 'SMTP server supports STARTTLS, but it is disabled ... staying in plain text',\n );\n }\n if (auth !== null) {\n logger.warning(\n 'Sending SMTP credentials unencrypted because starttls=False',\n );\n }\n } else if (starttls === true) {\n // Not upgraded without ignoreTLS: STARTTLS was not advertised.\n throw new SMTPError(\n 'STARTTLS required but not supported by the server',\n );\n } else if (auth === null) {\n logger.warning(\n 'SMTP server does not support STARTTLS. Proceeding in plain text!',\n );\n } else {\n // Checked before AUTH: an attacker can strip STARTTLS from the\n // plain-text EHLO reply (GHSA-2x4j-7g3q-wr6f).\n throw new SMTPError(PLAINTEXT_REFUSAL);\n }\n }\n if (auth !== null) {\n await step<boolean>(active, done => active.login(auth, done));\n }\n const messageTo = options.messageTo ?? null;\n if (messageTo === null) {\n throw new TypeError('message_to cannot be None');\n }\n // Every recipient, deduplicated: the envelope is Bcc's only path.\n const envelopeTo = [\n ...new Set([\n ...messageTo,\n ...(options.messageCc ?? []),\n ...(options.messageBcc ?? []),\n ]),\n ].map(envelopeAddress);\n const envelope = { from: envelopeAddress(messageFrom), to: envelopeTo };\n await step(active, done => active.send(envelope, message, done));\n } catch (error) {\n throw toSMTPError(error);\n } finally {\n connection?.quit();\n }\n}\n","// Email parsing results as a zip file, ported from parsedmarc's\n// `email_results()` and `_build_report_email_content()`.\n\nimport { AssertionError } from 'node:assert';\n\nimport { logger, type ParsingResults } from 'tsdmarc';\n\nimport { sendEmail } from './send-email';\n\n/**\n * The zip attachment: its bytes, or a function that builds them from the\n * results. Pass the core's `getReportZip` (parsedmarc's `get_report_zip()`).\n */\nexport type ReportZip =\n | Uint8Array\n | ((results: ParsingResults) => Promise<Uint8Array> | Uint8Array);\n\nexport interface ReportEmailContentOptions {\n /** Overrides the default subject (`DMARC results for YYYY-MM-DD`). */\n subject?: string | null;\n /** Overrides the default attachment filename; `.zip` is appended if missing. */\n attachmentFilename?: string | null;\n /** Overrides the default plain text body. */\n message?: string | null;\n /** The zip attachment, or how to build it. */\n reportZip: ReportZip;\n}\n\nexport interface ReportEmailContent {\n subject: string;\n message: string;\n attachments: [string, Uint8Array][];\n}\n\nexport interface EmailResultsOptions extends ReportEmailContentOptions {\n mailCc?: string[] | null;\n mailBcc?: string[] | null;\n /** 0 (default): 465 with `requireEncryption`, else 25. */\n port?: number;\n /**\n * Connect with implicit SSL/TLS from the start (usually port 465). When\n * false, the connection starts in plain text and `starttls` decides\n * whether it is upgraded.\n */\n requireEncryption?: boolean;\n /**\n * Whether to upgrade a plain-text (`requireEncryption: false`) connection\n * with STARTTLS (parsedmarc 11.2.1). `null`/`undefined` (default)\n * upgrades when the server advertises STARTTLS; when it does not,\n * `SMTPError` is thrown before authenticating if `username` and\n * `password` are given, and without credentials the message is sent in\n * plain text with a warning. `true` requires the upgrade. `false` never\n * upgrades, so any credentials and the message are sent in plain text (a\n * warning is logged when credentials are sent). Ignored with\n * `requireEncryption`. See `SendEmailOptions.starttls`.\n */\n starttls?: boolean | null;\n /** Verify the TLS certificate. Default: true. */\n verify?: boolean;\n username?: string | null;\n password?: string | null;\n}\n\nfunction pad(value: number): string {\n return String(value).padStart(2, '0');\n}\n\n/** `datetime.now().strftime(\"%Y-%m-%d\")`: today's local date. */\nfunction localDateString(now: Date = new Date()): string {\n return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;\n}\n\n/**\n * Build the subject, plain text body and zip attachment shared by every\n * report-summary email transport (SMTP here, Microsoft Graph in\n * `@tsdmarc/msgraph`).\n */\nexport async function buildReportEmailContent(\n results: ParsingResults,\n options: ReportEmailContentOptions,\n): Promise<ReportEmailContent> {\n const dateString = localDateString();\n let filename: string;\n if (options.attachmentFilename) {\n filename = options.attachmentFilename;\n if (!filename.toLowerCase().endsWith('.zip')) {\n filename += '.zip';\n }\n } else {\n filename = `DMARC-${dateString}.zip`;\n }\n const subject = options.subject ?? `DMARC results for ${dateString}`;\n const message = options.message ?? `DMARC results for ${dateString}`;\n const { reportZip } = options;\n const zipBytes =\n typeof reportZip === 'function' ? await reportZip(results) : reportZip;\n return { subject, message, attachments: [[filename, zipBytes]] };\n}\n\n/**\n * Email parsing results as a zip file.\n *\n * `options.reportZip` provides the attachment: pass the core's\n * `getReportZip` (or bytes already built). parsedmarc calls\n * `get_report_zip()` itself; taking it as an argument keeps this package\n * independent of the output module.\n */\nexport async function emailResults(\n results: ParsingResults,\n host: string,\n mailFrom: string,\n mailTo: string[] | null,\n options: EmailResultsOptions,\n): Promise<void> {\n logger.debug('Emailing report');\n if (!Array.isArray(mailTo)) {\n throw new AssertionError({\n message: 'mail_to must be a list',\n actual: mailTo,\n expected: 'an array',\n operator: 'Array.isArray',\n });\n }\n const { subject, message, attachments } = await buildReportEmailContent(\n results,\n options,\n );\n await sendEmail(host, mailFrom, {\n messageTo: mailTo,\n messageCc: options.mailCc ?? null,\n messageBcc: options.mailBcc ?? null,\n port: options.port ?? 0,\n requireEncryption: options.requireEncryption ?? false,\n verify: options.verify ?? true,\n username: options.username ?? null,\n password: options.password ?? null,\n subject,\n attachments,\n plainMessage: message,\n starttls: options.starttls ?? null,\n });\n}\n"],"mappings":";;;;;;AAcA,IAAa,YAAb,cAA+B,MAAM;CACnC,OAAgB;AAClB;AA0CA,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,oBACJ;;;;;AAMF,SAAS,aAAa,aAAqB,SAAmC;CAC5E,OAAO,YAAY;EACjB,aAAa,QAAQ,eAAe;EACpC,WAAW,QAAQ,aAAa;EAChC;EACA,WAAW,QAAQ,aAAa;EAChC,cAAc,QAAQ,gBAAgB;EACtC,SAAS,QAAQ,WAAW;CAC9B,CAAC,CAAC,CAAC,WAAW,WAAW,MAAM;AACjC;;AAGA,SAAS,gBAAgB,SAAyB;CAChD,MAAM,CAAC,UAAU,cAAc,SAAS,EAAE,SAAS,KAAK,CAAC;CACzD,OAAO,QAAQ,WAAW;AAC5B;AAOA,MAAM,4BAAiC,IAAI,IAAI;CAC7C;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,mBACJ;AACF,MAAM,sBAAsB;;AAG5B,SAAS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,MACA,UACA,QACA,SACe;CACf,OAAO,MAAM,iBAAiB;CAC9B,IAAI,CAAC,MAAM,QAAQ,MAAM,GACvB,MAAM,IAAI,eAAe;EACvB,SAAS;EACT,QAAQ;EACR,UAAU;EACV,UAAU;CACZ,CAAC;CAEH,MAAM,EAAE,SAAS,SAAS,gBAAgB,MAAM,wBAC9C,SACA,OACF;CACA,MAAM,UAAU,MAAM,UAAU;EAC9B,WAAW;EACX,WAAW,QAAQ,UAAU;EAC7B,YAAY,QAAQ,WAAW;EAC/B,MAAM,QAAQ,QAAQ;EACtB,mBAAmB,QAAQ,qBAAqB;EAChD,QAAQ,QAAQ,UAAU;EAC1B,UAAU,QAAQ,YAAY;EAC9B,UAAU,QAAQ,YAAY;EAC9B;EACA;EACA,cAAc;EACd,UAAU,QAAQ,YAAY;CAChC,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@tsdmarc/smtp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "SMTP sender for tsdmarc: email DMARC report results as a zip attachment (port of mailsuite.smtp).",
5
+ "license": "Apache-2.0",
6
+ "author": "HelixNebula (https://helixnebula.tech)",
7
+ "homepage": "https://github.com/helixnebulatech/tsdmarc/tree/main/packages/smtp#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/helixnebulatech/tsdmarc/issues"
10
+ },
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ "./package.json": "./package.json",
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist/**/*",
25
+ "CHANGELOG.md",
26
+ "README.md",
27
+ "LICENSE",
28
+ "NOTICE"
29
+ ],
30
+ "dependencies": {
31
+ "nodemailer": "^10.2.1"
32
+ },
33
+ "devDependencies": {
34
+ "@arethetypeswrong/cli": "0.18.5",
35
+ "@tsdmarc/tsconfig": "0.0.0",
36
+ "@tsdmarc/tsdown-config": "0.0.0",
37
+ "@types/node": "26.6.5",
38
+ "tsdmarc": "1.0.0",
39
+ "tsdown": "0.23.2",
40
+ "vitest": "5.0.5"
41
+ },
42
+ "peerDependencies": {
43
+ "tsdmarc": "^1.0.0"
44
+ },
45
+ "engines": {
46
+ "node": ">=24"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "provenance": true
51
+ },
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "git+https://github.com/helixnebulatech/tsdmarc.git",
55
+ "directory": "packages/smtp"
56
+ },
57
+ "keywords": [
58
+ "dmarc",
59
+ "tsdmarc",
60
+ "smtp",
61
+ "email",
62
+ "nodemailer",
63
+ "dmarc-reports"
64
+ ],
65
+ "scripts": {
66
+ "build": "tsdown",
67
+ "clean": "rm -rf dist *.tsbuildinfo",
68
+ "publint": "publint && attw --pack . --profile esm-only --ignore-rules cjs-resolves-to-esm",
69
+ "test": "vitest --run",
70
+ "test:watch": "vitest",
71
+ "type-check": "tsrs --noEmit -p tsconfig.json"
72
+ }
6
73
  }