@cotal-ai/core 0.171.2 → 0.171.3

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,585 @@
1
+ // The bearer and credential renewal of CotalEndpoint, as an internal component: fetch, prove, adopt
2
+ // and present the auth material, and swap the live connection onto it. Moved verbatim from endpoint.ts;
3
+ // the endpoint keeps the public methods and forwards to them. Not re-exported by the index.
4
+ import { randomUUID } from "node:crypto";
5
+ import { decodeBearerPrincipal, bearerExpiryMs, bearerRenewalDeadlineMs, bearerLifetimeMs, retryAfterMs, dialerFor, authOpts, probeConnect } from "./endpoint-dial.js";
6
+ import { MAX_TIMER_MS } from "./endpoint-options.js";
7
+ import { armRenewal, jitteredBackoffMs } from "./renewal.js";
8
+ import { credsClaims, credsFingerprint, credsRenewalDelayMs, idFromCreds } from "./identity.js";
9
+ import { withDeadline } from "./deadline.js";
10
+ import { requestSafeReconnect } from "./request-safe-reconnect.js";
11
+ /** One endpoint's bearer and credential renewal: the checked getters every connect attempt presents,
12
+ * the timed and explicit prove-then-adopt transactions, and the controlled reconnect onto adopted
13
+ * material. Internal: `CotalEndpoint` keeps the fields and the public methods and forwards to it. */
14
+ export class EndpointCredentials {
15
+ deps;
16
+ constructor(deps) {
17
+ this.deps = deps;
18
+ }
19
+ get nc() { return this.deps.nc(); }
20
+ get bearerSource() { return this.deps.bearerSource(); }
21
+ get owner() { return this.deps.owner(); }
22
+ get actor() { return this.deps.actor(); }
23
+ get space() { return this.deps.space(); }
24
+ get currentBearer() { return this.deps.currentBearer(); }
25
+ set currentBearer(value) { this.deps.setCurrentBearer(value); }
26
+ get bearerAdoptedAtMs() { return this.deps.bearerAdoptedAtMs(); }
27
+ set bearerAdoptedAtMs(value) { this.deps.setBearerAdoptedAtMs(value); }
28
+ get bearerRenewalFailures() { return this.deps.bearerRenewalFailures(); }
29
+ set bearerRenewalFailures(value) { this.deps.setBearerRenewalFailures(value); }
30
+ get cancelBearerRenewal() { return this.deps.cancelBearerRenewal(); }
31
+ set cancelBearerRenewal(value) { this.deps.setCancelBearerRenewal(value); }
32
+ get stopped() { return this.deps.stopped(); }
33
+ get presentedExp() { return this.deps.presentedExp(); }
34
+ set presentedExp(value) { this.deps.setPresentedExp(value); }
35
+ get currentCreds() { return this.deps.currentCreds(); }
36
+ set currentCreds(value) { this.deps.setCurrentCreds(value); }
37
+ get credsSource() { return this.deps.credsSource(); }
38
+ get connId() { return this.deps.connId(); }
39
+ get overlapOnConnectionRenewal() { return this.deps.overlapOnConnectionRenewal(); }
40
+ get onConnection() { return this.deps.onConnection(); }
41
+ get servers() { return this.deps.servers(); }
42
+ get card() { return this.deps.card(); }
43
+ get token() { return this.deps.token(); }
44
+ get user() { return this.deps.user(); }
45
+ get pass() { return this.deps.pass(); }
46
+ get userMode() { return this.deps.userMode(); }
47
+ get sentinelCreds() { return this.deps.sentinelCreds(); }
48
+ get tls() { return this.deps.tls(); }
49
+ get ownedConnections() { return this.deps.ownedConnections(); }
50
+ get authExpiryReconnectTimer() { return this.deps.authExpiryReconnectTimer(); }
51
+ set authExpiryReconnectTimer(value) { this.deps.setAuthExpiryReconnectTimer(value); }
52
+ get credsTxnsRunning() { return this.deps.credsTxnsRunning(); }
53
+ set credsTxnsRunning(value) { this.deps.setCredsTxnsRunning(value); }
54
+ get credsTxn() { return this.deps.credsTxn(); }
55
+ set credsTxn(value) { this.deps.setCredsTxn(value); }
56
+ get reconnecting() { return this.deps.reconnecting(); }
57
+ get reestablishing() { return this.deps.reestablishing(); }
58
+ get requestsAwaitingReply() { return this.deps.requestsAwaitingReply(); }
59
+ get residentSwap() { return this.deps.residentSwap(); }
60
+ set residentSwap(value) { this.deps.setResidentSwap(value); }
61
+ emitRecoverable(err) { void this.deps.emitRecoverable(err); }
62
+ kickBackoff() { void this.deps.kickBackoff(); }
63
+ armCredsRefresh(delayMs) { void this.deps.armCredsRefresh(delayMs); }
64
+ reconnect() { return this.deps.reconnect(); }
65
+ emit(event, ...args) { return this.deps.emit(event, ...args); }
66
+ on(event, listener) { void this.deps.on(event, listener); }
67
+ off(event, listener) { void this.deps.off(event, listener); }
68
+ /** The floor on a bearer renewal's delay. A token whose whole lifetime sits under it is renewed at
69
+ * this cadence (`expiry-renewal` mints 5s bearers). */
70
+ static BEARER_MIN_RENEWAL_MS = 5_000;
71
+ /** A failed bearer renewal retries after about this long, doubling per failure up to the cap. */
72
+ static BEARER_RETRY_MS = 5_000;
73
+ static BEARER_RETRY_CAP_MS = 60_000;
74
+ /** Fetch a fresh bearer from the source, pin its principal to ours, arm the next renewal. On a
75
+ * fetch/principal failure: THROWS when `initial` (start() must fail loud before first connect);
76
+ * otherwise retries on a jittered, capped backoff, and warns once for the whole run of failures —
77
+ * the live connection keeps working until its current JWT expiry, so a dead auth service is
78
+ * loud without instantly dropping the mesh, and without a line per attempt. */
79
+ async refreshBearer(initial = false) {
80
+ try {
81
+ const bearer = await this.bearerSource();
82
+ const claims = decodeBearerPrincipal(bearer);
83
+ if (claims.owner !== this.owner || claims.actor !== this.actor)
84
+ throw new Error(`bearer source returned principal ${claims.owner}.${claims.actor}, expected ${this.owner}.${this.actor}`);
85
+ // Two refusals, answering different questions, and both of them are about protecting what is
86
+ // ALREADY held. So both are scoped to there BEING something held, which is the same set as
87
+ // `!initial` but names the thing the rules actually depend on: on the first fetch there is no
88
+ // cache to lose, `start()` has to come up on whatever the source has, and the pre-dial guard
89
+ // in {@link bindConnection} is what speaks for a dead first token.
90
+ const expiryMs = bearerExpiryMs(bearer);
91
+ const held = this.currentBearer;
92
+ if (held !== undefined) {
93
+ // ALREADY DEAD, whatever else is true of it. Advancement is deliberately not part of this
94
+ // test: a candidate expiring at now-5s does advance a held one that died at now-60s, so an
95
+ // advance-only rule adopts it - overwriting the cache with material nothing can dial,
96
+ // skipping the recoverable warning because the fetch did not throw, and arming the next
97
+ // read off a non-positive delay. The creds path draws its line on expiry alone too, in
98
+ // {@link presentableCreds} (#1572).
99
+ if (expiryMs <= Date.now())
100
+ throw new Error("the bearer source returned a token that has already expired - nothing adopted");
101
+ // THE SAME BYTES BACK AGAIN from a source whose token is already past its renewal window:
102
+ // the renewal it arms is floored to 5s, and the next read returns that same token - a 5s
103
+ // loop against the auth service for the rest of its life, with the retry backoff bypassed
104
+ // because the fetch did not FAIL. It succeeded and returned nothing new (#1561).
105
+ //
106
+ // The test is byte identity, not expiry, and not advancement. `exp` carries one second of
107
+ // resolution, so a key rotation re-signing the same claims under a new key - and a healthy
108
+ // short-TTL source read twice inside one wall-clock second - both hand back a token whose
109
+ // `exp` has not moved. That is genuinely re-issued material, which an advancement test
110
+ // refuses and this one adopts. It is the question the creds path asks with
111
+ // `credsFingerprint`: did the source re-issue ANYTHING (#1572).
112
+ if (bearer === held && Date.now() >= bearerRenewalDeadlineMs(held, this.bearerAdoptedAtMs))
113
+ throw new Error("the bearer source re-served the token already held and it cannot carry another cycle (the auth service has not issued a fresh one) - nothing adopted");
114
+ }
115
+ if (bearer !== held)
116
+ this.bearerAdoptedAtMs = Date.now();
117
+ this.currentBearer = bearer;
118
+ this.bearerRenewalFailures = 0;
119
+ // The renewal point is drawn from the middle of the token's lifetime, spaced from this
120
+ // process's other renewals in the space: a fixed margin before `exp` kept every endpoint
121
+ // issued in one second renewing, and rebinding through the callout, in one second for life.
122
+ const { issuedAtMs, expiresAtMs } = bearerLifetimeMs(bearer, this.bearerAdoptedAtMs);
123
+ this.armBearerTimer(armRenewal(this.space, issuedAtMs, expiresAtMs, () => void this.renewBearerOnTimer(), EndpointCredentials.BEARER_MIN_RENEWAL_MS));
124
+ }
125
+ catch (e) {
126
+ if (initial)
127
+ throw e;
128
+ if (this.bearerRenewalFailures === 0)
129
+ this.emitRecoverable(new Error(`bearer refresh failed (${e instanceof Error ? e.message : String(e)}) - retrying with backoff; this connection dies at its current token's expiry if the auth service stays down`));
130
+ // A wait the source named is kept as named: never retried inside it, nor stretched by the backoff.
131
+ const named = retryAfterMs(e);
132
+ const delay = named > 0 ? named : jitteredBackoffMs(this.bearerRenewalFailures, EndpointCredentials.BEARER_RETRY_MS, EndpointCredentials.BEARER_RETRY_CAP_MS);
133
+ this.bearerRenewalFailures++;
134
+ const timer = setTimeout(() => void this.renewBearerOnTimer(), delay);
135
+ timer.unref?.();
136
+ this.armBearerTimer(() => clearTimeout(timer));
137
+ }
138
+ }
139
+ armBearerTimer(cancel) {
140
+ this.cancelBearerRenewal?.();
141
+ this.cancelBearerRenewal = cancel;
142
+ if (this.stopped)
143
+ cancel();
144
+ }
145
+ /** The timed renewal. A new token moves the live connection onto itself at once, through the
146
+ * same controlled reconnect the creds path uses, so the broker never has to expire a connection
147
+ * this endpoint could renew. With no live connection, it ends the rebuild loop's wait instead:
148
+ * that loop refuses to dial an expired token and leaves the retries to this timer. */
149
+ async renewBearerOnTimer() {
150
+ const held = this.currentBearer;
151
+ await this.refreshBearer();
152
+ if (this.stopped || this.currentBearer === held)
153
+ return;
154
+ if (this.nc && !this.nc.isClosed())
155
+ await this.swapConnectionOntoFreshCreds();
156
+ else
157
+ this.kickBackoff();
158
+ }
159
+ /** The cached bearer, checked: every (re)connect attempt reads it, the reconnects nats.js runs
160
+ * on its own included, so none presents an expired token, which the callout could only deny
161
+ * after a full round trip. The bearer counterpart of {@link credsForWire}. */
162
+ bearerForWire() {
163
+ const bearer = this.currentBearer;
164
+ if (bearer !== undefined && bearerExpiryMs(bearer) > Date.now())
165
+ return bearer;
166
+ throw new Error(this.bearerSource
167
+ ? "this endpoint's user bearer has expired and renewal through the auth exchange is failing - not presenting the expired token to the broker; retrying with backoff"
168
+ : "this endpoint's user bearer has expired and it holds no bearer source to renew it - re-authenticate and rebuild the endpoint (construct it with a bearer FUNCTION for standing renewal)");
169
+ }
170
+ /** How soon a FAILED creds refresh retries. Successful refreshes schedule by lifetime fraction
171
+ * (75% of iat→exp), not a fixed margin — standing creds span hours to days, bearers minutes. */
172
+ static CREDS_RETRY_MS = 60_000;
173
+ /** THE ONE PLACE a credential is cleared for presentation to a broker.
174
+ *
175
+ * The property is unconditional — this endpoint never presents a credential it has already
176
+ * decoded as expired — so it is a property of the SUPPLY, not of any one dial site. It used to
177
+ * live inside {@link bindConnection}, which only `start()` and `doRebuild` reach; the
178
+ * authenticator nats.js re-evaluates on ITS OWN reconnects read the cache directly and so
179
+ * presented whatever was last fetched, expired included. Two such reconnects exist and neither
180
+ * passes through bindConnection: the one the broker forces at JWT `exp`, and an ALREADY RUNNING
181
+ * dial loop from an earlier drop that crosses `exp` while it retries (the pre-expiry
182
+ * reconnect fence flips a policy flag nats-core only reads when it observes a NEW drop, so it
183
+ * cannot stop a loop already in flight).
184
+ *
185
+ * Putting the refusal here instead means a future caller cannot miss it: the only way to reach a
186
+ * dial is through {@link credsForWire}, and the one presentation that does not read the cache
187
+ * (the adoption preflight, which presents a fresh CANDIDATE) calls this same function on it.
188
+ *
189
+ * An unbounded credential (no numeric `exp`) is presentable: bounded lifetimes are the renewal
190
+ * seam's concern, and a cred with no expiry has none to be past. */
191
+ static presentableCreds(creds, opts) {
192
+ const { exp } = credsClaims(creds); // throws on a structurally-unusable file (fail-loud)
193
+ if (typeof exp === "number" && exp * 1000 <= Date.now())
194
+ throw new Error(opts.renewable
195
+ ? "this endpoint's creds have expired and renewal is failing - not presenting the expired credential to the broker; retrying with backoff"
196
+ : "this endpoint's creds have expired and it holds no creds source to renew them - replace the credential and rebuild the endpoint (pass a creds FUNCTION for standing renewal)");
197
+ return creds;
198
+ }
199
+ /** The connect attempt's credential getters: what {@link credsForWire} and {@link bearerForWire}
200
+ * return, with its expiry recorded as {@link presentedExp}. */
201
+ presentCreds() {
202
+ const creds = this.credsForWire();
203
+ this.presentedExp = credsClaims(creds).exp;
204
+ return creds;
205
+ }
206
+ presentBearer() {
207
+ const bearer = this.bearerForWire();
208
+ this.presentedExp = bearerExpiryMs(bearer) / 1000;
209
+ return bearer;
210
+ }
211
+ /** The cached credential, checked. Handed to nats.js as the authenticator's source on EVERY auth
212
+ * mode (renewed or static), so each (re)connect attempt — ours or the library's — re-reads a
213
+ * CHECKED value. A refusal throws out of the authenticator, which nats-core turns into a closed
214
+ * connection rather than a CONNECT carrying dead material; the endpoint's own supervisor then
215
+ * rebuilds on capped backoff, and {@link bindConnection} re-fetches from the source on each of
216
+ * those attempts, so a renewal that starts working recovers the endpoint without presenting
217
+ * anything expired in the meantime. Deliberately side-effect free: kicking the renewal timer
218
+ * from here would retry the source once per dial attempt, which is the flat load on a dead
219
+ * broker that {@link RETRY_BACKOFF_CAP_MS} exists to prevent. */
220
+ credsForWire() {
221
+ if (!this.currentCreds)
222
+ throw new Error(this.credsSource
223
+ ? "this endpoint has no credential to present yet (the creds source has not returned one) - not dialing without auth material"
224
+ : "this endpoint was constructed with an empty creds string - not dialing without auth material (an empty credential is not anonymous access)");
225
+ return EndpointCredentials.presentableCreds(this.currentCreds, { renewable: Boolean(this.credsSource) });
226
+ }
227
+ /** The credential this endpoint presents on its next connect, checked as {@link credsForWire}
228
+ * checks it. A second connection under the same identity reads it on every attempt, so it
229
+ * presents each credential this endpoint adopts and never an expired one. */
230
+ wireCreds() {
231
+ return this.credsForWire();
232
+ }
233
+ /** Refuses a fetched generation there is nothing to renew FROM, so the caller's failure posture
234
+ * ({@link CREDS_RETRY_MS}) applies instead of the renewal schedule (issue #1523).
235
+ *
236
+ * A source that hands back the SAME generation past its own renewal point has not re-signed yet:
237
+ * that is a missed remint, not a candidate. Adopting it re-arms from a non-positive delay, which
238
+ * {@link armCredsRefresh} floors to 1s, which fetches again, which is the same generation — a 1s
239
+ * read loop against a store that is already having a bad day, for the JWT's remaining 25% of life,
240
+ * with the 60s backoff that exists for exactly this bypassed because the fetch did not FAIL.
241
+ *
242
+ * The membership feed's rw-cred renewal already refuses it this way (`membership-feed.ts`,
243
+ * `adoptRwCreds`: "the rw source still holds the previous generation past its renewal point");
244
+ * this is the same rule on the endpoint's `delivery.creds` seam, so the two renewal paths answer
245
+ * a dead source identically.
246
+ *
247
+ * An ALREADY-EXPIRED generation is refused whatever it is: the delay is non-positive for it too,
248
+ * but it is dead rather than merely due, so it is named separately and refused even when the
249
+ * source keeps returning a different one. */
250
+ static assertRenewableGeneration(candidate, current, delayMs) {
251
+ const { exp } = credsClaims(candidate);
252
+ if (typeof exp === "number" && exp * 1000 <= Date.now())
253
+ throw new Error("the creds source returned an already-expired credential (its `exp` is in the past) - nothing adopted; the renewal owner has not re-signed it, or the store is serving a stale generation");
254
+ // Compared by GENERATION, not by envelope. `EndpointOptions.creds` takes opaque file content and
255
+ // promises no canonical whitespace: `jwtFromCreds` pads with `\s*` and trims, so a store, editor or
256
+ // filesystem round trip that adds a newline re-serves the SAME credential in bytes `===` calls
257
+ // different - and the refusal would be skipped for the one case it exists to catch. The envelope
258
+ // also carries the nkey seed, which is why `credsFingerprint` hashes the JWT instead.
259
+ if (current !== undefined && credsFingerprint(candidate) === credsFingerprint(current) && delayMs <= 0)
260
+ throw new Error("the creds source still holds the previous generation past its renewal point (the renewal owner has not re-signed it) - nothing adopted");
261
+ }
262
+ /** The disposable-preflight connect bound for the EXPLICIT reload proof (D5 class-2 adoption). A
263
+ * rogue or unreachable candidate must resolve well UNDER the manager's delivery-admin request
264
+ * bound, so this stays a few seconds and never blocks the responder. */
265
+ static PREFLIGHT_MS = 4_000;
266
+ /** How long the resident wire swap is deferred past the reply on the EXPLICIT reload path. The
267
+ * delivery-admin responder rides THIS connection, so `nc.reconnect()` must not run until the
268
+ * reply has flushed on the still-live old cred; the old cred stays valid until its exp, so a short
269
+ * deferral is safe. */
270
+ static RESIDENT_SWAP_DEFER_MS = 250;
271
+ /** How long a delivery-admin request read after a reload waits for the resident swap's reconnect.
272
+ * nats.js drops a publish made while the connection is down when it redials, so a reply sent
273
+ * during the swap is lost and its caller waits out its whole request timeout. Past this bound the
274
+ * request is answered anyway, as it was before the gate. */
275
+ static RESIDENT_SWAP_GATE_MS = 5_000;
276
+ /** The daemon-side deadline for the WHOLE prove-then-adopt transaction (source fetch + preflight +
277
+ * commit), kept strictly BELOW the manager's delivery-admin request bound so a slow or hung hosted
278
+ * store returns a structured component failure rather than an ambiguous client timeout, and a late
279
+ * fetch can never commit after the caller gave up. */
280
+ static RELOAD_DEADLINE_MS = 12_000;
281
+ /** Fetch fresh creds from the source, pin their identity to ours, cache them, and arm the next
282
+ * refresh at 75% of the new JWT's lifetime. THROWS on fetch/pin failure — the callers decide the
283
+ * failure posture (loud-and-retry for the timer, a structured error reply for an explicit
284
+ * {@link reloadCreds}). This is the PASSIVE-BACKSTOP fetch; the explicit auditable path
285
+ * ({@link reloadCreds}) does its own fetch so it can preflight the candidate on a disposable
286
+ * connection BEFORE mutating this live cache. */
287
+ async fetchFreshCreds() {
288
+ const creds = await this.credsSource();
289
+ const id = idFromCreds(creds);
290
+ if (id !== this.connId)
291
+ throw new Error(`creds source returned identity ${id}, expected ${this.connId} - renewal may not swap the connection's nkey`);
292
+ // Before the commit, so a refusal leaves the cache holding the last generation that was renewable
293
+ // from (and, on the initial fetch, fails loud rather than dialling with dead material).
294
+ const delay = credsRenewalDelayMs(creds);
295
+ EndpointCredentials.assertRenewableGeneration(creds, this.currentCreds, delay);
296
+ this.currentCreds = creds;
297
+ this.armCredsRefresh(delay);
298
+ const { iat, exp } = credsClaims(creds);
299
+ return { iat, exp };
300
+ }
301
+ /** Swap the live connection onto the freshest cached cred or bearer with a controlled
302
+ * `nc.reconnect()` (nats.js re-evaluates the authenticator per attempt). Swapping now, instead of
303
+ * waiting for the broker to close the connection at `exp`, means the wire never carries a
304
+ * near-dead JWT and the operator never sees a spurious "authentication expired". After the
305
+ * reconnect succeeds, re-arm the expiry fence for the credential now authenticated on the wire. */
306
+ async swapConnectionOntoFreshCreds() {
307
+ const nc = this.nc;
308
+ if (!(nc && !this.stopped))
309
+ return;
310
+ const overlap = this.overlapOnConnectionRenewal && this.onConnection
311
+ ? await this.openRenewalOverlap().catch(() => undefined)
312
+ : undefined;
313
+ try {
314
+ // reconnect() resolves when the disconnect is requested, before subscriptions return.
315
+ // A flush started now is sent after those subscriptions, so it resolves only once they
316
+ // are on the broker. The overlap stays up until then.
317
+ await nc.reconnect().catch(() => { });
318
+ if (overlap && !nc.isClosed())
319
+ await withDeadline(nc.flush(), 10_000, () => new Error("resident renewal flush did not finish")).catch(() => { });
320
+ if (this.nc === nc && !this.stopped)
321
+ this.armAuthExpiryReconnectFence(nc);
322
+ }
323
+ finally {
324
+ if (overlap && !overlap.isClosed())
325
+ await this.closeWithoutLibraryReconnect(overlap).catch(() => { });
326
+ }
327
+ }
328
+ /** A second connection whose `onConnection` subscriptions are flushed before the resident
329
+ * reconnect. Its inbox is not the resident connection's inbox. A flush that does not finish
330
+ * closes it and leaves the caller to reconnect in place. */
331
+ async openRenewalOverlap() {
332
+ const overlap = await dialerFor(this.servers)({
333
+ servers: this.servers,
334
+ noAsyncTraces: true,
335
+ name: `cotal:${this.card.name}:renewal`,
336
+ inboxPrefix: `_INBOX_renew_${randomUUID()}`,
337
+ maxReconnectAttempts: 0,
338
+ ...authOpts({
339
+ token: this.token, user: this.user, pass: this.pass,
340
+ creds: this.currentCreds !== undefined || this.credsSource ? () => this.presentCreds() : undefined,
341
+ bearer: this.userMode ? () => this.presentBearer() : undefined,
342
+ sentinelCreds: this.sentinelCreds, tls: this.tls,
343
+ }),
344
+ });
345
+ this.ownedConnections.add(overlap);
346
+ try {
347
+ this.onConnection?.(overlap);
348
+ await withDeadline(overlap.flush(), 5_000, () => new Error("renewal overlap flush did not finish"));
349
+ return overlap;
350
+ }
351
+ catch (error) {
352
+ await this.closeWithoutLibraryReconnect(overlap).catch(() => { });
353
+ throw error;
354
+ }
355
+ }
356
+ /** nats-core keeps its reconnect switch on the protocol handler. This pinned internal shape is the
357
+ * same last-resort surface used by {@link closeFailedBind}; there is no public API for changing the
358
+ * reconnect policy of an existing connection. Disabling it does not disable Cotal self-heal: the
359
+ * `nc.closed()` supervisor below rebuilds the endpoint with freshly checked auth material. */
360
+ disableLibraryReconnect(nc) {
361
+ const protocol = nc.protocol;
362
+ if (protocol?.options)
363
+ protocol.options.reconnect = false;
364
+ }
365
+ /** Close a connection whose library reconnect has already been disabled. `drain()` flushes with a
366
+ * PING and waits for the matching PONG; nats-core only rejects that waiter inside reconnect
367
+ * `prepare()`, so a half-open socket with reconnect=false leaves drain pending until the 2-minute
368
+ * ping interval times out. `close()` tears the transport down without that round-trip, which is
369
+ * the same public path {@link closeFailedBind} already uses when there is no graceful delivery
370
+ * contract left. */
371
+ async closeWithoutLibraryReconnect(nc) {
372
+ if (!nc)
373
+ return;
374
+ this.disableLibraryReconnect(nc);
375
+ await nc.close();
376
+ if (!nc.isClosed())
377
+ throw new Error("endpoint connection closure is unproved; consumer custody must be retained");
378
+ this.ownedConnections.delete(nc);
379
+ }
380
+ /** Disable nats-core reconnect shortly before the JWT authenticated on this wire expires. The small
381
+ * lead makes the policy change precede the broker's expiry close even when both timers wake in the
382
+ * same event-loop turn. A credential adoption does not move this fence until the resident reconnect
383
+ * is requested, so the old wire remains protected during the prove-then-adopt window. */
384
+ armAuthExpiryReconnectFence(nc) {
385
+ clearTimeout(this.authExpiryReconnectTimer);
386
+ this.authExpiryReconnectTimer = undefined;
387
+ const credsExp = this.currentCreds && credsClaims(this.currentCreds).exp;
388
+ const expiryMs = this.userMode && this.currentBearer
389
+ ? bearerExpiryMs(this.currentBearer)
390
+ : typeof credsExp === "number"
391
+ ? credsExp * 1000
392
+ : undefined;
393
+ if (expiryMs === undefined || this.stopped)
394
+ return;
395
+ // Node fires a delay above 2^31-1 ms (about 24.8 days) after 1 ms, which would disable reconnect
396
+ // at once. A later expiry waits in steps of that bound, and the fence is armed again from there.
397
+ const delay = Math.max(0, expiryMs - Date.now() - 500);
398
+ this.authExpiryReconnectTimer = delay > MAX_TIMER_MS
399
+ ? setTimeout(() => { if (this.nc === nc)
400
+ this.armAuthExpiryReconnectFence(nc); }, MAX_TIMER_MS)
401
+ : setTimeout(() => { if (this.nc === nc)
402
+ this.disableLibraryReconnect(nc); }, delay);
403
+ this.authExpiryReconnectTimer.unref?.();
404
+ }
405
+ /** The connectAndBind PRE-CONNECT fetch: pull the freshest source cred and pin it into
406
+ * {@link currentCreds} so the connect() that immediately follows presents it — that connect IS the
407
+ * proof, so NO preflight and NO live swap here. THROWS when `initial` (no cred to start from), else
408
+ * emits and retries. The LIVE-SWAP paths — the 75% timer {@link renewCredsOnTimer} and the explicit
409
+ * {@link reloadCreds} — preflight the candidate on a disposable connection instead, so they never
410
+ * reconnect the live connection onto an unproven cred. */
411
+ async refreshCreds(initial = false) {
412
+ try {
413
+ await this.fetchFreshCreds();
414
+ }
415
+ catch (e) {
416
+ if (initial)
417
+ throw e;
418
+ this.emitRecoverable(new Error(`creds refresh failed (${e instanceof Error ? e.message : String(e)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));
419
+ this.armCredsRefresh(EndpointCredentials.CREDS_RETRY_MS);
420
+ }
421
+ }
422
+ runCredsTxn(fn) {
423
+ const counted = async () => {
424
+ this.credsTxnsRunning++;
425
+ try {
426
+ return await fn();
427
+ }
428
+ finally {
429
+ this.credsTxnsRunning--;
430
+ }
431
+ };
432
+ const next = this.credsTxn.then(counted, counted);
433
+ this.credsTxn = next.then(() => undefined, () => undefined);
434
+ return next;
435
+ }
436
+ /** The one PROVE-then-adopt transaction shared by the 75% timer and the explicit reload (run under
437
+ * {@link runCredsTxn}). Fetch (deadline-bounded) → identity-pin → optional `expected` fingerprint →
438
+ * PREFLIGHT the candidate on a disposable connection → fence a late commit against the deadline →
439
+ * commit {@link currentCreds} → arm the next 75% timer. Because currentCreds is written ONLY after
440
+ * the preflight proves broker acceptance, the resident authenticator getter can never present an
441
+ * unproven cred (not even on an incidental reconnect), and a rejected candidate leaves the resident
442
+ * connection untouched on BOTH the timer and explicit paths. THROWS (structured) on any failure. */
443
+ async adoptFreshCreds(opts = {}) {
444
+ // ABSOLUTE deadline, captured at the CALLER's entry (reloadCreds / renewCredsOnTimer) BEFORE the
445
+ // single-flight enqueue, so the queue wait behind an in-flight transaction counts against it. A
446
+ // reload queued behind a hung-store timer tick can never receive a FRESH budget and commit after
447
+ // the renewal owner's request bound already elapsed.
448
+ const deadline = opts.deadline ?? Date.now() + EndpointCredentials.RELOAD_DEADLINE_MS;
449
+ // Fence BEFORE any source I/O: if the queue wait already burned the budget, fail structured now and
450
+ // never touch the store, the preflight, or currentCreds.
451
+ if (Date.now() > deadline)
452
+ throw new Error("reloadCreds: the request deadline elapsed while queued behind another credential transaction; nothing adopted");
453
+ const candidate = await withDeadline(this.credsSource(), deadline - Date.now(), () => new Error("reloadCreds: the creds source did not return before the daemon deadline; nothing adopted"));
454
+ const id = idFromCreds(candidate);
455
+ if (id !== this.connId)
456
+ throw new Error(`creds source returned identity ${id}, expected ${this.connId} - renewal may not swap the connection's nkey`);
457
+ // Non-material message ON PURPOSE: this text flows to the manager's persisted
458
+ // `RenewalRecord.adoption.error`, so neither the observed nor the expected digest may appear.
459
+ if (opts.expected !== undefined && credsFingerprint(candidate) !== opts.expected)
460
+ throw new Error("reloadCreds: re-read credential generation did not match the expected re-signed generation (a different store, or a torn/stale read); nothing adopted");
461
+ // PREFLIGHT = the proof. A disposable connection presenting exactly the candidate BEFORE the live
462
+ // cache is touched; a refused cred throws here, leaving the resident connection untouched.
463
+ // The candidate goes through the SAME checkpoint the resident getter uses: this is the one
464
+ // presentation that does not read the cache, so routing it here is what makes the refusal a
465
+ // property of every path rather than of the cached one. An already-dead re-signed generation is
466
+ // refused locally instead of spending a round trip to be told so, and — because this throws
467
+ // BEFORE the commit below — it can never become the resident connection's next-presented cred.
468
+ const proven = EndpointCredentials.presentableCreds(candidate, { renewable: true });
469
+ const probe = await probeConnect(this.servers, { creds: proven, tls: this.tls, timeoutMs: Math.max(500, Math.min(EndpointCredentials.PREFLIGHT_MS, deadline - Date.now())) });
470
+ if (!probe.ok)
471
+ throw new Error(`reloadCreds: the broker did not accept the re-signed credential (${probe.reason}); nothing adopted`);
472
+ if (Date.now() > deadline)
473
+ throw new Error("reloadCreds: the proof exceeded the daemon deadline; nothing adopted"); // fence a late commit
474
+ // Validate the bounded-window renewal delay BEFORE the commit: credsRenewalDelayMs throws on a cred
475
+ // lacking a numeric `exp`, and that throw must not leave currentCreds flipped to a candidate the
476
+ // authenticator would present on the next reconnect (a post-preflight validation failure is a no-op).
477
+ const delay = credsRenewalDelayMs(candidate);
478
+ EndpointCredentials.assertRenewableGeneration(candidate, this.currentCreds, delay);
479
+ this.currentCreds = candidate;
480
+ this.armCredsRefresh(delay);
481
+ this.emit("creds-adopted", credsClaims(candidate));
482
+ return credsClaims(candidate);
483
+ }
484
+ /** The 75%-of-lifetime renewal timer tick: prove + adopt + swap the LIVE connection. Preflights (it
485
+ * reconnects a live connection, so the candidate must be broker-proven first) and is serialized
486
+ * with the explicit reload. Never throws — a failed renewal logs and retries while the old cred
487
+ * stays live until its expiry. */
488
+ async renewCredsOnTimer() {
489
+ // Deadline captured HERE, before the enqueue, for the same reason as the explicit reload.
490
+ const deadline = Date.now() + EndpointCredentials.RELOAD_DEADLINE_MS;
491
+ try {
492
+ await this.runCredsTxn(() => this.adoptFreshCreds({ deadline }));
493
+ await this.swapConnectionOntoFreshCreds();
494
+ }
495
+ catch (e) {
496
+ this.emitRecoverable(new Error(`creds refresh failed (${e instanceof Error ? e.message : String(e)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));
497
+ this.armCredsRefresh(EndpointCredentials.CREDS_RETRY_MS);
498
+ }
499
+ }
500
+ /** Fetch, broker-prove and adopt the source credential, then refresh the same connection
501
+ * once outgoing mux and named-reply requests are quiet. A busy timeout retains the connection
502
+ * and adopted credential. Call again to retry. This does not tear down endpoint bindings.
503
+ * A dropped connection that is being re-established carries no request, so it redials now
504
+ * instead of after its backoff; the rebuild re-fetches a stale credential from the source. */
505
+ async refreshCredsRequestSafe() {
506
+ if (!this.credsSource)
507
+ throw new Error("credential refresh requires a creds source");
508
+ const nc = this.nc;
509
+ if (!nc && !this.stopped && (this.reconnecting || this.reestablishing))
510
+ return await this.reconnect();
511
+ if (!nc || this.stopped)
512
+ throw new Error("credential refresh requires a running endpoint");
513
+ const deadline = Date.now() + EndpointCredentials.RELOAD_DEADLINE_MS;
514
+ await this.runCredsTxn(async () => {
515
+ await this.adoptFreshCreds({ deadline });
516
+ if (this.nc !== nc || this.stopped)
517
+ throw new Error("endpoint connection changed during credential refresh");
518
+ await requestSafeReconnect(nc, () => this.requestsAwaitingReply.get(nc)?.size ?? 0);
519
+ if (this.nc === nc && !this.stopped)
520
+ this.armAuthExpiryReconnectFence(nc);
521
+ });
522
+ }
523
+ /** EXPLICIT credential reload — the auditable adoption step of D5 class-2 standing renewal (served
524
+ * to the renewal owner via the delivery-admin rail). The PROOF-OF-RECORD is a DISPOSABLE PREFLIGHT
525
+ * connection that presents exactly the candidate: it succeeds only when the BROKER accepts this
526
+ * re-signed generation, and it runs BEFORE the live cache is touched. So a cred the broker refuses
527
+ * throws HERE (structured), the resident connection — and the delivery-admin rail this very reply
528
+ * rides — is never disturbed, and "file re-signed" can never masquerade as "daemon adopted".
529
+ * `expected` is the renewal owner's generation token (SHA-256 of the JWT it re-signed): a re-read
530
+ * that does not match is rejected before the preflight even runs. On success the candidate becomes
531
+ * the resident connection's next-presented cred; the wire swap is NOT forced here — the caller
532
+ * ({@link handleDeliveryAdmin}) schedules it AFTER the aggregate reply, because the responder rides
533
+ * this connection and reconnecting before the reply flushes would strand it (see
534
+ * adoption-false-green.smoke.ts). Returns the BROKER-ACCEPTED generation's window (identity/iat/exp):
535
+ * the resident wire swap is best-effort and self-healing (the 75% timer + the broker's expiry-close),
536
+ * NOT witnessed, so the caller must claim broker acceptance, not verified resident reauth. NEVER a
537
+ * fingerprint. */
538
+ async reloadCreds(expected) {
539
+ if (!this.credsSource)
540
+ throw new Error("reloadCreds: this endpoint has no creds source (a static cred cannot be renewed in place)");
541
+ // Capture the ABSOLUTE deadline at ENTRY, before enqueue, so a reload queued behind a hung-store
542
+ // 75% timer tick is bounded by the SAME window (queue wait included) and cannot commit/swap after
543
+ // the renewal owner's request bound has already elapsed and it recorded "no responder".
544
+ const deadline = Date.now() + EndpointCredentials.RELOAD_DEADLINE_MS;
545
+ // The prove-then-adopt transaction (fetch + preflight + commit) runs under the single-flight so it
546
+ // cannot interleave with the 75% timer; the wire swap is scheduled by {@link handleDeliveryAdmin}
547
+ // after the aggregate reply (the responder rides this connection).
548
+ const { iat, exp } = await this.runCredsTxn(() => this.adoptFreshCreds({ expected, deadline }));
549
+ return { identity: this.connId, iat, exp };
550
+ }
551
+ /** Arm the resident wire swap for the delivery-admin `reloadCreds` path. Called by
552
+ * {@link handleDeliveryAdmin} ONLY after BOTH component proofs have settled and immediately before
553
+ * the reply is returned+responded — never from inside {@link reloadCreds} while the aggregate is
554
+ * still open, or a slow co-component proof would let `nc.reconnect()` reconnect the admin rail
555
+ * before the reply flushes and silently strand it. The short deferral lets the reply flush on the
556
+ * still-live old cred first. Best-effort — the proof was the preflight; a transient swap failure is
557
+ * retried by the 75% timer and the broker's own expiry-close, both presenting the adopted candidate.
558
+ * Until the swapped connection is back, {@link residentSwap} holds the delivery-admin requests that
559
+ * arrive after this reply. */
560
+ scheduleResidentSwap() {
561
+ if (this.stopped)
562
+ return;
563
+ const swap = new Promise((resolve) => { setTimeout(resolve, EndpointCredentials.RESIDENT_SWAP_DEFER_MS).unref?.(); })
564
+ .then(async () => {
565
+ const back = this.transportBack(EndpointCredentials.RESIDENT_SWAP_GATE_MS);
566
+ await this.swapConnectionOntoFreshCreds();
567
+ await back;
568
+ })
569
+ .finally(() => { if (this.residentSwap === swap)
570
+ this.residentSwap = undefined; });
571
+ this.residentSwap = swap;
572
+ }
573
+ /** Resolve when this endpoint reports its transport connected again, or after `ms`. */
574
+ transportBack(ms) {
575
+ return new Promise((resolve) => {
576
+ const done = () => { clearTimeout(timer); this.off("transport", seen); resolve(); };
577
+ const seen = (state) => { if (state.connected)
578
+ done(); };
579
+ const timer = setTimeout(done, ms);
580
+ timer.unref?.();
581
+ this.on("transport", seen);
582
+ });
583
+ }
584
+ }
585
+ //# sourceMappingURL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