@cosyte/mllp 0.1.10 → 0.1.12

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/index.cjs CHANGED
@@ -646,13 +646,21 @@ var MLLP_BIND_ALL_INTERFACES = "MLLP_BIND_ALL_INTERFACES";
646
646
  var MLLP_TLS_CIPHER_LIST_REJECTED = "MLLP_TLS_CIPHER_LIST_REJECTED";
647
647
  var MLLP_TLS_CIPHER_OPTION_CONFLICT = "MLLP_TLS_CIPHER_OPTION_CONFLICT";
648
648
  var MLLP_TLS_DH_PARAMETERS_REJECTED = "MLLP_TLS_DH_PARAMETERS_REJECTED";
649
- var TLS_CONFIGURATION_MESSAGES = Object.freeze({
650
- [MLLP_TLS_CIPHER_LIST_REJECTED]: "the TLS library rejected the configured cipher-suite list; no connection was opened and no fallback to the runtime default list was made",
651
- [MLLP_TLS_CIPHER_OPTION_CONFLICT]: "tls.atnaTransportSecurity and tls.ciphers both declare the offered cipher-suite list; set exactly one of them",
652
- [MLLP_TLS_DH_PARAMETERS_REJECTED]: "the configured ephemeral Diffie-Hellman parameters are not usable; nothing was bound and no fallback to a server without Diffie-Hellman parameters was made"
653
- });
649
+ var MLLP_TLS_CIPHER_LIST_UNENFORCEABLE = "MLLP_TLS_CIPHER_LIST_UNENFORCEABLE";
650
+ var MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE = "MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE";
651
+ var MLLP_TLS_PFX_REJECTED = "MLLP_TLS_PFX_REJECTED";
652
+ var MLLP_TLS_CREDENTIAL_CONFLICT = "MLLP_TLS_CREDENTIAL_CONFLICT";
654
653
  function tlsConfigurationMessage(code) {
655
- return TLS_CONFIGURATION_MESSAGES[code];
654
+ const messages = {
655
+ [MLLP_TLS_CIPHER_LIST_REJECTED]: "the TLS library rejected the configured cipher-suite list; no connection was opened and no fallback to the runtime default list was made",
656
+ [MLLP_TLS_CIPHER_OPTION_CONFLICT]: "tls.atnaTransportSecurity and tls.ciphers both declare the offered cipher-suite list; set exactly one of them",
657
+ [MLLP_TLS_DH_PARAMETERS_REJECTED]: "the configured ephemeral Diffie-Hellman parameters are not usable; nothing was bound and no fallback to a server without Diffie-Hellman parameters was made",
658
+ [MLLP_TLS_CIPHER_LIST_UNENFORCEABLE]: "this runtime's TLS library does not enforce a configured cipher-suite list; no connection was opened, rather than one offering a list other than the one configured",
659
+ [MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE]: "this runtime's TLS library does not enforce server Diffie-Hellman parameters; nothing was bound, rather than a server running without the parameters configured",
660
+ [MLLP_TLS_PFX_REJECTED]: "tls.pfx could not be loaded with tls.passphrase: the passphrase is wrong, the file is not PKCS#12, or it uses a legacy encryption (RC2-40, as `openssl pkcs12 -export -legacy` and older exports write it) that OpenSSL 3 does not load, so re-export it with AES-256; no socket was opened",
661
+ [MLLP_TLS_CREDENTIAL_CONFLICT]: "tls.pfx was set together with tls.cert or tls.key; the PKCS#12 file carries its own certificate and key, so set either cert and key or pfx, not both"
662
+ };
663
+ return messages[code];
656
664
  }
657
665
  var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
658
666
  name = "MllpTlsConfigurationError";
@@ -662,7 +670,8 @@ var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
662
670
  */
663
671
  code;
664
672
  /**
665
- * The TLS library's own error, when the runtime is what refused the list.
673
+ * The TLS library's own error, when the runtime is what refused the input
674
+ * (or, for an `_UNENFORCEABLE` code, refused one of the probes).
666
675
  * `undefined` when this package refused the configuration itself.
667
676
  */
668
677
  cause;
@@ -826,6 +835,47 @@ var ATNA_CIPHER_LIST = [
826
835
  ...TLS13_DEFAULT_CIPHER_SUITES,
827
836
  ...ATNA_CIPHER_SUITES
828
837
  ].join(":");
838
+ function refusalOf(options) {
839
+ try {
840
+ tls.createSecureContext(options);
841
+ } catch (err) {
842
+ return err instanceof Error ? err : new Error(String(err));
843
+ }
844
+ return null;
845
+ }
846
+ var probeResults = /* @__PURE__ */ new Map();
847
+ function probeRefusal(probe) {
848
+ const key = "ciphers" in probe ? `ciphers=${probe.ciphers}` : `dhparam=${probe.dhparam}`;
849
+ const found = probeResults.get(key);
850
+ if (found !== void 0) return found;
851
+ const refusal = refusalOf(probe);
852
+ probeResults.set(key, refusal);
853
+ return refusal;
854
+ }
855
+ function assertCipherListEnforced(atna) {
856
+ if (probeRefusal({ ciphers: "ECDHE-RSA-AES128-GCM-SHA256:!ECDHE-RSA-AES128-GCM-SHA256" }) === null) {
857
+ throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_UNENFORCEABLE);
858
+ }
859
+ if (!atna) return;
860
+ for (const suite of ATNA_CIPHER_SUITES) {
861
+ const refusal = probeRefusal({ ciphers: suite });
862
+ if (refusal !== null) {
863
+ throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_UNENFORCEABLE, { cause: refusal });
864
+ }
865
+ }
866
+ }
867
+ function assertDhParametersEnforced() {
868
+ const autoRefusal = probeRefusal({ dhparam: "auto" });
869
+ if (autoRefusal !== null) {
870
+ throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE, {
871
+ cause: autoRefusal
872
+ });
873
+ }
874
+ const undersized = "-----BEGIN DH PARAMETERS-----\nMAYCARcCAQU=\n-----END DH PARAMETERS-----\n";
875
+ if (probeRefusal({ dhparam: undersized }) === null) {
876
+ throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE);
877
+ }
878
+ }
829
879
  function assertUsableDhParameters(dhParameters) {
830
880
  if (!isDhParametersPem(dhParameters)) {
831
881
  throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_REJECTED);
@@ -850,7 +900,9 @@ function resolveTlsCipherPolicy(opts, side) {
850
900
  const supplied = side === "server" ? opts.dhParameters : void 0;
851
901
  if (supplied !== void 0) assertUsableDhParameters(supplied);
852
902
  const dhparam = supplied ?? (atna && side === "server" ? "auto" : void 0);
903
+ if (dhparam !== void 0) assertDhParametersEnforced();
853
904
  if (ciphers !== void 0) {
905
+ assertCipherListEnforced(atna);
854
906
  try {
855
907
  tls.createSecureContext({ ciphers });
856
908
  } catch (err) {
@@ -1373,6 +1425,20 @@ var Connection = class extends events.EventEmitter {
1373
1425
  });
1374
1426
  }
1375
1427
  };
1428
+ function checkCredentialMix(tls) {
1429
+ if (typeof tls !== "object" || tls.pfx === void 0) return;
1430
+ if (tls.cert !== void 0 || tls.key !== void 0) {
1431
+ throw new MllpTlsConfigurationError(MLLP_TLS_CREDENTIAL_CONFLICT);
1432
+ }
1433
+ }
1434
+ function checkPfx(pfx, passphrase) {
1435
+ if (pfx === void 0) return;
1436
+ try {
1437
+ tls.createSecureContext({ pfx, passphrase });
1438
+ } catch (err) {
1439
+ throw new MllpTlsConfigurationError(MLLP_TLS_PFX_REJECTED, { cause: err });
1440
+ }
1441
+ }
1376
1442
 
1377
1443
  // src/internal/control-id.ts
1378
1444
  var ASCII_M = 77;
@@ -1611,6 +1677,9 @@ function trimSpaces(value) {
1611
1677
  while (end > start && value.charAt(end - 1) === SPACE) end--;
1612
1678
  return value.substring(start, end);
1613
1679
  }
1680
+ function readConditionField(raw, delimiters) {
1681
+ return readTableField(raw, delimiters, TABLE_0155);
1682
+ }
1614
1683
  function readTableField(raw, delimiters, table) {
1615
1684
  if (raw === void 0) return { kind: "null", byteLength: 0 };
1616
1685
  const byteLength = raw.length;
@@ -1772,6 +1841,18 @@ var MllpServer = class extends events.EventEmitter {
1772
1841
  _host = null;
1773
1842
  _acceptedTotal = 0;
1774
1843
  _closedTotal = 0;
1844
+ /**
1845
+ * Sockets accepted and not yet closed, counted only when {@link ServerOptions.maxConnections} is
1846
+ * set: the number the cap is compared against.
1847
+ */
1848
+ _openSockets = 0;
1849
+ /** Sockets the connection cap closed at accept, so a runtime's report of them is recognised. */
1850
+ _closedAtAccept = /* @__PURE__ */ new WeakSet();
1851
+ /**
1852
+ * For each socket the connection cap counted, what gives its place back. Released once, however
1853
+ * many times it is called.
1854
+ */
1855
+ _capRelease = /* @__PURE__ */ new WeakMap();
1775
1856
  /** Count of `'tlsClientError'` events since listen(). */
1776
1857
  _tlsClientErrorsTotal = 0;
1777
1858
  /**
@@ -1798,11 +1879,17 @@ var MllpServer = class extends events.EventEmitter {
1798
1879
  "ServerOptions.maxConnections must be a positive integer, or left unset for no cap"
1799
1880
  );
1800
1881
  }
1882
+ const tlsInput = opts.tls;
1883
+ checkCredentialMix(tlsInput);
1884
+ if (tlsInput !== void 0 && tlsInput.pfx === void 0 && (tlsInput.cert === void 0 || tlsInput.key === void 0)) {
1885
+ throw new TypeError("ServerOptions.tls needs cert and key, or pfx");
1886
+ }
1801
1887
  this._opts = opts;
1802
1888
  this._isTls = opts.tls !== void 0;
1803
1889
  let cipherPolicy = null;
1804
1890
  if (opts.tls !== void 0) {
1805
1891
  try {
1892
+ checkPfx(opts.tls.pfx, opts.tls.passphrase);
1806
1893
  cipherPolicy = resolveTlsCipherPolicy(opts.tls, "server");
1807
1894
  } catch (err) {
1808
1895
  if (!(err instanceof MllpTlsConfigurationError)) throw err;
@@ -1817,6 +1904,7 @@ var MllpServer = class extends events.EventEmitter {
1817
1904
  const tlsServer = tls.createServer({
1818
1905
  cert: tlsOpts.cert,
1819
1906
  key: tlsOpts.key,
1907
+ pfx: tlsOpts.pfx,
1820
1908
  ...tlsOpts.ca !== void 0 ? { ca: tlsOpts.ca } : {},
1821
1909
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
1822
1910
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
@@ -1830,6 +1918,7 @@ var MllpServer = class extends events.EventEmitter {
1830
1918
  this._onSocketAccepted(socket);
1831
1919
  });
1832
1920
  tlsServer.on("tlsClientError", (err, socket) => {
1921
+ if (this._closedAtAccept.has(socket)) return;
1833
1922
  this._tlsClientErrorsTotal += 1;
1834
1923
  const nodeErr = err;
1835
1924
  const event = Object.freeze({
@@ -1854,26 +1943,67 @@ var MllpServer = class extends events.EventEmitter {
1854
1943
  this.emit("error", err);
1855
1944
  }
1856
1945
  });
1857
- if (maxConnections !== void 0) {
1858
- this._netServer.maxConnections = maxConnections;
1859
- this._netServer.on("drop", (data) => {
1860
- this._onConnectionOverCap(maxConnections, data);
1861
- });
1862
- }
1946
+ if (maxConnections !== void 0) this._gateConnections(maxConnections);
1947
+ }
1948
+ /**
1949
+ * Enforce {@link ServerOptions.maxConnections} by counting sockets here, at accept.
1950
+ *
1951
+ * WHY NOT THE LISTENER'S OWN `maxConnections`. Node's `net.Server` enforces a cap of its own and
1952
+ * reports each refusal on `'drop'`, but that report is the runtime's to make, and Deno's
1953
+ * `node:net` closes the socket without emitting `'drop'` (measured: Deno 2.9.8), so the cap held
1954
+ * and `'connectionRejected'` never fired. Counting here makes the cap and its event a property of
1955
+ * this package on every runtime.
1956
+ *
1957
+ * The gate sits IN FRONT of every `'connection'` listener the server already has, and replaces
1958
+ * them: for a plaintext server that is this class's own accept handler, and for a TLS server it
1959
+ * is the runtime's, which wraps the raw socket and starts the handshake. An over-cap socket is
1960
+ * destroyed before either runs, so it never becomes a `Connection`, costs no handshake, and is
1961
+ * not a `'tlsClientError'`. The count is of open sockets, the number that bounds file
1962
+ * descriptors: a socket counts from accept until its `'close'`, handshake in flight included.
1963
+ *
1964
+ * @param maxConnections - The validated cap.
1965
+ */
1966
+ _gateConnections(maxConnections) {
1967
+ const server = this._netServer;
1968
+ const downstream = server.listeners("connection");
1969
+ server.removeAllListeners("connection");
1970
+ server.on("connection", (socket) => {
1971
+ if (this._openSockets >= maxConnections) {
1972
+ const remoteAddress = socket.remoteAddress ?? null;
1973
+ const remotePort = socket.remotePort ?? null;
1974
+ this._closedAtAccept.add(socket);
1975
+ socket.destroy();
1976
+ this._onConnectionOverCap(maxConnections, remoteAddress, remotePort);
1977
+ return;
1978
+ }
1979
+ this._openSockets += 1;
1980
+ let released = false;
1981
+ const release = () => {
1982
+ if (released) return;
1983
+ released = true;
1984
+ this._openSockets -= 1;
1985
+ };
1986
+ this._capRelease.set(socket, release);
1987
+ try {
1988
+ for (const listener of downstream) listener.call(server, socket);
1989
+ } finally {
1990
+ socket.once("close", release);
1991
+ }
1992
+ });
1863
1993
  }
1864
1994
  /**
1865
- * Report a connection the listener closed at accept because the cap was full.
1995
+ * Report a connection closed at accept because the cap was full.
1866
1996
  *
1867
- * Contained: this runs inside the listener's own 'drop' callback, so a throwing subscriber would
1868
- * otherwise unwind into the accept path. The throw is surfaced on 'error' instead.
1997
+ * Contained: this runs inside the listener's own 'connection' callback, so a throwing subscriber
1998
+ * would otherwise unwind into the accept path. The throw is surfaced on 'error' instead.
1869
1999
  */
1870
- _onConnectionOverCap(maxConnections, data) {
2000
+ _onConnectionOverCap(maxConnections, remoteAddress, remotePort) {
1871
2001
  const event = Object.freeze({
1872
2002
  code: MLLP_CONNECTION_LIMIT_REACHED,
1873
2003
  message: CONNECTION_LIMIT_MESSAGE,
1874
2004
  maxConnections,
1875
- remoteAddress: data?.remoteAddress ?? null,
1876
- remotePort: data?.remotePort ?? null,
2005
+ remoteAddress,
2006
+ remotePort,
1877
2007
  timestamp: /* @__PURE__ */ new Date()
1878
2008
  });
1879
2009
  this._emitContained("connectionRejected", event);
@@ -2243,6 +2373,7 @@ var MllpServer = class extends events.EventEmitter {
2243
2373
  if (this._opts.keepaliveIntervalMs !== void 0) {
2244
2374
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
2245
2375
  }
2376
+ socket.setNoDelay(this._opts.noDelay !== false);
2246
2377
  const transport = this._isTls ? new TlsTransport(socket) : new NetTransport(socket);
2247
2378
  const mergedFraming = {
2248
2379
  ...SERVER_DEFAULT_FRAMING,
@@ -2250,6 +2381,8 @@ var MllpServer = class extends events.EventEmitter {
2250
2381
  };
2251
2382
  const connOpts = this._opts.onWarning !== void 0 ? { transport, framing: mergedFraming, onWarning: this._opts.onWarning } : { transport, framing: mergedFraming };
2252
2383
  const conn = new Connection(connOpts);
2384
+ const release = this._capRelease.get(socket);
2385
+ if (release !== void 0) socket.once("close", release);
2253
2386
  conn.beforeClose = () => Promise.resolve();
2254
2387
  conn.on("error", (errEvent) => {
2255
2388
  this._emitErrorIfListened(errEvent);
@@ -2589,6 +2722,24 @@ async function createStarterServer(opts) {
2589
2722
  return server;
2590
2723
  }
2591
2724
 
2725
+ // src/server/ack-code.ts
2726
+ function selectAckCode(input) {
2727
+ const { outcome } = input;
2728
+ if (outcome !== "AA" && outcome !== "AE" && outcome !== "AR") {
2729
+ throw new RangeError("selectAckCode: outcome must be one of AA, AE or AR");
2730
+ }
2731
+ const delimiters = delimitersFrom(input.encodingCharacters ?? "^~\\&");
2732
+ const accept = readConditionField(input.msh15, delimiters);
2733
+ const application = readConditionField(input.msh16, delimiters);
2734
+ return Object.freeze({
2735
+ code: acceptAckRequested(accept, outcome) ? acceptModeCounterpart(outcome) : outcome,
2736
+ mode: accept.kind === "null" && application.kind === "null" ? "original" : "enhanced",
2737
+ applicationAckRequested: application.kind !== "code" || acceptAckRequested(application, outcome),
2738
+ acceptTypeUnrecognised: accept.kind === "unrecognised",
2739
+ applicationTypeUnrecognised: application.kind === "unrecognised"
2740
+ });
2741
+ }
2742
+
2592
2743
  // src/client/correlator.ts
2593
2744
  var Correlator = class {
2594
2745
  _opts;
@@ -2658,8 +2809,11 @@ var Correlator = class {
2658
2809
  * `twoPhase` is the enhanced-mode state for a send being correlated by control ID.
2659
2810
  * Omitting it (or passing `null`) is what every other send does, and such an entry is
2660
2811
  * settled by the first acknowledgement matched to it, exactly as before.
2812
+ *
2813
+ * `ackTimeoutMs` is this send's own bound on the wait for its acknowledgement. Omitting it
2814
+ * gives the entry the correlator-wide `ackTimeoutMs`.
2661
2815
  */
2662
- enqueue(frame, controlIdOrNull, resolve, reject, twoPhase = null) {
2816
+ enqueue(frame, controlIdOrNull, resolve, reject, twoPhase = null, ackTimeoutMs) {
2663
2817
  if (this._pending.size >= this._opts.maxInFlight) return null;
2664
2818
  const key = this._opts.mode === "controlId" ? controlIdOrNull ?? `__seq-${++this._sendSeq}` : ++this._sendSeq;
2665
2819
  const entry = {
@@ -2668,6 +2822,7 @@ var Correlator = class {
2668
2822
  controlId: controlIdOrNull,
2669
2823
  byteCount: frame.length,
2670
2824
  sentAt: null,
2825
+ ackTimeoutMs: ackTimeoutMs ?? this._opts.ackTimeoutMs,
2671
2826
  resolve,
2672
2827
  reject,
2673
2828
  twoPhase
@@ -2844,7 +2999,7 @@ var Correlator = class {
2844
2999
  return null;
2845
3000
  }
2846
3001
  /**
2847
- * Sweep live entries; expire those past `sentAt + ackTimeoutMs`.
3002
+ * Sweep live entries; expire those past `sentAt` plus their own `ackTimeoutMs`.
2848
3003
  * Fires `onTimeout(entry, elapsedMs)`; entries move to graveyard.
2849
3004
  * Driven externally by `MllpClient`'s periodic sweep tick, Correlator
2850
3005
  * itself owns no timers.
@@ -2856,7 +3011,6 @@ var Correlator = class {
2856
3011
  */
2857
3012
  expireDue(now) {
2858
3013
  const t = now ?? this._opts.now();
2859
- const ackTimeoutMs = this._opts.ackTimeoutMs;
2860
3014
  for (const [key, entry] of this._pending) {
2861
3015
  if (entry.sentAt === null) continue;
2862
3016
  const twoPhase = entry.twoPhase;
@@ -2874,7 +3028,7 @@ var Correlator = class {
2874
3028
  }
2875
3029
  continue;
2876
3030
  }
2877
- if (entry.sentAt + ackTimeoutMs <= t) {
3031
+ if (entry.sentAt + entry.ackTimeoutMs <= t) {
2878
3032
  const elapsed = t - entry.sentAt;
2879
3033
  this._removeExpired(key, entry);
2880
3034
  if (twoPhase !== null) {
@@ -3239,6 +3393,14 @@ var OUTBOUND_WARNING_CONTEXT = Object.freeze({
3239
3393
  byteOffset: 0,
3240
3394
  elapsedSinceSendMs: 0
3241
3395
  });
3396
+ var MAX_CONNECT_TIMEOUT_MS = 2147483647;
3397
+ var CONNECT_TIMEOUT_MESSAGE = "connect timed out: the connection, including its TLS handshake when TLS is on, was not established within connectTimeoutMs";
3398
+ var ConnectTimeoutCause = class extends Error {
3399
+ code = "ETIMEDOUT";
3400
+ constructor() {
3401
+ super(CONNECT_TIMEOUT_MESSAGE);
3402
+ }
3403
+ };
3242
3404
  function identityOptions(host, servername) {
3243
3405
  const target = servername ?? host;
3244
3406
  if (net.isIP(target) === 0) return { servername: target };
@@ -3313,6 +3475,15 @@ var MllpClient = class extends events.EventEmitter {
3313
3475
  _connectSignal;
3314
3476
  /** Set when close()/destroy()/abort fires; reconnect handler short-circuits. */
3315
3477
  _userClosed = false;
3478
+ /**
3479
+ * The reason passed to the `destroy(reason)` that closed a connection still connecting, `null`
3480
+ * otherwise. The socket hands it back on `'error'`, and `connect()` compares by identity so the
3481
+ * caller's own reason is carried as the cause and never sorted into a TLS `connectionCause`.
3482
+ * Only the call that reaches the socket records it: a later `destroy()` finds the connection
3483
+ * already CLOSED and leaves it alone. Cleared once matched and at the start of `connect()`, so
3484
+ * the client does not keep the caller's object alive.
3485
+ */
3486
+ _destroyReason = null;
3316
3487
  /**
3317
3488
  * Sends parked inside the client with nothing written for them. See {@link ParkedSend}.
3318
3489
  * Every entry removes itself the moment its own wait ends, however it ends.
@@ -3369,6 +3540,13 @@ var MllpClient = class extends events.EventEmitter {
3369
3540
  */
3370
3541
  constructor(opts) {
3371
3542
  super();
3543
+ const connectTimeoutMs = opts.connectTimeoutMs;
3544
+ if (connectTimeoutMs !== void 0 && !(Number.isInteger(connectTimeoutMs) && connectTimeoutMs >= 1 && connectTimeoutMs <= MAX_CONNECT_TIMEOUT_MS)) {
3545
+ throw new RangeError(
3546
+ "ClientOptions.connectTimeoutMs must be an integer from 1 to 2147483647, or left unset for no bound"
3547
+ );
3548
+ }
3549
+ checkCredentialMix(opts.tls);
3372
3550
  this._opts = opts;
3373
3551
  this._ackTimeoutMs = opts.ackTimeoutMs ?? 3e4;
3374
3552
  this._applicationAckTimeoutMs = opts.applicationAckTimeoutMs;
@@ -3412,10 +3590,25 @@ var MllpClient = class extends events.EventEmitter {
3412
3590
  * TLS failures carry a `connectionCause`: `'tls-verify'` for certificate
3413
3591
  * verification failures, `'tls-handshake'` for TLS-protocol-shaped failures
3414
3592
  * ({@link isTlsProtocolError}); pure TCP failures carry none.
3593
+ * - `MllpConnectionError({ phase: 'connect', connectionCause: 'connect-timeout' })` if
3594
+ * {@link ClientOptions.connectTimeoutMs} is set and the TCP connect, or the TLS handshake
3595
+ * after it, did not complete in time. The socket is destroyed; nothing was written.
3596
+ * - `MllpConnectionError({ phase: 'connect' })` if {@link MllpClient.destroy} is called while
3597
+ * `connect()` is still connecting, over TCP or TLS, before or during the handshake. Its
3598
+ * `cause` is the reason passed to `destroy(reason)`, as it is, and its message is that
3599
+ * reason's; with no reason the cause is an `Error` whose message is `closed before connect`,
3600
+ * the same as for any socket that closes before connecting with no error. It carries no
3601
+ * `connectionCause` either way: a reason is the caller's own, so one whose message or `code`
3602
+ * reads like a TLS failure (`alert`, `ERR_SSL_*`, `EPROTO`, a certificate code) is never
3603
+ * sorted into `'tls-handshake'` or `'tls-verify'`. The first `destroy()` decides: a second
3604
+ * call before `connect()` settles, with a reason or without one, changes nothing.
3415
3605
  * - `MllpTlsConfigurationError` if the configured cipher-suite list cannot be
3416
- * honoured (the runtime rejects it, or `atnaTransportSecurity` and `ciphers`
3417
- * both declare one). Raised **before** a socket is opened, so nothing is left
3418
- * connected; identify it by `instanceof` plus its stable `code`.
3606
+ * honoured (the runtime rejects it, the runtime does not enforce cipher lists
3607
+ * at all, or `atnaTransportSecurity` and `ciphers` both declare one). Raised
3608
+ * **before** a socket is opened, so nothing is left connected; identify it by
3609
+ * `instanceof` plus its stable `code`.
3610
+ * - `MllpTlsConfigurationError` with `MLLP_TLS_PFX_REJECTED` if `tls.pfx` cannot be loaded
3611
+ * with `tls.passphrase` (see {@link TlsOptions.pfx}), also before a socket is opened.
3419
3612
  *
3420
3613
  * **Dual failure signal on initial connect:** the Connection's transport
3421
3614
  * error handler is attached before this promise's own error listener, so a
@@ -3456,12 +3649,14 @@ var MllpClient = class extends events.EventEmitter {
3456
3649
  if (signal !== void 0) {
3457
3650
  this._captureConnectSignal(signal);
3458
3651
  }
3652
+ this._destroyReason = null;
3459
3653
  return new Promise((resolve, reject) => {
3460
3654
  let aborted = false;
3461
3655
  const { socket, transport } = this._createSocketAndTransport();
3462
3656
  if (this._opts.keepaliveIntervalMs !== void 0) {
3463
3657
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
3464
3658
  }
3659
+ socket.setNoDelay(this._opts.noDelay !== false);
3465
3660
  this._socket = socket;
3466
3661
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
3467
3662
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -3470,12 +3665,14 @@ var MllpClient = class extends events.EventEmitter {
3470
3665
  const conn = new Connection(connOpts);
3471
3666
  this._attachConnection(conn);
3472
3667
  const connectEventName = this._opts.tls !== void 0 ? "secureConnect" : "connect";
3668
+ this._armConnectTimeout(socket, connectEventName);
3473
3669
  const cleanup = () => {
3474
3670
  if (signal !== void 0) {
3475
3671
  signal.removeEventListener("abort", abortHandler);
3476
3672
  }
3477
3673
  socket.removeListener(connectEventName, onSocketConnect);
3478
3674
  socket.removeListener("error", onSocketError);
3675
+ socket.removeListener("close", onSocketClose);
3479
3676
  };
3480
3677
  const abortHandler = () => {
3481
3678
  aborted = true;
@@ -3500,13 +3697,28 @@ var MllpClient = class extends events.EventEmitter {
3500
3697
  const onSocketError = (err) => {
3501
3698
  if (aborted) return;
3502
3699
  cleanup();
3700
+ if (err === this._destroyReason) {
3701
+ this._destroyReason = null;
3702
+ reject(new MllpConnectionError(err.message, { cause: err, phase: "connect" }));
3703
+ return;
3704
+ }
3503
3705
  reject(this._wrapConnectError(err, "connect"));
3504
3706
  };
3707
+ const onSocketClose = () => {
3708
+ cleanup();
3709
+ reject(
3710
+ new MllpConnectionError("connection closed before it was established", {
3711
+ cause: new Error("closed before connect"),
3712
+ phase: "connect"
3713
+ })
3714
+ );
3715
+ };
3505
3716
  if (signal !== void 0) {
3506
3717
  signal.addEventListener("abort", abortHandler, { once: true });
3507
3718
  }
3508
3719
  socket.once(connectEventName, onSocketConnect);
3509
3720
  socket.once("error", onSocketError);
3721
+ socket.once("close", onSocketClose);
3510
3722
  });
3511
3723
  }
3512
3724
  /**
@@ -3529,6 +3741,7 @@ var MllpClient = class extends events.EventEmitter {
3529
3741
  }
3530
3742
  const tlsOpts = tlsOpt === true ? {} : tlsOpt;
3531
3743
  const cipherPolicy = resolveTlsCipherPolicy(tlsOpts, "client");
3744
+ checkPfx(tlsOpts.pfx, tlsOpts.passphrase);
3532
3745
  const socket = tls.connect({
3533
3746
  host: this._opts.host,
3534
3747
  port: this._opts.port,
@@ -3537,6 +3750,7 @@ var MllpClient = class extends events.EventEmitter {
3537
3750
  ...tlsOpts.cert !== void 0 ? { cert: tlsOpts.cert } : {},
3538
3751
  ...tlsOpts.key !== void 0 ? { key: tlsOpts.key } : {},
3539
3752
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
3753
+ pfx: tlsOpts.pfx,
3540
3754
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
3541
3755
  ...tlsOpts.maxVersion !== void 0 ? { maxVersion: tlsOpts.maxVersion } : {},
3542
3756
  ...cipherPolicy,
@@ -3544,6 +3758,29 @@ var MllpClient = class extends events.EventEmitter {
3544
3758
  });
3545
3759
  return { socket, transport: new TlsTransport(socket) };
3546
3760
  }
3761
+ /**
3762
+ * Bound one connection attempt by {@link ClientOptions.connectTimeoutMs}, when it is set.
3763
+ *
3764
+ * Armed after the `Connection` has registered its own socket listeners (its set-once
3765
+ * `onClose`/`onError` would otherwise remove ours). The timer stops at the socket's connect
3766
+ * event (`'secureConnect'` for TLS, so the handshake is inside the bound) or at its `'close'`,
3767
+ * whichever comes first; a refused connect or an abort therefore leaves no timer behind. On
3768
+ * expiry the socket is destroyed with a {@link ConnectTimeoutCause}, which reaches the same
3769
+ * `'error'` listeners as any other connect failure: `connect()` rejects, and a reconnect
3770
+ * attempt hands it to the reconnect classifier.
3771
+ */
3772
+ _armConnectTimeout(socket, connectEventName) {
3773
+ const timeoutMs = this._opts.connectTimeoutMs;
3774
+ if (timeoutMs === void 0) return;
3775
+ const timer = setTimeout(() => {
3776
+ socket.destroy(new ConnectTimeoutCause());
3777
+ }, timeoutMs);
3778
+ const stop = () => {
3779
+ clearTimeout(timer);
3780
+ };
3781
+ socket.once(connectEventName, stop);
3782
+ socket.once("close", stop);
3783
+ }
3547
3784
  /**
3548
3785
  * Wrap a connect-phase socket error as `MllpConnectionError`, classifying
3549
3786
  * TLS failures into the additive `connectionCause`:
@@ -3558,6 +3795,13 @@ var MllpClient = class extends events.EventEmitter {
3558
3795
  * same shape as plaintext connect failures.
3559
3796
  */
3560
3797
  _wrapConnectError(err, phase) {
3798
+ if (err instanceof ConnectTimeoutCause) {
3799
+ return new MllpConnectionError(err.message, {
3800
+ cause: err,
3801
+ phase,
3802
+ connectionCause: "connect-timeout"
3803
+ });
3804
+ }
3561
3805
  if (this._opts.tls === void 0) {
3562
3806
  return new MllpConnectionError(err.message, { cause: err, phase });
3563
3807
  }
@@ -4038,6 +4282,7 @@ var MllpClient = class extends events.EventEmitter {
4038
4282
  if (this._opts.keepaliveIntervalMs !== void 0) {
4039
4283
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
4040
4284
  }
4285
+ socket.setNoDelay(this._opts.noDelay !== false);
4041
4286
  this._socket = socket;
4042
4287
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
4043
4288
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -4050,6 +4295,7 @@ var MllpClient = class extends events.EventEmitter {
4050
4295
  this._emitNegotiatedTlsParameters(socket);
4051
4296
  };
4052
4297
  const connectEventName = this._opts.tls !== void 0 ? "secureConnect" : "connect";
4298
+ this._armConnectTimeout(socket, connectEventName);
4053
4299
  socket.once("error", (sErr) => {
4054
4300
  if (this._lastError === null || this._lastError.message !== sErr.message) {
4055
4301
  this._lastError = sErr;
@@ -4225,8 +4471,8 @@ var MllpClient = class extends events.EventEmitter {
4225
4471
  *
4226
4472
  * Resolves with the ACK Buffer (framing stripped). Rejects with:
4227
4473
  * - `DOMException('Aborted', 'AbortError')` if `signal` aborts before the ACK.
4228
- * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs`.
4229
- * The clock starts at the underlying `write()` flush callback, NOT at
4474
+ * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs` (this send's own, else the
4475
+ * client's). The clock starts at the underlying `write()` flush callback, NOT at
4230
4476
  * the `send()` call.
4231
4477
  * - `MllpConnectionError({ phase: 'send' })` if the client is not connected.
4232
4478
  *
@@ -4255,7 +4501,10 @@ var MllpClient = class extends events.EventEmitter {
4255
4501
  *
4256
4502
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
4257
4503
  * @param opts.signal AbortSignal, aborting cancels the ACK wait.
4258
- * @param opts.ackTimeoutMs Per-send override of the backpressure wait budget.
4504
+ * @param opts.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4505
+ * moment its bytes are flushed, in place of the client's `ackTimeoutMs`. Under
4506
+ * `onBackpressure: "wait"` it also bounds the wait for queue room, and the
4507
+ * acknowledgement wait then starts afresh once the send is written.
4259
4508
  * @param opts.applicationAckTimeoutMs Per-send override of the second wait's bound.
4260
4509
  * @param opts.onCommitAck Called with the commit disposition when the peer commits the
4261
4510
  * message ahead of its application acknowledgement. See {@link CommitAckReport}.
@@ -4310,21 +4559,34 @@ var MllpClient = class extends events.EventEmitter {
4310
4559
  opts
4311
4560
  );
4312
4561
  }
4562
+ const sendAckTimeoutMs = opts?.ackTimeoutMs;
4313
4563
  return new Promise((resolve, reject) => {
4314
4564
  let abortListener = null;
4315
- const wrappedResolve = (ack) => {
4565
+ let ackDeadline;
4566
+ let settled = false;
4567
+ const settle = () => {
4568
+ settled = true;
4316
4569
  if (signal !== void 0 && abortListener !== null) {
4317
4570
  signal.removeEventListener("abort", abortListener);
4318
4571
  }
4572
+ clearTimeout(ackDeadline);
4573
+ };
4574
+ const wrappedResolve = (ack) => {
4575
+ settle();
4319
4576
  resolve(ack);
4320
4577
  };
4321
4578
  const wrappedReject = (err) => {
4322
- if (signal !== void 0 && abortListener !== null) {
4323
- signal.removeEventListener("abort", abortListener);
4324
- }
4579
+ settle();
4325
4580
  reject(err);
4326
4581
  };
4327
- const key = correlator.enqueue(frame, controlId, wrappedResolve, wrappedReject, twoPhase);
4582
+ const key = correlator.enqueue(
4583
+ frame,
4584
+ controlId,
4585
+ wrappedResolve,
4586
+ wrappedReject,
4587
+ twoPhase,
4588
+ sendAckTimeoutMs
4589
+ );
4328
4590
  if (key === null) {
4329
4591
  const parked = { cancel: () => void 0 };
4330
4592
  const neverDelivered = () => new MllpNeverDeliveredError({
@@ -4366,6 +4628,12 @@ var MllpClient = class extends events.EventEmitter {
4366
4628
  }
4367
4629
  conn.send(frame);
4368
4630
  correlator.markFlushed(key, Date.now());
4631
+ if (sendAckTimeoutMs !== void 0 && !settled) {
4632
+ ackDeadline = setTimeout(() => {
4633
+ correlator.expireDue();
4634
+ }, sendAckTimeoutMs);
4635
+ ackDeadline.unref();
4636
+ }
4369
4637
  this._sentTotal += 1;
4370
4638
  });
4371
4639
  }
@@ -4762,6 +5030,12 @@ var MllpClient = class extends events.EventEmitter {
4762
5030
  * ever written for it; that is a statement about the bytes, not about how the client was
4763
5031
  * shut down, so it holds on this path too.
4764
5032
  *
5033
+ * A {@link MllpClient.connect} still connecting rejects with an `MllpConnectionError` whose
5034
+ * `phase` is `'connect'` and no `connectionCause`. Its `cause` is `reason` when one is given,
5035
+ * never classified as a TLS failure whatever its message or `code`, and otherwise an `Error`
5036
+ * whose message is `closed before connect`. Only the first call reaches the socket, so a
5037
+ * second `destroy()` before `connect()` settles, with or without a reason, changes nothing.
5038
+ *
4765
5039
  * @example
4766
5040
  * ```typescript
4767
5041
  * client.destroy(new Error('shutting down'));
@@ -4782,6 +5056,7 @@ var MllpClient = class extends events.EventEmitter {
4782
5056
  this._teardownCorrelator(teardownReason);
4783
5057
  const conn = this._connection;
4784
5058
  if (conn === null) return;
5059
+ if (conn.state === "CONNECTING") this._destroyReason = reason ?? null;
4785
5060
  conn.destroy(reason);
4786
5061
  }
4787
5062
  /**
@@ -4862,6 +5137,8 @@ async function createStarterClient(opts) {
4862
5137
  ...opts.retryStrategy !== void 0 ? { retryStrategy: opts.retryStrategy } : {},
4863
5138
  ...opts.keepaliveIntervalMs !== void 0 ? { keepaliveIntervalMs: opts.keepaliveIntervalMs } : {},
4864
5139
  ...opts.deadPeerTimeoutMs !== void 0 ? { deadPeerTimeoutMs: opts.deadPeerTimeoutMs } : {},
5140
+ noDelay: opts.noDelay !== false,
5141
+ ...opts.connectTimeoutMs !== void 0 ? { connectTimeoutMs: opts.connectTimeoutMs } : {},
4865
5142
  ...opts.tls !== void 0 ? { tls: opts.tls } : {}
4866
5143
  };
4867
5144
  const client = createClient(clientOpts);
@@ -5182,7 +5459,7 @@ async function runDifferential(options = {}) {
5182
5459
  }
5183
5460
 
5184
5461
  // src/index.ts
5185
- var VERSION = "0.1.10";
5462
+ var VERSION = "0.1.12";
5186
5463
 
5187
5464
  exports.ATNA_CIPHER_LIST = ATNA_CIPHER_LIST;
5188
5465
  exports.ATNA_CIPHER_SUITES = ATNA_CIPHER_SUITES;
@@ -5192,8 +5469,12 @@ exports.MLLP_BIND_ALL_INTERFACES = MLLP_BIND_ALL_INTERFACES;
5192
5469
  exports.MLLP_CONNECTION_LIMIT_REACHED = MLLP_CONNECTION_LIMIT_REACHED;
5193
5470
  exports.MLLP_DIFF_PEER_UNPARSEABLE = MLLP_DIFF_PEER_UNPARSEABLE;
5194
5471
  exports.MLLP_TLS_CIPHER_LIST_REJECTED = MLLP_TLS_CIPHER_LIST_REJECTED;
5472
+ exports.MLLP_TLS_CIPHER_LIST_UNENFORCEABLE = MLLP_TLS_CIPHER_LIST_UNENFORCEABLE;
5195
5473
  exports.MLLP_TLS_CIPHER_OPTION_CONFLICT = MLLP_TLS_CIPHER_OPTION_CONFLICT;
5474
+ exports.MLLP_TLS_CREDENTIAL_CONFLICT = MLLP_TLS_CREDENTIAL_CONFLICT;
5196
5475
  exports.MLLP_TLS_DH_PARAMETERS_REJECTED = MLLP_TLS_DH_PARAMETERS_REJECTED;
5476
+ exports.MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE = MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE;
5477
+ exports.MLLP_TLS_PFX_REJECTED = MLLP_TLS_PFX_REJECTED;
5197
5478
  exports.MLLP_TLS_VERIFY_DISABLED = MLLP_TLS_VERIFY_DISABLED;
5198
5479
  exports.MllpAckError = MllpAckError;
5199
5480
  exports.MllpApplicationAckError = MllpApplicationAckError;
@@ -5233,6 +5514,7 @@ exports.resolveDifferentialPeer = resolveDifferentialPeer;
5233
5514
  exports.resolveNackCode = resolveNackCode;
5234
5515
  exports.resolveTlsCipherPolicy = resolveTlsCipherPolicy;
5235
5516
  exports.runDifferential = runDifferential;
5517
+ exports.selectAckCode = selectAckCode;
5236
5518
  exports.tlsConfigurationMessage = tlsConfigurationMessage;
5237
5519
  //# sourceMappingURL=index.cjs.map
5238
5520
  //# sourceMappingURL=index.cjs.map