@blamejs/core 0.4.21 → 0.4.23

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 CHANGED
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.4.x
10
10
 
11
+ - **0.4.22** (2026-04-30) — b.mail attachments + inline images + plain/HTML alternatives
12
+ - **0.4.21** (2026-04-30) — b.queue: repeat-in-queue (cron) + parent-child Flows
11
13
  - **0.4.20** (2026-04-30) — b.queue + b.jobs: priority, rate-limit, progress
12
14
  - **0.4.19** (2026-04-30) — b.router: schema-validated routes + OpenAPI gen
13
15
  - **0.4.18** (2026-04-30) — cookieJar forensic-test strengthening (real crypto, replay, nonce)
package/lib/audit.js CHANGED
@@ -202,6 +202,7 @@ var FRAMEWORK_NAMESPACES = [
202
202
  "apikey", // b.apiKey
203
203
  "backup", // b.backup
204
204
  "cache", // b.cache
205
+ "dkim", // b.mail.dkim (DKIM-Signature generation events)
205
206
  "mail", // b.mail (b.mail-bounce uses "system.mail.*")
206
207
  "notify", // b.notify
207
208
  "permissions", // b.permissions
@@ -0,0 +1,365 @@
1
+ "use strict";
2
+ /**
3
+ * mail-dkim — DKIM-Signature header generation for outbound mail.
4
+ *
5
+ * RFC 6376 (rsa-sha256) is the default; RFC 8463 (ed25519-sha256) is
6
+ * available as opt-in. The two share the same signer surface so
7
+ * operators flip algorithms by changing the `algorithm` opt and the
8
+ * private key — no code change.
9
+ *
10
+ * Forward-looking: the DKIM-Signature `a=` tag carries an algorithm
11
+ * identifier. When the IETF standardizes a post-quantum DKIM algorithm
12
+ * (an SLH-DSA or ML-DSA variant), this module gains a third allowed
13
+ * value alongside `rsa-sha256` and `ed25519-sha256`. The signer's
14
+ * outer surface stays the same.
15
+ *
16
+ * Public API:
17
+ *
18
+ * var signer = b.mail.dkim.create({
19
+ * domain: "example.com",
20
+ * selector: "s1",
21
+ * privateKey: pemString | crypto.KeyObject,
22
+ * algorithm: "rsa-sha256" (default) | "ed25519-sha256"
23
+ * headersToSign: ["from","to","subject","date","message-id"]
24
+ * (default — order matters in the signed string)
25
+ * canonicalization:"relaxed/relaxed" (default) | "simple/simple"
26
+ * | "relaxed/simple" | "simple/relaxed"
27
+ * bodyLength: number (optional `l=` cap; off by default)
28
+ * audit: false (default true)
29
+ * });
30
+ *
31
+ * var signedRfc822 = signer.sign(rfc822String);
32
+ *
33
+ * The signer never mutates the message object — it consumes the final
34
+ * RFC 822 wire format produced by `mail._buildRfc822` and returns a
35
+ * new string with the DKIM-Signature header prepended.
36
+ *
37
+ * Validation surface uses DkimError (FrameworkError subclass) with a
38
+ * permanent flag — every problem here is a configuration / shape
39
+ * problem, not a transient one.
40
+ */
41
+ var lazyRequire = require("./lazy-require");
42
+ var audit = lazyRequire(function () { return require("./audit"); });
43
+ var nodeCrypto = require("crypto");
44
+ var validateOpts = require("./validate-opts");
45
+ var { FrameworkError } = require("./framework-error");
46
+
47
+ class DkimError extends FrameworkError {
48
+ constructor(code, message) {
49
+ super(message, code);
50
+ this.name = "DkimError";
51
+ this.permanent = true;
52
+ this.isDkimError = true;
53
+ }
54
+ }
55
+
56
+ var ALLOWED_ALGORITHMS = ["rsa-sha256", "ed25519-sha256"];
57
+ var ALLOWED_CANON = [
58
+ "relaxed/relaxed",
59
+ "simple/simple",
60
+ "relaxed/simple",
61
+ "simple/relaxed",
62
+ ];
63
+ var DEFAULT_HEADERS = ["from", "to", "subject", "date", "message-id"];
64
+
65
+ // ---- Canonicalization (RFC 6376 §3.4) ----
66
+
67
+ function _canonHeaderRelaxed(name, value) {
68
+ // Lowercase name, unfold continuations, collapse internal WSP runs to
69
+ // single SP, strip leading/trailing WSP from value.
70
+ var unfolded = String(value).replace(/\r?\n[ \t]+/g, " ");
71
+ var trimmed = unfolded.replace(/[ \t]+/g, " ").replace(/^[ \t]+|[ \t]+$/g, "");
72
+ return name.toLowerCase() + ":" + trimmed + "\r\n";
73
+ }
74
+
75
+ function _canonHeaderSimple(name, value) {
76
+ // Preserve as-is. Used rarely in practice but spec-compliant.
77
+ return name + ":" + value + "\r\n";
78
+ }
79
+
80
+ function _canonBodyRelaxed(body) {
81
+ // 1) Reduce internal WSP runs in each line to a single SP, strip
82
+ // trailing WSP. 2) Strip empty lines at end of body. 3) Ensure
83
+ // a single trailing CRLF. Empty body → just "\r\n".
84
+ if (!body) return "\r\n";
85
+ var normalized = body.replace(/\r?\n/g, "\r\n");
86
+ var lines = normalized.split("\r\n");
87
+ for (var i = 0; i < lines.length; i++) {
88
+ lines[i] = lines[i].replace(/[ \t]+/g, " ").replace(/[ \t]+$/, "");
89
+ }
90
+ // Drop trailing empty lines.
91
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
92
+ if (lines.length === 0) return "\r\n";
93
+ return lines.join("\r\n") + "\r\n";
94
+ }
95
+
96
+ function _canonBodySimple(body) {
97
+ // Strip trailing empty lines but otherwise preserve the body. Empty
98
+ // body → "\r\n".
99
+ if (!body) return "\r\n";
100
+ var normalized = body.replace(/\r?\n/g, "\r\n");
101
+ // Strip trailing empty lines.
102
+ while (normalized.endsWith("\r\n\r\n")) {
103
+ normalized = normalized.slice(0, -2);
104
+ }
105
+ if (!normalized.endsWith("\r\n")) normalized += "\r\n";
106
+ return normalized;
107
+ }
108
+
109
+ // ---- RFC 822 split ----
110
+
111
+ function _splitHeadersBody(rfc822) {
112
+ // Headers terminated by the first empty line. Headers may use folded
113
+ // continuation lines (CRLF + WSP); we keep them folded and let the
114
+ // canonicalizer unfold relaxed-mode.
115
+ var sep = rfc822.indexOf("\r\n\r\n");
116
+ if (sep === -1) {
117
+ throw new DkimError("dkim/missing-body-separator",
118
+ "rfc822 input has no header/body separator (CRLF CRLF)");
119
+ }
120
+ return {
121
+ headers: rfc822.slice(0, sep + 2), // include trailing CRLF after last header
122
+ body: rfc822.slice(sep + 4),
123
+ };
124
+ }
125
+
126
+ function _parseHeaders(rawHeaders) {
127
+ // Parse into [{ name, value }, ...] preserving order. Folded
128
+ // continuation lines (start with WSP) are appended to the prior
129
+ // header's value verbatim.
130
+ var lines = rawHeaders.split("\r\n");
131
+ var out = [];
132
+ for (var i = 0; i < lines.length; i++) {
133
+ var line = lines[i];
134
+ if (!line) continue;
135
+ if (line[0] === " " || line[0] === "\t") {
136
+ if (out.length > 0) out[out.length - 1].value += "\r\n" + line;
137
+ continue;
138
+ }
139
+ var colon = line.indexOf(":");
140
+ if (colon === -1) continue;
141
+ out.push({
142
+ name: line.slice(0, colon),
143
+ value: line.slice(colon + 1), // preserve leading SP for simple canon
144
+ });
145
+ }
146
+ return out;
147
+ }
148
+
149
+ // ---- Hashing + signing ----
150
+
151
+ function _bodyHashB64(body, algorithm, canonBody) {
152
+ var canonicalized = canonBody === "simple"
153
+ ? _canonBodySimple(body)
154
+ : _canonBodyRelaxed(body);
155
+ var hashName = "sha256"; // both rsa-sha256 and ed25519-sha256 hash with sha256
156
+ return nodeCrypto.createHash(hashName)
157
+ .update(canonicalized).digest("base64");
158
+ }
159
+
160
+ function _signString(strToSign, privateKey, algorithm) {
161
+ if (algorithm === "rsa-sha256") {
162
+ return nodeCrypto.createSign("RSA-SHA256")
163
+ .update(strToSign).sign(privateKey).toString("base64");
164
+ }
165
+ if (algorithm === "ed25519-sha256") {
166
+ // Ed25519 in node:crypto signs the raw message (it hashes
167
+ // internally as part of EdDSA). Per RFC 8463 the verifier still
168
+ // sees `a=ed25519-sha256` because the body hash is sha256.
169
+ return nodeCrypto.sign(null, Buffer.from(strToSign, "utf8"), privateKey)
170
+ .toString("base64");
171
+ }
172
+ throw new DkimError("dkim/bad-algorithm",
173
+ "unknown algorithm: " + algorithm);
174
+ }
175
+
176
+ // ---- Signature header construction ----
177
+
178
+ function _foldSignatureHeader(unfolded) {
179
+ // RFC 5322 §2.2.3 line length: 78 preferred, 998 max. The b= value
180
+ // is long enough that folding helps readability and stays well clear
181
+ // of the limit.
182
+ var maxLine = 76;
183
+ var name = "DKIM-Signature: ";
184
+ var rest = unfolded;
185
+ if ((name + rest).length <= maxLine) return name + rest;
186
+ // Fold on tag boundaries (`; tag=value`). Keep the first chunk on
187
+ // the header line, subsequent chunks on continuation lines starting
188
+ // with TAB.
189
+ var parts = rest.split("; ");
190
+ var lines = [name + parts[0]];
191
+ for (var i = 1; i < parts.length; i++) {
192
+ lines.push("\t" + parts[i] + (i < parts.length - 1 ? ";" : ""));
193
+ }
194
+ return lines.join("\r\n");
195
+ }
196
+
197
+ // ---- Public surface ----
198
+
199
+ function create(opts) {
200
+ opts = opts || {};
201
+ validateOpts(opts, [
202
+ "domain", "selector", "privateKey", "algorithm",
203
+ "headersToSign", "canonicalization", "bodyLength", "audit",
204
+ ], "mail.dkim.create");
205
+
206
+ if (typeof opts.domain !== "string" || !/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(opts.domain)) {
207
+ throw new DkimError("dkim/bad-domain",
208
+ "domain must be a valid DNS name (e.g. 'example.com')");
209
+ }
210
+ if (typeof opts.selector !== "string" || !/^[a-z0-9_-]+$/i.test(opts.selector)) {
211
+ throw new DkimError("dkim/bad-selector",
212
+ "selector must be a non-empty token of [A-Za-z0-9_-]");
213
+ }
214
+ if (!opts.privateKey || (typeof opts.privateKey !== "string" &&
215
+ typeof opts.privateKey !== "object")) {
216
+ throw new DkimError("dkim/missing-private-key",
217
+ "privateKey is required (PEM string or crypto.KeyObject)");
218
+ }
219
+ var algorithm = opts.algorithm || "rsa-sha256";
220
+ if (ALLOWED_ALGORITHMS.indexOf(algorithm) === -1) {
221
+ throw new DkimError("dkim/bad-algorithm",
222
+ "algorithm must be one of: " + ALLOWED_ALGORITHMS.join(", "));
223
+ }
224
+ var canonicalization = opts.canonicalization || "relaxed/relaxed";
225
+ if (ALLOWED_CANON.indexOf(canonicalization) === -1) {
226
+ throw new DkimError("dkim/bad-canonicalization",
227
+ "canonicalization must be one of: " + ALLOWED_CANON.join(", "));
228
+ }
229
+ var canonHeader = canonicalization.split("/")[0];
230
+ var canonBody = canonicalization.split("/")[1];
231
+
232
+ var headersToSign = opts.headersToSign || DEFAULT_HEADERS;
233
+ if (!Array.isArray(headersToSign) || headersToSign.length === 0) {
234
+ throw new DkimError("dkim/bad-headers",
235
+ "headersToSign must be a non-empty array of header names");
236
+ }
237
+ for (var i = 0; i < headersToSign.length; i++) {
238
+ if (typeof headersToSign[i] !== "string" || headersToSign[i].length === 0) {
239
+ throw new DkimError("dkim/bad-headers",
240
+ "headersToSign[" + i + "] must be a non-empty string");
241
+ }
242
+ }
243
+ if (opts.bodyLength !== undefined &&
244
+ (typeof opts.bodyLength !== "number" || !isFinite(opts.bodyLength) || opts.bodyLength < 0)) {
245
+ throw new DkimError("dkim/bad-body-length",
246
+ "bodyLength must be a non-negative finite number");
247
+ }
248
+
249
+ var auditOn = opts.audit !== false;
250
+ // Try to parse the private key once at create time so misconfigured
251
+ // operators see the failure at boot rather than at first send().
252
+ var keyObject;
253
+ try {
254
+ keyObject = typeof opts.privateKey === "string" || Buffer.isBuffer(opts.privateKey)
255
+ ? nodeCrypto.createPrivateKey({ key: opts.privateKey, format: "pem" })
256
+ : opts.privateKey;
257
+ } catch (e) {
258
+ throw new DkimError("dkim/bad-private-key",
259
+ "privateKey could not be parsed: " + ((e && e.message) || String(e)));
260
+ }
261
+
262
+ function _emit(action, info) {
263
+ if (!auditOn) return;
264
+ audit().safeEmit({
265
+ action: action,
266
+ outcome: info.outcome || "success",
267
+ actor: info.actor || {},
268
+ metadata: {
269
+ domain: opts.domain,
270
+ selector: opts.selector,
271
+ algorithm: algorithm,
272
+ bodyLength: info.bodyLength,
273
+ durationMs: info.durationMs,
274
+ },
275
+ reason: info.reason || null,
276
+ });
277
+ }
278
+
279
+ function sign(rfc822) {
280
+ if (typeof rfc822 !== "string" || rfc822.length === 0) {
281
+ throw new DkimError("dkim/bad-input",
282
+ "sign() requires the rfc822 wire format as a non-empty string");
283
+ }
284
+ var t0 = Date.now();
285
+ var split = _splitHeadersBody(rfc822);
286
+ var parsedHeaders = _parseHeaders(split.headers);
287
+
288
+ // Body hash
289
+ var body = split.body;
290
+ if (opts.bodyLength !== undefined) {
291
+ body = body.slice(0, opts.bodyLength);
292
+ }
293
+ var bh = _bodyHashB64(body, algorithm, canonBody);
294
+
295
+ // Build the unsigned DKIM-Signature header (b= empty).
296
+ // Tag order follows RFC 6376 examples: v, a, c, d, s, h, bh, b.
297
+ var sigTags = [
298
+ "v=1",
299
+ "a=" + algorithm,
300
+ "c=" + canonicalization,
301
+ "d=" + opts.domain,
302
+ "s=" + opts.selector,
303
+ "h=" + headersToSign.join(":"),
304
+ "bh=" + bh,
305
+ ];
306
+ if (opts.bodyLength !== undefined) sigTags.push("l=" + opts.bodyLength);
307
+ sigTags.push("b=");
308
+ var unsignedSigValue = sigTags.join("; ");
309
+
310
+ // Canonicalize the header set: each header in headersToSign (in
311
+ // order, picking the LAST occurrence per RFC 6376 §5.4.2), then
312
+ // the DKIM-Signature header itself with empty b=. The result is
313
+ // what gets signed.
314
+ var headerNamesLc = parsedHeaders.map(function (h) { return h.name.toLowerCase(); });
315
+ var canonicalizedHeaders = "";
316
+ for (var j = 0; j < headersToSign.length; j++) {
317
+ var wantLc = headersToSign[j].toLowerCase();
318
+ var idx = -1;
319
+ for (var k = 0; k < headerNamesLc.length; k++) {
320
+ if (headerNamesLc[k] === wantLc) idx = k;
321
+ }
322
+ if (idx === -1) continue; // missing headers are skipped (signer's choice)
323
+ var h = parsedHeaders[idx];
324
+ canonicalizedHeaders += canonHeader === "simple"
325
+ ? _canonHeaderSimple(h.name, h.value)
326
+ : _canonHeaderRelaxed(h.name, h.value);
327
+ }
328
+ // Append the unsigned DKIM-Signature header without trailing CRLF
329
+ // per RFC 6376 §3.7.
330
+ var dkimHeaderForSigning = canonHeader === "simple"
331
+ ? _canonHeaderSimple("DKIM-Signature", " " + unsignedSigValue)
332
+ : _canonHeaderRelaxed("DKIM-Signature", unsignedSigValue);
333
+ canonicalizedHeaders += dkimHeaderForSigning.replace(/\r\n$/, "");
334
+
335
+ var signature = _signString(canonicalizedHeaders, keyObject, algorithm);
336
+ // Replace the empty `b=` placeholder with the actual base64 signature.
337
+ var finalSigValue = sigTags.slice(0, -1).concat(["b=" + signature]).join("; ");
338
+
339
+ var dkimHeaderLine = _foldSignatureHeader(finalSigValue) + "\r\n";
340
+
341
+ _emit("dkim.sign.success", {
342
+ bodyLength: body.length,
343
+ durationMs: Date.now() - t0,
344
+ });
345
+
346
+ return dkimHeaderLine + rfc822;
347
+ }
348
+
349
+ return {
350
+ sign: sign,
351
+ domain: opts.domain,
352
+ selector: opts.selector,
353
+ algorithm: algorithm,
354
+ };
355
+ }
356
+
357
+ // Test-only exports for unit testing the canonicalization primitives
358
+ // directly without going through a full sign() round.
359
+ module.exports = {
360
+ create: create,
361
+ DkimError: DkimError,
362
+ _canonHeaderRelaxedForTest: _canonHeaderRelaxed,
363
+ _canonBodyRelaxedForTest: _canonBodyRelaxed,
364
+ _canonBodySimpleForTest: _canonBodySimple,
365
+ };
package/lib/mail.js CHANGED
@@ -38,9 +38,24 @@
38
38
  * text: "plain body" (at least one of text/html)
39
39
  * html: "<p>...</p>"
40
40
  * headers: { "X-Custom": "v" } (merged with defaults)
41
+ * attachments: [{
42
+ * filename: "report.pdf", // required
43
+ * content: buf, // Buffer or string
44
+ * contentType: "application/pdf", // default application/octet-stream
45
+ * contentDisposition: "attachment", // or "inline"
46
+ * cid: "logo-1", // for inline images:
47
+ * // <img src="cid:logo-1">
48
+ * }, ...]
41
49
  * }
42
50
  * → whatever the transport returned
43
51
  *
52
+ * When attachments are present the SMTP transport wraps the body in
53
+ * multipart/mixed; text+html bodies still use multipart/alternative
54
+ * inside. Resend's http preset forwards attachments via the Resend API
55
+ * shape (base64 content + content_id for inline). Operators wiring
56
+ * other vendors against httpTransport include attachments in their
57
+ * own serialize() per-vendor.
58
+ *
44
59
  * Validation surface uses MailError (FrameworkError subclass) with
45
60
  * permanent flag. Distinct codes per failure: missing-to, missing-from,
46
61
  * missing-body, invalid-recipient, transport-failed, smtp-*, http-*,
@@ -124,9 +139,77 @@ function _validateMessage(message) {
124
139
  "message.subject contains forbidden CRLF", true);
125
140
  }
126
141
 
127
- if (!message.text && !message.html) {
142
+ if (!message.text && !message.html && !message.calendar) {
128
143
  throw new MailError("mail/missing-body",
129
- "message must include at least one of text or html", true);
144
+ "message must include at least one of text, html, or calendar", true);
145
+ }
146
+
147
+ if (message.calendar !== undefined) {
148
+ if (!message.calendar || typeof message.calendar !== "object") {
149
+ throw new MailError("mail/invalid-calendar",
150
+ "message.calendar must be an object { method, icalText }", true);
151
+ }
152
+ var ALLOWED_METHODS = ["REQUEST", "CANCEL", "REPLY", "PUBLISH", "COUNTER", "REFRESH", "ADD", "DECLINECOUNTER"];
153
+ if (typeof message.calendar.method !== "string" ||
154
+ ALLOWED_METHODS.indexOf(message.calendar.method) === -1) {
155
+ throw new MailError("mail/invalid-calendar",
156
+ "calendar.method must be one of: " + ALLOWED_METHODS.join(", "), true);
157
+ }
158
+ if (typeof message.calendar.icalText !== "string" ||
159
+ message.calendar.icalText.length === 0) {
160
+ throw new MailError("mail/invalid-calendar",
161
+ "calendar.icalText is required (non-empty string)", true);
162
+ }
163
+ if (!/^BEGIN:VCALENDAR/.test(message.calendar.icalText)) {
164
+ throw new MailError("mail/invalid-calendar",
165
+ "calendar.icalText must start with 'BEGIN:VCALENDAR' (RFC 5545)", true);
166
+ }
167
+ }
168
+
169
+ if (message.attachments !== undefined) {
170
+ if (!Array.isArray(message.attachments)) {
171
+ throw new MailError("mail/invalid-attachments",
172
+ "message.attachments must be an array", true);
173
+ }
174
+ for (var i = 0; i < message.attachments.length; i++) {
175
+ var att = message.attachments[i];
176
+ if (!att || typeof att !== "object") {
177
+ throw new MailError("mail/invalid-attachment",
178
+ "attachments[" + i + "] must be an object", true);
179
+ }
180
+ if (typeof att.filename !== "string" || att.filename.length === 0) {
181
+ throw new MailError("mail/invalid-attachment",
182
+ "attachments[" + i + "].filename must be a non-empty string", true);
183
+ }
184
+ if (/[\r\n\0]/.test(att.filename)) {
185
+ throw new MailError("mail/invalid-attachment",
186
+ "attachments[" + i + "].filename contains forbidden control characters", true);
187
+ }
188
+ if (att.content === undefined || att.content === null) {
189
+ throw new MailError("mail/invalid-attachment",
190
+ "attachments[" + i + "].content is required (Buffer or string)", true);
191
+ }
192
+ if (!Buffer.isBuffer(att.content) && typeof att.content !== "string") {
193
+ throw new MailError("mail/invalid-attachment",
194
+ "attachments[" + i + "].content must be a Buffer or string", true);
195
+ }
196
+ if (att.contentType !== undefined &&
197
+ (typeof att.contentType !== "string" || /[\r\n\0]/.test(att.contentType))) {
198
+ throw new MailError("mail/invalid-attachment",
199
+ "attachments[" + i + "].contentType must be a clean string", true);
200
+ }
201
+ if (att.contentDisposition !== undefined &&
202
+ att.contentDisposition !== "attachment" &&
203
+ att.contentDisposition !== "inline") {
204
+ throw new MailError("mail/invalid-attachment",
205
+ "attachments[" + i + "].contentDisposition must be 'attachment' or 'inline'", true);
206
+ }
207
+ if (att.cid !== undefined &&
208
+ (typeof att.cid !== "string" || /[\r\n\0<>]/.test(att.cid))) {
209
+ throw new MailError("mail/invalid-attachment",
210
+ "attachments[" + i + "].cid must be a clean string (no <>)", true);
211
+ }
212
+ }
130
213
  }
131
214
  }
132
215
 
@@ -201,6 +284,69 @@ function memoryTransport() {
201
284
  // cleartext port the transport always issues STARTTLS and refuses
202
285
  // to send AUTH or DATA in cleartext if the upgrade is rejected.
203
286
 
287
+ function _newBoundary(label) {
288
+ return "blamejs-" + label + "-" + Date.now() + "-" + Math.floor(Math.random() * 1e9);
289
+ }
290
+
291
+ // base64-encode the buffer with line wrapping at 76 chars (RFC 2045
292
+ // §6.8). Most clients tolerate longer lines but the spec maximum is
293
+ // 998 octets per line; sticking to 76 keeps everyone happy.
294
+ function _base64Wrap(buf) {
295
+ var b64 = buf.toString("base64");
296
+ var lines = [];
297
+ for (var i = 0; i < b64.length; i += 76) lines.push(b64.slice(i, i + 76));
298
+ return lines.join("\r\n");
299
+ }
300
+
301
+ function _buildAttachmentPart(att) {
302
+ var content = Buffer.isBuffer(att.content) ? att.content : Buffer.from(String(att.content), "utf8");
303
+ var contentType = att.contentType || "application/octet-stream";
304
+ var disposition = att.contentDisposition || (att.cid ? "inline" : "attachment");
305
+ var lines = [];
306
+ lines.push("Content-Type: " + contentType + '; name="' + att.filename + '"');
307
+ lines.push("Content-Transfer-Encoding: base64");
308
+ lines.push("Content-Disposition: " + disposition + '; filename="' + att.filename + '"');
309
+ if (att.cid) lines.push("Content-ID: <" + att.cid + ">");
310
+ lines.push("");
311
+ lines.push(_base64Wrap(content));
312
+ return lines.join("\r\n");
313
+ }
314
+
315
+ function _buildBodyPart(message) {
316
+ // Collect body parts (text / html / calendar). Multiple parts → wrap
317
+ // in multipart/alternative so the recipient client picks whichever
318
+ // it can render. Calendar parts carry the `method=` parameter so
319
+ // mail clients (Outlook / Gmail / Apple Mail) treat the message as
320
+ // an invite, not a generic ics download.
321
+ var parts = [];
322
+ if (message.text) {
323
+ parts.push({ contentType: "text/plain; charset=utf-8", body: message.text });
324
+ }
325
+ if (message.html) {
326
+ parts.push({ contentType: "text/html; charset=utf-8", body: message.html });
327
+ }
328
+ if (message.calendar) {
329
+ parts.push({
330
+ contentType: 'text/calendar; method="' + message.calendar.method + '"; charset=utf-8',
331
+ body: message.calendar.icalText,
332
+ });
333
+ }
334
+ if (parts.length === 1) return parts[0];
335
+ var altBoundary = _newBoundary("alt");
336
+ var lines = [];
337
+ for (var i = 0; i < parts.length; i++) {
338
+ lines.push("--" + altBoundary);
339
+ lines.push("Content-Type: " + parts[i].contentType);
340
+ lines.push("");
341
+ lines.push(parts[i].body);
342
+ }
343
+ lines.push("--" + altBoundary + "--");
344
+ return {
345
+ contentType: 'multipart/alternative; boundary="' + altBoundary + '"',
346
+ body: lines.join("\r\n"),
347
+ };
348
+ }
349
+
204
350
  function _buildRfc822(message) {
205
351
  var headers = [];
206
352
  headers.push("From: " + message.from);
@@ -221,27 +367,32 @@ function _buildRfc822(message) {
221
367
  }
222
368
  }
223
369
 
370
+ var attachments = Array.isArray(message.attachments) ? message.attachments : [];
371
+ var inner = _buildBodyPart(message);
224
372
  var body;
225
- if (message.text && message.html) {
226
- var boundary = "blamejs-mail-" + Date.now() + "-" + Math.floor(Math.random() * 1e9);
227
- headers.push('Content-Type: multipart/alternative; boundary="' + boundary + '"');
228
- body = [
229
- "--" + boundary,
230
- "Content-Type: text/plain; charset=utf-8",
231
- "",
232
- message.text,
233
- "--" + boundary,
234
- "Content-Type: text/html; charset=utf-8",
235
- "",
236
- message.html,
237
- "--" + boundary + "--",
238
- ].join("\r\n");
239
- } else if (message.html) {
240
- headers.push("Content-Type: text/html; charset=utf-8");
241
- body = message.html;
373
+
374
+ if (attachments.length === 0) {
375
+ headers.push("Content-Type: " + inner.contentType);
376
+ body = inner.body;
242
377
  } else {
243
- headers.push("Content-Type: text/plain; charset=utf-8");
244
- body = message.text || "";
378
+ // multipart/mixed: first part is the body (single or alternative),
379
+ // subsequent parts are the attachments. Inline disposition + Content-ID
380
+ // is interpreted correctly by every major client even inside mixed;
381
+ // operators with strict-RFC-2387 multipart/related needs subscribe
382
+ // to a future patch when demand surfaces.
383
+ var mixedBoundary = _newBoundary("mixed");
384
+ headers.push('Content-Type: multipart/mixed; boundary="' + mixedBoundary + '"');
385
+ var parts = [];
386
+ parts.push("--" + mixedBoundary);
387
+ parts.push("Content-Type: " + inner.contentType);
388
+ parts.push("");
389
+ parts.push(inner.body);
390
+ for (var ai = 0; ai < attachments.length; ai++) {
391
+ parts.push("--" + mixedBoundary);
392
+ parts.push(_buildAttachmentPart(attachments[ai]));
393
+ }
394
+ parts.push("--" + mixedBoundary + "--");
395
+ body = parts.join("\r\n");
245
396
  }
246
397
 
247
398
  // Normalize line endings then dot-stuff per SMTP transparency.
@@ -257,6 +408,12 @@ function smtpTransport(opts) {
257
408
  throw new MailError("mail/smtp-misconfigured",
258
409
  "smtp transport requires opts.host", true);
259
410
  }
411
+ if (opts.dkimSigner !== undefined && opts.dkimSigner !== null &&
412
+ (typeof opts.dkimSigner !== "object" || typeof opts.dkimSigner.sign !== "function")) {
413
+ throw new MailError("mail/smtp-misconfigured",
414
+ "dkimSigner must be an object with a .sign(rfc822) method " +
415
+ "(see b.mail.dkim.create)", true);
416
+ }
260
417
  var port = opts.port || 587;
261
418
  var useImplicitTLS = port === 465 || opts.implicitTls === true;
262
419
  var rejectUnauthorized = opts.rejectUnauthorized !== false;
@@ -278,6 +435,7 @@ function smtpTransport(opts) {
278
435
  ehloName: ehloName,
279
436
  timeoutMs: timeoutMs,
280
437
  tlsOpts: tlsOpts,
438
+ dkimSigner: opts.dkimSigner || null,
281
439
  };
282
440
 
283
441
  return {
@@ -301,6 +459,13 @@ function _smtpSend(message, cfg) {
301
459
  var bccList = _toArray(message.bcc).map(_extractAddr);
302
460
  var rcpts = toList.concat(ccList, bccList);
303
461
  var dataMessage = _buildRfc822(message);
462
+ if (cfg.dkimSigner) {
463
+ try { dataMessage = cfg.dkimSigner.sign(dataMessage); }
464
+ catch (e) {
465
+ return reject(new MailError("mail/dkim-sign-failed",
466
+ "dkim signing failed: " + ((e && e.message) || String(e)), true));
467
+ }
468
+ }
304
469
 
305
470
  function fail(reason) {
306
471
  if (settled) return;
@@ -587,6 +752,21 @@ function resendTransport(opts) {
587
752
  if (message.html) payload.html = message.html;
588
753
  if (message.text) payload.text = message.text;
589
754
  if (message.headers) payload.headers = message.headers;
755
+ // Resend attachments shape: [{ filename, content (base64 string),
756
+ // contentType?, content_id? }]. Inline images via cid go through
757
+ // the content_id field (Resend renders <img src="cid:...">).
758
+ if (Array.isArray(message.attachments) && message.attachments.length > 0) {
759
+ payload.attachments = message.attachments.map(function (att) {
760
+ var buf = Buffer.isBuffer(att.content) ? att.content : Buffer.from(String(att.content), "utf8");
761
+ var entry = {
762
+ filename: att.filename,
763
+ content: buf.toString("base64"),
764
+ };
765
+ if (att.contentType) entry.contentType = att.contentType;
766
+ if (att.cid) entry.content_id = att.cid;
767
+ return entry;
768
+ });
769
+ }
590
770
  return { body: JSON.stringify(payload) };
591
771
  },
592
772
  interpret: function (res) {
@@ -694,6 +874,13 @@ function create(opts) {
694
874
  module.exports = {
695
875
  create: create,
696
876
  MailError: MailError,
877
+ // DKIM-Signature header generation for outbound mail (rsa-sha256
878
+ // default, ed25519-sha256 opt-in). Wire it into the smtp transport
879
+ // via opts.dkimSigner. See lib/mail-dkim.js for the full surface.
880
+ dkim: require("./mail-dkim"),
881
+ // Test-only export: lets unit tests inspect the wire format without
882
+ // standing up a TLS-capable SMTP fixture. Operators don't call this.
883
+ _buildRfc822ForTest: _buildRfc822,
697
884
  transports: {
698
885
  console: consoleTransport,
699
886
  memory: memoryTransport,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.4.21",
3
+ "version": "0.4.23",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",