iosignal 6.1.2 → 7.0.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.
@@ -11,12 +11,13 @@ var require$$7 = require('url');
11
11
  var require$$0$1 = require('zlib');
12
12
  var require$$0$2 = require('buffer');
13
13
  var require$$2 = require('util');
14
+ var node_perf_hooks = require('node:perf_hooks');
14
15
  var os = require('os');
15
16
  var fs = require('fs');
16
17
  var process$1 = require('process');
17
18
  var path = require('path');
18
19
 
19
- var version$1 = "6.1.2";
20
+ var version$1 = "7.0.2";
20
21
  var pkg = {
21
22
  version: version$1};
22
23
 
@@ -965,7 +966,7 @@ class IOCore extends EventEmitter {
965
966
 
966
967
 
967
968
  /**
968
- * Performs common cleanup for the connection. It clears pending promises,
969
+ * Performs common cleanup for the connection. It rejects pending RPCs,
969
970
  * resets the socket reference, and sets the state to closed.
970
971
  * This method is guarded to only run once.
971
972
  * If autoReconnect is false, it also clears the keep-alive timer.
@@ -1000,6 +1001,12 @@ class IOCore extends EventEmitter {
1000
1001
  }
1001
1002
  this.socket = null;
1002
1003
  }
1004
+ const error = new Error('Connection closed');
1005
+ error.code = 'CONNECTION_CLOSED';
1006
+ for (const [, reject, timeoutId] of this.promiseMap.values()) {
1007
+ clearTimeout(timeoutId);
1008
+ reject(error);
1009
+ }
1003
1010
  this.promiseMap.clear();
1004
1011
  this.cid = '';
1005
1012
  if (this.boho) this.boho.isAuthorized = false;
@@ -1693,11 +1700,12 @@ class IOCore extends EventEmitter {
1693
1700
  call(target, topic, ...args) {
1694
1701
  if (!target || !topic)
1695
1702
  return Promise.reject(new Error('request need target and topic)'))
1703
+ this.mid = (this.mid + 1) & 0xffff;
1696
1704
  let sigPack;
1697
1705
  if (args.length > 0) {
1698
1706
  sigPack = $$1.pack(
1699
1707
  $$1.MB('#MsgType', '8', IOMsg.CALL),
1700
- $$1.MB('mid', '16', ++this.mid),
1708
+ $$1.MB('mid', '16', this.mid),
1701
1709
  $$1.MB('target', target),
1702
1710
  $$1.MB('topic', topic),
1703
1711
  $$1.MBA(...args)
@@ -1705,7 +1713,7 @@ class IOCore extends EventEmitter {
1705
1713
  } else {
1706
1714
  sigPack = $$1.pack(
1707
1715
  $$1.MB('#MsgType', '8', IOMsg.CALL),
1708
- $$1.MB('mid', '16', ++this.mid),
1716
+ $$1.MB('mid', '16', this.mid),
1709
1717
  $$1.MB('target', target),
1710
1718
  $$1.MB('topic', topic)
1711
1719
  );
@@ -2057,54 +2065,45 @@ class CongRx extends require$$0.Transform {
2057
2065
 
2058
2066
 
2059
2067
  parse() {
2060
- let head = this.buffer[0];
2061
- let headerLen;
2062
- let payloadSize;
2063
-
2064
- if (head == CongType.TYPE_LEN1) {
2065
- headerLen = 2;
2066
- if (this.buffer.byteLength < headerLen) return;
2067
- payloadSize = this.buffer.readUint8(1);
2068
-
2069
- } else if (head == CongType.TYPE_LEN2) {
2070
- headerLen = 3;
2071
- if (this.buffer.byteLength < headerLen) return;
2072
- payloadSize = this.buffer.readUint16LE(1);
2073
-
2074
- } else if (head == CongType.TYPE_LEN3) {
2075
- headerLen = 4;
2076
- if (this.buffer.byteLength < headerLen) return;
2077
- payloadSize = this.buffer.readUint16LE(1) + this.buffer.readUint8(3) * 65536;
2078
-
2079
- } else if (head == CongType.TYPE_LEN4) {
2080
- headerLen = 5;
2081
- if (this.buffer.byteLength < headerLen) return;
2082
- payloadSize = this.buffer.readUint32LE(1);
2083
-
2084
- } else {
2085
- this.emit('wrong', this.buffer);
2086
- this.buffer = Buffer.alloc(0);
2087
- }
2068
+ while (this.buffer.byteLength > 0) {
2069
+ const head = this.buffer[0];
2070
+ let headerLen;
2071
+ let payloadSize;
2072
+
2073
+ if (head === CongType.TYPE_LEN1) {
2074
+ headerLen = 2;
2075
+ if (this.buffer.byteLength < headerLen) return;
2076
+ payloadSize = this.buffer.readUint8(1);
2077
+ } else if (head === CongType.TYPE_LEN2) {
2078
+ headerLen = 3;
2079
+ if (this.buffer.byteLength < headerLen) return;
2080
+ payloadSize = this.buffer.readUint16LE(1);
2081
+ } else if (head === CongType.TYPE_LEN3) {
2082
+ headerLen = 4;
2083
+ if (this.buffer.byteLength < headerLen) return;
2084
+ payloadSize = this.buffer.readUint16LE(1) + this.buffer.readUint8(3) * 65536;
2085
+ } else if (head === CongType.TYPE_LEN4) {
2086
+ headerLen = 5;
2087
+ if (this.buffer.byteLength < headerLen) return;
2088
+ payloadSize = this.buffer.readUint32LE(1);
2089
+ } else {
2090
+ this.emit('wrong', this.buffer);
2091
+ this.buffer = Buffer.alloc(0);
2092
+ return;
2093
+ }
2088
2094
 
2095
+ const frameSize = headerLen + payloadSize;
2096
+ if (this.buffer.byteLength < frameSize) return;
2089
2097
 
2090
- if (payloadSize == this.buffer.byteLength - headerLen) {
2091
- this.frames.push(this.buffer.subarray(headerLen));
2092
- this.buffer = Buffer.alloc(0);
2093
- return
2094
- } else if (payloadSize < this.buffer.byteLength - headerLen) {
2095
- this.frames.push(this.buffer.subarray(headerLen, headerLen + payloadSize));
2096
- this.buffer = this.buffer.subarray(headerLen + payloadSize);
2097
- this.parse();
2098
- } else {
2099
- // not ready
2100
- // console.log('+')
2101
- return
2098
+ this.frames.push(this.buffer.subarray(headerLen, frameSize));
2099
+ if (this.buffer.byteLength === frameSize) {
2100
+ this.buffer = Buffer.alloc(0);
2101
+ return;
2102
+ }
2103
+ // Consume each complete frame without growing the call stack.
2104
+ this.buffer = this.buffer.subarray(frameSize);
2102
2105
  }
2103
-
2104
-
2105
2106
  }
2106
-
2107
-
2108
2107
  }
2109
2108
 
2110
2109
  class IOCongSocket extends IOCore {
@@ -7332,6 +7331,7 @@ let serverOption = {
7332
7331
  httpServer: null,
7333
7332
  wsPath: null,
7334
7333
  timeout: 50000,
7334
+ pingTimeoutGrace: 5000,
7335
7335
  showMessage: 'none',
7336
7336
  showMetric: 0,
7337
7337
  showChannel: 0,
@@ -7371,6 +7371,13 @@ let serverOption = {
7371
7371
  limitCounter: 1000
7372
7372
  },
7373
7373
 
7374
+ // Applied to each new Server instance; packet layouts remain unchanged.
7375
+ security: {
7376
+ maxClockSkewMs: 60000,
7377
+ authChallengeMaxAgeMs: 60000,
7378
+ maxReplayEntries: 65536
7379
+ },
7380
+
7374
7381
  auth: {
7375
7382
  delay_auth_fail: 600
7376
7383
  },
@@ -7394,6 +7401,13 @@ class RemoteCore {
7394
7401
  socket.openTime = Date.now();
7395
7402
 
7396
7403
  this.boho = new it();
7404
+ this.security = manager.server.security;
7405
+ this._challengeIssuedAt = null;
7406
+ this._challengeUsed = false;
7407
+ this._replayBuckets = new Map();
7408
+ this._replayEntries = 0;
7409
+ this._replayExpiredBefore = 0;
7410
+ this.securityFailure = null;
7397
7411
  this.encMode = ENC_MODE.AUTO;
7398
7412
  this.channels = new Set(); // subscribed tags
7399
7413
  this.retain_signal = new Map();
@@ -7469,6 +7483,7 @@ class RemoteCore {
7469
7483
  rxQuotaChecker(message) {
7470
7484
  let rxBytes = message.byteLength;
7471
7485
  this.manager.rxBytes += rxBytes;
7486
+ if (this.manager.telemetry) { this.manager.telemetry.rxBytes += rxBytes; this.manager.telemetry.rxMessages++; }
7472
7487
 
7473
7488
  if (serverOption.useQuota.signalSize && (rxBytes > this.quota.signalSize)) {
7474
7489
  console.log('## quota: size over');
@@ -7482,15 +7497,92 @@ class RemoteCore {
7482
7497
  return true;
7483
7498
  }
7484
7499
 
7500
+ issueAuthChallenge() {
7501
+ const packet = this.boho.server_time_nonce();
7502
+ this._challengeIssuedAt = node_perf_hooks.performance.now();
7503
+ return packet;
7504
+ }
7505
+
7506
+ securityMismatch(reason) {
7507
+ if (this._closing || this.state === STATE.CLOSED) return false;
7508
+ this.securityFailure = reason;
7509
+ this.boho.clearAuth();
7510
+ this.isAdmin = false;
7511
+ this._replayBuckets.clear();
7512
+ this._replayEntries = 0;
7513
+ this.close(true);
7514
+ this.manager.attackLogger?.log(`SECURITY #${this.ssid} reason:${reason}`);
7515
+ this.manager.server.emit('security:mismatch', this, reason);
7516
+ return false;
7517
+ }
7518
+
7519
+ checkAuthChallenge() {
7520
+ if (this._closing || this.state === STATE.CLOSED) return false;
7521
+ if (this._challengeUsed) return this.securityMismatch('AUTH_CHALLENGE_REUSED');
7522
+ if (this._challengeIssuedAt === null ||
7523
+ node_perf_hooks.performance.now() - this._challengeIssuedAt > this.security.authChallengeMaxAgeMs) {
7524
+ return this.securityMismatch('AUTH_CHALLENGE_EXPIRED');
7525
+ }
7526
+ return true;
7527
+ }
7528
+
7529
+ // Called only after Boho has authenticated the packet's clock and payload.
7530
+ acceptEncryptedClock(message, receivedAtMs) {
7531
+ const seconds = message.readUInt32LE(5);
7532
+ const milliseconds = message.readUInt16LE(9);
7533
+ const counter = message.readUInt16LE(11);
7534
+ const packetTime = seconds * 1000 + milliseconds;
7535
+ const earliest = receivedAtMs - this.security.maxClockSkewMs;
7536
+ if (milliseconds >= 1000 || Math.abs(receivedAtMs - packetTime) > this.security.maxClockSkewMs ||
7537
+ packetTime < this._replayExpiredBefore) {
7538
+ return this.securityMismatch('TIME_MISMATCH');
7539
+ }
7540
+ // Never reopen an expired timestamp range after the server clock moves back.
7541
+ this._replayExpiredBefore = Math.max(this._replayExpiredBefore, earliest);
7542
+ for (const [second, values] of this._replayBuckets) {
7543
+ if ((second + 1) * 1000 <= this._replayExpiredBefore) {
7544
+ this._replayEntries -= values.size;
7545
+ this._replayBuckets.delete(second);
7546
+ }
7547
+ }
7548
+ let bucket = this._replayBuckets.get(seconds);
7549
+ const value = milliseconds * 65536 + counter;
7550
+ if (bucket?.has(value)) return this.securityMismatch('REPLAY_DETECTED');
7551
+ // Fail closed instead of evicting still-valid replay evidence under load.
7552
+ if (this._replayEntries >= this.security.maxReplayEntries) {
7553
+ return this.securityMismatch('REPLAY_CAPACITY_EXCEEDED');
7554
+ }
7555
+ if (!bucket) this._replayBuckets.set(seconds, bucket = new Set());
7556
+ bucket.add(value);
7557
+ this._replayEntries++;
7558
+ return true;
7559
+ }
7560
+
7561
+ decryptSessionPacket(message, receivedAtMs) {
7562
+ let decoded;
7563
+ try {
7564
+ decoded = this.boho.decrypt_488(message);
7565
+ } catch {
7566
+ this.securityMismatch('INVALID_ENCRYPTED_PACKET');
7567
+ return;
7568
+ }
7569
+ if (!decoded) {
7570
+ this.securityMismatch('INVALID_ENCRYPTED_PACKET');
7571
+ return;
7572
+ }
7573
+ if (this.acceptEncryptedClock(message, receivedAtMs)) return decoded;
7574
+ }
7575
+
7485
7576
  onTimeDelayMessage(message, isBinary = true) {
7577
+ const receivedAtMs = Date.now();
7486
7578
  setTimeout(() => {
7487
- this.onSocketMessage(message, isBinary);
7579
+ this.onSocketMessage(message, isBinary, receivedAtMs);
7488
7580
  }
7489
7581
  , serverOption.debug.delay);
7490
7582
  }
7491
7583
 
7492
7584
  // CongSocket or WebSocket
7493
- onSocketMessage(message, isBinary = true) {
7585
+ onSocketMessage(message, isBinary = true, receivedAtMs = Date.now()) {
7494
7586
 
7495
7587
  if (this._closing || this.state === STATE.CLOSED) return;
7496
7588
 
@@ -7506,12 +7598,7 @@ class RemoteCore {
7506
7598
 
7507
7599
  if (msgType === it.BohoMsg.ENC_488) {
7508
7600
 
7509
- try {
7510
- decoded = this.boho.decrypt_488(message);
7511
- } catch (err) {
7512
- console.log('-- E488 DEC_FAIL', err);
7513
- return
7514
- }
7601
+ decoded = this.decryptSessionPacket(message, receivedAtMs);
7515
7602
 
7516
7603
  if (decoded) {
7517
7604
  msgType = decoded[0];
@@ -7521,12 +7608,7 @@ class RemoteCore {
7521
7608
  }
7522
7609
 
7523
7610
  } else if (msgType === it.BohoMsg.ENC_E2E) { // symetric E2EE Signal
7524
- try {
7525
- decoded = this.boho.decrypt_488(message);
7526
- } catch (err) {
7527
- // console.log('-- E2E DEC_FAIL', err)
7528
- return
7529
- }
7611
+ decoded = this.decryptSessionPacket(message, receivedAtMs);
7530
7612
  // console.log('e2e unpack:', decoded )
7531
7613
  if (decoded) {
7532
7614
  msgType = decoded[0];
@@ -7671,13 +7753,17 @@ class RemoteCore {
7671
7753
  // client's auth requst
7672
7754
  case it.BohoMsg.AUTH_REQ:
7673
7755
  if (!this.manager.authManager) return
7674
- // Do not start overlapping verification on the same connection.
7675
- if (this.state === STATE.AUTH_REQ) return;
7756
+ // A second request while verification is pending must not restart auth.
7757
+ if (this.state === STATE.AUTH_REQ) {
7758
+ this.securityMismatch('AUTH_IN_PROGRESS');
7759
+ return;
7760
+ }
7676
7761
  if (![STATE.SERVER_READY, STATE.AUTH_RES, STATE.AUTH_FAIL, STATE.CID_RES].includes(this.state)) {
7677
7762
  console.log('protocol error. must called auth_req after server_ready');
7678
7763
  this.close();
7679
7764
  return;
7680
7765
  }
7766
+ if (!this.checkAuthChallenge()) return;
7681
7767
  this.setState(STATE.AUTH_REQ);
7682
7768
  //async
7683
7769
  this.manager.authManager.verify_auth_req(message, this)
@@ -7869,6 +7955,10 @@ const decoder$2 = new TextDecoder();
7869
7955
  class Remote extends RemoteCore {
7870
7956
  constructor(socket, req, manager) {
7871
7957
  super(socket, manager);
7958
+ this.txQueuePeakBytes = 0;
7959
+ this.txWriteFalseCount = 0;
7960
+ this.txBlockedSince = null;
7961
+ this.txDrainMaxMs = 0;
7872
7962
  this.socketType = socket.socketType;
7873
7963
 
7874
7964
  if (this.socketType === 'websocket') {
@@ -7905,6 +7995,11 @@ class Remote extends RemoteCore {
7905
7995
  this.manager.removeRemote(this);
7906
7996
  };
7907
7997
  } else { // TCP else
7998
+ socket.on('drain', () => {
7999
+ if (this.txBlockedSince === null) return;
8000
+ this.txDrainMaxMs = Math.max(this.txDrainMaxMs, node_perf_hooks.performance.now() - this.txBlockedSince);
8001
+ this.txBlockedSince = null;
8002
+ });
7908
8003
  this.congRx = new CongRx();
7909
8004
  socket.on('data', data => { this.congRx.write(data); });
7910
8005
 
@@ -7973,6 +8068,7 @@ class Remote extends RemoteCore {
7973
8068
  // any type of received messages: message, ping, pong
7974
8069
  receiveMonitor() {
7975
8070
  this.socket.rxCounter++;
8071
+ if (this.socket.isAlive === false) this.manager.heartbeatPending.delete(this);
7976
8072
  this.socket.isAlive = true;
7977
8073
  }
7978
8074
 
@@ -8036,10 +8132,16 @@ class Remote extends RemoteCore {
8036
8132
  }
8037
8133
  }
8038
8134
 
8135
+ recordTxQueue() {
8136
+ const queued = this.socket.bufferedAmount ?? this.socket.writableLength ?? 0;
8137
+ if (queued > this.txQueuePeakBytes) this.txQueuePeakBytes = queued;
8138
+ }
8139
+
8039
8140
  // node.js server side remote.
8040
8141
  send(message, isBinary) {
8041
8142
  // console.log(`<-S [${IOMsg[ message[0]]}]`)
8042
8143
  this.manager.txBytes += message.byteLength;
8144
+ if (this.manager.telemetry) { this.manager.telemetry.txBytes += message.byteLength; this.manager.telemetry.txMessages++; }
8043
8145
  this.socket.txCounter++;
8044
8146
  if (this.socketType === 'websocket') {
8045
8147
  if (this.socket.readyState === 1) {
@@ -8048,6 +8150,7 @@ class Remote extends RemoteCore {
8048
8150
  } else {
8049
8151
  this.socket.send(message);
8050
8152
  }
8153
+ this.recordTxQueue();
8051
8154
  } else {
8052
8155
  console.log('server(ws)Remote.send() called. not open state. current readyState:', this.socket.readyState );
8053
8156
  this.close(true);
@@ -8055,7 +8158,12 @@ class Remote extends RemoteCore {
8055
8158
 
8056
8159
  } else { //CongSocket
8057
8160
  if (this.socket.readyState == 'open') {
8058
- this.socket.write(pack(message));
8161
+ const writable = this.socket.write(pack(message));
8162
+ this.recordTxQueue();
8163
+ if (!writable) {
8164
+ this.txWriteFalseCount++;
8165
+ if (this.txBlockedSince === null) this.txBlockedSince = node_perf_hooks.performance.now();
8166
+ }
8059
8167
  } else {
8060
8168
  console.log('server(cong)Remote.send() called. not open state. current readyState:', this.socket.readyState );
8061
8169
  this.close(true);
@@ -8259,6 +8367,12 @@ class Manager {
8259
8367
 
8260
8368
  constructor(server, authManager) {
8261
8369
  this.server = server;
8370
+ this.pingPeriod = serverOption.timeout;
8371
+ this.pingGrace = serverOption.pingTimeoutGrace;
8372
+ if (!Number.isFinite(this.pingPeriod) || this.pingPeriod <= 0 ||
8373
+ !Number.isFinite(this.pingGrace) || this.pingGrace < 0) {
8374
+ throw new RangeError('Invalid heartbeat period or grace');
8375
+ }
8262
8376
  this.txBytes = 0;
8263
8377
  this.rxBytes = 0;
8264
8378
 
@@ -8285,25 +8399,20 @@ class Manager {
8285
8399
  this.metrics = new Metrics(this);
8286
8400
  this.lastSSID = 0;
8287
8401
 
8288
- this.pingIntervalID = setInterval(e => {
8289
- this.remotes.forEach(function each(remo) {
8290
- let socket = remo.socket;
8291
- if (socket.isAlive === false) {
8292
- console.log('## timeout. cid:', remo.cid);
8293
- remo.close();
8294
- return;
8295
- }
8296
-
8297
- socket.txCounter++;
8298
- socket.isAlive = false;
8299
- if (remo.socketType === 'websocket') {
8300
- socket.ping();
8301
- } else {
8302
- remo.ping();
8303
- }
8304
-
8305
- });
8306
- }, serverOption.timeout);
8402
+ const groups = Math.min(50, Math.max(1, Math.floor(this.pingPeriod / 1000)));
8403
+ this.pingGroups = Array.from({ length: groups }, () => new Set());
8404
+ this.nextPingGroup = 0;
8405
+ this.pingGroupCursor = 0;
8406
+ // Same timeout for all entries: insertion order is also deadline order.
8407
+ this.heartbeatPending = new Map();
8408
+ this.pingTickMs = this.pingPeriod / groups;
8409
+ this.heartbeatStopped = false;
8410
+ const tick = () => {
8411
+ if (this.heartbeatStopped) return;
8412
+ this.heartbeatTick();
8413
+ if (!this.heartbeatStopped) this.pingIntervalID = setTimeout(tick, this.pingTickMs);
8414
+ };
8415
+ this.pingIntervalID = setTimeout(tick, this.pingTickMs);
8307
8416
 
8308
8417
  if (serverOption.showMetric) {
8309
8418
  this.monitIntervalID = setInterval((e) => {
@@ -8315,11 +8424,38 @@ class Manager {
8315
8424
  }
8316
8425
 
8317
8426
 
8427
+ heartbeatTick() {
8428
+ const now = node_perf_hooks.performance.now();
8429
+ // Process only expired requests, not every connected peer.
8430
+ for (const [remote, deadline] of this.heartbeatPending) {
8431
+ if (deadline > now) break;
8432
+ this.heartbeatPending.delete(remote);
8433
+ if (!remote._closing && remote.socket.isAlive === false) remote.close(true);
8434
+ }
8435
+ // The single timer schedules its next tick after this work; missed groups are not replayed.
8436
+ const group = this.pingGroups[this.pingGroupCursor];
8437
+ this.pingGroupCursor = (this.pingGroupCursor + 1) % this.pingGroups.length;
8438
+ for (const remote of group) {
8439
+ if (remote._closing || this.heartbeatPending.has(remote)) continue;
8440
+ remote.socket.isAlive = false;
8441
+ this.heartbeatPending.set(remote, node_perf_hooks.performance.now() + this.pingPeriod + this.pingGrace);
8442
+ try {
8443
+ remote.ping();
8444
+ } catch {
8445
+ this.heartbeatPending.delete(remote);
8446
+ remote.close(true);
8447
+ }
8448
+ }
8449
+ }
8450
+
8318
8451
  addRemote(socket, req) {
8319
8452
  socket.isAlive = true;
8320
8453
  let remote = new Remote(socket, req, this);
8321
8454
  this.remotes.add(remote);
8322
- remote.send( remote.boho.server_time_nonce() );
8455
+ remote.pingGroup = this.nextPingGroup;
8456
+ this.pingGroups[remote.pingGroup].add(remote);
8457
+ this.nextPingGroup = (this.nextPingGroup + 1) % this.pingGroups.length;
8458
+ remote.send(remote.issueAuthChallenge());
8323
8459
  remote.send( Buffer.from([ IOMsg.SERVER_READY]) );
8324
8460
  remote.setState(STATE.SERVER_READY);
8325
8461
  this.lastSSID = remote.ssid;
@@ -8332,6 +8468,8 @@ class Manager {
8332
8468
  removeRemote(remote) {
8333
8469
 
8334
8470
  remote._closing = true;
8471
+ this.pingGroups[remote.pingGroup]?.delete(remote);
8472
+ this.heartbeatPending.delete(remote);
8335
8473
  remote.setState(STATE.CLOSED);
8336
8474
 
8337
8475
  let remoteInfo = `- IP:${remote.ip} #${remote.ssid} cid:${remote.cid} ${remote?.socket.socketType === 'websocket' ? "WS" : "CS"} `;
@@ -8510,6 +8648,7 @@ class Manager {
8510
8648
 
8511
8649
  }
8512
8650
 
8651
+ if (this.telemetry) this.telemetry.publishes++;
8513
8652
  let sentCounter = 0;
8514
8653
  if (this.channel_map.has(tag)) {
8515
8654
  // console.log('raw channel_map matched tag:', tag)
@@ -8521,6 +8660,7 @@ class Manager {
8521
8660
  } else {
8522
8661
  limit = remotes.size;
8523
8662
  }
8663
+ if (this.telemetry) this.telemetry.quotaExcluded += remotes.size - limit;
8524
8664
  let peers = remotes.values();
8525
8665
  while (sentCounter < limit) {
8526
8666
  let c = peers.next().value;
@@ -8540,6 +8680,7 @@ class Manager {
8540
8680
  // } else {
8541
8681
  // // console.log(`pub >> [${tag}] sent: ${sentCounter} [no quota limit] total: ${remotes.size} subscribers. ` )
8542
8682
  // }
8683
+ if (this.telemetry) this.telemetry.deliveryAttempts += sentCounter;
8543
8684
  return ['ok', sentCounter]
8544
8685
  }
8545
8686
  }
@@ -8673,7 +8814,10 @@ class Manager {
8673
8814
 
8674
8815
  close() {
8675
8816
  this.metrics.close();
8676
- clearInterval(this.pingIntervalID);
8817
+ this.heartbeatStopped = true;
8818
+ clearTimeout(this.pingIntervalID);
8819
+ this.heartbeatPending.clear();
8820
+ for (const group of this.pingGroups) group.clear();
8677
8821
  if (this.monitIntervalID) {
8678
8822
  clearInterval(this.monitIntervalID);
8679
8823
  }
@@ -8701,11 +8845,25 @@ class Server extends require$$0$3 {
8701
8845
 
8702
8846
  constructor(options, authManager) {
8703
8847
  super();
8848
+ const security = { ...serverOption.security, ...options.security };
8849
+ for (const name of ['maxClockSkewMs', 'authChallengeMaxAgeMs', 'maxReplayEntries']) {
8850
+ if (!Number.isSafeInteger(security[name]) || security[name] <= 0) {
8851
+ throw new RangeError(`security.${name} must be a positive safe integer`);
8852
+ }
8853
+ }
8854
+ this.security = Object.freeze(security);
8704
8855
  this.serviceNames = new Set();
8705
8856
  this.wss = {};
8706
8857
  this.port = null;
8707
8858
  this.congPort = null;
8708
8859
 
8860
+ if (options.pingTimeoutGrace !== undefined) {
8861
+ if (!Number.isFinite(options.pingTimeoutGrace) || options.pingTimeoutGrace < 0) {
8862
+ throw new RangeError('pingTimeoutGrace must be a finite non-negative number');
8863
+ }
8864
+ serverOption.pingTimeoutGrace = options.pingTimeoutGrace;
8865
+ }
8866
+
8709
8867
  if (options.timeout) {
8710
8868
  let pingT = parseInt(options.timeout);
8711
8869
  if (pingT && pingT >= 1000) serverOption.timeout = pingT;
@@ -8839,44 +8997,36 @@ class Server extends require$$0$3 {
8839
8997
  throw new Error(`Service ${service} : no commands or !Array.`)
8840
8998
  }
8841
8999
 
8842
- // Service TYPE 1. single call() function.
8843
- if ( service_module.call && typeof service_module.call == 'function' ) {
8844
- this.on(service, (remote, req) => {
8845
- try {
8846
- if (!service_module.checkPermission(remote, req)) {
8847
- remote.response(req.mid, STATUS.ERROR, "NO_PERMISSION.");
8848
- return
8849
- }
8850
- if( service_module.commands.includes( req.topic )){
8851
- // console.log('server service_module req', req )
8852
- service_module.call(remote, req);
8853
- }else {
8854
- remote.response(req.mid, STATUS.ERROR, "UNKNOWN_COMMAND");
8855
- }
8856
- } catch (error) {
8857
- console.error(`Unhandled Service Error in service [${service}]:`, error);
8858
- remote.response(req.mid, STATUS.ERROR, "INTERNAL_SERVER_ERROR");
9000
+ const handleError = (remote, req, error) => {
9001
+ console.error(`Unhandled Service Error in service [${service}]:`, error);
9002
+ if (remote._closing) return;
9003
+ // A disconnected transport can also fail while reporting the service error.
9004
+ try {
9005
+ remote.response(req.mid, STATUS.ERROR, "INTERNAL_SERVER_ERROR");
9006
+ } catch (responseError) {
9007
+ console.error(`Service error response failed [${service}]:`, responseError);
9008
+ }
9009
+ };
9010
+ const useCall = typeof service_module.call === 'function';
9011
+ this.on(service, (remote, req) => {
9012
+ try {
9013
+ if (!service_module.checkPermission(remote, req)) {
9014
+ remote.response(req.mid, STATUS.ERROR, "NO_PERMISSION.");
9015
+ return;
8859
9016
  }
8860
- });
8861
- } else {
8862
- // Service TYPE 2. multiple functions.
8863
- this.on(service, (remote, req) => {
8864
- try {
8865
- if (!service_module.checkPermission(remote, req)) {
8866
- remote.response(req.mid, STATUS.ERROR, "NO_PERMISSION.");
8867
- return
8868
- }
8869
- if( service_module.commands.includes( req.topic )){
8870
- service_module[req.topic](remote, req);
8871
- }else {
8872
- remote.response(req.mid, STATUS.ERROR, "UNKNOWN_COMMAND");
8873
- }
8874
- } catch (error) {
8875
- console.error(`Unhandled Service Error in service [${service}]:`, error);
8876
- remote.response(req.mid, STATUS.ERROR, "INTERNAL_SERVER_ERROR");
9017
+ if (!service_module.commands.includes(req.topic)) {
9018
+ remote.response(req.mid, STATUS.ERROR, "UNKNOWN_COMMAND");
9019
+ return;
8877
9020
  }
8878
- });
8879
- }
9021
+ // Keep synchronous invocation and the service receiver; also observe async failures.
9022
+ const result = useCall
9023
+ ? service_module.call(remote, req)
9024
+ : service_module[req.topic](remote, req);
9025
+ Promise.resolve(result).catch(error => handleError(remote, req, error));
9026
+ } catch (error) {
9027
+ handleError(remote, req, error);
9028
+ }
9029
+ });
8880
9030
  this.serviceNames.add(service);
8881
9031
  // console.log(`[Service attached: ${service} ] accept commands: ${service_module.commands}`)
8882
9032
  return this
@@ -8962,6 +9112,12 @@ class BohoAuth {
8962
9112
 
8963
9113
  async verify_auth_req(auth_req, peer) {
8964
9114
  try {
9115
+ if (!peer.checkAuthChallenge()) return;
9116
+ if (!(auth_req instanceof Uint8Array) || auth_req.length !== it.MetaSize.AUTH_REQ ||
9117
+ auth_req[0] !== it.BohoMsg.AUTH_REQ) {
9118
+ peer.securityMismatch('INVALID_AUTH_PACKET');
9119
+ return;
9120
+ }
8965
9121
  //1. unpack
8966
9122
  let infoPack = $$1.unpack(auth_req, it.Meta.AUTH_REQ);
8967
9123
  if (!infoPack) {
@@ -8978,7 +9134,7 @@ class BohoAuth {
8978
9134
 
8979
9135
  //2. get key of id from DB
8980
9136
  let authInfo = await this.keyProvider.getAuth(id);
8981
- if (peer._closing || peer.state === STATE.CLOSED) return;
9137
+ if (!peer.checkAuthChallenge()) return;
8982
9138
  if (!authInfo) {
8983
9139
  this.send_auth_fail(peer, 'NO ID:' + id);
8984
9140
  return
@@ -9008,6 +9164,10 @@ class BohoAuth {
9008
9164
  return
9009
9165
  }
9010
9166
 
9167
+ // A valid proof consumes this challenge even if account policy rejects it.
9168
+ // Reauthentication requires a new connection, never a replay-state reset.
9169
+ peer._challengeUsed = true;
9170
+
9011
9171
  //4. get info
9012
9172
 
9013
9173
  //5. check duplicate login.