@imqueue/core 3.4.2 → 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.
@@ -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
@@ -29,4 +29,6 @@ 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';
@@ -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
package/CLAUDE.md DELETED
@@ -1,2 +0,0 @@
1
- See [AGENTS.md](./AGENTS.md) for build, test, layout and the invariants to
2
- respect when working on `@imqueue/core`. End-user docs: https://imqueue.org/.