@blamejs/core 0.16.34 → 0.16.36

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,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.16.x
10
10
 
11
+ - v0.16.36 (2026-07-16) — **DKIM simple header canonicalization now signs and verifies the DKIM-Signature header verbatim, so simple-canon signatures round-trip and interoperate.** b.mail.dkim's simple header canonicalization (c=simple/... in a signature) signs and verifies each header exactly as it appears on the wire, per RFC 6376 §3.4.1. Two defects broke that for the DKIM-Signature header itself: the signer canonicalized the header UNFOLDED while emitting it FOLDED on the wire, and the verifier prefixed a spurious extra space to the parsed header value. Together they meant a simple-header-canonicalization signature never matched the bytes that were signed -- neither the framework's own signatures nor an RFC-compliant peer's would verify under simple canon. The signer now canonicalizes and emits the same folded header (appending the signature to the folded, b-emptied form), and the verifier canonicalizes the parsed header verbatim, so a simple-canon signature round-trips and is byte-compatible with other implementations. Relaxed canonicalization, the common default, is unchanged. Separately, a supply-chain gate now fails the build if a vendored component in lib/vendor/MANIFEST.json has no attribution entry in NOTICE. **Added:** *b.safeBuffer.byteLengthOfIfMeasurable — measure a value's byte length, or null when it is not a byte carrier* — byteLengthOfIfMeasurable(value) returns the byte length of a string, Buffer, or Uint8Array, and null for anything else (a plain Array, an array-like object, a number, null). It is the safe way to cap the size of an untrusted metadata bag whose byte field may be any shape: measure the cap only when the value is measurable, rather than gating byteLengthOf (which throws on a non-byte-carrier) on a hand-rolled length check that admits array-likes and crashes. The image and PDF content guards now compose it for their byte caps instead of each vetting the type inline. **Fixed:** *DKIM simple header canonicalization signs and verifies the DKIM-Signature header verbatim* — Under simple header canonicalization (RFC 6376 §3.4.1) the DKIM-Signature header is signed and verified byte-for-byte as it appears on the wire, including its folding. b.mail.dkim canonicalized the header UNFOLDED when computing the signature but emitted it FOLDED on the wire, and the verifier prepended an extra space to the parsed header value before canonicalizing -- so the bytes signed never matched the bytes verified. A simple-header-canonicalization signature therefore never verified, whether produced by the framework or by an RFC-compliant peer. The signer now canonicalizes the folded, b-emptied header and builds the wire header by appending the signature to it, and the verifier canonicalizes the parsed (folded) header verbatim -- including the DKIM-Signature field name exactly as it appears on the wire, so a peer that signs a lowercase dkim-signature: field name also verifies -- so a simple-canon signature round-trips and interoperates. This was fail-closed -- a broken simple-canon signature was reported as a verification failure, never a false pass -- and relaxed canonicalization (the common default, which normalizes folding and whitespace on both sides) was and remains correct. **Detectors:** *Every vendored component in the manifest must be attributed in NOTICE* — A gate fails the build when a component recorded in lib/vendor/MANIFEST.json has no attribution entry in the NOTICE file. Third-party components ship with their license and attribution obligations; this catches a vendored library or data file added to the manifest without its NOTICE entry before the package is published, rather than after a downstream scanner flags the omission.
12
+
13
+ - v0.16.35 (2026-07-16) — **A resumed saga that later fails now compensates the steps it completed before the crash, and a webhook delivery retries a transient DNS failure during its safety re-check instead of dead-lettering.** Two durability fixes in the agent orchestration and webhook delivery primitives. b.agent.saga rebuilt its completed-step list from empty when a saga resumed from a persisted checkpoint, so a failure after the resume compensated only the steps that ran in that resumed pass -- the steps completed before the crash were never rolled back, defeating the saga's whole purpose (a charge committed before the crash would never be refunded when a later step failed). Resume now seeds the completed-step list with the steps that finished before the crash, so a failure compensates the full set in reverse order. Separately, b.webhook.dispatcher re-checks a delivery's destination for an SSRF rebind just before each attempt; that check resolves the destination host, and a transient resolver failure (a temporary DNS error) during it was treated as a permanent failure and dead-lettered the delivery on the first attempt. The re-check now dead-letters only a genuine SSRF refusal or malformed URL and treats a transient resolver fault as retryable, like every other transport error. **Added:** *b.webhook.dispatcher accepts a dnsLookup override for the destination SSRF check* — b.webhook.dispatcher now accepts an optional dnsLookup(host) resolver, forwarded to the SSRF destination check, so an operator can point destination resolution at a specific resolver (and a test can drive the transient-versus-permanent classification offline). It defaults to the framework's DNS-over-TLS resolver, unchanged. **Fixed:** *A resumed saga compensates the steps it completed before the crash, not only those in the resumed run* — b.agent.saga runs a sequence of steps and, on a step failure, compensates the completed steps in reverse order. When a saga resumed from a persisted checkpoint, it started its completed-step list empty, so a failure after the resume compensated only the steps that ran in the resumed pass -- the steps completed before the crash were left uncompensated. For a distributed transaction that is the exact failure the pattern exists to prevent: work committed before the crash (a charge, a reservation, an external call) would never be rolled back when a later step failed. Resume now seeds the completed-step list with the steps that finished before the crash, reconstructed from the saga definition, so a subsequent failure compensates the full completed set in reverse; compensation runs against the resumed state, which already reflects those steps' effects, and the failing step itself is not compensated. To keep that reseeding safe against replay, resume also refuses a saga the state store marks terminal (failed-and-compensated or completed) rather than re-running its compensators, and the state-store interface documents that compensators must be idempotent -- a crash mid-compensation can replay a compensation on the next resume, so compensating twice must be safe. · *Webhook delivery retries a transient DNS failure during its SSRF re-check instead of dead-lettering* — b.webhook.dispatcher re-validates a delivery's destination against SSRF (private / loopback / metadata IPs, or a rebind since registration) just before each attempt, which resolves the destination host. A transient resolver failure during that resolution -- a lookup timeout or system/resolve failure -- was caught and marked a permanent failure, dead-lettering the delivery on its first attempt rather than retrying. The re-check now classifies the failure: a genuine SSRF refusal or malformed URL dead-letters, a resolver failure honors the framework DNS resolver's own terminal-versus-transient verdict (a permanent failure such as a host with no addresses or a removed record dead-letters immediately, a transient one is retried on the backoff curve, capped at maxAttempts), matching how the dispatcher already treats a transient DNS error during the delivery POST itself. So a webhook is no longer lost to a momentary DNS blip, a genuine rebind to an internal address is still dead-lettered immediately, and a permanently unresolvable destination dead-letters without burning every retry attempt.
14
+
11
15
  - v0.16.34 (2026-07-16) — **The DPoP middleware returns the correct multiple-proof rejection when a request carries a repeated DPoP header, instead of mislabeling it as a missing proof.** RFC 9449 §4.1 permits only one DPoP header value per request. b.middleware.dpop rejected a request that carried the header as an array -- repeated DPoP: lines a custom server or proxy did not collapse -- but its array-shape check sat after the missing-header guard, and an array is not a string, so the missing-header guard always ran first. A duplicated DPoP proof was therefore rejected as a missing proof (and, when a DPoP nonce was required, answered with use_dpop_nonce, prompting the client into a pointless nonce-retry loop) rather than with the invalid_dpop_proof / multiple-DPoP-headers rejection the specification calls for. Both paths already refused the request, so this was never a fail-open -- only an incorrect diagnostic and a wasted round trip. The array-shape check now runs before the missing-header guard, so a repeated DPoP header is rejected with the correct error. **Fixed:** *DPoP middleware rejects a repeated DPoP header with the correct multiple-proof error* — b.middleware.dpop enforces the RFC 9449 §4.1 single-value rule, but its Array.isArray check for a repeated header (when a server or proxy delivered the DPoP header as an array rather than a comma-joined string) sat after the non-string / empty guard. Because an array fails the non-string check first, the dedicated multiple-DPoP-headers branch never ran: a duplicated proof was reported as a missing DPoP header, and under a required-nonce policy it returned use_dpop_nonce, driving the client into a fruitless nonce-retry loop. The array-shape check now runs first, so a repeated DPoP header is rejected with invalid_dpop_proof and a multiple-DPoP-headers message. This changes only the error code and message for that malformed-request case; both orderings already refused the request, so no valid request is affected.
12
16
 
13
17
  - v0.16.33 (2026-07-16) — **Agent-snapshot restore now authenticates a sealed snapshot's tenant and capture-time against its signature, closing a cross-tenant restore path, alongside fail-closed and never-throw hardening across the DKIM/ARC, crypto-envelope, and image/PDF verifiers.** A sealed agent snapshot's authenticated envelope binds its table, snapshot id, and schema version, but the decorative wrapper fields a hostile or compromised storage backend can rewrite -- the tenant id that loadLatest filters on and the capture time it sorts on -- were trusted without being checked against the signed body. b.agent.snapshot restore now cross-checks both wrapper fields against the signature-covered values and refuses a mismatch, so a relabelled row can no longer surface one tenant's authentic snapshot to another (cross-tenant restore) or misrepresent when the restored state was captured. The release also hardens several verifiers that a valid-but-unusual or hostile input could push off their documented contract: the DKIM, inbound-authentication, and ARC verifiers now accept a bare-LF (Unix line-ending) message and return an authentication verdict instead of throwing; the crypto envelope and packed-secret decoders reject a truncated ciphertext with their typed error instead of leaking a raw cipher exception; the image guard routes a byte-order-mark-prefixed SVG to refusal at every profile instead of serving it as unknown content; and the image and PDF guards no longer throw on a hostile metadata bag whose bytes field is an array-like object, honoring their never-throw inspection contract. **Fixed:** *DKIM, inbound-authentication, and ARC verifiers accept bare-LF messages instead of throwing* — b.mail.dkim.verify, b.mail.inbound.verify, and b.mail.arc.verify canonicalize over CRLF and split the header block on a CRLF-CRLF separator. A message read from a Unix file or mbox, or passed through operator tooling that stripped carriage returns, arrives with bare-LF line endings and previously raised an uncaught error out of the verifier rather than returning an authentication verdict. The header/body split now normalizes bare-LF to canonical CRLF before locating the separator (a no-op on a proper CRLF message), so a bare-LF message produces a verdict -- and a message signed on the CRLF wire but transported bare-LF now verifies correctly rather than failing. inbound.verify and arc.verify additionally treat a message with no separator at all as headers-only, returning a verdict in keeping with their always-return-a-verdict contract. · *Crypto envelope and packed-secret decoders reject truncated ciphertext with a typed error* — b.crypto.decryptEnvelope and b.crypto.decryptPacked verify that each declared component of an untrusted ciphertext -- the length-prefixed KEM ciphertext and hybrid ephemeral public key, and the trailing nonce and authentication tag -- fits within the envelope before handing it to the cipher or the key-agreement step. A ciphertext truncated inside any of those components previously reached Node crypto as an under-length value and surfaced as a raw exception (a cipher RangeError on the nonce, or a Failed to perform decapsulation / key-parse error on the KEM ciphertext or ephemeral key), escaping the documented Invalid envelope error contract and leaking implementation detail. Both decoders now reject a truncated input with their typed Invalid envelope / Invalid packed format error, while a truncation inside the ciphertext body still surfaces as the genuine authentication-tag failure; a well-formed input is never affected. · *Image guard routes a BOM-prefixed SVG to refusal at every profile* — b.guardImage detects SVG by its leading markup so it can route it to the SVG guard or refuse it. A UTF-8 byte-order-mark before the markup previously defeated the offset-anchored signature scan, so a BOM-prefixed SVG fell through as unknown content -- served rather than refused under the balanced and permissive profiles. The magic-byte scanner now skips a leading BOM when matching the SVG and XML signatures, so a BOM-prefixed SVG is detected and refused at every profile. The BOM skip applies only to those text-family signatures: a binary raster's magic must sit at its real offset, so a BOM-prefixed PNG or JPEG is still refused as unknown content rather than accepted as a valid raster. · *Image and PDF guards no longer throw on a hostile array-like metadata bag* — b.guardImage.validate and b.guardPdf.validate document pure inspection that never throws on hostile metadata. Their byte-size cap measured any value carrying a numeric length, but the measurement primitive accepts only strings, Buffers, and Uint8Arrays and threw on a plain Array or array-like object -- crashing a direct validate or sanitize caller (the gate path already fails closed). The cap now measures only those byte-carrying types and passes an unmeasurable array-like through to magic detection, which reads only the leading bytes and refuses unrecognized content, so validate returns a refusal instead of throwing. **Security:** *Agent-snapshot restore binds the requested tenant and capture-time to the sealed snapshot's signature* — b.agent.snapshot seals each snapshot under an authenticated envelope whose AAD binds the table, snapshot id, and schema version. The metadata a backend stores alongside the sealed blob -- the tenant id that loadLatest({ tenantId }) filters on and the takenAt it sorts on to pick the latest -- is not covered by that AAD, and a hostile or compromised backend can return independently tampered list() and get() results. A backend could therefore relabel tenant A's list() entry as tenant B (leaving A's get() row honest) so that loadLatest({ tenantId: 'tenant-b' }) selected and returned tenant A's authentic snapshot -- a cross-tenant restore of in-flight sagas, streams, and idempotency state -- or inflate a row's list() age to serve an older snapshot as the latest. loadLatest now binds the requested selection criteria to the loaded snapshot's signature-covered values: the authenticated tenant id must equal the requested tenant id, and the list() sort key that selected a row must equal that row's authenticated capture time; a divergence is refused (agent-snapshot/tenant-id-mismatch, agent-snapshot/taken-at-mismatch), and the load path additionally cross-checks the get() wrapper against the signed body. The fix is at load time and does not change the seal format, so previously persisted snapshots remain restorable. A hostile backend can still withhold snapshots it never reveals, but every snapshot returned is authentic and bound to the requested tenant. **Detectors:** *A byte-size cap must vet its input type before measuring it* — A codebase-patterns gate refuses a guard that measures a metadata bag's byte length gated only on a numeric length property -- the shape that let an array-like bytes field crash the image and PDF guards. A byte-size cap over untrusted metadata must confirm the value is a string, Buffer, or Uint8Array before measuring it, so a future guard cannot reintroduce the never-throw-contract violation.
package/lib/agent-saga.js CHANGED
@@ -115,10 +115,15 @@ function create(config) {
115
115
  // Interface: { saveStep, loadResumePoint, markCompleted, markFailed }.
116
116
  // saveStep({sagaId, stepIndex, stepName, state, status}) commits
117
117
  // after each step.run; loadResumePoint(sagaId) returns the resume
118
- // shape `{ stepIndex, state }` on restart. Without a stateStore, the
119
- // saga still runs end-to-end in-memory but a mid-saga crash loses
120
- // progress (operator-acknowledged dev mode; the audit emit
121
- // `agent.saga.no_state_store` surfaces the posture per call).
118
+ // shape `{ stepIndex, state }` on restart and, for a saga that already
119
+ // reached a terminal state, SHOULD set `terminal: true` (or return null)
120
+ // after markFailed / markCompleted so a resume of a failed-and-compensated
121
+ // (or completed) saga is refused rather than replayed. Compensators MUST be
122
+ // idempotent: a crash mid-compensation-cascade (before markFailed persists)
123
+ // can replay a compensation on the next resume, so compensating twice must be
124
+ // safe. Without a stateStore, the saga still runs end-to-end in-memory but a
125
+ // mid-saga crash loses progress (operator-acknowledged dev mode; the audit
126
+ // emit `agent.saga.no_state_store` surfaces the posture per call).
122
127
  var stateStore = config.stateStore || null;
123
128
  if (stateStore !== null) {
124
129
  validateOpts.requireMethods(stateStore, ["saveStep", "loadResumePoint"],
@@ -147,6 +152,21 @@ async function _resume(config, auditImpl, stateStore, sagaId, ctx, opts) {
147
152
  throw new AgentSagaError("agent-saga/not-found",
148
153
  "resume: no resume point for saga '" + sagaId + "'");
149
154
  }
155
+ // A saga that already reached a terminal state — failed-and-compensated, or
156
+ // completed — must NOT be resumed. Replaying it re-runs the remaining steps
157
+ // AND, on a failure, re-invokes the completed steps' compensators (including
158
+ // the pre-crash steps this run seeds); compensators are not required to be
159
+ // idempotent, so a second compensation could corrupt external state (a double
160
+ // refund). A well-behaved stateStore marks the saga terminal via markFailed /
161
+ // markCompleted and reflects it here (resumePoint.terminal); refuse the resume
162
+ // when it does. The residual window — a crash after a compensation but before
163
+ // markFailed — is inherent at-least-once compensation and is why compensators
164
+ // MUST be idempotent (see the interface note on create()).
165
+ if (resumePoint.terminal === true) {
166
+ throw new AgentSagaError("agent-saga/not-resumable",
167
+ "resume: saga '" + sagaId + "' is terminal and cannot be resumed — " +
168
+ "replaying a failed/completed saga would re-invoke its compensators");
169
+ }
150
170
  return _runFrom(config, auditImpl, stateStore, ctx,
151
171
  resumePoint.state || {}, opts, sagaId, resumePoint.stepIndex);
152
172
  }
@@ -158,11 +178,19 @@ async function _run(config, auditImpl, stateStore, ctx, initialState, opts) {
158
178
  }
159
179
 
160
180
  async function _runFrom(config, auditImpl, stateStore, ctx, state, opts, sagaId, startIndex) {
161
- // completedSteps captures index + step reference. On resume we
162
- // start mid-saga; prior steps are already committed and don't need
163
- // compensation on a failure in this run (compensation cascades
164
- // walked persistent state to find the prior completed set).
181
+ // completedSteps captures index + step reference for the reverse-order
182
+ // compensation cascade. On resume (startIndex > 0) the steps before
183
+ // startIndex were completed and committed BEFORE the crash; a failure in
184
+ // this run must still compensate them, or a saga that resumes and then
185
+ // fails leaves its pre-crash work uncompensated (a broken distributed-
186
+ // transaction guarantee — e.g. a charge committed pre-crash is never
187
+ // refunded when a later step fails). Seed those prior steps so the cascade
188
+ // unwinds the FULL completed set, not only this run's steps. Compensation
189
+ // runs against the resumed state, which already reflects their effects.
165
190
  var completedSteps = [];
191
+ for (var pre = 0; pre < startIndex; pre += 1) {
192
+ completedSteps.push({ step: config.steps[pre], index: pre });
193
+ }
166
194
 
167
195
  if (startIndex === 0) {
168
196
  agentAudit.safeAudit(auditImpl, "agent.saga.started", opts.actor, {
@@ -194,15 +194,15 @@ function _detectIssues(metadata, opts) {
194
194
  snippet: "image metadata is not an object" }];
195
195
  }
196
196
 
197
- // Measure the byte cap only for the types safeBuffer.byteLengthOf accepts
198
- // (string / Buffer / Uint8Array). A hostile bag whose `bytes` is a plain
199
- // Array or an array-like object still carries a numeric `.length` but is NOT
200
- // measurable measuring it threw TypeError, breaking validate's documented
201
- // never-throw contract. Skip the cap for those (magic detection below is
202
- // O(1)-bounded regardless of size) instead of crashing the caller.
197
+ // Measure the byte cap only for measurable values. A hostile bag whose
198
+ // `bytes` is a plain Array or array-like object carries a numeric `.length`
199
+ // but is NOT a byte-carrier measuring it would throw, breaking validate's
200
+ // documented never-throw contract; byteLengthOfIfMeasurable returns null for
201
+ // those, so the cap is skipped (magic detection below is O(1)-bounded
202
+ // regardless of size) instead of crashing the caller.
203
203
  var bytes = metadata.bytes;
204
- if (bytes && (Buffer.isBuffer(bytes) || typeof bytes === "string" || bytes instanceof Uint8Array) &&
205
- safeBuffer.byteLengthOf(bytes) > opts.maxBytes) {
204
+ var byteCount = safeBuffer.byteLengthOfIfMeasurable(bytes);
205
+ if (byteCount !== null && byteCount > opts.maxBytes) {
206
206
  return [{ kind: "image-cap", severity: "high",
207
207
  ruleId: "image.image-cap",
208
208
  snippet: "image bytes exceed maxBytes " + opts.maxBytes }];
package/lib/guard-pdf.js CHANGED
@@ -156,16 +156,16 @@ function _detectIssues(metadata, opts) {
156
156
  snippet: "pdf metadata is not an object" }];
157
157
  }
158
158
 
159
- // Measure the byte cap only for the types safeBuffer.byteLengthOf accepts
160
- // (string / Buffer / Uint8Array). A hostile bag whose `bytes` is a plain
161
- // Array or an array-like object still carries a numeric `.length` but is NOT
162
- // measurable measuring it threw TypeError, breaking validate's documented
163
- // never-throw-on-hostile-metadata contract. Skip the cap for those (magic
164
- // detection reads only the leading bytes, O(1)-bounded regardless of the
165
- // reported size) instead of crashing the caller.
159
+ // Measure the byte cap only for measurable values. A hostile bag whose
160
+ // `bytes` is a plain Array or array-like object carries a numeric `.length`
161
+ // but is NOT a byte-carrier measuring it would throw, breaking validate's
162
+ // documented never-throw-on-hostile-metadata contract; byteLengthOfIfMeasurable
163
+ // returns null for those, so the cap is skipped (magic detection reads only
164
+ // the leading bytes, O(1)-bounded regardless of the reported size) instead of
165
+ // crashing the caller.
166
166
  var bytes = metadata.bytes;
167
- if (bytes && (Buffer.isBuffer(bytes) || typeof bytes === "string" || bytes instanceof Uint8Array) &&
168
- safeBuffer.byteLengthOf(bytes) > opts.maxBytes) {
167
+ var byteCount = safeBuffer.byteLengthOfIfMeasurable(bytes);
168
+ if (byteCount !== null && byteCount > opts.maxBytes) {
169
169
  return [{ kind: "pdf-cap", severity: "high",
170
170
  ruleId: "pdf.pdf-cap",
171
171
  snippet: "pdf bytes exceed maxBytes " + opts.maxBytes }];
package/lib/mail-dkim.js CHANGED
@@ -413,18 +413,42 @@ function create(opts) {
413
413
  });
414
414
  } catch (_e) { /* drop-silent */ }
415
415
  }
416
- // Append the unsigned DKIM-Signature header without trailing CRLF
417
- // per RFC 6376 §3.7.
418
- var dkimHeaderForSigning = canonHeader === "simple"
419
- ? _canonHeaderSimple("DKIM-Signature", " " + unsignedSigValue)
420
- : _canonHeaderRelaxed("DKIM-Signature", unsignedSigValue);
416
+ // Append the unsigned DKIM-Signature header (b= value emptied) without a
417
+ // trailing CRLF per RFC 6376 §3.7. Under SIMPLE header canonicalization the
418
+ // header is signed and verified BYTE-FOR-BYTE as it appears on the wire —
419
+ // including its folding so the signer must canonicalize the FOLDED form,
420
+ // exactly as the verifier does when it strips b= from the parsed (folded)
421
+ // wire header. (Relaxed unfolds on both sides, so it signs the unfolded
422
+ // value.) The empty-b header folds identically to the final header up to the
423
+ // last `b=` line (folding breaks only at "; " tag boundaries and b= is the
424
+ // last tag), so we can build the wire header by appending the signature to
425
+ // this folded empty-b header, and the verifier recovers exactly these bytes.
426
+ var foldedEmptyB = _foldSignatureHeader(unsignedSigValue);
427
+ var dkimHeaderForSigning;
428
+ if (canonHeader === "simple") {
429
+ // Simple canon is verbatim (RFC 6376 §3.4.1): the canonical form of the
430
+ // DKIM-Signature header (b= emptied) is the folded wire header exactly as
431
+ // it will appear — which is precisely foldedEmptyB ("DKIM-Signature: " +
432
+ // the folded, b-emptied value). No re-spacing or re-canonicalization.
433
+ dkimHeaderForSigning = foldedEmptyB;
434
+ } else {
435
+ dkimHeaderForSigning = _canonHeaderRelaxed("DKIM-Signature", unsignedSigValue);
436
+ }
421
437
  canonicalizedHeaders += dkimHeaderForSigning.replace(/\r\n$/, "");
422
438
 
423
439
  var signature = _signString(canonicalizedHeaders, keyObject, algorithm);
424
- // Replace the empty `b=` placeholder with the actual base64 signature.
425
- var finalSigValue = sigTags.slice(0, -1).concat(["b=" + signature]).join("; ");
426
440
 
427
- var dkimHeaderLine = _foldSignatureHeader(finalSigValue) + "\r\n";
441
+ // Wire header. Under simple canon, append the signature to the SAME folded
442
+ // empty-b header we signed, so a verifier parsing the folded wire and
443
+ // stripping b= reconstructs the signed bytes exactly. Under relaxed, re-fold
444
+ // the completed value (folding is normalized away on verify).
445
+ var dkimHeaderLine;
446
+ if (canonHeader === "simple") {
447
+ dkimHeaderLine = foldedEmptyB + signature + "\r\n";
448
+ } else {
449
+ var finalSigValue = sigTags.slice(0, -1).concat(["b=" + signature]).join("; ");
450
+ dkimHeaderLine = _foldSignatureHeader(finalSigValue) + "\r\n";
451
+ }
428
452
 
429
453
  _emit("dkim.sign.success", {
430
454
  bodyLength: body.length,
@@ -816,13 +840,23 @@ function _verifySingleSignature(rfc822, parsedHeaders, sigHeader, keyTags, sigTa
816
840
  // structure instead.
817
841
  var unsignedSigValue = _stripBTagValue(sigHeader.value);
818
842
  // The signature header is canonicalized under its true field name (§3.7).
819
- // For the ARC reuse the header on the wire is ARC-Message-Signature, signed
820
- // under that name; the synthetic renames it to DKIM-Signature only so this
821
- // verifier finds it, so the canonical form must restore the real name or the
822
- // b= value never matches what the relay signed.
823
- var sigCanonName = verifyOpts.arcAmsReuse ? "ARC-Message-Signature" : "DKIM-Signature";
843
+ // Under simple canon the name is verbatim, so it must be the EXACT on-wire
844
+ // spelling the peer signed (sigHeader.name _findDkimSignatureHeaders matches
845
+ // the field name case-insensitively and _parseHeaders preserves its casing),
846
+ // not a hardcoded "DKIM-Signature"; a peer that emits `dkim-signature:` signs
847
+ // that lowercase name and would otherwise never verify. (Relaxed canon
848
+ // lowercases the name, so the on-wire spelling doesn't matter there.) For the
849
+ // ARC reuse the header on the wire is ARC-Message-Signature, signed under that
850
+ // name; the synthetic renames it to DKIM-Signature only so this verifier finds
851
+ // it, so the canonical form must restore the real ARC name.
852
+ var sigCanonName = verifyOpts.arcAmsReuse ? "ARC-Message-Signature" : sigHeader.name;
853
+ // Simple canon is verbatim: the parsed sigHeader.value already carries the
854
+ // single space the wire places after the colon and its folding, so it is
855
+ // canonicalized as-is (b= emptied) — NOT re-spaced. (A prior `" " +` prefix
856
+ // here injected a spurious second space, so simple-canon signatures — ours
857
+ // and any RFC-compliant peer's — never matched what was signed.)
824
858
  canonicalizedHeaders += canonHeader === "simple"
825
- ? _canonHeaderSimple(sigCanonName, " " + unsignedSigValue).replace(/\r\n$/, "")
859
+ ? _canonHeaderSimple(sigCanonName, unsignedSigValue).replace(/\r\n$/, "")
826
860
  : _canonHeaderRelaxed(sigCanonName, unsignedSigValue).replace(/\r\n$/, "");
827
861
 
828
862
  // 3. Verify the signature.
@@ -366,6 +366,38 @@ function byteLengthOf(value, encoding) {
366
366
  "Buffer, or Uint8Array; got " + (value === null ? "null" : typeof value));
367
367
  }
368
368
 
369
+ /**
370
+ * @primitive b.safeBuffer.byteLengthOfIfMeasurable
371
+ * @signature b.safeBuffer.byteLengthOfIfMeasurable(value)
372
+ * @since 0.16.36
373
+ * @related b.safeBuffer.byteLengthOf
374
+ *
375
+ * Like `byteLengthOf`, but returns `null` for a value that is not a
376
+ * measurable byte-carrier (a plain `Array`, an array-like object with a
377
+ * numeric `.length`, a number, ...) instead of throwing.
378
+ *
379
+ * For capping the size of an UNTRUSTED metadata bag whose byte field may be
380
+ * any shape: a content guard measures its cap only when the value is
381
+ * measurable and treats an unmeasurable value as uncapped-here — its
382
+ * magic/shape inspection reads only the leading bytes, so it is O(1)-bounded
383
+ * regardless of a claimed `.length` — rather than throwing out of its
384
+ * documented never-throw-on-hostile-metadata inspection contract. Route a
385
+ * hostile-metadata byte cap through this instead of gating `byteLengthOf` on
386
+ * a hand-rolled `typeof x.length === "number"` check (which admits array-likes
387
+ * and crashes `byteLengthOf`).
388
+ *
389
+ * @example
390
+ * var b = require("blamejs");
391
+ * b.safeBuffer.byteLengthOfIfMeasurable("abc"); // → 3
392
+ * b.safeBuffer.byteLengthOfIfMeasurable([1, 2, 3]); // → null (a plain Array)
393
+ * b.safeBuffer.byteLengthOfIfMeasurable({ length: 1e9 }); // → null (array-like)
394
+ */
395
+ function byteLengthOfIfMeasurable(value) {
396
+ if (typeof value === "string") return Buffer.byteLength(value, "utf8");
397
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) return value.length;
398
+ return null;
399
+ }
400
+
369
401
  // ---- boundedChunkCollector ----
370
402
  //
371
403
  // Replaces the unbounded `chunks.push(c); ... Buffer.concat(chunks)`
@@ -912,6 +944,7 @@ module.exports = {
912
944
  toBuffer: toBuffer,
913
945
  makeByteCoercer: makeByteCoercer,
914
946
  byteLengthOf: byteLengthOf,
947
+ byteLengthOfIfMeasurable: byteLengthOfIfMeasurable,
915
948
  boundedChunkCollector: boundedChunkCollector,
916
949
  collectStream: collectStream,
917
950
  secureZero: secureZero,
@@ -154,6 +154,7 @@ function _coercePayloadString(payload) {
154
154
  * allowInternalDestinations: boolean, // default false — refuse SSRF (private/loopback/metadata)
155
155
  * httpRequest: function, // (url, body, headers) → { status } — inject for tests
156
156
  * now: function, // clock injection → ms epoch
157
+ * dnsLookup: function, // (host) → [{ address, family }] — override the SSRF destination resolver
157
158
  *
158
159
  * @example
159
160
  * var wd = b.webhook.dispatcher({ externalDb: b.externalDb });
@@ -186,6 +187,7 @@ function dispatcher(opts) {
186
187
  allowInternalDestinations: "optional-boolean",
187
188
  httpRequest: "optional-function",
188
189
  now: "optional-function",
190
+ dnsLookup: "optional-function",
189
191
  }, "webhook.dispatcher", WebhookDispatcherError, "webhook-dispatcher/bad-opts");
190
192
  var externalDb = opts.externalDb;
191
193
  var endpointsTable = _validateTableName(
@@ -216,12 +218,20 @@ function dispatcher(opts) {
216
218
  // because the IP check resolves the host. Throws a dispatcher-coded error.
217
219
  async function _assertSafeDestination(url, where) {
218
220
  safeUrl.parse(url, { allowedProtocols: allowedProtocols, errorClass: WebhookDispatcherError });
221
+ var checkOpts = { allowInternal: allowInternal };
222
+ if (typeof opts.dnsLookup === "function") checkOpts.dnsLookup = opts.dnsLookup;
219
223
  try {
220
- await ssrfGuard().checkUrl(url, { allowInternal: allowInternal });
224
+ await ssrfGuard().checkUrl(url, checkOpts);
221
225
  } catch (e) {
222
226
  if (e && e.isSsrfError) {
227
+ // A genuine SSRF refusal (destination resolved to a private / loopback /
228
+ // metadata IP, or a rebind since registration) is PERMANENT — dead-letter.
223
229
  throw _err("webhook-dispatcher/ssrf-refused", where + ": " + e.message);
224
230
  }
231
+ // A non-SsrfError from checkUrl is a raw resolver / network fault during
232
+ // host resolution (EAI_AGAIN, ETIMEDOUT, SERVFAIL, ...). Re-throw it as-is
233
+ // so the caller classifies it as TRANSIENT (retry), not permanent — a
234
+ // transient DNS blip must not dead-letter a delivery.
225
235
  throw e;
226
236
  }
227
237
  }
@@ -483,8 +493,20 @@ function dispatcher(opts) {
483
493
  try {
484
494
  await _assertSafeDestination(row.url, "deliver");
485
495
  } catch (err) {
496
+ // Permanence by CLASS: a genuine SSRF refusal or malformed URL surfaces
497
+ // as a WebhookDispatcherError (won't fix on retry) -> dead-letter. A
498
+ // resolver fault from the host-resolution step carries the framework's
499
+ // own terminal-vs-transient verdict on err.permanent — honor it so a
500
+ // PERMANENT lookup failure (no addresses / a removed record: the
501
+ // dns/no-result DnsError) dead-letters, while a transient one (a lookup
502
+ // timeout, a system/resolve failure) is retried on the backoff curve
503
+ // (capped at maxAttempts) like every other transport error below. A raw
504
+ // resolver error without that verdict (EAI_AGAIN from the native
505
+ // fallback, an injected resolver) is treated as transient — a DNS blip
506
+ // must not dead-letter a delivery.
507
+ var permanent = (err instanceof WebhookDispatcherError) || (err && err.permanent === true);
486
508
  return await _onFailure(deliveryId, attemptNo,
487
- (err && err.message) || String(err), true);
509
+ (err && err.message) || String(err), permanent);
488
510
  }
489
511
  // Sign + POST. Transport errors (network, TLS, timeout, DNS) and any
490
512
  // non-2xx HTTP status are TRANSIENT — back off and retry (capped at
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.16.34",
3
+ "version": "0.16.36",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:cb89f635-0d20-4d7a-b200-e38dc8bed885",
5
+ "serialNumber": "urn:uuid:e5683da5-8c6c-4bc9-84ad-1d58dcca68c4",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-07-16T12:36:01.015Z",
8
+ "timestamp": "2026-07-16T17:16:56.426Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.16.34",
22
+ "bom-ref": "@blamejs/core@0.16.36",
23
23
  "type": "application",
24
24
  "name": "blamejs",
25
- "version": "0.16.34",
25
+ "version": "0.16.36",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.16.34",
29
+ "purl": "pkg:npm/%40blamejs/core@0.16.36",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.16.34",
57
+ "ref": "@blamejs/core@0.16.36",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]