@onlineapps/conn-infra-secrets 2.0.0 → 3.0.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/CHANGELOG.md CHANGED
@@ -4,6 +4,101 @@ All notable changes to this package. Follows [Keep a Changelog](https://keepacha
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [3.0.0] — 2026-09-16
8
+
9
+ ### Changed — BREAKING
10
+
11
+ - **The Redis credential and topology come from `redisUrl`, and from nothing else.** The constructor reads `username` (Redis 6 ACL), `password`, host, port and the database index off the URL — `redis://[user:password@]host:port[/db]`, `rediss://` for TLS — decoding percent-escapes exactly once. An absent userinfo means no AUTH at all: `username`/`password` are then not passed to ioredis, never as `''`, which would be sent as `AUTH ""`.
12
+ Measured reason (INFRA, dev, 2026-09-15 21:20Z): the constructor took `hostname`/`port` only and expected the password beside the URL, so a URL carrying userinfo lost it — ioredis connected without AUTH, the gateway went into a crash loop (RestartCount 51) and the dispatcher and ingest failed on their first secret read. `REDIS_URL` is the platform's one rail for this fact (INFRA-DOCS 2026-09-14; `service-common` 3.0.2 hands the whole URL to node-redis, `mq-client-core` 3.2.0 reads the credential off the URL), so a value beside it was a second rail — `.claude/rules/change-discipline.md` § One rail per concern.
13
+ - **A `redisUrl` that is not a `redis:`/`rediss:` URL is refused at construction**, as is one without a host or without a port. The silent branch that treated such a value as the hostname and defaulted the port to `6379` is gone: it hardcoded topology (principle 2) behind a fallback (principle 3), and it is what let a misspelt value reach a live boot. No message echoes the URL or the refused value — both carry the password.
14
+
15
+ ### Removed
16
+
17
+ - **`config.password`** — refused by name, not ignored (a retired option that is silently dropped leaves the caller believing a password reached the server). Four questions, `.claude/rules/change-discipline.md` § Removing: (1) it came to exist because the constructor read only host and port off the URL, so a Redis with `requirepass` needed the password from somewhere — `ServiceWrapper` began setting it on 2026-09-11; (2) no part of the concept carried it: the platform decision is that `REDIS_URL` carries endpoint AND credential, and it never sanctioned a second input; (3) after this change nothing reads it — the two callers that set it (`api/shared/connector/service-wrapper/src/ServiceWrapper.js`, `api_biz/ingest/scripts/lib/build-operator-context.js`) each re-derive the value from the very same URL, a copy of the parse rather than a second source; (4) the replacement is more conceptual — one rail, one parse, and a URL with userinfo can no longer lose its password without a word.
18
+ - **`config.db`** — refused by name; the database index is the URL's path. Four questions: (1) it came to exist as `config.db || 0`, so a caller could select a database; (2) nothing in the concept carried it — no platform document declares a non-default database for the SecretBox projection; (3) zero callers pass a value: only `ServiceWrapper` forwards `secretsConfig.db`, which no service config declares (`api_biz/ingest/config/service/config.json` has `"secrets": { "enabled": true }`); (4) the path is more conceptual — the database belongs to the address, and `|| 0` additionally swallowed a malformed declaration into a 0 nobody asked for. With no path declared the connector passes no `db` at all and ioredis selects its own default, database 0 — named here rather than re-implemented.
19
+
20
+ ### Added
21
+
22
+ - `tests/integration/redisAuthFromUrl.integration.test.js` — a throwaway `redis:7-alpine` with `requirepass` on an ephemeral loopback port (the shared dev cache runs without one and cannot answer this question): the happy path reads a real sealed secret back through an authenticated connection, the failure path shows the same URL without the password refused with `NOAUTH`, and the control case proves the server still required AUTH after the green run.
23
+
24
+ ### Changed — a failed `connect()` carries the server's verdict (d.566)
25
+
26
+ `connect()` handed the caller ioredis's end-of-socket sentence — `Connection is closed.`,
27
+ no context, no `cause`, no verdict — while the server's own answer reached `_lastError`
28
+ and the log alone. Measured against a `redis:7-alpine --requirepass` on 2026-09-16: a URL
29
+ without the password (`NOAUTH Authentication required.`), a URL with the wrong password
30
+ (`WRONGPASS invalid username-password pair or user is disabled.`) and a port with no
31
+ listener (`connect ECONNREFUSED …`) produced byte-identical caller errors. That is why dev
32
+ incident B88 (gateway crash loop, RestartCount 51) could not be read from the error at all.
33
+
34
+ The caller is now told which of two things happened:
35
+
36
+ - the server **ANSWERED and refused** — `NOAUTH`, `WRONGPASS`, `NOPERM`. The message
37
+ quotes the server's sentence and names the credential in `REDIS_URL` as the fix, and the
38
+ server's error travels as `cause`.
39
+ - the server **never answered** — the message says exactly that, quotes what the client
40
+ rejected with, and adds that a refused credential answers NOAUTH/WRONGPASS/NOPERM and is
41
+ reported as such, so this is not one. That error travels as `cause`.
42
+
43
+ It is the rule `@onlineapps/mq-client-core` d.295 states for a broker refusal (403/530/406),
44
+ on the same reasoning: an ANSWERED refusal is permanent, because the next attempt asks the
45
+ same question and gets the same answer.
46
+
47
+ So a refusal also **ends the attempts**, and a failed attempt takes its client with it.
48
+ Measured on all three failure paths: ioredis was left in status `reconnecting` after
49
+ `connect()` rejected, so a credential the server had already refused was asked again on a
50
+ loop, and the connector — which never sets `connected` on a later reconnect — would never
51
+ have used that socket anyway. A refusal on the `error` channel now disconnects the client
52
+ at once, and every failed `connect()` drops it.
53
+
54
+ Only the endpoint (`host:port`) is named in these messages, never the URL: this package
55
+ keeps the parsed fields and drops the value precisely because the value carries the
56
+ password.
57
+
58
+ ### Added (d.566)
59
+
60
+ - `tests/unit/connectVerdict.test.js` — both sentences asserted whole, the `cause` as a
61
+ value, no part of the credential in either, the refusal that ends the attempts, and two
62
+ controls (an accepted `connect()` still resolves `true` and keeps its client; a
63
+ transport error after the connection is open is NOT treated as a refusal).
64
+ - `tests/integration/redisAuthFromUrl.integration.test.js` grew the two failure paths this
65
+ change is about — a wrong password named `WRONGPASS` with no part of it echoed, and a
66
+ port with no listener reported as "no verdict" with `cause.code` `ECONNREFUSED` — and
67
+ its NOAUTH path now asserts the verdict the caller gets instead of `Connection is
68
+ closed.`. The error-message census moved 31 → 33.
69
+
70
+ ### Fixed — a store that comes back is read again (d.573)
71
+
72
+ `connected` was written once, when `connect()` resolved, and never read off the client
73
+ again. The connector therefore had no idea what the client was doing: a Redis that went
74
+ away mid-run left the flag `true`, so `get()` handed the read to a client with no socket
75
+ instead of naming the missing store — and nothing could ever put the flag back, because
76
+ the reconnection ioredis performs on its own was not watched. One outage decided the fate
77
+ of every secret read for the rest of the process's life.
78
+
79
+ `connected` is now the client's READY state — socket open, AUTH and SELECT done — one rail
80
+ with `@onlineapps/conn-base-cache` d.572: `ready` sets it, `close` and `end` take it down,
81
+ the next `ready` puts it back. Every handler acts only for the client this connector still
82
+ holds, so the verdict of d.566 stays exactly as terminal as it was: a client the server
83
+ refused is discarded, and nothing it emits afterwards can put the connector back in
84
+ service behind the caller's back.
85
+
86
+ ### Tests (d.573)
87
+
88
+ Unit 177 → 182, integration 26 → 28. New `tests/unit/connectionLifecycle.test.js` asserts
89
+ the state machine as values: the read that reaches the store answers `SECRET_NOT_FOUND`,
90
+ the one after a `close` answers `SECRET_STORE_UNAVAILABLE` and never touches the client,
91
+ and the flag through an outage reads `[true, false, true]` (it read `[true, true, true]`
92
+ before the fix), with `end` as a second way down and a refusal that survives a `ready`
93
+ from its discarded client as the control. New
94
+ `tests/integration/reconnect.integration.test.js` asks a real server: its own
95
+ `redis:7` container on a fixed loopback port, a value sealed and read back, `docker stop`
96
+ → `SECRET_STORE_UNAVAILABLE`, `docker start` → the same read succeeds, each step waited
97
+ for on the client's own `close`/`ready` event rather than on a guessed delay, with a
98
+ `WRONGPASS` refusal as the control that stays terminal.
99
+
100
+ ## [2.0.0] — 2026-09-14
101
+
7
102
  ### Changed — BREAKING
8
103
 
9
104
  - **`SECRETS_MASTER_KEYS` replaces `SECRETS_MASTER_KEY`**: the package reads an ordered LIST of master keys (`<key_id>:<base64 key>[,…]`). The first key seals every new write; every key in the list opens what it sealed, selected by the blob's `key_id`. A blob naming a key that is not in the list is refused with `SECRET_KEY_UNKNOWN` — there is no "try every key" pass. `SecretsConnector` takes `masterKeys` instead of `masterKeyBase64` (owner decision 2026-09-14, `docs/governance/confirmations/secretbox-master-keys.md` 001).
package/README.md CHANGED
@@ -96,6 +96,24 @@ await secrets.connect();
96
96
  Handlers only ever call `ctx.secrets.get(ref)`; the ContextBuilder facade injects
97
97
  the invocation scope.
98
98
 
99
+ **The Redis credential lives in the URL and nowhere else.** `redisUrl` carries the
100
+ endpoint, the optional Redis 6 ACL user, the password and the database index —
101
+ `redis://[user:password@]host:port[/db]`, `rediss://` for TLS — exactly as
102
+ `service-common` and `mq-client-core` read it. Percent-encode a password that
103
+ contains `@`, `:` or `/`. The options `password` and `db` beside the URL are
104
+ **refused by name**: they were a second rail for a fact the URL already carries,
105
+ and while they existed a URL with userinfo lost its password silently (INFRA, dev,
106
+ 2026-09-15: ioredis connected without AUTH, gateway crash loop, RestartCount 51).
107
+ A value that is not a `redis:`/`rediss:` URL, or one without a host or a port, is
108
+ refused at construction — this package declares no topology default, not even 6379.
109
+
110
+ **A failed `connect()` says what the server answered.** A server that ANSWERED and
111
+ refused the credential — `NOAUTH`, `WRONGPASS`, `NOPERM` — is permanent: the message
112
+ quotes the server's sentence, names `REDIS_URL` as the fix, carries the original error
113
+ as `cause`, and the attempts END there rather than looping on a question already
114
+ answered. A server that never answered is reported as exactly that and may be retried.
115
+ Only `host:port` appears in these messages; the URL carries the password.
116
+
99
117
  ## Public API
100
118
  ```js
101
119
  const SecretsConnector = require('@onlineapps/conn-infra-secrets'); // default = the connector
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onlineapps/conn-infra-secrets",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "Secret resolution connector for ctx.secrets.get(ref) — reads the SecretBox Redis projection and decrypts in-process (AES-256-GCM)",
5
5
  "oa": {
6
6
  "category": "connector"
package/src/index.js CHANGED
@@ -39,6 +39,42 @@ const { normalizeWorkspaceId } = require('./workspaceId');
39
39
  // Meta owns the projection; its StateConnector prefixes keys with `state:meta:`.
40
40
  const DEFAULT_KEY_PREFIX = 'state:meta:secret:';
41
41
 
42
+ /**
43
+ * The sentences with which a Redis server ANSWERS a connection attempt and
44
+ * REFUSES it — an answer, not a silence:
45
+ *
46
+ * NOAUTH the server requires AUTH and this connection sent none
47
+ * WRONGPASS the credential the URL carries is not the server's
48
+ * NOPERM the ACL user the URL names may not run the command
49
+ *
50
+ * The distinction is the one `@onlineapps/mq-client-core` draws for a broker
51
+ * (`_isBrokerRefusal()`, reply codes 403/530/406, d.295): an ANSWERED refusal is
52
+ * permanent — the next attempt asks the same question and gets the same answer,
53
+ * so the attempts end and the caller is told what the server said. Anything else
54
+ * is transient by design: nobody answered, and giving up forever on a server that
55
+ * may come back is a different defect.
56
+ *
57
+ * The list holds only sentences a live Redis 6/7 actually sends on this path:
58
+ * NOAUTH and WRONGPASS were measured against `redis:7-alpine --requirepass`
59
+ * (2026-09-16), NOPERM is the same class for the ACL user the URL may name. Redis
60
+ * 5's `ERR invalid password` is deliberately absent — the platform runs Redis 7,
61
+ * and a ban nothing can trigger is silence pretending to be coverage
62
+ * (`automation-gates.md` §5). `ERR Client sent AUTH, but no password is set` is
63
+ * absent for the same reason: ioredis warns on it and does not fail the
64
+ * connection (`ioredis/built/redis/event_handler.js`, `connectHandler`).
65
+ */
66
+ const SERVER_REFUSAL_PREFIXES = ['NOAUTH', 'WRONGPASS', 'NOPERM'];
67
+
68
+ /**
69
+ * Did the server answer and refuse?
70
+ * @param {Error|null|undefined} err
71
+ * @returns {boolean}
72
+ */
73
+ function isServerRefusal(err) {
74
+ if (!err || typeof err.message !== 'string') return false;
75
+ return SERVER_REFUSAL_PREFIXES.some((prefix) => err.message.startsWith(prefix));
76
+ }
77
+
42
78
  class SecretResolutionError extends Error {
43
79
  constructor(code, message, options) {
44
80
  super(message, options);
@@ -84,39 +120,247 @@ function projectionKey(tenantId, workspaceId, ref, keyPrefix = DEFAULT_KEY_PREFI
84
120
  return `${keyPrefix}${tenantId}:${workspaceSegment(workspaceId)}:${ref}`;
85
121
  }
86
122
 
123
+ // `REDIS_URL` is the platform's single rail for the Redis endpoint AND its
124
+ // credential (`service-common` 3.0.2 hands the whole URL to node-redis;
125
+ // `mq-client-core` 3.2.0 reads the credential off the URL). Anything else this
126
+ // package might accept beside it would be a second rail for the same fact.
127
+ const REDIS_URL_PROTOCOLS = new Set(['redis:', 'rediss:']);
128
+
129
+ /**
130
+ * Options beside `redisUrl` that used to carry a fact the URL already carries.
131
+ * They are REFUSED by name rather than ignored: an ignored option looks accepted
132
+ * and leaves the caller believing a password reached the server
133
+ * (`.claude/rules/change-discipline.md` § One rail per concern; principle 11,
134
+ * clean break — no shim that keeps reading them).
135
+ */
136
+ const RETIRED_OPTIONS = {
137
+ password: 'the Redis password comes from the userinfo of redisUrl (redis://user:password@host:port)',
138
+ db: 'the Redis database index comes from the path of redisUrl (redis://host:port/3)'
139
+ };
140
+
141
+ function refuseRetiredOptions(config) {
142
+ for (const [name, replacement] of Object.entries(RETIRED_OPTIONS)) {
143
+ if (config[name] === undefined) continue;
144
+ throw new Error(
145
+ `[conn-infra-secrets] Option "${name}" is not accepted - ${replacement}. `
146
+ + `Fix: drop "${name}" from the SecretsConnector config and put the value in REDIS_URL `
147
+ + '(api/config/env-active/shared.env); a value beside the URL is a second rail for a fact '
148
+ + 'the URL already carries. The refused value is not echoed here.'
149
+ );
150
+ }
151
+ }
152
+
153
+ /**
154
+ * The database index the URL declares, or `null` when it declares none.
155
+ *
156
+ * No path (`redis://h:6379`) and an empty path (`redis://h:6379/`) declare
157
+ * nothing, and the connector then passes no `db` at all — ioredis selects its own
158
+ * default, database 0. That default belongs to ioredis and is named here rather
159
+ * than re-implemented as `config.db || 0`, which would also swallow a malformed
160
+ * declaration into a 0 nobody asked for (principle 3, No Fallbacks).
161
+ */
162
+ function databaseFromPath(pathname) {
163
+ const declared = String(pathname || '').replace(/^\//, '');
164
+ if (declared === '') return null;
165
+ if (!/^\d+$/.test(declared)) {
166
+ throw new Error(
167
+ `[conn-infra-secrets] redisUrl declares database "${declared}" - Expected a non-negative `
168
+ + 'integer as the URL path, e.g. redis://host:6379/3. Fix: correct the path of REDIS_URL in '
169
+ + 'shared.env, or drop it to use the default database.'
170
+ );
171
+ }
172
+ return Number.parseInt(declared, 10);
173
+ }
174
+
175
+ /**
176
+ * Build the ioredis options from the URL — endpoint, ACL user and password alike.
177
+ *
178
+ * Measured reason this function exists (INFRA, dev, 2026-09-15 21:20Z): the
179
+ * constructor used to take `hostname`/`port` only and expect the password in a
180
+ * separate `config.password`, so a URL carrying userinfo lost it and ioredis
181
+ * connected without AUTH — gateway crash loop (RestartCount 51), dispatcher and
182
+ * ingest failing on the first secret read.
183
+ *
184
+ * Nothing here echoes the URL or any part of its userinfo: these messages reach
185
+ * logs, and the value carries the password.
186
+ */
187
+ function redisOptionsFromUrl(redisUrl) {
188
+ let parsed;
189
+ try {
190
+ parsed = new URL(redisUrl);
191
+ } catch (err) {
192
+ throw new Error(
193
+ '[conn-infra-secrets] redisUrl is not a URL - Expected redis://[user:password@]host:port[/db] '
194
+ + '(or rediss:// for TLS), the one rail that carries both the endpoint and the credential. '
195
+ + 'Fix: set REDIS_URL in api/config/env-active/shared.env to the full URL; a bare host:port '
196
+ + 'is not accepted. The value is not echoed here because it carries the password.',
197
+ { cause: err }
198
+ );
199
+ }
200
+ if (!REDIS_URL_PROTOCOLS.has(parsed.protocol)) {
201
+ throw new Error(
202
+ `[conn-infra-secrets] redisUrl has scheme "${parsed.protocol}" - Expected redis: or rediss:. `
203
+ + 'Fix: set REDIS_URL in api/config/env-active/shared.env to redis://host:port (rediss:// for TLS).'
204
+ );
205
+ }
206
+ if (!parsed.hostname) {
207
+ throw new Error(
208
+ '[conn-infra-secrets] redisUrl declares no host - Expected redis://host:port. '
209
+ + 'Fix: set REDIS_URL in api/config/env-active/shared.env to the full endpoint.'
210
+ );
211
+ }
212
+ if (!parsed.port) {
213
+ throw new Error(
214
+ '[conn-infra-secrets] redisUrl declares no port - Expected redis://host:port; the port is '
215
+ + 'topology and this package declares no default for it. Fix: set REDIS_URL in '
216
+ + 'api/config/env-active/shared.env to the full endpoint, e.g. redis://api_node_cache:6379.'
217
+ );
218
+ }
219
+
220
+ const options = {
221
+ host: parsed.hostname,
222
+ port: Number.parseInt(parsed.port, 10),
223
+ lazyConnect: true
224
+ };
225
+ // Redis 6 ACL: the URL may name a user as well as a password. An absent one is
226
+ // ABSENT — never `''`, which ioredis would send as `AUTH ""`.
227
+ if (parsed.username) options.username = decodeURIComponent(parsed.username);
228
+ if (parsed.password) options.password = decodeURIComponent(parsed.password);
229
+ const db = databaseFromPath(parsed.pathname);
230
+ if (db !== null) options.db = db;
231
+ return options;
232
+ }
233
+
87
234
  class SecretsConnector {
88
235
  /**
89
236
  * @param {Object} config
90
- * @param {string} config.redisUrl - redis://host:port (required)
237
+ * @param {string} config.redisUrl - `redis://[user:password@]host:port[/db]` or `rediss://…`
238
+ * (required). The URL is the ONLY rail: endpoint, ACL user, password and
239
+ * database index all come off it. `config.password` and `config.db` are
240
+ * refused by name.
91
241
  * @param {string} config.masterKeys - the declared list, `<key_id>:<base64 32-byte key>[,…]`
92
242
  * (required; the value of SECRETS_MASTER_KEYS, first entry = the active key)
93
- * @param {string} [config.password] - Redis password
94
- * @param {number} [config.db=0] - Redis database index
243
+ * @param {string} [config.keyPrefix] - projection key prefix (defaults to the one meta writes)
95
244
  */
96
245
  constructor(config = {}) {
97
246
  if (!config.redisUrl) {
98
247
  throw new Error('[conn-infra-secrets] redisUrl is required - Fix: pass REDIS_URL.');
99
248
  }
249
+ refuseRetiredOptions(config);
100
250
  this._keyring = loadMasterKeys(config.masterKeys);
101
251
  this._keyPrefix = config.keyPrefix || DEFAULT_KEY_PREFIX;
102
252
 
103
- let host = config.redisUrl;
104
- let port = 6379;
105
- if (config.redisUrl.startsWith('redis://')) {
106
- const parsed = new URL(config.redisUrl);
107
- host = parsed.hostname;
108
- port = parseInt(parsed.port, 10) || 6379;
109
- }
110
- this._redisOptions = { host, port, password: config.password, db: config.db || 0, lazyConnect: true };
253
+ this._redisOptions = redisOptionsFromUrl(config.redisUrl);
254
+ // What a message of this package may say about the store: host and port,
255
+ // never the URL. The connector keeps the parsed fields and drops the value
256
+ // precisely because the value carries the password, so there is no URL here
257
+ // to redact — and nothing to redact it with (this package declares one
258
+ // dependency, ioredis).
259
+ this._endpoint = `${this._redisOptions.host}:${this._redisOptions.port}`;
111
260
  this.client = null;
261
+ // Whether the CLIENT is ready — socket open, AUTH and SELECT done. It is not
262
+ // a latch set once by connect(): it follows the client through an outage and
263
+ // back (d.573), one rail with `@onlineapps/conn-base-cache` d.572.
112
264
  this.connected = false;
265
+ this._lastError = null;
113
266
  }
114
267
 
268
+ /**
269
+ * Open the connection, or say what the server answered.
270
+ *
271
+ * Until d.566 this method handed the caller ioredis's end-of-socket sentence —
272
+ * `Connection is closed.`, no `cause`, no verdict — while the server's actual
273
+ * answer reached `_lastError` and nothing else. That is how dev incident B88
274
+ * (gateway crash loop, RestartCount 51) could not be read from the error at
275
+ * all: the log said the socket closed, and the `NOAUTH` that closed it was a
276
+ * field nobody printed.
277
+ *
278
+ * Two outcomes now, told apart by `isServerRefusal()` and said in the caller's
279
+ * error: the server ANSWERED and refused (permanent — the attempts end here),
280
+ * or it never answered (transient — the caller may try again). Either way the
281
+ * original error travels as `cause`, so the stack survives the sentence.
282
+ *
283
+ * A failed attempt also takes its client with it. ioredis keeps retrying in the
284
+ * background after `connect()` rejects — measured 2026-09-16: status
285
+ * `reconnecting` on all three failure paths — so a connector that gives up
286
+ * without disconnecting leaves a socket loop nobody owns, and this one never
287
+ * reports `connected` again for it: the lifecycle handlers below act only for
288
+ * the client this connector still holds, so nothing that client emits after it
289
+ * has been discarded can put the connector back in service.
290
+ *
291
+ * What `connected` means afterwards is the client's own READY state, watched
292
+ * rather than assumed (d.573): a Redis that goes away mid-run takes the flag
293
+ * down, so `get()` names the missing store instead of walking into a client
294
+ * with no socket, and the reconnection ioredis performs on its own puts the
295
+ * flag back. Before d.573 the flag was written once and never read off the
296
+ * client again, so an outage decided the fate of every secret read that
297
+ * followed it.
298
+ *
299
+ * @returns {Promise<true>}
300
+ * @throws {Error} naming the server's verdict, with the original error as `cause`
301
+ */
115
302
  async connect() {
116
303
  if (this.connected) return true;
117
- this.client = new Redis(this._redisOptions);
118
- this.client.on('error', (err) => { /* surfaced on get() */ this._lastError = err; });
119
- await this.client.connect();
304
+ this._lastError = null;
305
+ const client = new Redis(this._redisOptions);
306
+ this.client = client;
307
+
308
+ // `ready`, not `connect`: ioredis emits `connect` when the socket opens,
309
+ // which is before AUTH and before SELECT, so it would report a usable store
310
+ // for a connection the server is about to refuse (the same rule as
311
+ // `@onlineapps/conn-base-cache` d.572). Every handler checks that this is
312
+ // still THE client of this connector: a discarded one keeps emitting for a
313
+ // while, and its events belong to nobody.
314
+ const mine = () => this.client === client;
315
+ client.on('ready', () => { if (mine()) this.connected = true; });
316
+ // `close` is the socket going away with a reconnection still to come; `end`
317
+ // is the client giving up for good. Both mean the store is not readable now.
318
+ client.on('close', () => { if (mine()) this.connected = false; });
319
+ client.on('end', () => { if (mine()) this.connected = false; });
320
+
321
+ client.on('error', (err) => {
322
+ // Surfaced on get(), and read below as the verdict of a failed connect().
323
+ this._lastError = err;
324
+ // A refusal the server has already spoken does not change on the next
325
+ // attempt: end the reconnection rather than ask again in a loop.
326
+ if (isServerRefusal(err)) client.disconnect();
327
+ });
328
+
329
+ try {
330
+ await client.connect();
331
+ } catch (rejection) {
332
+ // The verdict comes from whichever error carries it: ioredis delivers the
333
+ // server's sentence on the `error` channel and rejects connect() with the
334
+ // state of the socket, but a rejection that carries the verdict itself is
335
+ // read the same way.
336
+ const refusal = [this._lastError, rejection].find(isServerRefusal) || null;
337
+ const reported = refusal || this._lastError || rejection;
338
+
339
+ client.disconnect();
340
+ this.client = null;
341
+ this.connected = false;
342
+
343
+ if (refusal) {
344
+ throw new Error(
345
+ `[conn-infra-secrets] Failed to connect to Redis at ${this._endpoint} - the server `
346
+ + `answered and refused it with "${refusal.message}". Fix: correct the credential in `
347
+ + 'REDIS_URL (api/config/env-active/shared.env) — the ACL user too, if the URL names '
348
+ + 'one; a server that answers this way refuses every retry, so the connector stopped '
349
+ + 'instead of looping. Only the endpoint is named here; the URL carries the password.',
350
+ { cause: refusal }
351
+ );
352
+ }
353
+ throw new Error(
354
+ `[conn-infra-secrets] Failed to connect to Redis at ${this._endpoint} - the server sent `
355
+ + `no verdict; the client rejected with "${reported.message}". Fix: check that Redis is `
356
+ + 'listening at that endpoint and that the host and port in REDIS_URL '
357
+ + '(api/config/env-active/shared.env) are the right ones. A refused credential answers '
358
+ + 'NOAUTH, WRONGPASS or NOPERM and is reported as such, so this is not one. Only the '
359
+ + 'endpoint is named here; the URL carries the password.',
360
+ { cause: reported }
361
+ );
362
+ }
363
+
120
364
  this.connected = true;
121
365
  return true;
122
366
  }