@blamejs/core 0.8.7 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.8.x
10
10
 
11
+ - **0.8.8** (2026-05-07) — `b.middleware.requireBoundKey` + `b.audit.rotateSigningKey` / `reSignAll` + `b.circuitBreaker` top-level surface + `b.htmlBalance.checkSafe` + permissions predicate-shape audit + FIPS 140-3 boundary docs + ESLint pin. **`b.middleware.requireBoundKey`** — Bearer-API-key middleware with three-axis binding: required scopes, bound-field equality (operator pulls values from headers / query / body via `getBoundField` getters; bound-fields registered on the key are checked with constant-time match), and peer-cert fingerprint allowlist (composes with v0.8.4's `b.crypto.hashCertFingerprint` / `isCertRevoked`). Operator-supplied async `resolver(apiKey)` returns the registered record `{ id, scopes, boundFields, peerCertFingerprints }` or `null` when revoked. Refusals carry structured reasons (`no-bearer-token`, `key-unknown-or-revoked`, `missing-scope`, `bound-field-missing`, `bound-field-mismatch`, `peer-cert-required`, `peer-cert-not-pinned`); audit chain captures the keyId + reason on every refusal. **`b.audit.rotateSigningKey`** — operator-callable rotation of the audit-signing keypair. Generates (or accepts BYO) a new keypair, copies the existing sealed file to a timestamped history path so historical signatures remain verifiable, re-seals with the operator's passphrase, and atomic-swaps the in-memory keys. Companion `reSignAll(iter)` walks an operator-supplied async iterable of `{ payload, signature, oldPublicKeyPem }` and re-signs each entry with the new key — the audit module's checkpoint store calls this to re-stamp historical checkpoints after a rotation. **`b.circuitBreaker`** — top-level re-export of `b.retry.CircuitBreaker` so operators discover it alongside `b.retry`; same state machine, same `wrap()` API, ergonomic `create(opts)` factory. **`b.htmlBalance.checkSafe(html, opts)`** — combines structural `balance()` check with a `b.guardHtml.gate` security pass under the same `{ profile, posture }` opt shape used by `b.fileUpload({ contentSafety })` / `b.staticServe({ contentSafety })`. **`b.permissions.policy(scope, predicate)`** — emits `permissions.policy_predicate_shape_warning` audit on register-time when the predicate's `.length < 2` (operators commonly forget the `context` argument and ship a predicate that's always-true on the actor parameter). **`SECURITY.md`** — new "FIPS 140-3 cryptographic boundary" section explaining the dual boundary (Node.js OpenSSL FIPS provider for classical primitives, vendored noble-* implementations for PQ algorithms — the latter implement FIPS-published algorithms but the *implementations themselves* are not CMVP-validated). Operator path for FIPS-mandated environments documented. **CI** — eslint pinned to `10.3.0` across `ci.yml` / `npm-publish.yml` / `release-container.yml`; `eslint@latest` was silently letting new rule additions break the publish gate on releases that had passed the day before. The pin moves on operator-confirmed bumps.
12
+
11
13
  - **0.8.7** (2026-05-06) — `b.auth.accessLock` — three-mode access-lock primitive for stop-the-world / read-only / role-restricted operator interventions. `"open"` is normal operation; `"read-only"` refuses non-idempotent methods (POST/PUT/PATCH/DELETE) with 503 + Retry-After while letting GET/HEAD/OPTIONS pass; `"locked"` refuses everything except an operator-supplied `passthroughPaths` allowlist (status / health / unlock endpoint). Operators flip modes during incident response, schema-migration windows, or break-glass review via `lock.set("locked", { actor, reason })`; the transition emits `auth.access_lock.mode_changed` audit + metric. `unlockRoles: ["sre", ...]` lets a privileged role bypass all three modes via `getRole(req)` so a break-glass operator can always reach the unlock endpoint to flip back. The boot-time mode emits `auth.access_lock.boot` so the audit chain captures the deploy posture.
12
14
 
13
15
  - **0.8.6** (2026-05-06) — New primitives: `b.middleware.dailyByteQuota` + `b.appShutdown` extensions. **`b.middleware.dailyByteQuota`** — per-IP rolling 24-hour byte budget (24 hourly bins, slides per-second so a peer can't reset by waiting past midnight). Memory backend single-node by default; `opts.cache` wires `b.cache` for cluster-shared accounting. Refuses with 429 + `Retry-After` when peers exceed the quota; emits `middleware.daily_byte_quota.refused` audit + `middleware.daily_byte_quota.refused` metric. Inbound + outbound bytes counted (header bytes + content-length + outbound write/end byte counts). Fail-open on cache backend errors with audited reason — a flaky cache no longer takes the framework down. **`b.appShutdown` extensions** — `onUncaught` hook fires on `uncaughtException` / `unhandledRejection`; default is graceful-shutdown with exitCode=1, operators can wire a hook for relay to PagerDuty / observability before exit. `opts.signals` now accepts a custom signal list (defaults to `["SIGTERM","SIGINT"]`); operators add `SIGUSR2` (nodemon restart), `SIGHUP` (terminal disconnect), `SIGQUIT` (`kill -3`) without subclassing. `b.appShutdown.pidLock(lockPath)` — single-instance file lock that writes `process.pid`, refuses to acquire when another live process holds the lock, reaps stale lock files (PID gone), and releases on shutdown. **`b.observability.otlpExporter`** — new `system.observability.otlp_exporter.post_failed` audit emission distinguishes timeout / abort from generic network failure (operators can route timeout-rooted exporter degradation to a different alert channel). `stats()` now reports `droppedTotal` (queue overflow + export failed) and emits a `dropped_total` metric on every call so dashboards chart the running drop count. **`b.auth.oauth.fetchUserInfo`** — refuses on OIDC IdPs unless the caller threads `ufiOpts.idTokenSub` (the verified `sub` claim from `exchangeCode`'s `id_token`); cross-checks userinfo `sub === idTokenSub` to defend against token-substitution where a hostile IdP returns a different user's profile. Non-OIDC OAuth 2.0 deployments mis-flagged as `isOidc` opt out via `{ skipSubCheck: true }` with audited reason.
package/index.js CHANGED
@@ -247,6 +247,7 @@ module.exports = {
247
247
  storage: storage,
248
248
  objectStore: objectStore,
249
249
  retry: retry,
250
+ circuitBreaker: require("./lib/circuit-breaker"),
250
251
  queue: queue,
251
252
  logStream: logStream,
252
253
  redact: redact,
package/lib/audit-sign.js CHANGED
@@ -326,6 +326,158 @@ function getPublicKeyFingerprint() { _requireInit(); return keys.fingerprint; }
326
326
  function getMode() { return currentMode; }
327
327
  function getAlgorithm() { _requireInit(); return keys.algorithm; }
328
328
 
329
+ // Re-sign every payload in the operator-supplied iterable using the
330
+ // CURRENT in-memory key. Returns { reSigned: number, skipped: number,
331
+ // errors: number } so the caller (audit module's checkpoint store)
332
+ // can log a summary. Each iteration is wrapped in try/catch — a
333
+ // payload that fails to verify under the OLD key is skipped (already
334
+ // tampered or never signed under the historical key) rather than
335
+ // aborting the whole walk.
336
+ //
337
+ // The iterable yields { payload, signature, oldPublicKeyPem } so the
338
+ // caller's storage layer doesn't need to reach into audit-sign's
339
+ // internal key-history. The caller persists the new signature in
340
+ // place — this primitive returns the new bytes without touching
341
+ // storage.
342
+ async function reSignAll(iter, opts) {
343
+ _requireInit();
344
+ opts = opts || {};
345
+ var summary = { reSigned: 0, skipped: 0, errors: 0 };
346
+ var onProgress = typeof opts.onProgress === "function" ? opts.onProgress : null;
347
+ for await (var entry of iter) {
348
+ try {
349
+ if (!entry || !entry.payload || !entry.signature) {
350
+ summary.skipped += 1;
351
+ continue;
352
+ }
353
+ var oldPub = entry.oldPublicKeyPem || keys.publicKey;
354
+ if (!verify(entry.payload, entry.signature, oldPub)) {
355
+ summary.skipped += 1;
356
+ continue;
357
+ }
358
+ var newSig = sign(entry.payload);
359
+ summary.reSigned += 1;
360
+ if (onProgress) {
361
+ try { onProgress({ id: entry.id, newSignature: newSig }); }
362
+ catch (_e) { /* operator hook, drop-silent */ }
363
+ }
364
+ } catch (_e) {
365
+ summary.errors += 1;
366
+ }
367
+ }
368
+ return summary;
369
+ }
370
+
371
+ // Rotate the in-memory + on-disk keypair. Generates a fresh keypair
372
+ // (or accepts operator-supplied keypair via opts.privateKeyPem +
373
+ // publicKeyPem for the BYO-key case), writes the OLD sealed file
374
+ // to a timestamped history path so historical checkpoints can still
375
+ // be verified, then re-seals with the new keypair.
376
+ //
377
+ // rotation does NOT walk and re-sign existing audit checkpoints —
378
+ // the audit module orchestrates that via reSignAll() above so the
379
+ // per-row storage transactions stay in one place. Operators rotating
380
+ // the audit key in production typically:
381
+ // 1. Read existing audit checkpoints
382
+ // 2. Call rotateSigningKey() — gets new keys live
383
+ // 3. Walk checkpoints through reSignAll()
384
+ // 4. Write back the new signatures atomically
385
+ async function rotateSigningKey(rotOpts) {
386
+ _requireInit();
387
+ rotOpts = rotOpts || {};
388
+ var prevFingerprint = keys.fingerprint;
389
+ var prevPublicKey = keys.publicKey;
390
+ var prevAlgorithm = keys.algorithm;
391
+
392
+ // Operator may supply the new keypair (BYO; useful for a hardware-
393
+ // backed signer) or let the framework generate. The algorithm
394
+ // defaults to the current keypair's algorithm; operators upgrading
395
+ // the algorithm pass the new alg explicitly.
396
+ var newAlg;
397
+ var newPair;
398
+ if (typeof rotOpts.privateKeyPem === "string" && typeof rotOpts.publicKeyPem === "string") {
399
+ newAlg = rotOpts.algorithm || prevAlgorithm;
400
+ newPair = { publicKey: rotOpts.publicKeyPem, privateKey: rotOpts.privateKeyPem };
401
+ } else {
402
+ newAlg = rotOpts.algorithm || prevAlgorithm;
403
+ newPair = nodeCrypto.generateKeyPairSync(newAlg, {
404
+ publicKeyEncoding: { type: "spki", format: "pem" },
405
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
406
+ });
407
+ }
408
+ if (SUPPORTED_SIGNING_ALGS.indexOf(newAlg) === -1) {
409
+ throw _err("ROTATE_BAD_ALG",
410
+ "audit-sign.rotateSigningKey: algorithm '" + newAlg + "' is not in SUPPORTED_SIGNING_ALGS");
411
+ }
412
+
413
+ var newFingerprint = _computeFingerprint(newPair.publicKey);
414
+ if (newFingerprint === prevFingerprint) {
415
+ throw _err("ROTATE_NOOP",
416
+ "audit-sign.rotateSigningKey: new keypair has identical fingerprint to the current — refusing to write a no-op rotation");
417
+ }
418
+
419
+ // Move the existing sealed/plaintext file to a timestamped history
420
+ // path so historical checkpoints can still be verified by readers
421
+ // that load the old key. We keep the history forever — the file is
422
+ // small (a few KB) and signed audit checkpoints can be decades old.
423
+ var iso = new Date().toISOString().replace(/[:.]/g, "-");
424
+ if (currentMode === "wrapped" && paths && paths.sealed) {
425
+ var historyPath = paths.sealed + ".history-" + iso + "-" + prevFingerprint.slice(0, 16) /* allow:raw-byte-literal — fingerprint hex truncation count */;
426
+ try { await atomicFile.copy(paths.sealed, historyPath); }
427
+ catch (_e) { /* history copy is best-effort; the in-memory rotation still proceeds */ }
428
+ } else if (currentMode === "plaintext" && paths && paths.plaintext) {
429
+ var historyPathP = paths.plaintext + ".history-" + iso + "-" + prevFingerprint.slice(0, 16) /* allow:raw-byte-literal — fingerprint hex truncation count */;
430
+ try { await atomicFile.copy(paths.plaintext, historyPathP); }
431
+ catch (_e) { /* history copy is best-effort */ }
432
+ }
433
+
434
+ // Persist the new keypair through the same path as boot — sealed
435
+ // mode re-wraps with the operator's passphrase; plaintext mode
436
+ // writes JSON. We don't accept a passphrase override here; the
437
+ // existing in-process passphrase derivation runs again.
438
+ if (currentMode === "wrapped") {
439
+ var passphrase = await _getPassphrase("Audit-signing passphrase (rotate): ");
440
+ try {
441
+ var sealed = await vaultWrap.wrap(
442
+ JSON.stringify({ algorithm: newAlg, publicKey: newPair.publicKey, privateKey: newPair.privateKey }, null, 2),
443
+ passphrase
444
+ );
445
+ atomicFile.writeSync(paths.sealed, sealed, { fileMode: 0o600 });
446
+ } finally { safeBuffer.secureZero(passphrase); }
447
+ } else if (currentMode === "plaintext") {
448
+ atomicFile.writeSync(
449
+ paths.plaintext,
450
+ JSON.stringify({ algorithm: newAlg, publicKey: newPair.publicKey, privateKey: newPair.privateKey }, null, 2),
451
+ { fileMode: 0o600 }
452
+ );
453
+ }
454
+
455
+ // Atomic in-memory swap last (so a write failure above doesn't
456
+ // leave a half-rotated state where memory has the new key but the
457
+ // disk has the old one).
458
+ keys = {
459
+ publicKey: newPair.publicKey,
460
+ privateKey: newPair.privateKey,
461
+ algorithm: newAlg,
462
+ fingerprint: newFingerprint,
463
+ };
464
+ log("audit-signing keypair rotated (alg=" + newAlg + ", fp=" + newFingerprint.slice(0, 16) + "...)"); /* allow:raw-byte-literal — fingerprint hex truncation count */
465
+
466
+ return {
467
+ previousFingerprint: prevFingerprint,
468
+ previousPublicKey: prevPublicKey,
469
+ newFingerprint: newFingerprint,
470
+ newPublicKey: newPair.publicKey,
471
+ algorithm: newAlg,
472
+ rotatedAt: new Date().toISOString(),
473
+ historyPath: (currentMode === "wrapped" && paths && paths.sealed)
474
+ ? paths.sealed + ".history-" + iso + "-" + prevFingerprint.slice(0, 16) /* allow:raw-byte-literal — fingerprint hex truncation count */
475
+ : (currentMode === "plaintext" && paths && paths.plaintext)
476
+ ? paths.plaintext + ".history-" + iso + "-" + prevFingerprint.slice(0, 16) /* allow:raw-byte-literal — fingerprint hex truncation count */
477
+ : null,
478
+ };
479
+ }
480
+
329
481
  function _resetForTest() {
330
482
  keys = null;
331
483
  initialized = false;
@@ -338,6 +490,8 @@ module.exports = {
338
490
  init: init,
339
491
  sign: sign,
340
492
  verify: verify,
493
+ rotateSigningKey: rotateSigningKey,
494
+ reSignAll: reSignAll,
341
495
  getPublicKey: getPublicKey,
342
496
  getPublicKeyFingerprint: getPublicKeyFingerprint,
343
497
  getMode: getMode,
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ /**
3
+ * b.circuitBreaker — top-level circuit-breaker primitive.
4
+ *
5
+ * Re-exports the CircuitBreaker class previously only reachable as
6
+ * b.retry.CircuitBreaker, plus a `create(opts)` factory that matches
7
+ * every other framework primitive's `create()` shape. The
8
+ * implementation lives in lib/retry.js to keep the retry-classifier
9
+ * + CircuitBreaker close to each other (they share the
10
+ * isRetryable / observability emit conventions). This module is the
11
+ * top-level surface so operators don't have to know that retry
12
+ * happens to be the home of the circuit-breaker class.
13
+ *
14
+ * State machine:
15
+ * closed — normal flow; failures count up to failureThreshold
16
+ * open — fast-fail every call for cooldownMs
17
+ * half — first probe succeeds → close; first probe fails → re-open
18
+ *
19
+ * var cb = b.circuitBreaker.create({
20
+ * name: "upstream-billing",
21
+ * failureThreshold: 5,
22
+ * cooldownMs: b.constants.TIME.seconds(30),
23
+ * successThreshold: 2,
24
+ * audit: b.audit,
25
+ * onStateChange: function (event) {
26
+ * // event = { name, from, to, at }
27
+ * log("breaker " + event.name + " " + event.from + " -> " + event.to);
28
+ * },
29
+ * });
30
+ * await cb.wrap(function () { return upstream.callRiskyOp(); });
31
+ *
32
+ * The circuit-breaker is intended for per-target use (one instance
33
+ * per upstream service); operators sharing a breaker across
34
+ * unrelated targets defeat the failure-threshold semantic.
35
+ */
36
+
37
+ var retry = require("./retry");
38
+
39
+ // Pass-through factory — operators get the same instance shape as
40
+ // b.retry.CircuitBreaker but with the framework's `create(opts)`
41
+ // vocabulary. The breaker class is unchanged; this is a thin
42
+ // surface re-export so b.circuitBreaker is operator-discoverable
43
+ // alongside b.retry.
44
+ function create(opts) {
45
+ return new retry.CircuitBreaker(opts || {});
46
+ }
47
+
48
+ module.exports = {
49
+ create: create,
50
+ CircuitBreaker: retry.CircuitBreaker,
51
+ // Forward the error class so operators catching breaker rejections
52
+ // can `instanceof` against the framework's RetryError without
53
+ // requiring a separate b.retry import.
54
+ RetryError: retry.RetryError,
55
+ };
@@ -224,4 +224,41 @@ function check(html) {
224
224
  return null;
225
225
  }
226
226
 
227
- module.exports = { check: check };
227
+ // Optional content-safety pass for HTML rendered through the framework.
228
+ // Mirrors the same opt shape as b.fileUpload({ contentSafety }) /
229
+ // b.staticServe({ contentSafety }) so operators wiring guards across
230
+ // the stack pass a single { profile, posture } object — the pass-
231
+ // through to b.guardHtml.gate validates the HTML against the same
232
+ // strict / balanced / permissive vocabulary, plus the configured
233
+ // compliance posture.
234
+ //
235
+ // var safe = b.htmlBalance.checkSafe(html, { profile: "strict" });
236
+ // if (safe.issues.length) refuseRequest();
237
+ //
238
+ // checkSafe runs balance() first (cheap structural well-formedness),
239
+ // then guardHtml.gate({ profile }) for the security-class checks. The
240
+ // returned shape is { balanceIssue, guardIssues } so callers can
241
+ // distinguish a structural problem from a content-safety reject.
242
+ var lazyRequire = require("./lazy-require");
243
+ var _guardHtml = lazyRequire(function () { return require("./guard-html"); });
244
+
245
+ function checkSafe(html, opts) {
246
+ opts = opts || {};
247
+ var balanceIssue = check(html);
248
+ var guardIssues = [];
249
+ if (opts.profile || opts.contentSafety) {
250
+ var profile = opts.profile || (opts.contentSafety && opts.contentSafety.profile) || "strict";
251
+ var posture = opts.posture || (opts.contentSafety && opts.contentSafety.posture) || null;
252
+ var validateOpts = { profile: profile };
253
+ if (posture) validateOpts.compliancePosture = posture;
254
+ var rv = _guardHtml().validate(html, validateOpts);
255
+ if (rv && Array.isArray(rv.issues)) guardIssues = rv.issues;
256
+ }
257
+ return {
258
+ balanceIssue: balanceIssue,
259
+ guardIssues: guardIssues,
260
+ ok: !balanceIssue && guardIssues.length === 0,
261
+ };
262
+ }
263
+
264
+ module.exports = { check: check, checkSafe: checkSafe };
@@ -0,0 +1,249 @@
1
+ "use strict";
2
+ /**
3
+ * requireBoundKey middleware — Bearer-API-key auth with scope + bound-
4
+ * fields + cert-fingerprint binding.
5
+ *
6
+ * The framework's bearer-auth + dpop + requireMtls cover JWT, DPoP, and
7
+ * mTLS. requireBoundKey covers the API-key-with-binding case that
8
+ * shows up on internal service-to-service endpoints, partner API
9
+ * webhook receivers, and CI runners shipping events to a hosted
10
+ * blamejs deployment:
11
+ *
12
+ * - Authorization: Bearer <api-key>
13
+ * - the API key is registered in an operator-supplied resolver
14
+ * with: { scopes: [...], boundFields: { ... }, peerCertFingerprints: [...] }
15
+ * - the request must present a peer cert whose fingerprint is in
16
+ * peerCertFingerprints (when set)
17
+ * - the request must include the boundFields with the registered
18
+ * values (e.g. { tenantId: "acme", region: "us-east-1" }) — bound
19
+ * fields are pulled from headers / query / body via getter
20
+ * - the request must hold one of the operator-required scopes
21
+ *
22
+ * Failure mode: 401 / 403 with a structured JSON body identifying
23
+ * which check failed (operator audit trail). Audits emit
24
+ * `auth.require_bound_key.allowed` / `auth.require_bound_key.refused`
25
+ * with the api-key-id (not the secret) + reason metadata.
26
+ *
27
+ * var keys = b.middleware.requireBoundKey({
28
+ * resolver: async function (apiKey) {
29
+ * // operator-supplied — usually a DB lookup with timing-safe
30
+ * // compare. Returns { id, scopes, boundFields, peerCertFingerprints }
31
+ * // or null when the key is unknown / revoked.
32
+ * return await keyDb.findByKey(apiKey);
33
+ * },
34
+ * requiredScopes: ["webhook.ingest"],
35
+ * getBoundField: {
36
+ * tenantId: function (req) { return req.headers["x-tenant-id"]; },
37
+ * region: function (req) { return req.query.region; },
38
+ * },
39
+ * audit: b.audit,
40
+ * });
41
+ * router.post("/webhook/ingest", keys, ingestHandler);
42
+ *
43
+ * Composition with other middleware:
44
+ * - b.middleware.requireMtls runs FIRST (so req.peerCert is set)
45
+ * - b.middleware.requireBoundKey reads req.peerCert and cross-checks
46
+ *
47
+ * Defaults to fail-closed on every check; resolver throws / returns
48
+ * undefined → refused with reason "resolver-unavailable".
49
+ */
50
+
51
+ var defineClass = require("../framework-error").defineClass;
52
+ var lazyRequire = require("../lazy-require");
53
+ var validateOpts = require("../validate-opts");
54
+
55
+ var crypto = lazyRequire(function () { return require("../crypto"); });
56
+ var audit = lazyRequire(function () { return require("../audit"); });
57
+
58
+ var RequireBoundKeyError = defineClass("RequireBoundKeyError", { alwaysPermanent: true });
59
+
60
+ function _parseBearer(req) {
61
+ var h = req.headers && (req.headers.authorization || req.headers.Authorization);
62
+ if (typeof h !== "string" || h.length === 0) return null;
63
+ var m = h.match(/^Bearer\s+([\x21-\x7e]+)$/); // RFC 6750 token68
64
+ return m ? m[1] : null;
65
+ }
66
+
67
+ function _timingSafeStringEqual(a, b) {
68
+ if (typeof a !== "string" || typeof b !== "string") return false;
69
+ if (a.length !== b.length) return false;
70
+ return crypto().timingSafeEqual(Buffer.from(a), Buffer.from(b));
71
+ }
72
+
73
+ function create(opts) {
74
+ opts = opts || {};
75
+ validateOpts(opts, [
76
+ "resolver", "requiredScopes", "getBoundField",
77
+ "audit", "auditAction", "errorMessage",
78
+ "tolerateMissingPeerCert",
79
+ ], "middleware.requireBoundKey");
80
+
81
+ if (typeof opts.resolver !== "function") {
82
+ throw new RequireBoundKeyError("require-bound-key/bad-resolver",
83
+ "middleware.requireBoundKey: opts.resolver must be an async function (apiKey) -> {id, scopes, boundFields, peerCertFingerprints} | null");
84
+ }
85
+ var resolver = opts.resolver;
86
+ var requiredScopes = Array.isArray(opts.requiredScopes) ? opts.requiredScopes.slice() : [];
87
+ for (var rs = 0; rs < requiredScopes.length; rs++) {
88
+ if (typeof requiredScopes[rs] !== "string" || requiredScopes[rs].length === 0) {
89
+ throw new RequireBoundKeyError("require-bound-key/bad-scope",
90
+ "middleware.requireBoundKey: requiredScopes[" + rs + "] must be a non-empty string");
91
+ }
92
+ }
93
+ var getBoundField = (opts.getBoundField && typeof opts.getBoundField === "object")
94
+ ? opts.getBoundField : {};
95
+ var boundFieldNames = Object.keys(getBoundField);
96
+ for (var bf = 0; bf < boundFieldNames.length; bf++) {
97
+ if (typeof getBoundField[boundFieldNames[bf]] !== "function") {
98
+ throw new RequireBoundKeyError("require-bound-key/bad-bound-field-getter",
99
+ "middleware.requireBoundKey: getBoundField." + boundFieldNames[bf] + " must be a function (req) -> string");
100
+ }
101
+ }
102
+ var auditOn = opts.audit !== false;
103
+ var actionBase = typeof opts.auditAction === "string" && opts.auditAction.length > 0
104
+ ? opts.auditAction : "auth.require_bound_key";
105
+ var errorMessage = typeof opts.errorMessage === "string" && opts.errorMessage.length > 0
106
+ ? opts.errorMessage : "api key required";
107
+ // For operator-side fixtures and dev environments without an mTLS
108
+ // termination layer, allow disabling the peer-cert cross-check
109
+ // even when peerCertFingerprints is set on the registered key.
110
+ // Production deployments leave this at default false.
111
+ var tolerateMissingPeerCert = !!opts.tolerateMissingPeerCert;
112
+
113
+ function _emitAudit(outcome, metadata) {
114
+ if (!auditOn) return;
115
+ try {
116
+ audit().safeEmit({
117
+ action: actionBase + (outcome === "success" ? ".allowed" : ".refused"),
118
+ outcome: outcome,
119
+ metadata: metadata || {},
120
+ });
121
+ } catch (_e) { /* drop-silent */ }
122
+ }
123
+
124
+ function _refuse(res, status, reason, metadata) {
125
+ _emitAudit("denied", Object.assign({ reason: reason }, metadata || {}));
126
+ if (res.writableEnded || typeof res.writeHead !== "function") return;
127
+ res.writeHead(status, {
128
+ "Content-Type": "application/json; charset=utf-8",
129
+ "WWW-Authenticate": 'Bearer realm="api", error="invalid_request"',
130
+ "Cache-Control": "no-store",
131
+ });
132
+ res.end(JSON.stringify({ error: errorMessage, reason: reason }));
133
+ }
134
+
135
+ return async function requireBoundKeyMiddleware(req, res, next) {
136
+ var apiKey = _parseBearer(req);
137
+ if (!apiKey) return _refuse(res, 401, "no-bearer-token", {});
138
+
139
+ var record;
140
+ try { record = await resolver(apiKey); }
141
+ catch (e) {
142
+ return _refuse(res, 503, "resolver-unavailable", {
143
+ error: (e && e.message) || String(e),
144
+ });
145
+ }
146
+ if (!record || typeof record !== "object") {
147
+ return _refuse(res, 401, "key-unknown-or-revoked", {});
148
+ }
149
+
150
+ // Required-scope check — operator-supplied requiredScopes must be
151
+ // a subset of the registered key's scopes.
152
+ var keyScopes = Array.isArray(record.scopes) ? record.scopes : [];
153
+ for (var rsi = 0; rsi < requiredScopes.length; rsi++) {
154
+ if (keyScopes.indexOf(requiredScopes[rsi]) === -1) {
155
+ return _refuse(res, 403, "missing-scope", {
156
+ requiredScope: requiredScopes[rsi], keyId: record.id || null,
157
+ });
158
+ }
159
+ }
160
+
161
+ // Bound-field check — every key in the registered boundFields map
162
+ // must be present on the request and match. The operator's
163
+ // getBoundField extracts each value from headers / query / body.
164
+ var registered = (record.boundFields && typeof record.boundFields === "object") ? record.boundFields : {};
165
+ var registeredKeys = Object.keys(registered);
166
+ for (var bfi = 0; bfi < registeredKeys.length; bfi++) {
167
+ var fieldName = registeredKeys[bfi];
168
+ var getter = getBoundField[fieldName];
169
+ if (!getter) {
170
+ return _refuse(res, 500, "bound-field-no-getter", {
171
+ field: fieldName, keyId: record.id || null,
172
+ });
173
+ }
174
+ var presented;
175
+ try { presented = getter(req); }
176
+ catch (e) {
177
+ return _refuse(res, 400, "bound-field-getter-threw", { // allow:raw-byte-literal — HTTP 400
178
+ field: fieldName, error: (e && e.message) || String(e),
179
+ });
180
+ }
181
+ if (typeof presented !== "string" || presented.length === 0) {
182
+ return _refuse(res, 400, "bound-field-missing", { // allow:raw-byte-literal — HTTP 400
183
+ field: fieldName, keyId: record.id || null,
184
+ });
185
+ }
186
+ var expected = String(registered[fieldName]);
187
+ if (!_timingSafeStringEqual(presented, expected)) {
188
+ return _refuse(res, 403, "bound-field-mismatch", {
189
+ field: fieldName, keyId: record.id || null,
190
+ });
191
+ }
192
+ }
193
+
194
+ // Peer-cert fingerprint check — if the registered key pins peer
195
+ // certs, the request must come over mTLS with a fingerprint on
196
+ // the allowlist. b.middleware.requireMtls running upstream
197
+ // attaches req.peerCert / req.peerFingerprint; we re-derive when
198
+ // a downstream middleware order leaves them unset.
199
+ var pinned = Array.isArray(record.peerCertFingerprints) ? record.peerCertFingerprints : [];
200
+ if (pinned.length > 0) {
201
+ var fpHex = req.peerFingerprint && req.peerFingerprint.hex;
202
+ var fpColon = req.peerFingerprint && req.peerFingerprint.colon;
203
+ if (!fpHex && req.peerCert && req.peerCert.raw) {
204
+ try {
205
+ var fp = crypto().hashCertFingerprint(req.peerCert.raw);
206
+ fpHex = fp.hex; fpColon = fp.colon;
207
+ } catch (_e) { /* fall through to refused below */ }
208
+ }
209
+ if (!fpHex) {
210
+ if (tolerateMissingPeerCert) {
211
+ // Audited bypass for dev fixtures.
212
+ _emitAudit("denied", { reason: "peer-cert-bypass-tolerated", keyId: record.id });
213
+ } else {
214
+ return _refuse(res, 401, "peer-cert-required", {
215
+ keyId: record.id || null,
216
+ });
217
+ }
218
+ } else if (!crypto().isCertRevoked(req.peerCert.raw, pinned)) {
219
+ // isCertRevoked returns true on MATCH against the deny-list
220
+ // shape; we use it here as a fingerprint-set membership test
221
+ // because it does the same constant-time hex/colon comparison
222
+ // we want for an allow-list. A future refactor can rename to
223
+ // isCertFingerprintInSet — semantically identical.
224
+ return _refuse(res, 403, "peer-cert-not-pinned", {
225
+ fingerprint: fpColon, keyId: record.id || null,
226
+ });
227
+ }
228
+ }
229
+
230
+ // All checks passed. Attach the resolved record to req.apiKey for
231
+ // downstream handlers (without the secret — the resolver returned
232
+ // a normalized record, the middleware never re-exposes the bearer).
233
+ req.apiKey = {
234
+ id: record.id || null,
235
+ scopes: keyScopes.slice(),
236
+ boundFields: Object.assign({}, registered),
237
+ };
238
+ _emitAudit("success", {
239
+ keyId: record.id || null,
240
+ scopesGranted: keyScopes,
241
+ });
242
+ return next();
243
+ };
244
+ }
245
+
246
+ module.exports = {
247
+ create: create,
248
+ RequireBoundKeyError: RequireBoundKeyError,
249
+ };
@@ -300,6 +300,29 @@ function create(opts) {
300
300
  if (policies[scope]) {
301
301
  throw _err("DUPLICATE_POLICY", "permissions.policy: '" + scope + "' is already registered");
302
302
  }
303
+ // Predicate-shape sanity check — predicate(actor, context) is the
304
+ // documented contract. Operator-supplied 0-arg or 1-arg predicates
305
+ // typically indicate the operator forgot the context parameter
306
+ // and is silently always-true for any actor (the predicate
307
+ // returns based on closure state instead of inspecting the
308
+ // actor / context). Emit a one-time audit warning at register-
309
+ // time so operator-side tooling sees the misconfiguration.
310
+ if (predicate.length < 2) {
311
+ try {
312
+ if (audit && typeof audit.safeEmit === "function") {
313
+ audit.safeEmit({
314
+ action: "permissions.policy_predicate_shape_warning",
315
+ outcome: "warning",
316
+ metadata: {
317
+ scope: scope,
318
+ arity: predicate.length,
319
+ expected: "predicate(actor, context) -> bool",
320
+ hint: "predicate has " + predicate.length + " formal arg(s); the framework calls it as predicate(actor, context). Confirm the predicate inspects both args.",
321
+ },
322
+ });
323
+ }
324
+ } catch (_e) { /* drop-silent — audit is best-effort */ }
325
+ }
303
326
  policies[scope] = predicate;
304
327
  }
305
328
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:c89193b4-c13d-4dd9-882f-4581a77a92d9",
5
+ "serialNumber": "urn:uuid:44e2ace4-98b8-425c-a2f3-bd209fde34f3",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-05-07T01:02:55.563Z",
8
+ "timestamp": "2026-05-07T01:56:20.867Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.8.7",
22
+ "bom-ref": "@blamejs/core@0.8.8",
23
23
  "type": "library",
24
24
  "name": "blamejs",
25
- "version": "0.8.7",
25
+ "version": "0.8.8",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.8.7",
29
+ "purl": "pkg:npm/%40blamejs/core@0.8.8",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.8.7",
57
+ "ref": "@blamejs/core@0.8.8",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]