@cotal-ai/core 0.171.1 → 0.171.2

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,479 @@
1
+ // Dialing, auth options, bearer lifetimes and the reachability probes, moved verbatim from endpoint.ts.
2
+ // endpoint.ts re-exports the names it exported before, so the package's export set is unchanged.
3
+ import { createConnection, isIP } from "node:net";
4
+ import { connect, tokenAuthenticator, AuthorizationError, PermissionViolationError, UserAuthenticationExpiredError, TimeoutError, ConnectionError, } from "@nats-io/transport-node";
5
+ import { wsconnect } from "@nats-io/nats-core";
6
+ import {} from "@nats-io/jetstream";
7
+ import {} from "@nats-io/kv";
8
+ import { nativeCredsAuthenticator } from "./creds-authenticator.js";
9
+ import { renewalDeadlineMs } from "./renewal.js";
10
+ import { inspectCredHealth } from "./provision.js";
11
+ export const DEFAULT_SERVER = "nats://127.0.0.1:4222";
12
+ export function authOpts(a) {
13
+ const tls = a.tls ? {} : undefined;
14
+ // USER MODE: present the shared auth-account sentinel creds AND the user bearer as `auth_token` (an
15
+ // authenticator ARRAY — nats.js merges them into one CONNECT). The connect lands in the callout
16
+ // account, which validates the bearer and re-binds the client into the data account with a scoped JWT.
17
+ if (a.bearer) {
18
+ if (a.creds || a.token || a.user || a.pass)
19
+ throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");
20
+ if (!a.sentinelCreds)
21
+ throw new Error("user-mode bearer requires sentinelCreds");
22
+ return {
23
+ authenticator: [nativeCredsAuthenticator(a.sentinelCreds), tokenAuthenticator(a.bearer)],
24
+ tls,
25
+ };
26
+ }
27
+ // creds (JWT/nkey) are mutually exclusive with token/user/pass — reject rather than
28
+ // silently pick one, so a misconfigured caller fails loud.
29
+ if (a.creds) {
30
+ if (a.token || a.user || a.pass)
31
+ throw new Error("creds are mutually exclusive with token/user/pass auth");
32
+ const creds = a.creds;
33
+ // A getter re-wraps per (re)connect attempt so each attempt signs with the freshest cred;
34
+ // nats.js invokes the authenticator function on every attempt, including internal reconnects.
35
+ const authenticator = (nonce) => {
36
+ const presented = typeof creds === "function" ? creds() : creds;
37
+ const authenticated = nativeCredsAuthenticator(presented)(nonce);
38
+ a.onCreds?.(presented);
39
+ return authenticated;
40
+ };
41
+ return { authenticator, tls };
42
+ }
43
+ return { token: a.token, user: a.user, pass: a.pass, tls };
44
+ }
45
+ /** The bearer's `exp` as epoch ms — what the refresh schedule keys on. A bearer without a numeric
46
+ * `exp` is structurally unusable for a refreshing endpoint (fail-loud, like the principal decode). */
47
+ export function bearerExpiryMs(bearer) {
48
+ return bearerLifetimeMs(bearer, 0).expiresAtMs;
49
+ }
50
+ /** The bearer's lifetime as epoch ms: `iat` to `exp`, starting at `adoptedAtMs` when it carries no
51
+ * `iat`. */
52
+ export function bearerLifetimeMs(bearer, adoptedAtMs) {
53
+ const payload = bearer.split(".")[1];
54
+ if (!payload)
55
+ throw new Error("user-mode bearer is not a JWT (no payload segment)");
56
+ let claims;
57
+ try {
58
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
59
+ }
60
+ catch {
61
+ throw new Error("user-mode bearer payload is not valid base64url JSON");
62
+ }
63
+ if (typeof claims.exp !== "number")
64
+ throw new Error("user-mode bearer is missing a numeric exp claim");
65
+ const expiresAtMs = claims.exp * 1000;
66
+ return { issuedAtMs: Math.min(typeof claims.iat === "number" ? claims.iat * 1000 : adoptedAtMs, expiresAtMs), expiresAtMs };
67
+ }
68
+ /** Past this point a held bearer is overdue: its renewal should already have replaced it. */
69
+ export function bearerRenewalDeadlineMs(bearer, adoptedAtMs) {
70
+ const { issuedAtMs, expiresAtMs } = bearerLifetimeMs(bearer, adoptedAtMs);
71
+ return renewalDeadlineMs(issuedAtMs, expiresAtMs);
72
+ }
73
+ /** A refusal already surfaced once for this outage. The rebuild loop retries it without a notice,
74
+ * so an endpoint that cannot renew shows one status line rather than one per attempt. */
75
+ export class RepeatedRefusal extends Error {
76
+ }
77
+ /** Decode the owner+actor PRINCIPAL from a user bearer WITHOUT verifying it — the client trusts its own
78
+ * bearer only to build its subjects; the broker's minted grant (from the callout, which DOES verify the
79
+ * bearer) is the real boundary, so a client that lied to itself would just be denied. Per the token
80
+ * claim semantics the OWNER is the JWT `sub` (`act.owner` merely restates it) and the ACTOR is
81
+ * `act.actor`. Throws on a structurally-unusable bearer (fail-loud). */
82
+ export function decodeBearerPrincipal(bearer) {
83
+ const payload = bearer.split(".")[1];
84
+ if (!payload)
85
+ throw new Error("user-mode bearer is not a JWT (no payload segment)");
86
+ let claims;
87
+ try {
88
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
89
+ }
90
+ catch {
91
+ throw new Error("user-mode bearer payload is not valid base64url JSON");
92
+ }
93
+ const owner = claims.sub, actor = claims.act?.actor;
94
+ if (typeof owner !== "string" || typeof actor !== "string")
95
+ throw new Error("user-mode bearer is missing a string sub (owner) / act.actor claim");
96
+ return { owner, actor };
97
+ }
98
+ /** Turn a raw async-status error into one whose message says *why* — a permission
99
+ * violation looks like absence unless it's named as a denial. */
100
+ export function describeStatusError(err) {
101
+ if (err instanceof PermissionViolationError) {
102
+ return new Error(`NATS permission denied: cannot ${err.operation} "${err.subject}" - check this ` +
103
+ `endpoint's ACLs (a denied peer looks "absent" rather than blocked)`, { cause: err });
104
+ }
105
+ return err;
106
+ }
107
+ /** The ordered consumer behind a KV watch, which nats.js keeps on the iterator and the KV types hide. */
108
+ export function kvWatchConsumer(iter) {
109
+ const consumer = iter._data;
110
+ if (!consumer)
111
+ throw new Error("KV watch carries no consumer - the pinned nats.js changed shape");
112
+ return consumer;
113
+ }
114
+ /** True ONLY for a denial on a **publish** — the single case that proves the message was never
115
+ * ACCEPTED or stored. (Not "never reached the server": the server necessarily received enough of
116
+ * it to reject it. The distinction matters precisely here, because this helper exists to separate
117
+ * provably-not-stored from possibly-stored, and the looser phrasing overstates the very thing
118
+ * being measured.) {@link isPermissionDenied} deliberately does not look at the operation: it exists to
119
+ * separate "denied" from "service down", and that answer is the same either way. The operation
120
+ * matters enormously to a caller that reports *delivery*, because a JetStream publish is
121
+ * request/PubAck and the subscription half is the reply inbox — a denial THERE rejects
122
+ * `js.publish()` while the stream may already hold the message. Verified against a live broker: a
123
+ * user allowed to publish but denied its `_INBOX` subscription got
124
+ * `Permissions Violation for Subscription to "_INBOX.….*"` back from `js.publish()`, and an
125
+ * unrestricted observer then read `messages: 1` off the stream.
126
+ *
127
+ * Note what is deliberately NOT accepted: the untyped text fallback above. A permission-shaped
128
+ * message string carries no operation, so it cannot prove non-delivery, and guessing "publish"
129
+ * from wording would reintroduce exactly the false certainty this exists to prevent. Anything not
130
+ * provably a publish denial is unknown, and a caller reporting delivery must fail toward
131
+ * "I could not confirm" rather than toward "it did not happen" — the costly mistake is telling
132
+ * someone to re-send a message that was in fact stored. */
133
+ export function isPublishPermissionDenied(e) {
134
+ const typed = e instanceof PermissionViolationError
135
+ ? e
136
+ : e?.cause instanceof PermissionViolationError
137
+ ? (e.cause)
138
+ : undefined;
139
+ return typed?.operation === "publish";
140
+ }
141
+ /** Whether a server list dials over websocket: the FIRST entry's scheme decides (one list, one
142
+ * transport — a mixed tcp+ws list would race two transports over one identity). */
143
+ export function wsServers(servers) {
144
+ return /^wss?:\/\//i.test((servers.split(",")[0] ?? "").trim());
145
+ }
146
+ /** Default probe budget by TRANSPORT. 1s was tuned for the loopback/LAN TCP brokers every local
147
+ * probe dials; a ws(s) broker is by definition published through an HTTPS edge (CDN tunnel,
148
+ * reverse proxy), where TLS + upgrade + INFO + the auth round-trip routinely exceeds 1s cold —
149
+ * measured ~60% spurious "not reachable" against a Cloudflare-fronted broker. Callers passing an
150
+ * explicit `timeoutMs` are untouched.
151
+ *
152
+ * EXPORTED because a caller that judges a probe by WHEN it answered has to compare against the
153
+ * deadline this function actually handed the probe. The delivery watchdog does exactly that, and
154
+ * hardcoding 1000 there silently misread every ws broker: honest refusals arrive at 2-5s, past a
155
+ * budget that was never theirs, and would be classified as this process's starvation rather than
156
+ * the server's refusal. The budget and the judgment must come from one place. */
157
+ export function defaultProbeTimeoutMs(servers) {
158
+ return wsServers(servers) ? 5000 : 1000;
159
+ }
160
+ /** Pick the dial function by SCHEME: `ws://`/`wss://` servers go through nats-core's
161
+ * `wsconnect` (the websocket transport - e.g. a broker published through an HTTPS edge at
162
+ * `wss://host/path`), everything else through the TCP transport. The websocket dial OWNS its
163
+ * transport options: a required TLS connection refuses any `ws://` target before dialing.
164
+ * `wss://` performs TLS itself, and the w3c transport refuses a `tls` block outright
165
+ * ("'tls' is not configurable"), so the block is removed after that check.
166
+ * A TCP dial that requires TLS to one IP address names that address as the host its certificate
167
+ * must cover (see {@link withDialedTlsHost}). */
168
+ export function dialerFor(servers) {
169
+ if (!wsServers(servers))
170
+ return ((opts) => connect(withDialedTlsHost(servers, opts)));
171
+ return ((opts) => {
172
+ const { tls, ...rest } = (opts ?? {});
173
+ const targets = Array.isArray(rest.servers) ? rest.servers : String(rest.servers ?? servers).split(",");
174
+ if (tls && targets.some((target) => !/^wss:\/\//i.test(String(target).trim())))
175
+ return Promise.reject(new Error("TLS-required WebSocket connections must use wss:// for every server"));
176
+ return wsconnect(rest);
177
+ });
178
+ }
179
+ /** `opts` for a dial to `servers`, with the IP address it names as the host a TLS certificate must
180
+ * cover when the dial requires TLS: a `tls` block, or a `tls://` address. The TCP transport upgrades
181
+ * to TLS with no server name for an IP, and Node then checks the certificate against "localhost":
182
+ * a certificate for the dialed address alone is refused, and one naming localhost passes for any
183
+ * address. A dial that does not require TLS keeps its options, because a `tls` block refuses a
184
+ * plaintext broker, and so does a list of several servers, whose one host the options cannot name. */
185
+ function withDialedTlsHost(servers, opts) {
186
+ const urls = servers.split(",").map((url) => url.trim()).filter(Boolean);
187
+ const tls = opts?.tls;
188
+ if (urls.length !== 1 || tls === null || tls === undefined && !/^tls:\/\//i.test(urls[0]))
189
+ return opts;
190
+ let host;
191
+ try {
192
+ ({ host } = hostPort(urls[0]));
193
+ }
194
+ catch {
195
+ return opts;
196
+ }
197
+ // Node checks an upgraded socket's certificate against `host` when no server name is set.
198
+ return isIP(host) ? { ...opts, tls: { host, ...tls } } : opts;
199
+ }
200
+ /** Parse a NATS server URL (`nats://host:port`, `host:port`, a bare host, or a comma list — the
201
+ * first entry wins) into a host+port for {@link tcpInfoProbe}. Defaults the port to 4222. */
202
+ function hostPort(server) {
203
+ const raw = (server.split(",")[0] ?? "").trim();
204
+ const scheme = raw.match(/^([a-z][a-z0-9+.-]*):\/\//i)?.[1]?.toLowerCase();
205
+ const first = raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); // strip scheme
206
+ const u = new URL(`http://${first}`); // http:// so .hostname/.port resolve (incl. bracketed IPv6)
207
+ // A websocket broker rides the web's ports, not NATS's: `wss://host/path` reaches TCP 443.
208
+ const fallback = scheme === "wss" ? 443 : scheme === "ws" ? 80 : 4222;
209
+ return { host: u.hostname, port: u.port ? Number(u.port) : fallback };
210
+ }
211
+ /** Silent credless liveness probe. Opens a plain TCP connection and confirms a NATS server is there
212
+ * by reading its UNPROMPTED `INFO {…}` greeting — which the server sends on accept, BEFORE the
213
+ * client's CONNECT/auth (per the NATS client protocol) — then closes immediately without
214
+ * authenticating. Since it never sends CONNECT, an auth broker has nothing to reject, so this emits
215
+ * NO broker-side auth-error/auth-timeout log line (unlike a credless `connect()`, which an auth
216
+ * broker rejects and logs). It is a *plaintext NATS* liveness check only:
217
+ * • a TLS-first (`handshake_first`, NATS ≥ 2.10.4) listener sends its TLS handshake before INFO,
218
+ * so the read won't match → returns false (a documented false-negative for that broker config);
219
+ * • a non-NATS listener never sends a valid `INFO {` → also false, and a silent one resolves
220
+ * `"silent"` (we require the real greeting, never "any open port is reachable").
221
+ * Closes well within the server's ~1s authorization timeout, so it cannot trip a timeout log.
222
+ * A live server resolves to what its greeting said about auth. A peer that accepted the connection
223
+ * and sent no full line before the deadline, as a stopped or overloaded broker does, resolves
224
+ * `"silent"`; anything else resolves `false`. */
225
+ function tcpInfoProbe(server, timeoutMs) {
226
+ return new Promise((resolve) => {
227
+ let socket;
228
+ let done = false;
229
+ let connected = false;
230
+ const finish = (live) => {
231
+ if (done)
232
+ return;
233
+ done = true;
234
+ try {
235
+ socket?.destroy();
236
+ }
237
+ catch { /* already gone */ }
238
+ resolve(live);
239
+ };
240
+ let host, port;
241
+ try {
242
+ ({ host, port } = hostPort(server));
243
+ }
244
+ catch {
245
+ return resolve(false);
246
+ }
247
+ socket = createConnection({ host, port });
248
+ socket.setTimeout(timeoutMs);
249
+ let buf = "";
250
+ socket.on("data", (chunk) => {
251
+ buf += chunk.toString("utf8");
252
+ const nl = buf.indexOf("\r\n");
253
+ if (nl === -1) {
254
+ if (buf.length > 4096)
255
+ finish(false);
256
+ return;
257
+ } // no real INFO line is 4KB+
258
+ const line = buf.slice(0, nl);
259
+ const brace = line.indexOf("{"); // greeting is `INFO {json}` (the server appends a trailing space)
260
+ if (!/^INFO\b/.test(line) || brace === -1)
261
+ return finish(false); // not NATS (incl. a TLS-first handshake)
262
+ try {
263
+ finish({ authRequired: JSON.parse(line.slice(brace))?.auth_required === true });
264
+ } // require a real INFO greeting, not arbitrary bytes
265
+ catch {
266
+ finish(false);
267
+ }
268
+ });
269
+ socket.on("connect", () => { connected = true; });
270
+ socket.on("timeout", () => finish(connected ? "silent" : false));
271
+ socket.on("error", () => finish(false)); // refused / reset / DNS failure
272
+ socket.on("close", () => finish(false)); // closed before a full INFO line arrived
273
+ });
274
+ }
275
+ /** Bounded TCP reachability on a socket we OWN: does a handshake to `server` complete within
276
+ * `timeoutMs`? Deliberately narrower than {@link tcpInfoProbe} — it asks only whether the
277
+ * transport can be reached, never whether NATS is speaking there, so the TLS-first listener that
278
+ * `tcpInfoProbe` reports false for still passes this gate and goes on to a real connect.
279
+ *
280
+ * It exists because `connect()` cannot be trusted to release a connection it never established.
281
+ * `@nats-io/transport-node`'s `NodeTransport.dial()` keeps its socket in a local until the
282
+ * handshake resolves (`this.socket = await this.dial(hp)`), so `this.socket` is STILL UNDEFINED
283
+ * when the client's own connect timeout wins the race in `protocol.ts`'s `dial` and the catch
284
+ * calls `transport.close()` — whose teardown is `this.socket?.destroy()`, i.e. a destroy of
285
+ * nothing. Against an address that BLACKHOLES (SYN unanswered) rather than REFUSES (RST), the
286
+ * socket is orphaned in libuv until the OS SYN timeout, and the process cannot exit for minutes
287
+ * after the probe already returned its answer. That is issue #389, and it is upstream: nothing a
288
+ * caller passes (`reconnect: false`, `timeout`) reaches the orphan. Our socket, our `destroy()`,
289
+ * on every exit path — never an `unref`/force-exit, which would hide the symptom and a future
290
+ * real hang with it. A second orphan case (#2156) needs a greeting, not just a handshake, so it is
291
+ * gated by {@link tcpInfoProbe} instead wherever the dial will be plaintext. */
292
+ function tcpDialable(server, timeoutMs) {
293
+ return new Promise((resolve) => {
294
+ let socket;
295
+ let done = false;
296
+ const finish = (dialable) => {
297
+ if (done)
298
+ return;
299
+ done = true;
300
+ try {
301
+ socket?.destroy();
302
+ }
303
+ catch { /* already gone */ }
304
+ resolve(dialable);
305
+ };
306
+ let host, port;
307
+ try {
308
+ ({ host, port } = hostPort(server));
309
+ }
310
+ catch {
311
+ return resolve(false);
312
+ }
313
+ socket = createConnection({ host, port });
314
+ socket.setTimeout(timeoutMs);
315
+ socket.on("connect", () => finish(true));
316
+ socket.on("timeout", () => finish(false)); // blackhole: SYN unanswered inside our deadline
317
+ socket.on("error", () => finish(false)); // refused / reset / DNS failure
318
+ socket.on("close", () => finish(false));
319
+ });
320
+ }
321
+ /** Whether a failed connect was the server refusing these credentials: a server answered, so it is
322
+ * up. The same errors {@link isReachable} reads as up after its own authenticated connect. */
323
+ export function isAuthRejection(e) {
324
+ return e instanceof AuthorizationError || e instanceof UserAuthenticationExpiredError;
325
+ }
326
+ /** The wait a credential source asked for with a numeric `retryAfterSeconds` on its error, in
327
+ * milliseconds, or 0. */
328
+ export function retryAfterMs(e) {
329
+ const seconds = e?.retryAfterSeconds;
330
+ return typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 0;
331
+ }
332
+ /** Whether a NATS server is *running* at `servers`. With NO creds this is a SILENT plaintext
333
+ * liveness check ({@link tcpInfoProbe}): it reads the server's pre-auth `INFO` greeting and closes
334
+ * WITHOUT authenticating, so a live broker (open OR auth — INFO precedes auth) returns true while
335
+ * emitting no broker auth-error log. It may return false for a TLS-first listener — the credless
336
+ * probe is plaintext-only. With creds/token/tls supplied it is instead the AUTHORITATIVE identity
337
+ * check: a real authenticated connect, true on success AND on an auth rejection (a server that
338
+ * refuses these creds is still up — so the caller surfaces the real auth failure, and `up` won't
339
+ * start a duplicate on the bound port). Only a genuine connection failure (refused/timeout) is false. */
340
+ export async function isReachable(servers = DEFAULT_SERVER, opts = {}) {
341
+ const timeoutMs = opts.timeoutMs ?? defaultProbeTimeoutMs(servers);
342
+ if (!opts.creds && !opts.token && !opts.user && !opts.pass && !opts.tls) {
343
+ // A websocket broker rides an HTTPS edge: the plaintext INFO probe reads TLS bytes and
344
+ // declares a perfectly live broker down (which then blocks spawn/connect with a wrong
345
+ // remedy). Dial the ws transport credless instead — an auth broker REJECTING the bare
346
+ // connect still proves it is there, the same reading the authed branch below gives its
347
+ // catch. Costs one broker-side auth-error log line per probe, which the INFO probe was
348
+ // designed to avoid; on a ws broker there is no silent alternative.
349
+ if (wsServers(servers)) {
350
+ try {
351
+ const nc = await dialerFor(servers)({ servers, timeout: timeoutMs, reconnect: false, maxReconnectAttempts: 0 });
352
+ await nc.close();
353
+ return true;
354
+ }
355
+ catch (e) {
356
+ return e instanceof AuthorizationError || e instanceof UserAuthenticationExpiredError;
357
+ }
358
+ }
359
+ return typeof (await tcpInfoProbe(servers, timeoutMs)) === "object";
360
+ }
361
+ // The credless branch above already owns its socket. This one reaches `connect()`, so it carries
362
+ // the same orphaned-socket defects probeConnect did (#389, and the slow-greeting case #2156) and
363
+ // takes the same gate choice: reach the address on a socket we own first, requiring the NATS
364
+ // greeting for a plaintext dial (the upstream transport orphans a socket whose handshake
365
+ // completed but whose greeting came late) and only the handshake for a TLS-required or websocket
366
+ // dial (no plaintext greeting to read), then give `connect()` the remainder of the budget its own
367
+ // timeout always covered. A gate failure is a genuine connection failure, which is exactly the
368
+ // `false` the catch below already returns for one — an auth rejection cannot reach us from an
369
+ // address that never completed a handshake.
370
+ const started = Date.now();
371
+ const gate = opts.tls || wsServers(servers) ? tcpDialable : tcpInfoProbe;
372
+ const reached = await gate(servers, timeoutMs);
373
+ if (!reached || reached === "silent")
374
+ return false;
375
+ try {
376
+ const nc = await dialerFor(servers)({
377
+ servers,
378
+ timeout: Math.max(1, timeoutMs - (Date.now() - started)),
379
+ reconnect: false,
380
+ maxReconnectAttempts: 0,
381
+ ...authOpts(opts),
382
+ });
383
+ await nc.close();
384
+ return true;
385
+ }
386
+ catch (e) {
387
+ return e instanceof AuthorizationError || e instanceof UserAuthenticationExpiredError;
388
+ }
389
+ }
390
+ /** Like {@link isReachable}, but distinguishes "up but won't take these creds" from "nothing there".
391
+ * `spawn` needs the difference: auth-required → name the trust dir + next step; unreachable → the
392
+ * mesh is down (prune the stale entry, tell the user to `cotal up`). Pass `creds` to confirm a
393
+ * specific identity is accepted (`ok`); omit them to probe mere liveness (an auth broker answers
394
+ * `auth-required`, which still proves it's up). */
395
+ export async function probeConnect(server = DEFAULT_SERVER, opts = {}) {
396
+ const timeoutMs = opts.timeoutMs ?? defaultProbeTimeoutMs(server);
397
+ const started = Date.now();
398
+ // Reach the address on a socket we own BEFORE handing it to `connect()`, which orphans the
399
+ // connection it never established (see {@link tcpDialable} for the upstream mechanism, #389,
400
+ // and {@link tcpInfoProbe} for the second orphan case below, #2156). For a plaintext dial the
401
+ // gate must see the server's NATS greeting, not just the handshake: `connect()`'s own timeout
402
+ // can fire while it is still waiting on that greeting, and the upstream transport only destroys
403
+ // a socket whose handshake never completed, not one whose greeting came late (`_closed`'s guard
404
+ // on `connected`, which is set only after the greeting is read) — so `tcpInfoProbe` (which owns
405
+ // its socket and requires the greeting) is the gate there, while a TLS-required or websocket
406
+ // dial has no plaintext greeting to read and keeps the handshake-only `tcpDialable` gate. This
407
+ // cannot change any verdict: every address that gets past here had to complete a TCP handshake
408
+ // for `connect()` to have gotten anywhere either, and a gate failure is routed through the SAME
409
+ // classification the catch uses — so a locally-dead cred is still `stale-auth` and not silently
410
+ // downgraded to `unreachable` by the address being dark. The cost is one extra handshake (and,
411
+ // off TLS/ws, one extra greeting read) on the reachable path; the deadline below is the
412
+ // REMAINDER of the budget, because `connect()`'s own `timeout` always covered its handshake too.
413
+ const gate = opts.tls || wsServers(server) ? tcpDialable : tcpInfoProbe;
414
+ const greeting = await gate(server, timeoutMs);
415
+ if (!greeting)
416
+ return classifyProbeFailure(undefined, opts);
417
+ // A peer that took the connection and never greeted is there but not answering, as a stopped or
418
+ // overloaded broker is. That is the same latency verdict as a dial that ran out of its budget.
419
+ if (greeting === "silent")
420
+ return classifyProbeFailure(undefined, opts, false, "timeout");
421
+ try {
422
+ const nc = await dialerFor(server)({
423
+ servers: server,
424
+ timeout: Math.max(1, timeoutMs - (Date.now() - started)),
425
+ reconnect: false,
426
+ maxReconnectAttempts: 0,
427
+ ...authOpts(opts),
428
+ });
429
+ await nc.close();
430
+ return { ok: true };
431
+ }
432
+ catch (e) {
433
+ return classifyProbeFailure(e, opts, greeting !== true && greeting.authRequired);
434
+ }
435
+ }
436
+ /** Why a {@link probeConnect} attempt did not end in `ok`. Shared by the pre-connect reachability
437
+ * gate and the connect catch so both classify identically — the gate must never turn a diagnosable
438
+ * credential death into a bare `unreachable` just because the address went dark.
439
+ *
440
+ * A presented cred that is PROVABLY expired by its own JWT is stale-auth (credential death) — and
441
+ * that is knowable LOCALLY, without the network, so it is decided FIRST, before the error type. On
442
+ * the wire the broker's rejection and the socket close race: a slow CI/Windows handshake can
443
+ * surface a bare transport failure (→ "unreachable") instead of a clean AuthorizationError, which
444
+ * used to misclassify a dead cred. Reading the cred removes that timing dependency entirely, so the
445
+ * classification is deterministic. Unreadable content falls through to the wire truth (no false
446
+ * stale diagnosis from garbage). `e` is undefined when the gate refused before any connect.
447
+ * `authRequired` is true when the gate read a greeting that asked for auth. `otherwise` is the
448
+ * verdict when nothing more specific applies. */
449
+ function classifyProbeFailure(e, opts, authRequired = false, otherwise = "unreachable") {
450
+ if (typeof opts.creds === "string") {
451
+ try {
452
+ if (inspectCredHealth(opts.creds).state === "expired")
453
+ return { ok: false, reason: "stale-auth" };
454
+ }
455
+ catch { /* not introspectable — keep the wire truth */ }
456
+ }
457
+ if (e instanceof UserAuthenticationExpiredError)
458
+ return { ok: false, reason: "stale-auth" };
459
+ // The broker answered but rejected these creds (so it IS up) — auth-required, not stale-auth.
460
+ if (e instanceof AuthorizationError)
461
+ return { ok: false, reason: "auth-required" };
462
+ // A dial that ran out of its own budget is neither a refusal nor a dead broker — it is latency,
463
+ // and grading it `unreachable` made a TLS-required target read as a trust failure (#851). Only
464
+ // nats-core's TimeoutError means that: a peer's `-ERR` that mentions a timeout answered at once.
465
+ if (e instanceof TimeoutError)
466
+ return { ok: false, reason: "timeout" };
467
+ // The native client read a greeting without TLS support and refused the TLS requirement.
468
+ // That is a transport mismatch, not an unreachable listener or proof of mesh identity.
469
+ if (e instanceof ConnectionError && e.message === "server does not support 'tls'")
470
+ return { ok: false, reason: "tls-unsupported" };
471
+ // A broker that greeted us asking for auth and then reset the handshake most likely refused it.
472
+ // Windows can discard its `-ERR 'Authorization Violation'` when the reset lands, so the client
473
+ // sees only ECONNRESET, and a running auth broker used to read as gone. No rejection was read, so
474
+ // the verdict is marked inferred.
475
+ if (authRequired && e?.code === "ECONNRESET")
476
+ return { ok: false, reason: "auth-required", inferred: true };
477
+ return { ok: false, reason: otherwise };
478
+ }
479
+ //# sourceMappingURL=endpoint-dial.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint-dial.js","sourceRoot":"","sources":["../src/endpoint-dial.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,iGAAiG;AACjG,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,U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IACvF,IAAI,CAAC,YAAY,eAAe,IAAI,CAAC,CAAC,OAAO,KAAK,+BAA+B;QAC/E,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAClD,gGAAgG;IAChG,+FAA+F;IAC/F,kGAAkG;IAClG,kCAAkC;IAClC,IAAI,YAAY,IAAK,CAAoC,EAAE,IAAI,KAAK,YAAY;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAChJ,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAC1C,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { JsMsg } from "@nats-io/jetstream";
2
+ import type { NatsConnection } from "@nats-io/transport-node";
3
+ import { type ParsedSubject } from "./subjects.js";
4
+ import type { CotalMessage, Delivery, HistoryMessage, MessageMeta } from "./types.js";
5
+ /** A usable delivery-message id (#624): a string, possibly empty (the never-a-key case), but
6
+ * never absent and never a non-string. An absent or non-string id is a malformed envelope under
7
+ * SPEC sec 5; each delivery pump handles it per its own class (durable term, live drop, history
8
+ * skip) so it never reaches the receiver's id-keyed machinery as `undefined`. */
9
+ export declare function isUsableMessageId(id: unknown): id is string;
10
+ /** Map an authenticated parsed-subject kind to the message class surfaced to "message" listeners.
11
+ * Throws on `ctl` (control-plane is request/reply, never a "message") — per repo convention, no
12
+ * silent default: an unexpected delivering kind is a bug, not something to swallow. */
13
+ export declare function kindFromParsed(kind: ParsedSubject["kind"]): MessageMeta["kind"];
14
+ /** SPEC §5 on receive: a delivery comes from the principal its subject names. The payload is an
15
+ * object whose `from.id` is the subject's sender, and the subject's owner is a real principal, not
16
+ * an old-shape alias. Every receive path asks this one predicate. What a path does with a refusal
17
+ * (drop, skip, ack, term or reject) and its own extra checks (a usable id, its own echo) stay with
18
+ * the path. */
19
+ export declare function isFromSubjectSender(msg: unknown, parsed: ParsedSubject): boolean;
20
+ /** Routing fields in the envelope are advisory. The broker forge-locks sender (and for DMs,
21
+ * recipient) into the subject. Callers MUST already have passed {@link isFromSubjectSender}
22
+ * (SPEC §5). This derives the remaining
23
+ * routing tokens from the subject for rows that survived — it does not rewrite a mismatched
24
+ * `from.id`. Live tails, channel backfill, and channel recall skip the mismatch; history
25
+ * does the same (#388). The row's other fields pass through UNTOUCHED, so what the caller's
26
+ * row type already verified stays verified (#1413). */
27
+ export declare function authenticatedMessage<M extends CotalMessage>(msg: M, parsed: ParsedSubject): CotalMessage & M;
28
+ /** A DM-only copy's delivery. An ack, nak or in-progress signal on a closed connection is refused
29
+ * with a throw instead of being dropped silently: the copy stays unacked and the broker redelivers it. */
30
+ export declare function dmOnlyDelivery(m: JsMsg, ackWaitMs: number, nc: NatsConnection | undefined): Delivery;
31
+ /** History drain keeps `m.json()` and used to throw the subject away. SPEC §5: on receive, verify
32
+ * `from.id` equals the subject sender; on mismatch, a missing `from`, or an unparseable delivery
33
+ * subject, reject and never surface. Fail closed on shape too: a stored JSON `null` or a truthy
34
+ * non-object `from` must not throw mid-array. Do not echo-drop `from.id === this.card.id`:
35
+ * god-view history must include the viewer's own sends. */
36
+ export declare function historyMessageFromDelivery(m: {
37
+ subject: string;
38
+ json: <T>() => T;
39
+ }): HistoryMessage | undefined;
40
+ /** A part `partsToText` can read without throwing: an object with a string `kind` (#1413).
41
+ * Deliberately weaker than `isMessagePart` — a keyless `{kind:"data"}` part passes here —
42
+ * because history must surface rows a pre-#1404 producer wrote, not drop them. */
43
+ export declare function isReadableMessagePart(value: unknown): boolean;
44
+ //# sourceMappingURL=endpoint-messages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint-messages.d.ts","sourceRoot":"","sources":["../src/endpoint-messages.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAA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