@blamejs/core 0.7.4 → 0.7.18

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.
Files changed (180) hide show
  1. package/CHANGELOG.md +423 -395
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -284
  5. package/lib/api-key.js +660 -663
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -256
  27. package/lib/cache.js +1206 -1206
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/file-upload.js +213 -10
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -215
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -936
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -264
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -612
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -488
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -519
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -903
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -167
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -745
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -519
  146. package/lib/request-helpers.js +340 -340
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -618
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +184 -4
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -319
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -595
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -1,473 +1,473 @@
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
- validateOpts.requireNonEmptyString(opts.namespace, "create: opts.namespace", DualControlError, "BAD_OPT");
117
- if (!opts.cache || typeof opts.cache.get !== "function" || typeof opts.cache.set !== "function") {
118
- throw _err("BAD_OPT", "create: opts.cache is required (a b.cache instance)");
119
- }
120
- var ttlMs = opts.ttlMs !== undefined ? opts.ttlMs : DEFAULTS.ttlMs;
121
- if (typeof ttlMs !== "number" || !isFinite(ttlMs) || ttlMs <= 0) {
122
- throw _err("BAD_OPT", "create: ttlMs must be a positive finite number");
123
- }
124
- var minApprovers = opts.minApprovers !== undefined ? opts.minApprovers : DEFAULTS.minApprovers;
125
- if (typeof minApprovers !== "number" || !isFinite(minApprovers) ||
126
- minApprovers < 2 || Math.floor(minApprovers) !== minApprovers) {
127
- throw _err("BAD_OPT", "create: minApprovers must be an integer >= 2 (dual-control by definition needs 2+)");
128
- }
129
- var forbidSelfApprove = opts.forbidSelfApprove !== undefined ? opts.forbidSelfApprove === true : DEFAULTS.forbidSelfApprove;
130
- var consumeLockMs = opts.consumeLockMs !== undefined ? opts.consumeLockMs : DEFAULTS.consumeLockMs;
131
- if (typeof consumeLockMs !== "number" || !isFinite(consumeLockMs) || consumeLockMs < 0) {
132
- throw _err("BAD_OPT", "create: consumeLockMs must be a non-negative finite number");
133
- }
134
- var minReasonLength = opts.minReasonLength !== undefined ? opts.minReasonLength : DEFAULTS.minReasonLength;
135
- if (typeof minReasonLength !== "number" || !isFinite(minReasonLength) || minReasonLength < 0 ||
136
- Math.floor(minReasonLength) !== minReasonLength) {
137
- throw _err("BAD_OPT", "create: minReasonLength must be a non-negative integer");
138
- }
139
- var approverRoles = opts.approverRoles !== undefined ? opts.approverRoles : DEFAULTS.approverRoles;
140
- if (approverRoles !== null) {
141
- if (!Array.isArray(approverRoles) || approverRoles.length === 0 ||
142
- !approverRoles.every(function (r) { return typeof r === "string" && r.length > 0; })) {
143
- throw _err("BAD_OPT", "create: approverRoles must be null or a non-empty array of role-name strings");
144
- }
145
- }
146
- var notifyFn = opts.notify;
147
- if (notifyFn !== undefined && notifyFn !== null && typeof notifyFn !== "function") {
148
- throw _err("BAD_OPT", "create: notify must be a function (event) => void or null");
149
- }
150
- var namespace = opts.namespace;
151
- var cache = opts.cache;
152
- var auditOn = opts.audit !== false && opts.audit != null;
153
- var auditInstance = (opts.audit && opts.audit !== true) ? opts.audit : null;
154
-
155
- function _emit(action, info, outcome, req) {
156
- if (auditOn) {
157
- var sink = auditInstance || audit();
158
- try {
159
- sink.safeEmit({
160
- action: action,
161
- outcome: outcome,
162
- actor: requestHelpers.extractActorContext(req),
163
- resource: { kind: "dual.grant", id: info.grantId },
164
- reason: info.reason || null,
165
- metadata: info,
166
- });
167
- } catch (_e) { /* best-effort */ }
168
- }
169
- if (notifyFn) {
170
- try { notifyFn({ action: action, outcome: outcome, info: info }); }
171
- catch (_e) { /* best-effort */ }
172
- }
173
- }
174
-
175
- function _checkReason(reason, where) {
176
- if (minReasonLength <= 0) return null;
177
- var s = (reason == null) ? "" : String(reason).trim();
178
- if (s.length < minReasonLength) {
179
- return { error: "reason-too-short",
180
- message: where + ": reason must be at least " + minReasonLength + " characters" };
181
- }
182
- return null;
183
- }
184
-
185
- function _approverRoleOk(actor) {
186
- if (!approverRoles) return true;
187
- if (!actor || !Array.isArray(actor.roles)) return false;
188
- for (var i = 0; i < approverRoles.length; i++) {
189
- if (actor.roles.indexOf(approverRoles[i]) !== -1) return true;
190
- }
191
- return false;
192
- }
193
-
194
- function _key(grantId) { return namespace + ":" + grantId; }
195
-
196
- async function request(args) {
197
- if (!args || typeof args !== "object") {
198
- throw _err("BAD_ARG", "request: args object required");
199
- }
200
- if (typeof args.action !== "string" || args.action.length === 0) {
201
- throw _err("BAD_ARG", "request: args.action (string) is required");
202
- }
203
- var requesterId = _actorIdOf(args.requestedBy);
204
- if (!requesterId) {
205
- throw _err("BAD_ARG", "request: args.requestedBy must be an actor with a stable id");
206
- }
207
- var reasonProblem = _checkReason(args.reason, "request");
208
- if (reasonProblem) {
209
- return Object.assign({ grantId: null }, reasonProblem);
210
- }
211
- var grantId = "dc-" + crypto.generateToken(C.BYTES.bytes(8));
212
- var nowMs = Date.now();
213
- var record = {
214
- grantId: grantId,
215
- action: args.action,
216
- resource: args.resource || null,
217
- requestedBy: requesterId,
218
- requestedAt: nowMs,
219
- reason: args.reason || null,
220
- approvedBy: [], // ordered list of approver IDs
221
- approvalsAt: [], // matching timestamps
222
- approvalReasons:[],
223
- approverRoleHits: [], // recorded for audit when approverRoles is set
224
- consumedAt: null,
225
- revokedAt: null,
226
- revokedReason: null,
227
- cancelledAt: null,
228
- cancelledReason:null,
229
- quorumReachedAt:null,
230
- expiresAt: nowMs + ttlMs,
231
- minApprovers: minApprovers,
232
- consumeLockMs: consumeLockMs,
233
- };
234
- await cache.set(_key(grantId), record, { ttlMs: ttlMs });
235
- _emit("dual.grant.requested",
236
- { grantId: grantId, action: args.action, requestedBy: requesterId, needs: minApprovers,
237
- reason: args.reason || null, expiresAt: record.expiresAt,
238
- consumeLockMs: consumeLockMs, approverRolesRequired: approverRoles },
239
- "success", args.req);
240
- return {
241
- grantId: grantId,
242
- status: "pending",
243
- needs: minApprovers,
244
- approvedBy: [],
245
- expiresAt: record.expiresAt,
246
- };
247
- }
248
-
249
- async function cancel(args) {
250
- if (!args || typeof args !== "object") throw _err("BAD_ARG", "cancel: args required");
251
- var record = await _load(args.grantId);
252
- if (!record) return { error: "grant-not-found", grantId: args.grantId };
253
- if (record.consumedAt !== null) return { error: "grant-already-consumed", grantId: record.grantId };
254
- if (record.revokedAt !== null) return { error: "grant-revoked", grantId: record.grantId };
255
- if (record.cancelledAt !== null) return { error: "grant-already-cancelled", grantId: record.grantId };
256
- var actorId = _actorIdOf(args.cancelledBy);
257
- if (actorId !== record.requestedBy) {
258
- // Cancellation by anyone other than the requester is a revoke,
259
- // not a cancel. Surface explicitly.
260
- return { error: "only-requester-can-cancel", grantId: record.grantId,
261
- requestedBy: record.requestedBy };
262
- }
263
- record.cancelledAt = Date.now();
264
- record.cancelledReason = args.reason || null;
265
- var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
266
- await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
267
- _emit("dual.grant.cancelled",
268
- { grantId: record.grantId, action: record.action,
269
- cancelledBy: actorId, reason: args.reason || null },
270
- "success", args.req);
271
- return { grantId: record.grantId, status: "cancelled" };
272
- }
273
-
274
- async function _load(grantId) {
275
- if (typeof grantId !== "string" || grantId.length === 0) {
276
- throw _err("BAD_ARG", "grantId (string) is required");
277
- }
278
- var record = await cache.get(_key(grantId));
279
- return record || null;
280
- }
281
-
282
- async function approve(args) {
283
- if (!args || typeof args !== "object") throw _err("BAD_ARG", "approve: args required");
284
- var record = await _load(args.grantId);
285
- if (!record) {
286
- return { error: "grant-not-found", grantId: args.grantId };
287
- }
288
- if (record.consumedAt !== null) {
289
- return { error: "grant-already-consumed", grantId: record.grantId };
290
- }
291
- if (record.revokedAt !== null) {
292
- return { error: "grant-revoked", grantId: record.grantId, revokedReason: record.revokedReason };
293
- }
294
- if (record.cancelledAt !== null) {
295
- return { error: "grant-cancelled", grantId: record.grantId };
296
- }
297
- if (record.expiresAt < Date.now()) {
298
- _emit("dual.grant.expired", { grantId: record.grantId, action: record.action },
299
- "failure", args.req);
300
- await cache.del(_key(record.grantId));
301
- return { error: "grant-expired", grantId: record.grantId };
302
- }
303
- var approverId = _actorIdOf(args.approver);
304
- if (!approverId) throw _err("BAD_ARG", "approve: args.approver must be an actor with a stable id");
305
- if (forbidSelfApprove && approverId === record.requestedBy) {
306
- _emit("dual.grant.self_approval_denied",
307
- { grantId: record.grantId, action: record.action, approver: approverId },
308
- "denied", args.req);
309
- return { error: "self-approval-forbidden", grantId: record.grantId };
310
- }
311
- if (!_approverRoleOk(args.approver)) {
312
- _emit("dual.grant.role_denied",
313
- { grantId: record.grantId, action: record.action, approver: approverId,
314
- requiredRoles: approverRoles,
315
- actorRoles: (args.approver && Array.isArray(args.approver.roles)) ? args.approver.roles : [] },
316
- "denied", args.req);
317
- return { error: "approver-role-required", grantId: record.grantId,
318
- requiredRoles: approverRoles };
319
- }
320
- if (record.approvedBy.indexOf(approverId) !== -1) {
321
- return { error: "already-approved-by-this-actor", grantId: record.grantId,
322
- approvedBy: record.approvedBy };
323
- }
324
- var reasonProblem = _checkReason(args.reason, "approve");
325
- if (reasonProblem) {
326
- return Object.assign({ grantId: record.grantId }, reasonProblem);
327
- }
328
- record.approvedBy.push(approverId);
329
- record.approvalsAt.push(Date.now());
330
- record.approvalReasons.push(args.reason || null);
331
- if (approverRoles && args.approver && Array.isArray(args.approver.roles)) {
332
- // Record which of the required roles satisfied the approval —
333
- // useful when an audit reviewer needs to confirm the actor
334
- // approved as e.g. their security-officer role and not their
335
- // engineer role.
336
- var hits = args.approver.roles.filter(function (r) { return approverRoles.indexOf(r) !== -1; });
337
- record.approverRoleHits.push(hits);
338
- }
339
- var status = "pending";
340
- if (record.approvedBy.length >= record.minApprovers) {
341
- status = "approved";
342
- if (record.quorumReachedAt === null) record.quorumReachedAt = Date.now();
343
- }
344
- var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
345
- await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
346
- _emit("dual.grant.approved",
347
- { grantId: record.grantId, action: record.action, approver: approverId,
348
- approverCount: record.approvedBy.length, needs: record.minApprovers,
349
- status: status, reason: args.reason || null,
350
- consumeUnlockAt: record.quorumReachedAt !== null
351
- ? record.quorumReachedAt + record.consumeLockMs : null },
352
- "success", args.req);
353
- return {
354
- grantId: record.grantId,
355
- status: status,
356
- approvedBy: record.approvedBy.slice(),
357
- needs: record.minApprovers,
358
- expiresAt: record.expiresAt,
359
- consumeUnlockAt: record.quorumReachedAt !== null
360
- ? record.quorumReachedAt + record.consumeLockMs : null,
361
- };
362
- }
363
-
364
- async function revoke(args) {
365
- if (!args || typeof args !== "object") throw _err("BAD_ARG", "revoke: args required");
366
- var record = await _load(args.grantId);
367
- if (!record) return { error: "grant-not-found", grantId: args.grantId };
368
- if (record.consumedAt !== null) {
369
- return { error: "grant-already-consumed", grantId: record.grantId };
370
- }
371
- record.revokedAt = Date.now();
372
- record.revokedReason = args.reason || null;
373
- var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
374
- await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
375
- _emit("dual.grant.denied",
376
- { grantId: record.grantId, action: record.action,
377
- revokedBy: _actorIdOf(args.revokedBy), reason: args.reason || null },
378
- "denied", args.req);
379
- return { grantId: record.grantId, status: "revoked" };
380
- }
381
-
382
- async function consume(grantId, args) {
383
- args = args || {};
384
- var record = await _load(grantId);
385
- if (!record) return { ready: false, reason: "grant-not-found" };
386
- if (record.revokedAt !== null) {
387
- return { ready: false, reason: "revoked" };
388
- }
389
- if (record.cancelledAt !== null) {
390
- return { ready: false, reason: "cancelled" };
391
- }
392
- if (record.consumedAt !== null) {
393
- return { ready: false, reason: "already-consumed" };
394
- }
395
- if (record.expiresAt < Date.now()) {
396
- _emit("dual.grant.expired", { grantId: record.grantId, action: record.action },
397
- "failure", args.req);
398
- await cache.del(_key(record.grantId));
399
- return { ready: false, reason: "expired" };
400
- }
401
- if (record.approvedBy.length < record.minApprovers) {
402
- return { ready: false, reason: "not-enough-approvers",
403
- approvedBy: record.approvedBy.slice(), needs: record.minApprovers };
404
- }
405
- // Cooling-off lock: ANY approval-quorum-reached grant can't consume
406
- // until consumeLockMs has passed since the final approval. Defends
407
- // against rapid-burst compromise of requester+approver.
408
- if ((record.consumeLockMs || 0) > 0 && record.quorumReachedAt !== null) {
409
- var unlockAt = record.quorumReachedAt + record.consumeLockMs;
410
- if (Date.now() < unlockAt) {
411
- _emit("dual.grant.consume_locked",
412
- { grantId: record.grantId, action: record.action,
413
- unlockAt: unlockAt, waitMs: unlockAt - Date.now() },
414
- "denied", args.req);
415
- return { ready: false, reason: "consume-locked", unlockAt: unlockAt,
416
- waitMs: unlockAt - Date.now() };
417
- }
418
- }
419
- record.consumedAt = Date.now();
420
- // Drop the grant from the cache after consume — single-use by design.
421
- await cache.del(_key(record.grantId));
422
- _emit("dual.grant.consumed",
423
- { grantId: record.grantId, action: record.action,
424
- approvedBy: record.approvedBy.slice(),
425
- approvalReasons: record.approvalReasons.slice() },
426
- "success", args.req);
427
- return {
428
- ready: true,
429
- grantId: record.grantId,
430
- action: record.action,
431
- resource: record.resource,
432
- approvedBy: record.approvedBy.slice(),
433
- requestedBy:record.requestedBy,
434
- };
435
- }
436
-
437
- async function status(grantId) {
438
- var record = await _load(grantId);
439
- if (!record) return null;
440
- var s = "pending";
441
- if (record.revokedAt !== null) s = "revoked";
442
- else if (record.cancelledAt !== null) s = "cancelled";
443
- else if (record.consumedAt !== null) s = "consumed";
444
- else if (record.expiresAt < Date.now()) s = "expired";
445
- else if (record.approvedBy.length >= record.minApprovers) s = "approved";
446
- return {
447
- grantId: record.grantId,
448
- action: record.action,
449
- status: s,
450
- requestedBy: record.requestedBy,
451
- approvedBy: record.approvedBy.slice(),
452
- needs: record.minApprovers,
453
- expiresAt: record.expiresAt,
454
- quorumReachedAt: record.quorumReachedAt,
455
- consumeUnlockAt: record.quorumReachedAt !== null && record.consumeLockMs > 0
456
- ? record.quorumReachedAt + record.consumeLockMs : null,
457
- };
458
- }
459
-
460
- return {
461
- request: request,
462
- approve: approve,
463
- revoke: revoke,
464
- cancel: cancel,
465
- consume: consume,
466
- status: status,
467
- };
468
- }
469
-
470
- module.exports = {
471
- create: create,
472
- DualControlError: DualControlError,
473
- };
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
+ validateOpts.requireNonEmptyString(opts.namespace, "create: opts.namespace", DualControlError, "BAD_OPT");
117
+ if (!opts.cache || typeof opts.cache.get !== "function" || typeof opts.cache.set !== "function") {
118
+ throw _err("BAD_OPT", "create: opts.cache is required (a b.cache instance)");
119
+ }
120
+ var ttlMs = opts.ttlMs !== undefined ? opts.ttlMs : DEFAULTS.ttlMs;
121
+ if (typeof ttlMs !== "number" || !isFinite(ttlMs) || ttlMs <= 0) {
122
+ throw _err("BAD_OPT", "create: ttlMs must be a positive finite number");
123
+ }
124
+ var minApprovers = opts.minApprovers !== undefined ? opts.minApprovers : DEFAULTS.minApprovers;
125
+ if (typeof minApprovers !== "number" || !isFinite(minApprovers) ||
126
+ minApprovers < 2 || Math.floor(minApprovers) !== minApprovers) {
127
+ throw _err("BAD_OPT", "create: minApprovers must be an integer >= 2 (dual-control by definition needs 2+)");
128
+ }
129
+ var forbidSelfApprove = opts.forbidSelfApprove !== undefined ? opts.forbidSelfApprove === true : DEFAULTS.forbidSelfApprove;
130
+ var consumeLockMs = opts.consumeLockMs !== undefined ? opts.consumeLockMs : DEFAULTS.consumeLockMs;
131
+ if (typeof consumeLockMs !== "number" || !isFinite(consumeLockMs) || consumeLockMs < 0) {
132
+ throw _err("BAD_OPT", "create: consumeLockMs must be a non-negative finite number");
133
+ }
134
+ var minReasonLength = opts.minReasonLength !== undefined ? opts.minReasonLength : DEFAULTS.minReasonLength;
135
+ if (typeof minReasonLength !== "number" || !isFinite(minReasonLength) || minReasonLength < 0 ||
136
+ Math.floor(minReasonLength) !== minReasonLength) {
137
+ throw _err("BAD_OPT", "create: minReasonLength must be a non-negative integer");
138
+ }
139
+ var approverRoles = opts.approverRoles !== undefined ? opts.approverRoles : DEFAULTS.approverRoles;
140
+ if (approverRoles !== null) {
141
+ if (!Array.isArray(approverRoles) || approverRoles.length === 0 ||
142
+ !approverRoles.every(function (r) { return typeof r === "string" && r.length > 0; })) {
143
+ throw _err("BAD_OPT", "create: approverRoles must be null or a non-empty array of role-name strings");
144
+ }
145
+ }
146
+ var notifyFn = opts.notify;
147
+ if (notifyFn !== undefined && notifyFn !== null && typeof notifyFn !== "function") {
148
+ throw _err("BAD_OPT", "create: notify must be a function (event) => void or null");
149
+ }
150
+ var namespace = opts.namespace;
151
+ var cache = opts.cache;
152
+ var auditOn = opts.audit !== false && opts.audit != null;
153
+ var auditInstance = (opts.audit && opts.audit !== true) ? opts.audit : null;
154
+
155
+ function _emit(action, info, outcome, req) {
156
+ if (auditOn) {
157
+ var sink = auditInstance || audit();
158
+ try {
159
+ sink.safeEmit({
160
+ action: action,
161
+ outcome: outcome,
162
+ actor: requestHelpers.extractActorContext(req),
163
+ resource: { kind: "dual.grant", id: info.grantId },
164
+ reason: info.reason || null,
165
+ metadata: info,
166
+ });
167
+ } catch (_e) { /* best-effort */ }
168
+ }
169
+ if (notifyFn) {
170
+ try { notifyFn({ action: action, outcome: outcome, info: info }); }
171
+ catch (_e) { /* best-effort */ }
172
+ }
173
+ }
174
+
175
+ function _checkReason(reason, where) {
176
+ if (minReasonLength <= 0) return null;
177
+ var s = (reason == null) ? "" : String(reason).trim();
178
+ if (s.length < minReasonLength) {
179
+ return { error: "reason-too-short",
180
+ message: where + ": reason must be at least " + minReasonLength + " characters" };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function _approverRoleOk(actor) {
186
+ if (!approverRoles) return true;
187
+ if (!actor || !Array.isArray(actor.roles)) return false;
188
+ for (var i = 0; i < approverRoles.length; i++) {
189
+ if (actor.roles.indexOf(approverRoles[i]) !== -1) return true;
190
+ }
191
+ return false;
192
+ }
193
+
194
+ function _key(grantId) { return namespace + ":" + grantId; }
195
+
196
+ async function request(args) {
197
+ if (!args || typeof args !== "object") {
198
+ throw _err("BAD_ARG", "request: args object required");
199
+ }
200
+ if (typeof args.action !== "string" || args.action.length === 0) {
201
+ throw _err("BAD_ARG", "request: args.action (string) is required");
202
+ }
203
+ var requesterId = _actorIdOf(args.requestedBy);
204
+ if (!requesterId) {
205
+ throw _err("BAD_ARG", "request: args.requestedBy must be an actor with a stable id");
206
+ }
207
+ var reasonProblem = _checkReason(args.reason, "request");
208
+ if (reasonProblem) {
209
+ return Object.assign({ grantId: null }, reasonProblem);
210
+ }
211
+ var grantId = "dc-" + crypto.generateToken(C.BYTES.bytes(8));
212
+ var nowMs = Date.now();
213
+ var record = {
214
+ grantId: grantId,
215
+ action: args.action,
216
+ resource: args.resource || null,
217
+ requestedBy: requesterId,
218
+ requestedAt: nowMs,
219
+ reason: args.reason || null,
220
+ approvedBy: [], // ordered list of approver IDs
221
+ approvalsAt: [], // matching timestamps
222
+ approvalReasons:[],
223
+ approverRoleHits: [], // recorded for audit when approverRoles is set
224
+ consumedAt: null,
225
+ revokedAt: null,
226
+ revokedReason: null,
227
+ cancelledAt: null,
228
+ cancelledReason:null,
229
+ quorumReachedAt:null,
230
+ expiresAt: nowMs + ttlMs,
231
+ minApprovers: minApprovers,
232
+ consumeLockMs: consumeLockMs,
233
+ };
234
+ await cache.set(_key(grantId), record, { ttlMs: ttlMs });
235
+ _emit("dual.grant.requested",
236
+ { grantId: grantId, action: args.action, requestedBy: requesterId, needs: minApprovers,
237
+ reason: args.reason || null, expiresAt: record.expiresAt,
238
+ consumeLockMs: consumeLockMs, approverRolesRequired: approverRoles },
239
+ "success", args.req);
240
+ return {
241
+ grantId: grantId,
242
+ status: "pending",
243
+ needs: minApprovers,
244
+ approvedBy: [],
245
+ expiresAt: record.expiresAt,
246
+ };
247
+ }
248
+
249
+ async function cancel(args) {
250
+ if (!args || typeof args !== "object") throw _err("BAD_ARG", "cancel: args required");
251
+ var record = await _load(args.grantId);
252
+ if (!record) return { error: "grant-not-found", grantId: args.grantId };
253
+ if (record.consumedAt !== null) return { error: "grant-already-consumed", grantId: record.grantId };
254
+ if (record.revokedAt !== null) return { error: "grant-revoked", grantId: record.grantId };
255
+ if (record.cancelledAt !== null) return { error: "grant-already-cancelled", grantId: record.grantId };
256
+ var actorId = _actorIdOf(args.cancelledBy);
257
+ if (actorId !== record.requestedBy) {
258
+ // Cancellation by anyone other than the requester is a revoke,
259
+ // not a cancel. Surface explicitly.
260
+ return { error: "only-requester-can-cancel", grantId: record.grantId,
261
+ requestedBy: record.requestedBy };
262
+ }
263
+ record.cancelledAt = Date.now();
264
+ record.cancelledReason = args.reason || null;
265
+ var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
266
+ await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
267
+ _emit("dual.grant.cancelled",
268
+ { grantId: record.grantId, action: record.action,
269
+ cancelledBy: actorId, reason: args.reason || null },
270
+ "success", args.req);
271
+ return { grantId: record.grantId, status: "cancelled" };
272
+ }
273
+
274
+ async function _load(grantId) {
275
+ if (typeof grantId !== "string" || grantId.length === 0) {
276
+ throw _err("BAD_ARG", "grantId (string) is required");
277
+ }
278
+ var record = await cache.get(_key(grantId));
279
+ return record || null;
280
+ }
281
+
282
+ async function approve(args) {
283
+ if (!args || typeof args !== "object") throw _err("BAD_ARG", "approve: args required");
284
+ var record = await _load(args.grantId);
285
+ if (!record) {
286
+ return { error: "grant-not-found", grantId: args.grantId };
287
+ }
288
+ if (record.consumedAt !== null) {
289
+ return { error: "grant-already-consumed", grantId: record.grantId };
290
+ }
291
+ if (record.revokedAt !== null) {
292
+ return { error: "grant-revoked", grantId: record.grantId, revokedReason: record.revokedReason };
293
+ }
294
+ if (record.cancelledAt !== null) {
295
+ return { error: "grant-cancelled", grantId: record.grantId };
296
+ }
297
+ if (record.expiresAt < Date.now()) {
298
+ _emit("dual.grant.expired", { grantId: record.grantId, action: record.action },
299
+ "failure", args.req);
300
+ await cache.del(_key(record.grantId));
301
+ return { error: "grant-expired", grantId: record.grantId };
302
+ }
303
+ var approverId = _actorIdOf(args.approver);
304
+ if (!approverId) throw _err("BAD_ARG", "approve: args.approver must be an actor with a stable id");
305
+ if (forbidSelfApprove && approverId === record.requestedBy) {
306
+ _emit("dual.grant.self_approval_denied",
307
+ { grantId: record.grantId, action: record.action, approver: approverId },
308
+ "denied", args.req);
309
+ return { error: "self-approval-forbidden", grantId: record.grantId };
310
+ }
311
+ if (!_approverRoleOk(args.approver)) {
312
+ _emit("dual.grant.role_denied",
313
+ { grantId: record.grantId, action: record.action, approver: approverId,
314
+ requiredRoles: approverRoles,
315
+ actorRoles: (args.approver && Array.isArray(args.approver.roles)) ? args.approver.roles : [] },
316
+ "denied", args.req);
317
+ return { error: "approver-role-required", grantId: record.grantId,
318
+ requiredRoles: approverRoles };
319
+ }
320
+ if (record.approvedBy.indexOf(approverId) !== -1) {
321
+ return { error: "already-approved-by-this-actor", grantId: record.grantId,
322
+ approvedBy: record.approvedBy };
323
+ }
324
+ var reasonProblem = _checkReason(args.reason, "approve");
325
+ if (reasonProblem) {
326
+ return Object.assign({ grantId: record.grantId }, reasonProblem);
327
+ }
328
+ record.approvedBy.push(approverId);
329
+ record.approvalsAt.push(Date.now());
330
+ record.approvalReasons.push(args.reason || null);
331
+ if (approverRoles && args.approver && Array.isArray(args.approver.roles)) {
332
+ // Record which of the required roles satisfied the approval —
333
+ // useful when an audit reviewer needs to confirm the actor
334
+ // approved as e.g. their security-officer role and not their
335
+ // engineer role.
336
+ var hits = args.approver.roles.filter(function (r) { return approverRoles.indexOf(r) !== -1; });
337
+ record.approverRoleHits.push(hits);
338
+ }
339
+ var status = "pending";
340
+ if (record.approvedBy.length >= record.minApprovers) {
341
+ status = "approved";
342
+ if (record.quorumReachedAt === null) record.quorumReachedAt = Date.now();
343
+ }
344
+ var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
345
+ await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
346
+ _emit("dual.grant.approved",
347
+ { grantId: record.grantId, action: record.action, approver: approverId,
348
+ approverCount: record.approvedBy.length, needs: record.minApprovers,
349
+ status: status, reason: args.reason || null,
350
+ consumeUnlockAt: record.quorumReachedAt !== null
351
+ ? record.quorumReachedAt + record.consumeLockMs : null },
352
+ "success", args.req);
353
+ return {
354
+ grantId: record.grantId,
355
+ status: status,
356
+ approvedBy: record.approvedBy.slice(),
357
+ needs: record.minApprovers,
358
+ expiresAt: record.expiresAt,
359
+ consumeUnlockAt: record.quorumReachedAt !== null
360
+ ? record.quorumReachedAt + record.consumeLockMs : null,
361
+ };
362
+ }
363
+
364
+ async function revoke(args) {
365
+ if (!args || typeof args !== "object") throw _err("BAD_ARG", "revoke: args required");
366
+ var record = await _load(args.grantId);
367
+ if (!record) return { error: "grant-not-found", grantId: args.grantId };
368
+ if (record.consumedAt !== null) {
369
+ return { error: "grant-already-consumed", grantId: record.grantId };
370
+ }
371
+ record.revokedAt = Date.now();
372
+ record.revokedReason = args.reason || null;
373
+ var ttlRemaining = Math.max(1, record.expiresAt - Date.now());
374
+ await cache.set(_key(record.grantId), record, { ttlMs: ttlRemaining });
375
+ _emit("dual.grant.denied",
376
+ { grantId: record.grantId, action: record.action,
377
+ revokedBy: _actorIdOf(args.revokedBy), reason: args.reason || null },
378
+ "denied", args.req);
379
+ return { grantId: record.grantId, status: "revoked" };
380
+ }
381
+
382
+ async function consume(grantId, args) {
383
+ args = args || {};
384
+ var record = await _load(grantId);
385
+ if (!record) return { ready: false, reason: "grant-not-found" };
386
+ if (record.revokedAt !== null) {
387
+ return { ready: false, reason: "revoked" };
388
+ }
389
+ if (record.cancelledAt !== null) {
390
+ return { ready: false, reason: "cancelled" };
391
+ }
392
+ if (record.consumedAt !== null) {
393
+ return { ready: false, reason: "already-consumed" };
394
+ }
395
+ if (record.expiresAt < Date.now()) {
396
+ _emit("dual.grant.expired", { grantId: record.grantId, action: record.action },
397
+ "failure", args.req);
398
+ await cache.del(_key(record.grantId));
399
+ return { ready: false, reason: "expired" };
400
+ }
401
+ if (record.approvedBy.length < record.minApprovers) {
402
+ return { ready: false, reason: "not-enough-approvers",
403
+ approvedBy: record.approvedBy.slice(), needs: record.minApprovers };
404
+ }
405
+ // Cooling-off lock: ANY approval-quorum-reached grant can't consume
406
+ // until consumeLockMs has passed since the final approval. Defends
407
+ // against rapid-burst compromise of requester+approver.
408
+ if ((record.consumeLockMs || 0) > 0 && record.quorumReachedAt !== null) {
409
+ var unlockAt = record.quorumReachedAt + record.consumeLockMs;
410
+ if (Date.now() < unlockAt) {
411
+ _emit("dual.grant.consume_locked",
412
+ { grantId: record.grantId, action: record.action,
413
+ unlockAt: unlockAt, waitMs: unlockAt - Date.now() },
414
+ "denied", args.req);
415
+ return { ready: false, reason: "consume-locked", unlockAt: unlockAt,
416
+ waitMs: unlockAt - Date.now() };
417
+ }
418
+ }
419
+ record.consumedAt = Date.now();
420
+ // Drop the grant from the cache after consume — single-use by design.
421
+ await cache.del(_key(record.grantId));
422
+ _emit("dual.grant.consumed",
423
+ { grantId: record.grantId, action: record.action,
424
+ approvedBy: record.approvedBy.slice(),
425
+ approvalReasons: record.approvalReasons.slice() },
426
+ "success", args.req);
427
+ return {
428
+ ready: true,
429
+ grantId: record.grantId,
430
+ action: record.action,
431
+ resource: record.resource,
432
+ approvedBy: record.approvedBy.slice(),
433
+ requestedBy:record.requestedBy,
434
+ };
435
+ }
436
+
437
+ async function status(grantId) {
438
+ var record = await _load(grantId);
439
+ if (!record) return null;
440
+ var s = "pending";
441
+ if (record.revokedAt !== null) s = "revoked";
442
+ else if (record.cancelledAt !== null) s = "cancelled";
443
+ else if (record.consumedAt !== null) s = "consumed";
444
+ else if (record.expiresAt < Date.now()) s = "expired";
445
+ else if (record.approvedBy.length >= record.minApprovers) s = "approved";
446
+ return {
447
+ grantId: record.grantId,
448
+ action: record.action,
449
+ status: s,
450
+ requestedBy: record.requestedBy,
451
+ approvedBy: record.approvedBy.slice(),
452
+ needs: record.minApprovers,
453
+ expiresAt: record.expiresAt,
454
+ quorumReachedAt: record.quorumReachedAt,
455
+ consumeUnlockAt: record.quorumReachedAt !== null && record.consumeLockMs > 0
456
+ ? record.quorumReachedAt + record.consumeLockMs : null,
457
+ };
458
+ }
459
+
460
+ return {
461
+ request: request,
462
+ approve: approve,
463
+ revoke: revoke,
464
+ cancel: cancel,
465
+ consume: consume,
466
+ status: status,
467
+ };
468
+ }
469
+
470
+ module.exports = {
471
+ create: create,
472
+ DualControlError: DualControlError,
473
+ };