@blamejs/blamejs-shop 0.4.85 → 0.4.86

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/lib/asset-manifest.json +1 -1
  3. package/lib/order.js +4 -2
  4. package/lib/security-middleware.js +1 -0
  5. package/lib/vendor/MANIFEST.json +71 -39
  6. package/lib/vendor/blamejs/CHANGELOG.md +2 -0
  7. package/lib/vendor/blamejs/api-snapshot.json +11 -3
  8. package/lib/vendor/blamejs/lib/atomic-file.js +34 -0
  9. package/lib/vendor/blamejs/lib/auth/fido-mds3.js +10 -0
  10. package/lib/vendor/blamejs/lib/auth/password.js +1 -0
  11. package/lib/vendor/blamejs/lib/auth/saml.js +11 -3
  12. package/lib/vendor/blamejs/lib/daemon.js +4 -1
  13. package/lib/vendor/blamejs/lib/external-db.js +131 -0
  14. package/lib/vendor/blamejs/lib/graphql-federation.js +25 -15
  15. package/lib/vendor/blamejs/lib/log-stream-cloudwatch.js +1 -0
  16. package/lib/vendor/blamejs/lib/log-stream-local.js +14 -1
  17. package/lib/vendor/blamejs/lib/log-stream-otlp.js +1 -0
  18. package/lib/vendor/blamejs/lib/log-stream-webhook.js +1 -0
  19. package/lib/vendor/blamejs/lib/mail-auth.js +69 -14
  20. package/lib/vendor/blamejs/lib/mail-bimi.js +6 -0
  21. package/lib/vendor/blamejs/lib/mail-crypto-smime.js +10 -0
  22. package/lib/vendor/blamejs/lib/mail-dkim.js +68 -15
  23. package/lib/vendor/blamejs/lib/mail.js +39 -0
  24. package/lib/vendor/blamejs/lib/middleware/api-encrypt.js +6 -2
  25. package/lib/vendor/blamejs/lib/network-dns-resolver.js +61 -11
  26. package/lib/vendor/blamejs/lib/network-dns.js +47 -2
  27. package/lib/vendor/blamejs/lib/network-nts.js +16 -0
  28. package/lib/vendor/blamejs/lib/network-proxy.js +55 -2
  29. package/lib/vendor/blamejs/lib/object-store/azure-blob-bucket-ops.js +1 -0
  30. package/lib/vendor/blamejs/lib/object-store/gcs-bucket-ops.js +1 -0
  31. package/lib/vendor/blamejs/lib/object-store/http-request.js +4 -0
  32. package/lib/vendor/blamejs/lib/outbox.js +29 -0
  33. package/lib/vendor/blamejs/lib/queue-sqs.js +1 -0
  34. package/lib/vendor/blamejs/lib/request-helpers.js +25 -6
  35. package/lib/vendor/blamejs/lib/session-device-binding.js +46 -24
  36. package/lib/vendor/blamejs/lib/session.js +85 -28
  37. package/lib/vendor/blamejs/package.json +1 -1
  38. package/lib/vendor/blamejs/release-notes/v0.15.16.json +94 -0
  39. package/lib/vendor/blamejs/test/layer-0-primitives/api-encrypt.test.js +51 -0
  40. package/lib/vendor/blamejs/test/layer-0-primitives/atomic-file-open-append-nofollow.test.js +87 -0
  41. package/lib/vendor/blamejs/test/layer-0-primitives/codebase-patterns.test.js +48 -0
  42. package/lib/vendor/blamejs/test/layer-0-primitives/external-db-non-atomic-backend.test.js +200 -0
  43. package/lib/vendor/blamejs/test/layer-0-primitives/fido-mds3-cert-bad-validity.test.js +159 -0
  44. package/lib/vendor/blamejs/test/layer-0-primitives/graphql-federation.test.js +49 -2
  45. package/lib/vendor/blamejs/test/layer-0-primitives/mail-auth-dmarc-policy-failclosed.test.js +139 -0
  46. package/lib/vendor/blamejs/test/layer-0-primitives/mail-bimi-cert-validity-unparseable.test.js +137 -0
  47. package/lib/vendor/blamejs/test/layer-0-primitives/mail-crypto-smime-bad-validity.test.js +134 -0
  48. package/lib/vendor/blamejs/test/layer-0-primitives/mail-dkim-numericdate-failclosed.test.js +155 -0
  49. package/lib/vendor/blamejs/test/layer-0-primitives/mail-proxy-framing-bounds.test.js +263 -0
  50. package/lib/vendor/blamejs/test/layer-0-primitives/network-dns-lookup-timeout-default.test.js +116 -0
  51. package/lib/vendor/blamejs/test/layer-0-primitives/network-dns-resolver-timeout.test.js +126 -0
  52. package/lib/vendor/blamejs/test/layer-0-primitives/network-nts-handshake-byte-cap.test.js +127 -0
  53. package/lib/vendor/blamejs/test/layer-0-primitives/saml-subjectconfirmation-notbefore.test.js +238 -0
  54. package/lib/vendor/blamejs/test/layer-0-primitives/session-destroy-all-store-backed.test.js +128 -0
  55. package/lib/vendor/blamejs/test/layer-0-primitives/session-device-binding-ipv6-canonical-and-no-store.test.js +202 -0
  56. package/lib/vendor/blamejs/test/layer-0-primitives/session-device-binding.test.js +18 -9
  57. package/lib/vendor/blamejs/test/layer-0-primitives/webhook-verify-nonce-atomic.test.js +169 -0
  58. package/lib/webhooks.js +38 -9
  59. package/package.json +1 -1
@@ -1102,6 +1102,11 @@ async function _fetchDmarcRecord(domain, dnsLookup) {
1102
1102
  // throw on malformed v= / unrecognized np= or psd= values rather than
1103
1103
  // silently dropping — operators with a typo'd record otherwise see the
1104
1104
  // fallback policy applied without warning.
1105
+ // RFC 7489 §6.3 — p= (and DMARCbis sp=/np=) take exactly one of
1106
+ // none|quarantine|reject. p= is REQUIRED; a record without a valid p=
1107
+ // carries no usable policy (treat as if no record were published rather
1108
+ // than defaulting any unrecognized value to "deliver").
1109
+ var DMARC_VALID_P = { none: 1, quarantine: 1, reject: 1 };
1105
1110
  var DMARCBIS_VALID_NP = { none: 1, quarantine: 1, reject: 1 };
1106
1111
  var DMARCBIS_VALID_PSD = { y: 1, n: 1, u: 1 };
1107
1112
 
@@ -1115,8 +1120,22 @@ function _parseDmarcRecord(text) {
1115
1120
  var key = pairs[i][0];
1116
1121
  var val = pairs[i][1];
1117
1122
  if (key === "v") policy.v = val;
1118
- else if (key === "p") policy.p = val.toLowerCase();
1119
- else if (key === "sp") policy.sp = val.toLowerCase();
1123
+ else if (key === "p") {
1124
+ var pVal = val.toLowerCase();
1125
+ if (!Object.prototype.hasOwnProperty.call(DMARC_VALID_P, pVal)) {
1126
+ throw new MailAuthError("mail-auth/dmarcbis-bad-tag",
1127
+ "DMARC p= must be one of none|quarantine|reject, got " + JSON.stringify(val));
1128
+ }
1129
+ policy.p = pVal;
1130
+ }
1131
+ else if (key === "sp") {
1132
+ var spVal = val.toLowerCase();
1133
+ if (!Object.prototype.hasOwnProperty.call(DMARC_VALID_P, spVal)) {
1134
+ throw new MailAuthError("mail-auth/dmarcbis-bad-tag",
1135
+ "DMARC sp= must be one of none|quarantine|reject, got " + JSON.stringify(val));
1136
+ }
1137
+ policy.sp = spVal;
1138
+ }
1120
1139
  else if (key === "pct") policy.pct = parseInt(val, 10);
1121
1140
  else if (key === "adkim") policy.adkim = val.toLowerCase();
1122
1141
  else if (key === "aspf") policy.aspf = val.toLowerCase();
@@ -1141,6 +1160,16 @@ function _parseDmarcRecord(text) {
1141
1160
  throw new MailAuthError("mail-auth/dmarc-bad-version",
1142
1161
  "DMARC record version must be DMARC1, got " + JSON.stringify(policy.v));
1143
1162
  }
1163
+ // RFC 7489 §6.3 — p= is REQUIRED. A record syntactically valid in
1164
+ // every other respect but missing p= publishes no usable policy; the
1165
+ // receiver MUST treat it as if no record were found rather than
1166
+ // synthesizing a permissive default. Fail closed here so the caller
1167
+ // can route the missing-policy case (none/permerror) instead of
1168
+ // delivering an unauthenticated message.
1169
+ if (policy.p === null) {
1170
+ throw new MailAuthError("mail-auth/dmarc-missing-policy",
1171
+ "DMARC record has no required p= tag (RFC 7489 §6.3)");
1172
+ }
1144
1173
  return policy;
1145
1174
  }
1146
1175
 
@@ -1236,7 +1265,18 @@ async function dmarcEvaluate(opts) {
1236
1265
  }
1237
1266
  }
1238
1267
  } catch (e) {
1239
- return { result: "temperror", explanation: e.message,
1268
+ // RFC 7489 §6.6.3 a syntactically invalid / policy-less record is a
1269
+ // PERMANENT error (permerror); only transient DNS resolution failures
1270
+ // are temperror. The DMARC parser raises typed MailAuthError codes for
1271
+ // the permanent cases (bad version, unrecognized tag value, missing
1272
+ // required p=); anything else (DNS lookup) is transient. Either way the
1273
+ // disposition is fail-closed — neither path yields recommendedAction
1274
+ // "deliver".
1275
+ var permanent = e && typeof e.code === "string" &&
1276
+ (e.code === "mail-auth/dmarc-bad-version" ||
1277
+ e.code === "mail-auth/dmarcbis-bad-tag" ||
1278
+ e.code === "mail-auth/dmarc-missing-policy");
1279
+ return { result: permanent ? "permerror" : "temperror", explanation: e.message,
1240
1280
  policy: null, alignment: { spf: false, dkim: false },
1241
1281
  orgDomain: orgDomain };
1242
1282
  }
@@ -1312,13 +1352,23 @@ async function dmarcEvaluate(opts) {
1312
1352
  sampleRoll = bCrypto.randomInt(0, 100); // pct sample roll
1313
1353
  }
1314
1354
  var sampled = !pass && pct < 100 && sampleRoll >= pct;
1315
- var recommendedAction = pass ? "deliver" :
1316
- sampled
1317
- ? (policy.p === "reject" ? "quarantine" :
1318
- policy.p === "quarantine" ? "none" : "deliver")
1319
- : (policy.p === "reject" ? "reject" :
1320
- policy.p === "quarantine" ? "quarantine" :
1321
- "deliver");
1355
+ // Disposition is driven by the validated p= value. policy.p is one of
1356
+ // none|quarantine|reject (the parser fails closed on anything else, so a
1357
+ // missing/typo'd policy never reaches here). "none" is monitor-only →
1358
+ // deliver; reject/quarantine map to their disposition (sampled = the
1359
+ // next-less-strict step per §6.6.4). The explicit "none" arm — rather
1360
+ // than a catch-all "else deliver" — keeps an unexpected value from
1361
+ // silently delivering a failing message.
1362
+ var recommendedAction;
1363
+ if (pass) {
1364
+ recommendedAction = "deliver";
1365
+ } else if (policy.p === "none") {
1366
+ recommendedAction = "deliver";
1367
+ } else if (sampled) {
1368
+ recommendedAction = policy.p === "reject" ? "quarantine" : "none"; // p is reject|quarantine here
1369
+ } else {
1370
+ recommendedAction = policy.p === "reject" ? "reject" : "quarantine"; // p is reject|quarantine here
1371
+ }
1322
1372
 
1323
1373
  return {
1324
1374
  result: pass ? "pass" : "fail",
@@ -1544,10 +1594,15 @@ async function arcVerify(rfc822, opts) {
1544
1594
  var asX = asTags.x ? parseInt(asTags.x, 10) : null;
1545
1595
  var skewSec = Math.floor(arcClockSkewMs / 1000); // sec divisor
1546
1596
  var timeFault = null;
1547
- if (amsT && isFinite(amsT) && amsT - skewSec > nowSec) timeFault = "ams-t-future";
1548
- if (amsX && isFinite(amsX) && amsX + skewSec < nowSec) timeFault = "ams-x-expired";
1549
- if (asT && isFinite(asT) && asT - skewSec > nowSec) timeFault = "as-t-future";
1550
- if (asX && isFinite(asX) && asX + skewSec < nowSec) timeFault = "as-x-expired";
1597
+ // RFC 8617 §5.2 a PRESENT t=/x= that is unparseable (parseInt → NaN) must
1598
+ // FAIL CLOSED (a time fault), not silently skip the future/expiry check: a
1599
+ // bare `isFinite(amsT) &&` lets a malformed timestamp slip the MUST-reject
1600
+ // gate. Gate on the RAW tag's presence (amsTags.t/x) so an unparseable value
1601
+ // becomes a fault, while an absent tag is correctly ignored.
1602
+ if (amsTags.t && (!isFinite(amsT) || amsT - skewSec > nowSec)) timeFault = isFinite(amsT) ? "ams-t-future" : "ams-t-unparseable";
1603
+ if (amsTags.x && (!isFinite(amsX) || amsX + skewSec < nowSec)) timeFault = isFinite(amsX) ? "ams-x-expired" : "ams-x-unparseable";
1604
+ if (asTags.t && (!isFinite(asT) || asT - skewSec > nowSec)) timeFault = isFinite(asT) ? "as-t-future" : "as-t-unparseable";
1605
+ if (asTags.x && (!isFinite(asX) || asX + skewSec < nowSec)) timeFault = isFinite(asX) ? "as-x-expired" : "as-x-unparseable";
1551
1606
 
1552
1607
  // AMS — RFC 8617 §5.1.1. Same shape as a DKIM-Signature; reuses
1553
1608
  // the DKIM verifier by injecting a temporary message that has
@@ -819,6 +819,12 @@ function _verifyCertChain(leaf, intermediates, anchors) {
819
819
  while (depth < MAX_DEPTH) {
820
820
  var notBefore = Date.parse(current.validFrom);
821
821
  var notAfter = Date.parse(current.validTo);
822
+ // Fail closed on a present-but-unparseable validity window: a NaN date
823
+ // would otherwise skip both window checks below and let the cert pass
824
+ // validation unchecked.
825
+ if (!isFinite(notBefore) || !isFinite(notAfter)) {
826
+ return { ok: false, reason: "cert validity dates unparseable" };
827
+ }
822
828
  if (isFinite(notBefore) && now < notBefore) {
823
829
  return { ok: false, reason: "cert not-yet-valid (notBefore=" + current.validFrom + ")" };
824
830
  }
@@ -829,6 +829,16 @@ function checkCert(opts) {
829
829
  var nowMs = Date.now();
830
830
  var notBeforeMs = Date.parse(cert.validFrom);
831
831
  var notAfterMs = Date.parse(cert.validTo);
832
+ // Fail closed on a present-but-unparseable validity field — gating
833
+ // each comparison behind isFinite() alone let a NaN notBefore /
834
+ // notAfter skip both checks and pass validity. RFC 5280 §4.1.2.5
835
+ // makes both dates mandatory; a date a peer cannot parse must be
836
+ // refused at preflight, not accepted and left to fail interop later.
837
+ if (!isFinite(notBeforeMs) || !isFinite(notAfterMs)) {
838
+ throw new MailCryptoError("mail-crypto/smime/bad-validity",
839
+ "cert has unparseable validity dates (validFrom=" + cert.validFrom +
840
+ ", validTo=" + cert.validTo + ")");
841
+ }
832
842
  if (isFinite(notBeforeMs) && nowMs < notBeforeMs) {
833
843
  throw new MailCryptoError("mail-crypto/smime/expired-cert",
834
844
  "cert is not yet valid (notBefore=" + cert.validFrom + ", now=" +
@@ -482,6 +482,36 @@ function _parseDkimTagList(value) {
482
482
  return tags;
483
483
  }
484
484
 
485
+ // RFC 6376 §3.5 — x= / t= / l= are unsigned decimal integers ("1*DIGIT").
486
+ // parseInt() is too lenient here ("12abc" → 12, "0x10" → 0, " 12" → 12),
487
+ // so a present-but-malformed value must not be coerced into a finite
488
+ // number that then passes the downstream check. Returns the parsed integer,
489
+ // or null when the value is not a well-formed unsigned integer — the caller
490
+ // fails CLOSED on null. `maxDigits` bounds the digit count (a ReDoS-free
491
+ // length cap; x=/t= are NumericDate, bounded to 12 digits).
492
+ function _parseDkimUnsignedInt(raw, maxDigits) {
493
+ if (typeof raw !== "string") return null;
494
+ var len = raw.length;
495
+ // "1*DIGIT": non-empty, ASCII 0-9 only, length-capped. A char-code scan
496
+ // (no regex) keeps this linear and avoids a dynamic RegExp / a shared
497
+ // digit-pattern literal — maxDigits bounds x=/t=/l= to their NumericDate
498
+ // / octet-count headroom.
499
+ if (len === 0 || (maxDigits && len > maxDigits)) return null;
500
+ for (var i = 0; i < len; i++) {
501
+ var c = raw.charCodeAt(i);
502
+ if (c < 0x30 || c > 0x39) return null; // not an ASCII digit
503
+ }
504
+ var n = parseInt(raw, 10);
505
+ if (!isFinite(n)) return null;
506
+ return n;
507
+ }
508
+
509
+ // x= / t= are NumericDate (seconds-since-epoch); 12 digits is ample headroom
510
+ // past any realistic epoch and keeps the parse bounded.
511
+ function _parseDkimNumericDate(raw) {
512
+ return _parseDkimUnsignedInt(raw, 12);
513
+ }
514
+
485
515
  function _selectorTxtToKeyTags(txtRecords) {
486
516
  // DKIM key record is a TXT record at <selector>._domainkey.<domain>.
487
517
  // Format: "v=DKIM1; k=rsa; p=<base64>" (chunks may be split across
@@ -694,8 +724,16 @@ function _verifySingleSignature(rfc822, parsedHeaders, sigHeader, keyTags, sigTa
694
724
  // the signature still validates against legitimate senders that
695
725
  // use l=, but flag in the result. The cap is octets of the
696
726
  // CANONICALIZED body (RFC 6376 §3.4.5), applied inside _bodyHashB64.
697
- var parsedL = parseInt(sigTags.l, 10);
698
- if (isFinite(parsedL) && parsedL >= 0) lcap = parsedL;
727
+ // l= is an unsigned decimal integer ("1*DIGIT" per §3.5); a
728
+ // present-but-unparseable value must FAIL CLOSED rather than fall
729
+ // through to lcap=undefined (hashing the whole body silently masks the
730
+ // malformed tag instead of refusing it).
731
+ var parsedL = _parseDkimUnsignedInt(sigTags.l, 18);
732
+ if (parsedL === null) {
733
+ return { result: "permerror",
734
+ errors: ["DKIM-Signature l= present but unparseable (RFC 6376 §3.5 — unsigned integer required)"] };
735
+ }
736
+ lcap = parsedL;
699
737
  }
700
738
 
701
739
  // 1. Body-hash check.
@@ -922,34 +960,49 @@ async function verify(rfc822, opts) {
922
960
  // attack). Both are in seconds-since-epoch per ABNF.
923
961
  var nowSec = Math.floor(Date.now() / C.TIME.seconds(1));
924
962
  var clockSkewSec = Math.floor(clockSkewMs / C.TIME.seconds(1));
963
+ // x= / t= are NumericDate (digits-only seconds-since-epoch per the
964
+ // §3.5 ABNF). A present-but-unparseable value must FAIL CLOSED — a NaN
965
+ // result silently skipping the expiry / future-date / ordering checks
966
+ // would let verification proceed to result:"pass" with NO expiry
967
+ // enforced (mirrors the SAML Conditions present-but-unparseable fix).
968
+ var xSec = null;
925
969
  if (sigTags.x !== undefined) {
926
- var expSec = parseInt(sigTags.x, 10);
927
- if (isFinite(expSec) && expSec + clockSkewSec < nowSec) {
970
+ xSec = _parseDkimNumericDate(sigTags.x);
971
+ if (xSec === null) {
972
+ results.push({ d: d || null, s: s || null, alg: alg || null,
973
+ result: "permerror",
974
+ errors: ["DKIM-Signature x= present but unparseable (RFC 6376 §3.5 — NumericDate required)"] });
975
+ continue;
976
+ }
977
+ if (xSec + clockSkewSec < nowSec) {
928
978
  results.push({ d: d || null, s: s || null, alg: alg || null,
929
979
  result: "permerror",
930
- errors: ["DKIM-Signature x=" + expSec + " has expired (RFC 6376 §3.5)"] });
980
+ errors: ["DKIM-Signature x=" + xSec + " has expired (RFC 6376 §3.5)"] });
931
981
  continue;
932
982
  }
933
983
  }
934
984
  if (sigTags.t !== undefined) {
935
- var tSec = parseInt(sigTags.t, 10);
985
+ var tSec = _parseDkimNumericDate(sigTags.t);
986
+ if (tSec === null) {
987
+ results.push({ d: d || null, s: s || null, alg: alg || null,
988
+ result: "permerror",
989
+ errors: ["DKIM-Signature t= present but unparseable (RFC 6376 §3.5 — NumericDate required)"] });
990
+ continue;
991
+ }
936
992
  // Allow up to 24h future-skew; beyond that, refuse — neither
937
993
  // operator clock drift nor delivery latency explains a future-
938
994
  // dated signing time of more than a day.
939
- if (isFinite(tSec) && tSec - (24 * 60 * 60) > nowSec) { // allow:raw-time-literal — 24h future-date sanity ceiling
995
+ if (tSec - (24 * 60 * 60) > nowSec) { // allow:raw-time-literal — 24h future-date sanity ceiling
940
996
  results.push({ d: d || null, s: s || null, alg: alg || null,
941
997
  result: "permerror",
942
998
  errors: ["DKIM-Signature t=" + tSec + " is more than 24h in the future (RFC 6376 §3.5 sanity)"] });
943
999
  continue;
944
1000
  }
945
- if (sigTags.x !== undefined) {
946
- var xSec = parseInt(sigTags.x, 10);
947
- if (isFinite(xSec) && isFinite(tSec) && xSec < tSec) {
948
- results.push({ d: d || null, s: s || null, alg: alg || null,
949
- result: "permerror",
950
- errors: ["DKIM-Signature x= must be after t= (RFC 6376 §3.5)"] });
951
- continue;
952
- }
1001
+ if (xSec !== null && xSec < tSec) {
1002
+ results.push({ d: d || null, s: s || null, alg: alg || null,
1003
+ result: "permerror",
1004
+ errors: ["DKIM-Signature x= must be after t= (RFC 6376 §3.5)"] });
1005
+ continue;
953
1006
  }
954
1007
  }
955
1008
  if (!d || !s) {
@@ -825,6 +825,16 @@ function smtpTransport(opts) {
825
825
  _refuseCtlBytes("host", opts.host);
826
826
  _refuseCtlBytes("servername", opts.servername);
827
827
  var timeoutMs = opts.timeoutMs || C.TIME.seconds(15);
828
+ // Absolute transaction deadline — distinct from the per-socket IDLE
829
+ // timeout above. A slow-trickle MX that emits one byte just inside
830
+ // every idle window resets socket.setTimeout forever and never
831
+ // completes; this wall-clock bound fails the whole send regardless of
832
+ // trickle. Defaults well above timeoutMs so a normal multi-round-trip
833
+ // SMTP conversation (greeting → EHLO → STARTTLS → AUTH → MAIL/RCPT →
834
+ // DATA/BDAT) never trips it.
835
+ numericBounds.requirePositiveFiniteIntIfPresent(opts.maxTransactionMs,
836
+ "smtp transport: opts.maxTransactionMs", MailError, "mail/smtp-misconfigured");
837
+ var maxTransactionMs = opts.maxTransactionMs || C.TIME.minutes(5);
828
838
  var tlsOpts = {
829
839
  rejectUnauthorized: rejectUnauthorized,
830
840
  minVersion: opts.minTlsVersion || "TLSv1.3",
@@ -875,6 +885,7 @@ function smtpTransport(opts) {
875
885
  useImplicitTLS: useImplicitTLS,
876
886
  ehloName: ehloName,
877
887
  timeoutMs: timeoutMs,
888
+ maxTransactionMs: maxTransactionMs,
878
889
  tlsOpts: tlsOpts,
879
890
  servername: servername,
880
891
  dkimSigner: opts.dkimSigner || null,
@@ -1043,6 +1054,7 @@ function _smtpSend(message, cfg) {
1043
1054
  var dataWireBytes = null; // Buffer view of dataMessage for BDAT slicing
1044
1055
  var useBdat = false; // Decided post-EHLO based on peerSupportsChunking + cfg.chunkingEnabled
1045
1056
  var bodyMode = "7BIT"; // "7BIT" / "8BITMIME" / "BINARYMIME"
1057
+ var txTimer = null; // Absolute transaction-deadline timer (cfg.maxTransactionMs)
1046
1058
 
1047
1059
  var fromAddr = _extractAddr(message.from);
1048
1060
  var toList = _toArray(message.to).map(_extractAddr);
@@ -1081,9 +1093,13 @@ function _smtpSend(message, cfg) {
1081
1093
  }
1082
1094
  }
1083
1095
 
1096
+ function clearTxTimer() {
1097
+ if (txTimer) { try { clearTimeout(txTimer); } catch (_e) { /* best-effort */ } txTimer = null; }
1098
+ }
1084
1099
  function fail(reason) {
1085
1100
  if (settled) return;
1086
1101
  settled = true;
1102
+ clearTxTimer();
1087
1103
  try { if (socket) socket.destroy(); } catch (_e) { /* socket may already be torn down */ }
1088
1104
  reject(new MailError("mail/smtp-failed",
1089
1105
  "SMTP send failed: " + reason, false));
@@ -1091,6 +1107,7 @@ function _smtpSend(message, cfg) {
1091
1107
  function done(ok, code) {
1092
1108
  if (settled) return;
1093
1109
  settled = true;
1110
+ clearTxTimer();
1094
1111
  try { socket.end(); } catch (_e) { /* socket may already be torn down */ }
1095
1112
  if (ok) resolve({ transport: "smtp", deliveredAt: Date.now(), code: code });
1096
1113
  else reject(new MailError("mail/smtp-rejected",
@@ -1149,6 +1166,16 @@ function _smtpSend(message, cfg) {
1149
1166
 
1150
1167
  function onData(data) {
1151
1168
  buffer += data;
1169
+ // Bound the framing accumulator. A hostile / broken MX that
1170
+ // streams bytes without ever sending CRLF would otherwise grow
1171
+ // `buffer` without limit and OOM the process. SMTP responses are
1172
+ // tiny per spec; the 256 KiB cap is generous headroom. Measure
1173
+ // bytes (not UTF-16 code units) so multibyte trickle can't slip a
1174
+ // larger payload past a char-length check.
1175
+ if (safeBuffer.byteLengthOf(buffer) > MAIL_RESPONSE_MAX_BYTES) {
1176
+ fail("response-too-large");
1177
+ return;
1178
+ }
1152
1179
  var lines = buffer.split("\r\n");
1153
1180
  buffer = lines.pop();
1154
1181
  for (var i = 0; i < lines.length; i++) {
@@ -1233,6 +1260,7 @@ function _smtpSend(message, cfg) {
1233
1260
  // would corrupt NUL-bearing octets in transit.
1234
1261
  if (requiresBinaryMime && !peerSupportsBinaryMime) {
1235
1262
  settled = true;
1263
+ clearTxTimer();
1236
1264
  try { socket.destroy(); } catch (_e) { /* socket may already be torn down */ }
1237
1265
  reject(new MailError("mail/binarymime-not-advertised",
1238
1266
  "message has 8-bit binary content but peer does not advertise BINARYMIME (RFC 3030 §3)",
@@ -1245,6 +1273,7 @@ function _smtpSend(message, cfg) {
1245
1273
  // cap"; -1 means "SIZE not advertised" (no precheck).
1246
1274
  if (cfg.respectPeerSize && peerSizeCap > 0 && messageWireSize > peerSizeCap) {
1247
1275
  settled = true;
1276
+ clearTxTimer();
1248
1277
  try { socket.destroy(); } catch (_e) { /* socket may already be torn down */ }
1249
1278
  reject(new MailError("mail/peer-size-exceeded",
1250
1279
  "message wire size " + messageWireSize + " bytes exceeds peer SIZE cap " +
@@ -1341,6 +1370,7 @@ function _smtpSend(message, cfg) {
1341
1370
  // the chunked-body failure mode.
1342
1371
  if (code !== 250) {
1343
1372
  settled = true;
1373
+ clearTxTimer();
1344
1374
  try { socket.destroy(); } catch (_e) { /* socket may already be torn down */ }
1345
1375
  reject(new MailError("mail/bdat-chunk-rejected",
1346
1376
  "BDAT chunk rejected (code " + code + ", offset " + bdatOffset + "/" +
@@ -1360,6 +1390,15 @@ function _smtpSend(message, cfg) {
1360
1390
  }
1361
1391
  }
1362
1392
 
1393
+ // Arm the absolute transaction deadline before opening the socket so
1394
+ // a peer that connects but then trickles (or never responds) is
1395
+ // bounded regardless of how it games the per-socket idle timer.
1396
+ // unref so a pending deadline never keeps the process alive on its own.
1397
+ txTimer = setTimeout(function () {
1398
+ fail("transaction-timeout");
1399
+ }, cfg.maxTransactionMs);
1400
+ if (txTimer && typeof txTimer.unref === "function") txTimer.unref();
1401
+
1363
1402
  try { connect(); }
1364
1403
  catch (e) { fail(e.message || String(e)); }
1365
1404
  });
@@ -1086,8 +1086,12 @@ function httpClientEncrypted(opts) {
1086
1086
  headers["Content-Type"] = "application/json";
1087
1087
 
1088
1088
  var passThrough = {};
1089
- var passable = ["allowedProtocols", "allowInternal", "idleTimeoutMs", "maxResponseBytes",
1090
- "agent", "errorClass"];
1089
+ // timeoutMs (overall wall-clock cap) and signal (caller cancellation) are
1090
+ // forwarded alongside idleTimeoutMs: without the wall-clock cap a peer that
1091
+ // trickles bytes within the idle window holds the encrypted call open
1092
+ // indefinitely (the plain request path already accepts both).
1093
+ var passable = ["allowedProtocols", "allowInternal", "timeoutMs", "idleTimeoutMs",
1094
+ "maxResponseBytes", "signal", "agent", "errorClass"];
1091
1095
  for (var i = 0; i < passable.length; i++) {
1092
1096
  if (reqOpts[passable[i]] !== undefined) passThrough[passable[i]] = reqOpts[passable[i]];
1093
1097
  }
@@ -112,6 +112,7 @@ var networkDns = require("./network-dns");
112
112
  var safeDns = require("./safe-dns");
113
113
  var safeUrl = require("./safe-url");
114
114
  var safeBuffer = require("./safe-buffer");
115
+ var safeAsync = require("./safe-async");
115
116
  var lazyRequire = require("./lazy-require");
116
117
 
117
118
  var audit = lazyRequire(function () { return require("./audit"); });
@@ -126,6 +127,14 @@ var DEFAULT_MAX_TTL_MS = C.TIME.hours(24);
126
127
  var DEFAULT_MIN_TTL_MS = C.TIME.seconds(60);
127
128
  var DEFAULT_STALE_WINDOW = C.TIME.hours(6);
128
129
  var DEFAULT_PROFILE = "strict";
130
+ // CWE-400. Per-query wall-clock deadline on the upstream transport
131
+ // lookup. A non-responsive / slow / stalling DoH endpoint (or a
132
+ // transport that sends headers then never ends the body) must not hold
133
+ // the await pending forever — every query() and every followCnames hop
134
+ // is bounded by this, and the default _wireLookup additionally tears
135
+ // the socket down (req.setTimeout) so the fd is released, not just the
136
+ // promise rejected. 10s matches a generous DoH round-trip ceiling.
137
+ var DEFAULT_TIMEOUT_MS = C.TIME.seconds(10);
129
138
  // CWE-400/770. Bound the cache so a hostile peer
130
139
  // that can drive query-name selection (e.g. inbound SMTP forwarding
131
140
  // DKIM `s=` / `d=` tag-controlled lookups) cannot inflate the Map to
@@ -168,6 +177,7 @@ var QTYPE_BY_NAME = Object.freeze({
168
177
  * maxTtlMs: number, // cap any TTL from upstream; default 24h
169
178
  * minTtlMs: number, // floor short-TTL records; default 60s
170
179
  * serveStale: number | false, // ms to retain expired entries; default 6h
180
+ * timeoutMs: number, // per-query upstream deadline; default 10s
171
181
  * transport: { lookup(name, qtype) → Promise<Buffer> }, // operator override
172
182
  * audit: b.audit namespace,
173
183
  *
@@ -187,7 +197,12 @@ function create(opts) {
187
197
  var minTtlMs = typeof opts.minTtlMs === "number" ? opts.minTtlMs : DEFAULT_MIN_TTL_MS;
188
198
  var serveStale = opts.serveStale === false ? 0 :
189
199
  typeof opts.serveStale === "number" ? opts.serveStale : DEFAULT_STALE_WINDOW;
190
- var transport = opts.transport || _defaultTransport();
200
+ var timeoutMs = typeof opts.timeoutMs === "number" ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
201
+ if (!isFinite(timeoutMs) || timeoutMs <= 0) {
202
+ throw new ResolverError("resolver/bad-input",
203
+ "create: timeoutMs must be a positive finite number");
204
+ }
205
+ var transport = opts.transport || _defaultTransport(timeoutMs);
191
206
  // Audit goes to the operator-supplied sink (opts.audit) when present, else the
192
207
  // framework chain — b.audit.namespaced no-ops if the sink has no safeEmit.
193
208
  var _baseAudit = audit().namespaced("network.dns.resolver", { sink: opts.audit });
@@ -276,10 +291,18 @@ function create(opts) {
276
291
  return _result(hit.parsed, hit.ttl, true, false, hit.validated);
277
292
  }
278
293
 
279
- // Cache miss / expired — fetch from upstream.
294
+ // Cache miss / expired — fetch from upstream, bounded by the
295
+ // per-query wall-clock deadline. withTimeout rejects the await so a
296
+ // non-responsive / stalling endpoint can't hold the request pending
297
+ // forever; the default _wireLookup also tears the socket down on its
298
+ // own req.setTimeout so the underlying fd is released.
280
299
  var wireResponse;
281
300
  try {
282
- wireResponse = await transport.lookup(name, qtype);
301
+ wireResponse = await safeAsync.withTimeout(
302
+ Promise.resolve(transport.lookup(name, qtype)),
303
+ timeoutMs,
304
+ { name: "dns-resolver:" + name + "/" + qtype }
305
+ );
283
306
  } catch (e) {
284
307
  // Upstream failure — serve stale if we have it within window.
285
308
  if (hit && serveStale > 0 && hit.staleUntil > now) {
@@ -425,13 +448,13 @@ function create(opts) {
425
448
  };
426
449
  }
427
450
 
428
- function _defaultTransport() {
451
+ function _defaultTransport(timeoutMs) {
429
452
  // Default transport — compose b.network.dns.useDnsOverHttps()'s
430
453
  // existing DoH path. We use the wire-format DoH endpoint directly
431
454
  // so the response arrives as raw bytes for safeDns parsing.
432
455
  return {
433
456
  lookup: function (name, qtype) {
434
- return _wireLookup(name, qtype);
457
+ return _wireLookup(name, qtype, timeoutMs);
435
458
  },
436
459
  };
437
460
  }
@@ -440,7 +463,9 @@ function _defaultTransport() {
440
463
  // existing DoH path. Returns the raw response bytes for safeDns to
441
464
  // parse. Distinct from the existing network-dns DoH path which returns
442
465
  // already-decoded address strings — we need the raw bytes here.
443
- async function _wireLookup(name, qtype) {
466
+ async function _wireLookup(name, qtype, timeoutMs) {
467
+ var ms = typeof timeoutMs === "number" && isFinite(timeoutMs) && timeoutMs > 0
468
+ ? timeoutMs : DEFAULT_TIMEOUT_MS;
444
469
  var url = networkDns._getDohUrlForTest ? networkDns._getDohUrlForTest() : "https://cloudflare-dns.com/dns-query";
445
470
  // Encode a wire-format query for the target qtype.
446
471
  var qbuf = _encodeWireQuery(name, qtype);
@@ -448,6 +473,18 @@ async function _wireLookup(name, qtype) {
448
473
  var getUrl = url + (url.indexOf("?") === -1 ? "?" : "&") + "dns=" + b64;
449
474
  var u = safeUrl.parse(getUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS });
450
475
  return new Promise(function (resolve, reject) {
476
+ var settled = false;
477
+ function _fail(err) {
478
+ if (settled) return;
479
+ settled = true;
480
+ try { req.destroy(); } catch (_e) { /* best-effort socket teardown */ }
481
+ reject(err);
482
+ }
483
+ function _done(buf) {
484
+ if (settled) return;
485
+ settled = true;
486
+ resolve(buf);
487
+ }
451
488
  // Raw DoH wire-format request — bypasses b.httpClient envelope
452
489
  // because we need the raw binary response bytes for safeDns to
453
490
  // parse (httpClient assumes JSON/text shapes).
@@ -470,18 +507,31 @@ async function _wireLookup(name, qtype) {
470
507
  res.on("data", function (c) { if (!pushFailed) { try { collector.push(c); } catch (e) { pushFailed = e; } } });
471
508
  res.on("end", function () {
472
509
  try {
473
- if (pushFailed) { reject(pushFailed); return; }
510
+ if (pushFailed) { _fail(pushFailed); return; }
474
511
  if (res.statusCode !== 200) { // HTTP 200 OK
475
- reject(new ResolverError("resolver/upstream-http",
512
+ _fail(new ResolverError("resolver/upstream-http",
476
513
  "DoH HTTP " + res.statusCode + " for " + name));
477
514
  return;
478
515
  }
479
- resolve(collector.result());
480
- } catch (e) { reject(e); }
516
+ _done(collector.result());
517
+ } catch (e) { _fail(e); }
481
518
  });
482
519
  });
520
+ // Wall-clock / idle deadline — a DoH endpoint that accepts the
521
+ // connection, sends 200 headers, then never ends the body would
522
+ // otherwise hold the socket (and its fd) open indefinitely. setTimeout
523
+ // arms on socket inactivity; on fire we tear the socket down AND reject
524
+ // so neither the promise nor the fd leaks (CWE-400 slowloris-style).
525
+ req.setTimeout(ms, function () {
526
+ _fail(new ResolverError("resolver/upstream-timeout",
527
+ "DoH request to " + u.hostname + " for " + name + " exceeded " + ms + "ms"));
528
+ });
529
+ req.on("timeout", function () {
530
+ _fail(new ResolverError("resolver/upstream-timeout",
531
+ "DoH request to " + u.hostname + " for " + name + " exceeded " + ms + "ms"));
532
+ });
483
533
  req.on("error", function (e) {
484
- reject(new ResolverError("resolver/upstream-failed",
534
+ _fail(new ResolverError("resolver/upstream-failed",
485
535
  "DoH request failed: " + e.message));
486
536
  });
487
537
  req.end();