@imqueue/rpc 3.8.0 → 3.9.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/AGENTS.md CHANGED
@@ -46,7 +46,8 @@ describes itself and its client is generated from that description.
46
46
  ```bash
47
47
  npm install
48
48
  npm run build # build ../core (if present) + clean + tsc
49
- npm test # build + node:test over every test/**/*.spec.js
49
+ npm test # build + node:test over test/**/*.spec.js, minus test/integration
50
+ npm run test-integration # build + test/integration/**/*.spec.js (real redis)
50
51
  npm run lint # oxlint
51
52
  npm run format # oxfmt (write) | npm run format:check (verify)
52
53
  npm run test-coverage # tests + experimental coverage
@@ -57,6 +58,24 @@ Tests use the native `node:test` runner with
57
58
  15s. A local Redis on `localhost:6379` is expected for the integration-style
58
59
  specs.
59
60
 
61
+ **`test/integration/` is different, and must stay outside `npm test`.** Those
62
+ specs run *unmocked* — the preload replaces `ioredis` wholesale, which is fine
63
+ for every option except `tls`, whose whole point is a handshake a mock does not
64
+ perform. `test/integration/tlsBroker.ts` issues a throwaway CA and certificates
65
+ with `openssl`, then starts `redis-server` on a port picked at run time with
66
+ `--port 0 --tls-port <n>`: with no plaintext listener at all, a connection that
67
+ reaches it has demonstrably gone over TLS.
68
+
69
+ **They skip, never fail, when the machine cannot host a broker.**
70
+ `startTlsBroker()` returns a reason string instead of throwing when
71
+ `redis-server` or `openssl` is missing, or when redis will not start with TLS,
72
+ and that reason becomes the suite's `skip`. CI has no redis and must stay
73
+ green, so keep that contract: report a skip reason, do not throw, keep the
74
+ `npm test` glob excluding `test/integration`, and do not add these specs to a
75
+ runner CI invokes. The harness is a copy of the one in `@imqueue/core` — a
76
+ package's `test/` is not published, so there is nothing to import; keep the two
77
+ in step.
78
+
60
79
  ## Layout
61
80
 
62
81
  | Path | Role |
package/CHANGELOG.md CHANGED
@@ -14,6 +14,28 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
14
14
 
15
15
  ### Added
16
16
 
17
+ - **TLS on the cache connection.** `RedisCache.init()` now honours `tls`, which
18
+ it inherited from the queue option shape and silently ignored. `true`
19
+ connects with Node's defaults, an object is handed to `tls.connect()` as
20
+ given, so a private CA and mutual TLS both work — and with it unset the
21
+ `IMQ_REDIS_TLS*` environment variables are consulted, so one setting encrypts
22
+ a service's queues and its method cache together. Requires `@imqueue/core`
23
+ 3.5.0, which is where the option became real.
24
+
25
+ Covered by integration specs in `test/integration/`, run by
26
+ `npm run test-integration`, which stand up a throwaway TLS-only redis and
27
+ assert what a mocked `ioredis` cannot: that the handshake completes and is
28
+ verified, that a cached value survives a round trip over it, and that
29
+ plaintext, an unverifiable certificate and a wrong server name are refused
30
+ rather than downgraded. They skip themselves, with a reason, wherever
31
+ `redis-server` and `openssl` are not both available, so a checkout without
32
+ redis still passes; `npm test` excludes them and is unchanged in what it runs.
33
+
34
+ The shared connection is still opened once per process and the first
35
+ initialization still decides its transport. What is new is that a later one
36
+ asking for a different transport is told so, rather than silently handed an
37
+ encrypted connection when it asked for plaintext or, worse, the reverse.
38
+
17
39
  - **Opt-in graceful shutdown draining.** With `IMQ_DRAIN_ENABLE=1` — or the new
18
40
  `drain` service option — `SIGTERM` and `SIGINT` now stop consuming, wait for
19
41
  the requests already being handled, publish their replies, tear the transport
package/README.md CHANGED
@@ -261,6 +261,33 @@ Because standard decorators provide no runtime type reflection (there is no
261
261
  and `removeComments` must remain `false` so those comments survive compilation.
262
262
  Undocumented parameters fall back to `any` in generated clients.
263
263
 
264
+ ## Encrypting the method cache
265
+
266
+ `RedisCache` opens its own connection to Redis, separate from the queue's, and
267
+ it takes the same `tls` option:
268
+
269
+ ```typescript
270
+ import { IMQCache, RedisCache } from '@imqueue/rpc';
271
+ import { readFileSync } from 'node:fs';
272
+
273
+ IMQCache.register(RedisCache, {
274
+ prefix: 'my-service',
275
+ tls: { ca: readFileSync('/etc/redis-tls/ca.crt') },
276
+ });
277
+ ```
278
+
279
+ With `tls` unset the `IMQ_REDIS_TLS*` environment variables are consulted — the
280
+ same ones `@imqueue/core` reads — so one setting encrypts a service's queues
281
+ and its method cache together. Pass `false` to decline that fallback.
282
+
283
+ Two things to know about the connection itself. It is opened **once per
284
+ process** and shared by every `RedisCache` instance, so the first
285
+ initialization decides its transport; a later one asking for something
286
+ different is warned rather than silently given what already exists. And `conn`
287
+ still lets a service hand the cache a connection it already has — a running
288
+ queue's writer, for example — in which case the cache inherits whatever
289
+ transport that connection was opened with.
290
+
264
291
  ## Graceful shutdown
265
292
 
266
293
  By default a service signalled mid-request abandons it: the signal handler
package/index.d.ts CHANGED
@@ -21,7 +21,9 @@
21
21
  */
22
22
  /**
23
23
  * Type-safe RPC over a message queue — services, clients and the decorators that
24
- * describe them, built on `@imqueue/core`.
24
+ * describe them, built on `@imqueue/core`. An exposed method's JSDoc is the
25
+ * runtime type source, so consuming projects must compile with
26
+ * `removeComments: false`.
25
27
  *
26
28
  * Write a service by extending `IMQService` and marking each remotely callable
27
29
  * method with `@expose()`. Complex argument and return types need a class-level
package/index.js CHANGED
@@ -21,7 +21,9 @@
21
21
  */
22
22
  /**
23
23
  * Type-safe RPC over a message queue — services, clients and the decorators that
24
- * describe them, built on `@imqueue/core`.
24
+ * describe them, built on `@imqueue/core`. An exposed method's JSDoc is the
25
+ * runtime type source, so consuming projects must compile with
26
+ * `removeComments: false`.
25
27
  *
26
28
  * Write a service by extending `IMQService` and marking each remotely callable
27
29
  * method with `@expose()`. Complex argument and return types need a class-level
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/rpc",
3
- "version": "3.8.0",
3
+ "version": "3.9.1",
4
4
  "description": "Type-safe RPC framework for Node.js & TypeScript microservices over a Redis message queue — self-describing services generate their own strongly-typed clients (@imqueue framework)",
5
5
  "keywords": [
6
6
  "redis",
@@ -27,10 +27,11 @@
27
27
  "lint": "oxlint",
28
28
  "format": "oxfmt \"index.ts\" \"debug.ts\" \"src/**/*.ts\" \"test/**/*.ts\"",
29
29
  "format:check": "oxfmt --check \"index.ts\" \"debug.ts\" \"src/**/*.ts\" \"test/**/*.ts\"",
30
- "test": "npm run build && node --experimental-test-module-mocks --import ./test/warmup.mjs --test --test-timeout=15000 $(find test -name '*.spec.js')",
31
- "test-coverage": "npm run build && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-timeout=15000 $(find test -name '*.spec.js')",
32
- "test-lcov": "npm run build && mkdir -p coverage && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --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",
30
+ "test": "npm run build && node --experimental-test-module-mocks --import ./test/warmup.mjs --test --test-timeout=15000 $(find test -name '*.spec.js' -not -path 'test/integration/*')",
31
+ "test-coverage": "npm run build && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-timeout=15000 $(find test -name '*.spec.js' -not -path 'test/integration/*')",
32
+ "test-lcov": "npm run build && mkdir -p coverage && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-timeout=15000 $(find test -name '*.spec.js' -not -path 'test/integration/*'); node scripts/strip-comment-coverage.mjs coverage/lcov.info",
33
33
  "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\"",
34
+ "test-integration": "npm run build && node --test --test-timeout=60000 $(find test/integration -name '*.spec.js')",
34
35
  "test-dev": "npm run test && npm run clean-js && npm run clean-typedefs && npm run clean-maps",
35
36
  "clean-typedefs": "find . -name '*.d.ts' -not -wholename '*node_modules*' -not -wholename '*generator*' -type f -delete",
36
37
  "clean-maps": "find . -name '*.js.map' -not -wholename '*node_modules*' -not -wholename '*generator*' -type f -delete",
@@ -51,7 +52,7 @@
51
52
  "author": "imqueue.com <support@imqueue.com> (https://imqueue.com)",
52
53
  "license": "GPL-3.0-only",
53
54
  "dependencies": {
54
- "@imqueue/core": "^3.4.3",
55
+ "@imqueue/core": "^3.5.0",
55
56
  "acorn": "^8.17.0",
56
57
  "typescript": "^7.0.2"
57
58
  },
@@ -28,8 +28,14 @@ import { type ICache } from './index.js';
28
28
  *
29
29
  * @remarks
30
30
  * This inherits the queue option shape, but the adapter only honours `host`,
31
- * `port`, `username`, `password`, `prefix`, `logger` and `conn`. All other
32
- * inherited queue options are accepted by the type and silently ignored.
31
+ * `port`, `username`, `password`, `tls`, `prefix`, `logger` and `conn`. All
32
+ * other inherited queue options are accepted by the type and silently ignored.
33
+ *
34
+ * `tls` encrypts the cache connection exactly as it encrypts a queue's: `true`
35
+ * for Node's defaults, an object handed to `tls.connect()` as given, and when
36
+ * omitted the `IMQ_REDIS_TLS*` environment variables are consulted, so a
37
+ * deployment can encrypt its caches and its queues with one setting. Pass
38
+ * `false` to decline that fallback.
33
39
  */
34
40
  export interface IRedisCacheOptions extends Partial<IMQOptions> {
35
41
  /**
@@ -61,6 +67,7 @@ export declare const REDIS_CLIENT_INIT_ERROR = "Redis client is not initialized!
61
67
  */
62
68
  export declare class RedisCache implements ICache {
63
69
  private static redis?;
70
+ private static tlsPrint?;
64
71
  private static initPromise?;
65
72
  private logger;
66
73
  /**
@@ -21,7 +21,7 @@
21
21
  * purchase a proprietary commercial license. Please contact us at
22
22
  * <support@imqueue.com> to get commercial licensing options.
23
23
  */
24
- import { DEFAULT_IMQ_OPTIONS, Redis, } from '@imqueue/core';
24
+ import { DEFAULT_IMQ_OPTIONS, envTls, Redis, tlsFingerprint, } from '@imqueue/core';
25
25
  import { hostname } from 'node:os';
26
26
  import {} from './index.js';
27
27
  /**
@@ -47,6 +47,11 @@ export const REDIS_CLIENT_INIT_ERROR = 'Redis client is not initialized!';
47
47
  */
48
48
  export class RedisCache {
49
49
  static redis;
50
+ // fingerprint of the TLS configuration the shared connection was opened
51
+ // with, so a later init() asking for a different one can be told that it
52
+ // is getting the existing connection rather than the transport it asked
53
+ // for. Absent when the shared connection is plaintext.
54
+ static tlsPrint;
50
55
  // pending shared connection attempt; concurrent init() calls await this
51
56
  // single promise instead of opening one connection each
52
57
  static initPromise;
@@ -87,12 +92,50 @@ export class RedisCache {
87
92
  ...options,
88
93
  };
89
94
  this.logger = this.options.logger || console;
95
+ if (this.options.tls === undefined) {
96
+ // an unreadable CA or client key throws out of here rather than
97
+ // yielding a cache that would quietly talk to redis in the clear
98
+ const fromEnv = envTls();
99
+ if (fromEnv !== undefined) {
100
+ // assigned only when the environment actually asks for TLS, so
101
+ // that a cache nobody configured for it carries no `tls` key at
102
+ // all and `options` keeps exactly the shape it always had
103
+ this.options.tls = fromEnv;
104
+ }
105
+ }
106
+ const tlsPrint = this.options.tls
107
+ ? tlsFingerprint(this.options.tls)
108
+ : undefined;
109
+ if (this.options.tls &&
110
+ this.options.tls !== true &&
111
+ this.options.tls.rejectUnauthorized === false) {
112
+ this.logger.warn('%s: TLS certificate verification is disabled for the cache' +
113
+ ' connection to %s:%s — it is encrypted but the server is' +
114
+ ' not authenticated, so it is open to interception', this.name, this.options.host, this.options.port);
115
+ }
90
116
  if (RedisCache.redis && !RedisCache.initPromise) {
117
+ // the connection is process-wide and the first caller's transport
118
+ // is what every later one gets. Silently handing a caller that
119
+ // asked for TLS a plaintext connection - or the reverse - is the
120
+ // one case where that is worth saying out loud
121
+ if (tlsPrint !== RedisCache.tlsPrint) {
122
+ this.logger.warn('%s: re-using the existing %s cache connection, which is' +
123
+ ' not the transport these options asked for — the' +
124
+ ' first initialization in a process decides it', this.name, RedisCache.tlsPrint ? 'encrypted' : 'plaintext');
125
+ }
91
126
  this.ready = true;
92
127
  return this;
93
128
  }
94
129
  if (this.options.conn && !RedisCache.initPromise) {
95
130
  this.logger.info('Re-using given connection for cache.');
131
+ // the caller's own connection brings its transport with it, so
132
+ // read the fingerprint off the client rather than off the options
133
+ // this adapter was handed - otherwise a reused TLS connection
134
+ // would be reported as plaintext to whoever initializes next. It
135
+ // comes from outside this package and need not be a full client,
136
+ // so read through it rather than assume the option bag is there.
137
+ const given = this.options.conn.options?.tls;
138
+ RedisCache.tlsPrint = given ? tlsFingerprint(given) : undefined;
96
139
  RedisCache.redis = this.options.conn;
97
140
  this.ready = true;
98
141
  return this;
@@ -100,11 +143,19 @@ export class RedisCache {
100
143
  if (!RedisCache.initPromise) {
101
144
  RedisCache.initPromise = new Promise((resolve, reject) => {
102
145
  const connectionName = `${this.options.prefix}:${this.name}:pid:${process.pid}:host:${hostname()}`;
146
+ RedisCache.tlsPrint = tlsPrint;
103
147
  RedisCache.redis = new Redis({
104
148
  port: Number(this.options.port),
105
149
  host: String(this.options.host),
106
150
  username: this.options.username,
107
151
  password: this.options.password,
152
+ ...(this.options.tls
153
+ ? {
154
+ tls: this.options.tls === true
155
+ ? {}
156
+ : this.options.tls,
157
+ }
158
+ : {}),
108
159
  connectionName,
109
160
  });
110
161
  RedisCache.redis.on('ready', () => {
@@ -215,6 +266,7 @@ export class RedisCache {
215
266
  */
216
267
  static async destroy() {
217
268
  RedisCache.initPromise = undefined;
269
+ RedisCache.tlsPrint = undefined;
218
270
  try {
219
271
  if (RedisCache.redis) {
220
272
  RedisCache.redis.removeAllListeners();