@cotal-ai/core 0.171.1 → 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.
- package/dist/advisory-lock.d.ts +2 -0
- package/dist/advisory-lock.d.ts.map +1 -1
- package/dist/advisory-lock.js +10 -0
- package/dist/advisory-lock.js.map +1 -1
- package/dist/agent-file.d.ts +3 -2
- package/dist/agent-file.d.ts.map +1 -1
- package/dist/agent-file.js +11 -2
- package/dist/agent-file.js.map +1 -1
- package/dist/connector.d.ts +5 -0
- package/dist/connector.d.ts.map +1 -1
- package/dist/connector.js.map +1 -1
- package/dist/endpoint-credentials.d.ts +306 -0
- package/dist/endpoint-credentials.d.ts.map +1 -0
- package/dist/endpoint-credentials.js +585 -0
- package/dist/endpoint-credentials.js.map +1 -0
- package/dist/endpoint-dial.d.ts +171 -0
- package/dist/endpoint-dial.d.ts.map +1 -0
- package/dist/endpoint-dial.js +479 -0
- package/dist/endpoint-dial.js.map +1 -0
- package/dist/endpoint-messages.d.ts +44 -0
- package/dist/endpoint-messages.d.ts.map +1 -0
- package/dist/endpoint-messages.js +153 -0
- package/dist/endpoint-messages.js.map +1 -0
- package/dist/endpoint-options.d.ts +295 -0
- package/dist/endpoint-options.d.ts.map +1 -0
- package/dist/endpoint-options.js +75 -0
- package/dist/endpoint-options.js.map +1 -0
- package/dist/endpoint-subscriptions.d.ts +2 -2
- package/dist/endpoint-subscriptions.d.ts.map +1 -1
- package/dist/endpoint-subscriptions.js +4 -6
- package/dist/endpoint-subscriptions.js.map +1 -1
- package/dist/endpoint.d.ts +26 -536
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +102 -1184
- package/dist/endpoint.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { connect } from "@nats-io/transport-node";
|
|
2
|
+
import { type PushConsumer } from "@nats-io/jetstream";
|
|
3
|
+
import { type KV } from "@nats-io/kv";
|
|
4
|
+
export declare const DEFAULT_SERVER = "nats://127.0.0.1:4222";
|
|
5
|
+
/** Auth subset of connect() options, shared by the endpoint and isReachable. `bearer` may be a
|
|
6
|
+
* sync GETTER — nats.js re-evaluates token authenticators per (re)connect attempt, which is how a
|
|
7
|
+
* refreshing endpoint presents its freshest bearer without rebuilding the connection options. */
|
|
8
|
+
interface AuthOpts {
|
|
9
|
+
token?: string;
|
|
10
|
+
user?: string;
|
|
11
|
+
pass?: string;
|
|
12
|
+
/** May be a sync GETTER (like `bearer`) — the authenticator then re-reads it per (re)connect
|
|
13
|
+
* attempt, which is how a standing-renewal endpoint presents its freshest cred. */
|
|
14
|
+
creds?: string | (() => string);
|
|
15
|
+
/** Observe only the credential actually presented, including native reconnect authentication. */
|
|
16
|
+
onCreds?: (creds: string) => void;
|
|
17
|
+
bearer?: string | (() => string);
|
|
18
|
+
sentinelCreds?: string;
|
|
19
|
+
tls?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function authOpts(a: AuthOpts): {
|
|
22
|
+
authenticator: import("@nats-io/transport-node").Authenticator[];
|
|
23
|
+
tls: {} | undefined;
|
|
24
|
+
token?: undefined;
|
|
25
|
+
user?: undefined;
|
|
26
|
+
pass?: undefined;
|
|
27
|
+
} | {
|
|
28
|
+
authenticator: (nonce?: string) => import("@nats-io/transport-node").Auth;
|
|
29
|
+
tls: {} | undefined;
|
|
30
|
+
token?: undefined;
|
|
31
|
+
user?: undefined;
|
|
32
|
+
pass?: undefined;
|
|
33
|
+
} | {
|
|
34
|
+
token: string | undefined;
|
|
35
|
+
user: string | undefined;
|
|
36
|
+
pass: string | undefined;
|
|
37
|
+
tls: {} | undefined;
|
|
38
|
+
authenticator?: undefined;
|
|
39
|
+
};
|
|
40
|
+
/** The bearer's `exp` as epoch ms — what the refresh schedule keys on. A bearer without a numeric
|
|
41
|
+
* `exp` is structurally unusable for a refreshing endpoint (fail-loud, like the principal decode). */
|
|
42
|
+
export declare function bearerExpiryMs(bearer: string): number;
|
|
43
|
+
/** The bearer's lifetime as epoch ms: `iat` to `exp`, starting at `adoptedAtMs` when it carries no
|
|
44
|
+
* `iat`. */
|
|
45
|
+
export declare function bearerLifetimeMs(bearer: string, adoptedAtMs: number): {
|
|
46
|
+
issuedAtMs: number;
|
|
47
|
+
expiresAtMs: number;
|
|
48
|
+
};
|
|
49
|
+
/** Past this point a held bearer is overdue: its renewal should already have replaced it. */
|
|
50
|
+
export declare function bearerRenewalDeadlineMs(bearer: string, adoptedAtMs: number): number;
|
|
51
|
+
/** A refusal already surfaced once for this outage. The rebuild loop retries it without a notice,
|
|
52
|
+
* so an endpoint that cannot renew shows one status line rather than one per attempt. */
|
|
53
|
+
export declare class RepeatedRefusal extends Error {
|
|
54
|
+
}
|
|
55
|
+
/** Decode the owner+actor PRINCIPAL from a user bearer WITHOUT verifying it — the client trusts its own
|
|
56
|
+
* bearer only to build its subjects; the broker's minted grant (from the callout, which DOES verify the
|
|
57
|
+
* bearer) is the real boundary, so a client that lied to itself would just be denied. Per the token
|
|
58
|
+
* claim semantics the OWNER is the JWT `sub` (`act.owner` merely restates it) and the ACTOR is
|
|
59
|
+
* `act.actor`. Throws on a structurally-unusable bearer (fail-loud). */
|
|
60
|
+
export declare function decodeBearerPrincipal(bearer: string): {
|
|
61
|
+
owner: string;
|
|
62
|
+
actor: string;
|
|
63
|
+
};
|
|
64
|
+
/** Turn a raw async-status error into one whose message says *why* — a permission
|
|
65
|
+
* violation looks like absence unless it's named as a denial. */
|
|
66
|
+
export declare function describeStatusError(err: Error): Error;
|
|
67
|
+
/** The ordered consumer behind a KV watch, which nats.js keeps on the iterator and the KV types hide. */
|
|
68
|
+
export declare function kvWatchConsumer(iter: Awaited<ReturnType<KV["watch"]>>): PushConsumer;
|
|
69
|
+
/** True ONLY for a denial on a **publish** — the single case that proves the message was never
|
|
70
|
+
* ACCEPTED or stored. (Not "never reached the server": the server necessarily received enough of
|
|
71
|
+
* it to reject it. The distinction matters precisely here, because this helper exists to separate
|
|
72
|
+
* provably-not-stored from possibly-stored, and the looser phrasing overstates the very thing
|
|
73
|
+
* being measured.) {@link isPermissionDenied} deliberately does not look at the operation: it exists to
|
|
74
|
+
* separate "denied" from "service down", and that answer is the same either way. The operation
|
|
75
|
+
* matters enormously to a caller that reports *delivery*, because a JetStream publish is
|
|
76
|
+
* request/PubAck and the subscription half is the reply inbox — a denial THERE rejects
|
|
77
|
+
* `js.publish()` while the stream may already hold the message. Verified against a live broker: a
|
|
78
|
+
* user allowed to publish but denied its `_INBOX` subscription got
|
|
79
|
+
* `Permissions Violation for Subscription to "_INBOX.….*"` back from `js.publish()`, and an
|
|
80
|
+
* unrestricted observer then read `messages: 1` off the stream.
|
|
81
|
+
*
|
|
82
|
+
* Note what is deliberately NOT accepted: the untyped text fallback above. A permission-shaped
|
|
83
|
+
* message string carries no operation, so it cannot prove non-delivery, and guessing "publish"
|
|
84
|
+
* from wording would reintroduce exactly the false certainty this exists to prevent. Anything not
|
|
85
|
+
* provably a publish denial is unknown, and a caller reporting delivery must fail toward
|
|
86
|
+
* "I could not confirm" rather than toward "it did not happen" — the costly mistake is telling
|
|
87
|
+
* someone to re-send a message that was in fact stored. */
|
|
88
|
+
export declare function isPublishPermissionDenied(e: unknown): boolean;
|
|
89
|
+
/** Whether a server list dials over websocket: the FIRST entry's scheme decides (one list, one
|
|
90
|
+
* transport — a mixed tcp+ws list would race two transports over one identity). */
|
|
91
|
+
export declare function wsServers(servers: string): boolean;
|
|
92
|
+
/** Default probe budget by TRANSPORT. 1s was tuned for the loopback/LAN TCP brokers every local
|
|
93
|
+
* probe dials; a ws(s) broker is by definition published through an HTTPS edge (CDN tunnel,
|
|
94
|
+
* reverse proxy), where TLS + upgrade + INFO + the auth round-trip routinely exceeds 1s cold —
|
|
95
|
+
* measured ~60% spurious "not reachable" against a Cloudflare-fronted broker. Callers passing an
|
|
96
|
+
* explicit `timeoutMs` are untouched.
|
|
97
|
+
*
|
|
98
|
+
* EXPORTED because a caller that judges a probe by WHEN it answered has to compare against the
|
|
99
|
+
* deadline this function actually handed the probe. The delivery watchdog does exactly that, and
|
|
100
|
+
* hardcoding 1000 there silently misread every ws broker: honest refusals arrive at 2-5s, past a
|
|
101
|
+
* budget that was never theirs, and would be classified as this process's starvation rather than
|
|
102
|
+
* the server's refusal. The budget and the judgment must come from one place. */
|
|
103
|
+
export declare function defaultProbeTimeoutMs(servers: string): number;
|
|
104
|
+
/** Pick the dial function by SCHEME: `ws://`/`wss://` servers go through nats-core's
|
|
105
|
+
* `wsconnect` (the websocket transport - e.g. a broker published through an HTTPS edge at
|
|
106
|
+
* `wss://host/path`), everything else through the TCP transport. The websocket dial OWNS its
|
|
107
|
+
* transport options: a required TLS connection refuses any `ws://` target before dialing.
|
|
108
|
+
* `wss://` performs TLS itself, and the w3c transport refuses a `tls` block outright
|
|
109
|
+
* ("'tls' is not configurable"), so the block is removed after that check.
|
|
110
|
+
* A TCP dial that requires TLS to one IP address names that address as the host its certificate
|
|
111
|
+
* must cover (see {@link withDialedTlsHost}). */
|
|
112
|
+
export declare function dialerFor(servers: string): typeof connect;
|
|
113
|
+
/** Whether a failed connect was the server refusing these credentials: a server answered, so it is
|
|
114
|
+
* up. The same errors {@link isReachable} reads as up after its own authenticated connect. */
|
|
115
|
+
export declare function isAuthRejection(e: unknown): boolean;
|
|
116
|
+
/** The wait a credential source asked for with a numeric `retryAfterSeconds` on its error, in
|
|
117
|
+
* milliseconds, or 0. */
|
|
118
|
+
export declare function retryAfterMs(e: unknown): number;
|
|
119
|
+
/** Whether a NATS server is *running* at `servers`. With NO creds this is a SILENT plaintext
|
|
120
|
+
* liveness check ({@link tcpInfoProbe}): it reads the server's pre-auth `INFO` greeting and closes
|
|
121
|
+
* WITHOUT authenticating, so a live broker (open OR auth — INFO precedes auth) returns true while
|
|
122
|
+
* emitting no broker auth-error log. It may return false for a TLS-first listener — the credless
|
|
123
|
+
* probe is plaintext-only. With creds/token/tls supplied it is instead the AUTHORITATIVE identity
|
|
124
|
+
* check: a real authenticated connect, true on success AND on an auth rejection (a server that
|
|
125
|
+
* refuses these creds is still up — so the caller surfaces the real auth failure, and `up` won't
|
|
126
|
+
* start a duplicate on the bound port). Only a genuine connection failure (refused/timeout) is false. */
|
|
127
|
+
export declare function isReachable(servers?: string, opts?: AuthOpts & {
|
|
128
|
+
timeoutMs?: number;
|
|
129
|
+
}): Promise<boolean>;
|
|
130
|
+
/** What a connect attempt told us about the server — the distinction {@link isReachable} flattens.
|
|
131
|
+
* `auth-required` means a server answered but rejected these creds (so it IS up); `stale-auth`
|
|
132
|
+
* means the PRESENTED CREDENTIAL ITSELF is dead — expired by its bounded lifetime, either because
|
|
133
|
+
* the broker said "authentication expired" or because the cred is LOCALLY PROVABLY expired (its own
|
|
134
|
+
* JWT `exp` is past). The local check is decided without a round-trip, so a slow or failed connect
|
|
135
|
+
* never downgrades a dead cred to `unreachable`; the repair is `doctor auth` either way, never a
|
|
136
|
+
* registry prune (the D5 credential-death event). `unreachable` means nothing usable answered and
|
|
137
|
+
* the cred is not provably dead (refused / timeout / a stale registry entry). `timeout` means the
|
|
138
|
+
* dial ran out of its own budget before anything conclusive came back — never a trust or credential
|
|
139
|
+
* verdict, just "try again with more time" (#851). `inferred` marks an `auth-required` read from
|
|
140
|
+
* the broker's greeting rather than from a rejection: the greeting asked for auth and the handshake
|
|
141
|
+
* was then reset. The greeting is unauthenticated, so that verdict may name a failure but must never
|
|
142
|
+
* be grounds for deleting state. */
|
|
143
|
+
export type ProbeResult = {
|
|
144
|
+
ok: true;
|
|
145
|
+
} | {
|
|
146
|
+
ok: false;
|
|
147
|
+
reason: "auth-required";
|
|
148
|
+
inferred?: true;
|
|
149
|
+
} | {
|
|
150
|
+
ok: false;
|
|
151
|
+
reason: "stale-auth";
|
|
152
|
+
} | {
|
|
153
|
+
ok: false;
|
|
154
|
+
reason: "unreachable";
|
|
155
|
+
} | {
|
|
156
|
+
ok: false;
|
|
157
|
+
reason: "tls-unsupported";
|
|
158
|
+
} | {
|
|
159
|
+
ok: false;
|
|
160
|
+
reason: "timeout";
|
|
161
|
+
};
|
|
162
|
+
/** Like {@link isReachable}, but distinguishes "up but won't take these creds" from "nothing there".
|
|
163
|
+
* `spawn` needs the difference: auth-required → name the trust dir + next step; unreachable → the
|
|
164
|
+
* mesh is down (prune the stale entry, tell the user to `cotal up`). Pass `creds` to confirm a
|
|
165
|
+
* specific identity is accepted (`ok`); omit them to probe mere liveness (an auth broker answers
|
|
166
|
+
* `auth-required`, which still proves it's up). */
|
|
167
|
+
export declare function probeConnect(server?: string, opts?: AuthOpts & {
|
|
168
|
+
timeoutMs?: number;
|
|
169
|
+
}): Promise<ProbeResult>;
|
|
170
|
+
export {};
|
|
171
|
+
//# sourceMappingURL=endpoint-dial.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoint-dial.d.ts","sourceRoot":"","sources":["../src/endpoint-dial.ts"],"names":[],"mappings":"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"}
|
|
@@ -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
|