@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,475 @@
1
+ "use strict";
2
+ /**
3
+ * dual-control — two-person-rule primitive for destructive operations.
4
+ *
5
+ * b.breakGlass already gates a single-actor step-up (TOTP / passkey
6
+ * proof from the SAME actor performing the unseal). dual-control
7
+ * raises the bar to "two distinct named actors must approve before
8
+ * the operation runs" — the standard control for destructive actions
9
+ * in compliance-sensitive domains (HIPAA admin actions, PCI key
10
+ * rotation, financial close, T+1 settlement, etc.).
11
+ *
12
+ * var approvals = b.dualControl.create({
13
+ * namespace: "wiki.destructive",
14
+ * audit: b.audit,
15
+ * ttlMs: C.TIME.minutes(15), // grant expires after this; default 15m
16
+ * minApprovers: 2, // dual = 2; quorum can be larger
17
+ * forbidSelfApprove: true, // requester cannot also approve; default true
18
+ * });
19
+ *
20
+ * // Step 1: requester opens the request
21
+ * var req1 = await approvals.request({
22
+ * action: "<your-domain>.<verb>", // e.g. operator picks a stable name
23
+ * resource: { kind: "user.bulk", id: "older-than-30d" },
24
+ * requestedBy: actor1, // operator-shaped { id, email, ... }
25
+ * reason: "GDPR sweep; quarter-close",
26
+ * req: req, // for actor-context capture
27
+ * });
28
+ * // → { grantId, status: "pending", needs: 2, approvedBy: [actor1.id], expiresAt: ... }
29
+ *
30
+ * // Step 2: a DIFFERENT actor approves
31
+ * var req2 = await approvals.approve({
32
+ * grantId: req1.grantId,
33
+ * approver: actor2,
34
+ * reason: "verified ticket #4421",
35
+ * req: req,
36
+ * });
37
+ * // → { grantId, status: "approved", approvedBy: [actor1.id, actor2.id] }
38
+ *
39
+ * // Step 3: code that performs the destructive op consumes the grant
40
+ * var grant = await approvals.consume(req1.grantId, { req });
41
+ * if (!grant.ready) throw new Error("not approved or already consumed");
42
+ * // ... perform users.purge ...
43
+ *
44
+ * Audit posture:
45
+ * - Every state transition emits to b.audit:
46
+ * dual.grant.requested (status pending)
47
+ * dual.grant.approved (each approval; metadata.approverCount)
48
+ * dual.grant.denied (operator-callable revoke())
49
+ * dual.grant.consumed (the destructive op ran)
50
+ * dual.grant.expired (TTL hit before approve+consume)
51
+ * - Each event carries the grant ID + the actor 5 W's so a compliance
52
+ * reviewer can reconstruct the chain.
53
+ *
54
+ * Storage: the grants live in a b.cache instance the operator passes
55
+ * in (memory backend → per-process; cluster backend → shared across
56
+ * nodes). The cache TTL bounds grant freshness automatically.
57
+ *
58
+ * Validation:
59
+ * - create() opts: throw at boot on bad shape
60
+ * - request() / approve() / consume() / revoke(): throw on missing
61
+ * required args, return { error } on policy denials (already
62
+ * consumed, expired, self-approval, etc.)
63
+ */
64
+ var lazyRequire = require("./lazy-require");
65
+ var crypto = require("./crypto");
66
+ var requestHelpers = require("./request-helpers");
67
+ var validateOpts = require("./validate-opts");
68
+ var C = require("./constants");
69
+ var { defineClass } = require("./framework-error");
70
+
71
+ var audit = lazyRequire(function () { return require("./audit"); });
72
+
73
+ var DualControlError = defineClass("DualControlError", { alwaysPermanent: true });
74
+ var _err = DualControlError.factory;
75
+
76
+ var DEFAULTS = Object.freeze({
77
+ ttlMs: C.TIME.minutes(15),
78
+ minApprovers: 2,
79
+ forbidSelfApprove: true,
80
+ // Cooling-off lock between final approval and consume. Prevents the
81
+ // "rushed approval" failure where an attacker compromises the
82
+ // requester AND an approver in close succession and immediately
83
+ // executes the destructive op. Default 0 (no lock); compliance
84
+ // regimes typically pin 30s–2min.
85
+ consumeLockMs: 0,
86
+ // Minimum reason length on request() AND each approve(). Forces a
87
+ // meaningful audit trail — empty / single-char reasons aren't
88
+ // compliance-defensible. 0 disables.
89
+ minReasonLength: 0,
90
+ // Optional approver-role gate. When set, the approver actor MUST
91
+ // carry one of these roles (actor.roles list) for approve() to
92
+ // accept. The framework can't enforce role assignment from this
93
+ // primitive — operator wires actor.roles upstream of approve().
94
+ approverRoles: null,
95
+ // Notification hook fired on every state transition. Operator-
96
+ // supplied function (event) → void; thrown errors are swallowed
97
+ // (best-effort, the audit chain is the source of truth).
98
+ notify: null,
99
+ });
100
+
101
+ function _actorIdOf(actor) {
102
+ if (!actor || typeof actor !== "object") return null;
103
+ if (typeof actor.id === "string" && actor.id.length > 0) return actor.id;
104
+ if (typeof actor._id === "string" && actor._id.length > 0) return actor._id;
105
+ if (typeof actor.userId === "string" && actor.userId.length > 0) return actor.userId;
106
+ if (typeof actor.email === "string" && actor.email.length > 0) return "email:" + actor.email;
107
+ return null;
108
+ }
109
+
110
+ function create(opts) {
111
+ opts = opts || {};
112
+ validateOpts(opts, [
113
+ "namespace", "cache", "audit", "ttlMs", "minApprovers", "forbidSelfApprove",
114
+ "consumeLockMs", "minReasonLength", "approverRoles", "notify",
115
+ ], "dualControl");
116
+ if (typeof opts.namespace !== "string" || opts.namespace.length === 0) {
117
+ throw _err("BAD_OPT", "create: opts.namespace is required");
118
+ }
119
+ if (!opts.cache || typeof opts.cache.get !== "function" || typeof opts.cache.set !== "function") {
120
+ throw _err("BAD_OPT", "create: opts.cache is required (a b.cache instance)");
121
+ }
122
+ var ttlMs = opts.ttlMs !== undefined ? opts.ttlMs : DEFAULTS.ttlMs;
123
+ if (typeof ttlMs !== "number" || !isFinite(ttlMs) || ttlMs <= 0) {
124
+ throw _err("BAD_OPT", "create: ttlMs must be a positive finite number");
125
+ }
126
+ var minApprovers = opts.minApprovers !== undefined ? opts.minApprovers : DEFAULTS.minApprovers;
127
+ if (typeof minApprovers !== "number" || !isFinite(minApprovers) ||
128
+ minApprovers < 2 || Math.floor(minApprovers) !== minApprovers) {
129
+ throw _err("BAD_OPT", "create: minApprovers must be an integer >= 2 (dual-control by definition needs 2+)");
130
+ }
131
+ var forbidSelfApprove = opts.forbidSelfApprove !== undefined ? opts.forbidSelfApprove === true : DEFAULTS.forbidSelfApprove;
132
+ var consumeLockMs = opts.consumeLockMs !== undefined ? opts.consumeLockMs : DEFAULTS.consumeLockMs;
133
+ if (typeof consumeLockMs !== "number" || !isFinite(consumeLockMs) || consumeLockMs < 0) {
134
+ throw _err("BAD_OPT", "create: consumeLockMs must be a non-negative finite number");
135
+ }
136
+ var minReasonLength = opts.minReasonLength !== undefined ? opts.minReasonLength : DEFAULTS.minReasonLength;
137
+ if (typeof minReasonLength !== "number" || !isFinite(minReasonLength) || minReasonLength < 0 ||
138
+ Math.floor(minReasonLength) !== minReasonLength) {
139
+ throw _err("BAD_OPT", "create: minReasonLength must be a non-negative integer");
140
+ }
141
+ var approverRoles = opts.approverRoles !== undefined ? opts.approverRoles : DEFAULTS.approverRoles;
142
+ if (approverRoles !== null) {
143
+ if (!Array.isArray(approverRoles) || approverRoles.length === 0 ||
144
+ !approverRoles.every(function (r) { return typeof r === "string" && r.length > 0; })) {
145
+ throw _err("BAD_OPT", "create: approverRoles must be null or a non-empty array of role-name strings");
146
+ }
147
+ }
148
+ var notifyFn = opts.notify;
149
+ if (notifyFn !== undefined && notifyFn !== null && typeof notifyFn !== "function") {
150
+ throw _err("BAD_OPT", "create: notify must be a function (event) => void or null");
151
+ }
152
+ var namespace = opts.namespace;
153
+ var cache = opts.cache;
154
+ var auditOn = opts.audit !== false && opts.audit != null;
155
+ var auditInstance = (opts.audit && opts.audit !== true) ? opts.audit : null;
156
+
157
+ function _emit(action, info, outcome, req) {
158
+ if (auditOn) {
159
+ var sink = auditInstance || audit();
160
+ try {
161
+ sink.safeEmit({
162
+ action: action,
163
+ outcome: outcome,
164
+ actor: requestHelpers.extractActorContext(req),
165
+ resource: { kind: "dual.grant", id: info.grantId },
166
+ reason: info.reason || null,
167
+ metadata: info,
168
+ });
169
+ } catch (_e) { /* best-effort */ }
170
+ }
171
+ if (notifyFn) {
172
+ try { notifyFn({ action: action, outcome: outcome, info: info }); }
173
+ catch (_e) { /* best-effort */ }
174
+ }
175
+ }
176
+
177
+ function _checkReason(reason, where) {
178
+ if (minReasonLength <= 0) return null;
179
+ var s = (reason == null) ? "" : String(reason).trim();
180
+ if (s.length < minReasonLength) {
181
+ return { error: "reason-too-short",
182
+ message: where + ": reason must be at least " + minReasonLength + " characters" };
183
+ }
184
+ return null;
185
+ }
186
+
187
+ function _approverRoleOk(actor) {
188
+ if (!approverRoles) return true;
189
+ if (!actor || !Array.isArray(actor.roles)) return false;
190
+ for (var i = 0; i < approverRoles.length; i++) {
191
+ if (actor.roles.indexOf(approverRoles[i]) !== -1) return true;
192
+ }
193
+ return false;
194
+ }
195
+
196
+ function _key(grantId) { return namespace + ":" + grantId; }
197
+
198
+ async function request(args) {
199
+ if (!args || typeof args !== "object") {
200
+ throw _err("BAD_ARG", "request: args object required");
201
+ }
202
+ if (typeof args.action !== "string" || args.action.length === 0) {
203
+ throw _err("BAD_ARG", "request: args.action (string) is required");
204
+ }
205
+ var requesterId = _actorIdOf(args.requestedBy);
206
+ if (!requesterId) {
207
+ throw _err("BAD_ARG", "request: args.requestedBy must be an actor with a stable id");
208
+ }
209
+ var reasonProblem = _checkReason(args.reason, "request");
210
+ if (reasonProblem) {
211
+ return Object.assign({ grantId: null }, reasonProblem);
212
+ }
213
+ var grantId = "dc-" + crypto.generateToken(8);
214
+ var nowMs = Date.now();
215
+ var record = {
216
+ grantId: grantId,
217
+ action: args.action,
218
+ resource: args.resource || null,
219
+ requestedBy: requesterId,
220
+ requestedAt: nowMs,
221
+ reason: args.reason || null,
222
+ approvedBy: [], // ordered list of approver IDs
223
+ approvalsAt: [], // matching timestamps
224
+ approvalReasons:[],
225
+ approverRoleHits: [], // recorded for audit when approverRoles is set
226
+ consumedAt: null,
227
+ revokedAt: null,
228
+ revokedReason: null,
229
+ cancelledAt: null,
230
+ cancelledReason:null,
231
+ quorumReachedAt:null,
232
+ expiresAt: nowMs + ttlMs,
233
+ minApprovers: minApprovers,
234
+ consumeLockMs: consumeLockMs,
235
+ };
236
+ await cache.set(_key(grantId), record, { ttlMs: ttlMs });
237
+ _emit("dual.grant.requested",
238
+ { grantId: grantId, action: args.action, requestedBy: requesterId, needs: minApprovers,
239
+ reason: args.reason || null, expiresAt: record.expiresAt,
240
+ consumeLockMs: consumeLockMs, approverRolesRequired: approverRoles },
241
+ "success", args.req);
242
+ return {
243
+ grantId: grantId,
244
+ status: "pending",
245
+ needs: minApprovers,
246
+ approvedBy: [],
247
+ expiresAt: record.expiresAt,
248
+ };
249
+ }
250
+
251
+ async function cancel(args) {
252
+ if (!args || typeof args !== "object") throw _err("BAD_ARG", "cancel: args required");
253
+ var record = await _load(args.grantId);
254
+ if (!record) return { error: "grant-not-found", grantId: args.grantId };
255
+ if (record.consumedAt !== null) return { error: "grant-already-consumed", grantId: record.grantId };
256
+ if (record.revokedAt !== null) return { error: "grant-revoked", grantId: record.grantId };
257
+ if (record.cancelledAt !== null) return { error: "grant-already-cancelled", grantId: record.grantId };
258
+ var actorId = _actorIdOf(args.cancelledBy);
259
+ if (actorId !== record.requestedBy) {
260
+ // Cancellation by anyone other than the requester is a revoke,
261
+ // not a cancel. Surface explicitly.
262
+ return { error: "only-requester-can-cancel", grantId: record.grantId,
263
+ requestedBy: record.requestedBy };
264
+ }
265
+ record.cancelledAt = Date.now();
266
+ record.cancelledReason = args.reason || null;
267
+ var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
268
+ await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
269
+ _emit("dual.grant.cancelled",
270
+ { grantId: record.grantId, action: record.action,
271
+ cancelledBy: actorId, reason: args.reason || null },
272
+ "success", args.req);
273
+ return { grantId: record.grantId, status: "cancelled" };
274
+ }
275
+
276
+ async function _load(grantId) {
277
+ if (typeof grantId !== "string" || grantId.length === 0) {
278
+ throw _err("BAD_ARG", "grantId (string) is required");
279
+ }
280
+ var record = await cache.get(_key(grantId));
281
+ return record || null;
282
+ }
283
+
284
+ async function approve(args) {
285
+ if (!args || typeof args !== "object") throw _err("BAD_ARG", "approve: args required");
286
+ var record = await _load(args.grantId);
287
+ if (!record) {
288
+ return { error: "grant-not-found", grantId: args.grantId };
289
+ }
290
+ if (record.consumedAt !== null) {
291
+ return { error: "grant-already-consumed", grantId: record.grantId };
292
+ }
293
+ if (record.revokedAt !== null) {
294
+ return { error: "grant-revoked", grantId: record.grantId, revokedReason: record.revokedReason };
295
+ }
296
+ if (record.cancelledAt !== null) {
297
+ return { error: "grant-cancelled", grantId: record.grantId };
298
+ }
299
+ if (record.expiresAt < Date.now()) {
300
+ _emit("dual.grant.expired", { grantId: record.grantId, action: record.action },
301
+ "failure", args.req);
302
+ await cache.del(_key(record.grantId));
303
+ return { error: "grant-expired", grantId: record.grantId };
304
+ }
305
+ var approverId = _actorIdOf(args.approver);
306
+ if (!approverId) throw _err("BAD_ARG", "approve: args.approver must be an actor with a stable id");
307
+ if (forbidSelfApprove && approverId === record.requestedBy) {
308
+ _emit("dual.grant.self_approval_denied",
309
+ { grantId: record.grantId, action: record.action, approver: approverId },
310
+ "denied", args.req);
311
+ return { error: "self-approval-forbidden", grantId: record.grantId };
312
+ }
313
+ if (!_approverRoleOk(args.approver)) {
314
+ _emit("dual.grant.role_denied",
315
+ { grantId: record.grantId, action: record.action, approver: approverId,
316
+ requiredRoles: approverRoles,
317
+ actorRoles: (args.approver && Array.isArray(args.approver.roles)) ? args.approver.roles : [] },
318
+ "denied", args.req);
319
+ return { error: "approver-role-required", grantId: record.grantId,
320
+ requiredRoles: approverRoles };
321
+ }
322
+ if (record.approvedBy.indexOf(approverId) !== -1) {
323
+ return { error: "already-approved-by-this-actor", grantId: record.grantId,
324
+ approvedBy: record.approvedBy };
325
+ }
326
+ var reasonProblem = _checkReason(args.reason, "approve");
327
+ if (reasonProblem) {
328
+ return Object.assign({ grantId: record.grantId }, reasonProblem);
329
+ }
330
+ record.approvedBy.push(approverId);
331
+ record.approvalsAt.push(Date.now());
332
+ record.approvalReasons.push(args.reason || null);
333
+ if (approverRoles && args.approver && Array.isArray(args.approver.roles)) {
334
+ // Record which of the required roles satisfied the approval —
335
+ // useful when an audit reviewer needs to confirm the actor
336
+ // approved as e.g. their security-officer role and not their
337
+ // engineer role.
338
+ var hits = args.approver.roles.filter(function (r) { return approverRoles.indexOf(r) !== -1; });
339
+ record.approverRoleHits.push(hits);
340
+ }
341
+ var status = "pending";
342
+ if (record.approvedBy.length >= record.minApprovers) {
343
+ status = "approved";
344
+ if (record.quorumReachedAt === null) record.quorumReachedAt = Date.now();
345
+ }
346
+ var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
347
+ await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
348
+ _emit("dual.grant.approved",
349
+ { grantId: record.grantId, action: record.action, approver: approverId,
350
+ approverCount: record.approvedBy.length, needs: record.minApprovers,
351
+ status: status, reason: args.reason || null,
352
+ consumeUnlockAt: record.quorumReachedAt !== null
353
+ ? record.quorumReachedAt + record.consumeLockMs : null },
354
+ "success", args.req);
355
+ return {
356
+ grantId: record.grantId,
357
+ status: status,
358
+ approvedBy: record.approvedBy.slice(),
359
+ needs: record.minApprovers,
360
+ expiresAt: record.expiresAt,
361
+ consumeUnlockAt: record.quorumReachedAt !== null
362
+ ? record.quorumReachedAt + record.consumeLockMs : null,
363
+ };
364
+ }
365
+
366
+ async function revoke(args) {
367
+ if (!args || typeof args !== "object") throw _err("BAD_ARG", "revoke: args required");
368
+ var record = await _load(args.grantId);
369
+ if (!record) return { error: "grant-not-found", grantId: args.grantId };
370
+ if (record.consumedAt !== null) {
371
+ return { error: "grant-already-consumed", grantId: record.grantId };
372
+ }
373
+ record.revokedAt = Date.now();
374
+ record.revokedReason = args.reason || null;
375
+ var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
376
+ await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
377
+ _emit("dual.grant.denied",
378
+ { grantId: record.grantId, action: record.action,
379
+ revokedBy: _actorIdOf(args.revokedBy), reason: args.reason || null },
380
+ "denied", args.req);
381
+ return { grantId: record.grantId, status: "revoked" };
382
+ }
383
+
384
+ async function consume(grantId, args) {
385
+ args = args || {};
386
+ var record = await _load(grantId);
387
+ if (!record) return { ready: false, reason: "grant-not-found" };
388
+ if (record.revokedAt !== null) {
389
+ return { ready: false, reason: "revoked" };
390
+ }
391
+ if (record.cancelledAt !== null) {
392
+ return { ready: false, reason: "cancelled" };
393
+ }
394
+ if (record.consumedAt !== null) {
395
+ return { ready: false, reason: "already-consumed" };
396
+ }
397
+ if (record.expiresAt < Date.now()) {
398
+ _emit("dual.grant.expired", { grantId: record.grantId, action: record.action },
399
+ "failure", args.req);
400
+ await cache.del(_key(record.grantId));
401
+ return { ready: false, reason: "expired" };
402
+ }
403
+ if (record.approvedBy.length < record.minApprovers) {
404
+ return { ready: false, reason: "not-enough-approvers",
405
+ approvedBy: record.approvedBy.slice(), needs: record.minApprovers };
406
+ }
407
+ // Cooling-off lock: ANY approval-quorum-reached grant can't consume
408
+ // until consumeLockMs has passed since the final approval. Defends
409
+ // against rapid-burst compromise of requester+approver.
410
+ if ((record.consumeLockMs || 0) > 0 && record.quorumReachedAt !== null) {
411
+ var unlockAt = record.quorumReachedAt + record.consumeLockMs;
412
+ if (Date.now() < unlockAt) {
413
+ _emit("dual.grant.consume_locked",
414
+ { grantId: record.grantId, action: record.action,
415
+ unlockAt: unlockAt, waitMs: unlockAt - Date.now() },
416
+ "denied", args.req);
417
+ return { ready: false, reason: "consume-locked", unlockAt: unlockAt,
418
+ waitMs: unlockAt - Date.now() };
419
+ }
420
+ }
421
+ record.consumedAt = Date.now();
422
+ // Drop the grant from the cache after consume — single-use by design.
423
+ await cache.del(_key(record.grantId));
424
+ _emit("dual.grant.consumed",
425
+ { grantId: record.grantId, action: record.action,
426
+ approvedBy: record.approvedBy.slice(),
427
+ approvalReasons: record.approvalReasons.slice() },
428
+ "success", args.req);
429
+ return {
430
+ ready: true,
431
+ grantId: record.grantId,
432
+ action: record.action,
433
+ resource: record.resource,
434
+ approvedBy: record.approvedBy.slice(),
435
+ requestedBy:record.requestedBy,
436
+ };
437
+ }
438
+
439
+ async function status(grantId) {
440
+ var record = await _load(grantId);
441
+ if (!record) return null;
442
+ var s = "pending";
443
+ if (record.revokedAt !== null) s = "revoked";
444
+ else if (record.cancelledAt !== null) s = "cancelled";
445
+ else if (record.consumedAt !== null) s = "consumed";
446
+ else if (record.expiresAt < Date.now()) s = "expired";
447
+ else if (record.approvedBy.length >= record.minApprovers) s = "approved";
448
+ return {
449
+ grantId: record.grantId,
450
+ action: record.action,
451
+ status: s,
452
+ requestedBy: record.requestedBy,
453
+ approvedBy: record.approvedBy.slice(),
454
+ needs: record.minApprovers,
455
+ expiresAt: record.expiresAt,
456
+ quorumReachedAt: record.quorumReachedAt,
457
+ consumeUnlockAt: record.quorumReachedAt !== null && record.consumeLockMs > 0
458
+ ? record.quorumReachedAt + record.consumeLockMs : null,
459
+ };
460
+ }
461
+
462
+ return {
463
+ request: request,
464
+ approve: approve,
465
+ revoke: revoke,
466
+ cancel: cancel,
467
+ consume: consume,
468
+ status: status,
469
+ };
470
+ }
471
+
472
+ module.exports = {
473
+ create: create,
474
+ DualControlError: DualControlError,
475
+ };