iosignal 9.14.0 → 9.21.0

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.
@@ -20,7 +20,7 @@ import { readFileSync } from 'node:fs';
20
20
  import { totalmem } from 'node:os';
21
21
  import path from 'path';
22
22
 
23
- var version$1 = "9.14.0";
23
+ var version$1 = "9.21.0";
24
24
  var pkg = {
25
25
  version: version$1};
26
26
 
@@ -446,6 +446,11 @@ for (let c in ENC_MODE) { ENC_MODE[ENC_MODE[c]] = c; }
446
446
  * @property {number} TAG_LEN2
447
447
  * @property {number} CONNECTION_CHECKER_PERIOD
448
448
  * @property {number} CLIENT_PING_PERIOD
449
+ * @property {number} PONG_TIMEOUT
450
+ * @property {number} RECONNECT_JITTER
451
+ * @property {number} RECONNECT_BASE
452
+ * @property {number} RECONNECT_MAX
453
+ * @property {number} SERVER_HELLO_TIMEOUT
449
454
  * @property {number} PROMISE_TIMEOUT
450
455
  * @property {number} DID
451
456
  * @property {number} CID
@@ -455,6 +460,20 @@ const SIZE_LIMIT = {
455
460
  TAG_LEN2: 65535,
456
461
  CONNECTION_CHECKER_PERIOD: 3000,
457
462
  CLIENT_PING_PERIOD: 40000,
463
+ // After a client PING (sent when nothing was received for CLIENT_PING_PERIOD): with no message
464
+ // from the server in this time the connection is taken as dead and closed, so the client
465
+ // reconnects. A lost Wi-Fi or mobile link may leave a socket open for many minutes otherwise.
466
+ PONG_TIMEOUT: 15000,
467
+ // Reconnecting (autoReconnect): the first attempt after a connection closes waits a random time
468
+ // up to RECONNECT_JITTER, so the clients of a restarted server do not all return at once; each
469
+ // further attempt without reaching ready waits RECONNECT_BASE, doubled each time up to
470
+ // RECONNECT_MAX (each +-20%). Reaching ready starts over.
471
+ RECONNECT_JITTER: 1000,
472
+ RECONNECT_BASE: 3000,
473
+ RECONNECT_MAX: 30000,
474
+ // From starting a connection to the server's hello (SERVER_TIME_NONCE). A connection that hangs
475
+ // longer is closed, so the client reconnects to its own URL (after a redirect: the original one).
476
+ SERVER_HELLO_TIMEOUT: 15000,
458
477
  PROMISE_TIMEOUT: 5000,
459
478
  DID: 8,
460
479
  CID: 12
@@ -772,6 +791,14 @@ function sendSubscription(io, tag) {
772
791
  ]));
773
792
  }
774
793
 
794
+ // Names the client emits itself. A signal, SERVER_SIGNAL or SET with one of these as its tag is not
795
+ // emitted under that name, so nothing from the network can pose as a connection event (a signal
796
+ // on a channel called 'close' would otherwise run the client's own close handling).
797
+ const INTERNAL_EVENTS = new Set(['open', 'close', 'closed', 'socket_data', 'change', 'error', 'message',
798
+ 'connecting', 'closing', 'server_ready', 'auth_req', 'auth_res', 'auth_fail', 'auth_clear',
799
+ 'cid_req', 'cid_res', 'ready', 'stop', 'redirecting', 'pong', 'echo', 'iam_res', 'over_size',
800
+ 'text_message']);
801
+
775
802
  function byteToUrl(buffer) {
776
803
  //ipv4(4bytes) , port(2bytes)
777
804
  if (buffer.byteLength != 6) return
@@ -849,6 +876,16 @@ class IOCore extends EventEmitter {
849
876
  * @type {number}
850
877
  */
851
878
  this.lastTxRxTime = Date.now();
879
+ /**
880
+ * Last time anything was received from the server (see keepAlive()).
881
+ * @type {number}
882
+ */
883
+ this.lastRxTime = Date.now();
884
+ /** @private Time of a PING that has had no answer yet; 0 when none is pending. */
885
+ this._pingSentAt = 0;
886
+ /** @private Connections closed since the last ready, and the earliest time of the next automatic attempt. */
887
+ this._reconnectAttempts = 0;
888
+ this._nextConnectAt = 0;
852
889
  /**
853
890
  * Period for connection checker.
854
891
  * @type {number}
@@ -963,6 +1000,8 @@ class IOCore extends EventEmitter {
963
1000
  */
964
1001
  close() {
965
1002
  // console.log('####### IOCOre.js close() called')
1003
+ this.clearHelloTimer();
1004
+ this._pingSentAt = 0;
966
1005
  // If auto-reconnect is disabled, we must stop the keep-alive timer.
967
1006
  if (this.autoReconnect === false) {
968
1007
  clearInterval(this.connectionCheckerIntervalID);
@@ -970,6 +1009,7 @@ class IOCore extends EventEmitter {
970
1009
  }
971
1010
  if (this._closed) return;
972
1011
  this._closed = true;
1012
+ this.scheduleReconnect();
973
1013
 
974
1014
  // socket clean
975
1015
  if (this.socket) {
@@ -1043,12 +1083,37 @@ class IOCore extends EventEmitter {
1043
1083
  * is implemented keepConnection() in the child classes (IOWS, IOCongSocket, etc.).
1044
1084
  */
1045
1085
  keepAlive() {
1046
- this.keepConnection();
1047
- if( Date.now() - this.lastTxRxTime > SIZE_LIMIT.CLIENT_PING_PERIOD ){
1086
+ if (Date.now() >= this._nextConnectAt) this.keepConnection();
1087
+ if (!this.isLinkUp()) return;
1088
+ const now = Date.now();
1089
+ // A PING the server did not answer with anything: the connection is dead although the socket
1090
+ // still looks open (lost Wi-Fi, a sleeping phone, a NAT that dropped it). Close it; with
1091
+ // autoReconnect the next keepAlive() connects again.
1092
+ if (this._pingSentAt && now - this._pingSentAt > SIZE_LIMIT.PONG_TIMEOUT) {
1093
+ this.emit('error', new Error('no reply from the server in ' + SIZE_LIMIT.PONG_TIMEOUT / 1000 + ' s; reconnecting'));
1094
+ this.close();
1095
+ return;
1096
+ }
1097
+ // Sending does not show the server is there, so this follows what was received.
1098
+ if (!this._pingSentAt && now - this.lastRxTime > SIZE_LIMIT.CLIENT_PING_PERIOD) {
1048
1099
  this.ping();
1049
1100
  }
1050
1101
  }
1051
1102
 
1103
+ /** @private When keepAlive() may connect again after this close: see SIZE_LIMIT.RECONNECT_*. */
1104
+ scheduleReconnect() {
1105
+ const attempt = this._reconnectAttempts++;
1106
+ const delay = attempt === 0
1107
+ ? Math.random() * SIZE_LIMIT.RECONNECT_JITTER
1108
+ : Math.min(SIZE_LIMIT.RECONNECT_MAX, SIZE_LIMIT.RECONNECT_BASE * 2 ** (attempt - 1)) * (0.8 + Math.random() * 0.4);
1109
+ this._nextConnectAt = Date.now() + delay;
1110
+ }
1111
+
1112
+ /** @private True from the socket opening until it closes (any state a server message can arrive in). */
1113
+ isLinkUp() {
1114
+ return !!this.socket && !this._closed && (this.state === STATE.OPEN || this.state >= STATE.SERVER_READY);
1115
+ }
1116
+
1052
1117
  /**
1053
1118
  * Redirects the connection to a new URL.
1054
1119
  * @param {string} url2 - The new URL to redirect to.
@@ -1057,6 +1122,30 @@ class IOCore extends EventEmitter {
1057
1122
  this.stateChange('redirecting','redirecting');
1058
1123
  this.close();
1059
1124
  this.createConnection(url2);
1125
+ this.armHelloTimer();
1126
+ }
1127
+
1128
+ /**
1129
+ * Closes a connection that has not got the server's hello in SIZE_LIMIT.SERVER_HELLO_TIMEOUT
1130
+ * (a server that cannot be reached, or a connection that opens but never answers). With
1131
+ * autoReconnect the client then reconnects to this.url, so a failed redirect falls back to the
1132
+ * original server, as the Arduino library does.
1133
+ */
1134
+ armHelloTimer() {
1135
+ this.clearHelloTimer();
1136
+ if (this._closed || !this.socket) return;
1137
+ const socket = this.socket;
1138
+ this.helloTimerID = setTimeout(() => {
1139
+ this.helloTimerID = null;
1140
+ if (this.socket !== socket) return;
1141
+ this.emit('error', new Error('no reply from the server in ' + SIZE_LIMIT.SERVER_HELLO_TIMEOUT / 1000 + ' s'));
1142
+ this.close();
1143
+ }, SIZE_LIMIT.SERVER_HELLO_TIMEOUT);
1144
+ }
1145
+
1146
+ clearHelloTimer() {
1147
+ if (this.helloTimerID) clearTimeout(this.helloTimerID);
1148
+ this.helloTimerID = null;
1060
1149
  }
1061
1150
 
1062
1151
  /**
@@ -1082,6 +1171,7 @@ class IOCore extends EventEmitter {
1082
1171
  // The actual connection is created here.
1083
1172
  this.createConnection(this.url);
1084
1173
  if (this._closed) return; // A connecting listener may have stopped the client.
1174
+ this.armHelloTimer();
1085
1175
 
1086
1176
  // Ensure the keep-alive timer is running.
1087
1177
  if (!this.connectionCheckerIntervalID) {
@@ -1094,6 +1184,8 @@ class IOCore extends EventEmitter {
1094
1184
  */
1095
1185
  onOpen() {
1096
1186
  this._closed = false;
1187
+ this.lastRxTime = Date.now();
1188
+ this._pingSentAt = 0;
1097
1189
  if (this.url.includes("wss://")) {
1098
1190
  this.TLS = true;
1099
1191
  } else {
@@ -1120,6 +1212,8 @@ class IOCore extends EventEmitter {
1120
1212
  this.auth(id, key);
1121
1213
  this.useAuth = true;
1122
1214
  let auth_pack = this.boho.auth_req(this.serverTimeNonce );
1215
+ // false: no key was set (bad arguments), or the server has not said hello on this connection yet.
1216
+ if (!auth_pack) return this
1123
1217
  this.send(auth_pack);
1124
1218
  this.stateChange('auth_req', 'auth_req');
1125
1219
  }
@@ -1133,17 +1227,21 @@ class IOCore extends EventEmitter {
1133
1227
  * @returns {this}
1134
1228
  */
1135
1229
  auth(id, key) {
1136
- if (!id && !key) {
1137
- this.emit('error', new Error('auth failed. no id and key.'));
1230
+ if (key === null || key === '') key = undefined; // auth('id.key', '') from a form with one field
1231
+ if (typeof id !== 'string' || !id || (key === undefined ? !/^[^.]+\..+$/.test(id) : typeof key !== 'string')) {
1232
+ this.emit('error', new Error("auth failed. use auth('id', 'key') or auth('id.key')."));
1233
+ return this
1138
1234
  }
1139
-
1140
- if (!key && id.includes('.')) {
1235
+ // The ID travels as 8 bytes; a longer one is cut (as before), which the server may not know.
1236
+ const loginId = key === undefined ? id.slice(0, id.indexOf('.')) : id;
1237
+ if (encoder$2.encode(loginId).byteLength > SIZE_LIMIT.DID) {
1238
+ this.emit('error', new Error(`auth: login ID '${loginId}' is longer than ${SIZE_LIMIT.DID} bytes and is cut to them.`));
1239
+ }
1240
+ if (key === undefined) {
1141
1241
  this.boho.set_id_key(id);
1142
- } else if (id && key) {
1242
+ } else {
1143
1243
  this.boho.set_id8(id);
1144
1244
  this.boho.set_key(key);
1145
- } else {
1146
- this.emit('error', new Error('auth failed. no id or key.'));
1147
1245
  }
1148
1246
  this.useAuth = true;
1149
1247
  return this
@@ -1154,6 +1252,8 @@ class IOCore extends EventEmitter {
1154
1252
  * @param {Buffer} buffer - The incoming data buffer.
1155
1253
  */
1156
1254
  onData(buffer) {
1255
+ this.lastRxTime = Date.now();
1256
+ this._pingSentAt = 0;
1157
1257
  let msgType = buffer[0];
1158
1258
  let decoded;
1159
1259
 
@@ -1162,6 +1262,9 @@ class IOCore extends EventEmitter {
1162
1262
  if (decoded) {
1163
1263
  msgType = decoded[0];
1164
1264
  buffer = decoded;
1265
+ } else {
1266
+ // Not from this session (or damaged): dropped, never passed on as a text message.
1267
+ return
1165
1268
  }
1166
1269
  } else if (msgType === it.BohoMsg.ENC_E2E) {
1167
1270
 
@@ -1235,6 +1338,7 @@ class IOCore extends EventEmitter {
1235
1338
  // State first (subscribe_channels needs READY), then the stored subscriptions, and only then
1236
1339
  // 'ready': a signal sent from a ready handler reaches the server after our own subscriptions.
1237
1340
  // stateChange() without a message emits 'change' only; false means a handler moved the state on.
1341
+ this._reconnectAttempts = 0;
1238
1342
  if (!this.stateChange('ready')) break;
1239
1343
  this.subscribe_channels();
1240
1344
  this._readyDispatch = true;
@@ -1276,6 +1380,7 @@ class IOCore extends EventEmitter {
1276
1380
  break;
1277
1381
 
1278
1382
  case it.BohoMsg.SERVER_TIME_NONCE: // SERVER_READY
1383
+ this.clearHelloTimer();
1279
1384
  buffer.copy(this.serverTimeNonce);
1280
1385
  if (!this.stateChange('server_ready', 'server_ready')) break;
1281
1386
  if (this.useAuth) {
@@ -1293,7 +1398,7 @@ class IOCore extends EventEmitter {
1293
1398
  let str = decoder$4.decode(buffer.subarray(1));
1294
1399
  let ss = JSON.parse(str);
1295
1400
 
1296
- if (ss.event && ss.data) {
1401
+ if (typeof ss.event === 'string' && ss.event && ss.data && !INTERNAL_EVENTS.has(ss.event)) {
1297
1402
  this.serverSet = ss.data;
1298
1403
  this.emit(ss.event, ss.data);
1299
1404
  }
@@ -1306,8 +1411,8 @@ class IOCore extends EventEmitter {
1306
1411
  case IOMsg.SET:
1307
1412
  try {
1308
1413
  let setPack = $$1.unpack(buffer);
1309
- if (setPack) {
1310
- this.emit(setPack.topic, ...setPack.args);
1414
+ if (setPack && typeof setPack.topic === 'string' && !INTERNAL_EVENTS.has(setPack.topic)) {
1415
+ this.emit(setPack.topic, ...(setPack.args ?? []));
1311
1416
  }
1312
1417
  } catch (error) {
1313
1418
  this.emit('error', new Error('SET parsing error'));
@@ -1335,7 +1440,8 @@ class IOCore extends EventEmitter {
1335
1440
  this.emit('@', tag, ...args);
1336
1441
  if (tag !== '@') this.emit(tag, tag, ...args);
1337
1442
  } else {
1338
- this.emit(tag, tag, ...args);
1443
+ // A channel whose name is one of the client's own events reaches 'message' only.
1444
+ if (!INTERNAL_EVENTS.has(tag)) this.emit(tag, tag, ...args);
1339
1445
  this.emit('message', tag, ...args);
1340
1446
  }
1341
1447
  }
@@ -1402,6 +1508,8 @@ class IOCore extends EventEmitter {
1402
1508
  * Sends a PING message to the server.
1403
1509
  */
1404
1510
  ping() {
1511
+ // Any message from the server answers it (see keepAlive()).
1512
+ if (!this._pingSentAt && this.isLinkUp()) this._pingSentAt = Date.now();
1405
1513
  this.send(Buffer$1.from([IOMsg.PING]));
1406
1514
  }
1407
1515
 
@@ -2159,8 +2267,15 @@ class IOCongSocket extends IOCore {
2159
2267
 
2160
2268
  createConnection(url) {
2161
2269
  // TCP Socket
2162
- let urlObj = new URL(url);
2163
- if (urlObj.protocol != "cong:") {
2270
+ // 'host:port', 'ip:port' or 'cong://host:port'. 'ip:port' alone is not a URL (a scheme cannot
2271
+ // start with a digit), and 'host:port' parses with 'host:' as its scheme.
2272
+ let urlObj;
2273
+ try {
2274
+ urlObj = new URL(url);
2275
+ } catch {
2276
+ urlObj = null;
2277
+ }
2278
+ if (urlObj?.protocol != "cong:") {
2164
2279
  urlObj = new URL('cong://' + url);
2165
2280
  }
2166
2281
  // URL keeps the brackets of an IPv6 literal ('[::1]'); net expects the bare address.
@@ -7359,7 +7474,8 @@ const serverOption = {
7359
7474
  // A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
7360
7475
  // letting its send queue grow without limit.
7361
7476
  maxBufferedBytes: 64 * 1024 * 1024,
7362
- // Drop signals from connections that are not authenticated.
7477
+ // Only authenticated connections may send signals or subscribe; an anonymous one that tries
7478
+ // gets AUTH_CLEAR and is closed.
7363
7479
  membersOnly: false,
7364
7480
  // Observability. logMessages: log each received message (type and tag, never the payload).
7365
7481
  // logStats: print a one-line summary every N ms (0 = off).
@@ -7371,7 +7487,11 @@ const serverOption = {
7371
7487
  security: {
7372
7488
  maxClockSkewMs: 60000,
7373
7489
  authChallengeMaxAgeMs: 60000,
7374
- maxReplayEntries: 65536
7490
+ maxReplayEntries: 65536,
7491
+ // true: a logged-in connection without TLS must send its signals, subscriptions and calls
7492
+ // encrypted (as clients do in ENC_MODE.AUTO); a plain one closes it (PLAINTEXT_AFTER_LOGIN).
7493
+ // Off by default: a client with encMode NO would be closed.
7494
+ requireEncryption: false
7375
7495
  },
7376
7496
  // Named quota profiles. A connection uses one: an anonymous connection the Server's
7377
7497
  // anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
@@ -7381,11 +7501,12 @@ const serverOption = {
7381
7501
  // fanout: most subscribers one channel publish is delivered to
7382
7502
  // msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
7383
7503
  // maxConnections: connections of one account (uid) at a time; over: the login fails
7504
+ // maxSubscriptions: tags one connection may be subscribed to at a time; over: the tag is left out
7384
7505
  quotas: {
7385
- anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null },
7386
- basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20 },
7387
- pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200 },
7388
- unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null }
7506
+ anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null, maxSubscriptions: 1000 },
7507
+ basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20, maxSubscriptions: 2000 },
7508
+ pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200, maxSubscriptions: 10000 },
7509
+ unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null, maxSubscriptions: null }
7389
7510
  },
7390
7511
  anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
7391
7512
 
@@ -7425,6 +7546,13 @@ const serverOption = {
7425
7546
 
7426
7547
  auth: {
7427
7548
  failDelay: 600, // ms before AUTH_FAIL is sent
7549
+ // Wrong logins: a connection is closed after maxFailuresPerConnection; a public address with
7550
+ // maxFailuresPerAddress in failureWindowMs gets its next logins closed unchecked until the window
7551
+ // has passed (closed, not AUTH_FAIL, so a device with the right key there connects again).
7552
+ // Loopback and private addresses are not counted (a proxy, a LAN, tests).
7553
+ maxFailuresPerConnection: 5,
7554
+ maxFailuresPerAddress: 30,
7555
+ failureWindowMs: 60000,
7428
7556
  // Default for BohoAuth, when the same authenticated CID is already online:
7429
7557
  // 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
7430
7558
  // Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
@@ -7442,6 +7570,11 @@ const serverOption = {
7442
7570
 
7443
7571
  const decoder$3 = new TextDecoder();
7444
7572
 
7573
+ // With security.requireEncryption, what a logged-in connection without TLS may not send in plain.
7574
+ // PING, PONG, CID_REQ, ECHO and CLOSE carry nothing and stay plain, as clients send them.
7575
+ const PLAINTEXT_REFUSED = new Set([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.SUBSCRIBE_REQ,
7576
+ IOMsg.UNSUBSCRIBE, IOMsg.CALL, IOMsg.IAM]);
7577
+
7445
7578
  $$1.NB;
7446
7579
  const MB = $$1.MB;
7447
7580
 
@@ -7480,6 +7613,7 @@ class RemoteCore {
7480
7613
  this.security = manager.server.security;
7481
7614
  this._challengeIssuedAt = null;
7482
7615
  this._challengeUsed = false;
7616
+ this.authFailures = 0; // failed logins on this connection (BohoAuth)
7483
7617
  this._replayBuckets = new Map();
7484
7618
  this._replayEntries = 0;
7485
7619
  this._replayExpiredBefore = 0;
@@ -7751,6 +7885,11 @@ class RemoteCore {
7751
7885
  }
7752
7886
 
7753
7887
  } else ;
7888
+ if (!encrypted && this.security.requireEncryption && this.boho.isAuthorized && !this.TLS &&
7889
+ PLAINTEXT_REFUSED.has(msgType)) {
7890
+ this.securityMismatch('PLAINTEXT_AFTER_LOGIN');
7891
+ return;
7892
+ }
7754
7893
  if (logMessages) this.logMessage(msgType, message, encrypted);
7755
7894
 
7756
7895
  switch (msgType) {
@@ -7864,8 +8003,10 @@ class RemoteCore {
7864
8003
  tag = decoder$3.decode(tag);
7865
8004
  let tagList = tag.split(',');
7866
8005
  // console.log('>> SUBSCRIBE_REQ from:', this.cid, tagList)
7867
- this.manager.subscribe(tagList, this);
7868
- this.response(msgID, 0);
8006
+ const rejected = this.subscriptionsRejected ?? 0;
8007
+ if (this.manager.subscribe(tagList, this) === false) return
8008
+ // 255: some tags were over the quota's maxSubscriptions and were not subscribed.
8009
+ this.response(msgID, (this.subscriptionsRejected ?? 0) > rejected ? 255 : 0);
7869
8010
  } else {
7870
8011
  this.response(msgID, 255);
7871
8012
  }
@@ -7900,7 +8041,11 @@ class RemoteCore {
7900
8041
 
7901
8042
  // client's auth requst
7902
8043
  case it.BohoMsg.AUTH_REQ:
7903
- if (!this.manager.authManager) return
8044
+ // No login on this server: say so, or the client would wait in auth_req forever.
8045
+ if (!this.manager.authManager) {
8046
+ this.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
8047
+ return
8048
+ }
7904
8049
  // A second request while verification is pending must not restart auth.
7905
8050
  if (this.state === STATE.AUTH_REQ) {
7906
8051
  this.securityMismatch('AUTH_IN_PROGRESS');
@@ -8112,6 +8257,15 @@ function getLocalAddress() {
8112
8257
  }
8113
8258
 
8114
8259
 
8260
+ // A login ID travels as 8 bytes (Boho id8): a longer one would be cut and could never match, or
8261
+ // match another entry. Key providers refuse it when it is added.
8262
+ function checkLoginId(id) {
8263
+ if (typeof id !== 'string' || !id || new TextEncoder().encode(id).byteLength > 8) {
8264
+ throw new RangeError(`login ID must be 1-8 bytes: ${typeof id === 'string' ? id : typeof id}`)
8265
+ }
8266
+ return id
8267
+ }
8268
+
8115
8269
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
8116
8270
 
8117
8271
  const decoder$2 = new TextDecoder();
@@ -9115,6 +9269,7 @@ class Manager {
9115
9269
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
9116
9270
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
9117
9271
  peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
9272
+ subscriptionsRejected: 0, // subscriptions over a connection's quota maxSubscriptions, left out
9118
9273
  policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
9119
9274
  hostInbound: 0, // client signals handed to a host (server.host)
9120
9275
  hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
@@ -9661,7 +9816,16 @@ class Manager {
9661
9816
  if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
9662
9817
  }
9663
9818
 
9819
+ // Returns false when nothing was subscribed (membersOnly), else the connection's subscription count.
9820
+ // Tags over the quota's maxSubscriptions are left out and counted in subscriptionsRejected.
9664
9821
  subscribe(chArr, remote) {
9822
+ // Reading is closed to anonymous connections like sending (sender): same answer.
9823
+ if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
9824
+ remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
9825
+ remote.close();
9826
+ return false
9827
+ }
9828
+ const maxSubscriptions = remote.quota?.maxSubscriptions ?? null;
9665
9829
  chArr.forEach(tag => {
9666
9830
  if (tag.indexOf('#') === 0) {
9667
9831
  tag = remote.HOME_CHANNEL + tag;
@@ -9671,6 +9835,12 @@ class Manager {
9671
9835
  tag = this.CHANNEL_PREFIX + tag;
9672
9836
  }
9673
9837
 
9838
+ if (maxSubscriptions !== null && remote.channels.size >= maxSubscriptions && !remote.channels.has(tag)) {
9839
+ this.counters.subscriptionsRejected++;
9840
+ remote.subscriptionsRejected = (remote.subscriptionsRejected ?? 0) + 1;
9841
+ return
9842
+ }
9843
+
9674
9844
  // 1. set channel map
9675
9845
  if (this.channel_map.has(tag)) {
9676
9846
  this.channel_map.get(tag).add(remote);
@@ -9943,6 +10113,7 @@ class BohoAuth {
9943
10113
  if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
9944
10114
  this.onAuthEvent = options.onAuthEvent ?? null;
9945
10115
  this.resolveQuota = options.resolveQuota ?? defaultQuota;
10116
+ this.addressFailures = new Map(); // public address -> { count, since } of wrong logins
9946
10117
  this.authLogger;
9947
10118
  if (serverOption.fileLogger.auth.use) {
9948
10119
  this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
@@ -9983,9 +10154,46 @@ class BohoAuth {
9983
10154
  }
9984
10155
  }
9985
10156
 
9986
- send_auth_fail(peer, reason) {
10157
+ // Wrong logins of a public address in the current window (see serverOption.auth).
10158
+ #addressEntry(ip, now = Date.now()) {
10159
+ if (typeof ip !== 'string' || !ip || isPrivateIP(ip)) return null
10160
+ let entry = this.addressFailures.get(ip);
10161
+ if (entry && now - entry.since >= serverOption.auth.failureWindowMs) {
10162
+ this.addressFailures.delete(ip);
10163
+ entry = undefined;
10164
+ }
10165
+ return entry ?? { count: 0, since: now, fresh: true }
10166
+ }
10167
+
10168
+ /** True while this address has too many wrong logins: its logins are closed without a check. */
10169
+ addressBlocked(ip) {
10170
+ const entry = this.#addressEntry(ip);
10171
+ return !!entry && entry.count >= serverOption.auth.maxFailuresPerAddress
10172
+ }
10173
+
10174
+ #countFailure(peer) {
10175
+ peer.authFailures = (peer.authFailures ?? 0) + 1;
10176
+ const entry = this.#addressEntry(peer.ip);
10177
+ if (!entry) return
10178
+ if (entry.fresh) {
10179
+ delete entry.fresh;
10180
+ // Bounded: forget windows that have passed before adding another address.
10181
+ if (this.addressFailures.size >= 10000) {
10182
+ const now = Date.now();
10183
+ for (const [ip, e] of this.addressFailures) if (now - e.since >= serverOption.auth.failureWindowMs) this.addressFailures.delete(ip);
10184
+ if (this.addressFailures.size >= 10000) this.addressFailures.clear();
10185
+ }
10186
+ this.addressFailures.set(peer.ip, entry);
10187
+ }
10188
+ entry.count++;
10189
+ }
10190
+
10191
+ // countFailure: a wrong ID or key (not a refusal of a valid key, such as a duplicate login).
10192
+ send_auth_fail(peer, reason, countFailure = false) {
9987
10193
  if (peer._closing || peer.state === STATE.CLOSED) return;
9988
10194
  peer.boho.isAuthorized = false;
10195
+ if (countFailure) this.#countFailure(peer);
10196
+ const lastTry = countFailure && peer.authFailures >= serverOption.auth.maxFailuresPerConnection;
9989
10197
  if (this.authLogger) {
9990
10198
  let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
9991
10199
  this.authLogger.log(peerInfo);
@@ -9996,11 +10204,50 @@ class BohoAuth {
9996
10204
  setTimeout(e => {
9997
10205
  if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
9998
10206
  peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
10207
+ // Too many wrong logins on this connection: it has to connect again to go on.
10208
+ if (lastTry) peer.close();
9999
10209
  }
10000
10210
  }, serverOption.auth.failDelay);
10001
10211
  }
10002
10212
 
10003
10213
 
10214
+ // The login could not be checked (key store unreachable): not an answer about the key. The
10215
+ // connection is closed, so the client connects and logs in again, instead of AUTH_FAIL, which
10216
+ // clients take as "wrong key" and do not retry.
10217
+ close_unavailable(peer, reason) {
10218
+ if (peer._closing || peer.state === STATE.CLOSED) return;
10219
+ console.error('BohoAuth: login not checked, closing the connection:', reason);
10220
+ if (this.authLogger) this.authLogger.log(`UNAVAILABLE #${peer.ssid} reason:${reason} `);
10221
+ peer.boho.isAuthorized = false;
10222
+ peer.close();
10223
+ }
10224
+
10225
+ /**
10226
+ * Hook for a subclass: decide where a verified login belongs before it is accepted.
10227
+ * Called after the key and role checks, before quotas and the duplicate login check.
10228
+ * Return null to accept the login here, or a message (e.g. SERVER_REDIRECT) that is sent to the
10229
+ * client instead of AUTH_RES before the connection is closed. The default accepts every login.
10230
+ * @param {object} peer the connection
10231
+ * @param {object} authInfo the key provider's entry for the login ID (cid, uid, role, quota, ...)
10232
+ * @param {string} role resolved role
10233
+ * @param {string} id login ID
10234
+ * @returns {Promise<Uint8Array | null> | Uint8Array | null}
10235
+ */
10236
+ beforeAccept(peer, authInfo, role, id) {
10237
+ return null
10238
+ }
10239
+
10240
+ // An error in the hook accepts the login: placement must never lock clients out.
10241
+ async #beforeAcceptSafe(peer, authInfo, role, id) {
10242
+ try {
10243
+ const result = await this.beforeAccept(peer, authInfo, role, id);
10244
+ return result instanceof Uint8Array && result.byteLength > 0 ? result : null
10245
+ } catch (error) {
10246
+ console.error('BohoAuth.beforeAccept error:', error);
10247
+ return null
10248
+ }
10249
+ }
10250
+
10004
10251
  async verify_auth_req(auth_req, peer) {
10005
10252
  try {
10006
10253
  if (!peer.checkAuthChallenge()) return;
@@ -10023,11 +10270,23 @@ class BohoAuth {
10023
10270
  id = decoder.decode(infoPack.id8);
10024
10271
  }
10025
10272
 
10273
+ // Too many wrong logins from this address: not checked until its window has passed.
10274
+ if (this.addressBlocked(peer.ip)) {
10275
+ this.close_unavailable(peer, 'too many wrong logins from ' + peer.ip);
10276
+ return
10277
+ }
10278
+
10026
10279
  //2. get key of id from DB
10027
- let authInfo = await this.keyProvider.getAuth(id);
10280
+ let authInfo;
10281
+ try {
10282
+ authInfo = await this.keyProvider.getAuth(id);
10283
+ } catch (error) {
10284
+ this.close_unavailable(peer, 'key provider: ' + (error?.message ?? error));
10285
+ return
10286
+ }
10028
10287
  if (!peer.checkAuthChallenge()) return;
10029
10288
  if (!authInfo) {
10030
- this.send_auth_fail(peer, 'NO ID:' + id);
10289
+ this.send_auth_fail(peer, 'NO ID:' + id, true);
10031
10290
  return
10032
10291
  }
10033
10292
 
@@ -10052,7 +10311,7 @@ class BohoAuth {
10052
10311
  //3. check hmac
10053
10312
  let auth_res = peer.boho.verify_auth_req(infoPack);
10054
10313
  if (!auth_res) {
10055
- this.send_auth_fail(peer, 'hmac dismatched');
10314
+ this.send_auth_fail(peer, 'hmac dismatched', true);
10056
10315
  return
10057
10316
  }
10058
10317
 
@@ -10066,7 +10325,23 @@ class BohoAuth {
10066
10325
  this.send_auth_fail(peer, 'unknown auth.role: ' + authInfo.role);
10067
10326
  return
10068
10327
  }
10069
- const quotaName = await this.resolveQuota(authInfo, role);
10328
+ // A login another server should take (beforeAccept) goes there before it is counted here or
10329
+ // replaces a connection here.
10330
+ const redirect = await this.#beforeAcceptSafe(peer, authInfo, role, id);
10331
+ if (peer._closing) return; // closed while deciding
10332
+ if (redirect) {
10333
+ peer.boho.isAuthorized = false;
10334
+ peer.send(redirect);
10335
+ peer.close();
10336
+ return
10337
+ }
10338
+ let quotaName;
10339
+ try {
10340
+ quotaName = await this.resolveQuota(authInfo, role);
10341
+ } catch (error) {
10342
+ this.close_unavailable(peer, 'quota: ' + (error?.message ?? error));
10343
+ return
10344
+ }
10070
10345
  const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
10071
10346
  if (!quota) {
10072
10347
  this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
@@ -10121,9 +10396,19 @@ class BohoAuth {
10121
10396
  }
10122
10397
 
10123
10398
  //6. delete current (or anonymouse)cid if exist.
10124
- if (peer.cid) {
10125
- // console.log('if peer has cid', peer.cid)
10126
- peer.manager.cid2remote.delete(peer.cid);
10399
+ if (peer.cid && peer.cid !== authInfo.cid) {
10400
+ // Subscribers of the CID it had (an anonymous one, before login()) are told it is gone, as when
10401
+ // a connection closes. Sent to them only: nothing is retained under the new CID.
10402
+ const manager = peer.manager;
10403
+ for (const topic of ['@state', '@$state']) {
10404
+ const tag = peer.cid + topic;
10405
+ manager.deliver(manager.CID_PREFIX + tag, getSignalPack(tag, 'close'), null);
10406
+ }
10407
+ // What it retained carries the old CID in its tag: dropped, the device publishes again when ready.
10408
+ for (const message of peer.retain_signal.values()) manager.retainBytes -= message.byteLength;
10409
+ peer.retain_signal.clear();
10410
+ peer.retainBytes = 0;
10411
+ manager.cid2remote.delete(peer.cid);
10127
10412
  }
10128
10413
 
10129
10414
  //7. setting info.
@@ -10996,7 +11281,7 @@ function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
10996
11281
  }
10997
11282
  const positive = (name, value) => integer(name, value, 1);
10998
11283
  const nonNegative = (name, value) => integer(name, value, 0);
10999
- const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
11284
+ const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections', 'maxSubscriptions'];
11000
11285
 
11001
11286
  // This Server's quota profiles: the defaults with each given profile merged over its default
11002
11287
  // (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
@@ -11061,13 +11346,13 @@ class Server extends require$$0$3 {
11061
11346
  * loopback/private peer, true always, false never, or N trusted proxy hops.
11062
11347
  * options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
11063
11348
  * options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
11064
- * options.membersOnly: drop signals from connections that are not authenticated.
11349
+ * options.membersOnly: only authenticated connections may send signals or subscribe.
11065
11350
  * options.logMessages: log each received message after decryption: type and tag, never the payload.
11066
11351
  * options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
11067
- * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
11352
+ * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries, requireEncryption }.
11068
11353
  * options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
11069
11354
  * options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
11070
- * maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
11355
+ * maxConnections, maxSubscriptions } }, merged over serverOption.quotas; always enforced, null is unlimited.
11071
11356
  * Adjustable later on server.quotas. The client is told its maxMessageBytes.
11072
11357
  * options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
11073
11358
  * options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
@@ -11088,7 +11373,7 @@ class Server extends require$$0$3 {
11088
11373
  // never written, so servers in one process do not affect each other.
11089
11374
  checkRemoved(options);
11090
11375
  this.security = Object.freeze(group('security', options.security,
11091
- { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
11376
+ { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive, requireEncryption: boolean }));
11092
11377
  // retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
11093
11378
  this.retain = group('retain', options.retain, {
11094
11379
  enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
@@ -11406,7 +11691,6 @@ class FileKeyProvider {
11406
11691
  //loaded when server start.
11407
11692
  loadAuthInfoFile_JS(path) {
11408
11693
  import(path).then((file) => {
11409
- console.log(file.authInfo);
11410
11694
  file.authInfo.forEach(item => {
11411
11695
  this.addAuth(...item);
11412
11696
  });
@@ -11436,6 +11720,7 @@ class FileKeyProvider {
11436
11720
 
11437
11721
  // Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
11438
11722
  addAuth(id, keyStr, cid, role, quota) {
11723
+ checkLoginId(id);
11439
11724
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11440
11725
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11441
11726
  }
@@ -11455,28 +11740,47 @@ class RedisKeyProvider {
11455
11740
  }
11456
11741
 
11457
11742
  // get device key from DB. (for Boho auth.)
11743
+ // null: no such device. A Redis failure throws, so BohoAuth closes the connection (the client
11744
+ // connects again) instead of answering AUTH_FAIL as if the ID were unknown.
11458
11745
  async getAuth(id) {
11459
- try {
11460
- let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11461
- if (result && result.key) return result
11462
- else return null;
11463
- } catch (error) {
11464
- console.log('getAuth', error);
11465
- }
11746
+ let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11747
+ if (result && result.key) return result
11748
+ else return null;
11466
11749
  }
11467
11750
 
11468
11751
  //sudoService call
11469
11752
  async getAuthIdList() {
11470
- let result = await this.redis.keys(DEVICE_PREFIX + '*');
11471
- result = result.map(v => {
11472
- return v.split(':')[1]
11473
- });
11474
- if (result) return result
11753
+ const keys = await this.scanKeys(DEVICE_PREFIX + '*');
11754
+ return keys.map(key => key.slice(DEVICE_PREFIX.length))
11755
+ }
11756
+
11757
+ // Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
11758
+ // Falls back to KEYS for a client without scan, or a redis-service from before 2026-11-17 that refuses it
11759
+ // (RemoteRedisClient throws on a refused command; an undefined reply is treated the same).
11760
+ async scanKeys(pattern) {
11761
+ if (typeof this.redis.scan === 'function') {
11762
+ const keys = new Set(); // SCAN may return a key more than once
11763
+ let cursor = '0';
11764
+ do {
11765
+ let reply;
11766
+ try {
11767
+ reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11768
+ } catch {
11769
+ break
11770
+ }
11771
+ if (!reply || !Array.isArray(reply.keys)) break
11772
+ for (const key of reply.keys) keys.add(key);
11773
+ cursor = String(reply.cursor);
11774
+ if (cursor === '0') return [...keys]
11775
+ } while (true)
11776
+ }
11777
+ return (await this.redis.keys(pattern)) ?? []
11475
11778
  }
11476
11779
 
11477
11780
  // add device auth info
11478
11781
  // role and quota are optional (see StringKeyProvider); an omitted one is not stored.
11479
11782
  async addAuth(id, keyStr, cid = '', role, quota) {
11783
+ checkLoginId(id);
11480
11784
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11481
11785
  const fields = { 'key': Base64hashKey, 'cid': cid };
11482
11786
  if (role) fields.role = role;
@@ -11545,6 +11849,7 @@ class StringKeyProvider {
11545
11849
  }
11546
11850
 
11547
11851
  addAuth(id, keyStr, cid, role, quota) {
11852
+ checkLoginId(id);
11548
11853
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11549
11854
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11550
11855
  }
@@ -11689,12 +11994,13 @@ var sudoService = /*#__PURE__*/Object.freeze({
11689
11994
  *
11690
11995
  */
11691
11996
 
11997
+ // KEYS stays for older clients; new ones list keys with SCAN (RedisKeyProvider.scanKeys).
11692
11998
  const COMMANDS = [
11693
11999
  'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
11694
- 'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
12000
+ 'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SCAN', 'SAVE',
11695
12001
  'LPUSH', 'LTRIM', 'LRANGE', 'LINDEX', 'LSET', 'EXPIRE',
11696
12002
  'get', 'set', 'hGetAll', 'hGet', 'hSet', 'sAdd', 'sIsMember',
11697
- 'sMembers', 'exists', 'sRem', 'del', 'keys', 'save',
12003
+ 'sMembers', 'exists', 'sRem', 'del', 'keys', 'scan', 'save',
11698
12004
  'lPush', 'lTrim', 'lRange', 'lIndex', 'lSet', 'expire'
11699
12005
  ];
11700
12006
 
@@ -11737,4 +12043,4 @@ class RedisService {
11737
12043
 
11738
12044
  const version = pkg.version;
11739
12045
 
11740
- export { it as Boho, BohoAuth, CongRx, ENC_MODE, FileKeyProvider, FileLogger, IOWS as IO, IOCongSocket, IOMsg, LocalKeyProvider, $$1 as MBP, PAYLOAD_TYPE, ROLES, RedisKeyProvider, RedisService, SIZE_LIMIT, STATE, STATUS$1 as STATUS, Server, StringKeyProvider, defaultQuota, delay, getIPv4HexString, getIPv6PrefixHexString, getLocalAddress, getPayloadFromSignalPack, getSignalPack, hasRole, isPrivateIP, numberWithCommas, pack, parsePayload, replyService, serverOption, sudoService, version };
12046
+ export { it as Boho, BohoAuth, CongRx, ENC_MODE, FileKeyProvider, FileLogger, IOWS as IO, IOCongSocket, IOMsg, LocalKeyProvider, $$1 as MBP, PAYLOAD_TYPE, ROLES, RedisKeyProvider, RedisService, SIZE_LIMIT, STATE, STATUS$1 as STATUS, Server, StringKeyProvider, checkLoginId, defaultQuota, delay, getIPv4HexString, getIPv6PrefixHexString, getLocalAddress, getPayloadFromSignalPack, getSignalPack, hasRole, isPrivateIP, numberWithCommas, pack, parsePayload, replyService, serverOption, sudoService, version };