iosignal 9.19.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.19.0";
23
+ var version$1 = "9.21.0";
24
24
  var pkg = {
25
25
  version: version$1};
26
26
 
@@ -446,6 +446,10 @@ 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
449
453
  * @property {number} SERVER_HELLO_TIMEOUT
450
454
  * @property {number} PROMISE_TIMEOUT
451
455
  * @property {number} DID
@@ -456,6 +460,17 @@ const SIZE_LIMIT = {
456
460
  TAG_LEN2: 65535,
457
461
  CONNECTION_CHECKER_PERIOD: 3000,
458
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,
459
474
  // From starting a connection to the server's hello (SERVER_TIME_NONCE). A connection that hangs
460
475
  // longer is closed, so the client reconnects to its own URL (after a redirect: the original one).
461
476
  SERVER_HELLO_TIMEOUT: 15000,
@@ -776,6 +791,14 @@ function sendSubscription(io, tag) {
776
791
  ]));
777
792
  }
778
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
+
779
802
  function byteToUrl(buffer) {
780
803
  //ipv4(4bytes) , port(2bytes)
781
804
  if (buffer.byteLength != 6) return
@@ -853,6 +876,16 @@ class IOCore extends EventEmitter {
853
876
  * @type {number}
854
877
  */
855
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;
856
889
  /**
857
890
  * Period for connection checker.
858
891
  * @type {number}
@@ -968,6 +1001,7 @@ class IOCore extends EventEmitter {
968
1001
  close() {
969
1002
  // console.log('####### IOCOre.js close() called')
970
1003
  this.clearHelloTimer();
1004
+ this._pingSentAt = 0;
971
1005
  // If auto-reconnect is disabled, we must stop the keep-alive timer.
972
1006
  if (this.autoReconnect === false) {
973
1007
  clearInterval(this.connectionCheckerIntervalID);
@@ -975,6 +1009,7 @@ class IOCore extends EventEmitter {
975
1009
  }
976
1010
  if (this._closed) return;
977
1011
  this._closed = true;
1012
+ this.scheduleReconnect();
978
1013
 
979
1014
  // socket clean
980
1015
  if (this.socket) {
@@ -1048,12 +1083,37 @@ class IOCore extends EventEmitter {
1048
1083
  * is implemented keepConnection() in the child classes (IOWS, IOCongSocket, etc.).
1049
1084
  */
1050
1085
  keepAlive() {
1051
- this.keepConnection();
1052
- 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) {
1053
1099
  this.ping();
1054
1100
  }
1055
1101
  }
1056
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
+
1057
1117
  /**
1058
1118
  * Redirects the connection to a new URL.
1059
1119
  * @param {string} url2 - The new URL to redirect to.
@@ -1124,6 +1184,8 @@ class IOCore extends EventEmitter {
1124
1184
  */
1125
1185
  onOpen() {
1126
1186
  this._closed = false;
1187
+ this.lastRxTime = Date.now();
1188
+ this._pingSentAt = 0;
1127
1189
  if (this.url.includes("wss://")) {
1128
1190
  this.TLS = true;
1129
1191
  } else {
@@ -1150,6 +1212,8 @@ class IOCore extends EventEmitter {
1150
1212
  this.auth(id, key);
1151
1213
  this.useAuth = true;
1152
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
1153
1217
  this.send(auth_pack);
1154
1218
  this.stateChange('auth_req', 'auth_req');
1155
1219
  }
@@ -1163,17 +1227,21 @@ class IOCore extends EventEmitter {
1163
1227
  * @returns {this}
1164
1228
  */
1165
1229
  auth(id, key) {
1166
- if (!id && !key) {
1167
- 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
1168
1234
  }
1169
-
1170
- 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) {
1171
1241
  this.boho.set_id_key(id);
1172
- } else if (id && key) {
1242
+ } else {
1173
1243
  this.boho.set_id8(id);
1174
1244
  this.boho.set_key(key);
1175
- } else {
1176
- this.emit('error', new Error('auth failed. no id or key.'));
1177
1245
  }
1178
1246
  this.useAuth = true;
1179
1247
  return this
@@ -1184,6 +1252,8 @@ class IOCore extends EventEmitter {
1184
1252
  * @param {Buffer} buffer - The incoming data buffer.
1185
1253
  */
1186
1254
  onData(buffer) {
1255
+ this.lastRxTime = Date.now();
1256
+ this._pingSentAt = 0;
1187
1257
  let msgType = buffer[0];
1188
1258
  let decoded;
1189
1259
 
@@ -1192,6 +1262,9 @@ class IOCore extends EventEmitter {
1192
1262
  if (decoded) {
1193
1263
  msgType = decoded[0];
1194
1264
  buffer = decoded;
1265
+ } else {
1266
+ // Not from this session (or damaged): dropped, never passed on as a text message.
1267
+ return
1195
1268
  }
1196
1269
  } else if (msgType === it.BohoMsg.ENC_E2E) {
1197
1270
 
@@ -1265,6 +1338,7 @@ class IOCore extends EventEmitter {
1265
1338
  // State first (subscribe_channels needs READY), then the stored subscriptions, and only then
1266
1339
  // 'ready': a signal sent from a ready handler reaches the server after our own subscriptions.
1267
1340
  // stateChange() without a message emits 'change' only; false means a handler moved the state on.
1341
+ this._reconnectAttempts = 0;
1268
1342
  if (!this.stateChange('ready')) break;
1269
1343
  this.subscribe_channels();
1270
1344
  this._readyDispatch = true;
@@ -1324,7 +1398,7 @@ class IOCore extends EventEmitter {
1324
1398
  let str = decoder$4.decode(buffer.subarray(1));
1325
1399
  let ss = JSON.parse(str);
1326
1400
 
1327
- if (ss.event && ss.data) {
1401
+ if (typeof ss.event === 'string' && ss.event && ss.data && !INTERNAL_EVENTS.has(ss.event)) {
1328
1402
  this.serverSet = ss.data;
1329
1403
  this.emit(ss.event, ss.data);
1330
1404
  }
@@ -1337,8 +1411,8 @@ class IOCore extends EventEmitter {
1337
1411
  case IOMsg.SET:
1338
1412
  try {
1339
1413
  let setPack = $$1.unpack(buffer);
1340
- if (setPack) {
1341
- 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 ?? []));
1342
1416
  }
1343
1417
  } catch (error) {
1344
1418
  this.emit('error', new Error('SET parsing error'));
@@ -1366,7 +1440,8 @@ class IOCore extends EventEmitter {
1366
1440
  this.emit('@', tag, ...args);
1367
1441
  if (tag !== '@') this.emit(tag, tag, ...args);
1368
1442
  } else {
1369
- 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);
1370
1445
  this.emit('message', tag, ...args);
1371
1446
  }
1372
1447
  }
@@ -1433,6 +1508,8 @@ class IOCore extends EventEmitter {
1433
1508
  * Sends a PING message to the server.
1434
1509
  */
1435
1510
  ping() {
1511
+ // Any message from the server answers it (see keepAlive()).
1512
+ if (!this._pingSentAt && this.isLinkUp()) this._pingSentAt = Date.now();
1436
1513
  this.send(Buffer$1.from([IOMsg.PING]));
1437
1514
  }
1438
1515
 
@@ -7397,7 +7474,8 @@ const serverOption = {
7397
7474
  // A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
7398
7475
  // letting its send queue grow without limit.
7399
7476
  maxBufferedBytes: 64 * 1024 * 1024,
7400
- // 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.
7401
7479
  membersOnly: false,
7402
7480
  // Observability. logMessages: log each received message (type and tag, never the payload).
7403
7481
  // logStats: print a one-line summary every N ms (0 = off).
@@ -7409,7 +7487,11 @@ const serverOption = {
7409
7487
  security: {
7410
7488
  maxClockSkewMs: 60000,
7411
7489
  authChallengeMaxAgeMs: 60000,
7412
- 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
7413
7495
  },
7414
7496
  // Named quota profiles. A connection uses one: an anonymous connection the Server's
7415
7497
  // anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
@@ -7419,11 +7501,12 @@ const serverOption = {
7419
7501
  // fanout: most subscribers one channel publish is delivered to
7420
7502
  // msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
7421
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
7422
7505
  quotas: {
7423
- anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null },
7424
- basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20 },
7425
- pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200 },
7426
- 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 }
7427
7510
  },
7428
7511
  anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
7429
7512
 
@@ -7463,6 +7546,13 @@ const serverOption = {
7463
7546
 
7464
7547
  auth: {
7465
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,
7466
7556
  // Default for BohoAuth, when the same authenticated CID is already online:
7467
7557
  // 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
7468
7558
  // Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
@@ -7480,6 +7570,11 @@ const serverOption = {
7480
7570
 
7481
7571
  const decoder$3 = new TextDecoder();
7482
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
+
7483
7578
  $$1.NB;
7484
7579
  const MB = $$1.MB;
7485
7580
 
@@ -7518,6 +7613,7 @@ class RemoteCore {
7518
7613
  this.security = manager.server.security;
7519
7614
  this._challengeIssuedAt = null;
7520
7615
  this._challengeUsed = false;
7616
+ this.authFailures = 0; // failed logins on this connection (BohoAuth)
7521
7617
  this._replayBuckets = new Map();
7522
7618
  this._replayEntries = 0;
7523
7619
  this._replayExpiredBefore = 0;
@@ -7789,6 +7885,11 @@ class RemoteCore {
7789
7885
  }
7790
7886
 
7791
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
+ }
7792
7893
  if (logMessages) this.logMessage(msgType, message, encrypted);
7793
7894
 
7794
7895
  switch (msgType) {
@@ -7902,8 +8003,10 @@ class RemoteCore {
7902
8003
  tag = decoder$3.decode(tag);
7903
8004
  let tagList = tag.split(',');
7904
8005
  // console.log('>> SUBSCRIBE_REQ from:', this.cid, tagList)
7905
- this.manager.subscribe(tagList, this);
7906
- 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);
7907
8010
  } else {
7908
8011
  this.response(msgID, 255);
7909
8012
  }
@@ -7938,7 +8041,11 @@ class RemoteCore {
7938
8041
 
7939
8042
  // client's auth requst
7940
8043
  case it.BohoMsg.AUTH_REQ:
7941
- 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
+ }
7942
8049
  // A second request while verification is pending must not restart auth.
7943
8050
  if (this.state === STATE.AUTH_REQ) {
7944
8051
  this.securityMismatch('AUTH_IN_PROGRESS');
@@ -8150,6 +8257,15 @@ function getLocalAddress() {
8150
8257
  }
8151
8258
 
8152
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
+
8153
8269
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
8154
8270
 
8155
8271
  const decoder$2 = new TextDecoder();
@@ -9153,6 +9269,7 @@ class Manager {
9153
9269
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
9154
9270
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
9155
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
9156
9273
  policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
9157
9274
  hostInbound: 0, // client signals handed to a host (server.host)
9158
9275
  hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
@@ -9699,7 +9816,16 @@ class Manager {
9699
9816
  if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
9700
9817
  }
9701
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.
9702
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;
9703
9829
  chArr.forEach(tag => {
9704
9830
  if (tag.indexOf('#') === 0) {
9705
9831
  tag = remote.HOME_CHANNEL + tag;
@@ -9709,6 +9835,12 @@ class Manager {
9709
9835
  tag = this.CHANNEL_PREFIX + tag;
9710
9836
  }
9711
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
+
9712
9844
  // 1. set channel map
9713
9845
  if (this.channel_map.has(tag)) {
9714
9846
  this.channel_map.get(tag).add(remote);
@@ -9981,6 +10113,7 @@ class BohoAuth {
9981
10113
  if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
9982
10114
  this.onAuthEvent = options.onAuthEvent ?? null;
9983
10115
  this.resolveQuota = options.resolveQuota ?? defaultQuota;
10116
+ this.addressFailures = new Map(); // public address -> { count, since } of wrong logins
9984
10117
  this.authLogger;
9985
10118
  if (serverOption.fileLogger.auth.use) {
9986
10119
  this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
@@ -10021,9 +10154,46 @@ class BohoAuth {
10021
10154
  }
10022
10155
  }
10023
10156
 
10024
- 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) {
10025
10193
  if (peer._closing || peer.state === STATE.CLOSED) return;
10026
10194
  peer.boho.isAuthorized = false;
10195
+ if (countFailure) this.#countFailure(peer);
10196
+ const lastTry = countFailure && peer.authFailures >= serverOption.auth.maxFailuresPerConnection;
10027
10197
  if (this.authLogger) {
10028
10198
  let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
10029
10199
  this.authLogger.log(peerInfo);
@@ -10034,11 +10204,24 @@ class BohoAuth {
10034
10204
  setTimeout(e => {
10035
10205
  if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
10036
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();
10037
10209
  }
10038
10210
  }, serverOption.auth.failDelay);
10039
10211
  }
10040
10212
 
10041
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
+
10042
10225
  /**
10043
10226
  * Hook for a subclass: decide where a verified login belongs before it is accepted.
10044
10227
  * Called after the key and role checks, before quotas and the duplicate login check.
@@ -10087,11 +10270,23 @@ class BohoAuth {
10087
10270
  id = decoder.decode(infoPack.id8);
10088
10271
  }
10089
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
+
10090
10279
  //2. get key of id from DB
10091
- 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
+ }
10092
10287
  if (!peer.checkAuthChallenge()) return;
10093
10288
  if (!authInfo) {
10094
- this.send_auth_fail(peer, 'NO ID:' + id);
10289
+ this.send_auth_fail(peer, 'NO ID:' + id, true);
10095
10290
  return
10096
10291
  }
10097
10292
 
@@ -10116,7 +10311,7 @@ class BohoAuth {
10116
10311
  //3. check hmac
10117
10312
  let auth_res = peer.boho.verify_auth_req(infoPack);
10118
10313
  if (!auth_res) {
10119
- this.send_auth_fail(peer, 'hmac dismatched');
10314
+ this.send_auth_fail(peer, 'hmac dismatched', true);
10120
10315
  return
10121
10316
  }
10122
10317
 
@@ -10140,7 +10335,13 @@ class BohoAuth {
10140
10335
  peer.close();
10141
10336
  return
10142
10337
  }
10143
- const quotaName = await this.resolveQuota(authInfo, role);
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
+ }
10144
10345
  const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
10145
10346
  if (!quota) {
10146
10347
  this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
@@ -10195,9 +10396,19 @@ class BohoAuth {
10195
10396
  }
10196
10397
 
10197
10398
  //6. delete current (or anonymouse)cid if exist.
10198
- if (peer.cid) {
10199
- // console.log('if peer has cid', peer.cid)
10200
- 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);
10201
10412
  }
10202
10413
 
10203
10414
  //7. setting info.
@@ -11070,7 +11281,7 @@ function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
11070
11281
  }
11071
11282
  const positive = (name, value) => integer(name, value, 1);
11072
11283
  const nonNegative = (name, value) => integer(name, value, 0);
11073
- const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
11284
+ const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections', 'maxSubscriptions'];
11074
11285
 
11075
11286
  // This Server's quota profiles: the defaults with each given profile merged over its default
11076
11287
  // (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
@@ -11135,13 +11346,13 @@ class Server extends require$$0$3 {
11135
11346
  * loopback/private peer, true always, false never, or N trusted proxy hops.
11136
11347
  * options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
11137
11348
  * options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
11138
- * options.membersOnly: drop signals from connections that are not authenticated.
11349
+ * options.membersOnly: only authenticated connections may send signals or subscribe.
11139
11350
  * options.logMessages: log each received message after decryption: type and tag, never the payload.
11140
11351
  * options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
11141
- * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
11352
+ * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries, requireEncryption }.
11142
11353
  * options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
11143
11354
  * options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
11144
- * maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
11355
+ * maxConnections, maxSubscriptions } }, merged over serverOption.quotas; always enforced, null is unlimited.
11145
11356
  * Adjustable later on server.quotas. The client is told its maxMessageBytes.
11146
11357
  * options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
11147
11358
  * options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
@@ -11162,7 +11373,7 @@ class Server extends require$$0$3 {
11162
11373
  // never written, so servers in one process do not affect each other.
11163
11374
  checkRemoved(options);
11164
11375
  this.security = Object.freeze(group('security', options.security,
11165
- { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
11376
+ { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive, requireEncryption: boolean }));
11166
11377
  // retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
11167
11378
  this.retain = group('retain', options.retain, {
11168
11379
  enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
@@ -11480,7 +11691,6 @@ class FileKeyProvider {
11480
11691
  //loaded when server start.
11481
11692
  loadAuthInfoFile_JS(path) {
11482
11693
  import(path).then((file) => {
11483
- console.log(file.authInfo);
11484
11694
  file.authInfo.forEach(item => {
11485
11695
  this.addAuth(...item);
11486
11696
  });
@@ -11510,6 +11720,7 @@ class FileKeyProvider {
11510
11720
 
11511
11721
  // Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
11512
11722
  addAuth(id, keyStr, cid, role, quota) {
11723
+ checkLoginId(id);
11513
11724
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11514
11725
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11515
11726
  }
@@ -11529,14 +11740,12 @@ class RedisKeyProvider {
11529
11740
  }
11530
11741
 
11531
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.
11532
11745
  async getAuth(id) {
11533
- try {
11534
- let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11535
- if (result && result.key) return result
11536
- else return null;
11537
- } catch (error) {
11538
- console.log('getAuth', error);
11539
- }
11746
+ let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11747
+ if (result && result.key) return result
11748
+ else return null;
11540
11749
  }
11541
11750
 
11542
11751
  //sudoService call
@@ -11547,13 +11756,18 @@ class RedisKeyProvider {
11547
11756
 
11548
11757
  // Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
11549
11758
  // Falls back to KEYS for a client without scan, or a redis-service from before 2026-11-17 that refuses it
11550
- // (RemoteRedisClient answers a refused command with undefined).
11759
+ // (RemoteRedisClient throws on a refused command; an undefined reply is treated the same).
11551
11760
  async scanKeys(pattern) {
11552
11761
  if (typeof this.redis.scan === 'function') {
11553
11762
  const keys = new Set(); // SCAN may return a key more than once
11554
11763
  let cursor = '0';
11555
11764
  do {
11556
- const reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11765
+ let reply;
11766
+ try {
11767
+ reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11768
+ } catch {
11769
+ break
11770
+ }
11557
11771
  if (!reply || !Array.isArray(reply.keys)) break
11558
11772
  for (const key of reply.keys) keys.add(key);
11559
11773
  cursor = String(reply.cursor);
@@ -11566,6 +11780,7 @@ class RedisKeyProvider {
11566
11780
  // add device auth info
11567
11781
  // role and quota are optional (see StringKeyProvider); an omitted one is not stored.
11568
11782
  async addAuth(id, keyStr, cid = '', role, quota) {
11783
+ checkLoginId(id);
11569
11784
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11570
11785
  const fields = { 'key': Base64hashKey, 'cid': cid };
11571
11786
  if (role) fields.role = role;
@@ -11634,6 +11849,7 @@ class StringKeyProvider {
11634
11849
  }
11635
11850
 
11636
11851
  addAuth(id, keyStr, cid, role, quota) {
11852
+ checkLoginId(id);
11637
11853
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11638
11854
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11639
11855
  }
@@ -11827,4 +12043,4 @@ class RedisService {
11827
12043
 
11828
12044
  const version = pkg.version;
11829
12045
 
11830
- 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 };