@imqueue/core 3.4.3 → 3.5.0
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/AGENTS.md +31 -4
- package/CHANGELOG.md +109 -31
- package/README.md +150 -0
- package/SECURITY.md +28 -0
- package/index.d.ts +3 -2
- package/index.js +3 -2
- package/package.json +5 -4
- package/src/ClusteredRedisQueue.js +7 -0
- package/src/IMessageQueue.d.ts +42 -5
- package/src/RedisQueue.d.ts +55 -16
- package/src/RedisQueue.js +115 -27
- package/src/helpers/envTls.d.ts +31 -0
- package/src/helpers/envTls.js +158 -0
- package/src/helpers/index.d.ts +2 -0
- package/src/helpers/index.js +2 -0
- package/src/helpers/tlsFingerprint.d.ts +15 -0
- package/src/helpers/tlsFingerprint.js +88 -0
- package/src/index.d.ts +2 -0
- package/src/index.js +2 -0
- package/src/redis.d.ts +6 -0
package/AGENTS.md
CHANGED
|
@@ -38,7 +38,8 @@ Redis blocking list moves and keyspace notifications.
|
|
|
38
38
|
```bash
|
|
39
39
|
npm install
|
|
40
40
|
npm run build # clean-compiled + tsc (emits alongside sources)
|
|
41
|
-
npm test # build + node:test over
|
|
41
|
+
npm test # build + node:test over test/unit/**/*.spec.js (mocked)
|
|
42
|
+
npm run test-integration # build + test/integration/**/*.spec.js (real redis)
|
|
42
43
|
npm run lint # oxlint
|
|
43
44
|
npm run format # oxfmt (write) | npm run format:check (verify)
|
|
44
45
|
npm run test-coverage # tests + experimental coverage summary
|
|
@@ -46,10 +47,36 @@ npm run test-lcov # writes coverage/lcov.info
|
|
|
46
47
|
npm run benchmark # message-throughput benchmark (see below)
|
|
47
48
|
```
|
|
48
49
|
|
|
49
|
-
|
|
50
|
-
`--experimental-test-module-mocks` and preload `./test/mocks/index.js`;
|
|
50
|
+
Unit specs live in `test/unit/` and use the native `node:test` runner with
|
|
51
|
+
`--experimental-test-module-mocks` and a preload of `./test/mocks/index.js`;
|
|
51
52
|
timeout is 15s per test. Run a single spec after a build with
|
|
52
|
-
`node --experimental-test-module-mocks --import ./test/mocks/index.js --test test/
|
|
53
|
+
`node --experimental-test-module-mocks --import ./test/mocks/index.js --test test/unit/RedisQueue.spec.js`.
|
|
54
|
+
|
|
55
|
+
`npm test` deliberately globs `test/unit` rather than `test`: the integration
|
|
56
|
+
specs must not run under a preload that replaces `ioredis` wholesale. Keep that
|
|
57
|
+
glob scoped when adding runners.
|
|
58
|
+
|
|
59
|
+
**The unit specs never open a socket** — `test/mocks/redis.ts` replaces
|
|
60
|
+
`ioredis` wholesale. That is fine for everything except the TLS option, whose
|
|
61
|
+
entire point is what happens during a handshake the mock does not perform.
|
|
62
|
+
`test/integration/` covers that against a real broker, and anything touching
|
|
63
|
+
`tls`, the connection literal in `RedisQueue.connect()`, the pool key or
|
|
64
|
+
connection teardown must be checked with `npm run test-integration` as well as
|
|
65
|
+
`npm test`.
|
|
66
|
+
|
|
67
|
+
`test/integration/tlsBroker.ts` issues a throwaway CA, server and client
|
|
68
|
+
certificate with `openssl`, then starts `redis-server` on a port picked at run
|
|
69
|
+
time with `--port 0 --tls-port <n>`. `--port 0` is the part that matters: with
|
|
70
|
+
no plaintext listener at all, a queue that reaches the broker has demonstrably
|
|
71
|
+
done so over TLS. It is started twice, once with `--tls-auth-clients no` and
|
|
72
|
+
once with `yes`, so both server-authenticated and mutual TLS are exercised.
|
|
73
|
+
|
|
74
|
+
**The integration specs skip, never fail, when the machine cannot host a
|
|
75
|
+
broker.** `startTlsBroker()` returns a reason string instead of throwing when
|
|
76
|
+
`redis-server` or `openssl` is missing, or when redis will not start with TLS
|
|
77
|
+
enabled, and that reason becomes the suite's `skip`. CI has no redis and must
|
|
78
|
+
stay green, so keep that contract: report a skip reason, do not throw, and do
|
|
79
|
+
not add these specs to a runner that CI invokes.
|
|
53
80
|
|
|
54
81
|
## Layout
|
|
55
82
|
|
package/CHANGELOG.md
CHANGED
|
@@ -11,40 +11,70 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
11
11
|
|
|
12
12
|
## [Unreleased]
|
|
13
13
|
|
|
14
|
-
###
|
|
15
|
-
|
|
16
|
-
- **`safeDelivery` lost a message when a worker died mid-handler.** It released
|
|
17
|
-
the message's worker key the instant the message was dispatched to the
|
|
18
|
-
`message` listener, so a worker killed while its handler was still running
|
|
19
|
-
took that message with it and nothing brought it back — the option guaranteed
|
|
20
|
-
the hand-off while its name and documentation promised guaranteed delivery.
|
|
21
|
-
The key is now held until the listener has finished with the message.
|
|
22
|
-
|
|
23
|
-
**A listener says it has finished by what it returns.** Return a promise and
|
|
24
|
-
the message stays checked out until it settles; return anything else and it is
|
|
25
|
-
released as the listener returns. Every registered listener is consulted, and
|
|
26
|
-
the message is released once all the promises they returned have settled —
|
|
27
|
-
settled, not fulfilled, because a handler that threw has still had its turn
|
|
28
|
-
and re-delivering on a rejection would retry a poison message forever.
|
|
29
|
-
|
|
30
|
-
Nothing needs changing to get this: a listener that already returns a promise
|
|
31
|
-
— as `@imqueue/rpc` and `@imqueue/job` both do — is covered as it stands, and
|
|
32
|
-
a synchronous listener behaves exactly as it did.
|
|
33
|
-
|
|
34
|
-
A message that cannot be unpacked releases its lease rather than coming back
|
|
35
|
-
on every sweep.
|
|
14
|
+
### Added
|
|
36
15
|
|
|
37
|
-
- **
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
16
|
+
- **TLS on connections to the redis broker.** A new `tls` option encrypts every
|
|
17
|
+
connection a queue opens — reader, writer, watcher and subscription alike.
|
|
18
|
+
Pass `true` for Node's defaults, or an object handed to `tls.connect()` as
|
|
19
|
+
given, so a private CA (`ca`) and mutual TLS (`cert`/`key`) both work. The
|
|
20
|
+
option was previously accepted by the type system and dropped on the way to
|
|
21
|
+
the client, which meant the bus could not be encrypted at all.
|
|
22
|
+
|
|
23
|
+
Cluster entries may carry their own `tls`, overriding the cluster-wide one
|
|
24
|
+
for that server alone; an entry that omits it falls back to the top level.
|
|
25
|
+
Per-entry `username` and `password` are still ignored, exactly as before —
|
|
26
|
+
honouring them would change what an existing cluster authenticates with, and
|
|
27
|
+
that has nothing to do with this feature.
|
|
28
|
+
|
|
29
|
+
With `tls` left unset the environment is consulted — `IMQ_REDIS_TLS`,
|
|
30
|
+
`IMQ_REDIS_TLS_CA_FILE`, `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE`,
|
|
31
|
+
`IMQ_REDIS_TLS_KEY_PASSPHRASE`, `IMQ_REDIS_TLS_SERVERNAME` and
|
|
32
|
+
`IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` — so a deployment can encrypt a fleet
|
|
33
|
+
without a code change. Certificate files are read as the queue is
|
|
34
|
+
constructed, and an unreadable one throws: an unmounted secret stops the
|
|
35
|
+
process rather than leaving it talking to the broker in the clear. Passing
|
|
36
|
+
`tls` explicitly always wins, `tls: false` included, and
|
|
37
|
+
`rejectUnauthorized: false` is warned about because it leaves a connection
|
|
38
|
+
encrypted but unauthenticated.
|
|
39
|
+
|
|
40
|
+
This covers the queue's own connections. `UDPClusterManager` announcements
|
|
41
|
+
remain unauthenticated UDP broadcast and are unaffected.
|
|
42
|
+
|
|
43
|
+
- **Integration specs covering TLS against a real broker**, in
|
|
44
|
+
`test/integration/`, run by `npm run test-integration`. They stand up a
|
|
45
|
+
throwaway TLS-only redis and assert what a mocked `ioredis` cannot: that the
|
|
46
|
+
handshake completes and is verified, that a message crosses it, that the
|
|
47
|
+
connection pool keeps differing TLS configurations apart, and that plaintext,
|
|
48
|
+
an unverifiable certificate and a wrong server name are all refused rather
|
|
49
|
+
than downgraded. They skip themselves, with a reason, wherever
|
|
50
|
+
`redis-server` and `openssl` are not both available, so a checkout without
|
|
51
|
+
redis still passes. `npm test` now globs `test/unit` and does not run them.
|
|
45
52
|
|
|
46
53
|
### Changed
|
|
47
54
|
|
|
55
|
+
- **Nothing changes for a queue that does not use TLS.** The option is absent
|
|
56
|
+
from `options` unless it was configured, the connection pool key stays the
|
|
57
|
+
plain `host:port`, the redis client is handed no `tls` option, and no new
|
|
58
|
+
warning is emitted. The only added work on that path is one environment
|
|
59
|
+
lookup per queue construction, about a microsecond, and nothing at all per
|
|
60
|
+
message. This is covered by its own group of specs rather than left as a
|
|
61
|
+
claim.
|
|
62
|
+
|
|
63
|
+
- **A connection failure no longer takes the process down during teardown.**
|
|
64
|
+
This is a behaviour change for everyone, not only TLS users: a socket that
|
|
65
|
+
reported a second failure after the one that closed it used to reach an
|
|
66
|
+
`error` with no listener and terminate the process. Such a process now stays
|
|
67
|
+
up, and the failure is still logged and emitted as it always was. Nothing
|
|
68
|
+
that previously succeeded behaves differently; a crash becomes a log line.
|
|
69
|
+
|
|
70
|
+
- **Shared writer and watcher connections are now keyed by TLS configuration as
|
|
71
|
+
well as by `host:port`.** These connections are shared per server within a
|
|
72
|
+
process; queues reaching one server under different TLS configurations now get
|
|
73
|
+
separate connections, so a queue that asked for encryption can never be handed
|
|
74
|
+
a plaintext socket another queue opened first, nor the reverse. Configurations
|
|
75
|
+
equal by value still share, and the public `redisKey` still reports the plain
|
|
76
|
+
`host:port` address.
|
|
77
|
+
|
|
48
78
|
- **`safeDeliveryTtl` is now the longest a message may be worked on**, and its
|
|
49
79
|
default moves from `5000` to `300000`. It used to be a hand-off recovery
|
|
50
80
|
deadline, which meant it bounded nothing that mattered: the key was deleted at
|
|
@@ -75,7 +105,55 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
75
105
|
wait would hand a message a sizeable part of its budget already spent. At the
|
|
76
106
|
old defaults both of these resolve to exactly what they were.
|
|
77
107
|
|
|
78
|
-
-
|
|
108
|
+
- The safe-delivery changes above alter meanings and defaults only —
|
|
109
|
+
`safeDelivery`, `safeDeliveryTtl` and `watcherCheckDelay` are the same three
|
|
110
|
+
options they were.
|
|
111
|
+
|
|
112
|
+
### Fixed
|
|
113
|
+
|
|
114
|
+
- **A failed connection could crash the process as it was being torn down.**
|
|
115
|
+
The redis client guards its socket with a one-shot `error` listener, which
|
|
116
|
+
the failure that brings the connection down spends. A socket that goes on to
|
|
117
|
+
report a second failure — a rejected TLS handshake is answered by an alert
|
|
118
|
+
that arrives after the rejection itself — then reached a socket with nothing
|
|
119
|
+
attached, and the unhandled `error` took the process with it. The queue now
|
|
120
|
+
installs a durable listener on the socket when a connection first fails and
|
|
121
|
+
again before teardown, and `destroyChannel` no longer strips the client's
|
|
122
|
+
own `error` handler before writing its `QUIT`.
|
|
123
|
+
|
|
124
|
+
Reachable without TLS in principle, but TLS is what makes it ordinary: a
|
|
125
|
+
service started against a broker it cannot verify would reject `start()` and
|
|
126
|
+
then die inside `destroy()` rather than reporting the misconfiguration.
|
|
127
|
+
|
|
128
|
+
- **`safeDelivery` lost a message when a worker died mid-handler.** It released
|
|
129
|
+
the message's worker key the instant the message was dispatched to the
|
|
130
|
+
`message` listener, so a worker killed while its handler was still running
|
|
131
|
+
took that message with it and nothing brought it back — the option guaranteed
|
|
132
|
+
the hand-off while its name and documentation promised guaranteed delivery.
|
|
133
|
+
The key is now held until the listener has finished with the message.
|
|
134
|
+
|
|
135
|
+
**A listener says it has finished by what it returns.** Return a promise and
|
|
136
|
+
the message stays checked out until it settles; return anything else and it is
|
|
137
|
+
released as the listener returns. Every registered listener is consulted, and
|
|
138
|
+
the message is released once all the promises they returned have settled —
|
|
139
|
+
settled, not fulfilled, because a handler that threw has still had its turn
|
|
140
|
+
and re-delivering on a rejection would retry a poison message forever.
|
|
141
|
+
|
|
142
|
+
Nothing needs changing to get this: a listener that already returns a promise
|
|
143
|
+
— as `@imqueue/rpc` and `@imqueue/job` both do — is covered as it stands, and
|
|
144
|
+
a synchronous listener behaves exactly as it did.
|
|
145
|
+
|
|
146
|
+
A message that cannot be unpacked releases its lease rather than coming back
|
|
147
|
+
on every sweep.
|
|
148
|
+
|
|
149
|
+
- **A dead worker's message is recovered by asking the broker, not a clock.**
|
|
150
|
+
The worker key now carries the identity of the process that took it, and the
|
|
151
|
+
watcher reclaims it once that process has left `CLIENT LIST` — detected as
|
|
152
|
+
fast as the socket closes, and needing nothing renewed to keep a live lease
|
|
153
|
+
alive. Reconnecting workers get one sweep of grace, mirroring what the cleanup
|
|
154
|
+
pass already gave them, so a reconnect backoff does not cost a duplicate. If
|
|
155
|
+
the client list cannot be read at all, liveness is unknown and a lease is left
|
|
156
|
+
to its budget rather than guessed at.
|
|
79
157
|
|
|
80
158
|
### Keeping the old behaviour
|
|
81
159
|
|
package/README.md
CHANGED
|
@@ -38,6 +38,8 @@ With current implementation on RedisQueue:
|
|
|
38
38
|
no delays in delivery and low CPU usage on application workers. When idle,
|
|
39
39
|
it consumes no resources.
|
|
40
40
|
- **Supports Gzip compression for messages** (decreases traffic usage but is slower).
|
|
41
|
+
- **TLS on the wire**, including mutual TLS, on every connection the queue
|
|
42
|
+
opens — and switchable from the environment, without a code change.
|
|
41
43
|
- **Concurrent workers model supported**, the same queue can have multiple
|
|
42
44
|
consumers.
|
|
43
45
|
- **Delayed messages supported**, fast as ~10K of 1Kb messages per second on i7
|
|
@@ -188,6 +190,154 @@ in which in-flight work is lost — it does not close it, and `SIGKILL` on the
|
|
|
188
190
|
whole node, an OOM kill or a lost machine still take work with them — so handlers
|
|
189
191
|
must be idempotent.
|
|
190
192
|
|
|
193
|
+
# Transport encryption (TLS)
|
|
194
|
+
|
|
195
|
+
Set `tls` and every connection the queue opens — reader, writer, watcher and
|
|
196
|
+
subscription alike — is encrypted. `true` connects with Node's defaults,
|
|
197
|
+
verifying the broker against the system trust store; an object is handed to
|
|
198
|
+
`tls.connect()` as given:
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
import { readFileSync } from 'node:fs';
|
|
202
|
+
|
|
203
|
+
const queue = IMQ.create('Orders', {
|
|
204
|
+
host: 'redis.internal',
|
|
205
|
+
port: 6380,
|
|
206
|
+
password: process.env.REDIS_PASSWORD,
|
|
207
|
+
tls: {
|
|
208
|
+
ca: readFileSync('/etc/redis-tls/ca.crt'), // a private CA
|
|
209
|
+
cert: readFileSync('/etc/redis-tls/client.crt'), // mutual TLS,
|
|
210
|
+
key: readFileSync('/etc/redis-tls/client.key'), // if the broker
|
|
211
|
+
}, // asks for it
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
The broker has to be listening for TLS — `tls-port 6380` and a server
|
|
216
|
+
certificate, plus `tls-auth-clients yes` if you are using client certificates.
|
|
217
|
+
A server that is not will refuse the handshake, and the queue reports the
|
|
218
|
+
failure rather than falling back to plaintext: there is no downgrade path.
|
|
219
|
+
|
|
220
|
+
| option | default | meaning |
|
|
221
|
+
|---|---|---|
|
|
222
|
+
| `tls` | `undefined` | `true` for Node's defaults, an object for `tls.connect()`, `false` to force plaintext |
|
|
223
|
+
|
|
224
|
+
## Turning it on without a code change
|
|
225
|
+
|
|
226
|
+
With `tls` left unset, the environment is consulted, so a deployment can encrypt
|
|
227
|
+
a fleet it does not want to edit:
|
|
228
|
+
|
|
229
|
+
| variable | meaning |
|
|
230
|
+
|---|---|
|
|
231
|
+
| `IMQ_REDIS_TLS` | `1` enables TLS with default verification; `0` forces plaintext and wins over everything below |
|
|
232
|
+
| `IMQ_REDIS_TLS_CA_FILE` | PEM bundle to verify the broker against — implies `IMQ_REDIS_TLS=1` |
|
|
233
|
+
| `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE` | client certificate and key for mutual TLS — imply `IMQ_REDIS_TLS=1` |
|
|
234
|
+
| `IMQ_REDIS_TLS_KEY_PASSPHRASE` | passphrase of an encrypted private key |
|
|
235
|
+
| `IMQ_REDIS_TLS_SERVERNAME` | expected certificate name, when it is not the host you connect to |
|
|
236
|
+
| `IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` | `0` accepts an unverified certificate — see the warning below |
|
|
237
|
+
|
|
238
|
+
Passing `tls` explicitly always wins, `tls: false` included. The certificate
|
|
239
|
+
files are read as the queue is constructed, and an unreadable one throws: a
|
|
240
|
+
mistyped path or an unmounted secret stops the process rather than leaving it
|
|
241
|
+
talking to the broker in the clear.
|
|
242
|
+
|
|
243
|
+
## Two things that will bite you
|
|
244
|
+
|
|
245
|
+
**The certificate is checked against the host you connect to**, which is a
|
|
246
|
+
problem the moment you connect to an address. See below.
|
|
247
|
+
|
|
248
|
+
**`rejectUnauthorized: false` is not "TLS with less fuss".** It encrypts the
|
|
249
|
+
connection and then accepts whatever certificate answers, which is exactly what
|
|
250
|
+
an interceptor needs. The queue logs a warning when it sees it. Use it to poke
|
|
251
|
+
at a self-signed broker on your laptop, never in a deployment — supply the `ca`
|
|
252
|
+
instead, which is no harder and actually authenticates the server.
|
|
253
|
+
|
|
254
|
+
## Rotating certificates
|
|
255
|
+
|
|
256
|
+
Certificates expire, and the material is read **once**, as the queue is
|
|
257
|
+
constructed. A file replaced in place at the same path — which is what
|
|
258
|
+
cert-manager, Vault and a rotated Kubernetes secret all do — is not picked up
|
|
259
|
+
by a running process, and neither a reconnect nor a broker restart re-reads it.
|
|
260
|
+
|
|
261
|
+
So plan for a restart. Roll the pods when the secret changes and the new
|
|
262
|
+
material is loaded on the way up, which is what most deployments do anyway.
|
|
263
|
+
What you must not do is let the old certificate expire before that restart
|
|
264
|
+
happens.
|
|
265
|
+
|
|
266
|
+
Rotating the **certificate authority** is the case that needs care, because
|
|
267
|
+
every client must trust the new CA before the broker starts presenting
|
|
268
|
+
certificates signed by it. `ca` takes an array, so trust both across the
|
|
269
|
+
overlap:
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
tls: { ca: [readFileSync('ca-old.crt'), readFileSync('ca-new.crt')] }
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
Roll the fleet with both trusted, switch the broker, then drop the old one on
|
|
276
|
+
the next roll. `IMQ_REDIS_TLS_CA_FILE` points at a single file, but a PEM
|
|
277
|
+
bundle — several certificates concatenated into one file — works there and is
|
|
278
|
+
the usual way to do this from the environment.
|
|
279
|
+
|
|
280
|
+
## Brokers addressed by IP
|
|
281
|
+
|
|
282
|
+
Cluster discovery announces **addresses**, not names, so a queue dials
|
|
283
|
+
`10.1.2.3` and the default check compares that against the certificate — which
|
|
284
|
+
cannot carry an address nobody knew when it was issued. The handshake fails
|
|
285
|
+
with `ERR_TLS_CERT_ALTNAME_INVALID`.
|
|
286
|
+
|
|
287
|
+
Pin `servername` and the check runs against that name instead of the address:
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
tls: { ca, servername: 'redis-broker.internal' }
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Or, with no code at all, `IMQ_REDIS_TLS_SERVERNAME=redis-broker.internal`.
|
|
294
|
+
|
|
295
|
+
This is not a weakening. Certificate verification is two independent checks —
|
|
296
|
+
*is this certificate signed by an authority I trust*, and *does it name who I
|
|
297
|
+
expected to reach*. Pinning `servername` changes only the second, from an
|
|
298
|
+
address that is an accident of scheduling to an identity that is stable. A
|
|
299
|
+
broker without a certificate from your CA is refused exactly as before; so is
|
|
300
|
+
one whose certificate names something else. The specs in `test/integration/`
|
|
301
|
+
assert all three.
|
|
302
|
+
|
|
303
|
+
Issuing an IP SAN instead works, and needs no `servername` — but only where
|
|
304
|
+
broker addresses are stable and known in advance. An autoscaled pool's are
|
|
305
|
+
neither, and that is the point: **the certificate names an identity, not a
|
|
306
|
+
location.** A broker that scales out, is rescheduled, or comes back on a
|
|
307
|
+
different address presents the same certificate as before, and the client
|
|
308
|
+
verifies it against the same pinned name. Nothing is issued, re-issued or
|
|
309
|
+
reloaded when an address changes — there is no per-pod PKI to run, and one
|
|
310
|
+
certificate serves the whole pool.
|
|
311
|
+
|
|
312
|
+
Concretely, on Kubernetes: one `Certificate` for `redis-broker.internal`, its
|
|
313
|
+
Secret mounted by every broker pod, its `ca.crt` mounted by every service pod,
|
|
314
|
+
and `IMQ_REDIS_TLS_CA_FILE` plus `IMQ_REDIS_TLS_SERVERNAME` set in the service
|
|
315
|
+
deployment. Scaling the broker pool changes nothing about any of it.
|
|
316
|
+
|
|
317
|
+
**This is also what makes UDP discovery safe to keep.** The announce channel is
|
|
318
|
+
unauthenticated, so anyone who can inject a broadcast can point a service at an
|
|
319
|
+
address of their choosing. With TLS and a private CA, the worst that address can
|
|
320
|
+
do is fail to complete a handshake: it cannot present a certificate your CA
|
|
321
|
+
signed, so a spoofed announcement costs you a connection rather than the
|
|
322
|
+
traffic on it. That converts an interception risk into a denial-of-service one.
|
|
323
|
+
It does not authenticate the announcements themselves.
|
|
324
|
+
|
|
325
|
+
## Connection sharing
|
|
326
|
+
|
|
327
|
+
Writer and watcher connections are shared per server within a process, and that
|
|
328
|
+
sharing accounts for TLS: queues reaching the same host and port under different
|
|
329
|
+
TLS configurations get separate connections. A queue that asked for encryption
|
|
330
|
+
can never be handed a plaintext socket another queue opened first, nor the
|
|
331
|
+
reverse. Configurations equal by value — the same anchors, the same client
|
|
332
|
+
certificate, the same callbacks — still share.
|
|
333
|
+
|
|
334
|
+
## What it does not cover
|
|
335
|
+
|
|
336
|
+
`UDPClusterManager` announces cluster membership over unauthenticated UDP
|
|
337
|
+
broadcast, and `tls` does not touch that: it secures the queue's connections to
|
|
338
|
+
the broker, not the discovery channel that tells it which brokers exist. Treat
|
|
339
|
+
UDP discovery as trusted-network-only regardless of this setting.
|
|
340
|
+
|
|
191
341
|
# Benchmarking
|
|
192
342
|
|
|
193
343
|
First, make sure redis-server is running on localhost. The current version of the
|
package/SECURITY.md
CHANGED
|
@@ -38,3 +38,31 @@ release before reporting.
|
|
|
38
38
|
The `@imqueue` framework is open source under GPL-3.0. This policy covers the code
|
|
39
39
|
in the `@imqueue/*` packages. Vulnerabilities in third-party dependencies should be
|
|
40
40
|
reported to those projects, though we're glad to help coordinate an upgrade.
|
|
41
|
+
|
|
42
|
+
## Transport security
|
|
43
|
+
|
|
44
|
+
Connections to the redis broker are plaintext unless you ask for TLS. Set the
|
|
45
|
+
`tls` option, or the `IMQ_REDIS_TLS*` environment variables, to encrypt every
|
|
46
|
+
connection a queue opens — see the TLS section of the README. When TLS is
|
|
47
|
+
configured there is no downgrade path: a broker that will not complete the
|
|
48
|
+
handshake is reported as a connection failure rather than reached in the clear.
|
|
49
|
+
|
|
50
|
+
Two limits are worth stating plainly:
|
|
51
|
+
|
|
52
|
+
- `UDPClusterManager` announces cluster membership over unauthenticated UDP
|
|
53
|
+
broadcast. The announcements are neither encrypted nor signed, and the `tls`
|
|
54
|
+
option does not apply to them.
|
|
55
|
+
|
|
56
|
+
It does, however, bound what a forged announcement can achieve. Because
|
|
57
|
+
brokers are announced by address, verification must be pinned to a name
|
|
58
|
+
(`servername`) rather than left to compare against the address; a forged
|
|
59
|
+
announcement then points a service at a host that cannot present a
|
|
60
|
+
certificate signed by your authority, so it fails to connect rather than
|
|
61
|
+
receiving traffic. Treat that as reducing an interception risk to a
|
|
62
|
+
denial-of-service one, not as authenticating discovery.
|
|
63
|
+
- `rejectUnauthorized: false` leaves a connection encrypted but unauthenticated,
|
|
64
|
+
and therefore open to interception. The queue warns when it is set. Supply the
|
|
65
|
+
`ca` for your private authority instead.
|
|
66
|
+
- TLS material is read once, when the queue is constructed. A certificate
|
|
67
|
+
rotated in place is not picked up by a running process, so rotation needs a
|
|
68
|
+
restart — see the README for the CA-overlap procedure.
|
package/index.d.ts
CHANGED
|
@@ -41,8 +41,9 @@
|
|
|
41
41
|
*
|
|
42
42
|
* Delivery is at-least-once, so message handlers must be idempotent. Within a
|
|
43
43
|
* single process, writer and watcher connections are shared per `host:port` and
|
|
44
|
-
* reference-counted, and exactly one queue per key prefix
|
|
45
|
-
* watcher that releases delayed messages and performs
|
|
44
|
+
* TLS configuration and reference-counted, and exactly one queue per key prefix
|
|
45
|
+
* is elected as the watcher that releases delayed messages and performs
|
|
46
|
+
* maintenance.
|
|
46
47
|
*
|
|
47
48
|
* Under {@link IMQOptions.safeDelivery} a message stays checked out to its
|
|
48
49
|
* worker until the `message` listener has finished with it, and what a listener
|
package/index.js
CHANGED
|
@@ -41,8 +41,9 @@
|
|
|
41
41
|
*
|
|
42
42
|
* Delivery is at-least-once, so message handlers must be idempotent. Within a
|
|
43
43
|
* single process, writer and watcher connections are shared per `host:port` and
|
|
44
|
-
* reference-counted, and exactly one queue per key prefix
|
|
45
|
-
* watcher that releases delayed messages and performs
|
|
44
|
+
* TLS configuration and reference-counted, and exactly one queue per key prefix
|
|
45
|
+
* is elected as the watcher that releases delayed messages and performs
|
|
46
|
+
* maintenance.
|
|
46
47
|
*
|
|
47
48
|
* Under {@link IMQOptions.safeDelivery} a message stays checked out to its
|
|
48
49
|
* worker until the `message` listener has finished with it, and what a listener
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imqueue/core",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.5.0",
|
|
4
4
|
"description": "Fast JSON message queue over Redis for inter-service communication in Node.js & TypeScript microservices — the transport layer of the @imqueue framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"message-queue",
|
|
@@ -25,10 +25,11 @@
|
|
|
25
25
|
"lint": "oxlint",
|
|
26
26
|
"format": "oxfmt \"index.ts\" \"src/**/*.ts\" \"test/**/*.ts\" \"benchmark/**/*.ts\"",
|
|
27
27
|
"format:check": "oxfmt --check \"index.ts\" \"src/**/*.ts\" \"test/**/*.ts\" \"benchmark/**/*.ts\"",
|
|
28
|
-
"test": "npm run build && node --experimental-test-module-mocks --import ./test/mocks/index.js --test --test-timeout=15000 $(find test -name '*.spec.js')",
|
|
29
|
-
"test-coverage": "npm run build && node --experimental-test-module-mocks --enable-source-maps --import ./test/mocks/index.js --test --experimental-test-coverage --test-timeout=15000 $(find test -name '*.spec.js')",
|
|
30
|
-
"test-lcov": "npm run build && mkdir -p coverage && node --experimental-test-module-mocks --enable-source-maps --import ./test/mocks/index.js --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-timeout=15000 $(find test -name '*.spec.js'); node scripts/strip-comment-coverage.mjs coverage/lcov.info",
|
|
28
|
+
"test": "npm run build && node --experimental-test-module-mocks --import ./test/mocks/index.js --test --test-timeout=15000 $(find test/unit -name '*.spec.js')",
|
|
29
|
+
"test-coverage": "npm run build && node --experimental-test-module-mocks --enable-source-maps --import ./test/mocks/index.js --test --experimental-test-coverage --test-timeout=15000 $(find test/unit -name '*.spec.js')",
|
|
30
|
+
"test-lcov": "npm run build && mkdir -p coverage && node --experimental-test-module-mocks --enable-source-maps --import ./test/mocks/index.js --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-timeout=15000 $(find test/unit -name '*.spec.js'); node scripts/strip-comment-coverage.mjs coverage/lcov.info",
|
|
31
31
|
"test-coverage-html": "npm run test-lcov; genhtml coverage/lcov.info --output-directory coverage/html --ignore-errors inconsistent,corrupt,format,mismatch && echo \"Coverage report: file://$(pwd)/coverage/html/index.html\"",
|
|
32
|
+
"test-integration": "npm run build && node --test --test-timeout=60000 $(find test/integration -name '*.spec.js')",
|
|
32
33
|
"test-dev": "npm run test && npm run clean-js && npm run clean-typedefs && npm run clean-maps",
|
|
33
34
|
"clean-typedefs": "find . -name '*.d.ts' -not -wholename '*node_modules*' -not -wholename '*generator*' -type f -delete",
|
|
34
35
|
"clean-maps": "find . -name '*.js.map' -not -wholename '*node_modules*' -not -wholename '*generator*' -type f -delete",
|
|
@@ -783,6 +783,13 @@ export class ClusteredRedisQueue {
|
|
|
783
783
|
host: server.host,
|
|
784
784
|
port: server.port,
|
|
785
785
|
};
|
|
786
|
+
// carried through only when the entry actually states it: the entry is
|
|
787
|
+
// spread over the cluster-wide options below, and a key present but
|
|
788
|
+
// undefined would blank out the top-level value rather than fall back
|
|
789
|
+
// to it
|
|
790
|
+
if (server.tls !== undefined) {
|
|
791
|
+
newServer.tls = server.tls;
|
|
792
|
+
}
|
|
786
793
|
const opts = { ...this.mqOptions, ...newServer };
|
|
787
794
|
const imq = new RedisQueue(this.name, opts);
|
|
788
795
|
copyEventEmitter(this.templateEmitter, imq);
|
package/src/IMessageQueue.d.ts
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
* <support@imqueue.com> to get commercial licensing options.
|
|
23
23
|
*/
|
|
24
24
|
import { EventEmitter } from 'node:events';
|
|
25
|
+
import type { ConnectionOptions as TlsOptions } from 'node:tls';
|
|
25
26
|
import { IMQMode } from './IMQMode.js';
|
|
26
27
|
import { ClusterManager } from './ClusterManager.js';
|
|
27
28
|
export { EventEmitter } from 'node:events';
|
|
@@ -168,10 +169,11 @@ export interface IMessageQueueConnection extends IMessageQueueAuthConnection {
|
|
|
168
169
|
}
|
|
169
170
|
/**
|
|
170
171
|
* Optional credentials for a queue host, forwarded to the Redis client as
|
|
171
|
-
* `username` and `password
|
|
172
|
+
* `username` and `password`, plus the transport security to reach it with.
|
|
172
173
|
*
|
|
173
|
-
* Supply both for a Redis ACL user, or just `password` for a
|
|
174
|
-
* server. Omit both to connect unauthenticated, which is the
|
|
174
|
+
* Supply both credentials for a Redis ACL user, or just `password` for a
|
|
175
|
+
* `requirepass`-only server. Omit both to connect unauthenticated, which is the
|
|
176
|
+
* default.
|
|
175
177
|
*/
|
|
176
178
|
export interface IMessageQueueAuthConnection {
|
|
177
179
|
/**
|
|
@@ -182,6 +184,37 @@ export interface IMessageQueueAuthConnection {
|
|
|
182
184
|
* Password for the queue host.
|
|
183
185
|
*/
|
|
184
186
|
password?: string;
|
|
187
|
+
/**
|
|
188
|
+
* Encrypts this connection with TLS. `true` connects with Node's defaults,
|
|
189
|
+
* verifying the server against the system trust store; an object is handed
|
|
190
|
+
* to `tls.connect()` as given, so supply `ca` for a private certificate
|
|
191
|
+
* authority and `cert` with `key` for mutual TLS.
|
|
192
|
+
*
|
|
193
|
+
* Applies to every channel the queue opens — reader, writer, watcher and
|
|
194
|
+
* subscription alike — so enabling it here encrypts the whole bus. The
|
|
195
|
+
* broker must be listening for TLS (`tls-port`); a server that is not will
|
|
196
|
+
* refuse the handshake rather than fall back to plaintext.
|
|
197
|
+
*
|
|
198
|
+
* @defaultValue undefined
|
|
199
|
+
*
|
|
200
|
+
* @remarks
|
|
201
|
+
* The certificate is verified against {@link IMessageQueueConnection.host}
|
|
202
|
+
* unless `servername` says otherwise. A host that is a bare IP address
|
|
203
|
+
* therefore needs a certificate carrying that address as an IP SAN — reach
|
|
204
|
+
* the broker by the name on its certificate, or set `servername` to it.
|
|
205
|
+
*
|
|
206
|
+
* The writer and watcher connections are shared per server within the
|
|
207
|
+
* process, and that sharing accounts for this option: queues reaching the
|
|
208
|
+
* same host and port under different TLS configurations get separate
|
|
209
|
+
* connections rather than silently inheriting whichever was opened first.
|
|
210
|
+
* Configurations that are equal by value still share.
|
|
211
|
+
*
|
|
212
|
+
* When omitted, the environment is consulted instead — see
|
|
213
|
+
* `IMQ_REDIS_TLS` and its companions in {@link envTls} — which lets a
|
|
214
|
+
* deployment turn encryption on without a code change. Passing `false`
|
|
215
|
+
* declines that fallback and forces a plaintext connection.
|
|
216
|
+
*/
|
|
217
|
+
tls?: boolean | TlsOptions;
|
|
185
218
|
}
|
|
186
219
|
/**
|
|
187
220
|
* Options accepted by every queue implementation.
|
|
@@ -372,8 +405,12 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
|
|
|
372
405
|
* cluster-membership matching. Sends are distributed across the servers by
|
|
373
406
|
* health-aware round-robin, preferring ones whose connection is ready.
|
|
374
407
|
*
|
|
375
|
-
*
|
|
376
|
-
*
|
|
408
|
+
* An entry may carry its own `tls`, overriding the top-level one for that
|
|
409
|
+
* server alone — for a cluster whose members do not share trust anchors.
|
|
410
|
+
* An entry that leaves it out falls back to the top level.
|
|
411
|
+
*
|
|
412
|
+
* Per-entry `username` and `password` remain ignored: the underlying
|
|
413
|
+
* queues authenticate with the top-level credentials.
|
|
377
414
|
*/
|
|
378
415
|
cluster?: IMessageQueueConnection[];
|
|
379
416
|
/**
|
package/src/RedisQueue.d.ts
CHANGED
|
@@ -71,11 +71,12 @@ export declare const IMQ_CONNECTION_QUIT_TIMEOUT: number;
|
|
|
71
71
|
* @remarks
|
|
72
72
|
* Connection model: the reader is per instance and exists only in
|
|
73
73
|
* {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, while the writer and
|
|
74
|
-
* watcher connections are shared per `host:port`
|
|
75
|
-
* process and reference-counted. Exactly one queue
|
|
76
|
-
* the watcher through a `<prefix>:watch:lock` key,
|
|
77
|
-
* delayed messages, recovers abandoned
|
|
78
|
-
* {@link IMQOptions.cleanup} is on — prunes
|
|
74
|
+
* watcher connections are shared per `host:port` — and per TLS configuration —
|
|
75
|
+
* across every queue in the process and reference-counted. Exactly one queue
|
|
76
|
+
* per key prefix is elected as the watcher through a `<prefix>:watch:lock` key,
|
|
77
|
+
* and that owner also releases delayed messages, recovers abandoned
|
|
78
|
+
* safe-delivery hand-offs and — when {@link IMQOptions.cleanup} is on — prunes
|
|
79
|
+
* orphaned keys.
|
|
79
80
|
*
|
|
80
81
|
* Lifecycle: {@link RedisQueue.start} is required before consuming or
|
|
81
82
|
* publishing, while {@link RedisQueue.send} starts the queue lazily.
|
|
@@ -238,13 +239,33 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
|
|
|
238
239
|
*
|
|
239
240
|
* @remarks
|
|
240
241
|
* This is not an instance identifier. It is deliberately shared by every
|
|
241
|
-
* queue in the process that targets the same server, and is
|
|
242
|
-
*
|
|
243
|
-
*
|
|
244
|
-
*
|
|
245
|
-
*
|
|
242
|
+
* queue in the process that targets the same server, and it is what
|
|
243
|
+
* identifies that server in logs. It includes neither the key prefix nor
|
|
244
|
+
* the credentials.
|
|
245
|
+
*
|
|
246
|
+
* It is no longer the whole of the connection pool key — see
|
|
247
|
+
* {@link RedisQueue.poolKey} — because connections differing in their
|
|
248
|
+
* transport security must not be shared.
|
|
246
249
|
*/
|
|
247
250
|
readonly redisKey: string;
|
|
251
|
+
/**
|
|
252
|
+
* Key under which the shared writer and watcher connections, and the writer
|
|
253
|
+
* reference count, are stored.
|
|
254
|
+
*
|
|
255
|
+
* @remarks
|
|
256
|
+
* This is {@link RedisQueue.redisKey} for a plaintext connection, and that
|
|
257
|
+
* address plus a fingerprint of {@link IMQOptions.tls} for an encrypted
|
|
258
|
+
* one. Two queues reaching one server under equal TLS configurations
|
|
259
|
+
* therefore still share a connection, while queues that differ in their
|
|
260
|
+
* trust anchors, client certificate or verification callbacks get separate
|
|
261
|
+
* ones — a queue asking for TLS can never be handed a plaintext socket
|
|
262
|
+
* another queue opened first, nor the reverse.
|
|
263
|
+
*
|
|
264
|
+
* The prefix and the credentials remain outside the key, so queues
|
|
265
|
+
* differing only in those still share a connection and the first one
|
|
266
|
+
* created still wins.
|
|
267
|
+
*/
|
|
268
|
+
private readonly poolKey;
|
|
248
269
|
/**
|
|
249
270
|
* Lua scripts for redis
|
|
250
271
|
*/
|
|
@@ -593,21 +614,22 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
|
|
|
593
614
|
* Used for health-aware routing in the clustered queue.
|
|
594
615
|
*
|
|
595
616
|
* @remarks
|
|
596
|
-
* The writer connection is shared per `host:port`
|
|
597
|
-
* reflects the health of that server connection
|
|
598
|
-
* alone — every queue pointing at the same
|
|
617
|
+
* The writer connection is shared per `host:port` and TLS configuration
|
|
618
|
+
* within the process, so this reflects the health of that server connection
|
|
619
|
+
* rather than of this instance alone — every queue pointing at the same
|
|
620
|
+
* server the same way reports the same value.
|
|
599
621
|
*/
|
|
600
622
|
get available(): boolean;
|
|
601
623
|
/**
|
|
602
624
|
* Writer connection associated with this queue instance. Shared by every
|
|
603
|
-
* queue in the process that targets the same
|
|
625
|
+
* queue in the process that targets the same {@link RedisQueue.poolKey}.
|
|
604
626
|
*/
|
|
605
627
|
private get writer();
|
|
606
628
|
private set writer(value);
|
|
607
629
|
/**
|
|
608
630
|
* Watcher connection associated with this queue instance. Shared by every
|
|
609
|
-
* queue in the process that targets the same
|
|
610
|
-
* per prefix is the elected watcher owner.
|
|
631
|
+
* queue in the process that targets the same {@link RedisQueue.poolKey}; at
|
|
632
|
+
* most one queue per prefix is the elected watcher owner.
|
|
611
633
|
*/
|
|
612
634
|
private get watcher();
|
|
613
635
|
private set watcher(value);
|
|
@@ -645,6 +667,23 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
|
|
|
645
667
|
* Destroys writer channel
|
|
646
668
|
*/
|
|
647
669
|
private destroyWriter;
|
|
670
|
+
/**
|
|
671
|
+
* Installs a durable `error` listener on a connection's socket.
|
|
672
|
+
*
|
|
673
|
+
* @param client - the connection whose socket to guard
|
|
674
|
+
*
|
|
675
|
+
* @remarks
|
|
676
|
+
* The redis client guards the socket with a one-shot listener, which the
|
|
677
|
+
* first failure consumes. A socket that goes on to report a second one -
|
|
678
|
+
* a rejected TLS handshake is answered by an alert that arrives after the
|
|
679
|
+
* failure that caused it - then reaches a socket with nothing attached,
|
|
680
|
+
* and an unhandled `error` takes the process down. Nothing is left to act
|
|
681
|
+
* on it by then, so it is swallowed.
|
|
682
|
+
*
|
|
683
|
+
* Idempotent: connections are marked once guarded, so repeated failures on
|
|
684
|
+
* one socket do not accumulate listeners.
|
|
685
|
+
*/
|
|
686
|
+
private guardSocket;
|
|
648
687
|
/**
|
|
649
688
|
* Destroys any channel
|
|
650
689
|
*/
|
package/src/RedisQueue.js
CHANGED
|
@@ -59,7 +59,7 @@ import { EventEmitter } from 'node:events';
|
|
|
59
59
|
import { randomUUID } from 'node:crypto';
|
|
60
60
|
import { hostname } from 'node:os';
|
|
61
61
|
import { IMQMode, profile, } from './index.js';
|
|
62
|
-
import { buildOptions, escapeRegExp, randomInt, pack, sha1, unpack, envInt, errorCode, LOG_MAX_KEYS, } from './helpers/index.js';
|
|
62
|
+
import { buildOptions, escapeRegExp, randomInt, pack, sha1, unpack, envInt, envTls, tlsFingerprint, errorCode, LOG_MAX_KEYS, } from './helpers/index.js';
|
|
63
63
|
import Redis from './redis.js';
|
|
64
64
|
const RX_CLIENT_NAME = /name=(\S+)/g;
|
|
65
65
|
const RX_CLIENT_TEST = /:(reader|writer|watcher)/;
|
|
@@ -178,11 +178,12 @@ const IMQ_REDIS_MAX_LISTENERS_LIMIT = envInt('IMQ_REDIS_MAX_LISTENERS_LIMIT', 10
|
|
|
178
178
|
* @remarks
|
|
179
179
|
* Connection model: the reader is per instance and exists only in
|
|
180
180
|
* {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, while the writer and
|
|
181
|
-
* watcher connections are shared per `host:port`
|
|
182
|
-
* process and reference-counted. Exactly one queue
|
|
183
|
-
* the watcher through a `<prefix>:watch:lock` key,
|
|
184
|
-
* delayed messages, recovers abandoned
|
|
185
|
-
* {@link IMQOptions.cleanup} is on — prunes
|
|
181
|
+
* watcher connections are shared per `host:port` — and per TLS configuration —
|
|
182
|
+
* across every queue in the process and reference-counted. Exactly one queue
|
|
183
|
+
* per key prefix is elected as the watcher through a `<prefix>:watch:lock` key,
|
|
184
|
+
* and that owner also releases delayed messages, recovers abandoned
|
|
185
|
+
* safe-delivery hand-offs and — when {@link IMQOptions.cleanup} is on — prunes
|
|
186
|
+
* orphaned keys.
|
|
186
187
|
*
|
|
187
188
|
* Lifecycle: {@link RedisQueue.start} is required before consuming or
|
|
188
189
|
* publishing, while {@link RedisQueue.send} starts the queue lazily.
|
|
@@ -355,13 +356,33 @@ let RedisQueue = (() => {
|
|
|
355
356
|
*
|
|
356
357
|
* @remarks
|
|
357
358
|
* This is not an instance identifier. It is deliberately shared by every
|
|
358
|
-
* queue in the process that targets the same server, and is
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
359
|
+
* queue in the process that targets the same server, and it is what
|
|
360
|
+
* identifies that server in logs. It includes neither the key prefix nor
|
|
361
|
+
* the credentials.
|
|
362
|
+
*
|
|
363
|
+
* It is no longer the whole of the connection pool key — see
|
|
364
|
+
* {@link RedisQueue.poolKey} — because connections differing in their
|
|
365
|
+
* transport security must not be shared.
|
|
363
366
|
*/
|
|
364
367
|
redisKey;
|
|
368
|
+
/**
|
|
369
|
+
* Key under which the shared writer and watcher connections, and the writer
|
|
370
|
+
* reference count, are stored.
|
|
371
|
+
*
|
|
372
|
+
* @remarks
|
|
373
|
+
* This is {@link RedisQueue.redisKey} for a plaintext connection, and that
|
|
374
|
+
* address plus a fingerprint of {@link IMQOptions.tls} for an encrypted
|
|
375
|
+
* one. Two queues reaching one server under equal TLS configurations
|
|
376
|
+
* therefore still share a connection, while queues that differ in their
|
|
377
|
+
* trust anchors, client certificate or verification callbacks get separate
|
|
378
|
+
* ones — a queue asking for TLS can never be handed a plaintext socket
|
|
379
|
+
* another queue opened first, nor the reverse.
|
|
380
|
+
*
|
|
381
|
+
* The prefix and the credentials remain outside the key, so queues
|
|
382
|
+
* differing only in those still share a connection and the first one
|
|
383
|
+
* created still wins.
|
|
384
|
+
*/
|
|
385
|
+
poolKey;
|
|
365
386
|
/**
|
|
366
387
|
* Lua scripts for redis
|
|
367
388
|
*/
|
|
@@ -444,9 +465,30 @@ let RedisQueue = (() => {
|
|
|
444
465
|
this.name = name;
|
|
445
466
|
this.mode = mode;
|
|
446
467
|
this.options = buildOptions(DEFAULT_IMQ_OPTIONS, options);
|
|
468
|
+
if (this.options.tls === undefined) {
|
|
469
|
+
// an unreadable CA or client key throws out of here rather than
|
|
470
|
+
// yielding a queue that would quietly talk to the broker in clear
|
|
471
|
+
const fromEnv = envTls();
|
|
472
|
+
if (fromEnv !== undefined) {
|
|
473
|
+
// assigned only when the environment actually asks for TLS, so
|
|
474
|
+
// that a queue nobody configured for it carries no `tls` key at
|
|
475
|
+
// all and `options` keeps exactly the shape it always had
|
|
476
|
+
this.options.tls = fromEnv;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
447
479
|
this.pack = this.options.useGzip ? pack : JSON.stringify;
|
|
448
480
|
this.unpack = this.options.useGzip ? unpack : JSON.parse;
|
|
449
481
|
this.redisKey = `${this.options.host}:${this.options.port}`;
|
|
482
|
+
this.poolKey = this.options.tls
|
|
483
|
+
? `${this.redisKey}#${tlsFingerprint(this.options.tls)}`
|
|
484
|
+
: this.redisKey;
|
|
485
|
+
if (this.options.tls &&
|
|
486
|
+
this.options.tls !== true &&
|
|
487
|
+
this.options.tls.rejectUnauthorized === false) {
|
|
488
|
+
this.logger.warn('%s: TLS certificate verification is disabled for redis host' +
|
|
489
|
+
' %s — the connection is encrypted but the server is not' +
|
|
490
|
+
' authenticated, so it is open to interception', this.name, this.redisKey);
|
|
491
|
+
}
|
|
450
492
|
for (const script of Object.keys(this.scripts)) {
|
|
451
493
|
this.scripts[script].checksum = sha1(this.scripts[script].code);
|
|
452
494
|
}
|
|
@@ -722,8 +764,8 @@ let RedisQueue = (() => {
|
|
|
722
764
|
RedisQueue.bindSignals();
|
|
723
765
|
}
|
|
724
766
|
if (!this.writerAcquired) {
|
|
725
|
-
RedisQueue.writerRefs[this.
|
|
726
|
-
(RedisQueue.writerRefs[this.
|
|
767
|
+
RedisQueue.writerRefs[this.poolKey] =
|
|
768
|
+
(RedisQueue.writerRefs[this.poolKey] || 0) + 1;
|
|
727
769
|
this.writerAcquired = true;
|
|
728
770
|
}
|
|
729
771
|
await this.initWatcher();
|
|
@@ -1082,33 +1124,34 @@ let RedisQueue = (() => {
|
|
|
1082
1124
|
* Used for health-aware routing in the clustered queue.
|
|
1083
1125
|
*
|
|
1084
1126
|
* @remarks
|
|
1085
|
-
* The writer connection is shared per `host:port`
|
|
1086
|
-
* reflects the health of that server connection
|
|
1087
|
-
* alone — every queue pointing at the same
|
|
1127
|
+
* The writer connection is shared per `host:port` and TLS configuration
|
|
1128
|
+
* within the process, so this reflects the health of that server connection
|
|
1129
|
+
* rather than of this instance alone — every queue pointing at the same
|
|
1130
|
+
* server the same way reports the same value.
|
|
1088
1131
|
*/
|
|
1089
1132
|
get available() {
|
|
1090
1133
|
return !this.writer || this.writer.status === 'ready';
|
|
1091
1134
|
}
|
|
1092
1135
|
/**
|
|
1093
1136
|
* Writer connection associated with this queue instance. Shared by every
|
|
1094
|
-
* queue in the process that targets the same
|
|
1137
|
+
* queue in the process that targets the same {@link RedisQueue.poolKey}.
|
|
1095
1138
|
*/
|
|
1096
1139
|
get writer() {
|
|
1097
|
-
return RedisQueue.writers[this.
|
|
1140
|
+
return RedisQueue.writers[this.poolKey];
|
|
1098
1141
|
}
|
|
1099
1142
|
set writer(conn) {
|
|
1100
|
-
RedisQueue.writers[this.
|
|
1143
|
+
RedisQueue.writers[this.poolKey] = conn;
|
|
1101
1144
|
}
|
|
1102
1145
|
/**
|
|
1103
1146
|
* Watcher connection associated with this queue instance. Shared by every
|
|
1104
|
-
* queue in the process that targets the same
|
|
1105
|
-
* per prefix is the elected watcher owner.
|
|
1147
|
+
* queue in the process that targets the same {@link RedisQueue.poolKey}; at
|
|
1148
|
+
* most one queue per prefix is the elected watcher owner.
|
|
1106
1149
|
*/
|
|
1107
1150
|
get watcher() {
|
|
1108
|
-
return RedisQueue.watchers[this.
|
|
1151
|
+
return RedisQueue.watchers[this.poolKey];
|
|
1109
1152
|
}
|
|
1110
1153
|
set watcher(conn) {
|
|
1111
|
-
RedisQueue.watchers[this.
|
|
1154
|
+
RedisQueue.watchers[this.poolKey] = conn;
|
|
1112
1155
|
}
|
|
1113
1156
|
/**
|
|
1114
1157
|
* Returns the connection currently bound to the given channel, if any.
|
|
@@ -1175,7 +1218,7 @@ let RedisQueue = (() => {
|
|
|
1175
1218
|
if (this.watcher) {
|
|
1176
1219
|
this.verbose('Destroying watcher...');
|
|
1177
1220
|
this.destroyChannel('watcher');
|
|
1178
|
-
delete RedisQueue.watchers[this.
|
|
1221
|
+
delete RedisQueue.watchers[this.poolKey];
|
|
1179
1222
|
this.verbose('Watcher destroyed!');
|
|
1180
1223
|
}
|
|
1181
1224
|
}
|
|
@@ -1185,8 +1228,8 @@ let RedisQueue = (() => {
|
|
|
1185
1228
|
destroyWriter(release = true) {
|
|
1186
1229
|
if (release && this.writerAcquired) {
|
|
1187
1230
|
this.writerAcquired = false;
|
|
1188
|
-
RedisQueue.writerRefs[this.
|
|
1189
|
-
if (RedisQueue.writerRefs[this.
|
|
1231
|
+
RedisQueue.writerRefs[this.poolKey] = Math.max(0, (RedisQueue.writerRefs[this.poolKey] || 1) - 1);
|
|
1232
|
+
if (RedisQueue.writerRefs[this.poolKey] > 0) {
|
|
1190
1233
|
// the shared writer connection is still used by other
|
|
1191
1234
|
// queue instances within this process
|
|
1192
1235
|
this.verbose('Writer is still in use, skipping destroy...');
|
|
@@ -1196,10 +1239,34 @@ let RedisQueue = (() => {
|
|
|
1196
1239
|
if (this.writer) {
|
|
1197
1240
|
this.verbose('Destroying writer...');
|
|
1198
1241
|
this.destroyChannel('writer');
|
|
1199
|
-
delete RedisQueue.writers[this.
|
|
1242
|
+
delete RedisQueue.writers[this.poolKey];
|
|
1200
1243
|
this.verbose('Writer destroyed!');
|
|
1201
1244
|
}
|
|
1202
1245
|
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Installs a durable `error` listener on a connection's socket.
|
|
1248
|
+
*
|
|
1249
|
+
* @param client - the connection whose socket to guard
|
|
1250
|
+
*
|
|
1251
|
+
* @remarks
|
|
1252
|
+
* The redis client guards the socket with a one-shot listener, which the
|
|
1253
|
+
* first failure consumes. A socket that goes on to report a second one -
|
|
1254
|
+
* a rejected TLS handshake is answered by an alert that arrives after the
|
|
1255
|
+
* failure that caused it - then reaches a socket with nothing attached,
|
|
1256
|
+
* and an unhandled `error` takes the process down. Nothing is left to act
|
|
1257
|
+
* on it by then, so it is swallowed.
|
|
1258
|
+
*
|
|
1259
|
+
* Idempotent: connections are marked once guarded, so repeated failures on
|
|
1260
|
+
* one socket do not accumulate listeners.
|
|
1261
|
+
*/
|
|
1262
|
+
guardSocket(client) {
|
|
1263
|
+
const stream = client.stream;
|
|
1264
|
+
if (!stream || client.__guarded__) {
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
client.__guarded__ = true;
|
|
1268
|
+
stream.on('error', () => undefined);
|
|
1269
|
+
}
|
|
1203
1270
|
/**
|
|
1204
1271
|
* Destroys any channel
|
|
1205
1272
|
*/
|
|
@@ -1209,7 +1276,15 @@ let RedisQueue = (() => {
|
|
|
1209
1276
|
return;
|
|
1210
1277
|
}
|
|
1211
1278
|
try {
|
|
1279
|
+
this.guardSocket(client);
|
|
1212
1280
|
client.removeAllListeners();
|
|
1281
|
+
// removing the listeners leaves the client with no `error` handler
|
|
1282
|
+
// while the teardown below still writes to it. On a socket that has
|
|
1283
|
+
// already failed - a TLS handshake the peer rejected, most
|
|
1284
|
+
// obviously - that write raises an error an EventEmitter with no
|
|
1285
|
+
// listener rethrows, taking the process down as it is shutting the
|
|
1286
|
+
// connection cleanly. Nothing is left to report it to, so swallow.
|
|
1287
|
+
client.on('error', () => undefined);
|
|
1213
1288
|
let disconnected = false;
|
|
1214
1289
|
const forceDisconnect = () => {
|
|
1215
1290
|
if (disconnected) {
|
|
@@ -1268,6 +1343,13 @@ let RedisQueue = (() => {
|
|
|
1268
1343
|
host: options.host || 'localhost',
|
|
1269
1344
|
username: options.username,
|
|
1270
1345
|
password: options.password,
|
|
1346
|
+
// spread conditionally: the literal stays closed on purpose, so
|
|
1347
|
+
// that nothing a caller passes can override the retry strategy,
|
|
1348
|
+
// the offline queue or the lazy connect this queue's reconnection
|
|
1349
|
+
// logic is built on
|
|
1350
|
+
...(options.tls
|
|
1351
|
+
? { tls: options.tls === true ? {} : options.tls }
|
|
1352
|
+
: {}),
|
|
1271
1353
|
connectionName: this.getChannelName(this.name, options.prefix || '', channel),
|
|
1272
1354
|
retryStrategy: noRetryStrategy,
|
|
1273
1355
|
autoResubscribe: true,
|
|
@@ -1403,6 +1485,12 @@ let RedisQueue = (() => {
|
|
|
1403
1485
|
onErrorHandler(channel) {
|
|
1404
1486
|
return (error) => {
|
|
1405
1487
|
this.verbose(`Redis Error: ${error}`);
|
|
1488
|
+
// the failure that brings a socket down is rarely the last thing
|
|
1489
|
+
// it reports, and the client's own guard is spent by this one
|
|
1490
|
+
const failed = this.connectionOf(channel);
|
|
1491
|
+
if (failed) {
|
|
1492
|
+
this.guardSocket(failed);
|
|
1493
|
+
}
|
|
1406
1494
|
if (this.destroyed) {
|
|
1407
1495
|
return;
|
|
1408
1496
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ConnectionOptions as TlsOptions } from 'node:tls';
|
|
2
|
+
/**
|
|
3
|
+
* Builds a TLS configuration from the environment, for turning encryption on
|
|
4
|
+
* across a fleet without touching application code.
|
|
5
|
+
*
|
|
6
|
+
* TLS is enabled by `IMQ_REDIS_TLS`, or implicitly by supplying any TLS
|
|
7
|
+
* material; `IMQ_REDIS_TLS=0` wins over both and disables it outright. The
|
|
8
|
+
* recognised variables are:
|
|
9
|
+
*
|
|
10
|
+
* - `IMQ_REDIS_TLS` — enables TLS with Node's default verification against the
|
|
11
|
+
* system trust store
|
|
12
|
+
* - `IMQ_REDIS_TLS_CA_FILE` — PEM bundle of the trust anchors to verify the
|
|
13
|
+
* broker against, for a private CA
|
|
14
|
+
* - `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE` — client certificate
|
|
15
|
+
* and its private key, for mutual TLS
|
|
16
|
+
* - `IMQ_REDIS_TLS_KEY_PASSPHRASE` — passphrase of an encrypted private key
|
|
17
|
+
* - `IMQ_REDIS_TLS_SERVERNAME` — expected certificate name, needed when the
|
|
18
|
+
* broker is reached at an address the certificate does not carry
|
|
19
|
+
* - `IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` — set to `0` to accept an unverified
|
|
20
|
+
* certificate. This reduces the connection to encryption without
|
|
21
|
+
* authentication and leaves it open to interception; use it for a local
|
|
22
|
+
* experiment, never in a deployment.
|
|
23
|
+
*
|
|
24
|
+
* Certificate files are read eagerly, and an unreadable one throws rather than
|
|
25
|
+
* yielding a configuration that would connect in the clear.
|
|
26
|
+
*
|
|
27
|
+
* @returns the configuration, or `undefined` when the environment asks for no
|
|
28
|
+
* TLS
|
|
29
|
+
* @throws {Error} when TLS material is named but cannot be read
|
|
30
|
+
*/
|
|
31
|
+
export declare function envTls(): TlsOptions | undefined;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Helper: envTls
|
|
3
|
+
*
|
|
4
|
+
* I'm Queue Software Project
|
|
5
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
6
|
+
*
|
|
7
|
+
* This program is free software: you can redistribute it and/or modify
|
|
8
|
+
* it under the terms of the GNU General Public License as published by
|
|
9
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
* (at your option) any later version.
|
|
11
|
+
*
|
|
12
|
+
* This program is distributed in the hope that it will be useful,
|
|
13
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
* GNU General Public License for more details.
|
|
16
|
+
*
|
|
17
|
+
* You should have received a copy of the GNU General Public License
|
|
18
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
19
|
+
*
|
|
20
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
21
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
22
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
23
|
+
*/
|
|
24
|
+
import { readFileSync } from 'node:fs';
|
|
25
|
+
/**
|
|
26
|
+
* Environment variables read by {@link envTls}, in the order they are combined
|
|
27
|
+
* into the resulting configuration.
|
|
28
|
+
*/
|
|
29
|
+
const ENV_VARS = [
|
|
30
|
+
'IMQ_REDIS_TLS',
|
|
31
|
+
'IMQ_REDIS_TLS_CA_FILE',
|
|
32
|
+
'IMQ_REDIS_TLS_CERT_FILE',
|
|
33
|
+
'IMQ_REDIS_TLS_KEY_FILE',
|
|
34
|
+
'IMQ_REDIS_TLS_KEY_PASSPHRASE',
|
|
35
|
+
'IMQ_REDIS_TLS_SERVERNAME',
|
|
36
|
+
'IMQ_REDIS_TLS_REJECT_UNAUTHORIZED',
|
|
37
|
+
];
|
|
38
|
+
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);
|
|
39
|
+
const FALSE_VALUES = new Set(['0', 'false', 'no', 'off']);
|
|
40
|
+
/**
|
|
41
|
+
* Result of the last {@link envTls} evaluation, together with the environment
|
|
42
|
+
* it was computed from, so that repeated queue construction re-reads the
|
|
43
|
+
* certificate files only when something actually changed.
|
|
44
|
+
*/
|
|
45
|
+
let cache;
|
|
46
|
+
/**
|
|
47
|
+
* Reads a boolean environment variable.
|
|
48
|
+
*
|
|
49
|
+
* @param name - variable name
|
|
50
|
+
* @returns the parsed value, or `undefined` when unset or unrecognised
|
|
51
|
+
*/
|
|
52
|
+
function envBool(name) {
|
|
53
|
+
const value = (process.env[name] || '').trim().toLowerCase();
|
|
54
|
+
if (TRUE_VALUES.has(value)) {
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
if (FALSE_VALUES.has(value)) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Reads a file named by an environment variable.
|
|
64
|
+
*
|
|
65
|
+
* @param name - variable name holding the path
|
|
66
|
+
* @returns the file contents, or `undefined` when the variable is unset
|
|
67
|
+
* @throws {Error} when the variable is set but the file cannot be read
|
|
68
|
+
*/
|
|
69
|
+
function envFile(name) {
|
|
70
|
+
const path = (process.env[name] || '').trim();
|
|
71
|
+
if (!path) {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return readFileSync(path);
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
// deliberately fatal: a mistyped path or an unmounted secret must stop
|
|
79
|
+
// the queue, never quietly leave it talking plaintext to the broker
|
|
80
|
+
const error = new Error(`${name}: unable to read TLS material from "${path}": ${err.message}`);
|
|
81
|
+
error.code =
|
|
82
|
+
'IMQ_TLS_MATERIAL_UNREADABLE';
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Builds a TLS configuration from the environment, for turning encryption on
|
|
88
|
+
* across a fleet without touching application code.
|
|
89
|
+
*
|
|
90
|
+
* TLS is enabled by `IMQ_REDIS_TLS`, or implicitly by supplying any TLS
|
|
91
|
+
* material; `IMQ_REDIS_TLS=0` wins over both and disables it outright. The
|
|
92
|
+
* recognised variables are:
|
|
93
|
+
*
|
|
94
|
+
* - `IMQ_REDIS_TLS` — enables TLS with Node's default verification against the
|
|
95
|
+
* system trust store
|
|
96
|
+
* - `IMQ_REDIS_TLS_CA_FILE` — PEM bundle of the trust anchors to verify the
|
|
97
|
+
* broker against, for a private CA
|
|
98
|
+
* - `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE` — client certificate
|
|
99
|
+
* and its private key, for mutual TLS
|
|
100
|
+
* - `IMQ_REDIS_TLS_KEY_PASSPHRASE` — passphrase of an encrypted private key
|
|
101
|
+
* - `IMQ_REDIS_TLS_SERVERNAME` — expected certificate name, needed when the
|
|
102
|
+
* broker is reached at an address the certificate does not carry
|
|
103
|
+
* - `IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` — set to `0` to accept an unverified
|
|
104
|
+
* certificate. This reduces the connection to encryption without
|
|
105
|
+
* authentication and leaves it open to interception; use it for a local
|
|
106
|
+
* experiment, never in a deployment.
|
|
107
|
+
*
|
|
108
|
+
* Certificate files are read eagerly, and an unreadable one throws rather than
|
|
109
|
+
* yielding a configuration that would connect in the clear.
|
|
110
|
+
*
|
|
111
|
+
* @returns the configuration, or `undefined` when the environment asks for no
|
|
112
|
+
* TLS
|
|
113
|
+
* @throws {Error} when TLS material is named but cannot be read
|
|
114
|
+
*/
|
|
115
|
+
export function envTls() {
|
|
116
|
+
const env = ENV_VARS.map(name => `${name}=${process.env[name] ?? ''}`).join('\n');
|
|
117
|
+
if (cache && cache.env === env) {
|
|
118
|
+
return cache.tls;
|
|
119
|
+
}
|
|
120
|
+
const enabled = envBool('IMQ_REDIS_TLS');
|
|
121
|
+
const tls = {};
|
|
122
|
+
if (enabled === false) {
|
|
123
|
+
cache = { env, tls: undefined };
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
const ca = envFile('IMQ_REDIS_TLS_CA_FILE');
|
|
127
|
+
const cert = envFile('IMQ_REDIS_TLS_CERT_FILE');
|
|
128
|
+
const key = envFile('IMQ_REDIS_TLS_KEY_FILE');
|
|
129
|
+
const passphrase = (process.env.IMQ_REDIS_TLS_KEY_PASSPHRASE || '').trim();
|
|
130
|
+
const servername = (process.env.IMQ_REDIS_TLS_SERVERNAME || '').trim();
|
|
131
|
+
const rejectUnauthorized = envBool('IMQ_REDIS_TLS_REJECT_UNAUTHORIZED');
|
|
132
|
+
if (ca) {
|
|
133
|
+
tls.ca = ca;
|
|
134
|
+
}
|
|
135
|
+
if (cert) {
|
|
136
|
+
tls.cert = cert;
|
|
137
|
+
}
|
|
138
|
+
if (key) {
|
|
139
|
+
tls.key = key;
|
|
140
|
+
}
|
|
141
|
+
if (passphrase) {
|
|
142
|
+
tls.passphrase = passphrase;
|
|
143
|
+
}
|
|
144
|
+
if (servername) {
|
|
145
|
+
tls.servername = servername;
|
|
146
|
+
}
|
|
147
|
+
if (rejectUnauthorized !== undefined) {
|
|
148
|
+
tls.rejectUnauthorized = rejectUnauthorized;
|
|
149
|
+
}
|
|
150
|
+
// an explicit switch turns TLS on by itself; so does supplying key
|
|
151
|
+
// material, which is only ever meaningful with TLS on. The remaining
|
|
152
|
+
// variables only shape a connection someone else has asked for - reading
|
|
153
|
+
// an enable out of `rejectUnauthorized=0` would be perverse.
|
|
154
|
+
const on = enabled === true || !!(ca || cert || key);
|
|
155
|
+
cache = { env, tls: on ? tls : undefined };
|
|
156
|
+
return cache.tls;
|
|
157
|
+
}
|
|
158
|
+
//# sourceMappingURL=envTls.js.map
|
package/src/helpers/index.d.ts
CHANGED
package/src/helpers/index.js
CHANGED
|
@@ -29,5 +29,7 @@ export * from './unpack.js';
|
|
|
29
29
|
export * from './escapeRegExp.js';
|
|
30
30
|
export * from './copyEventEmitter.js';
|
|
31
31
|
export * from './envInt.js';
|
|
32
|
+
export * from './envTls.js';
|
|
33
|
+
export * from './tlsFingerprint.js';
|
|
32
34
|
export * from './logging.js';
|
|
33
35
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ConnectionOptions as TlsOptions } from 'node:tls';
|
|
2
|
+
/**
|
|
3
|
+
* Computes a stable fingerprint of a TLS configuration, used to keep
|
|
4
|
+
* connections that differ in their transport security out of the same
|
|
5
|
+
* connection pool slot.
|
|
6
|
+
*
|
|
7
|
+
* Two configurations that are equal by value share a fingerprint, so pooling
|
|
8
|
+
* still works across independently built option literals. Any difference in
|
|
9
|
+
* the trust anchors, the client certificate, the verification callbacks or the
|
|
10
|
+
* expected server name yields a different one.
|
|
11
|
+
*
|
|
12
|
+
* @param tls - the TLS configuration, as accepted by {@link IMQOptions.tls}
|
|
13
|
+
* @returns a hex digest identifying the configuration
|
|
14
|
+
*/
|
|
15
|
+
export declare function tlsFingerprint(tls: boolean | TlsOptions): string;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Helper: tlsFingerprint
|
|
3
|
+
*
|
|
4
|
+
* I'm Queue Software Project
|
|
5
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
6
|
+
*
|
|
7
|
+
* This program is free software: you can redistribute it and/or modify
|
|
8
|
+
* it under the terms of the GNU General Public License as published by
|
|
9
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
* (at your option) any later version.
|
|
11
|
+
*
|
|
12
|
+
* This program is distributed in the hope that it will be useful,
|
|
13
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
* GNU General Public License for more details.
|
|
16
|
+
*
|
|
17
|
+
* You should have received a copy of the GNU General Public License
|
|
18
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
19
|
+
*
|
|
20
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
21
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
22
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
23
|
+
*/
|
|
24
|
+
import { sha1 } from './sha1.js';
|
|
25
|
+
/**
|
|
26
|
+
* Renders an arbitrary TLS option value as a stable string, so that two
|
|
27
|
+
* structurally identical configurations built independently produce the same
|
|
28
|
+
* text and two differing ones do not.
|
|
29
|
+
*
|
|
30
|
+
* @param value - the option value to render
|
|
31
|
+
* @returns a deterministic textual form of the value
|
|
32
|
+
*/
|
|
33
|
+
function canonical(value) {
|
|
34
|
+
if (value === null) {
|
|
35
|
+
return 'null';
|
|
36
|
+
}
|
|
37
|
+
if (value === undefined) {
|
|
38
|
+
return 'undefined';
|
|
39
|
+
}
|
|
40
|
+
if (typeof value === 'function') {
|
|
41
|
+
// a verifier or a PSK callback is part of the security posture: two
|
|
42
|
+
// connections differing only in it must not be pooled together
|
|
43
|
+
return `fn:${sha1(value.toString())}`;
|
|
44
|
+
}
|
|
45
|
+
if (typeof value !== 'object') {
|
|
46
|
+
return JSON.stringify(value);
|
|
47
|
+
}
|
|
48
|
+
if (ArrayBuffer.isView(value)) {
|
|
49
|
+
const view = value;
|
|
50
|
+
return `bin:${sha1(Buffer.from(view.buffer, view.byteOffset, view.byteLength).toString('base64'))}`;
|
|
51
|
+
}
|
|
52
|
+
if (value instanceof ArrayBuffer) {
|
|
53
|
+
return `bin:${sha1(Buffer.from(value).toString('base64'))}`;
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(value)) {
|
|
56
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
57
|
+
}
|
|
58
|
+
const proto = Object.getPrototypeOf(value);
|
|
59
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
60
|
+
// an opaque host object - a SecureContext, an Agent - has no readable
|
|
61
|
+
// structure to compare, so it is rendered by type alone. Two distinct
|
|
62
|
+
// instances of the same class therefore collide; pass the material
|
|
63
|
+
// itself rather than a prebuilt context if that matters.
|
|
64
|
+
return `obj:${value.constructor?.name || 'unknown'}`;
|
|
65
|
+
}
|
|
66
|
+
const entries = Object.entries(value)
|
|
67
|
+
.filter(([, item]) => item !== undefined)
|
|
68
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
69
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`);
|
|
70
|
+
return `{${entries.join(',')}}`;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Computes a stable fingerprint of a TLS configuration, used to keep
|
|
74
|
+
* connections that differ in their transport security out of the same
|
|
75
|
+
* connection pool slot.
|
|
76
|
+
*
|
|
77
|
+
* Two configurations that are equal by value share a fingerprint, so pooling
|
|
78
|
+
* still works across independently built option literals. Any difference in
|
|
79
|
+
* the trust anchors, the client certificate, the verification callbacks or the
|
|
80
|
+
* expected server name yields a different one.
|
|
81
|
+
*
|
|
82
|
+
* @param tls - the TLS configuration, as accepted by {@link IMQOptions.tls}
|
|
83
|
+
* @returns a hex digest identifying the configuration
|
|
84
|
+
*/
|
|
85
|
+
export function tlsFingerprint(tls) {
|
|
86
|
+
return sha1(canonical(tls === true ? {} : tls));
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=tlsFingerprint.js.map
|
package/src/index.d.ts
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
*/
|
|
22
22
|
export * from './profile.js';
|
|
23
23
|
export * from './redis.js';
|
|
24
|
+
export { envTls } from './helpers/envTls.js';
|
|
25
|
+
export { tlsFingerprint } from './helpers/tlsFingerprint.js';
|
|
24
26
|
export * from './IMQMode.js';
|
|
25
27
|
export * from './IMessageQueue.js';
|
|
26
28
|
export * from './RedisQueue.js';
|
package/src/index.js
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
*/
|
|
22
22
|
export * from './profile.js';
|
|
23
23
|
export * from './redis.js';
|
|
24
|
+
export { envTls } from './helpers/envTls.js';
|
|
25
|
+
export { tlsFingerprint } from './helpers/tlsFingerprint.js';
|
|
24
26
|
export * from './IMQMode.js';
|
|
25
27
|
export * from './IMessageQueue.js';
|
|
26
28
|
export * from './RedisQueue.js';
|
package/src/redis.d.ts
CHANGED
|
@@ -34,6 +34,12 @@ export interface IRedisClient extends Redis {
|
|
|
34
34
|
* runs at most once per connection. Not part of the supported API.
|
|
35
35
|
*/
|
|
36
36
|
__ready__?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Internal flag marking a connection whose socket has been given a durable
|
|
39
|
+
* `error` listener, so that the guard is installed at most once per
|
|
40
|
+
* connection. Not part of the supported API.
|
|
41
|
+
*/
|
|
42
|
+
__guarded__?: boolean;
|
|
37
43
|
/**
|
|
38
44
|
* Internal marker stamped on every Redis connection created by the queue,
|
|
39
45
|
* identifying it as imq-owned. Currently written but not read by the
|