@blamejs/core 0.4.22 → 0.4.24

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.23** (2026-04-30) — b.mail.dkim signing + calendar invites
12
+ - **0.4.22** (2026-04-30) — b.mail attachments + inline images + plain/HTML alternatives
11
13
  - **0.4.21** (2026-04-30) — b.queue: repeat-in-queue (cron) + parent-child Flows
12
14
  - **0.4.20** (2026-04-30) — b.queue + b.jobs: priority, rate-limit, progress
13
15
  - **0.4.19** (2026-04-30) — b.router: schema-validated routes + OpenAPI gen
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
@@ -139,9 +139,31 @@ function _validateMessage(message) {
139
139
  "message.subject contains forbidden CRLF", true);
140
140
  }
141
141
 
142
- if (!message.text && !message.html) {
142
+ if (!message.text && !message.html && !message.calendar) {
143
143
  throw new MailError("mail/missing-body",
144
- "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
+ }
145
167
  }
146
168
 
147
169
  if (message.attachments !== undefined) {
@@ -291,28 +313,38 @@ function _buildAttachmentPart(att) {
291
313
  }
292
314
 
293
315
  function _buildBodyPart(message) {
294
- // Text + html multipart/alternative; otherwise single-part.
295
- if (message.text && message.html) {
296
- var altBoundary = _newBoundary("alt");
297
- return {
298
- contentType: 'multipart/alternative; boundary="' + altBoundary + '"',
299
- body: [
300
- "--" + altBoundary,
301
- "Content-Type: text/plain; charset=utf-8",
302
- "",
303
- message.text,
304
- "--" + altBoundary,
305
- "Content-Type: text/html; charset=utf-8",
306
- "",
307
- message.html,
308
- "--" + altBoundary + "--",
309
- ].join("\r\n"),
310
- };
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 });
311
324
  }
312
325
  if (message.html) {
313
- return { contentType: "text/html; charset=utf-8", body: 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
+ });
314
333
  }
315
- return { contentType: "text/plain; charset=utf-8", body: message.text || "" };
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
+ };
316
348
  }
317
349
 
318
350
  function _buildRfc822(message) {
@@ -376,6 +408,12 @@ function smtpTransport(opts) {
376
408
  throw new MailError("mail/smtp-misconfigured",
377
409
  "smtp transport requires opts.host", true);
378
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
+ }
379
417
  var port = opts.port || 587;
380
418
  var useImplicitTLS = port === 465 || opts.implicitTls === true;
381
419
  var rejectUnauthorized = opts.rejectUnauthorized !== false;
@@ -397,6 +435,7 @@ function smtpTransport(opts) {
397
435
  ehloName: ehloName,
398
436
  timeoutMs: timeoutMs,
399
437
  tlsOpts: tlsOpts,
438
+ dkimSigner: opts.dkimSigner || null,
400
439
  };
401
440
 
402
441
  return {
@@ -420,6 +459,13 @@ function _smtpSend(message, cfg) {
420
459
  var bccList = _toArray(message.bcc).map(_extractAddr);
421
460
  var rcpts = toList.concat(ccList, bccList);
422
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
+ }
423
469
 
424
470
  function fail(reason) {
425
471
  if (settled) return;
@@ -828,6 +874,10 @@ function create(opts) {
828
874
  module.exports = {
829
875
  create: create,
830
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"),
831
881
  // Test-only export: lets unit tests inspect the wire format without
832
882
  // standing up a TLS-capable SMTP fixture. Operators don't call this.
833
883
  _buildRfc822ForTest: _buildRfc822,
@@ -208,6 +208,135 @@ function _request(method, url, headers, body, opts) {
208
208
  });
209
209
  }
210
210
 
211
+ // ---- Multipart-upload constants ----
212
+
213
+ // S3 spec floor for non-final part size. Below this the API rejects
214
+ // CompleteMultipartUpload with EntityTooSmall. The framework refuses
215
+ // configurations below this floor at create() time so operators don't
216
+ // see surprising failures only on large uploads.
217
+ var MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
218
+ // S3 spec ceiling on part count. CompleteMultipartUpload rejects
219
+ // uploads with more than 10000 parts.
220
+ var MAX_PARTS = 10000;
221
+ // Auto-multipart trigger: buffered bodies under this stay single-PUT.
222
+ // Streams always go multipart since size isn't known up-front.
223
+ var DEFAULT_MULTIPART_THRESHOLD_BYTES = 64 * 1024 * 1024;
224
+ // Conservative default part size — large enough to keep round-trip
225
+ // overhead small relative to payload, small enough to fit comfortably
226
+ // in a 4-way-concurrent upload's memory footprint.
227
+ var DEFAULT_PART_SIZE_BYTES = 16 * 1024 * 1024;
228
+ var DEFAULT_PART_CONCURRENCY = 4;
229
+
230
+ // ---- SSE option handling ----
231
+
232
+ function _resolveSseHeaders(sse) {
233
+ if (sse === undefined || sse === null) return null;
234
+ var type;
235
+ var keyId = null;
236
+ if (typeof sse === "string") {
237
+ type = sse;
238
+ } else if (sse && typeof sse === "object") {
239
+ type = sse.type;
240
+ keyId = sse.keyId || null;
241
+ } else {
242
+ throw _err("INVALID_SSE",
243
+ "opts.sse must be a string ('AES256' | 'aws:kms') or " +
244
+ "{ type, keyId }, got " + typeof sse, true);
245
+ }
246
+ if (type !== "AES256" && type !== "aws:kms") {
247
+ throw _err("INVALID_SSE",
248
+ "opts.sse type must be 'AES256' or 'aws:kms', got '" + type + "'", true);
249
+ }
250
+ var h = { "x-amz-server-side-encryption": type };
251
+ if (type === "aws:kms" && keyId) {
252
+ h["x-amz-server-side-encryption-aws-kms-key-id"] = String(keyId);
253
+ }
254
+ return { type: type, keyId: keyId, headers: h };
255
+ }
256
+
257
+ function _verifySseResponse(sseRequested, resHeaders) {
258
+ // Operators who specified an SSE policy expect the bucket / object to
259
+ // honor it. If the server silently dropped the header (mis-configured
260
+ // bucket policy, unsupported endpoint, etc.) the request looks like a
261
+ // success but the at-rest data is unencrypted. Surface this as a
262
+ // hard failure rather than a silent compliance hole.
263
+ if (!sseRequested) return;
264
+ var got = resHeaders["x-amz-server-side-encryption"];
265
+ if (!got) {
266
+ throw _err("SSE_NOT_APPLIED",
267
+ "opts.sse was '" + sseRequested.type + "' but server did not " +
268
+ "apply server-side encryption (no x-amz-server-side-encryption " +
269
+ "response header)", true);
270
+ }
271
+ if (got !== sseRequested.type) {
272
+ throw _err("SSE_MISMATCH",
273
+ "opts.sse requested '" + sseRequested.type + "' but server " +
274
+ "applied '" + got + "'", true);
275
+ }
276
+ }
277
+
278
+ // ---- Multipart helpers ----
279
+
280
+ // Build the CompleteMultipartUpload request body. Parts must be in
281
+ // ascending PartNumber order. ETags from S3 include surrounding
282
+ // quotes — preserve them exactly.
283
+ function _buildCompleteMultipartXml(parts) {
284
+ var body = "<CompleteMultipartUpload>";
285
+ for (var i = 0; i < parts.length; i++) {
286
+ body += "<Part>";
287
+ body += "<PartNumber>" + parts[i].partNumber + "</PartNumber>";
288
+ body += "<ETag>" + parts[i].etag + "</ETag>";
289
+ body += "</Part>";
290
+ }
291
+ body += "</CompleteMultipartUpload>";
292
+ return body;
293
+ }
294
+
295
+ // Read a Readable stream into fixed-size buffers. Yields one Buffer
296
+ // per part (size <= partSize). The final part may be smaller. The
297
+ // stream is consumed exactly once.
298
+ async function _readStreamParts(readable, partSize) {
299
+ var parts = [];
300
+ var pending = [];
301
+ var pendingBytes = 0;
302
+ for await (var chunk of readable) {
303
+ var buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
304
+ pending.push(buf);
305
+ pendingBytes += buf.length;
306
+ while (pendingBytes >= partSize) {
307
+ var combined = Buffer.concat(pending, pendingBytes);
308
+ parts.push(combined.slice(0, partSize));
309
+ var leftover = combined.slice(partSize);
310
+ pending = leftover.length > 0 ? [leftover] : [];
311
+ pendingBytes = leftover.length;
312
+ }
313
+ }
314
+ if (pendingBytes > 0) {
315
+ parts.push(Buffer.concat(pending, pendingBytes));
316
+ }
317
+ return parts;
318
+ }
319
+
320
+ // Run an array of async tasks with bounded parallelism. Preserves
321
+ // result order by index.
322
+ async function _bounded(items, concurrency, runner) {
323
+ var results = new Array(items.length);
324
+ var i = 0;
325
+ async function worker() {
326
+ while (true) {
327
+ var idx = i++;
328
+ if (idx >= items.length) return;
329
+ results[idx] = await runner(items[idx], idx);
330
+ }
331
+ }
332
+ var workers = [];
333
+ for (var w = 0; w < Math.min(concurrency, items.length); w++) {
334
+ workers.push(worker());
335
+ }
336
+ await Promise.all(workers);
337
+ return results;
338
+ }
339
+
211
340
  // ---- Public adapter factory ----
212
341
 
213
342
  function create(config) {
@@ -220,6 +349,30 @@ function create(config) {
220
349
  var endpoint = config.endpoint || ("https://s3." + config.region + ".amazonaws.com");
221
350
  if (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
222
351
  var pathStyle = !!(config.pathStyle || config.forcePathStyle);
352
+
353
+ var partSize = config.partSizeBytes != null
354
+ ? config.partSizeBytes
355
+ : DEFAULT_PART_SIZE_BYTES;
356
+ if (typeof partSize !== "number" || !isFinite(partSize) || partSize < MIN_PART_SIZE_BYTES) {
357
+ throw _err("INVALID_CONFIG",
358
+ "sigv4: partSizeBytes must be a number >= " + MIN_PART_SIZE_BYTES +
359
+ " (S3 minimum part size), got " + partSize, true);
360
+ }
361
+ var multipartThreshold = config.multipartThresholdBytes != null
362
+ ? config.multipartThresholdBytes
363
+ : DEFAULT_MULTIPART_THRESHOLD_BYTES;
364
+ if (typeof multipartThreshold !== "number" || !isFinite(multipartThreshold) || multipartThreshold < 0) {
365
+ throw _err("INVALID_CONFIG",
366
+ "sigv4: multipartThresholdBytes must be a non-negative finite number, got " +
367
+ multipartThreshold, true);
368
+ }
369
+ var partConcurrency = config.partConcurrency != null
370
+ ? config.partConcurrency
371
+ : DEFAULT_PART_CONCURRENCY;
372
+ if (typeof partConcurrency !== "number" || partConcurrency < 1 || !isFinite(partConcurrency)) {
373
+ throw _err("INVALID_CONFIG",
374
+ "sigv4: partConcurrency must be a positive finite number, got " + partConcurrency, true);
375
+ }
223
376
  // HTTPS-only by default — AWS S3, R2, MinIO-over-https. Operators with
224
377
  // an internal cleartext S3-compatible endpoint (test fixtures, local
225
378
  // dev MinIO) opt in via config.allowedProtocols.
@@ -274,19 +427,150 @@ function create(config) {
274
427
  }
275
428
 
276
429
  function put(key, body, opts) {
277
- var url = _keyToUrl(key);
430
+ opts = opts || {};
431
+ var sseRequested = _resolveSseHeaders(opts.sse);
432
+ // Streams always go multipart — size isn't known up-front. Buffers
433
+ // dispatch to multipart when they exceed the threshold; operators
434
+ // can force the single-PUT path with `multipart: false` (small
435
+ // bodies in unit tests, or to keep the request count to one).
436
+ var isStream = body && typeof body === "object" && typeof body.pipe === "function";
437
+ if (isStream) {
438
+ if (opts.multipart === false) {
439
+ return Promise.reject(_err("STREAM_REQUIRES_MULTIPART",
440
+ "put(stream) requires multipart upload (set opts.multipart !== false)", true));
441
+ }
442
+ return _multipartPut(key, body, opts, sseRequested);
443
+ }
278
444
  var buf = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : "", "utf8");
445
+ if (opts.multipart !== false &&
446
+ (opts.multipart === true || buf.length > multipartThreshold)) {
447
+ return _multipartPut(key, buf, opts, sseRequested);
448
+ }
449
+ return _singlePut(key, buf, opts, sseRequested);
450
+ }
451
+
452
+ function _singlePut(key, buf, opts, sseRequested) {
453
+ var url = _keyToUrl(key);
279
454
  var payloadHash = sha256Hex(buf);
280
- var contentType = (opts && opts.contentType) || "application/octet-stream";
281
- var headers = _makeSigned("PUT", url, payloadHash, {
455
+ var contentType = opts.contentType || "application/octet-stream";
456
+ var extra = {
282
457
  "Content-Type": contentType,
283
458
  "Content-Length": String(buf.length),
284
- });
459
+ };
460
+ if (sseRequested) Object.assign(extra, sseRequested.headers);
461
+ var headers = _makeSigned("PUT", url, payloadHash, extra);
285
462
  return _request("PUT", url, headers, buf, reqOpts).then(function (res) {
463
+ _verifySseResponse(sseRequested, res.headers);
286
464
  return { size: buf.length, etag: res.headers.etag };
287
465
  });
288
466
  }
289
467
 
468
+ async function _multipartPut(key, body, opts, sseRequested) {
469
+ var contentType = opts.contentType || "application/octet-stream";
470
+
471
+ // Slice into parts. For Buffers we slice up-front; for streams we
472
+ // read sequentially into part-sized buffers (memory bounded).
473
+ var parts;
474
+ if (Buffer.isBuffer(body)) {
475
+ parts = [];
476
+ for (var off = 0; off < body.length; off += partSize) {
477
+ parts.push(body.slice(off, Math.min(off + partSize, body.length)));
478
+ }
479
+ // Edge case: empty buffer → one zero-length part. S3 rejects
480
+ // multipart with zero parts; rather than handling this corner
481
+ // we route empty buffers through single-PUT instead.
482
+ if (parts.length === 0) parts = [Buffer.alloc(0)];
483
+ } else {
484
+ parts = await _readStreamParts(body, partSize);
485
+ if (parts.length === 0) parts = [Buffer.alloc(0)];
486
+ }
487
+ if (parts.length > MAX_PARTS) {
488
+ throw _err("TOO_MANY_PARTS",
489
+ "multipart upload would require " + parts.length + " parts " +
490
+ "(S3 max " + MAX_PARTS + "); increase partSizeBytes", true);
491
+ }
492
+
493
+ // 1. Initiate
494
+ var url = _keyToUrl(key);
495
+ var initiateUrl = new URL(url.href);
496
+ initiateUrl.searchParams.set("uploads", "");
497
+ var initiateExtra = {
498
+ "Content-Type": contentType,
499
+ "Content-Length": "0",
500
+ };
501
+ if (sseRequested) Object.assign(initiateExtra, sseRequested.headers);
502
+ var initiateHeaders = _makeSigned("POST", initiateUrl, sha256Hex(Buffer.alloc(0)), initiateExtra);
503
+ var initRes = await _request("POST", initiateUrl, initiateHeaders, Buffer.alloc(0), reqOpts);
504
+ _verifySseResponse(sseRequested, initRes.headers);
505
+ var initDoc = safeXml.parse(initRes.body, LIST_PARSE_OPTS);
506
+ var uploadId = initDoc.InitiateMultipartUploadResult &&
507
+ initDoc.InitiateMultipartUploadResult.UploadId;
508
+ if (!uploadId) {
509
+ throw _err("MULTIPART_INIT_FAILED",
510
+ "S3 InitiateMultipartUpload response missing UploadId", false);
511
+ }
512
+
513
+ var totalSize = 0;
514
+ var uploadedEtags;
515
+
516
+ try {
517
+ // 2. Upload parts (concurrency-bounded)
518
+ uploadedEtags = await _bounded(parts, partConcurrency, async function (partBuf, idx) {
519
+ var partNumber = idx + 1;
520
+ var partUrl = new URL(url.href);
521
+ partUrl.searchParams.set("partNumber", String(partNumber));
522
+ partUrl.searchParams.set("uploadId", uploadId);
523
+ var partHeaders = _makeSigned("PUT", partUrl, sha256Hex(partBuf), {
524
+ "Content-Length": String(partBuf.length),
525
+ });
526
+ var partRes = await _request("PUT", partUrl, partHeaders, partBuf, reqOpts);
527
+ if (!partRes.headers.etag) {
528
+ throw _err("MULTIPART_PART_FAILED",
529
+ "UploadPart response missing ETag for part " + partNumber, false);
530
+ }
531
+ totalSize += partBuf.length;
532
+ return { partNumber: partNumber, etag: partRes.headers.etag };
533
+ });
534
+
535
+ // 3. Complete
536
+ var completeUrl = new URL(url.href);
537
+ completeUrl.searchParams.set("uploadId", uploadId);
538
+ var completeBody = Buffer.from(_buildCompleteMultipartXml(uploadedEtags), "utf8");
539
+ var completeHeaders = _makeSigned("POST", completeUrl, sha256Hex(completeBody), {
540
+ "Content-Type": "application/xml",
541
+ "Content-Length": String(completeBody.length),
542
+ });
543
+ var completeRes = await _request("POST", completeUrl, completeHeaders, completeBody, reqOpts);
544
+ // S3 may return 200 OK with an error body on CompleteMultipartUpload —
545
+ // surface that as a hard error rather than a silent success.
546
+ var completeDoc = safeXml.parse(completeRes.body, LIST_PARSE_OPTS);
547
+ if (completeDoc.Error) {
548
+ throw _err("MULTIPART_COMPLETE_FAILED",
549
+ "CompleteMultipartUpload returned error: " +
550
+ (completeDoc.Error.Code || "unknown") + " " +
551
+ (completeDoc.Error.Message || ""), false);
552
+ }
553
+ // SSE was already verified on the InitiateMultipartUpload
554
+ // response — that's the request that establishes the upload's
555
+ // encryption policy server-side. The CompleteMultipartUpload
556
+ // response may or may not echo the header depending on vendor;
557
+ // re-verifying here would double-fault on otherwise-fine setups.
558
+ var result = completeDoc.CompleteMultipartUploadResult || {};
559
+ return { size: totalSize, etag: result.ETag || completeRes.headers.etag, multipart: true };
560
+ } catch (e) {
561
+ // Abort cleans up server-side storage for the partial upload.
562
+ // Failures here are silently swallowed — the caller's original
563
+ // error is what they need to see, not a secondary cleanup error.
564
+ try {
565
+ var abortUrl = new URL(url.href);
566
+ abortUrl.searchParams.set("uploadId", uploadId);
567
+ var abortHeaders = _makeSigned("DELETE", abortUrl, sha256Hex(Buffer.alloc(0)));
568
+ await _request("DELETE", abortUrl, abortHeaders, null, reqOpts);
569
+ } catch (_e) { /* primary error wins */ }
570
+ throw e;
571
+ }
572
+ }
573
+
290
574
  function get(key) {
291
575
  var url = _keyToUrl(key);
292
576
  var headers = _makeSigned("GET", url, sha256Hex(Buffer.alloc(0)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.4.22",
3
+ "version": "0.4.24",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",