iosignal 9.19.0 → 9.22.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.22.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
 
@@ -1991,6 +2068,9 @@ class IOCore extends EventEmitter {
1991
2068
 
1992
2069
  }
1993
2070
 
2071
+ // CongSocket framing without Node.js streams: pack() and the frame parser. The server's Remote
2072
+ // uses CongParser directly; CongRx (CongPacket.js) wraps the same parser in a stream Transform.
2073
+
1994
2074
  const CongType = {
1995
2075
  TYPE_LEN1: 1,
1996
2076
  TYPE_LEN2: 2,
@@ -2002,7 +2082,7 @@ const CongType = {
2002
2082
  function pack(payload) {
2003
2083
 
2004
2084
  if( payload.byteLength == undefined ) payload = Buffer.from(payload);
2005
-
2085
+
2006
2086
  if (payload.byteLength < 256) { //one byte len
2007
2087
  return $$1.pack(
2008
2088
  $$1.MB('#type', '8', CongType.TYPE_LEN1),
@@ -2037,6 +2117,130 @@ function pack(payload) {
2037
2117
 
2038
2118
  }
2039
2119
 
2120
+ /**
2121
+ * Adds a received chunk to a parser state and parses the complete frames into state.frames.
2122
+ * state: { buffer, frames, rxi, rxi_zero, maxFrameSize, skipBytes } (a CongParser or CongRx).
2123
+ * emit(event, value): 'wrong' (the unparsable buffer) or 'oversize' (payload size; the frame is
2124
+ * skipped without buffering). Shared by CongParser and CongRx so both parse alike.
2125
+ */
2126
+ function addCongData(state, chunk, emit) {
2127
+ let c = chunk.byteLength;
2128
+ let i = 0;
2129
+ while (c--) {
2130
+ state.rxi++;
2131
+ if (chunk[i++] == 0) {
2132
+ state.rxi_zero++;
2133
+ }
2134
+ }
2135
+
2136
+ if (state.skipBytes > 0) {
2137
+ if (chunk.byteLength <= state.skipBytes) {
2138
+ state.skipBytes -= chunk.byteLength;
2139
+ return;
2140
+ }
2141
+ chunk = chunk.subarray(state.skipBytes);
2142
+ state.skipBytes = 0;
2143
+ }
2144
+
2145
+ if (state.buffer.byteLength > 0) {
2146
+ state.buffer = Buffer.concat([state.buffer, chunk]);
2147
+ } else {
2148
+ state.buffer = chunk;
2149
+ }
2150
+ parseCongFrames(state, emit);
2151
+ }
2152
+
2153
+ function parseCongFrames(state, emit) {
2154
+ while (state.buffer.byteLength > 0) {
2155
+ const head = state.buffer[0];
2156
+ let headerLen;
2157
+ let payloadSize;
2158
+
2159
+ if (head === CongType.TYPE_LEN1) {
2160
+ headerLen = 2;
2161
+ if (state.buffer.byteLength < headerLen) return;
2162
+ payloadSize = state.buffer.readUint8(1);
2163
+ } else if (head === CongType.TYPE_LEN2) {
2164
+ headerLen = 3;
2165
+ if (state.buffer.byteLength < headerLen) return;
2166
+ payloadSize = state.buffer.readUint16LE(1);
2167
+ } else if (head === CongType.TYPE_LEN3) {
2168
+ headerLen = 4;
2169
+ if (state.buffer.byteLength < headerLen) return;
2170
+ payloadSize = state.buffer.readUint16LE(1) + state.buffer.readUint8(3) * 65536;
2171
+ } else if (head === CongType.TYPE_LEN4) {
2172
+ headerLen = 5;
2173
+ if (state.buffer.byteLength < headerLen) return;
2174
+ payloadSize = state.buffer.readUint32LE(1);
2175
+ } else {
2176
+ emit('wrong', state.buffer);
2177
+ state.buffer = Buffer.alloc(0);
2178
+ return;
2179
+ }
2180
+
2181
+ // Decide as soon as the length is known: the header can advertise up to 4 GiB.
2182
+ // Skipping keeps frame boundaries, so later frames still parse.
2183
+ if (payloadSize > state.maxFrameSize) {
2184
+ emit('oversize', payloadSize);
2185
+ const available = state.buffer.byteLength - headerLen;
2186
+ if (available < payloadSize) {
2187
+ state.skipBytes = payloadSize - available;
2188
+ state.buffer = Buffer.alloc(0);
2189
+ return;
2190
+ }
2191
+ state.buffer = state.buffer.subarray(headerLen + payloadSize);
2192
+ continue;
2193
+ }
2194
+
2195
+ const frameSize = headerLen + payloadSize;
2196
+ if (state.buffer.byteLength < frameSize) return;
2197
+
2198
+ state.frames.push(state.buffer.subarray(headerLen, frameSize));
2199
+ if (state.buffer.byteLength === frameSize) {
2200
+ state.buffer = Buffer.alloc(0);
2201
+ return;
2202
+ }
2203
+ // Consume each complete frame without growing the call stack.
2204
+ state.buffer = state.buffer.subarray(frameSize);
2205
+ }
2206
+ }
2207
+
2208
+ /**
2209
+ * CongSocket frame parser without streams: write(chunk) calls onFrame(payload) for each complete
2210
+ * frame, onWrong(buffer) for an unparsable stream and onOversize(payloadSize) for a frame larger
2211
+ * than maxFrameSize (skipped without buffering).
2212
+ */
2213
+ class CongParser {
2214
+ constructor({ maxFrameSize = Infinity, onFrame = null, onWrong = null, onOversize = null } = {}) {
2215
+ this.buffer = Buffer.alloc(0);
2216
+ this.frames = [];
2217
+ this.rxi = 0;
2218
+ this.rxi_zero = 0;
2219
+ this.maxFrameSize = maxFrameSize;
2220
+ this.skipBytes = 0; // remaining payload bytes of an oversized frame to discard
2221
+ this.onFrame = onFrame;
2222
+ this.onWrong = onWrong;
2223
+ this.onOversize = onOversize;
2224
+ }
2225
+
2226
+ write(chunk) {
2227
+ addCongData(this, chunk, (event, value) => {
2228
+ if (event === 'wrong') this.onWrong?.(value);
2229
+ else this.onOversize?.(value);
2230
+ });
2231
+ const frames = this.frames;
2232
+ this.frames = [];
2233
+ for (const frame of frames) this.onFrame?.(frame);
2234
+ }
2235
+
2236
+ /** Stops calling the handlers (the connection closed). */
2237
+ clear() {
2238
+ this.onFrame = this.onWrong = this.onOversize = null;
2239
+ this.buffer = Buffer.alloc(0);
2240
+ this.frames = [];
2241
+ }
2242
+ }
2243
+
2040
2244
  class CongRx extends Transform {
2041
2245
  /**
2042
2246
  * @param {import('stream').TransformOptions & { maxFrameSize?: number }} [options] Stream options.
@@ -2069,86 +2273,7 @@ class CongRx extends Transform {
2069
2273
 
2070
2274
 
2071
2275
  addData(chunk) {
2072
- let c = chunk.byteLength;
2073
- let i = 0;
2074
- while (c--) {
2075
- this.rxi++;
2076
- if (chunk[i++] == 0) {
2077
- this.rxi_zero++;
2078
- }
2079
- }
2080
-
2081
- if (this.skipBytes > 0) {
2082
- if (chunk.byteLength <= this.skipBytes) {
2083
- this.skipBytes -= chunk.byteLength;
2084
- return;
2085
- }
2086
- chunk = chunk.subarray(this.skipBytes);
2087
- this.skipBytes = 0;
2088
- }
2089
-
2090
- if (this.buffer.byteLength > 0) {
2091
- this.buffer = Buffer.concat([this.buffer, chunk]);
2092
- } else {
2093
- this.buffer = chunk;
2094
- }
2095
- this.parse();
2096
- }
2097
-
2098
-
2099
- parse() {
2100
- while (this.buffer.byteLength > 0) {
2101
- const head = this.buffer[0];
2102
- let headerLen;
2103
- let payloadSize;
2104
-
2105
- if (head === CongType.TYPE_LEN1) {
2106
- headerLen = 2;
2107
- if (this.buffer.byteLength < headerLen) return;
2108
- payloadSize = this.buffer.readUint8(1);
2109
- } else if (head === CongType.TYPE_LEN2) {
2110
- headerLen = 3;
2111
- if (this.buffer.byteLength < headerLen) return;
2112
- payloadSize = this.buffer.readUint16LE(1);
2113
- } else if (head === CongType.TYPE_LEN3) {
2114
- headerLen = 4;
2115
- if (this.buffer.byteLength < headerLen) return;
2116
- payloadSize = this.buffer.readUint16LE(1) + this.buffer.readUint8(3) * 65536;
2117
- } else if (head === CongType.TYPE_LEN4) {
2118
- headerLen = 5;
2119
- if (this.buffer.byteLength < headerLen) return;
2120
- payloadSize = this.buffer.readUint32LE(1);
2121
- } else {
2122
- this.emit('wrong', this.buffer);
2123
- this.buffer = Buffer.alloc(0);
2124
- return;
2125
- }
2126
-
2127
- // Decide as soon as the length is known: the header can advertise up to 4 GiB.
2128
- // Skipping keeps frame boundaries, so later frames still parse.
2129
- if (payloadSize > this.maxFrameSize) {
2130
- this.emit('oversize', payloadSize);
2131
- const available = this.buffer.byteLength - headerLen;
2132
- if (available < payloadSize) {
2133
- this.skipBytes = payloadSize - available;
2134
- this.buffer = Buffer.alloc(0);
2135
- return;
2136
- }
2137
- this.buffer = this.buffer.subarray(headerLen + payloadSize);
2138
- continue;
2139
- }
2140
-
2141
- const frameSize = headerLen + payloadSize;
2142
- if (this.buffer.byteLength < frameSize) return;
2143
-
2144
- this.frames.push(this.buffer.subarray(headerLen, frameSize));
2145
- if (this.buffer.byteLength === frameSize) {
2146
- this.buffer = Buffer.alloc(0);
2147
- return;
2148
- }
2149
- // Consume each complete frame without growing the call stack.
2150
- this.buffer = this.buffer.subarray(frameSize);
2151
- }
2276
+ addCongData(this, chunk, (event, value) => this.emit(event, value));
2152
2277
  }
2153
2278
  }
2154
2279
 
@@ -7397,7 +7522,8 @@ const serverOption = {
7397
7522
  // A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
7398
7523
  // letting its send queue grow without limit.
7399
7524
  maxBufferedBytes: 64 * 1024 * 1024,
7400
- // Drop signals from connections that are not authenticated.
7525
+ // Only authenticated connections may send signals or subscribe; an anonymous one that tries
7526
+ // gets AUTH_CLEAR and is closed.
7401
7527
  membersOnly: false,
7402
7528
  // Observability. logMessages: log each received message (type and tag, never the payload).
7403
7529
  // logStats: print a one-line summary every N ms (0 = off).
@@ -7409,7 +7535,11 @@ const serverOption = {
7409
7535
  security: {
7410
7536
  maxClockSkewMs: 60000,
7411
7537
  authChallengeMaxAgeMs: 60000,
7412
- maxReplayEntries: 65536
7538
+ maxReplayEntries: 65536,
7539
+ // true: a logged-in connection without TLS must send its signals, subscriptions and calls
7540
+ // encrypted (as clients do in ENC_MODE.AUTO); a plain one closes it (PLAINTEXT_AFTER_LOGIN).
7541
+ // Off by default: a client with encMode NO would be closed.
7542
+ requireEncryption: false
7413
7543
  },
7414
7544
  // Named quota profiles. A connection uses one: an anonymous connection the Server's
7415
7545
  // anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
@@ -7419,11 +7549,12 @@ const serverOption = {
7419
7549
  // fanout: most subscribers one channel publish is delivered to
7420
7550
  // msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
7421
7551
  // maxConnections: connections of one account (uid) at a time; over: the login fails
7552
+ // maxSubscriptions: tags one connection may be subscribed to at a time; over: the tag is left out
7422
7553
  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 }
7554
+ anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null, maxSubscriptions: 1000 },
7555
+ basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20, maxSubscriptions: 2000 },
7556
+ pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200, maxSubscriptions: 10000 },
7557
+ unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null, maxSubscriptions: null }
7427
7558
  },
7428
7559
  anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
7429
7560
 
@@ -7463,6 +7594,13 @@ const serverOption = {
7463
7594
 
7464
7595
  auth: {
7465
7596
  failDelay: 600, // ms before AUTH_FAIL is sent
7597
+ // Wrong logins: a connection is closed after maxFailuresPerConnection; a public address with
7598
+ // maxFailuresPerAddress in failureWindowMs gets its next logins closed unchecked until the window
7599
+ // has passed (closed, not AUTH_FAIL, so a device with the right key there connects again).
7600
+ // Loopback and private addresses are not counted (a proxy, a LAN, tests).
7601
+ maxFailuresPerConnection: 5,
7602
+ maxFailuresPerAddress: 30,
7603
+ failureWindowMs: 60000,
7466
7604
  // Default for BohoAuth, when the same authenticated CID is already online:
7467
7605
  // 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
7468
7606
  // Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
@@ -7480,6 +7618,11 @@ const serverOption = {
7480
7618
 
7481
7619
  const decoder$3 = new TextDecoder();
7482
7620
 
7621
+ // With security.requireEncryption, what a logged-in connection without TLS may not send in plain.
7622
+ // PING, PONG, CID_REQ, ECHO and CLOSE carry nothing and stay plain, as clients send them.
7623
+ const PLAINTEXT_REFUSED = new Set([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.SUBSCRIBE_REQ,
7624
+ IOMsg.UNSUBSCRIBE, IOMsg.CALL, IOMsg.IAM]);
7625
+
7483
7626
  $$1.NB;
7484
7627
  const MB = $$1.MB;
7485
7628
 
@@ -7518,6 +7661,7 @@ class RemoteCore {
7518
7661
  this.security = manager.server.security;
7519
7662
  this._challengeIssuedAt = null;
7520
7663
  this._challengeUsed = false;
7664
+ this.authFailures = 0; // failed logins on this connection (BohoAuth)
7521
7665
  this._replayBuckets = new Map();
7522
7666
  this._replayEntries = 0;
7523
7667
  this._replayExpiredBefore = 0;
@@ -7789,6 +7933,11 @@ class RemoteCore {
7789
7933
  }
7790
7934
 
7791
7935
  } else ;
7936
+ if (!encrypted && this.security.requireEncryption && this.boho.isAuthorized && !this.TLS &&
7937
+ PLAINTEXT_REFUSED.has(msgType)) {
7938
+ this.securityMismatch('PLAINTEXT_AFTER_LOGIN');
7939
+ return;
7940
+ }
7792
7941
  if (logMessages) this.logMessage(msgType, message, encrypted);
7793
7942
 
7794
7943
  switch (msgType) {
@@ -7902,8 +8051,10 @@ class RemoteCore {
7902
8051
  tag = decoder$3.decode(tag);
7903
8052
  let tagList = tag.split(',');
7904
8053
  // console.log('>> SUBSCRIBE_REQ from:', this.cid, tagList)
7905
- this.manager.subscribe(tagList, this);
7906
- this.response(msgID, 0);
8054
+ const rejected = this.subscriptionsRejected ?? 0;
8055
+ if (this.manager.subscribe(tagList, this) === false) return
8056
+ // 255: some tags were over the quota's maxSubscriptions and were not subscribed.
8057
+ this.response(msgID, (this.subscriptionsRejected ?? 0) > rejected ? 255 : 0);
7907
8058
  } else {
7908
8059
  this.response(msgID, 255);
7909
8060
  }
@@ -7938,7 +8089,11 @@ class RemoteCore {
7938
8089
 
7939
8090
  // client's auth requst
7940
8091
  case it.BohoMsg.AUTH_REQ:
7941
- if (!this.manager.authManager) return
8092
+ // No login on this server: say so, or the client would wait in auth_req forever.
8093
+ if (!this.manager.authManager) {
8094
+ this.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
8095
+ return
8096
+ }
7942
8097
  // A second request while verification is pending must not restart auth.
7943
8098
  if (this.state === STATE.AUTH_REQ) {
7944
8099
  this.securityMismatch('AUTH_IN_PROGRESS');
@@ -8150,6 +8305,15 @@ function getLocalAddress() {
8150
8305
  }
8151
8306
 
8152
8307
 
8308
+ // A login ID travels as 8 bytes (Boho id8): a longer one would be cut and could never match, or
8309
+ // match another entry. Key providers refuse it when it is added.
8310
+ function checkLoginId(id) {
8311
+ if (typeof id !== 'string' || !id || new TextEncoder().encode(id).byteLength > 8) {
8312
+ throw new RangeError(`login ID must be 1-8 bytes: ${typeof id === 'string' ? id : typeof id}`)
8313
+ }
8314
+ return id
8315
+ }
8316
+
8153
8317
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
8154
8318
 
8155
8319
  const decoder$2 = new TextDecoder();
@@ -8256,26 +8420,20 @@ class Remote extends RemoteCore {
8256
8420
  this.txDrainMaxMs = Math.max(this.txDrainMaxMs, performance.now() - this.txBlockedSince);
8257
8421
  this.txBlockedSince = null;
8258
8422
  });
8259
- this.congRx = new CongRx({ maxFrameSize: this.rxFrameLimit() });
8423
+ // tcpSocket -> congRx (frame parser, no stream) -> onSocketMessage
8424
+ this.congRx = new CongParser({
8425
+ maxFrameSize: this.rxFrameLimit(),
8426
+ onFrame: (serverOption.debug.slow ? this.onTimeDelayMessage : this.onSocketMessage).bind(this),
8427
+ onWrong: this.onWrongCongPacketMessage.bind(this),
8428
+ onOversize: this.onOversizeCongPacket.bind(this)
8429
+ });
8260
8430
  socket.on('data', data => { this.congRx.write(data); });
8261
8431
 
8262
- this.congRx.on('wrong', this.onWrongCongPacketMessage.bind(this));
8263
- this.congRx.on('oversize', this.onOversizeCongPacket.bind(this));
8264
- // readable.pipe( destination )
8265
- // tcpSocket -> congRx(parser) -> onMessage
8266
- // socket.pipe( this.congRx )
8267
-
8268
- if (serverOption.debug.slow) {
8269
- this.congRx.on('data', this.onTimeDelayMessage.bind(this));
8270
- } else {
8271
- this.congRx.on('data', this.onSocketMessage.bind(this));
8272
- }
8273
-
8274
8432
  socket.on('error', e => { console.log('TCP Socket error', e); });
8275
8433
  socket.on('close', e => {
8276
8434
  // Clean up listeners on both the socket and the parser
8277
8435
  socket.removeAllListeners();
8278
- this.congRx.removeAllListeners();
8436
+ this.congRx.clear();
8279
8437
  this.manager.removeRemote(this);
8280
8438
  });
8281
8439
 
@@ -9153,6 +9311,7 @@ class Manager {
9153
9311
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
9154
9312
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
9155
9313
  peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
9314
+ subscriptionsRejected: 0, // subscriptions over a connection's quota maxSubscriptions, left out
9156
9315
  policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
9157
9316
  hostInbound: 0, // client signals handed to a host (server.host)
9158
9317
  hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
@@ -9699,7 +9858,16 @@ class Manager {
9699
9858
  if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
9700
9859
  }
9701
9860
 
9861
+ // Returns false when nothing was subscribed (membersOnly), else the connection's subscription count.
9862
+ // Tags over the quota's maxSubscriptions are left out and counted in subscriptionsRejected.
9702
9863
  subscribe(chArr, remote) {
9864
+ // Reading is closed to anonymous connections like sending (sender): same answer.
9865
+ if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
9866
+ remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
9867
+ remote.close();
9868
+ return false
9869
+ }
9870
+ const maxSubscriptions = remote.quota?.maxSubscriptions ?? null;
9703
9871
  chArr.forEach(tag => {
9704
9872
  if (tag.indexOf('#') === 0) {
9705
9873
  tag = remote.HOME_CHANNEL + tag;
@@ -9709,6 +9877,12 @@ class Manager {
9709
9877
  tag = this.CHANNEL_PREFIX + tag;
9710
9878
  }
9711
9879
 
9880
+ if (maxSubscriptions !== null && remote.channels.size >= maxSubscriptions && !remote.channels.has(tag)) {
9881
+ this.counters.subscriptionsRejected++;
9882
+ remote.subscriptionsRejected = (remote.subscriptionsRejected ?? 0) + 1;
9883
+ return
9884
+ }
9885
+
9712
9886
  // 1. set channel map
9713
9887
  if (this.channel_map.has(tag)) {
9714
9888
  this.channel_map.get(tag).add(remote);
@@ -9981,6 +10155,7 @@ class BohoAuth {
9981
10155
  if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
9982
10156
  this.onAuthEvent = options.onAuthEvent ?? null;
9983
10157
  this.resolveQuota = options.resolveQuota ?? defaultQuota;
10158
+ this.addressFailures = new Map(); // public address -> { count, since } of wrong logins
9984
10159
  this.authLogger;
9985
10160
  if (serverOption.fileLogger.auth.use) {
9986
10161
  this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
@@ -10021,9 +10196,46 @@ class BohoAuth {
10021
10196
  }
10022
10197
  }
10023
10198
 
10024
- send_auth_fail(peer, reason) {
10199
+ // Wrong logins of a public address in the current window (see serverOption.auth).
10200
+ #addressEntry(ip, now = Date.now()) {
10201
+ if (typeof ip !== 'string' || !ip || isPrivateIP(ip)) return null
10202
+ let entry = this.addressFailures.get(ip);
10203
+ if (entry && now - entry.since >= serverOption.auth.failureWindowMs) {
10204
+ this.addressFailures.delete(ip);
10205
+ entry = undefined;
10206
+ }
10207
+ return entry ?? { count: 0, since: now, fresh: true }
10208
+ }
10209
+
10210
+ /** True while this address has too many wrong logins: its logins are closed without a check. */
10211
+ addressBlocked(ip) {
10212
+ const entry = this.#addressEntry(ip);
10213
+ return !!entry && entry.count >= serverOption.auth.maxFailuresPerAddress
10214
+ }
10215
+
10216
+ #countFailure(peer) {
10217
+ peer.authFailures = (peer.authFailures ?? 0) + 1;
10218
+ const entry = this.#addressEntry(peer.ip);
10219
+ if (!entry) return
10220
+ if (entry.fresh) {
10221
+ delete entry.fresh;
10222
+ // Bounded: forget windows that have passed before adding another address.
10223
+ if (this.addressFailures.size >= 10000) {
10224
+ const now = Date.now();
10225
+ for (const [ip, e] of this.addressFailures) if (now - e.since >= serverOption.auth.failureWindowMs) this.addressFailures.delete(ip);
10226
+ if (this.addressFailures.size >= 10000) this.addressFailures.clear();
10227
+ }
10228
+ this.addressFailures.set(peer.ip, entry);
10229
+ }
10230
+ entry.count++;
10231
+ }
10232
+
10233
+ // countFailure: a wrong ID or key (not a refusal of a valid key, such as a duplicate login).
10234
+ send_auth_fail(peer, reason, countFailure = false) {
10025
10235
  if (peer._closing || peer.state === STATE.CLOSED) return;
10026
10236
  peer.boho.isAuthorized = false;
10237
+ if (countFailure) this.#countFailure(peer);
10238
+ const lastTry = countFailure && peer.authFailures >= serverOption.auth.maxFailuresPerConnection;
10027
10239
  if (this.authLogger) {
10028
10240
  let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
10029
10241
  this.authLogger.log(peerInfo);
@@ -10034,11 +10246,24 @@ class BohoAuth {
10034
10246
  setTimeout(e => {
10035
10247
  if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
10036
10248
  peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
10249
+ // Too many wrong logins on this connection: it has to connect again to go on.
10250
+ if (lastTry) peer.close();
10037
10251
  }
10038
10252
  }, serverOption.auth.failDelay);
10039
10253
  }
10040
10254
 
10041
10255
 
10256
+ // The login could not be checked (key store unreachable): not an answer about the key. The
10257
+ // connection is closed, so the client connects and logs in again, instead of AUTH_FAIL, which
10258
+ // clients take as "wrong key" and do not retry.
10259
+ close_unavailable(peer, reason) {
10260
+ if (peer._closing || peer.state === STATE.CLOSED) return;
10261
+ console.error('BohoAuth: login not checked, closing the connection:', reason);
10262
+ if (this.authLogger) this.authLogger.log(`UNAVAILABLE #${peer.ssid} reason:${reason} `);
10263
+ peer.boho.isAuthorized = false;
10264
+ peer.close();
10265
+ }
10266
+
10042
10267
  /**
10043
10268
  * Hook for a subclass: decide where a verified login belongs before it is accepted.
10044
10269
  * Called after the key and role checks, before quotas and the duplicate login check.
@@ -10087,11 +10312,23 @@ class BohoAuth {
10087
10312
  id = decoder.decode(infoPack.id8);
10088
10313
  }
10089
10314
 
10315
+ // Too many wrong logins from this address: not checked until its window has passed.
10316
+ if (this.addressBlocked(peer.ip)) {
10317
+ this.close_unavailable(peer, 'too many wrong logins from ' + peer.ip);
10318
+ return
10319
+ }
10320
+
10090
10321
  //2. get key of id from DB
10091
- let authInfo = await this.keyProvider.getAuth(id);
10322
+ let authInfo;
10323
+ try {
10324
+ authInfo = await this.keyProvider.getAuth(id);
10325
+ } catch (error) {
10326
+ this.close_unavailable(peer, 'key provider: ' + (error?.message ?? error));
10327
+ return
10328
+ }
10092
10329
  if (!peer.checkAuthChallenge()) return;
10093
10330
  if (!authInfo) {
10094
- this.send_auth_fail(peer, 'NO ID:' + id);
10331
+ this.send_auth_fail(peer, 'NO ID:' + id, true);
10095
10332
  return
10096
10333
  }
10097
10334
 
@@ -10116,7 +10353,7 @@ class BohoAuth {
10116
10353
  //3. check hmac
10117
10354
  let auth_res = peer.boho.verify_auth_req(infoPack);
10118
10355
  if (!auth_res) {
10119
- this.send_auth_fail(peer, 'hmac dismatched');
10356
+ this.send_auth_fail(peer, 'hmac dismatched', true);
10120
10357
  return
10121
10358
  }
10122
10359
 
@@ -10140,7 +10377,13 @@ class BohoAuth {
10140
10377
  peer.close();
10141
10378
  return
10142
10379
  }
10143
- const quotaName = await this.resolveQuota(authInfo, role);
10380
+ let quotaName;
10381
+ try {
10382
+ quotaName = await this.resolveQuota(authInfo, role);
10383
+ } catch (error) {
10384
+ this.close_unavailable(peer, 'quota: ' + (error?.message ?? error));
10385
+ return
10386
+ }
10144
10387
  const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
10145
10388
  if (!quota) {
10146
10389
  this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
@@ -10195,9 +10438,19 @@ class BohoAuth {
10195
10438
  }
10196
10439
 
10197
10440
  //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);
10441
+ if (peer.cid && peer.cid !== authInfo.cid) {
10442
+ // Subscribers of the CID it had (an anonymous one, before login()) are told it is gone, as when
10443
+ // a connection closes. Sent to them only: nothing is retained under the new CID.
10444
+ const manager = peer.manager;
10445
+ for (const topic of ['@state', '@$state']) {
10446
+ const tag = peer.cid + topic;
10447
+ manager.deliver(manager.CID_PREFIX + tag, getSignalPack(tag, 'close'), null);
10448
+ }
10449
+ // What it retained carries the old CID in its tag: dropped, the device publishes again when ready.
10450
+ for (const message of peer.retain_signal.values()) manager.retainBytes -= message.byteLength;
10451
+ peer.retain_signal.clear();
10452
+ peer.retainBytes = 0;
10453
+ manager.cid2remote.delete(peer.cid);
10201
10454
  }
10202
10455
 
10203
10456
  //7. setting info.
@@ -11070,7 +11323,7 @@ function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
11070
11323
  }
11071
11324
  const positive = (name, value) => integer(name, value, 1);
11072
11325
  const nonNegative = (name, value) => integer(name, value, 0);
11073
- const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
11326
+ const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections', 'maxSubscriptions'];
11074
11327
 
11075
11328
  // This Server's quota profiles: the defaults with each given profile merged over its default
11076
11329
  // (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
@@ -11135,13 +11388,13 @@ class Server extends require$$0$3 {
11135
11388
  * loopback/private peer, true always, false never, or N trusted proxy hops.
11136
11389
  * options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
11137
11390
  * options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
11138
- * options.membersOnly: drop signals from connections that are not authenticated.
11391
+ * options.membersOnly: only authenticated connections may send signals or subscribe.
11139
11392
  * options.logMessages: log each received message after decryption: type and tag, never the payload.
11140
11393
  * options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
11141
- * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
11394
+ * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries, requireEncryption }.
11142
11395
  * options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
11143
11396
  * options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
11144
- * maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
11397
+ * maxConnections, maxSubscriptions } }, merged over serverOption.quotas; always enforced, null is unlimited.
11145
11398
  * Adjustable later on server.quotas. The client is told its maxMessageBytes.
11146
11399
  * options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
11147
11400
  * options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
@@ -11162,7 +11415,7 @@ class Server extends require$$0$3 {
11162
11415
  // never written, so servers in one process do not affect each other.
11163
11416
  checkRemoved(options);
11164
11417
  this.security = Object.freeze(group('security', options.security,
11165
- { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
11418
+ { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive, requireEncryption: boolean }));
11166
11419
  // retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
11167
11420
  this.retain = group('retain', options.retain, {
11168
11421
  enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
@@ -11480,7 +11733,6 @@ class FileKeyProvider {
11480
11733
  //loaded when server start.
11481
11734
  loadAuthInfoFile_JS(path) {
11482
11735
  import(path).then((file) => {
11483
- console.log(file.authInfo);
11484
11736
  file.authInfo.forEach(item => {
11485
11737
  this.addAuth(...item);
11486
11738
  });
@@ -11510,6 +11762,7 @@ class FileKeyProvider {
11510
11762
 
11511
11763
  // Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
11512
11764
  addAuth(id, keyStr, cid, role, quota) {
11765
+ checkLoginId(id);
11513
11766
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11514
11767
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11515
11768
  }
@@ -11529,14 +11782,12 @@ class RedisKeyProvider {
11529
11782
  }
11530
11783
 
11531
11784
  // get device key from DB. (for Boho auth.)
11785
+ // null: no such device. A Redis failure throws, so BohoAuth closes the connection (the client
11786
+ // connects again) instead of answering AUTH_FAIL as if the ID were unknown.
11532
11787
  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
- }
11788
+ let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11789
+ if (result && result.key) return result
11790
+ else return null;
11540
11791
  }
11541
11792
 
11542
11793
  //sudoService call
@@ -11547,13 +11798,18 @@ class RedisKeyProvider {
11547
11798
 
11548
11799
  // Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
11549
11800
  // 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).
11801
+ // (RemoteRedisClient throws on a refused command; an undefined reply is treated the same).
11551
11802
  async scanKeys(pattern) {
11552
11803
  if (typeof this.redis.scan === 'function') {
11553
11804
  const keys = new Set(); // SCAN may return a key more than once
11554
11805
  let cursor = '0';
11555
11806
  do {
11556
- const reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11807
+ let reply;
11808
+ try {
11809
+ reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11810
+ } catch {
11811
+ break
11812
+ }
11557
11813
  if (!reply || !Array.isArray(reply.keys)) break
11558
11814
  for (const key of reply.keys) keys.add(key);
11559
11815
  cursor = String(reply.cursor);
@@ -11566,6 +11822,7 @@ class RedisKeyProvider {
11566
11822
  // add device auth info
11567
11823
  // role and quota are optional (see StringKeyProvider); an omitted one is not stored.
11568
11824
  async addAuth(id, keyStr, cid = '', role, quota) {
11825
+ checkLoginId(id);
11569
11826
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11570
11827
  const fields = { 'key': Base64hashKey, 'cid': cid };
11571
11828
  if (role) fields.role = role;
@@ -11634,6 +11891,7 @@ class StringKeyProvider {
11634
11891
  }
11635
11892
 
11636
11893
  addAuth(id, keyStr, cid, role, quota) {
11894
+ checkLoginId(id);
11637
11895
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11638
11896
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11639
11897
  }
@@ -11827,4 +12085,4 @@ class RedisService {
11827
12085
 
11828
12086
  const version = pkg.version;
11829
12087
 
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 };
12088
+ 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 };