@blamejs/core 0.6.13 → 0.6.20

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/lib/network.js ADDED
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+
3
+ var ntpCheck = require("./ntp-check");
4
+ var nts = require("./network-nts");
5
+ var dns = require("./network-dns");
6
+ var proxy = require("./network-proxy");
7
+ var trust = require("./network-tls");
8
+ var heartbeat = require("./network-heartbeat");
9
+
10
+ var validateOpts = require("./validate-opts");
11
+ var lazyRequire = require("./lazy-require");
12
+ var { defineClass } = require("./framework-error");
13
+
14
+ var NetworkError = defineClass("NetworkError", { alwaysPermanent: true });
15
+
16
+ var observability = lazyRequire(function () { return require("./observability"); });
17
+ var audit = lazyRequire(function () { return require("./audit"); });
18
+
19
+ var SOCKET_DEFAULTS = {
20
+ noDelay: true,
21
+ keepAlive: true,
22
+ keepAliveInitialDelayMs: 0,
23
+ };
24
+
25
+ function _setSocketNoDelay(value) {
26
+ if (typeof value !== "boolean") {
27
+ throw new NetworkError("socket/bad-no-delay", "socket.setDefaultNoDelay: expected boolean, got " + typeof value);
28
+ }
29
+ SOCKET_DEFAULTS.noDelay = value;
30
+ }
31
+
32
+ function _setSocketKeepAlive(opts) {
33
+ opts = opts || {};
34
+ validateOpts(opts, ["enable", "initialDelayMs"], "socket.setDefaultKeepAlive");
35
+ if (opts.enable !== undefined) {
36
+ if (typeof opts.enable !== "boolean") {
37
+ throw new NetworkError("socket/bad-keepalive", "socket.setDefaultKeepAlive: enable must be boolean");
38
+ }
39
+ SOCKET_DEFAULTS.keepAlive = opts.enable;
40
+ }
41
+ if (opts.initialDelayMs !== undefined) {
42
+ if (typeof opts.initialDelayMs !== "number" || !isFinite(opts.initialDelayMs) || opts.initialDelayMs < 0) {
43
+ throw new NetworkError("socket/bad-keepalive-delay", "socket.setDefaultKeepAlive: initialDelayMs must be non-negative finite number");
44
+ }
45
+ SOCKET_DEFAULTS.keepAliveInitialDelayMs = opts.initialDelayMs;
46
+ }
47
+ }
48
+
49
+ // SO_LINGER is intentionally NOT exposed: Node's net.Socket has no
50
+ // public setLinger() method (the option is tracked at
51
+ // nodejs/node#27293 / rejected for the public surface). Reaching into
52
+ // socket._handle to call setLinger is an unstable internal API. The
53
+ // closest operator-exposed semantic is socket.destroy() (RST = "abort
54
+ // on close") vs socket.end() (graceful FIN). Operators needing true
55
+ // SO_LINGER should use a native binding outside the framework. This
56
+ // stub stays in the export with throw-on-call so a future Node release
57
+ // that exposes setLinger can be wired without an API addition.
58
+ function _setSocketLinger(_opts) {
59
+ throw new NetworkError("socket/linger-not-supported",
60
+ "socket.setDefaultLinger: SO_LINGER is not exposed by Node's public net.Socket API " +
61
+ "(see nodejs/node#27293). Use socket.destroy() (abort) vs socket.end() (graceful) " +
62
+ "to control close semantics, or a native binding if true SO_LINGER is required.");
63
+ }
64
+
65
+ function _socketDefaults() {
66
+ return {
67
+ noDelay: SOCKET_DEFAULTS.noDelay,
68
+ keepAlive: SOCKET_DEFAULTS.keepAlive,
69
+ keepAliveInitialDelayMs: SOCKET_DEFAULTS.keepAliveInitialDelayMs,
70
+ };
71
+ }
72
+
73
+ function applyToSocket(socket) {
74
+ if (!socket) return socket;
75
+ try {
76
+ if (typeof socket.setNoDelay === "function") socket.setNoDelay(SOCKET_DEFAULTS.noDelay);
77
+ if (typeof socket.setKeepAlive === "function") {
78
+ socket.setKeepAlive(SOCKET_DEFAULTS.keepAlive, SOCKET_DEFAULTS.keepAliveInitialDelayMs || 0);
79
+ }
80
+ } catch (_e) {}
81
+ return socket;
82
+ }
83
+
84
+ var ntpFacade = {
85
+ querySingle: ntpCheck.querySingle,
86
+ checkDrift: ntpCheck.checkDrift,
87
+ bootCheck: ntpCheck.bootCheck,
88
+ setThresholds: ntpCheck.setThresholds,
89
+ getThresholds: ntpCheck.getThresholds,
90
+ setServers: function (list) {
91
+ if (!Array.isArray(list) || list.length === 0) {
92
+ throw new NetworkError("ntp/bad-servers", "ntp.setServers: expected non-empty array");
93
+ }
94
+ ntpFacade._defaultServers = list.slice();
95
+ _emitObs("network.ntp.servers.set", { count: list.length });
96
+ },
97
+ getServers: function () {
98
+ return (ntpFacade._defaultServers || ntpCheck.DEFAULT_SERVERS).slice();
99
+ },
100
+ _defaultServers: null,
101
+ nts: nts,
102
+ };
103
+
104
+ function bootFromEnv(opts) {
105
+ opts = opts || {};
106
+ validateOpts(opts, ["env", "audit"], "network.bootFromEnv");
107
+ var env = opts.env || process.env;
108
+ var applied = { ntp: {}, dns: {}, proxy: false, tls: {}, heartbeat: 0, socket: {} };
109
+
110
+ if (env.BLAMEJS_NTP_SERVERS) {
111
+ var list = String(env.BLAMEJS_NTP_SERVERS).split(",").map(function (s) { return s.trim(); }).filter(Boolean);
112
+ if (list.length > 0) { ntpFacade.setServers(list); applied.ntp.servers = list.length; }
113
+ }
114
+ var ntpTimeout = env.BLAMEJS_NTP_TIMEOUT_MS;
115
+ if (ntpTimeout) {
116
+ var t = parseInt(ntpTimeout, 10);
117
+ if (isFinite(t) && t > 0) { ntpFacade._defaultTimeoutMs = t; applied.ntp.timeoutMs = t; }
118
+ }
119
+ var ntpWarn = env.BLAMEJS_NTP_DRIFT_WARN_MS;
120
+ var ntpFatal = env.BLAMEJS_NTP_DRIFT_FATAL_MS;
121
+ if (ntpWarn || ntpFatal) {
122
+ var thr = {};
123
+ if (ntpWarn) { thr.warnMs = parseInt(ntpWarn, 10); applied.ntp.warnMs = thr.warnMs; }
124
+ if (ntpFatal) { thr.fatalMs = parseInt(ntpFatal, 10); applied.ntp.fatalMs = thr.fatalMs; }
125
+ ntpCheck.setThresholds(thr);
126
+ }
127
+
128
+ var dnsServers = env.BLAMEJS_DNS_SERVERS;
129
+ if (dnsServers) {
130
+ var dl = String(dnsServers).split(",").map(function (s) { return s.trim(); }).filter(Boolean);
131
+ if (dl.length > 0) { dns.setServers(dl); applied.dns.servers = dl.length; }
132
+ }
133
+ if (env.BLAMEJS_DNS_RESULT_ORDER) { dns.setResultOrder(env.BLAMEJS_DNS_RESULT_ORDER); applied.dns.resultOrder = env.BLAMEJS_DNS_RESULT_ORDER; }
134
+ if (env.BLAMEJS_DNS_FAMILY) { dns.setFamily(parseInt(env.BLAMEJS_DNS_FAMILY, 10)); applied.dns.family = parseInt(env.BLAMEJS_DNS_FAMILY, 10); }
135
+ if (env.BLAMEJS_DNS_LOOKUP_TIMEOUT_MS) { dns.setLookupTimeoutMs(parseInt(env.BLAMEJS_DNS_LOOKUP_TIMEOUT_MS, 10)); applied.dns.lookupTimeoutMs = parseInt(env.BLAMEJS_DNS_LOOKUP_TIMEOUT_MS, 10); }
136
+ if (env.BLAMEJS_DNS_CACHE_TTL_MS) { dns.setCacheTtlMs(parseInt(env.BLAMEJS_DNS_CACHE_TTL_MS, 10)); applied.dns.cacheTtlMs = parseInt(env.BLAMEJS_DNS_CACHE_TTL_MS, 10); }
137
+ if (env.BLAMEJS_DOH_URL) { dns.useDnsOverHttps({ url: env.BLAMEJS_DOH_URL }); applied.dns.doh = env.BLAMEJS_DOH_URL; }
138
+ else if (env.BLAMEJS_DOH_PROVIDER) { dns.useDnsOverHttps({ provider: env.BLAMEJS_DOH_PROVIDER }); applied.dns.dohProvider = env.BLAMEJS_DOH_PROVIDER; }
139
+ if (env.BLAMEJS_DOT_HOST) { dns.useDnsOverTls({ host: env.BLAMEJS_DOT_HOST, port: env.BLAMEJS_DOT_PORT ? parseInt(env.BLAMEJS_DOT_PORT, 10) : 853 }); applied.dns.dot = env.BLAMEJS_DOT_HOST; }
140
+
141
+ if (env.HTTP_PROXY || env.http_proxy || env.HTTPS_PROXY || env.https_proxy ||
142
+ env.NO_PROXY || env.no_proxy || env.ALL_PROXY || env.all_proxy) {
143
+ applied.proxy = proxy.fromEnv(env);
144
+ }
145
+
146
+ if (env.BLAMEJS_EXTRA_CA_CERTS) {
147
+ trust.addCa(env.BLAMEJS_EXTRA_CA_CERTS, { label: "BLAMEJS_EXTRA_CA_CERTS" });
148
+ applied.tls.fileLoaded = env.BLAMEJS_EXTRA_CA_CERTS;
149
+ }
150
+ if (env.BLAMEJS_EXTRA_CA_CERTS_DIR) {
151
+ trust.addCaBundle(env.BLAMEJS_EXTRA_CA_CERTS_DIR, { label: "BLAMEJS_EXTRA_CA_CERTS_DIR" });
152
+ applied.tls.dirLoaded = env.BLAMEJS_EXTRA_CA_CERTS_DIR;
153
+ }
154
+ if (env.BLAMEJS_USE_SYSTEM_TRUST === "1" || env.BLAMEJS_USE_SYSTEM_TRUST === "true") {
155
+ trust.useSystemTrust(true);
156
+ applied.tls.systemTrust = true;
157
+ }
158
+
159
+ if (env.BLAMEJS_SOCKET_NO_DELAY) _setSocketNoDelay(env.BLAMEJS_SOCKET_NO_DELAY === "1" || env.BLAMEJS_SOCKET_NO_DELAY === "true");
160
+ if (env.BLAMEJS_SOCKET_KEEPALIVE) _setSocketKeepAlive({ enable: env.BLAMEJS_SOCKET_KEEPALIVE === "1" || env.BLAMEJS_SOCKET_KEEPALIVE === "true" });
161
+ if (env.BLAMEJS_SOCKET_KEEPALIVE_DELAY_MS) _setSocketKeepAlive({ initialDelayMs: parseInt(env.BLAMEJS_SOCKET_KEEPALIVE_DELAY_MS, 10) });
162
+ applied.socket = _socketDefaults();
163
+
164
+ var auditOn = opts.audit !== false;
165
+ if (auditOn) {
166
+ var sink;
167
+ try { sink = audit(); } catch (_e) { sink = null; }
168
+ if (sink && typeof sink.safeEmit === "function") {
169
+ try {
170
+ sink.safeEmit({
171
+ action: "network.boot.from_env",
172
+ outcome: "success",
173
+ metadata: applied,
174
+ });
175
+ } catch (_e) {}
176
+ }
177
+ }
178
+ _emitObs("network.boot.from_env", { source: "env" });
179
+ return applied;
180
+ }
181
+
182
+ function snapshot() {
183
+ return {
184
+ ntp: {
185
+ servers: ntpFacade.getServers(),
186
+ thresholds: ntpCheck.getThresholds(),
187
+ },
188
+ dns: dns._stateForTest(),
189
+ proxy: proxy.snapshot(),
190
+ tls: {
191
+ systemTrust: trust.isSystemTrustEnabled(),
192
+ caCount: trust.getTrustStore().length,
193
+ },
194
+ heartbeat: heartbeat.statuses(),
195
+ socket: _socketDefaults(),
196
+ };
197
+ }
198
+
199
+ function _emitObs(name, fields) {
200
+ try { observability().emit(name, fields || {}); } catch (_e) {}
201
+ }
202
+
203
+ function _resetForTest() {
204
+ ntpFacade._defaultServers = null;
205
+ ntpFacade._defaultTimeoutMs = null;
206
+ if (typeof ntpCheck._resetThresholdsForTest === "function") ntpCheck._resetThresholdsForTest();
207
+ dns._resetForTest();
208
+ proxy._resetForTest();
209
+ trust._resetForTest();
210
+ heartbeat._resetForTest();
211
+ SOCKET_DEFAULTS.noDelay = true;
212
+ SOCKET_DEFAULTS.keepAlive = true;
213
+ SOCKET_DEFAULTS.keepAliveInitialDelayMs = 0;
214
+ }
215
+
216
+ module.exports = {
217
+ ntp: ntpFacade,
218
+ dns: dns,
219
+ proxy: proxy,
220
+ tls: trust,
221
+ heartbeat: heartbeat,
222
+ socket: {
223
+ setDefaultNoDelay: _setSocketNoDelay,
224
+ setDefaultKeepAlive: _setSocketKeepAlive,
225
+ setDefaultLinger: _setSocketLinger,
226
+ defaults: _socketDefaults,
227
+ applyToSocket: applyToSocket,
228
+ },
229
+ bootFromEnv: bootFromEnv,
230
+ snapshot: snapshot,
231
+ NetworkError: NetworkError,
232
+ _resetForTest: _resetForTest,
233
+ };
package/lib/ntp-check.js CHANGED
@@ -36,6 +36,43 @@ var DEFAULT_SERVERS = ["pool.ntp.org", "time.cloudflare.com"];
36
36
  var DEFAULT_PORT = 123;
37
37
  var DEFAULT_TIMEOUT_MS = 3000;
38
38
 
39
+ var DEFAULT_DRIFT_WARN_MS = C.TIME.minutes(5);
40
+ var DEFAULT_DRIFT_FATAL_MS = C.TIME.hours(1);
41
+
42
+ var thresholds = {
43
+ warnMs: DEFAULT_DRIFT_WARN_MS,
44
+ fatalMs: DEFAULT_DRIFT_FATAL_MS,
45
+ };
46
+
47
+ function setThresholds(opts) {
48
+ opts = opts || {};
49
+ if (opts.warnMs !== undefined) {
50
+ if (typeof opts.warnMs !== "number" || !isFinite(opts.warnMs) || opts.warnMs < 0) {
51
+ throw new TypeError("ntpCheck.setThresholds: warnMs must be non-negative finite number, got " + JSON.stringify(opts.warnMs));
52
+ }
53
+ thresholds.warnMs = opts.warnMs;
54
+ }
55
+ if (opts.fatalMs !== undefined) {
56
+ if (typeof opts.fatalMs !== "number" || !isFinite(opts.fatalMs) || opts.fatalMs < 0) {
57
+ throw new TypeError("ntpCheck.setThresholds: fatalMs must be non-negative finite number, got " + JSON.stringify(opts.fatalMs));
58
+ }
59
+ thresholds.fatalMs = opts.fatalMs;
60
+ }
61
+ if (thresholds.warnMs > thresholds.fatalMs && thresholds.fatalMs > 0) {
62
+ throw new RangeError("ntpCheck.setThresholds: warnMs (" + thresholds.warnMs +
63
+ ") must be <= fatalMs (" + thresholds.fatalMs + ")");
64
+ }
65
+ }
66
+
67
+ function getThresholds() {
68
+ return { warnMs: thresholds.warnMs, fatalMs: thresholds.fatalMs };
69
+ }
70
+
71
+ function _resetThresholdsForTest() {
72
+ thresholds.warnMs = DEFAULT_DRIFT_WARN_MS;
73
+ thresholds.fatalMs = DEFAULT_DRIFT_FATAL_MS;
74
+ }
75
+
39
76
  /**
40
77
  * Query an NTP server once. Resolves with { driftMs, serverTimeMs } or
41
78
  * rejects with { code, message } where code is one of:
@@ -142,22 +179,26 @@ async function bootCheck(opts) {
142
179
  }
143
180
  var absMs = Math.abs(result.driftMs);
144
181
  var driftStr = (result.driftMs >= 0 ? "+" : "") + result.driftMs + "ms";
145
- if (absMs >= C.TIME.hours(1)) {
182
+ var fatalMs = (opts && typeof opts.driftFatalMs === "number") ? opts.driftFatalMs : thresholds.fatalMs;
183
+ var warnMs = (opts && typeof opts.driftWarnMs === "number") ? opts.driftWarnMs : thresholds.warnMs;
184
+ if (fatalMs > 0 && absMs >= fatalMs) {
146
185
  return {
147
186
  ok: false,
148
187
  severity: "fatal",
149
188
  driftMs: result.driftMs,
150
189
  server: result.server,
151
- message: "clock drift " + driftStr + " from " + result.server + " (>= 1 hour) — refuse to boot",
190
+ message: "clock drift " + driftStr + " from " + result.server +
191
+ " (>= " + fatalMs + "ms) — refuse to boot",
152
192
  };
153
193
  }
154
- if (absMs >= C.TIME.minutes(5)) {
194
+ if (warnMs > 0 && absMs >= warnMs) {
155
195
  return {
156
196
  ok: true,
157
197
  severity: "warning",
158
198
  driftMs: result.driftMs,
159
199
  server: result.server,
160
- message: "clock drift " + driftStr + " from " + result.server + " (>= 5 minutes) — investigate",
200
+ message: "clock drift " + driftStr + " from " + result.server +
201
+ " (>= " + warnMs + "ms) — investigate",
161
202
  };
162
203
  }
163
204
  return {
@@ -173,6 +214,11 @@ module.exports = {
173
214
  querySingle: querySingle,
174
215
  checkDrift: checkDrift,
175
216
  bootCheck: bootCheck,
217
+ setThresholds: setThresholds,
218
+ getThresholds: getThresholds,
176
219
  DEFAULT_SERVERS: DEFAULT_SERVERS,
220
+ DEFAULT_DRIFT_WARN_MS: DEFAULT_DRIFT_WARN_MS,
221
+ DEFAULT_DRIFT_FATAL_MS: DEFAULT_DRIFT_FATAL_MS,
177
222
  NTP_TO_UNIX_OFFSET_SECONDS: NTP_TO_UNIX_OFFSET_SECONDS,
223
+ _resetThresholdsForTest: _resetThresholdsForTest,
178
224
  };
@@ -400,49 +400,23 @@ function create(config) {
400
400
  function presignedUploadUrl(opts) { return _presign("PUT", "cw", opts); }
401
401
  function presignedDownloadUrl(opts) { return _presign("GET", "r", opts); }
402
402
 
403
- // Azure SAS doesn't support an equivalent of S3 / GCS POST policy
404
- // with a content-length-range constraint. The SAS spec carries
405
- // permissions / start / expiry / IP / protocol / resource-content-
406
- // headers but no body-size cap Azure validates the upload at the
407
- // service level only via the operator's optional Block Blob size
408
- // limit applied at storage-account or container scope, not via the
409
- // SAS token itself.
403
+ // Azure SAS has no equivalent of S3 / GCS POST policy with a
404
+ // content-length-range constraint the SAS spec carries permissions
405
+ // / start / expiry / IP / protocol / resource-content-headers but
406
+ // no body-size cap. Returning a PUT URL under the POST-policy name
407
+ // would be a silent shape mismatch (operators wiring an HTML form
408
+ // expecting multipart fields get a PUT URL with no fields), so the
409
+ // azure-blob backend refuses cleanly.
410
410
  //
411
- // Rather than throw NOT_SUPPORTED, this returns the same SAS PUT
412
- // shape as presignedUploadUrl with an `enforcement: 'client-only'`
413
- // marker so operators making cross-vendor decisions know the
414
- // body-size guard is advisory on Azure and must be enforced on the
415
- // client side or via a server-side post-upload check.
416
- //
417
- // For strict server-side body-size enforcement on Azure, the
418
- // canonical pattern is: SAS-authorize the upload, then have the
419
- // operator's app issue a HEAD on the resulting blob and delete +
420
- // 4xx the requester if Content-Length > opts.maxBytes.
421
- function presignedUploadPolicy(opts) {
422
- opts = opts || {};
423
- if (typeof opts.maxBytes !== "number" || !Number.isFinite(opts.maxBytes) ||
424
- opts.maxBytes <= 0) {
425
- throw _err("INVALID_MAX_BYTES",
426
- "presignedUploadPolicy: maxBytes (positive number of bytes) is required " +
427
- "(advisory on Azure — see docstring for server-side enforcement)", true);
428
- }
429
- var underlying = _presign("PUT", "cw", opts);
430
- return {
431
- url: underlying.url,
432
- method: "PUT",
433
- // SAS uploads are PUT, not multipart POST — there are no form
434
- // fields. Operators uploading attach the body directly to the
435
- // returned URL with the headers in `headers`.
436
- fields: null,
437
- headers: underlying.headers,
438
- expiresAt: underlying.expiresAt,
439
- maxBytes: opts.maxBytes,
440
- enforcement: "client-only",
441
- enforcementNote:
442
- "Azure SAS does not natively cap upload size. Operators needing " +
443
- "strict size enforcement must HEAD the blob post-upload and reject " +
444
- "if Content-Length exceeds maxBytes.",
445
- };
411
+ // For strict server-side body-size enforcement on Azure: use
412
+ // presignedUploadUrl + a server-side post-upload HEAD that deletes
413
+ // and 4xxs the requester if Content-Length > limit.
414
+ function presignedUploadPolicy(_opts) {
415
+ throw _err("PRESIGN_NOT_SUPPORTED",
416
+ "azure-blob backend does not support presigned upload policies — " +
417
+ "Azure SAS has no body-size cap. Use presignedUploadUrl + a server-side " +
418
+ "HEAD-and-delete check, or switch to an S3 / GCS-compatible backend.",
419
+ true);
446
420
  }
447
421
 
448
422
  return {
@@ -117,7 +117,8 @@ function _validateScopePattern(scope, ctx) {
117
117
 
118
118
  function _normalizeRoleEntry(name, entry) {
119
119
  if (Array.isArray(entry)) {
120
- return { extends: [], permissions: entry.slice(), dbRole: null };
120
+ return { extends: [], permissions: entry.slice(), dbRole: null,
121
+ requireMfa: false, mfaWindowMs: null };
121
122
  }
122
123
  if (entry && typeof entry === "object") {
123
124
  var ext = entry.extends || [];
@@ -146,9 +147,19 @@ function _normalizeRoleEntry(name, entry) {
146
147
  }
147
148
  dbRole = entry.dbRole;
148
149
  }
149
- return { extends: ext.slice(), permissions: perms.slice(), dbRole: dbRole };
150
+ var requireMfa = entry.requireMfa === true;
151
+ var mfaWindowMs = null;
152
+ if (entry.mfaWindowMs !== undefined && entry.mfaWindowMs !== null) {
153
+ if (typeof entry.mfaWindowMs !== "number" || !isFinite(entry.mfaWindowMs) || entry.mfaWindowMs <= 0) {
154
+ throw _err("BAD_ROLE",
155
+ "role '" + name + "': mfaWindowMs must be a positive finite number");
156
+ }
157
+ mfaWindowMs = entry.mfaWindowMs;
158
+ }
159
+ return { extends: ext.slice(), permissions: perms.slice(), dbRole: dbRole,
160
+ requireMfa: requireMfa, mfaWindowMs: mfaWindowMs };
150
161
  }
151
- throw _err("BAD_ROLE", "role '" + name + "' must be an array of scopes or { extends?, permissions, dbRole? }");
162
+ throw _err("BAD_ROLE", "role '" + name + "' must be an array of scopes or { extends?, permissions, dbRole?, requireMfa?, mfaWindowMs? }");
152
163
  }
153
164
 
154
165
  function _validateRoles(roles) {
@@ -279,6 +290,33 @@ function create(opts) {
279
290
  var missingActorStatus = opts.missingActorStatus || DEFAULTS.missingActorStatus;
280
291
  var responder = opts.responder || _defaultResponder;
281
292
 
293
+ // ABAC predicate registry. Each entry: scope-string → async predicate
294
+ // function (actor, context) → boolean. The middleware evaluates the
295
+ // predicate AFTER the RBAC scope check passes — so a route protected
296
+ // by `perms.require("orders.read")` first checks the actor has the
297
+ // orders:read scope, then (if the scope has a policy registered)
298
+ // evaluates the predicate with the actor + a per-request context
299
+ // built by the route's `context` middleware opt. ABAC + RBAC stack
300
+ // — a route needs to pass BOTH layers when both are configured.
301
+ var policies = {};
302
+
303
+ function policy(scope, predicate) {
304
+ _validateScopePattern(scope, "permissions.policy");
305
+ if (typeof predicate !== "function") {
306
+ throw _err("BAD_OPT", "permissions.policy: predicate must be a function (actor, context) -> bool");
307
+ }
308
+ if (policies[scope]) {
309
+ throw _err("DUPLICATE_POLICY", "permissions.policy: '" + scope + "' is already registered");
310
+ }
311
+ policies[scope] = predicate;
312
+ }
313
+
314
+ function _findPolicy(requestedScope) {
315
+ // Exact match wins; no wildcard expansion (a wildcard policy
316
+ // gating arbitrary scopes is too easy to misconfigure).
317
+ return policies[requestedScope] || null;
318
+ }
319
+
282
320
  function _auditEmit(action, info) {
283
321
  if (!audit) return;
284
322
  if (info && info.outcome === "success" && !auditSuccess) return;
@@ -332,7 +370,7 @@ function create(opts) {
332
370
 
333
371
  // Middleware factory. `mode` is "single" | "all" | "any"; `requested`
334
372
  // is the scope or scope list. Throw at registration time on bad shape.
335
- function _middleware(mode, requested) {
373
+ function _middleware(mode, requested, mwOpts) {
336
374
  if (mode === "single") {
337
375
  _validateScopePattern(requested, "permissions.require");
338
376
  } else {
@@ -345,7 +383,31 @@ function create(opts) {
345
383
  }
346
384
  }
347
385
 
348
- return function permissionsMiddleware(req, res, next) {
386
+ // Per-route MFA enforcement opts: { requireMfa, mfaWindowMs }.
387
+ // When set, the middleware blocks unless the actor's mfaAuthenticated
388
+ // flag is truthy AND (when mfaWindowMs is set) actor.mfaAt is fresher
389
+ // than (now - mfaWindowMs). The actor signal is operator-set: after
390
+ // a successful TOTP / passkey step-up, the route handler stamps
391
+ // req.user.mfaAuthenticated = true and req.user.mfaAt = Date.now().
392
+ mwOpts = mwOpts || {};
393
+ var routeRequireMfa = mwOpts.requireMfa === true;
394
+ var routeMfaWindowMs = null;
395
+ if (mwOpts.mfaWindowMs !== undefined && mwOpts.mfaWindowMs !== null) {
396
+ if (typeof mwOpts.mfaWindowMs !== "number" || !isFinite(mwOpts.mfaWindowMs) || mwOpts.mfaWindowMs <= 0) {
397
+ throw _err("BAD_OPT", "permissions middleware: mfaWindowMs must be a positive finite number");
398
+ }
399
+ routeMfaWindowMs = mwOpts.mfaWindowMs;
400
+ }
401
+ // ABAC context provider — operator-supplied function (req)→object.
402
+ // The function runs once per request, AFTER scope/MFA pass, BEFORE
403
+ // the policy predicate. Whatever it returns is passed to the
404
+ // policy as `context`. Async functions are awaited.
405
+ var contextProvider = mwOpts.context;
406
+ if (contextProvider !== undefined && typeof contextProvider !== "function") {
407
+ throw _err("BAD_OPT", "permissions middleware: context must be a function (req) -> object");
408
+ }
409
+
410
+ return async function permissionsMiddleware(req, res, next) {
349
411
  var actor = resolver(req);
350
412
  if (!actor) {
351
413
  // Diagnostic: the most common cause of a null actor is that
@@ -392,13 +454,164 @@ function create(opts) {
392
454
  });
393
455
  }
394
456
 
457
+ // MFA enforcement gate. Two sources of "this needs MFA":
458
+ // 1. Per-route opt: perms.require("scope", { requireMfa: true })
459
+ // 2. Per-role flag: a role spec with requireMfa:true that
460
+ // contributes to satisfying the requested scope
461
+ // Either source enabling MFA forces the gate. mfaWindowMs (per-route
462
+ // OR per-role, route wins on conflict) bounds freshness — without
463
+ // it, ANY past MFA stamp counts (which is too permissive for high-
464
+ // value routes; operators set a window like C.TIME.minutes(15)).
465
+ var enforceMfa = routeRequireMfa;
466
+ var enforceWindowMs = routeMfaWindowMs;
467
+ if (!enforceMfa) {
468
+ // Walk the actor's roles and check whether any role with
469
+ // requireMfa=true contributes a permission that matches the
470
+ // requested scope. If so, MFA is required regardless of the
471
+ // route-level opt.
472
+ var actorRoles = Array.isArray(actor.roles) ? actor.roles : [];
473
+ for (var ri = 0; ri < actorRoles.length; ri++) {
474
+ var rname = actorRoles[ri];
475
+ if (typeof rname !== "string") continue;
476
+ var rspec = roleTable[rname];
477
+ if (!rspec || !rspec.requireMfa) continue;
478
+ // Cheap match: if the role grants any scope that satisfies the
479
+ // requested scope (single mode) or any of the requested
480
+ // (all/any modes), MFA is required for this route.
481
+ var visited = new Set();
482
+ var roleScopes = [];
483
+ _expandOne(rname, roleTable, visited, roleScopes);
484
+ var roleMatches = false;
485
+ var requestedList = mode === "single" ? [requested] : requested;
486
+ outer: for (var rj = 0; rj < roleScopes.length; rj++) {
487
+ for (var rk = 0; rk < requestedList.length; rk++) {
488
+ if (match(roleScopes[rj], requestedList[rk])) {
489
+ roleMatches = true; break outer;
490
+ }
491
+ }
492
+ }
493
+ if (roleMatches) {
494
+ enforceMfa = true;
495
+ if (enforceWindowMs === null && rspec.mfaWindowMs !== null) {
496
+ enforceWindowMs = rspec.mfaWindowMs;
497
+ }
498
+ }
499
+ }
500
+ }
501
+
502
+ if (enforceMfa) {
503
+ var mfaOk = actor.mfaAuthenticated === true;
504
+ if (mfaOk && enforceWindowMs !== null) {
505
+ var mfaAt = typeof actor.mfaAt === "number" ? actor.mfaAt : 0;
506
+ if (Date.now() - mfaAt > enforceWindowMs) {
507
+ mfaOk = false;
508
+ }
509
+ }
510
+ if (!mfaOk) {
511
+ _emitEvent("permissions.mfa_required", 1,
512
+ { requested: _labelize(requested), mode: mode });
513
+ _auditEmit("permissions.mfa.required", {
514
+ actor: _actorAuditShape(actor, req),
515
+ resource: { kind: "permission", id: _labelize(requested) },
516
+ outcome: "denied",
517
+ reason: "mfa-required",
518
+ metadata: { mode: mode, windowMs: enforceWindowMs },
519
+ });
520
+ return responder(req, res, denyStatus, {
521
+ error: "mfa_required",
522
+ status: denyStatus,
523
+ requested: _labelize(requested),
524
+ });
525
+ }
526
+ }
527
+
528
+ // ABAC layer fires for every requested scope that has a
529
+ // registered policy predicate. Single-mode evaluates the one
530
+ // scope; requireAll evaluates each scope's policy (every must
531
+ // pass); requireAny evaluates only the policies on scopes the
532
+ // actor's RBAC layer satisfied (so a failing policy on a scope
533
+ // the actor doesn't even hold doesn't leak the policy's
534
+ // existence). Each predicate failure short-circuits with a
535
+ // policy.deny audit row naming the failing scope.
536
+ var policyTargets = [];
537
+ if (mode === "single" && _findPolicy(requested)) {
538
+ policyTargets.push(requested);
539
+ } else if (mode === "all" || mode === "any") {
540
+ for (var pi = 0; pi < requested.length; pi++) {
541
+ if (_findPolicy(requested[pi])) {
542
+ if (mode === "any" && !check(actor, requested[pi])) continue;
543
+ policyTargets.push(requested[pi]);
544
+ }
545
+ }
546
+ }
547
+ if (policyTargets.length > 0) {
548
+ var policyContext = null;
549
+ if (contextProvider) {
550
+ try {
551
+ policyContext = await contextProvider(req);
552
+ } catch (e) {
553
+ _emitEvent("permissions.policy_context_error", 1,
554
+ { requested: _labelize(requested) });
555
+ _auditEmit("permissions.policy.error", {
556
+ actor: _actorAuditShape(actor, req),
557
+ resource: { kind: "permission", id: _labelize(requested) },
558
+ outcome: "failure",
559
+ reason: "context-provider-threw",
560
+ metadata: { error: (e && e.message) || String(e), mode: mode },
561
+ });
562
+ return responder(req, res, denyStatus, {
563
+ error: "policy_context_error",
564
+ status: denyStatus,
565
+ requested: _labelize(requested),
566
+ });
567
+ }
568
+ }
569
+ for (var pti = 0; pti < policyTargets.length; pti++) {
570
+ var thisScope = policyTargets[pti];
571
+ var pred = _findPolicy(thisScope);
572
+ var verdict;
573
+ try {
574
+ verdict = await pred(actor, policyContext);
575
+ } catch (e2) {
576
+ _emitEvent("permissions.policy_error", 1, { requested: thisScope });
577
+ _auditEmit("permissions.policy.error", {
578
+ actor: _actorAuditShape(actor, req),
579
+ resource: { kind: "permission", id: thisScope },
580
+ outcome: "failure",
581
+ reason: "predicate-threw",
582
+ metadata: { error: (e2 && e2.message) || String(e2), mode: mode },
583
+ });
584
+ return responder(req, res, denyStatus, {
585
+ error: "policy_error",
586
+ status: denyStatus,
587
+ requested: thisScope,
588
+ });
589
+ }
590
+ if (verdict !== true) {
591
+ _emitEvent("permissions.policy_denied", 1, { requested: thisScope });
592
+ _auditEmit("permissions.policy.deny", {
593
+ actor: _actorAuditShape(actor, req),
594
+ resource: { kind: "permission", id: thisScope },
595
+ outcome: "failure",
596
+ reason: "policy-predicate-returned-falsy",
597
+ metadata: { mode: mode, scopeIndex: pti },
598
+ });
599
+ return responder(req, res, denyStatus, {
600
+ error: "policy_denied",
601
+ status: denyStatus,
602
+ requested: thisScope,
603
+ });
604
+ }
605
+ }
606
+ }
607
+
395
608
  _emitEvent("permissions.check", 1,
396
609
  { outcome: "success", mode: mode });
397
610
  _auditEmit("permissions.check.success", {
398
611
  actor: _actorAuditShape(actor, req),
399
612
  resource: { kind: "permission", id: _labelize(requested) },
400
613
  outcome: "success",
401
- metadata: { mode: mode },
614
+ metadata: { mode: mode, mfaEnforced: enforceMfa },
402
615
  });
403
616
  next();
404
617
  };
@@ -443,9 +656,10 @@ function create(opts) {
443
656
  }
444
657
 
445
658
  return {
446
- require: function (scope) { return _middleware("single", scope); },
447
- requireAll: function (scopes) { return _middleware("all", scopes); },
448
- requireAny: function (scopes) { return _middleware("any", scopes); },
659
+ require: function (scope, mwOpts) { return _middleware("single", scope, mwOpts); },
660
+ requireAll: function (scopes, mwOpts) { return _middleware("all", scopes, mwOpts); },
661
+ requireAny: function (scopes, mwOpts) { return _middleware("any", scopes, mwOpts); },
662
+ policy: policy,
449
663
  check: check,
450
664
  checkAll: checkAll,
451
665
  checkAny: checkAny,