@blamejs/core 0.14.21 → 0.14.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,12 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.14.x
10
10
 
11
+ - v0.14.24 (2026-06-05) — **Per-row data residency enforced at the write boundary, and the long-advertised column-residency gate is wired.** Rows can now carry their own residency tag, and the database write paths enforce it: under a cross-border regulated posture (GDPR / UK-GDPR / DPDP / PIPL / LGPD / APPI / PDPA) a row tagged for one region is refused before it lands on a backend in another. `b.cryptoField.declarePerRowResidency` declares which column carries the tag; local SQLite writes check it against the deployment's `dataResidency` region set, and `b.externalDb.query` / `transaction` DML to a residency-tagged backend takes the tag per call via `rowResidencyTag`. The column-scoped gate (`assertColumnResidency`) — exported and documented since v0.7.27 but never composed into any write path — is now enforced on the same boundary. Unregulated deployments are unaffected: every gate passes with an advisory audit instead of a refusal, so operators can observe before adopting a posture. Note: v0.14.23 was tagged but not published to npm (its publish run timed out in validation); its changes — the MX DATA-phase SPF/DKIM/DMARC gate and the inbound mail authentication pipeline — are included in this package, and the publish-validation timeout is fixed here. **Added:** *`b.cryptoField.declarePerRowResidency` / `getPerRowResidency` — row-scoped residency tags* — Declares the plaintext column carrying each row's residency tag plus the whitelist of valid tag values (`{ residencyColumn, allowedTags }`). On INSERT to a declared table the tag is required and must be in `allowedTags`; rows tagged `global` or `unrestricted` pass any backend. The declaration registry mirrors `declareColumnResidency`, and `clearResidencyForTest` now clears both. The tag comes from application logic (the user's declared region) — the framework never infers it from request metadata. · *Local write gate on `b.db.from(...).insertOne` / `update`* — Runs on the plaintext row before sealing, so the tag column stays inspectable when sibling columns seal. Under a cross-border regulated posture, a row whose tag falls outside the deployment's region set (`dataResidency.region` plus `allowedStorageRegions`) is refused with `db-query/row-residency-local-mismatch`; a missing or out-of-whitelist tag refuses with `db-query/row-residency-tag-missing` / `-tag-invalid` regardless of posture. UPDATEs gate when the change set touches the residency column — an update that doesn't move residency is not a transfer. Refusals are typed `DbQueryError`s (new error class) and land in the audit chain (`db.residency.gate.rejected`); unregulated postures emit `db.residency.gate.advisory` and pass. · *External write gate — `rowResidencyTag` on `b.externalDb.query` / `transaction`* — External-db takes raw SQL, not row objects, so the row's tag travels as `opts.rowResidencyTag` (validated at transaction entry too). Under a regulated posture, a write to a residency-tagged backend requires the tag (`RESIDENCY_GATE_REQUIRED`) and refuses a mismatch (`RESIDENCY_TAG_MISMATCH`) before the statement reaches the wire. The gate classifies by what a statement does, not its leading keyword: it resolves the effective verb behind a `WITH` (CTE) or `EXPLAIN ANALYZE` prefix and treats `INSERT`/`UPDATE`/`DELETE`/`MERGE`/`REPLACE`, `CALL`/`EXECUTE`/`DO`, and `COPY ... FROM` as writes — only recognized pure reads (`SELECT`, `SHOW`/`DESCRIBE`/`PRAGMA`, a `COPY ... TO` export, plan-only `EXPLAIN`, and session/transaction statements) pass untagged. A statement whose class can't be resolved, or a multi-statement string that hides a trailing write behind a harmless prefix, is refused (`STATEMENT_UNRESOLVED_REFUSED` / `MULTI_STATEMENT_REFUSED`). Inside `transaction()`, the transaction-level tag applies to every statement and a per-call override on `tx.query(sql, params, opts)` wins for that statement; a refusal rolls the transaction back. Replica reads that carry a tag refuse routing to an incompatible replica (`REPLICA_RESIDENCY_INCOMPATIBLE`) unless the replica is configured `allowCrossBorder: true`, which is audited (`db.residency.replica.cross_border` at read time, `db.residency.replica.cross_border_allowed` at config time). Unrestricted backends are not gated, and the migration runner's own tracking writes are region-neutral so migrations run unaffected on a residency-tagged backend. · *`b.compliance.isCrossBorderRegulated` — shared posture vocabulary* — The cross-border regulated posture set (gdpr, uk-gdpr, dpdp, pipl-cn, lgpd-br, appi-jp, pdpa-sg) now lives on `b.compliance` (`CROSS_BORDER_REGULATED_POSTURES` + the membership helper), one source of truth shared by the local gate, the external gate, and the existing replica-topology boot check. **Fixed:** *`assertColumnResidency` is now actually enforced* — `b.cryptoField.declareColumnResidency` / `assertColumnResidency` shipped in v0.7.27 documenting a write-time gate, but no write path ever called the assertion — column tags were recorded and never checked. The local write paths now run it against the deployment region: a mismatch refuses with `db-query/column-residency-mismatch` under a regulated posture and emits an advisory otherwise. Operators tag columns with the region value their `dataResidency` declares. · *Cross-border-allowed replica audit event is now recorded* — The config-time audit event for a consciously-permitted cross-border replica used a malformed action name that the audit validator silently dropped, so a compliance reviewer saw no record of the `allowCrossBorder` decision in the audit chain. It now emits as `db.residency.replica.cross_border_allowed` and lands like every other audit row. · *Publish-validation timeout that blocked the v0.14.23 npm release* — The v0.14.23 publish run timed out in release validation — the pattern-catalog self-test crossed a per-file watchdog budget as the codebase grew, and the same self-test, which scans the whole library and runs far longer on the slower macOS CI runner, hit the same wall on this package's first CI run. The validation budgets are corrected so a genuinely stuck file still fails fast while the catalog completes. v0.14.23 exists as a signed tag; npm goes 0.14.22 → 0.14.24 carrying both releases' changes. **Detectors:** *db-query-write-without-residency-gate* — Every local write method that seals a row must run the residency gates on the plaintext first — a future write path (upsert, bulk) inherits the requirement automatically. · *Residency-gates-wired catalog check* — The pattern catalog now pins the wiring itself: the local write methods call the gate, the external query/transaction paths call theirs, and `assertColumnResidency` has a real caller — the declared-but-never-enforced class cannot silently reappear. **Migration:** *No action required unless you adopt the gates* — Tables without a residency declaration, deployments without a `dataResidency` region, and unregulated postures behave exactly as before (advisory audit events at most). Adopting: declare per-row residency on mixed-region tables, pass `rowResidencyTag` on external DML, and set a cross-border posture (`b.compliance.set("gdpr")`) to turn refusals on.
12
+
13
+ - v0.14.23 (2026-06-05) — **Inbound mail authentication: a DATA-phase SPF/DKIM/DMARC gate on the MX listener and the one-call receiver pipeline.** The MX listener can now refuse policy-failing mail at the wire instead of asking operators to verify after delivery. `b.mail.inbound.verify` is the receiver pipeline — SPF on the envelope identity, DKIM on the message bytes, DMARC policy + alignment on the From-header domain, and the RFC 8601 Authentication-Results header — and the listener's new `guardEnvelope` opt runs it at DATA completion: when the sender's published DMARC policy says reject, the message is refused with 550 before it reaches the agent handoff; accepted mail carries the verdict to the agent and gains the receiver's Authentication-Results header, with any sender-forged header carrying the receiver's name stripped first. Monitor mode annotates without refusing, so operators can observe verdicts on live traffic before enforcing. **Added:** *`b.mail.inbound.verify` — one-call receiver authentication pipeline* — Runs the inbound authentication set on a full RFC 5322 message (string or Buffer): SPF (RFC 7208) on the MAIL FROM identity with HELO fallback for the null reverse-path, DKIM (RFC 6376) on every signature, From-header extraction, DMARC (RFC 7489 / DMARCbis) policy discovery + alignment, and — when an `authservId` is supplied — the RFC 8601 Authentication-Results header. Returns `{ spf, dkim, from, dmarc, authResults }` with `dmarc.recommendedAction` carrying the policy disposition. From-header discipline per RFC 7489 §6.6.1: a message with zero From fields, several From fields, or several author addresses in one field returns `permerror` with a reject recommendation instead of picking one of the authors — the header-duplication shape behind the CVE-2024-7208 / CVE-2024-7209 hosted-relay spoofing class. The author parser is quote-aware: a literal `<` or comma inside a quoted display-name (`"Doe, John" <j@example.com>`) is one author, not two. A fail verdict computed while SPF or DKIM returned temperror surfaces as temperror (RFC 7489 §6.6.2) — the transiently-failed lookup could have produced the aligned pass, so the caller defers and the sender retries instead of being permanently refused during a DNS blip. · *MX listener `guardEnvelope` — the DATA-phase authentication gate* — `b.mail.server.mx.create({ guardEnvelope: true })` (or a config object: `mode`, `onTemperror`, `authservId`, `dnsLookup`, `maxSignatures`, `clockSkewMs`, `minRsaBits`, `timeoutMs`) runs the pipeline after the SIZE check and before the agent handoff. Enforce mode refuses with 550 5.7.26 (RFC 7372 — multiple authentication checks failed) when DMARC evaluates to fail under a reject policy, 550 5.7.1 on the multi-From shape, and 451 4.7.0 on DNS temperror or pipeline timeout — `onTemperror: "accept"` admits unauthenticated mail instead when availability wins. The whole pipeline runs under a wall-clock ceiling (`timeoutMs`, default 20s) so a message stuffed with signatures pointing at slow resolvers cannot pin the connection slot. Accepted messages reach the agent handoff with the verdict as `auth` (including `quarantine: true` when the sender's policy says quarantine — the agent owns foldering) and gain the receiver's Authentication-Results header; any sender-attached header forging the receiver's authserv-id is stripped first (RFC 8601 §5). Monitor mode (the default under the permissive profile) annotates and audits without refusing. New audit events: `mail.server.mx.envelope_verdict` and `mail.server.mx.envelope_error`. **Detectors:** *ar-header-prepend-without-forged-strip* — Any code path that prepends an emitted Authentication-Results header must first strip sender-attached instances claiming the same authserv-id (RFC 8601 §5) — a forged pre-attached verdict would otherwise shadow the computed one for downstream consumers. **Migration:** *No action required; the gate is opt-in* — `guardEnvelope` is off unless wired — an unwired gate is skipped like the sibling HELO / RBL / greylist gates, and existing listeners behave exactly as before. The agent handoff context gains an `auth` field (null when the gate is off). Start with `guardEnvelope: { mode: "monitor" }` to observe verdicts on live traffic before switching to enforce.
14
+
15
+ - v0.14.22 (2026-06-04) — **RFC 9101 signed request objects: a JAR request-object builder, a classical JWS signer for external interop, and pushed authorization requests that carry `request=`.** The framework can now mint JWT-Secured Authorization Requests, completing the JAR surface whose verify side (`b.auth.jar.parse`) shipped in v0.12.31 with the builder documented as waiting on a classical signer. `b.auth.jws.sign` is that signer — a compact-JWS producer for RS / PS / ES / EdDSA keys that exists strictly for interop with external ecosystems (authorization servers and relying parties that require classical algorithms); the framework's own tokens stay on the PQC-first signer. `b.auth.jar.build` mints the RFC 9101 request object on top of it, and `pushAuthorizationRequest` composes both so a pushed authorization request can carry the signed `request=` parameter — the FAPI 2.0 message-signing client shape. The OAuth client-attestation builder now composes the same promoted signer internally, with identical wire output. **Added:** *`b.auth.jar.build` — RFC 9101 request-object builder* — Mints the JWT-Secured Authorization Request: header `typ: oauth-authz-req+jwt` (RFC 9101 §10.8), `iss` = the client_id and `aud` = the authorization server (§5), `response_type` and `client_id` required as claims (§4), and every authorization parameter carried as a claim. A params object containing `request` or `request_uri` is refused (§4 forbids nesting), reserved-claim collisions are refused, and a `params.client_id` that disagrees with `opts.clientId` is refused. The JWT carries a short `exp` (default 5 minutes, `expiresInMs`-overridable), `nbf`, and a random `jti` for FAPI 2.0 message signing. The signing algorithm derives from the supplied key; `none` is impossible. Round-trips against the existing `b.auth.jar.parse` verifier. · *`b.auth.jws.sign` — classical compact-JWS signer for external interop* — Signs a compact JWS with an RS / PS / ES (P-256/P-384/P-521) / EdDSA key, deriving the algorithm from the key per RFC 7518 §3.1 and refusing `none`, HMAC, and algorithm/key mismatches; a caller-supplied `header.alg` cannot override the derived algorithm (algorithm-substitution closed). This primitive exists for interop with external ecosystems that require classical JOSE — JAR request objects, attestation JWTs, and similar cross-vendor surfaces. It is never the framework-internal token default: `b.auth.jwt` remains the PQC-first signer for the framework's own tokens. · *Pushed authorization requests can carry a signed request object (RFC 9126 §3)* — `pushAuthorizationRequest` accepts a `signedRequestObject` option (`{ key, alg?, kid?, audience?, expiresInMs? }`). When present, the authorization parameters are minted into a JAR request object and the PAR body carries `request=<jwt>` plus only the client-authentication material RFC 9126 allows alongside it; the bare authorization parameters are not duplicated in the form. Absent, the existing plain-form path sends the same key/value set as before. · *`validateOpts.assignOwnEnumerable` — shared prototype-safe claim merge* — Consolidates the own-enumerable key merge with prototype-pollution and reserved-key guards that the request-object builder, the classical signer, and the client-attestation builder all need. Existing call sites compose it; behavior is unchanged. **Changed:** *OAuth client-attestation signing composes the promoted classical signer* — The attestation builder's private JWS assembly moved to the shared `b.auth.jws.sign` internals. Wire output is identical — same headers, claim order, algorithm selection, and accepted-algorithm set — and the `auth-oauth/attestation-*` error codes are preserved, so operators routing alerts on those codes see no change. · *Object key-copy sites compose the prototype-safe merge* — The long-running-operation status reader, the deny-path response-header merge, the HTTP client's cross-origin redirect header strip, and the trace-log logger wrapper now copy keys through `validateOpts.assignOwnEnumerable` instead of raw bracket-assign loops, so a `__proto__`/`constructor`/`prototype` key in the source object can never graft onto the copy. Behavior is otherwise unchanged. **Removed:** *Maintainer planning note removed from the repository* — `memory/specs/node-26-map-getorinsert-migration.md` — a maintainer-local planning note that had been committed since v0.11.2 — is gone from the repository (it was never part of the npm package). The Node 26 detector allowlists in the pattern catalog now carry their per-site annotations standalone, and `SECURITY.md` / `.pinact.yaml` no longer reference maintainer-local note paths. **Security:** *`jar.parse` returns prototype-safe authorization params (CWE-1321)* — A verified request object whose payload carried a `__proto__` claim (JSON.parse materializes it as an own key) previously grafted that claim's value onto the returned `params` object's prototype chain — a signature from a registered-but-malicious client was sufficient. The params object is now built through the prototype-safe merge; `__proto__`/`constructor`/`prototype` claim names are inert and are not copied. · *`jws.sign` refuses `b64` and `crit` protected-header members* — RFC 7797 `b64: false` changes the JWS signing input (the payload is signed raw, not base64url-encoded) and RFC 7515 §4.1.11 `crit` promises the producer implements every extension it names. The signer always base64url-encodes the payload and implements no header extensions, so passing either member through minted a JWS whose header advertised semantics its signature was not computed under — a compliant verifier derives a different signing input or refuses the critical header. Both members are now refused with `auth-jwt-external/sign-unsupported-header`; unencoded-payload support would land as an explicit feature, not a header pass-through. **Detectors:** *raw-key-copy-loop-bypasses-assign-own-enumerable* — Refuses raw `out[keys[i]] = src[keys[i]]` bracket-assign copy loops in `lib/` — the shape behind the `jar.parse` finding. Key-copy sites compose `validateOpts.assignOwnEnumerable`; the two genuinely-different bodies (audit-chain hash canonicalization, schema-shape transforms) carry allowlist entries with structural reasons. · *jose-header-passthrough-without-b64-crit-refusal* — Any caller-supplied JOSE protected-header pass-through must name-refuse `b64`/`crit` before signing. · *no-tracked-internal-notes gate* — The pattern catalog now refuses any tracked file under `memory/`, `notes/`, or `.scratch*` paths at commit time. **Migration:** *No action required; everything is additive* — The JAR builder, the classical signer, the PAR `signedRequestObject` option, and the shared merge helper are new surface. Existing `jar.parse` callers, attestation flows, and plain PAR requests behave exactly as before.
16
+
11
17
  - v0.14.21 (2026-06-04) — **SCIM Bulk forward references, an atomic api-encrypt replay gate, OID4VCI `x5c` proofs, HEAD responses without bodies, and a sweep that makes every accepted option do what its documentation says.** This release closes correctness and conformance gaps across recently shipped standards surfaces, plus a framework-wide sweep for options that were accepted but never read. SCIM `/Bulk` resolves `bulkId` cross-references regardless of operation order; the `apiEncrypt` middleware closes a concurrent-replay window on multi-replica session stores and validates its numeric options at boot; OID4VCI accepts `x5c` holder-key binding; `problemDetails` spreads its documented `extensions` object as RFC 9457 sibling members; `openapiServe` / `asyncapiServe` answer HEAD without a body; and a batch of entry points now throw on mistyped numeric options instead of silently defaulting. Options whose documented behavior was never implemented are now wired; options that could never do anything are removed and refuse as unknown. **Removed:** *Options that could never do anything now refuse as unknown* — The sweep removed accepted-but-impossible option keys: the `securityTxt` / `traceLogCorrelation` / tracer / TLS-RPT `audit` keys (these surfaces emit no audit rows), TLS-RPT `reportingMta` (not an RFC 8460 report field), `dsr.create` `observability` and create-time `verifyContext` (the per-call `process()` option of the same name is unchanged), `breakGlass.init` `now` (a single init-time timestamp cannot coherently override later time reads), WCAG `checkAll`, mail-deploy `compliance`, and bucket-ops `ca` (TLS trust is owned by the PQC agent — use `NODE_EXTRA_CA_CERTS` or `opts.agent`). Passing one of these now throws the standard unknown-option error. **Fixed:** *SCIM `/Bulk` resolves `bulkId` cross-references regardless of operation order (RFC 7644 §3.7.2)* — Forward references (an operation referencing a resource a later operation creates — the shape Okta and Entra emit) now execute in dependency order; circular references are refused with status 409; a reference to an undeclared `bulkId`, or to an operation that failed, fails that operation with `invalidValue`. References are resolved on BOTH surfaces the spec allows: operation data (`"value": "bulkId:u1"`) and the operation path (`PATCH /Groups/bulkId:g1` targeting a group created in the same request) — path references order, substitute, and fail exactly like data references. Previously an unresolvable reference passed the literal `bulkId:<id>` token through to your resource adapter as if it were a real id. The Bulk response keeps results in original request order, and `failOnErrors` still short-circuits. · *OID4VCI `x5c` holder-key binding implemented (RFC 7515 §4.1.6; OID4VCI §8.2.1.1)* — The proof-JWT verifier named `x5c` as a valid holder-key binding in its own error message but always refused `x5c`-only proofs. The certificate chain is now shape-validated (standard base64 DER, leaf first), the leaf certificate's public key becomes the holder key at the same self-asserted trust level as an inline `jwk`, and a new optional `validateX5c(chainDerBuffers, header)` hook lets the issuer enforce chain trust (PKI anchoring, EKU checks, attestation-CA allowlists) before the key is accepted. · *OID4VCI expired `c_nonce` refuses with a typed error* — A wallet whose access token outlived the shorter `c_nonce` TTL hit an untyped `TypeError` from the nonce comparison; issuance now refuses with `auth-oid4vci/c-nonce-expired` so handlers keying on typed codes respond correctly. The refusal direction is unchanged — no credential was ever minted on this path. · *OID4VP DCQL numeric claim-path segments must be non-negative integers (OpenID4VP 1.0 §7.1.1)* — A query carrying `-1`, `1.5`, `NaN`, or `Infinity` as an array-index segment previously validated and then silently never matched; it now throws at build time, surfacing the malformed query to the verifier author instead of degrading to a silent non-match. · *`problemDetails` `extensions` spread as sibling members (RFC 9457 §3.2)* — `send` and `create` documented an `extensions` object as the way to attach extension members, but emitted it as a literal nested `extensions` member instead. The keys now land as top-level siblings; reserved fields (`type` / `title` / `status` / `detail` / `instance`) cannot be overridden by an extension key, prototype-pollution-shaped keys are dropped, and a direct top-level key wins on collision. · *`cspReport` honors `audit: false`* — The documented audit knob was accepted but never read; the `csp.violation` audit row fired unconditionally for every report. `audit: false` now suppresses the row while reports are still normalized and delivered to `onReport`. The default (audit on) is unchanged, and `maxBytes` now throws at config time on a non-positive-integer value instead of silently reverting to 64 KiB. · *`openapiServe` / `asyncapiServe` HEAD responses carry no body (RFC 9110 §9.3.2)* — Both middlewares advertised GET/HEAD but answered HEAD with the full JSON / YAML document as a body. HEAD now returns the GET headers (including `Content-Length`) with an empty body, matching the rest of the framework's document-serving middlewares. · *Config-time numeric options throw on bad input across entry points* — A mistyped numeric option now throws at `create()` instead of silently becoming the default or garbage downstream: `scimServer` `maxPageSize` (a non-number propagated `NaN` into your `impl.list({ count })` and `ServiceProviderConfig`), `mail.send.deliver` `retry.maxAttempts` / `timeouts.mxLookupMs` / `timeouts.perHostMs`, the `redis` client `db` / `connectTimeoutMs` / `commandTimeoutMs` / `maxReconnectAttempts` (a non-numeric value made the reconnect-cap check false and silently disabled the bound entirely), `pubsub` cluster `pollIntervalMs` / `retentionMs` / `pruneEveryMs`, and SQS queue `visibilityTimeoutSec` / `waitTimeSec` (`0` short-polling stays valid). · *Accepted-but-unread options now do what their documentation says* — The db-backed `config` reloader's `audit` knob gates its `config.reload.*` rows; `honeytoken` honors the documented injectable audit sink (`{ audit: yourSink }`) instead of always emitting to the global sink; `dora`'s `observability` knob gates its report counter, and that counter now actually emits (it previously called a method the observability module doesn't export, and the failure was swallowed); flag evaluation-context `tenantKey` sets the tenant axis; the WCAG `aria` / `forms` / `tables` sub-scanners stamp `scopeUrl` on every finding so direct callers can correlate findings to a source document; `safeRedirect`'s documented `base` lets a same-origin absolute URL pass without an explicit allowlist (cross-origin still refused); and object-store bucket operations honor a per-call `actor` override on audit rows. **Security:** *api-encrypt concurrent-replay window closed (CWE-367)* — On a multi-replica session store, two concurrent requests carrying the same valid counter could both pass the monotonic replay check and execute twice — an attacker who captured one encrypted request could replay it concurrently and have a non-idempotent route run twice. The per-session path now claims each `(session, counter)` tuple through the same atomic nonce store the bootstrap path uses; exactly one concurrent request wins and the loser is refused with the standard rejection shape. The claim lives until the session expires (not just the staleness window), so a failed best-effort session write cannot re-open the tuple for late replay. The bootstrap response counter is also persisted correctly on serializing session stores, fixing a response-replay false positive on the second request of a session. · *api-encrypt envelope metadata is authenticated (AEAD-bound)* — The envelope's plaintext fields — `_ts`, `_nonce`, `_sid`, `_ctr` — were not bound into the ciphertext, so a captured request could be replayed past the staleness window with a rewritten `_ts`, and a captured response could be replayed to the client under a bumped `_ctr` (the client's monotonic check reads the plaintext field). Every request and response envelope now binds its metadata as AEAD associated data on both protocol halves; any rewrite fails authenticated decryption and is refused (server: standard rejection; client: typed `CLIENT_RESPONSE_TAMPERED`). The client also advances its response counter only after authenticated decryption, so a refused forgery cannot poison the monotonic check and block subsequent genuine responses. · *api-encrypt numeric options validated at boot* — A mistyped `replayWindowMs` (for example the string `"5m"`) made the timestamp-staleness comparison always false and silently disabled that replay defense. `replayWindowMs`, `maxDecryptedBytes`, and `pruneIntervalMs` now throw at config time across `create`, `client`, and `httpClient.encrypted`. **Detectors:** *Three new codebase-pattern gates* — An option key accepted by a validation allowlist must be read by the file that accepts it (an accepted-but-never-read key is an advertised knob with no implementation); entry-point numeric options must validate rather than coerce-or-default (`Number(opts.x) || DEFAULT` swallows exactly the typo the config-time tier exists to surface); and a dispatcher that admits HEAD must suppress the response body somewhere in the same file. **Migration:** *Delete removed option keys; everything else is a behavioral fix or additive* — If you pass one of the removed keys listed under Removed, delete it — it did nothing before and now throws the standard unknown-option error. Callers passing valid options see conforming behavior with no code change; the new `validateX5c` hook and the per-finding `scopeUrl` stamp are additive. · *apiEncrypt middleware and client must upgrade together* — Binding the envelope metadata into the AEAD changes what the ciphertext authenticates, so a pre-0.14.21 client cannot talk to a 0.14.21 middleware or vice versa — mixed-version peers fail authenticated decryption and are refused. Both halves ship in this package; a single service upgrading normally is unaffected. If separate services pin different framework versions and speak apiEncrypt to each other, upgrade them together.
12
18
 
13
19
  - v0.14.20 (2026-06-02) — **OAuth Rich Authorization Requests and client attestation, a sealed-field unseal rate cap, DMARC forensic-report parsing, monitor-mode browser-isolation headers, and FedCM / Storage-Access fetch-metadata.** This release extends several standards surfaces the framework already covered in part. The OAuth client gains RFC 9396 Rich Authorization Requests: a typed `authorizationDetails` array is validated before the request and the granted details in the token response are cross-checked, refusing a grant the OP broadened beyond what was asked. The client also gains the OAuth 2.0 Attestation-Based Client Authentication primitives — it can build the `OAuth-Client-Attestation` / `-PoP` JWT pair and verify an inbound attestation. Sealed-field reads gain an opt-in unseal-failure rate cap that throttles a decryption-oracle / brute-force burst against attacker-written sealed columns (CWE-307). The inbound mail stack gains a DMARC forensic (RUF) report parser, the inverse of the aggregate-report parser. On the browser side, the security-headers middleware adds report-only COOP / COEP / Document-Policy variants for safe cross-origin-isolation rollout plus the embedder Require-Document-Policy and Service-Worker-Allowed headers, and the fetch-metadata middleware recognizes the FedCM `webidentity` destination and the Storage-Access request headers first-class. Observability adds a batch of current OpenTelemetry semantic-convention attributes. Every addition is additive or opt-in: an operator who sets no new option, and configures no rate cap, sees prior behavior unchanged. **Added:** *OAuth client: RFC 9396 Rich Authorization Requests (`authorizationDetails`)* — The OAuth / OIDC client accepts an `authorizationDetails` array (RFC 9396 §2 — each element a typed object) on the authorization and pushed-authorization-request paths; it is validated at config time (every element must be an object carrying a string `type`) and serialized as the `authorization_details` parameter, with a cap on the serialized payload. When `verifyAuthorizationDetails` is set, the granted `authorization_details` returned in the token response (RFC 9396 §7) is cross-checked against the request, and a grant that exceeds what was requested is refused — defending against an upstream broadened-grant privilege escalation. Without `authorizationDetails`, the request is unchanged. · *OAuth 2.0 Attestation-Based Client Authentication* — `b.auth.oauth.buildClientAttestation` and `buildClientAttestationPop` mint the `OAuth-Client-Attestation` JWT (a client-backend-signed assertion binding a per-instance key, `typ: oauth-client-attestation+jwt`) and its per-instance `OAuth-Client-Attestation-PoP` proof; `verifyClientAttestation` validates the pair, including the alg allowlist (`ATTESTATION_ALGS`), the audience, and a constant-time `jti` check. This is the wallet / per-device client-authentication shape used in OpenID4VCI and the EUDI Wallet, an alternative to a shared `client_secret`. · *`b.cryptoField.configureUnsealRateCap` — sealed-field decryption-oracle throttle* — An opt-in per-(actor, table, column) sliding-window cap on sealed-column unseal failures. A DB-write attacker who can place crafted `vault:` / `vault.aad:` bytes in sealed columns can force KEM decapsulation / AEAD verification on attacker-controlled input on every read; past `threshold` failures within `windowMs`, further unseal attempts for that tuple are refused for `cooldownMs` with a typed `CryptoFieldRateError` and a distinct `system.crypto.unseal_rate_exceeded` audit event (CWE-307; OWASP ASVS v5 §2.2.1; NIST SP 800-63B §5.2.2). Default off — with no cap configured, `unsealRow` behaves exactly as before (null the field, emit `system.crypto.unseal_failed`); the cap is count-based and lazily pruned, with no background timer. · *`b.mail.dmarc.parseForensicReport` — RFC 6591 forensic (RUF) report parser* — Parses a DMARC failure (forensic) report: a `multipart/report; report-type=feedback-report` message (RFC 6591 §3) whose `message/feedback-report` subpart carries the `Feedback-Type: auth-failure` fields, with the required-field set validated (`Auth-Failure` and the other §3.1 fields) and a part-count and byte cap bounding a hostile report. It is the inbound inverse of the aggregate-report path, so an operator ingesting RUF mail has a parser symmetric with the existing aggregate parser and the v0.14.19 aggregate builder. · *Monitor-mode cross-origin-isolation and embedder headers* — `b.middleware.securityHeaders` gains `coopReportOnly`, `coepReportOnly`, and `documentPolicyReportOnly` — set a policy string to emit the matching `*-Report-Only` header so a UA evaluates and reports violations without enforcing, the safe way to stage a COOP / COEP / Document-Policy rollout (WHATWG HTML cross-origin isolation; W3C Document Policy). `requireDocumentPolicy` emits the embedder `Require-Document-Policy` a parent demands of subframes, and `serviceWorkerAllowed` emits `Service-Worker-Allowed` to broaden a service worker's registration scope (W3C Service Workers). All default off. · *fetch-metadata: FedCM `webidentity` and Storage-Access headers* — `b.middleware.fetchMetadata` recognizes the `webidentity` `Sec-Fetch-Dest` (a FedCM credentialed request) first-class and adds `deniedDest` — a list of destinations refused outright on the gated methods regardless of site, so a `webidentity` request hitting a route that is not an identity endpoint is refused. `allowStorageAccess` (default true) governs whether a request carrying `Sec-Fetch-Storage-Access: active` / `inactive` (the Storage Access API headers) is allowed, and `strictDest` throws at config time on an `allowedDest` / `deniedDest` value outside the known `Sec-Fetch-Dest` vocabulary, catching a typo at boot. · *OpenTelemetry semantic-convention attributes* — The observability semantic-convention map gains a batch of current stable attributes: `peer.service`, the `faas.*` function attributes (`name` / `version` / `instance` / `trigger`), `deployment.environment.name`, `telemetry.distro.*`, `otel.scope.*`, and a Kubernetes subset (`k8s.cluster.name` and the node / container / cronjob / daemonset / job / replicaset / statefulset names), so a span or metric carrying these keys is recognized and emitted under the canonical name. **Fixed:** *`b.auth.sdJwtVc.holder` signed the key-binding JWT with a non-key-derived algorithm* — The holder helper defaulted the key-binding JWT (KB-JWT) signing algorithm to a fixed `ES256` regardless of the holder key type, so a non-EC-P-256 holder key produced a presentation that either could not be built (an Ed25519 or P-384 key) or whose KB-JWT header advertised `ES256` while the signature used the actual key — a self-invalid token a verifier rejects. The algorithm is now derived from the holder key: ES256 / ES384 by EC curve, EdDSA for Ed25519 / Ed448, and ML-DSA-87 / ML-DSA-65 for an ML-DSA key. An RSA holder key, which has no supported KB-JWT algorithm, is refused at `holder.create` with a clear error instead of producing a broken presentation. An EC P-256 holder key, and any explicit `algorithm`, behave exactly as before. **Security:** *Throttle a sealed-column decryption oracle (opt-in)* — `b.cryptoField.configureUnsealRateCap` lets an operator bound repeated unseal failures against sealed columns, so an attacker who can write crafted bytes into a sealed field cannot hammer the KEM / AEAD verify path indefinitely while only an off-band alert rule notices the burst (CWE-307). It is opt-in because a sensible threshold and window depend on a deployment's legitimate sealed-read volume; the always-on defense (null the field plus an audit event on every unseal failure) is unchanged. · *Refuse a broadened OAuth grant* — With `verifyAuthorizationDetails` enabled, the OAuth client refuses a token response whose granted `authorization_details` exceed the requested set (RFC 9396 §7), so a compromised or misbehaving authorization server cannot silently widen a client's authorization beyond what the request asked for. **Migration:** *No action required; additions are additive or opt-in* — The OAuth `authorizationDetails` request parameter, the granted-details cross-check, the client-attestation builders / verifier, the sealed-field unseal rate cap, the DMARC forensic-report parser, the monitor-mode and embedder browser headers, the fetch-metadata FedCM / Storage-Access options, and the new OpenTelemetry attribute keys are all additive or opt-in. A client that passes no `authorizationDetails`, an operator who calls no `configureUnsealRateCap`, and a security-headers / fetch-metadata configuration that sets none of the new options all see prior behavior byte-for-byte unchanged. The one behavior change is the SD-JWT VC holder fix: a `b.auth.sdJwtVc.holder` built with an RSA holder key is now refused at `holder.create` (RSA has no supported KB-JWT algorithm; it previously produced a self-invalid presentation) — switch such a holder to an EC P-256 / P-384, Ed25519, or ML-DSA key. EC P-256 holders and any explicit `algorithm` are unaffected.
package/README.md CHANGED
@@ -97,7 +97,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
97
97
 
98
98
  - **At-rest envelope** — envelope-versioned PQC (ML-KEM-1024 + P-384 hybrid, XChaCha20-Poly1305, SHAKE256); vault sealing (`b.crypto`, `b.vault`)
99
99
  - **Power-on self-test** — `b.crypto.selfTest()` runs FIPS 140-3-style integrity checks: NIST FIPS 202 known-answer tests (SHA3-256/512, SHAKE256), AEAD round-trip + tamper-detect, and ML-KEM-1024 / ML-DSA-87 / SLH-DSA-SHAKE-256f pairwise-consistency + negative tests; fails closed (throws) on any mismatch
100
- - **Field-level + crypto-shred** — `b.cryptoField.eraseRow`; per-column data residency tagging + per-row keys (`K_row = HKDF(K_table, rowId)`) so erasing the per-row key makes WAL / replica residuals undecryptable (`b.cryptoField.declareColumnResidency`, `b.cryptoField.declarePerRowKey`)
100
+ - **Field-level + crypto-shred** — `b.cryptoField.eraseRow`; per-column and per-row data residency tagging enforced at the write boundary (cross-border DML refused under GDPR / UK-GDPR / DPDP / PIPL / LGPD / APPI / PDPA postures) + per-row keys (`K_row = HKDF(K_table, rowId)`) so erasing the per-row key makes WAL / replica residuals undecryptable (`b.cryptoField.declareColumnResidency`, `b.cryptoField.declarePerRowResidency`, `b.cryptoField.declarePerRowKey`)
101
101
  - **AAD-bound sealed columns** — AEAD tag tied to `(table, rowId, column, schemaVersion)`; copy-paste between rows or schema-version replay surfaces as refused decrypt (`b.vault.aad`). The database encryption key is sealed the same way — bound to its purpose, data directory, and key path — so a relocated key file fails to unseal; an older unbound key upgrades itself on first load. A vault-key rotation re-seals every AAD-bound cell, the database key, and tenant archives under the new keypair and refuses rather than silently orphaning a store it cannot reach (`b.vaultRotate`, `b.vault.aad.resealRoot`, `b.archive.rewrapTenant`)
102
102
  - **Keyed lookup hashes** — sealed-column equality-lookup hashes default to salted SHA3-512 and can opt into a keyed `hmac-shake256` MAC off a per-deployment key (`cryptoField.registerTable({ derivedHashMode })`, `b.vault.getDerivedHashMacKey`), making the lookup hash unforgeable and un-correlatable across deployments
103
103
  - **Signed webhooks + API encryption** — SLH-DSA-SHAKE-256f default; ML-DSA-65 opt-in; ECIES API encryption (`b.webhook`, `b.crypto`)
@@ -168,7 +168,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
168
168
  - **Mail (outbound)** — multipart + attachments + DKIM + calendar invites; bounce intake (`b.mail`, `b.mailBounce`)
169
169
  - **Mail (outbound delivery)** — turnkey MX-lookup → MTA-STS-fetch → DANE-TLSA → REQUIRETLS handshake → SMTP wire layer → RFC 3464 DSN-on-permanent-failure → deferred-retry scheduling, all wired once (`b.mail.send.deliver`)
170
170
  - **Mail (inbound auth)** — SPF / DMARC / ARC verify + ARC chain signing for relays, plus DMARC aggregate (RUA) + forensic (RUF) report parsing (`b.mail.spf`, `b.mail.dmarc`, `b.mail.arc`)
171
- - **Mail server listeners** — RFC 5321 MX inbound with connection-level gate cascade (HELO identity / DNS blocklist / greylisting) (`b.mail.server.mx`), RFC 6409 submission with SASL + identity-binding (`b.mail.server.submission`), RFC 9051 IMAP4rev2 with CONDSTORE / QRESYNC / NOTIFY / METADATA / CATENATE (`b.mail.server.imap`), RFC 8620 + RFC 8621 JMAP Core + Mail over HTTP/SSE/WebSocket (`b.mail.server.jmap`), POP3 (`b.mail.server.pop3`), ManageSieve (`b.mail.server.managesieve`)
171
+ - **Mail server listeners** — RFC 5321 MX inbound with connection-level gate cascade (HELO identity / DNS blocklist / greylisting) and a DATA-phase SPF/DKIM/DMARC gate that refuses policy-failing mail before storage (`b.mail.server.mx`), RFC 6409 submission with SASL + identity-binding (`b.mail.server.submission`), RFC 9051 IMAP4rev2 with CONDSTORE / QRESYNC / NOTIFY / METADATA / CATENATE (`b.mail.server.imap`), RFC 8620 + RFC 8621 JMAP Core + Mail over HTTP/SSE/WebSocket (`b.mail.server.jmap`), POP3 (`b.mail.server.pop3`), ManageSieve (`b.mail.server.managesieve`)
172
172
  - **JMAP EmailSubmission reference** — composes `b.mail.send.deliver` to land the RFC 8621 §7.5 surface end-to-end (`b.mail.server.jmap.emailSubmissionSetHandler`)
173
173
  - **Mail crypto** — PQC-first S/MIME via CMS (`b.mail.crypto.cms`) + OpenPGP encrypt/decrypt + WKD key discovery with IDN-homograph defense (`b.mail.crypto.pgp`)
174
174
  - **Mail-stack agent** — multi-threaded worker pool + queue dispatch + sealed mail-store backed by SQLite FTS5 (`b.mail.agent`, `b.mailStore`)
package/index.js CHANGED
@@ -32,7 +32,7 @@ _tls.DEFAULT_MIN_VERSION = "TLSv1.3";
32
32
  * error-handler, body-parser, csp-nonce, compression,
33
33
  * health, api-encrypt), httpClient, websocket,
34
34
  * websocketChannels, nonceStore
35
- * Auth: auth.{password,totp,passkey,jwt,oauth,lockout}, authHeader
35
+ * Auth: auth.{password,totp,passkey,jwt,jws,oauth,jar,lockout}, authHeader
36
36
  * Render: template, render, staticServe, forms, errorPage
37
37
  * App: createApp, jobs, mail, mailBounce, scheduler,
38
38
  * appShutdown
@@ -247,6 +247,10 @@ var auth = {
247
247
  jwt: Object.assign({},
248
248
  require("./lib/auth/jwt"),
249
249
  { verifyExternal: require("./lib/auth/jwt-external").verifyExternal }),
250
+ // Classical-JOSE signer (RS/PS/ES/EdDSA) for external-ecosystem interop —
251
+ // OPs/RPs that require a classical-signed request object / assertion. Never
252
+ // the framework-internal token default; b.auth.jwt stays PQC-only.
253
+ jws: { sign: require("./lib/auth/jwt-external").signExternal },
250
254
  oauth: require("./lib/auth/oauth"),
251
255
  jar: require("./lib/auth/jar"),
252
256
  lockout: require("./lib/auth/lockout"),
package/lib/auth/jar.js CHANGED
@@ -15,14 +15,26 @@
15
15
  * can verify they arrived exactly as the client sent them.
16
16
  *
17
17
  * <code>b.auth.jar.parse(jar, opts)</code> verifies an incoming
18
- * request object: the signature is checked through
19
- * <code>b.auth.jwt.verifyExternal</code> (mandatory <code>algorithms</code>
20
- * allowlist — no <code>alg: "none"</code>, no HMAC-vs-RSA confusion,
21
- * no JWE-on-a-JWS-verifier), <code>iss</code> is pinned to the
22
- * expected <code>clientId</code>, <code>aud</code> to this server's
23
- * issuer identifier, the request object's <code>client_id</code>
24
- * claim must match the client, and the authorization parameters are
25
- * returned with the JWT envelope claims stripped.
18
+ * request object (the authorization-server side): the signature is
19
+ * checked through <code>b.auth.jwt.verifyExternal</code> (mandatory
20
+ * <code>algorithms</code> allowlist — no <code>alg: "none"</code>, no
21
+ * HMAC-vs-RSA confusion, no JWE-on-a-JWS-verifier), <code>iss</code>
22
+ * is pinned to the expected <code>clientId</code>, <code>aud</code> to
23
+ * this server's issuer identifier, the request object's
24
+ * <code>client_id</code> claim must match the client, and the
25
+ * authorization parameters are returned with the JWT envelope claims
26
+ * stripped.
27
+ *
28
+ * <code>b.auth.jar.build(params, opts)</code> mints a request object
29
+ * (the client side): the authorization-request parameters become
30
+ * claims of a JWT signed with the client's classical key via
31
+ * <code>b.auth.jws.sign</code> (RS/PS/ES/EdDSA — the interop algs an
32
+ * authorization server accepts), typed <code>oauth-authz-req+jwt</code>,
33
+ * with <code>iss</code>/<code>aud</code> pinned and a short FAPI-2
34
+ * <code>exp</code>. <code>build</code> and <code>parse</code>
35
+ * round-trip. The framework's own tokens stay PQC-signed
36
+ * (<code>b.auth.jwt</code>); JAR signs classically only because no
37
+ * standard authorization server verifies a PQC request object today.
26
38
  *
27
39
  * <strong>Anti-nesting (RFC 9101 §6.3):</strong> a request object
28
40
  * may not itself carry a <code>request</code> or <code>request_uri</code>
@@ -35,33 +47,48 @@
35
47
  * shapes against a JWKS public-key trust source. JAR adds the
36
48
  * request-object-specific bindings on top.
37
49
  *
38
- * <strong>Emitting</strong> a request object (the client side) is
39
- * deferred-with-condition: it requires signing with the client's
40
- * key under a classical JWS algorithm (RS256 / ES256 / EdDSA), and
41
- * the framework's own JWT signer (<code>b.auth.jwt.sign</code>) is
42
- * PQC-only (ML-DSA / SLH-DSA) for the tokens the framework itself
43
- * issues a PQC-signed request object would not interoperate with
44
- * any standard authorization server today. blamejs sits on the
45
- * authorization-server side here (it verifies client request
46
- * objects); client-side emission re-opens when a classical
47
- * <code>b.auth.jws.sign</code> primitive lands or operators surface
48
- * the need. Until then clients sign their request objects with
49
- * their existing JOSE tooling.
50
+ * The request object is signed with a classical JWS algorithm
51
+ * (RS/PS/ES/EdDSA) because no standard authorization server verifies a
52
+ * PQC-signed request object today; the framework's own JWT signer
53
+ * (<code>b.auth.jwt.sign</code>) stays PQC-only (ML-DSA / SLH-DSA) for
54
+ * the tokens blamejs itself issues. <code>build</code> composes
55
+ * <code>b.auth.jws.sign</code> for the classical signature the
56
+ * client-side emission this module previously left to the operator's
57
+ * own JOSE tooling now ships in-framework.
50
58
  *
51
59
  * @card
52
- * RFC 9101 JWT-Secured Authorization Request (server side) verify
53
- * the OAuth request object with mandatory alg allowlist, iss +
54
- * client_id binding, audience pinning, and anti-nesting.
60
+ * RFC 9101 JWT-Secured Authorization Request build the client
61
+ * request object (classical JWS, typed, iss/aud-pinned, short exp) and
62
+ * verify it on the server with mandatory alg allowlist, client_id
63
+ * binding, and anti-nesting.
55
64
  */
56
65
 
57
66
  var jwtExternal = require("./jwt-external");
58
67
  var validateOpts = require("../validate-opts");
68
+ var C = require("../constants");
69
+ var bCrypto = require("../crypto");
59
70
  var { defineClass } = require("../framework-error");
60
71
 
61
72
  var AuthJarError = defineClass("AuthJarError", { alwaysPermanent: true });
62
73
 
63
74
  var JAR_TYP = "oauth-authz-req+jwt";
64
75
 
76
+ // RFC 9101 §4 — a request object MUST carry response_type + client_id as
77
+ // claims (they are REQUIRED OAuth 2.0 authorization-request parameters).
78
+ var REQUIRED_REQUEST_PARAMS = ["response_type", "client_id"];
79
+
80
+ // Claims the builder sets itself from opts (iss = client_id, aud =
81
+ // audience) plus the JWT lifetime claims it mints (exp/nbf/iat/jti).
82
+ // Operator params colliding with iss / aud are refused so a params.iss
83
+ // can't shadow the builder-pinned issuer; the lifetime claims are owned by
84
+ // the builder's exp/nbf/jti opts, not by free-form params.
85
+ var BUILDER_OWNED_CLAIMS = ["iss", "aud", "exp", "nbf", "iat", "jti"];
86
+
87
+ // Default request-object lifetime. FAPI-2 message-signing wants a short
88
+ // window; 5 minutes mirrors the attestation-PoP floor and is overridable
89
+ // via opts.expiresInMs.
90
+ var DEFAULT_JAR_EXPIRES_MS = C.TIME.minutes(5);
91
+
65
92
  // JWT-standard claims that are request-object envelope metadata, not
66
93
  // OAuth authorization parameters — stripped from the returned params.
67
94
  var ENVELOPE_CLAIMS = ["iss", "aud", "exp", "iat", "nbf", "jti"];
@@ -164,16 +191,151 @@ async function parse(jar, opts) {
164
191
  "jar.parse: request object must not carry `request` or `request_uri` (RFC 9101 §6.3)");
165
192
  }
166
193
 
167
- var params = {};
168
- var keys = Object.keys(payload);
169
- for (var i = 0; i < keys.length; i++) {
170
- if (ENVELOPE_CLAIMS.indexOf(keys[i]) === -1) params[keys[i]] = payload[keys[i]];
171
- }
194
+ // Authorization parameters = every claim minus the JWT envelope.
195
+ // assignOwnEnumerable skips the prototype-pollution sentinel keys a
196
+ // verified-but-hostile request object carrying a `__proto__` claim
197
+ // (JSON.parse materializes it as an own key) must not graft onto the
198
+ // returned params object's prototype chain (CWE-1321).
199
+ var params = validateOpts.assignOwnEnumerable({}, payload, ENVELOPE_CLAIMS);
172
200
  return { params: params, claims: payload };
173
201
  }
174
202
 
203
+ /**
204
+ * @primitive b.auth.jar.build
205
+ * @signature b.auth.jar.build(params, opts)
206
+ * @since 0.14.22
207
+ * @status stable
208
+ * @compliance soc2
209
+ * @related b.auth.jar.parse, b.auth.jws.sign
210
+ *
211
+ * Mint an RFC 9101 request object — the client side of JWT-Secured
212
+ * Authorization Requests. The authorization-request parameters in
213
+ * <code>params</code> become claims of a JWT signed with the client's
214
+ * classical key, ready to send as the <code>request</code> parameter (or
215
+ * pushed through PAR). The inverse of <code>b.auth.jar.parse</code>; the
216
+ * two round-trip.
217
+ *
218
+ * The protected header carries <code>typ: "oauth-authz-req+jwt"</code>
219
+ * (RFC 9101 §10.8 — explicit typing closes the cross-JWT-confusion vector
220
+ * where a token minted for another purpose is replayed as a request
221
+ * object). <code>iss</code> is set to <code>opts.clientId</code> and
222
+ * <code>aud</code> to <code>opts.audience</code> — the authorization
223
+ * server's issuer identifier (RFC 9101 §5; the FAPI 2.0 message-signing
224
+ * profile requires both). <code>response_type</code> and
225
+ * <code>client_id</code> are REQUIRED claims (RFC 9101 §4); the builder
226
+ * refuses if either is absent from <code>params</code>. A request object
227
+ * <strong>MUST NOT</strong> nest <code>request</code> /
228
+ * <code>request_uri</code> (RFC 9101 §4) — supplying either in
229
+ * <code>params</code> is refused at build, the mirror of
230
+ * <code>parse</code>'s anti-nesting check.
231
+ *
232
+ * <code>exp</code> defaults to 5 minutes (FAPI-2 wants a short signing
233
+ * window; tune via <code>opts.expiresInMs</code>); <code>nbf</code> is set
234
+ * to <code>iat</code> and a random <code>jti</code> is minted so the AS can
235
+ * single-use the object. The signing <code>alg</code> is derived from
236
+ * <code>opts.key</code> via <code>b.auth.jws.sign</code> (RS/PS/ES/EdDSA);
237
+ * <code>alg: "none"</code> is impossible — the signer refuses it. This is
238
+ * the classical-interop path: the framework's own tokens stay PQC-signed.
239
+ *
240
+ * @opts
241
+ * {
242
+ * clientId: string, // required — → iss + must equal params.client_id
243
+ * audience: string, // required — AS issuer identifier → aud
244
+ * key: KeyObject|PEM|JWK, // required — client's classical signing key
245
+ * alg?: string, // JWS alg override (default inferred from the key)
246
+ * kid?: string, // protected-header kid (JWKS selection at the AS)
247
+ * expiresInMs?: number, // exp = iat + this (default: 5m; positive int)
248
+ * }
249
+ *
250
+ * @example
251
+ * var ro = b.auth.jar.build(
252
+ * { response_type: "code", client_id: "s6BhdRkqt3",
253
+ * redirect_uri: "https://app/cb", scope: "openid", state: "xyz" },
254
+ * { clientId: "s6BhdRkqt3", audience: "https://as.example.com", key: clientKey, kid: "c1" });
255
+ * // → "eyJhbGciOiJFUzI1NiIsInR5cCI6Im9hdXRoLWF1dGh6LXJlcStqd3QiLCJraWQiOiJjMSJ9..."
256
+ */
257
+ function build(params, opts) {
258
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
259
+ throw new AuthJarError("auth-jar/bad-params",
260
+ "jar.build: params must be a plain object of authorization-request parameters");
261
+ }
262
+ validateOpts.requireObject(opts, "jar.build", AuthJarError, "auth-jar/bad-opts");
263
+ validateOpts(opts, ["clientId", "audience", "key", "alg", "kid", "expiresInMs"], "jar.build");
264
+ validateOpts.requireNonEmptyString(opts.clientId, "jar.build: clientId", AuthJarError, "auth-jar/bad-client-id");
265
+ validateOpts.requireNonEmptyString(opts.audience, "jar.build: audience", AuthJarError, "auth-jar/bad-audience");
266
+ if (opts.key === undefined || opts.key === null) {
267
+ throw new AuthJarError("auth-jar/no-key", "jar.build: key (the client's signing key) is required");
268
+ }
269
+ validateOpts.optionalNonEmptyString(opts.alg, "jar.build: alg", AuthJarError, "auth-jar/bad-alg");
270
+ validateOpts.optionalNonEmptyString(opts.kid, "jar.build: kid", AuthJarError, "auth-jar/bad-kid");
271
+ validateOpts.optionalPositiveInt(opts.expiresInMs, "jar.build: expiresInMs", AuthJarError, "auth-jar/bad-expiry");
272
+
273
+ // RFC 9101 §4 — a request object MUST NOT itself carry request /
274
+ // request_uri (recursion / confused-deputy vector). Refuse at build, the
275
+ // mirror of parse's anti-nesting check.
276
+ if (params.request !== undefined || params.request_uri !== undefined) {
277
+ throw new AuthJarError("auth-jar/nested-request",
278
+ "jar.build: params must not carry `request` or `request_uri` " +
279
+ "(RFC 9101 §4 — a request object cannot nest another)");
280
+ }
281
+ // The builder owns iss/aud and the JWT lifetime claims — a params key
282
+ // colliding with one would either shadow a builder-pinned binding (iss /
283
+ // aud) or fight the exp/nbf/jti the builder mints. Refuse so the operator
284
+ // routes lifetime through opts.expiresInMs and the identity bindings
285
+ // through clientId / audience.
286
+ for (var bi = 0; bi < BUILDER_OWNED_CLAIMS.length; bi += 1) {
287
+ var owned = BUILDER_OWNED_CLAIMS[bi];
288
+ if (Object.prototype.hasOwnProperty.call(params, owned)) {
289
+ throw new AuthJarError("auth-jar/reserved-claim",
290
+ "jar.build: params must not set the builder-owned claim '" + owned +
291
+ "' (iss/aud come from clientId/audience; exp/nbf/iat/jti are minted by the builder)");
292
+ }
293
+ }
294
+ // RFC 9101 §4 — response_type + client_id are REQUIRED request parameters.
295
+ for (var ri = 0; ri < REQUIRED_REQUEST_PARAMS.length; ri += 1) {
296
+ var req = REQUIRED_REQUEST_PARAMS[ri];
297
+ if (params[req] === undefined || params[req] === null || params[req] === "") {
298
+ throw new AuthJarError("auth-jar/missing-required-param",
299
+ "jar.build: params is missing the required '" + req + "' claim (RFC 9101 §4)");
300
+ }
301
+ }
302
+ // An explicit params.client_id MUST match opts.clientId — the iss the
303
+ // builder pins. A divergence is an operator mistake that would mint an
304
+ // object parse() then refuses on the client_id-mismatch path.
305
+ if (params.client_id !== opts.clientId) {
306
+ throw new AuthJarError("auth-jar/client-id-mismatch",
307
+ "jar.build: params.client_id ('" + params.client_id + "') must equal opts.clientId ('" +
308
+ opts.clientId + "')");
309
+ }
310
+
311
+ var nowSec = Math.floor(Date.now() / C.TIME.seconds(1));
312
+ var ttlMs = typeof opts.expiresInMs === "number" ? opts.expiresInMs : DEFAULT_JAR_EXPIRES_MS;
313
+ var claims = {
314
+ iss: opts.clientId, // RFC 9101 §5 — iss = client_id
315
+ aud: opts.audience, // RFC 9101 §5 — aud = AS issuer identifier
316
+ iat: nowSec,
317
+ nbf: nowSec,
318
+ exp: nowSec + Math.floor(ttlMs / C.TIME.seconds(1)), // FAPI-2 short window
319
+ jti: bCrypto.toBase64Url(bCrypto.generateBytes(16)), // single-use marker for the AS
320
+ };
321
+ // Every authorization-request parameter becomes a claim. Proto-pollution
322
+ // sentinels skipped; builder-owned claims passed as reserved so a stray
323
+ // collision (already refused above) can never shadow the minted set.
324
+ validateOpts.assignOwnEnumerable(claims, params, BUILDER_OWNED_CLAIMS);
325
+
326
+ // Sign through the classical-JWS primitive (b.auth.jws.sign). The typed
327
+ // header + alg-from-key + none-refusal all live there.
328
+ return jwtExternal.signExternal(claims, {
329
+ privateKey: opts.key,
330
+ alg: opts.alg,
331
+ kid: opts.kid,
332
+ typ: JAR_TYP,
333
+ });
334
+ }
335
+
175
336
  module.exports = {
176
337
  parse: parse,
338
+ build: build,
177
339
  JAR_TYP: JAR_TYP,
178
340
  AuthJarError: AuthJarError,
179
341
  };