@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.
@@ -0,0 +1,368 @@
1
+ "use strict";
2
+ /**
3
+ * security-assert — boot-time policy assertions for production posture.
4
+ *
5
+ * The framework already prints WARNINGs when individual security
6
+ * choices land in their dev-friendly defaults (vault plaintext mode,
7
+ * db at-rest plain, audit-sign plaintext, NTP drift, etc.). Operators
8
+ * shipping a real deployment want a stricter gate: not "warn, then
9
+ * boot anyway" but "this combination of settings is not acceptable
10
+ * in production — fail boot so we don't silently ship a weak posture
11
+ * to prod."
12
+ *
13
+ * b.security.assertProduction({ ... }) is the policy engine. It
14
+ * collects the operator's stated production-mode requirements and
15
+ * either passes silently OR throws a SecurityAssertError listing
16
+ * every failed assertion so the operator gets the full diagnostic on
17
+ * the first restart.
18
+ *
19
+ * await b.security.assertProduction({
20
+ * // Required posture (default true — set false to opt out per-line)
21
+ * vault: "wrapped", // require b.vault.getMode() === this
22
+ * dbAtRest: "encrypted", // require b.db.getAtRestMode() === this
23
+ * auditSigning: "wrapped", // require b.auditSign.getMode() === this
24
+ * ntpStrict: true, // require BLAMEJS_NTP_STRICT != "0"
25
+ *
26
+ * // Each of these is an opt-in tightening. Default off — the
27
+ * // framework doesn't know which are appropriate to YOUR deploy.
28
+ * requireTLS: true, // refuse boot if app.protocol !== 'https'
29
+ * // (no app.protocol on cleartext deployments)
30
+ * requireCSPNonce: true, // require operator wired b.middleware.cspNonce
31
+ * requireCSRF: true, // require b.middleware.csrfProtect mounted
32
+ * requireRateLimit:true, // require b.middleware.rateLimit mounted
33
+ *
34
+ * // Operator-supplied custom assertions. Each is a function returning
35
+ * // { ok: bool, code, message }. Failed asserts are aggregated into
36
+ * // the thrown error.
37
+ * extra: [
38
+ * function () {
39
+ * return { ok: !!process.env.WIKI_ADMIN_PASSWORD,
40
+ * code: "wiki/admin-password-missing",
41
+ * message: "WIKI_ADMIN_PASSWORD must be set in production" };
42
+ * },
43
+ * ],
44
+ *
45
+ * // Wire the audit so the operator's audit chain captures both
46
+ * // pass AND fail outcomes (next operator can see "boot was asserted
47
+ * // production-clean at <T>" or "asserts failed at <T> with reasons").
48
+ * audit: b.audit,
49
+ *
50
+ * // The detected indicators the policy reads. Optional; default
51
+ * // resolves from the framework instance via lazy-require so the
52
+ * // call site stays minimal.
53
+ * resolvers: {
54
+ * vault: function () { return require("./vault").getMode(); },
55
+ * dbAtRest: function () { return require("./db").getAtRestMode(); },
56
+ * auditSigning: function () { return require("./audit-sign").getMode(); },
57
+ * },
58
+ * });
59
+ * // throws SecurityAssertError on any failure;
60
+ * // each failure carries { code, message } and the .failures array
61
+ * // on the error lists them all
62
+ *
63
+ * The audit event namespace is "system.security.assert" — pass / fail
64
+ * lands on the chain like every other framework lifecycle event.
65
+ *
66
+ * Validation: throws at config time on malformed opts (unknown key,
67
+ * non-function extra entry, etc.) so the operator catches typos at
68
+ * boot, not at the moment they were trying to gate the boot.
69
+ */
70
+ var lazyRequire = require("./lazy-require");
71
+ var validateOpts = require("./validate-opts");
72
+ var { defineClass } = require("./framework-error");
73
+
74
+ var audit = lazyRequire(function () { return require("./audit"); });
75
+ var vault = lazyRequire(function () { return require("./vault"); });
76
+ var db = lazyRequire(function () { return require("./db"); });
77
+ var auditSign = lazyRequire(function () { return require("./audit-sign"); });
78
+ var networkTls = lazyRequire(function () { return require("./network-tls"); });
79
+ var networkProxy = lazyRequire(function () { return require("./network-proxy"); });
80
+
81
+ var SecurityAssertError = defineClass("SecurityAssertError", { alwaysPermanent: true });
82
+
83
+ var DEFAULT_RESOLVERS = Object.freeze({
84
+ vault: function () {
85
+ try { return vault().getMode(); } catch (_e) { return null; }
86
+ },
87
+ dbAtRest: function () {
88
+ try {
89
+ var d = db();
90
+ return typeof d.getAtRestMode === "function" ? d.getAtRestMode() : null;
91
+ } catch (_e) { return null; }
92
+ },
93
+ auditSigning: function () {
94
+ try { return auditSign().getMode(); } catch (_e) { return null; }
95
+ },
96
+ });
97
+
98
+ function _check(name, want, gotter) {
99
+ var got;
100
+ try { got = gotter(); }
101
+ catch (e) {
102
+ return { ok: false, code: "security/" + name + "-resolver-failed",
103
+ message: name + " resolver threw: " + ((e && e.message) || String(e)) };
104
+ }
105
+ if (got !== want) {
106
+ return { ok: false, code: "security/" + name + "-mismatch",
107
+ message: name + " is '" + got + "', production policy requires '" + want + "'" };
108
+ }
109
+ return { ok: true };
110
+ }
111
+
112
+ async function assertProduction(opts) {
113
+ opts = opts || {};
114
+ validateOpts(opts, [
115
+ "vault", "dbAtRest", "auditSigning", "ntpStrict",
116
+ "requireTLS", "requireCSPNonce", "requireCSRF", "requireRateLimit",
117
+ "extra", "audit", "resolvers", "router", "protocol",
118
+ "minNodeMajor", "minTlsVersion", "requireEnv", "forbidEnv",
119
+ "dataDir", "maxDataDirMode", "forbidNodeEnv",
120
+ "allowDpiTrust", "forbidProxy",
121
+ ], "security.assertProduction");
122
+
123
+ var resolvers = Object.assign({}, DEFAULT_RESOLVERS, opts.resolvers || {});
124
+ var failures = [];
125
+
126
+ // Each posture-mode default fires unless the operator explicitly
127
+ // sets it to false. The default value is the production-target
128
+ // string for that posture.
129
+ function _maybeRun(name, want, gotter) {
130
+ if (want === false || want === null || want === undefined) return;
131
+ var verdict = _check(name, want, gotter);
132
+ if (!verdict.ok) failures.push(verdict);
133
+ }
134
+ _maybeRun("vault", opts.vault !== undefined ? opts.vault : "wrapped", resolvers.vault);
135
+ _maybeRun("dbAtRest", opts.dbAtRest !== undefined ? opts.dbAtRest : "encrypted", resolvers.dbAtRest);
136
+ _maybeRun("auditSigning", opts.auditSigning !== undefined ? opts.auditSigning : "wrapped", resolvers.auditSigning);
137
+
138
+ // ntpStrict default ON — production should refuse to boot on >1hr
139
+ // clock drift (audit-chain timestamps stop being trustworthy).
140
+ if (opts.ntpStrict !== false) {
141
+ var ntpEnv = process.env.BLAMEJS_NTP_STRICT;
142
+ if (ntpEnv === "0" || ntpEnv === "false") {
143
+ failures.push({ ok: false, code: "security/ntp-strict-disabled",
144
+ message: "BLAMEJS_NTP_STRICT is '" + ntpEnv + "'; production policy requires NTP strict mode" });
145
+ }
146
+ }
147
+
148
+ // Optional opt-in tightenings. Operators set these true when their
149
+ // deployment shape satisfies the requirement.
150
+ if (opts.requireTLS === true) {
151
+ var protocol = opts.protocol || ""; // operator-supplied (no framework signal — TLS may terminate at the proxy)
152
+ if (protocol !== "https") {
153
+ failures.push({ ok: false, code: "security/tls-required",
154
+ message: "requireTLS:true but observed protocol is '" + protocol + "'; pass opts.protocol from your TLS terminator config" });
155
+ }
156
+ }
157
+ if (opts.requireCSPNonce === true || opts.requireCSRF === true || opts.requireRateLimit === true) {
158
+ if (!opts.router || !Array.isArray(opts.router._mounted)) {
159
+ failures.push({ ok: false, code: "security/router-introspection-missing",
160
+ message: "require* middleware checks need opts.router exposing ._mounted (the router's mounted middleware list); pass the framework Router instance" });
161
+ } else {
162
+ var mounted = opts.router._mounted.map(function (m) { return (m.name || "").toLowerCase(); });
163
+ function _requireMounted(name, label) {
164
+ if (mounted.indexOf(name) === -1) {
165
+ failures.push({ ok: false, code: "security/middleware-missing",
166
+ message: label + " is not mounted on the router; production policy requires it" });
167
+ }
168
+ }
169
+ if (opts.requireCSPNonce === true) _requireMounted("cspnonce", "b.middleware.cspNonce");
170
+ if (opts.requireCSRF === true) _requireMounted("csrfprotect", "b.middleware.csrfProtect");
171
+ if (opts.requireRateLimit === true) _requireMounted("ratelimit", "b.middleware.rateLimit");
172
+ }
173
+ }
174
+
175
+ // Node major version. Defaults to 24 (the framework's pinned LTS);
176
+ // operator can pin lower at their own risk.
177
+ var minNodeMajor = opts.minNodeMajor !== undefined ? opts.minNodeMajor : 24;
178
+ if (minNodeMajor !== false && typeof minNodeMajor === "number") {
179
+ var nodeMajor = parseInt(process.versions.node.split(".")[0], 10);
180
+ if (nodeMajor < minNodeMajor) {
181
+ failures.push({ ok: false, code: "security/node-version",
182
+ message: "Node " + process.versions.node + " < required minimum major " + minNodeMajor +
183
+ " — upgrade Node before deploying" });
184
+ }
185
+ }
186
+
187
+ // TLS minimum version. Production should be TLS 1.3-only; the
188
+ // framework's pqcGate already enforces that for inbound HTTPS but
189
+ // operators with their own server.listen() flow should re-assert.
190
+ if (opts.minTlsVersion !== undefined && opts.minTlsVersion !== false) {
191
+ var nodeTls;
192
+ try { nodeTls = require("node:tls"); } catch (_e) { nodeTls = null; }
193
+ if (nodeTls && nodeTls.DEFAULT_MIN_VERSION) {
194
+ var got = nodeTls.DEFAULT_MIN_VERSION;
195
+ var want = opts.minTlsVersion;
196
+ // Compare TLSv1.3 > TLSv1.2 > TLSv1.1 > TLSv1.0 by string.
197
+ var order = ["TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"];
198
+ if (order.indexOf(got) < order.indexOf(want)) {
199
+ failures.push({ ok: false, code: "security/tls-min-version",
200
+ message: "Node TLS DEFAULT_MIN_VERSION is '" + got + "', required '" + want + "'" });
201
+ }
202
+ }
203
+ }
204
+
205
+ // Required env-var presence. Common pattern: BLAMEJS_VAULT_PASSPHRASE
206
+ // MUST be set when vault is in wrapped mode. Operator-supplied list
207
+ // because the requirements are deployment-specific.
208
+ if (Array.isArray(opts.requireEnv)) {
209
+ for (var ri = 0; ri < opts.requireEnv.length; ri++) {
210
+ var reKey = opts.requireEnv[ri];
211
+ if (typeof reKey !== "string" || reKey.length === 0) continue;
212
+ if (!process.env[reKey] || String(process.env[reKey]).length === 0) {
213
+ failures.push({ ok: false, code: "security/env-missing",
214
+ message: "production policy requires env var '" + reKey + "' to be set and non-empty" });
215
+ }
216
+ }
217
+ }
218
+
219
+ // Forbidden env-var presence. Catches dev / debug knobs that
220
+ // shouldn't reach production (BLAMEJS_DEBUG, BLAMEJS_NTP_STRICT=0
221
+ // when ntpStrict is on, etc.).
222
+ if (Array.isArray(opts.forbidEnv)) {
223
+ for (var fi = 0; fi < opts.forbidEnv.length; fi++) {
224
+ var feEntry = opts.forbidEnv[fi];
225
+ if (typeof feEntry === "string") {
226
+ if (process.env[feEntry] !== undefined) {
227
+ failures.push({ ok: false, code: "security/env-forbidden",
228
+ message: "production policy forbids env var '" + feEntry + "' but it is set" });
229
+ }
230
+ } else if (feEntry && typeof feEntry === "object" && typeof feEntry.key === "string") {
231
+ // Forbid only when value matches.
232
+ if (process.env[feEntry.key] === feEntry.value) {
233
+ failures.push({ ok: false, code: "security/env-forbidden-value",
234
+ message: "production policy forbids env var '" + feEntry.key +
235
+ "' = '" + feEntry.value + "' but the runtime has exactly that" });
236
+ }
237
+ }
238
+ }
239
+ }
240
+
241
+ // NODE_ENV pinning — refuses common-mistake values like
242
+ // "development" or "test" in a production-asserted boot.
243
+ if (opts.forbidNodeEnv !== false) {
244
+ var forbidNodeEnv = Array.isArray(opts.forbidNodeEnv) ? opts.forbidNodeEnv : ["development", "dev", "test"];
245
+ if (process.env.NODE_ENV && forbidNodeEnv.indexOf(process.env.NODE_ENV) !== -1) {
246
+ failures.push({ ok: false, code: "security/node-env-forbidden",
247
+ message: "NODE_ENV='" + process.env.NODE_ENV + "' is in the production-forbidden list " +
248
+ JSON.stringify(forbidNodeEnv) });
249
+ }
250
+ }
251
+
252
+ // dataDir mode check — refuses world-writable / group-writable
253
+ // data directories (mode > 0o750 by default). POSIX-only; Windows
254
+ // skips silently.
255
+ if (typeof opts.dataDir === "string" && opts.dataDir.length > 0 && process.platform !== "win32") {
256
+ var maxMode = typeof opts.maxDataDirMode === "number" ? opts.maxDataDirMode : 0o750;
257
+ var fs;
258
+ try { fs = require("node:fs"); } catch (_e) { fs = null; }
259
+ if (fs) {
260
+ try {
261
+ var stat = fs.statSync(opts.dataDir);
262
+ var mode = stat.mode & 0o777;
263
+ if (mode > maxMode) {
264
+ failures.push({ ok: false, code: "security/datadir-permissions",
265
+ message: "dataDir '" + opts.dataDir + "' has mode 0" + mode.toString(8) +
266
+ "; production policy requires <= 0" + maxMode.toString(8) +
267
+ " (chmod " + maxMode.toString(8) + " " + opts.dataDir + ")" });
268
+ }
269
+ } catch (e) {
270
+ failures.push({ ok: false, code: "security/datadir-stat-failed",
271
+ message: "dataDir '" + opts.dataDir + "' could not be stat'd: " +
272
+ ((e && e.message) || String(e)) });
273
+ }
274
+ }
275
+ }
276
+
277
+ // CORS allow-all detection — the most common production-mistake
278
+ // middleware misconfig. Catches a router whose CORS middleware
279
+ // origins config is the literal "*" wildcard.
280
+ if (opts.router && Array.isArray(opts.router._mounted)) {
281
+ var corsMounted = opts.router._mounted.find(function (m) {
282
+ return (m.name || "").toLowerCase() === "cors";
283
+ });
284
+ if (corsMounted && corsMounted.opts && corsMounted.opts.origins === "*") {
285
+ failures.push({ ok: false, code: "security/cors-allow-all",
286
+ message: "b.middleware.cors is mounted with origins:'*' — production policy forbids wildcard CORS" });
287
+ }
288
+ }
289
+
290
+ if (opts.allowDpiTrust !== true) {
291
+ var trustList = null;
292
+ try { trustList = networkTls().getTrustStore(); } catch (_e) { trustList = null; }
293
+ if (trustList && trustList.length > 0) {
294
+ failures.push({ ok: false, code: "security/dpi-trust-installed",
295
+ message: "network.tls trust store has " + trustList.length +
296
+ " operator-installed CA(s); production policy refuses runtime trust additions unless allowDpiTrust:true is set" });
297
+ }
298
+ }
299
+
300
+ if (opts.forbidProxy === true) {
301
+ var proxySnap = null;
302
+ try { proxySnap = networkProxy().snapshot(); } catch (_e) { proxySnap = null; }
303
+ if (proxySnap && (proxySnap.http || proxySnap.https)) {
304
+ failures.push({ ok: false, code: "security/outbound-proxy-set",
305
+ message: "network.proxy is configured (http=" + !!proxySnap.http +
306
+ ", https=" + !!proxySnap.https + "); production policy with forbidProxy:true refuses outbound proxy" });
307
+ }
308
+ }
309
+
310
+ // Operator-supplied extra asserts.
311
+ if (opts.extra !== undefined) {
312
+ if (!Array.isArray(opts.extra)) {
313
+ throw new SecurityAssertError(
314
+ "security.assertProduction: opts.extra must be an array of functions, got " + typeof opts.extra,
315
+ "BAD_OPT", true);
316
+ }
317
+ for (var ei = 0; ei < opts.extra.length; ei++) {
318
+ if (typeof opts.extra[ei] !== "function") {
319
+ throw new SecurityAssertError(
320
+ "security.assertProduction: opts.extra[" + ei + "] must be a function",
321
+ "BAD_OPT", true);
322
+ }
323
+ var verdict;
324
+ try { verdict = await opts.extra[ei](); }
325
+ catch (e) {
326
+ verdict = { ok: false, code: "security/extra-threw",
327
+ message: "extra[" + ei + "] threw: " + ((e && e.message) || String(e)) };
328
+ }
329
+ if (!verdict || verdict.ok !== true) {
330
+ failures.push(Object.assign({ ok: false, code: "security/extra-failed",
331
+ message: "extra[" + ei + "] returned not-ok" }, verdict || {}));
332
+ }
333
+ }
334
+ }
335
+
336
+ // Audit pass / fail to the chain regardless of outcome — operators
337
+ // need both signals (production-clean boots are evidence too).
338
+ var auditOn = opts.audit !== false && opts.audit != null;
339
+ var auditInstance = (opts.audit && opts.audit !== true) ? opts.audit : null;
340
+ if (auditOn) {
341
+ var sink = auditInstance || audit();
342
+ try {
343
+ sink.safeEmit({
344
+ action: failures.length === 0 ? "system.security.assert.success" : "system.security.assert.failure",
345
+ outcome: failures.length === 0 ? "success" : "failure",
346
+ metadata: {
347
+ failureCount: failures.length,
348
+ failedCodes: failures.map(function (f) { return f.code; }),
349
+ },
350
+ });
351
+ } catch (_e) { /* audit best-effort */ }
352
+ }
353
+
354
+ if (failures.length > 0) {
355
+ var summary = failures.map(function (f) { return " - " + f.code + ": " + f.message; }).join("\n");
356
+ var err = new SecurityAssertError(
357
+ "production security policy failed (" + failures.length + " assertion(s)):\n" + summary,
358
+ "ASSERT_FAILED", true);
359
+ err.failures = failures;
360
+ throw err;
361
+ }
362
+ }
363
+
364
+ module.exports = {
365
+ assertProduction: assertProduction,
366
+ SecurityAssertError: SecurityAssertError,
367
+ DEFAULT_RESOLVERS: DEFAULT_RESOLVERS,
368
+ };
package/lib/session.js CHANGED
@@ -87,6 +87,55 @@ function _sealForInsert(row) {
87
87
 
88
88
  // ---- Public API ----
89
89
 
90
+ // Build a stable fingerprint from a request's client-derived signals.
91
+ // Operators opt in via session.create({ req, fingerprintFields }) and
92
+ // session.verify({ req, ... }); when the fingerprint drifts (different
93
+ // IP / user-agent / accept-language), the verify result carries
94
+ // fingerprintDrift: true and an audit event fires. Operators in strict
95
+ // mode pass requireFingerprintMatch:true to make the drift kill the
96
+ // session; default returns the session (so a phone roaming between
97
+ // wifi and LTE doesn't get logged out, but the operator AND ops sees
98
+ // the drift signal).
99
+ //
100
+ // The fingerprint is HMAC'd with the session sid so a stolen DB can't
101
+ // be cross-correlated with public IP-UA logs to attribute sessions to
102
+ // users — same defense the sidHash already provides for the token
103
+ // itself, extended to the fingerprint.
104
+ var DEFAULT_FINGERPRINT_FIELDS = ["clientIp", "userAgent", "acceptLanguage"];
105
+
106
+ function _buildFingerprintInputs(req, fields) {
107
+ if (!req) return null;
108
+ var headers = req.headers || {};
109
+ var inputs = {};
110
+ for (var i = 0; i < fields.length; i++) {
111
+ var f = fields[i];
112
+ if (f === "clientIp") {
113
+ inputs.clientIp = (req.socket && req.socket.remoteAddress) ||
114
+ (req.connection && req.connection.remoteAddress) || "";
115
+ } else if (f === "userAgent") {
116
+ inputs.userAgent = String(headers["user-agent"] || "");
117
+ } else if (f === "acceptLanguage") {
118
+ // Take only the primary tag (en-US,en;q=0.9 → en-US) so a
119
+ // browser's secondary q-list reordering doesn't flap drift.
120
+ var raw = String(headers["accept-language"] || "");
121
+ var primary = raw.split(",")[0] || "";
122
+ inputs.acceptLanguage = primary.split(";")[0].trim().toLowerCase();
123
+ } else if (typeof f === "function") {
124
+ try { inputs[f.name || ("custom" + i)] = String(f(req) || ""); }
125
+ catch (_e) { inputs[f.name || ("custom" + i)] = ""; }
126
+ }
127
+ }
128
+ return inputs;
129
+ }
130
+
131
+ function _hashFingerprint(sid, inputs) {
132
+ if (!inputs) return null;
133
+ // Deterministic key order so the hash is stable.
134
+ var keys = Object.keys(inputs).sort();
135
+ var canonical = keys.map(function (k) { return k + "=" + inputs[k]; }).join("|");
136
+ return sha3Hash("bj-session-fingerprint:" + sid + ":" + canonical);
137
+ }
138
+
90
139
  async function create(opts) {
91
140
  cluster.requireLeader();
92
141
  if (!opts || !opts.userId) {
@@ -100,10 +149,22 @@ async function create(opts) {
100
149
  var nowMs = Date.now();
101
150
  var expiresAt = nowMs + ttl;
102
151
 
152
+ // Fingerprint capture (opt-in via opts.req). Stored as a reserved
153
+ // key inside the sealed `data` field so it lives alongside the
154
+ // operator-supplied session data without needing a schema column.
155
+ var dataObj = opts.data ? Object.assign({}, opts.data) : null;
156
+ var fpFields = Array.isArray(opts.fingerprintFields) && opts.fingerprintFields.length > 0
157
+ ? opts.fingerprintFields : DEFAULT_FINGERPRINT_FIELDS;
158
+ var fpInputs = _buildFingerprintInputs(opts.req, fpFields);
159
+ if (fpInputs) {
160
+ if (!dataObj) dataObj = {};
161
+ dataObj.__bj_fingerprint = _hashFingerprint(sid, fpInputs);
162
+ }
163
+
103
164
  var sealed = _sealForInsert({
104
165
  sidHash: sidHash,
105
166
  userId: opts.userId,
106
- data: opts.data ? JSON.stringify(opts.data) : null,
167
+ data: dataObj ? JSON.stringify(dataObj) : null,
107
168
  createdAt: nowMs,
108
169
  expiresAt: expiresAt,
109
170
  lastActivity: nowMs,
@@ -119,8 +180,9 @@ async function create(opts) {
119
180
  return { token: sid, expiresAt: expiresAt };
120
181
  }
121
182
 
122
- async function verify(token) {
183
+ async function verify(token, verifyOpts) {
123
184
  if (typeof token !== "string" || token.length === 0) return null;
185
+ verifyOpts = verifyOpts || {};
124
186
  var sidHash = _hashSid(token);
125
187
 
126
188
  var row = await clusterStorage.executeOne(
@@ -143,8 +205,18 @@ async function verify(token) {
143
205
  // db().from(...).first() path delivered.
144
206
  var unsealed = cryptoField.unsealRow("_blamejs_sessions", row);
145
207
  var data = null;
208
+ var storedFingerprint = null;
146
209
  if (unsealed.data) {
147
- try { data = safeJson.parse(unsealed.data); }
210
+ try {
211
+ data = safeJson.parse(unsealed.data);
212
+ if (data && typeof data === "object" && typeof data.__bj_fingerprint === "string") {
213
+ storedFingerprint = data.__bj_fingerprint;
214
+ // Strip the reserved key from the operator-visible data so
215
+ // routes don't accidentally render it / log it / pass it on.
216
+ delete data.__bj_fingerprint;
217
+ if (Object.keys(data).length === 0) data = null;
218
+ }
219
+ }
148
220
  catch (e) {
149
221
  // Decrypt-then-parse failure is rare but operationally important —
150
222
  // it usually signals key-rotation skew, DB corruption, or
@@ -162,12 +234,70 @@ async function verify(token) {
162
234
  } catch (_ignored) { /* audit best-effort */ }
163
235
  }
164
236
  }
237
+
238
+ // Fingerprint check — opt-in via verifyOpts.req. When the stored
239
+ // fingerprint differs from the current request's fingerprint, audit
240
+ // the drift and (in strict mode) refuse the session. Default mode
241
+ // returns the session with `fingerprintDrift: true` so the operator
242
+ // can decide (some drift — phone roaming wifi/LTE — is benign; a
243
+ // login-from-Tokyo-then-immediately-from-Brazil pattern is not).
244
+ var fingerprintDrift = false;
245
+ var fingerprintAnomalyScore = null;
246
+ if (storedFingerprint && verifyOpts.req) {
247
+ var fpFields = Array.isArray(verifyOpts.fingerprintFields) && verifyOpts.fingerprintFields.length > 0
248
+ ? verifyOpts.fingerprintFields : DEFAULT_FINGERPRINT_FIELDS;
249
+ var currentInputs = _buildFingerprintInputs(verifyOpts.req, fpFields);
250
+ var currentHash = _hashFingerprint(token, currentInputs);
251
+ if (currentHash !== storedFingerprint) {
252
+ fingerprintDrift = true;
253
+ // Operator-supplied scorer: receives { storedHash, currentInputs,
254
+ // currentHash, sessionAge: ms-since-create }. Returns a number
255
+ // in [0, 1] — 0 = benign drift (phone roaming wifi), 1 =
256
+ // definitely-malicious. Errors are swallowed; scorer-throw
257
+ // doesn't break verify.
258
+ if (typeof verifyOpts.scorer === "function") {
259
+ try {
260
+ var rawScore = verifyOpts.scorer({
261
+ storedHash: storedFingerprint,
262
+ currentInputs: currentInputs,
263
+ currentHash: currentHash,
264
+ sessionAge: Date.now() - Number(unsealed.createdAt),
265
+ });
266
+ if (typeof rawScore === "number" && isFinite(rawScore)) {
267
+ fingerprintAnomalyScore = Math.max(0, Math.min(1, rawScore));
268
+ }
269
+ } catch (_e) { /* scorer best-effort */ }
270
+ }
271
+ try {
272
+ audit.safeEmit({
273
+ action: "auth.session.fingerprint_drift",
274
+ outcome: "warning",
275
+ metadata: { hasUserId: !!unsealed.userId,
276
+ anomalyScore: fingerprintAnomalyScore },
277
+ });
278
+ } catch (_ignored) { /* audit best-effort */ }
279
+ // Strict modes:
280
+ // requireFingerprintMatch: true — any drift kills the session
281
+ // maxAnomalyScore: <0..1> — drift above threshold kills
282
+ if (verifyOpts.requireFingerprintMatch === true) {
283
+ return null;
284
+ }
285
+ if (typeof verifyOpts.maxAnomalyScore === "number" &&
286
+ fingerprintAnomalyScore !== null &&
287
+ fingerprintAnomalyScore > verifyOpts.maxAnomalyScore) {
288
+ return null;
289
+ }
290
+ }
291
+ }
292
+
165
293
  return {
166
- userId: unsealed.userId,
167
- data: data,
168
- createdAt: Number(unsealed.createdAt),
169
- expiresAt: Number(unsealed.expiresAt),
170
- lastActivity: Number(unsealed.lastActivity),
294
+ userId: unsealed.userId,
295
+ data: data,
296
+ createdAt: Number(unsealed.createdAt),
297
+ expiresAt: Number(unsealed.expiresAt),
298
+ lastActivity: Number(unsealed.lastActivity),
299
+ fingerprintDrift: fingerprintDrift,
300
+ fingerprintAnomalyScore: fingerprintAnomalyScore,
171
301
  };
172
302
  }
173
303
 
package/lib/ssrf-guard.js CHANGED
@@ -43,11 +43,14 @@
43
43
  var dns = require("node:dns").promises;
44
44
  var net = require("node:net");
45
45
 
46
+ var lazyRequire = require("./lazy-require");
46
47
  var safeUrl = require("./safe-url");
47
48
  var validateOpts = require("./validate-opts");
48
49
 
49
50
  var { FrameworkError } = require("./framework-error");
50
51
 
52
+ var networkDns = lazyRequire(function () { return require("./network-dns"); });
53
+
51
54
  class SsrfError extends FrameworkError {
52
55
  constructor(message, code, ctx) {
53
56
  super(message, code);
@@ -319,6 +322,12 @@ async function checkUrl(url, opts) {
319
322
  ips = [{ address: hostForCheck, family: net.isIP(hostForCheck) }];
320
323
  } else {
321
324
  var lookup = opts.dnsLookup || function (host) {
325
+ try {
326
+ var nd = networkDns();
327
+ if (nd && typeof nd.lookup === "function") {
328
+ return nd.lookup(host, { all: true });
329
+ }
330
+ } catch (_e) { /* fall through to native */ }
322
331
  return dns.lookup(host, { all: true });
323
332
  };
324
333
  ips = await lookup(hostForCheck);
@@ -59,6 +59,18 @@
59
59
  "bundler": "esbuild --format=cjs --minify --platform=node --external:crypto --external:node:crypto",
60
60
  "bundledAt": "2026-04-26"
61
61
  },
62
+ "SecLists-common-passwords-top-10000": {
63
+ "version": "10k-most-common (master)",
64
+ "license": "CC-BY-3.0",
65
+ "author": "Daniel Miessler / SecLists contributors",
66
+ "source": "https://github.com/danielmiessler/SecLists",
67
+ "_about": "Top 10,000 most-common passwords (breach-derived). Loaded by b.auth.password.policy() to satisfy NIST 800-63B §5.1.1.2 'previously breached' check. Operators with deeper enforcement (HIBP downloads, NCSC 100k) layer on top via opts.forbidCommon — the bundled set is additive.",
68
+ "files": {
69
+ "server": "lib/vendor/common-passwords-top-10000.txt"
70
+ },
71
+ "bundler": "curl https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10k-most-common.txt",
72
+ "bundledAt": "2026-05-02"
73
+ },
62
74
  "peculiar-pki": {
63
75
  "version": "2.0.0+pkijs-3.4.0",
64
76
  "license": "MIT",