@blamejs/core 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +230 -0
- package/LICENSE +201 -0
- package/LTS-CALENDAR.md +29 -0
- package/MIGRATING.md +7 -0
- package/NOTICE +59 -0
- package/README.md +100 -0
- package/bin/blamejs.js +13 -0
- package/index.js +253 -0
- package/lib/api-key.js +705 -0
- package/lib/api-snapshot.js +335 -0
- package/lib/app-shutdown.js +381 -0
- package/lib/app.js +364 -0
- package/lib/atomic-file.js +525 -0
- package/lib/audit-chain.js +168 -0
- package/lib/audit-sign.js +319 -0
- package/lib/audit-tools.js +682 -0
- package/lib/audit.js +753 -0
- package/lib/auth/jwt.js +280 -0
- package/lib/auth/oauth.js +691 -0
- package/lib/auth/passkey.js +185 -0
- package/lib/auth/password.js +139 -0
- package/lib/auth/totp.js +17 -0
- package/lib/auth-header.js +81 -0
- package/lib/backup/bundle.js +219 -0
- package/lib/backup/crypto.js +174 -0
- package/lib/backup/index.js +490 -0
- package/lib/backup/manifest.js +275 -0
- package/lib/bundler.js +295 -0
- package/lib/cache.js +819 -0
- package/lib/chain-writer.js +234 -0
- package/lib/cli-helpers.js +201 -0
- package/lib/cli.js +1377 -0
- package/lib/cluster-provider-db.js +245 -0
- package/lib/cluster-storage.js +166 -0
- package/lib/cluster.js +691 -0
- package/lib/consent.js +222 -0
- package/lib/constants.js +186 -0
- package/lib/cookies.js +293 -0
- package/lib/credential-hash.js +303 -0
- package/lib/crypto-field.js +159 -0
- package/lib/crypto.js +250 -0
- package/lib/db-query.js +297 -0
- package/lib/db-schema.js +250 -0
- package/lib/db.js +1054 -0
- package/lib/deprecate.js +226 -0
- package/lib/dev.js +324 -0
- package/lib/error-page.js +424 -0
- package/lib/events.js +135 -0
- package/lib/external-db.js +422 -0
- package/lib/forms.js +378 -0
- package/lib/framework-error.js +189 -0
- package/lib/framework-schema.js +604 -0
- package/lib/handlers.js +350 -0
- package/lib/html-balance.js +227 -0
- package/lib/http-client.js +615 -0
- package/lib/i18n.js +780 -0
- package/lib/jobs.js +181 -0
- package/lib/lazy-require.js +48 -0
- package/lib/log-stream-local.js +137 -0
- package/lib/log-stream-webhook.js +170 -0
- package/lib/log-stream.js +211 -0
- package/lib/log.js +355 -0
- package/lib/mail-bounce.js +507 -0
- package/lib/mail.js +701 -0
- package/lib/metrics.js +647 -0
- package/lib/middleware/api-encrypt.js +553 -0
- package/lib/middleware/attach-user.js +156 -0
- package/lib/middleware/body-parser.js +883 -0
- package/lib/middleware/bot-guard.js +148 -0
- package/lib/middleware/compression.js +436 -0
- package/lib/middleware/cors.js +236 -0
- package/lib/middleware/csp-nonce.js +332 -0
- package/lib/middleware/csrf-protect.js +275 -0
- package/lib/middleware/error-handler.js +46 -0
- package/lib/middleware/health.js +358 -0
- package/lib/middleware/index.js +52 -0
- package/lib/middleware/rate-limit.js +319 -0
- package/lib/middleware/request-id.js +53 -0
- package/lib/middleware/require-auth.js +95 -0
- package/lib/middleware/security-headers.js +91 -0
- package/lib/migrations.js +353 -0
- package/lib/mtls-ca.js +333 -0
- package/lib/mtls-engine-default.js +285 -0
- package/lib/nonce-store.js +177 -0
- package/lib/notify.js +643 -0
- package/lib/ntp-check.js +178 -0
- package/lib/object-store/azure-blob.js +467 -0
- package/lib/object-store/gcs.js +469 -0
- package/lib/object-store/http-put.js +153 -0
- package/lib/object-store/index.js +140 -0
- package/lib/object-store/local.js +163 -0
- package/lib/object-store/retry.js +15 -0
- package/lib/object-store/sigv4.js +535 -0
- package/lib/observability.js +114 -0
- package/lib/pagination.js +371 -0
- package/lib/parsers/index.js +64 -0
- package/lib/parsers/safe-csv.js +224 -0
- package/lib/parsers/safe-env.js +614 -0
- package/lib/parsers/safe-toml.js +745 -0
- package/lib/parsers/safe-xml.js +379 -0
- package/lib/parsers/safe-yaml.js +977 -0
- package/lib/permissions.js +430 -0
- package/lib/pqc-agent.js +85 -0
- package/lib/pqc-gate.js +266 -0
- package/lib/protocol-dispatcher.js +144 -0
- package/lib/queue-local.js +327 -0
- package/lib/queue.js +430 -0
- package/lib/redact.js +192 -0
- package/lib/render.js +193 -0
- package/lib/request-helpers.js +178 -0
- package/lib/restore-bundle.js +239 -0
- package/lib/restore-rollback.js +254 -0
- package/lib/restore.js +301 -0
- package/lib/retry.js +329 -0
- package/lib/router.js +437 -0
- package/lib/safe-async.js +520 -0
- package/lib/safe-buffer.js +162 -0
- package/lib/safe-json.js +532 -0
- package/lib/safe-schema.js +1176 -0
- package/lib/safe-sql.js +157 -0
- package/lib/safe-url.js +109 -0
- package/lib/scheduler.js +680 -0
- package/lib/seeders.js +622 -0
- package/lib/session.js +304 -0
- package/lib/slug.js +243 -0
- package/lib/static.js +268 -0
- package/lib/storage.js +470 -0
- package/lib/subject.js +281 -0
- package/lib/template.js +781 -0
- package/lib/testing.js +621 -0
- package/lib/totp.js +285 -0
- package/lib/tracing.js +484 -0
- package/lib/validate-opts.js +56 -0
- package/lib/vault/index.js +299 -0
- package/lib/vault/passphrase-ops.js +311 -0
- package/lib/vault/passphrase-source.js +198 -0
- package/lib/vault/rotate.js +761 -0
- package/lib/vault/wrap.js +289 -0
- package/lib/vendor/MANIFEST.json +84 -0
- package/lib/vendor/argon2/argon2.cjs +466 -0
- package/lib/vendor/argon2/argon2.d.cts +62 -0
- package/lib/vendor/argon2/package.json +1 -0
- package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
- package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
- package/lib/vendor/noble-ciphers.cjs +9 -0
- package/lib/vendor/pki.cjs +181 -0
- package/lib/vendor/simplewebauthn-server.cjs +328 -0
- package/lib/webhook.js +632 -0
- package/lib/websocket-channels.js +413 -0
- package/lib/websocket.js +833 -0
- package/package.json +39 -0
package/lib/queue.js
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Queue dispatcher — pluggable job queue with retry, lease semantics, and
|
|
4
|
+
* graceful shutdown.
|
|
5
|
+
*
|
|
6
|
+
* Same dispatcher pattern as object-store: backends are configured per-name,
|
|
7
|
+
* each with a protocol + protocol-specific options. The built-in 'local'
|
|
8
|
+
* protocol is SQLite-backed (baked into the framework's main DB).
|
|
9
|
+
* External protocols (redis, sqs, amqp, nats) are listed as deferred and
|
|
10
|
+
* surface a clear error when selected.
|
|
11
|
+
*
|
|
12
|
+
* Public API:
|
|
13
|
+
* queue.init({ backends: { name: { protocol: 'local' } }, defaultBackend? })
|
|
14
|
+
* queue.enqueue(queueName, payload, opts?)
|
|
15
|
+
* → { jobId, queueName, ... }
|
|
16
|
+
* queue.consume(queueName, handler, opts?)
|
|
17
|
+
* → consumer handle (with cancel())
|
|
18
|
+
* queue.size(queueName, opts?) → number (pending + inflight)
|
|
19
|
+
* queue.purge(queueName, opts?) → number deleted
|
|
20
|
+
* queue.shutdown(opts?) → drain handlers gracefully
|
|
21
|
+
* queue.listBackends() → [{ name, protocol }]
|
|
22
|
+
*
|
|
23
|
+
* Job lifecycle:
|
|
24
|
+
* enqueued (status='pending')
|
|
25
|
+
* ↓ availableAt reached + consumer leases
|
|
26
|
+
* inflight (status='inflight', lease expires after leaseDurationMs)
|
|
27
|
+
* ↓ handler returns ↓ handler throws
|
|
28
|
+
* done (status='done') if attempts < maxAttempts:
|
|
29
|
+
* pending (with backoff)
|
|
30
|
+
* else:
|
|
31
|
+
* failed (status='failed')
|
|
32
|
+
*/
|
|
33
|
+
var C = require("./constants");
|
|
34
|
+
var localProto = require("./queue-local");
|
|
35
|
+
var retryHelper = require("./retry");
|
|
36
|
+
var safeAsync = require("./safe-async");
|
|
37
|
+
var lazyRequire = require("./lazy-require");
|
|
38
|
+
var observability = require("./observability");
|
|
39
|
+
var protocolDispatcher = require("./protocol-dispatcher");
|
|
40
|
+
var { QueueError } = require("./framework-error");
|
|
41
|
+
|
|
42
|
+
var dispatcher = protocolDispatcher.create({
|
|
43
|
+
name: "queue",
|
|
44
|
+
errorClass: QueueError,
|
|
45
|
+
protocols: { "local": localProto },
|
|
46
|
+
deferred: {
|
|
47
|
+
"redis": { description: "Redis Streams (XADD/XREADGROUP/XACK/XCLAIM)" },
|
|
48
|
+
"sqs": { description: "AWS SQS (and S3-compatible queue endpoints) via SigV4" },
|
|
49
|
+
"amqp": { description: "AMQP 0-9-1 (RabbitMQ etc.)" },
|
|
50
|
+
"nats": { description: "NATS JetStream" },
|
|
51
|
+
},
|
|
52
|
+
fallbackProtocol: "local",
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
var _err = QueueError.factory;
|
|
56
|
+
|
|
57
|
+
var audit = lazyRequire(function () { return require("./audit"); });
|
|
58
|
+
|
|
59
|
+
var initialized = false;
|
|
60
|
+
var backends = {};
|
|
61
|
+
var defaultBackend = null;
|
|
62
|
+
var consumers = []; // [{ queueName, backendName, cancel(), running, inFlight: Set }]
|
|
63
|
+
var sweepTimer = null;
|
|
64
|
+
|
|
65
|
+
function init(opts) {
|
|
66
|
+
if (initialized) return;
|
|
67
|
+
if (!opts || !opts.backends) {
|
|
68
|
+
throw _err("INVALID_CONFIG", "queue.init({ backends }) is required", true);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
backends = {};
|
|
72
|
+
for (var name in opts.backends) {
|
|
73
|
+
var cfg = opts.backends[name];
|
|
74
|
+
var proto = dispatcher.resolve(cfg.protocol);
|
|
75
|
+
var raw = proto.create(cfg);
|
|
76
|
+
var breaker = new retryHelper.CircuitBreaker(
|
|
77
|
+
"queue:" + name,
|
|
78
|
+
cfg.breaker
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
// Wrap mutating ops with retry + breaker (idempotent only — enqueue and
|
|
82
|
+
// complete are safe to retry; lease isn't because partial-double-lease
|
|
83
|
+
// is dangerous, so it goes through the breaker but not retry).
|
|
84
|
+
function wrapWithRetry(fn) {
|
|
85
|
+
return function () {
|
|
86
|
+
var args = Array.prototype.slice.call(arguments);
|
|
87
|
+
return retryHelper.withRetry(function () {
|
|
88
|
+
return breaker.wrap(function () { return fn.apply(raw, args); });
|
|
89
|
+
}, cfg.retry);
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function wrapBreakerOnly(fn) {
|
|
93
|
+
return function () {
|
|
94
|
+
var args = Array.prototype.slice.call(arguments);
|
|
95
|
+
return breaker.wrap(function () { return fn.apply(raw, args); });
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
backends[name] = {
|
|
100
|
+
name: name,
|
|
101
|
+
protocol: cfg.protocol,
|
|
102
|
+
breaker: breaker,
|
|
103
|
+
raw: raw,
|
|
104
|
+
enqueue: wrapWithRetry(raw.enqueue),
|
|
105
|
+
lease: wrapBreakerOnly(raw.lease),
|
|
106
|
+
extendLease: raw.extendLease ? wrapWithRetry(raw.extendLease) : null,
|
|
107
|
+
complete: wrapWithRetry(raw.complete),
|
|
108
|
+
fail: wrapWithRetry(raw.fail),
|
|
109
|
+
sweepExpired: raw.sweepExpired ? wrapBreakerOnly(raw.sweepExpired) : null,
|
|
110
|
+
size: wrapWithRetry(raw.size),
|
|
111
|
+
purge: wrapWithRetry(raw.purge),
|
|
112
|
+
dlqList: raw.dlqList ? wrapWithRetry(raw.dlqList) : null,
|
|
113
|
+
dlqRetry: raw.dlqRetry ? wrapWithRetry(raw.dlqRetry) : null,
|
|
114
|
+
dlqSize: raw.dlqSize ? wrapWithRetry(raw.dlqSize) : null,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
defaultBackend = opts.defaultBackend || Object.keys(backends)[0];
|
|
119
|
+
|
|
120
|
+
// Sweep expired leases periodically (every 30s) so crashed-handler jobs
|
|
121
|
+
// get re-pended.
|
|
122
|
+
sweepTimer = setInterval(function () {
|
|
123
|
+
Object.keys(backends).forEach(function (n) {
|
|
124
|
+
if (backends[n].sweepExpired) {
|
|
125
|
+
backends[n].sweepExpired().catch(function () { /* best effort */ });
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}, 30000);
|
|
129
|
+
sweepTimer.unref();
|
|
130
|
+
|
|
131
|
+
initialized = true;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function _backendFor(opts) {
|
|
135
|
+
opts = opts || {};
|
|
136
|
+
var name = opts.backend || defaultBackend;
|
|
137
|
+
var b = backends[name];
|
|
138
|
+
if (!b) throw _err("UNKNOWN_BACKEND", "no backend named '" + name + "'", true);
|
|
139
|
+
return b;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---- Public API ----
|
|
143
|
+
|
|
144
|
+
function enqueue(queueName, payload, opts) {
|
|
145
|
+
_requireInit();
|
|
146
|
+
if (!queueName) throw _err("MISSING_QUEUE", "enqueue requires queueName", true);
|
|
147
|
+
opts = opts || {};
|
|
148
|
+
var b = _backendFor(opts);
|
|
149
|
+
return observability.tap("queue.enqueue",
|
|
150
|
+
{ queueName: queueName, backend: b.name },
|
|
151
|
+
function () {
|
|
152
|
+
return b.enqueue(queueName, payload, opts).then(function (result) {
|
|
153
|
+
_emit("system.queue.enqueue", {
|
|
154
|
+
metadata: {
|
|
155
|
+
queue: queueName,
|
|
156
|
+
backend: b.name,
|
|
157
|
+
jobId: result.jobId,
|
|
158
|
+
classification: result.classification,
|
|
159
|
+
traceId: opts.traceId,
|
|
160
|
+
delaySeconds: opts.delaySeconds || 0,
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
return result;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function consume(queueName, handler, opts) {
|
|
170
|
+
_requireInit();
|
|
171
|
+
if (!queueName) throw _err("MISSING_QUEUE", "consume requires queueName", true);
|
|
172
|
+
if (typeof handler !== "function") throw _err("INVALID_HANDLER", "handler must be a function", true);
|
|
173
|
+
opts = opts || {};
|
|
174
|
+
var b = _backendFor(opts);
|
|
175
|
+
var concurrency = opts.concurrency || 1;
|
|
176
|
+
var leaseDurationMs = opts.leaseDurationMs || 30000;
|
|
177
|
+
var pollIntervalMs = opts.pollIntervalMs || 1000;
|
|
178
|
+
var fastPollMs = opts.fastPollMs || 50;
|
|
179
|
+
|
|
180
|
+
// Each consumer has its own AbortController so cancel() unblocks any
|
|
181
|
+
// in-flight poll-sleep immediately rather than waiting up to
|
|
182
|
+
// pollIntervalMs (default 1s) for the next while-loop iteration.
|
|
183
|
+
var abortCtrl = new AbortController();
|
|
184
|
+
var state = {
|
|
185
|
+
queueName: queueName,
|
|
186
|
+
backendName: b.name,
|
|
187
|
+
cancelled: false,
|
|
188
|
+
inFlight: new Set(),
|
|
189
|
+
abortCtrl: abortCtrl,
|
|
190
|
+
cancel: function () {
|
|
191
|
+
state.cancelled = true;
|
|
192
|
+
try { abortCtrl.abort(); } catch (_e) {}
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
consumers.push(state);
|
|
196
|
+
|
|
197
|
+
(async function loop() {
|
|
198
|
+
// Helper — sleep with cancellation. On abort, returns instead of
|
|
199
|
+
// rejecting so the next while-iteration sees `state.cancelled` and
|
|
200
|
+
// exits cleanly.
|
|
201
|
+
async function _pollSleep(ms) {
|
|
202
|
+
try { await safeAsync.sleep(ms, { signal: abortCtrl.signal }); }
|
|
203
|
+
catch (_e) { /* aborted — loop condition will catch it */ }
|
|
204
|
+
}
|
|
205
|
+
while (!state.cancelled) {
|
|
206
|
+
// Don't lease more than (concurrency - inFlight) at a time
|
|
207
|
+
var slots = concurrency - state.inFlight.size;
|
|
208
|
+
if (slots <= 0) {
|
|
209
|
+
await _pollSleep(fastPollMs);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
var jobs;
|
|
213
|
+
try { jobs = await b.lease(queueName, leaseDurationMs, slots); }
|
|
214
|
+
catch {
|
|
215
|
+
// Backend down (breaker open, etc.) — back off
|
|
216
|
+
await _pollSleep(pollIntervalMs);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (!jobs || jobs.length === 0) {
|
|
220
|
+
await _pollSleep(pollIntervalMs);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
for (var i = 0; i < jobs.length; i++) {
|
|
224
|
+
observability.event("queue.lease", 1, { queueName: queueName });
|
|
225
|
+
(function (job) {
|
|
226
|
+
state.inFlight.add(job.jobId);
|
|
227
|
+
_emit("system.queue.consume.start", {
|
|
228
|
+
metadata: { queue: queueName, backend: b.name, jobId: job.jobId, attempt: job.attempts, traceId: job.traceId },
|
|
229
|
+
});
|
|
230
|
+
// Handler context — second arg to handler. Carries
|
|
231
|
+
// ctx.extendLease(ms) for long-running handlers that need to
|
|
232
|
+
// bump their own lease before the sweeper reclaims the job.
|
|
233
|
+
var ctx = {
|
|
234
|
+
extendLease: function (additionalMs) {
|
|
235
|
+
if (typeof b.extendLease !== "function") {
|
|
236
|
+
throw _err("EXTEND_LEASE_UNSUPPORTED",
|
|
237
|
+
"queue backend '" + b.name + "' does not support extendLease",
|
|
238
|
+
true);
|
|
239
|
+
}
|
|
240
|
+
return b.extendLease(job.jobId, additionalMs).then(function (ok) {
|
|
241
|
+
if (ok) {
|
|
242
|
+
_emit("system.queue.lease.extended", {
|
|
243
|
+
metadata: { queue: queueName, backend: b.name, jobId: job.jobId, additionalMs: additionalMs },
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return ok;
|
|
247
|
+
});
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
observability.tap("queue.consume",
|
|
251
|
+
{ queueName: queueName, backend: b.name, jobId: job.jobId, attempt: job.attempts },
|
|
252
|
+
function () {
|
|
253
|
+
return Promise.resolve()
|
|
254
|
+
.then(function () { return handler(job, ctx); })
|
|
255
|
+
.then(function () {
|
|
256
|
+
return b.complete(job.jobId).then(function () {
|
|
257
|
+
_emit("system.queue.consume.success", {
|
|
258
|
+
metadata: { queue: queueName, backend: b.name, jobId: job.jobId, attempt: job.attempts, traceId: job.traceId },
|
|
259
|
+
});
|
|
260
|
+
observability.event("queue.complete", 1, { queueName: queueName });
|
|
261
|
+
});
|
|
262
|
+
}, function (err) {
|
|
263
|
+
var msg = (err && err.message) || String(err);
|
|
264
|
+
var willRetry = job.attempts < job.maxAttempts;
|
|
265
|
+
return b.fail(job.jobId, msg, { retryDelayMs: _backoffDelay(job.attempts) })
|
|
266
|
+
.then(function () {
|
|
267
|
+
observability.event("queue.fail", 1, { queueName: queueName, willRetry: willRetry });
|
|
268
|
+
_emit("system.queue.consume.failure", {
|
|
269
|
+
metadata: {
|
|
270
|
+
queue: queueName, backend: b.name, jobId: job.jobId,
|
|
271
|
+
attempt: job.attempts, traceId: job.traceId,
|
|
272
|
+
maxAttempts: job.maxAttempts, willRetry: willRetry,
|
|
273
|
+
},
|
|
274
|
+
reason: msg,
|
|
275
|
+
outcome: "failure",
|
|
276
|
+
});
|
|
277
|
+
// DLQ-write event when the job has exhausted its retries.
|
|
278
|
+
// Operators wire this to their alerting / dashboards
|
|
279
|
+
// — failed-after-retries is "needs human review" not
|
|
280
|
+
// "in the normal flow." Audit chain captures the
|
|
281
|
+
// final state for forensics.
|
|
282
|
+
if (!willRetry) {
|
|
283
|
+
_emit("system.queue.dlq.write", {
|
|
284
|
+
metadata: {
|
|
285
|
+
queue: queueName, backend: b.name, jobId: job.jobId,
|
|
286
|
+
attempts: job.attempts, traceId: job.traceId,
|
|
287
|
+
},
|
|
288
|
+
reason: msg,
|
|
289
|
+
outcome: "failure",
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
})
|
|
294
|
+
.catch(function (_e) { /* lifecycle errors swallowed — operator sees via audit */ })
|
|
295
|
+
.then(function () { state.inFlight.delete(job.jobId); });
|
|
296
|
+
}
|
|
297
|
+
);
|
|
298
|
+
})(jobs[i]);
|
|
299
|
+
}
|
|
300
|
+
await _pollSleep(fastPollMs);
|
|
301
|
+
}
|
|
302
|
+
})();
|
|
303
|
+
|
|
304
|
+
return state;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
var _QUEUE_BACKOFF_OPTS = {
|
|
308
|
+
baseDelayMs: C.TIME.seconds(1),
|
|
309
|
+
maxDelayMs: C.TIME.minutes(5),
|
|
310
|
+
jitterFactor: 0, // queue uses deterministic backoff (no jitter) for predictability
|
|
311
|
+
};
|
|
312
|
+
function _backoffDelay(attempt) {
|
|
313
|
+
return retryHelper.backoffDelay(attempt, _QUEUE_BACKOFF_OPTS);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function size(queueName, opts) {
|
|
317
|
+
_requireInit();
|
|
318
|
+
return _backendFor(opts).size(queueName);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function purge(queueName, opts) {
|
|
322
|
+
_requireInit();
|
|
323
|
+
var b = _backendFor(opts);
|
|
324
|
+
return b.purge(queueName).then(function (n) {
|
|
325
|
+
_emit("system.queue.purge", {
|
|
326
|
+
metadata: { queue: queueName, backend: b.name, deleted: n },
|
|
327
|
+
});
|
|
328
|
+
return n;
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---- Dead-letter queue ----
|
|
333
|
+
//
|
|
334
|
+
// `dlqList` returns failed-after-retries jobs for operator review;
|
|
335
|
+
// `dlqRetry` resets a single job back to 'pending' so it gets picked
|
|
336
|
+
// up by consumers again (operator-driven — never automatic).
|
|
337
|
+
|
|
338
|
+
function dlqList(queueName, opts) {
|
|
339
|
+
_requireInit();
|
|
340
|
+
var b = _backendFor(opts);
|
|
341
|
+
if (typeof b.dlqList !== "function") {
|
|
342
|
+
return Promise.reject(_err("DLQ_UNSUPPORTED",
|
|
343
|
+
"queue backend '" + b.name + "' does not support dlqList", true));
|
|
344
|
+
}
|
|
345
|
+
return b.dlqList(queueName, opts);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function dlqRetry(jobId, opts) {
|
|
349
|
+
_requireInit();
|
|
350
|
+
var b = _backendFor(opts);
|
|
351
|
+
if (typeof b.dlqRetry !== "function") {
|
|
352
|
+
return Promise.reject(_err("DLQ_UNSUPPORTED",
|
|
353
|
+
"queue backend '" + b.name + "' does not support dlqRetry", true));
|
|
354
|
+
}
|
|
355
|
+
return b.dlqRetry(jobId).then(function (ok) {
|
|
356
|
+
if (ok) {
|
|
357
|
+
_emit("system.queue.dlq.retry", {
|
|
358
|
+
metadata: { jobId: jobId, backend: b.name },
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
return ok;
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function dlqSize(queueName, opts) {
|
|
366
|
+
_requireInit();
|
|
367
|
+
var b = _backendFor(opts);
|
|
368
|
+
if (typeof b.dlqSize !== "function") {
|
|
369
|
+
return Promise.reject(_err("DLQ_UNSUPPORTED",
|
|
370
|
+
"queue backend '" + b.name + "' does not support dlqSize", true));
|
|
371
|
+
}
|
|
372
|
+
return b.dlqSize(queueName);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function shutdown(opts) {
|
|
376
|
+
if (!initialized) return;
|
|
377
|
+
opts = opts || {};
|
|
378
|
+
var timeoutMs = opts.timeoutMs != null ? opts.timeoutMs : C.TIME.seconds(30);
|
|
379
|
+
// Signal all consumers to stop
|
|
380
|
+
consumers.forEach(function (c) { c.cancel(); });
|
|
381
|
+
// Wait for in-flight handlers to complete
|
|
382
|
+
var deadline = Date.now() + timeoutMs;
|
|
383
|
+
while (consumers.some(function (c) { return c.inFlight.size > 0; })) {
|
|
384
|
+
if (Date.now() > deadline) break;
|
|
385
|
+
await safeAsync.sleep(50);
|
|
386
|
+
}
|
|
387
|
+
consumers = [];
|
|
388
|
+
if (sweepTimer) { clearInterval(sweepTimer); sweepTimer = null; }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function listBackends() {
|
|
392
|
+
_requireInit();
|
|
393
|
+
return Object.keys(backends).map(function (name) {
|
|
394
|
+
return { name: name, protocol: backends[name].protocol, breakerState: backends[name].breaker.getState() };
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function _emit(action, info) {
|
|
399
|
+
audit().safeEmit({ action: action, ...(info || {}) });
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function _requireInit() {
|
|
403
|
+
if (!initialized) throw _err("NOT_INITIALIZED", "queue.init() must be called first", true);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function _resetForTest() {
|
|
407
|
+
if (sweepTimer) { clearInterval(sweepTimer); sweepTimer = null; }
|
|
408
|
+
consumers.forEach(function (c) { c.cancel(); });
|
|
409
|
+
consumers = [];
|
|
410
|
+
backends = {};
|
|
411
|
+
defaultBackend = null;
|
|
412
|
+
initialized = false;
|
|
413
|
+
audit.reset();
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
module.exports = {
|
|
417
|
+
init: init,
|
|
418
|
+
enqueue: enqueue,
|
|
419
|
+
consume: consume,
|
|
420
|
+
size: size,
|
|
421
|
+
purge: purge,
|
|
422
|
+
shutdown: shutdown,
|
|
423
|
+
listBackends: listBackends,
|
|
424
|
+
dlqList: dlqList,
|
|
425
|
+
dlqRetry: dlqRetry,
|
|
426
|
+
dlqSize: dlqSize,
|
|
427
|
+
PROTOCOLS: dispatcher.protocols,
|
|
428
|
+
DEFERRED_PROTOCOLS: dispatcher.deferred,
|
|
429
|
+
_resetForTest: _resetForTest,
|
|
430
|
+
};
|
package/lib/redact.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Operational-log redaction layer.
|
|
4
|
+
*
|
|
5
|
+
* Wraps every operational log emit so PHI / PCI / personal data never
|
|
6
|
+
* reaches a debug sink, file, or external SIEM. Two complementary signals:
|
|
7
|
+
*
|
|
8
|
+
* 1. Field-name allow/deny: known sensitive fields are scrubbed by name
|
|
9
|
+
* regardless of the value's contents.
|
|
10
|
+
* 2. Pattern detection: even if a field name slips past, common-shape
|
|
11
|
+
* detectors (credit-card via Luhn, JWT, PEM blocks, AWS-key-shape)
|
|
12
|
+
* catch the value and replace with a marker.
|
|
13
|
+
*
|
|
14
|
+
* The redactor returns a NEW object — the original log payload is never
|
|
15
|
+
* mutated. This matters because the same object may be passed to the
|
|
16
|
+
* audit-log path (which DOES seal sensitive content via vault) AND the
|
|
17
|
+
* operational path (which redacts) in the same call.
|
|
18
|
+
*
|
|
19
|
+
* Public API:
|
|
20
|
+
* redact.redact(value, opts?) → redacted value
|
|
21
|
+
* redact.registerFieldRule(pattern, replacement)
|
|
22
|
+
* redact.registerValueDetector(name, fn, replacement)
|
|
23
|
+
* redact.MARKER → '[REDACTED]'
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
var DEFAULT_MARKER = "[REDACTED]";
|
|
27
|
+
|
|
28
|
+
// Field names that are always redacted, regardless of value contents.
|
|
29
|
+
// Match is case-insensitive and includes substring (so 'userPassword' matches).
|
|
30
|
+
var SENSITIVE_FIELDS = [
|
|
31
|
+
"password", "passwd", "secret", "token", "apikey", "api_key",
|
|
32
|
+
"authorization", "auth", "ssn", "creditcard", "credit_card",
|
|
33
|
+
"card_number", "cardnumber", "cvc", "cvv", "pin",
|
|
34
|
+
"privatekey", "private_key", "passphrase", "session", "sid",
|
|
35
|
+
"_authtoken", "auth_token", "bearer", "cookie",
|
|
36
|
+
// Vault-sealed values (don't log even though they're encrypted —
|
|
37
|
+
// operational logs aren't a place to leak ciphertext shape either)
|
|
38
|
+
// matched separately by value detector below
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
// Value-shape detectors. Each takes a string, returns true if the value
|
|
42
|
+
// matches the pattern. Used as a fallback when field-name redaction misses.
|
|
43
|
+
function _luhnCheck(num) {
|
|
44
|
+
var digits = num.replace(/\D/g, "");
|
|
45
|
+
if (digits.length < 13 || digits.length > 19) return false;
|
|
46
|
+
var sum = 0;
|
|
47
|
+
var alt = false;
|
|
48
|
+
for (var i = digits.length - 1; i >= 0; i--) {
|
|
49
|
+
var d = parseInt(digits.charAt(i), 10);
|
|
50
|
+
if (alt) { d *= 2; if (d > 9) d -= 9; }
|
|
51
|
+
sum += d;
|
|
52
|
+
alt = !alt;
|
|
53
|
+
}
|
|
54
|
+
return sum % 10 === 0;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
var VALUE_DETECTORS = [
|
|
58
|
+
{
|
|
59
|
+
name: "credit-card",
|
|
60
|
+
test: function (v) {
|
|
61
|
+
if (typeof v !== "string") return false;
|
|
62
|
+
var digits = v.replace(/\s|-/g, "");
|
|
63
|
+
if (!/^\d{13,19}$/.test(digits)) return false;
|
|
64
|
+
return _luhnCheck(digits);
|
|
65
|
+
},
|
|
66
|
+
replacement: "[REDACTED-CC]",
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: "jwt",
|
|
70
|
+
test: function (v) {
|
|
71
|
+
return typeof v === "string" && /^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(v);
|
|
72
|
+
},
|
|
73
|
+
replacement: "[REDACTED-JWT]",
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
name: "pem",
|
|
77
|
+
test: function (v) { return typeof v === "string" && /-----BEGIN [A-Z ]+-----/.test(v); },
|
|
78
|
+
replacement: "[REDACTED-PEM]",
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: "ssh-private",
|
|
82
|
+
test: function (v) { return typeof v === "string" && /-----BEGIN OPENSSH PRIVATE KEY-----/.test(v); },
|
|
83
|
+
replacement: "[REDACTED-SSH-KEY]",
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
name: "aws-access-key",
|
|
87
|
+
test: function (v) { return typeof v === "string" && /^(AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16}$/.test(v); },
|
|
88
|
+
replacement: "[REDACTED-AWS-KEY]",
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: "vault-sealed",
|
|
92
|
+
test: function (v) { return typeof v === "string" && v.startsWith("vault:"); },
|
|
93
|
+
replacement: "[REDACTED-SEALED]",
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
name: "ssn",
|
|
97
|
+
test: function (v) { return typeof v === "string" && /^\d{3}-?\d{2}-?\d{4}$/.test(v); },
|
|
98
|
+
replacement: "[REDACTED-SSN]",
|
|
99
|
+
},
|
|
100
|
+
];
|
|
101
|
+
|
|
102
|
+
var sensitiveFieldsSet = new Set(SENSITIVE_FIELDS);
|
|
103
|
+
var customDetectors = [];
|
|
104
|
+
|
|
105
|
+
function registerFieldRule(name, replacement) {
|
|
106
|
+
void replacement; // marker not used here; redact replaces with marker
|
|
107
|
+
if (typeof name === "string") {
|
|
108
|
+
sensitiveFieldsSet.add(name.toLowerCase());
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
throw new Error("registerFieldRule expects a string field name");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function registerValueDetector(name, testFn, replacement) {
|
|
115
|
+
if (typeof testFn !== "function") {
|
|
116
|
+
throw new Error("registerValueDetector requires a test function");
|
|
117
|
+
}
|
|
118
|
+
customDetectors.push({ name: name, test: testFn, replacement: replacement || DEFAULT_MARKER });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function _isSensitiveFieldName(key) {
|
|
122
|
+
if (typeof key !== "string") return false;
|
|
123
|
+
var lk = key.toLowerCase();
|
|
124
|
+
if (sensitiveFieldsSet.has(lk)) return true;
|
|
125
|
+
// Substring match: 'userPassword' contains 'password'
|
|
126
|
+
for (var s of sensitiveFieldsSet) {
|
|
127
|
+
if (lk.indexOf(s) !== -1) return true;
|
|
128
|
+
}
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function _redactValue(value) {
|
|
133
|
+
if (typeof value !== "string") return value;
|
|
134
|
+
var allDetectors = VALUE_DETECTORS.concat(customDetectors);
|
|
135
|
+
for (var i = 0; i < allDetectors.length; i++) {
|
|
136
|
+
if (allDetectors[i].test(value)) return allDetectors[i].replacement;
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function redact(value, opts) {
|
|
142
|
+
opts = opts || {};
|
|
143
|
+
var marker = opts.marker || DEFAULT_MARKER;
|
|
144
|
+
var maxDepth = opts.maxDepth || 50;
|
|
145
|
+
return _redact(value, 0, maxDepth, marker, opts.parentKey || null);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function _redact(value, depth, maxDepth, marker, parentKey) {
|
|
149
|
+
if (depth > maxDepth) return marker;
|
|
150
|
+
if (value === null || value === undefined) return value;
|
|
151
|
+
if (typeof value === "string") {
|
|
152
|
+
if (parentKey && _isSensitiveFieldName(parentKey)) return marker;
|
|
153
|
+
return _redactValue(value);
|
|
154
|
+
}
|
|
155
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
156
|
+
if (parentKey && _isSensitiveFieldName(parentKey)) return marker;
|
|
157
|
+
return value;
|
|
158
|
+
}
|
|
159
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
|
|
160
|
+
return marker; // never log raw binary
|
|
161
|
+
}
|
|
162
|
+
if (Array.isArray(value)) {
|
|
163
|
+
return value.map(function (v) { return _redact(v, depth + 1, maxDepth, marker, null); });
|
|
164
|
+
}
|
|
165
|
+
if (typeof value === "object") {
|
|
166
|
+
var out = {};
|
|
167
|
+
for (var k in value) {
|
|
168
|
+
if (!Object.prototype.hasOwnProperty.call(value, k)) continue;
|
|
169
|
+
if (_isSensitiveFieldName(k)) {
|
|
170
|
+
out[k] = marker;
|
|
171
|
+
} else {
|
|
172
|
+
out[k] = _redact(value[k], depth + 1, maxDepth, marker, k);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
return value;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function _resetForTest() {
|
|
181
|
+
sensitiveFieldsSet = new Set(SENSITIVE_FIELDS);
|
|
182
|
+
customDetectors = [];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
module.exports = {
|
|
186
|
+
redact: redact,
|
|
187
|
+
registerFieldRule: registerFieldRule,
|
|
188
|
+
registerValueDetector: registerValueDetector,
|
|
189
|
+
MARKER: DEFAULT_MARKER,
|
|
190
|
+
SENSITIVE_FIELDS: SENSITIVE_FIELDS,
|
|
191
|
+
_resetForTest: _resetForTest,
|
|
192
|
+
};
|