@blamejs/core 0.14.24 → 0.14.26
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 +4 -0
- package/lib/auth/oauth.js +25 -5
- package/lib/auth/sd-jwt-vc.js +16 -3
- package/lib/break-glass.js +153 -3
- package/lib/constants.js +11 -0
- package/lib/crypto-field.js +307 -78
- package/lib/db-query.js +65 -5
- package/lib/db.js +17 -3
- package/lib/dsr.js +378 -52
- package/lib/middleware/idempotency-key.js +21 -13
- package/lib/queue-local.js +23 -1
- package/lib/queue.js +7 -0
- package/lib/request-helpers.js +7 -0
- package/lib/retention.js +11 -1
- package/lib/vault/rotate.js +64 -44
- package/lib/vault-aad.js +6 -0
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
|
|
|
8
8
|
|
|
9
9
|
## v0.14.x
|
|
10
10
|
|
|
11
|
+
- v0.14.26 (2026-06-06) — **Break-glass IP and session pins fail closed, DSR ticket PII is sealed and erasable, and queue jobs are sealed at rest from the first write.** Break-glass grant pins (`pinIp` / `sessionPin`, documented default-ON) were enforced only when the grant had captured a binding at mint time; a grant minted without an IP or session was redeemable from anywhere, so the pin failed open exactly when it mattered. Pins now fail closed: a grant carrying no binding is refused at redemption, and the redeeming client IP falls back to `req.ip` when not threaded explicitly. The Data Subject Request ticket store kept the subject's identifiers and the raw request body in plaintext, so an erasure request could not destroy the very PII it was processing; those columns are now sealed under the vault with `(table, rowId)` additional-data binding, erasure purges the ticket on completion, and an in-place schema upgrade seals existing stores. Queue jobs were sealed at rest only after a table had been registered, which did not happen until the first explicit registration — the queue now self-registers its job table on `init`, so jobs are sealed from the first write. Rounding out the bundle: the OAuth back-channel-logout `logout_token` is parsed under a byte ceiling, the SD-JWT-VC holder key-binding JWT signs with an algorithm asserted against the holder key's type (an RSA or OKP holder no longer mints a self-invalid token), and a pushed authorization request carrying a signed request object emits `authorization_details` as a native array. **Security:** *Break-glass IP and session pins fail closed* — `b.breakGlass` grants document `pinIp` and `sessionPin` as default-ON, and grant minting captures the issuing IP and session at that time. Redemption now refuses a grant whose binding was never captured (`pinIp` on but no IP recorded, or `sessionPin` on but no session) instead of treating the absent binding as 'nothing to check' and allowing the redemption from any origin. The redeeming client IP is resolved from the redemption request and falls back to `req.ip` when the caller does not thread an explicit address. The one-time-code replay floor is keyed per `(actor, secret)` so a code consumed under one actor cannot be replayed under another, and the accepted TOTP step is reserved atomically as part of acceptance, so two concurrent grants presenting the same in-window code cannot both pass. · *DSR ticket store seals subject identifiers and request payload, and erasure purges the ticket* — `b.dsr` with the database-backed ticket store now seals the data subject's identifiers and the raw request payload via `b.cryptoField.registerTable` with `(table, rowId)` additional-data binding, so the PII a request processes is encrypted at rest and is destroyed when the ticket's row key is shredded. An erasure request purges its own ticket on completion rather than leaving the subject's identifiers behind. Existing ticket stores are upgraded in place on the next `init` — sealed columns are added via `ALTER TABLE ADD COLUMN` and the legacy `payload NOT NULL` constraint relaxes to `DEFAULT ''` so the add succeeds without data loss. Wrapped ticket keys are re-sealed under the new root on vault keypair rotation (`b.dsr.reseal`), so rotation does not strand tickets. Rows written before the upgrade (plaintext subject, no lookup hash) are backfilled on the next `init` — their hashes are computed and their subject columns sealed — so a subject lookup still finds them and an erasure request can purge them. · *Queue jobs are sealed at rest from the first write* — The local queue backend self-registers its job table for sealing on `init` rather than on first explicit registration, so a job persisted before any other code touched the seal table is encrypted at rest instead of written in plaintext. `b.cryptoField.sealRow` is a silent no-op against an unregistered table; the self-register on `init` closes that fail-open window for the queue's own rows. · *OAuth back-channel logout is bounded; SD-JWT-VC holder binding matches the holder key type* — The OAuth back-channel-logout endpoint parses the `logout_token` under an explicit byte ceiling, so an unauthenticated caller cannot exhaust memory with an oversized body. The SD-JWT-VC holder key-binding JWT now signs with an algorithm asserted against the holder key's type, so a holder presenting an RSA or OKP key no longer mints a key-binding JWT that fails its own verification. A pushed authorization request (PAR) that carries a signed request object emits `authorization_details` as a native JSON array per RFC 9396, not a JSON-encoded string. · *Vault keypair rotation writes its staging files with exclusive, no-follow create* — Every file the rotation pipeline writes into its staging directory — the re-encrypted database, the resealed vault and database keys, additional sealed files, the derived-hash material, and the transient plaintext database — is now created with exclusive, symlink-refusing semantics (`O_CREAT | O_EXCL | O_NOFOLLOW`, owner-only `0o600`), and the fsync-by-path step refuses to follow a symlink. A same-user pre-planted file or symlink swap in the staging directory is now a hard failure rather than a followed write, closing a local tamper window during rotation (CWE-377 / CWE-379 / CWE-59) on top of the directory's existing `0o700` owner-only permissions. **Detectors:** *break-glass-pin-fails-open-on-null-binding* — The pattern catalog refuses a break-glass pin comparison guarded by a `grantRow.ip != null &&` (or `sessionId`) short-circuit — a guard that skips enforcement when the captured binding is absent, which is precisely the fail-open. Pin enforcement must refuse a grant with no captured binding, not wave it through. · *dsr-ticket-store-pii-must-be-sealed* — The catalog requires the DSR database ticket store to register its seal table, so the subject identifiers and request payload it holds cannot regress to plaintext-at-rest and remain un-erasable. The queue self-register, the bounded logout parse, and the holder key-type parity are covered by their expanded request-driven tests and the existing fixed-classical-algorithm-default guard. **Migration:** *Break-glass grants now require a resolvable binding to redeem under default pins* — With `pinIp` left at its default (on), a grant is now refused at redemption unless the issuing IP was captured and the redeeming client IP can be resolved. In-tree redemption paths thread the request and resolve the IP automatically. If your redemption path does not surface a client address and you do not intend to bind to IP, set `pinIp: false` (and `sessionPin: false`) explicitly on the grant; the previous behavior silently accepted such grants from any origin. · *DSR ticket stores are sealed in place on next init* — An existing database-backed DSR ticket store gains sealed columns via `ALTER TABLE ADD COLUMN` on the next `init`, and the legacy `payload NOT NULL` constraint relaxes to `DEFAULT ''` to permit the in-place add. No data is lost; tickets written before the upgrade remain readable and become sealed as they are rewritten.
|
|
12
|
+
|
|
13
|
+
- v0.14.25 (2026-06-06) — **Per-row crypto-shred is real and AAD-bound, and the idempotency fingerprint key is sealed at rest.** The per-row encryption-key feature that backs `b.subject.eraseHard` crypto-shred was both non-functional and, as documented, unsound: the per-row key (`K_row`) was derived deterministically from a salt that is stored in plaintext in the data directory, so an actor with disk access could re-derive it and decrypt 'shredded' residual ciphertext (WAL / replica / backup) — and the key was never actually materialized on insert, so no table ever used it. Per-row keys are now derived from a fresh 32-byte CSPRNG secret stored only in `_blamejs_per_row_keys`, wrapped under the vault with AEAD additional-data binding `(table, rowId)`, and materialized on insert for tables that declare them; destroying the wrapped secret now genuinely renders the row's residual ciphertext undecryptable. The same plaintext-salt class is fixed for the idempotency request-fingerprint HMAC, which now seeds off the sealed-at-rest `vault.getDerivedHashMacKey()`. There is no migration: the per-row-key table was empty in every deployment, so keyed tables are correct from their first write. **Security:** *Per-row crypto-shred: random secret, AAD-bound wrap, materialized on insert* — `b.cryptoField.declarePerRowKey` tables now get a per-row key derived from a fresh `b.crypto.generateBytes(32)` secret — never from the plaintext per-deployment salt — so the key has no input recomputable from disk. The secret is stored in `_blamejs_per_row_keys` wrapped via `b.vault.aad.seal` with additional-data bound to `(table, rowId)`, so a wrapped key copied onto another row fails its Poly1305 tag. Sealed columns are encrypted under the per-row key and tagged with a `vault.row:` envelope (`b.cryptoField.isRowSealed`); the residency-tag column is never key-sealed so the write-boundary residency gate can still read it. The key is materialized on insert (it previously never was) and re-derived once per read; `b.subject.eraseHard` and the retention sweep destroy the wrapped secret, after which the row's residual ciphertext reads as absent and cannot be recovered even if the vault root is later compromised. Wrapped keys are re-sealed under the new root on vault keypair rotation, so rotation does not strand keyed rows. · *Idempotency request-fingerprint HMAC seeds off the sealed MAC key* — The `fingerprintSeal` HMAC over the request fingerprint was keyed from the plaintext per-deployment salt, so a disk-access actor could recompute the key and brute-force the low-entropy preimage (method + URL + body) offline. It now seeds off `b.vault.getDerivedHashMacKey()`, which is sealed at rest. Fingerprints cached before the upgrade no longer match, so a replayed request re-executes once (the safe direction). **Detectors:** *kdf-key-from-plaintext-derived-hash-salt* — The pattern catalog refuses a key-derivation (`kdf(... getDerivedHashSalt() ...)`) that seeds a per-row shred key or a vault-secret-promising keyed-MAC off the plaintext-on-disk derived-hash salt. Such a key is re-derivable by anyone with the data directory, defeating the shred / secrecy it advertises; the correct sources are a CSPRNG secret or the sealed `getDerivedHashMacKey()`. The deterministic salted-SHA3 equality index is a distinct shape and is unaffected. **Migration:** *No action required* — No data migration: the per-row-key table was empty in every deployment, so tables that declare per-row keys are correct from their first write going forward. The only observable change is that the first request after upgrade matching a pre-upgrade idempotency fingerprint re-executes once.
|
|
14
|
+
|
|
11
15
|
- 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
16
|
|
|
13
17
|
- 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.
|
package/lib/auth/oauth.js
CHANGED
|
@@ -2016,13 +2016,19 @@ function create(opts) {
|
|
|
2016
2016
|
if (uopts.prompt) authzParams.prompt = uopts.prompt;
|
|
2017
2017
|
if (uopts.loginHint) authzParams.login_hint = uopts.loginHint;
|
|
2018
2018
|
if (uopts.maxAge != null) authzParams.max_age = String(uopts.maxAge);
|
|
2019
|
-
// RFC 9396 — push the fine-grained authorization request through PAR
|
|
2020
|
-
//
|
|
2019
|
+
// RFC 9396 — push the fine-grained authorization request through PAR.
|
|
2020
|
+
// On the plain-form branch the value is a form parameter (JSON STRING);
|
|
2021
|
+
// on the signed-request-object branch it becomes a JAR claim and MUST
|
|
2022
|
+
// be the native JSON ARRAY (RFC 9101/9396) — a conforming AS rejects a
|
|
2023
|
+
// string-valued authorization_details claim. Carry the validated array
|
|
2024
|
+
// and serialize ONLY when it travels as a form param.
|
|
2021
2025
|
var requestedAuthzDetails = null;
|
|
2022
2026
|
if (uopts.authorizationDetails !== undefined) {
|
|
2023
2027
|
requestedAuthzDetails = _validateAuthorizationDetailsArray(
|
|
2024
2028
|
uopts.authorizationDetails, "pushAuthorizationRequest");
|
|
2025
|
-
authzParams.authorization_details =
|
|
2029
|
+
authzParams.authorization_details = sro
|
|
2030
|
+
? requestedAuthzDetails // JAR claim — native array
|
|
2031
|
+
: JSON.stringify(requestedAuthzDetails); // form param — JSON string
|
|
2026
2032
|
}
|
|
2027
2033
|
if (uopts.extraParams && typeof uopts.extraParams === "object") {
|
|
2028
2034
|
var ek = Object.keys(uopts.extraParams);
|
|
@@ -2160,9 +2166,18 @@ function create(opts) {
|
|
|
2160
2166
|
// store — operators wire b.cache or b.db.
|
|
2161
2167
|
async function verifyBackchannelLogoutToken(logoutToken, vopts) {
|
|
2162
2168
|
vopts = vopts || {};
|
|
2163
|
-
|
|
2169
|
+
// Type / non-empty / length-cap gate, folded into one bounds check.
|
|
2170
|
+
// The cap runs BEFORE the split + base64url decode — an attacker-
|
|
2171
|
+
// reachable endpoint can POST an arbitrarily large logout_token, and
|
|
2172
|
+
// bounding it first stops the decode from allocating unbounded memory.
|
|
2173
|
+
var logoutTokenIsString = typeof logoutToken === "string";
|
|
2174
|
+
if (!logoutTokenIsString || logoutToken.length === 0) {
|
|
2164
2175
|
throw new OAuthError("auth-oauth/bad-logout-token",
|
|
2165
2176
|
"verifyBackchannelLogoutToken: logoutToken must be a non-empty string");
|
|
2177
|
+
} else if (logoutToken.length > OAUTH_MAX_RESPONSE_BYTES) {
|
|
2178
|
+
throw new OAuthError("auth-oauth/logout-token-too-large",
|
|
2179
|
+
"verifyBackchannelLogoutToken: logout_token exceeds " +
|
|
2180
|
+
OAUTH_MAX_RESPONSE_BYTES + " bytes");
|
|
2166
2181
|
}
|
|
2167
2182
|
var parts = logoutToken.split(".");
|
|
2168
2183
|
if (parts.length !== 3) {
|
|
@@ -2170,7 +2185,12 @@ function create(opts) {
|
|
|
2170
2185
|
"verifyBackchannelLogoutToken: logout_token must be a 3-segment JWS");
|
|
2171
2186
|
}
|
|
2172
2187
|
var headerObj;
|
|
2173
|
-
|
|
2188
|
+
// Route the pre-verify header parse through safeJson (size-bounded) like
|
|
2189
|
+
// the in-module id_token / JWS-header siblings — the bare JSON.parse on
|
|
2190
|
+
// an attacker-reachable, not-yet-signature-checked header was the one
|
|
2191
|
+
// unbounded parse on this surface. The JWS signature is verified by
|
|
2192
|
+
// verifyIdToken below.
|
|
2193
|
+
try { headerObj = safeJson.parse(_b64urlDecode(parts[0]).toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES }); }
|
|
2174
2194
|
catch (_e) {
|
|
2175
2195
|
throw new OAuthError("auth-oauth/bad-logout-header",
|
|
2176
2196
|
"verifyBackchannelLogoutToken: malformed header");
|
package/lib/auth/sd-jwt-vc.js
CHANGED
|
@@ -482,9 +482,13 @@ async function verify(presentation, opts) {
|
|
|
482
482
|
"verify: issuerKeyResolver returned no key");
|
|
483
483
|
}
|
|
484
484
|
// CVE-2026-22817 — when issuerKeyResolver returns a JWK object,
|
|
485
|
-
// cross-check alg/kty BEFORE handing it to
|
|
486
|
-
// KeyObject / PEM shapes can't surface kty so
|
|
487
|
-
// JWK
|
|
485
|
+
// cross-check the issuer JWS alg/kty BEFORE handing it to
|
|
486
|
+
// node:crypto.verify. KeyObject / PEM shapes can't surface kty, so this
|
|
487
|
+
// guard only fires when the resolver hands back a JWK (the common path).
|
|
488
|
+
// The holder KB-JWT path applies its OWN _assertAlgKtyMatch against the
|
|
489
|
+
// cnf.jwk below — note that the holder key is issuer-ATTESTED (it comes
|
|
490
|
+
// from the cryptographically-verified issuer payload's cnf claim), not
|
|
491
|
+
// header-resolved, so the two cross-checks defend different trust edges.
|
|
488
492
|
if (typeof issuerKey === "object" &&
|
|
489
493
|
!(issuerKey instanceof nodeCrypto.KeyObject) &&
|
|
490
494
|
!Buffer.isBuffer(issuerKey) &&
|
|
@@ -610,6 +614,15 @@ async function verify(presentation, opts) {
|
|
|
610
614
|
throw new AuthError("auth-sd-jwt-vc/unsupported-alg",
|
|
611
615
|
"verify: KB-JWT alg unsupported");
|
|
612
616
|
}
|
|
617
|
+
// CVE-2026-22817 — cross-check the KB-JWT header alg against the holder
|
|
618
|
+
// key type BEFORE importing the key / verifying. The issuer path does
|
|
619
|
+
// this for issuerKey (above); the holder KB-JWT path must too. The
|
|
620
|
+
// KB-JWT header alg is attacker-controllable (the holder mints the
|
|
621
|
+
// KB-JWT), and holderKey is a cnf.jwk with a kty, so an alg/kty
|
|
622
|
+
// mismatch (e.g. a header claiming EdDSA against an EC cnf key) is
|
|
623
|
+
// refused with the precise alg-mismatch error rather than handed to
|
|
624
|
+
// node:crypto.verify.
|
|
625
|
+
jwtExternal._assertAlgKtyMatch(kbAlg, holderKey);
|
|
613
626
|
var holderKeyObj = nodeCrypto.createPublicKey({ key: holderKey, format: "jwk" });
|
|
614
627
|
var kbParsed = _verifyJwt(maybeKbJwt, holderKeyObj, kbAlg);
|
|
615
628
|
if (opts.audience && kbParsed.payload.aud !== opts.audience) {
|
package/lib/break-glass.js
CHANGED
|
@@ -75,6 +75,10 @@ var DEK_BYTES = C.BYTES.bytes(32);
|
|
|
75
75
|
var GRANT_ID_BYTES = C.BYTES.bytes(16);
|
|
76
76
|
|
|
77
77
|
var DEFAULT_GRANT_TTL_MS = C.TIME.minutes(15);
|
|
78
|
+
// Replay-step retention. A TOTP code is only valid inside the verifier's
|
|
79
|
+
// drift window (minutes); retaining the highest-accepted step for an hour
|
|
80
|
+
// guarantees any in-window replay attempt arrives after the floor is set.
|
|
81
|
+
var REPLAY_STEP_TTL_MS = C.TIME.hours(1);
|
|
78
82
|
var DEFAULT_MAX_ROWS = 1; // operator-locked: row-by-row auth
|
|
79
83
|
var DEFAULT_REASON_MIN_LEN = 12;
|
|
80
84
|
var DEFAULT_LOCKED_BEHAVIOR = "throw"; // or "redact"
|
|
@@ -817,10 +821,58 @@ function _verifyTotpFactor(factor) {
|
|
|
817
821
|
if (!factor || typeof factor !== "object") return { ok: false };
|
|
818
822
|
if (typeof factor.secret !== "string" || factor.secret.length === 0) return { ok: false };
|
|
819
823
|
if (typeof factor.code !== "string" || factor.code.length === 0) return { ok: false };
|
|
820
|
-
|
|
824
|
+
// factor.now threads a deterministic test clock into totp.verify. The
|
|
825
|
+
// replay floor is NOT applied here: acceptance reserves the matched step
|
|
826
|
+
// atomically in _reserveTotpStep, so two concurrent grants presenting the
|
|
827
|
+
// same in-window code cannot both pass (a read-then-commit floor races —
|
|
828
|
+
// both reads observe the old floor before either commits). totp.verify
|
|
829
|
+
// returns the step the code matches (a fixed value for a given code within
|
|
830
|
+
// the drift window) or false; the reserve then floors replays of that step.
|
|
831
|
+
var vopts = {};
|
|
832
|
+
if (typeof factor.now === "number") vopts.now = factor.now;
|
|
833
|
+
var verified = totp.verify(factor.secret, factor.code, vopts);
|
|
821
834
|
return { ok: verified !== false, step: verified };
|
|
822
835
|
}
|
|
823
836
|
|
|
837
|
+
// Replay-step cache key. Keyed by BOTH the actorId AND a non-reversible
|
|
838
|
+
// fingerprint of the TOTP secret. Keying on actorId alone would falsely
|
|
839
|
+
// reject a legitimate second grant when two distinct credentials accept a
|
|
840
|
+
// code at the same TOTP step (the step number is a wall-clock counter, not
|
|
841
|
+
// per-credential) — the secret fingerprint disambiguates them. The secret
|
|
842
|
+
// never reaches the cache in any reversible form.
|
|
843
|
+
function _replayStepKey(actorId, secret) {
|
|
844
|
+
return "totp-step:" + actorId + ":" + sha3Hash(secret);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// Atomically reserve the accepted TOTP step for (actorId, secret): advance
|
|
848
|
+
// the stored replay floor to `step` only when `step` is strictly above the
|
|
849
|
+
// current floor, and report whether THIS caller won the reservation. The
|
|
850
|
+
// compare-and-advance is one atomic cache update, so two concurrent grant()
|
|
851
|
+
// calls presenting the same in-window code cannot both pass — the first wins
|
|
852
|
+
// and raises the floor to `step`, the second observes step <= floor and is
|
|
853
|
+
// refused. (A separate read-then-commit sequence let both reads see the old
|
|
854
|
+
// floor before either committed, so both verified — the replay this closes.)
|
|
855
|
+
// The TTL outlives the verify drift window many times over so a replayed code
|
|
856
|
+
// stays floored until it expires.
|
|
857
|
+
//
|
|
858
|
+
// Fails CLOSED (returns false) on a cache fault: a grant cannot proceed
|
|
859
|
+
// without a working factor cache regardless — the lockout check at the top of
|
|
860
|
+
// grant() already gates on the same cache — so refusing here can only reject,
|
|
861
|
+
// never loosen replay protection.
|
|
862
|
+
async function _reserveTotpStep(actorId, secret, step) {
|
|
863
|
+
_ensureFactorLockout();
|
|
864
|
+
if (typeof step !== "number") return false;
|
|
865
|
+
var won = false;
|
|
866
|
+
try {
|
|
867
|
+
await _factorLockoutCache.update(_replayStepKey(actorId, secret), function (prior) {
|
|
868
|
+
if (typeof prior === "number" && step <= prior) { won = false; return { value: prior }; }
|
|
869
|
+
won = true;
|
|
870
|
+
return { value: step };
|
|
871
|
+
}, { ttlMs: REPLAY_STEP_TTL_MS });
|
|
872
|
+
} catch (_e) { return false; }
|
|
873
|
+
return won;
|
|
874
|
+
}
|
|
875
|
+
|
|
824
876
|
// Passkey factor — operator presents a WebAuthn assertion plus the
|
|
825
877
|
// challenge/origin/RPID + the previously-enrolled credential record.
|
|
826
878
|
// Phishing-resistant; the private key lives on the YubiKey, not in
|
|
@@ -990,8 +1042,20 @@ async function grant(opts) {
|
|
|
990
1042
|
}
|
|
991
1043
|
|
|
992
1044
|
var factorOk = false;
|
|
1045
|
+
var totpSecret = null;
|
|
993
1046
|
if (factorType === "totp") {
|
|
994
|
-
|
|
1047
|
+
totpSecret = opts.factor && opts.factor.secret;
|
|
1048
|
+
// Verify the code, then atomically reserve the step it matched as the act
|
|
1049
|
+
// of acceptance. The reserve advances the per-(actor,secret) replay floor
|
|
1050
|
+
// in one compare-and-set, so a code already redeemed inside the drift
|
|
1051
|
+
// window — including by a concurrent grant for the same credential — is
|
|
1052
|
+
// refused. (A read-then-commit floor raced: both grants read the old
|
|
1053
|
+
// floor before either committed, so both passed.)
|
|
1054
|
+
var totpResult = _verifyTotpFactor(opts.factor);
|
|
1055
|
+
if (totpResult.ok && typeof totpResult.step === "number" &&
|
|
1056
|
+
typeof totpSecret === "string" && totpSecret.length > 0) {
|
|
1057
|
+
factorOk = await _reserveTotpStep(actorId, totpSecret, totpResult.step);
|
|
1058
|
+
}
|
|
995
1059
|
} else if (factorType === "passkey") {
|
|
996
1060
|
factorOk = (await _verifyPasskeyFactor(opts.factor)).ok;
|
|
997
1061
|
}
|
|
@@ -1086,6 +1150,78 @@ function _reasonForAudit(reason, mode) {
|
|
|
1086
1150
|
return out;
|
|
1087
1151
|
}
|
|
1088
1152
|
|
|
1153
|
+
// Enforce the grant's IP / session bindings at redemption. policy.set
|
|
1154
|
+
// documents pinIp / sessionPin as default-ON, and grant() captures
|
|
1155
|
+
// grantRow.ip / grantRow.sessionId at mint time — but without this gate
|
|
1156
|
+
// the bindings are stored-and-never-enforced (a grant minted from IP-A
|
|
1157
|
+
// would redeem from IP-B). Called BEFORE the SELECT-then-increment so a
|
|
1158
|
+
// mismatch does not consume a grant.
|
|
1159
|
+
//
|
|
1160
|
+
// FAIL-CLOSED: when a pin is requested but the binding was captured null
|
|
1161
|
+
// (e.g. an Express-shaped req whose IP requestHelpers.clientIp couldn't
|
|
1162
|
+
// read at mint time), the redemption is REFUSED rather than silently
|
|
1163
|
+
// skipped — a `grantRow.ip != null` short-circuit would defeat the pin
|
|
1164
|
+
// for exactly the requests whose binding capture failed.
|
|
1165
|
+
function _enforceGrantPins(policy, grantRow, redeemReq, actorFor) {
|
|
1166
|
+
if (!policy) return;
|
|
1167
|
+
if (policy.pinIp) {
|
|
1168
|
+
if (grantRow.ip == null) {
|
|
1169
|
+
audit.safeEmit({
|
|
1170
|
+
action: "breakglass.unsealrow",
|
|
1171
|
+
outcome: "denied",
|
|
1172
|
+
actor: actorFor(grantRow),
|
|
1173
|
+
reason: "grant-ip-binding-missing",
|
|
1174
|
+
metadata: { grantId: grantRow._id, table: grantRow.scopeTable },
|
|
1175
|
+
});
|
|
1176
|
+
throw new BreakGlassError("breakglass/grant-ip-mismatch",
|
|
1177
|
+
"unsealRow: grant " + grantRow._id + " has pinIp on but no IP was " +
|
|
1178
|
+
"captured at mint (fail-closed) — re-mint from a request whose client " +
|
|
1179
|
+
"IP the framework can resolve", true);
|
|
1180
|
+
}
|
|
1181
|
+
var redeemIp = requestHelpers.clientIp(redeemReq, { trustProxy: _trustProxy });
|
|
1182
|
+
if (redeemIp !== grantRow.ip) {
|
|
1183
|
+
audit.safeEmit({
|
|
1184
|
+
action: "breakglass.unsealrow",
|
|
1185
|
+
outcome: "denied",
|
|
1186
|
+
actor: actorFor(grantRow),
|
|
1187
|
+
reason: "grant-ip-mismatch",
|
|
1188
|
+
metadata: { grantId: grantRow._id, table: grantRow.scopeTable },
|
|
1189
|
+
});
|
|
1190
|
+
throw new BreakGlassError("breakglass/grant-ip-mismatch",
|
|
1191
|
+
"unsealRow: grant " + grantRow._id + " is pinned to its issuing IP " +
|
|
1192
|
+
"and this redemption arrived from a different address", true);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
if (policy.sessionPin) {
|
|
1196
|
+
if (grantRow.sessionId == null) {
|
|
1197
|
+
audit.safeEmit({
|
|
1198
|
+
action: "breakglass.unsealrow",
|
|
1199
|
+
outcome: "denied",
|
|
1200
|
+
actor: actorFor(grantRow),
|
|
1201
|
+
reason: "grant-session-binding-missing",
|
|
1202
|
+
metadata: { grantId: grantRow._id, table: grantRow.scopeTable },
|
|
1203
|
+
});
|
|
1204
|
+
throw new BreakGlassError("breakglass/grant-session-mismatch",
|
|
1205
|
+
"unsealRow: grant " + grantRow._id + " has sessionPin on but no " +
|
|
1206
|
+
"session id was captured at mint (fail-closed) — re-mint from a " +
|
|
1207
|
+
"request carrying req.session.id", true);
|
|
1208
|
+
}
|
|
1209
|
+
var redeemSession = (redeemReq && redeemReq.session && redeemReq.session.id) || null;
|
|
1210
|
+
if (redeemSession !== grantRow.sessionId) {
|
|
1211
|
+
audit.safeEmit({
|
|
1212
|
+
action: "breakglass.unsealrow",
|
|
1213
|
+
outcome: "denied",
|
|
1214
|
+
actor: actorFor(grantRow),
|
|
1215
|
+
reason: "grant-session-mismatch",
|
|
1216
|
+
metadata: { grantId: grantRow._id, table: grantRow.scopeTable },
|
|
1217
|
+
});
|
|
1218
|
+
throw new BreakGlassError("breakglass/grant-session-mismatch",
|
|
1219
|
+
"unsealRow: grant " + grantRow._id + " is pinned to its issuing " +
|
|
1220
|
+
"session and this redemption arrived from a different session", true);
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1089
1225
|
// ---- Use a grant ----
|
|
1090
1226
|
|
|
1091
1227
|
/**
|
|
@@ -1195,6 +1331,13 @@ async function unsealRow(grantHandle, table, rowId, opts) {
|
|
|
1195
1331
|
grantRow.maxRowsPerGrant + " allowed rows", true);
|
|
1196
1332
|
}
|
|
1197
1333
|
|
|
1334
|
+
// IP / session pin enforcement — BEFORE the SELECT-then-increment so a
|
|
1335
|
+
// pin mismatch does not consume the grant. Fail-closed when a requested
|
|
1336
|
+
// pin's binding was captured null (see _enforceGrantPins). The policy is
|
|
1337
|
+
// fetched once here and reused for the Model-A/B unseal dispatch below.
|
|
1338
|
+
var policy = await policyGet(table);
|
|
1339
|
+
_enforceGrantPins(policy, grantRow, opts.req, _actorFor);
|
|
1340
|
+
|
|
1198
1341
|
// SELECT-before-increment — fetch the target row FIRST. If the row
|
|
1199
1342
|
// doesn't exist (operator typo, race with row-deletion, etc.), the
|
|
1200
1343
|
// grant should not be consumed. Without this ordering, a single
|
|
@@ -1237,7 +1380,8 @@ async function unsealRow(grantHandle, table, rowId, opts) {
|
|
|
1237
1380
|
"unsealRow: grant " + grantHandle.id + " was exhausted by a concurrent read", true);
|
|
1238
1381
|
}
|
|
1239
1382
|
void updateRes;
|
|
1240
|
-
|
|
1383
|
+
// policy was fetched above for the pin enforcement; reuse it for the
|
|
1384
|
+
// Model-A vs Model-B (cryptographic) unseal dispatch.
|
|
1241
1385
|
var unsealedRow;
|
|
1242
1386
|
if (policy && policy.cryptographic) {
|
|
1243
1387
|
// Snapshot the raw glass-locked column ciphertexts BEFORE
|
|
@@ -1427,6 +1571,12 @@ async function listActive(opts) {
|
|
|
1427
1571
|
* distinct `breakglass.grant.bypass` audit row so post-incident review
|
|
1428
1572
|
* separates operator-initiated reads from scheduled-job reads.
|
|
1429
1573
|
*
|
|
1574
|
+
* This path is service-to-service: it consumes NO grant row, so the
|
|
1575
|
+
* `pinIp` / `sessionPin` grant bindings enforced by `unsealRow` do not
|
|
1576
|
+
* apply here. A grant that was minted with those pins is not redeemable
|
|
1577
|
+
* through this surface — the bypass is gated solely by the
|
|
1578
|
+
* `serviceAccountBypass` allowlist + required-role check.
|
|
1579
|
+
*
|
|
1430
1580
|
* @opts
|
|
1431
1581
|
* reason: string, // operator-supplied reason recorded into the audit row
|
|
1432
1582
|
*
|
package/lib/constants.js
CHANGED
|
@@ -179,6 +179,16 @@ var TLS_GROUP_CURVE_STR = TLS_GROUP_PREFERENCE.join(":");
|
|
|
179
179
|
// ---- Vault sealed-value prefix ----
|
|
180
180
|
var VAULT_PREFIX = "vault:";
|
|
181
181
|
|
|
182
|
+
// ---- Per-row-key sealed-column prefix ----
|
|
183
|
+
// Columns encrypted under a row-scoped key (K_row) — distinct from the
|
|
184
|
+
// vault-root `vault:` / AAD-bound `vault.aad:` prefixes so the read path
|
|
185
|
+
// can route a cell to its decrypt: K_row-sealed cells unwrap the row's
|
|
186
|
+
// secret from `_blamejs_per_row_keys`, derive K_row, then decrypt under
|
|
187
|
+
// it (XChaCha20-Poly1305, AEAD-bound to (table, rowId, column,
|
|
188
|
+
// schemaVersion)). Destroying the row's wrapped secret leaves these
|
|
189
|
+
// cells mathematically undecryptable — the crypto-shred substrate.
|
|
190
|
+
var ROW_PREFIX = "vault.row:";
|
|
191
|
+
|
|
182
192
|
// ---- Default hash namespaces for derived-hash indexed lookups ----
|
|
183
193
|
// Apps add their own via app-config registries. The 'bj-' namespace
|
|
184
194
|
// prevents collision between framework-derived and app-derived hashes.
|
|
@@ -205,5 +215,6 @@ module.exports = {
|
|
|
205
215
|
TLS_GROUP_PREFERENCE: TLS_GROUP_PREFERENCE,
|
|
206
216
|
TLS_GROUP_CURVE_STR: TLS_GROUP_CURVE_STR,
|
|
207
217
|
VAULT_PREFIX: VAULT_PREFIX,
|
|
218
|
+
ROW_PREFIX: ROW_PREFIX,
|
|
208
219
|
HASH_PREFIX: HASH_PREFIX,
|
|
209
220
|
};
|