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.
@@ -23,7 +23,7 @@ var node_os = require('node:os');
23
23
  var path = require('path');
24
24
 
25
25
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
26
- var version$1 = "9.19.0";
26
+ var version$1 = "9.22.0";
27
27
  var pkg = {
28
28
  version: version$1};
29
29
 
@@ -449,6 +449,10 @@ for (let c in ENC_MODE) { ENC_MODE[ENC_MODE[c]] = c; }
449
449
  * @property {number} TAG_LEN2
450
450
  * @property {number} CONNECTION_CHECKER_PERIOD
451
451
  * @property {number} CLIENT_PING_PERIOD
452
+ * @property {number} PONG_TIMEOUT
453
+ * @property {number} RECONNECT_JITTER
454
+ * @property {number} RECONNECT_BASE
455
+ * @property {number} RECONNECT_MAX
452
456
  * @property {number} SERVER_HELLO_TIMEOUT
453
457
  * @property {number} PROMISE_TIMEOUT
454
458
  * @property {number} DID
@@ -459,6 +463,17 @@ const SIZE_LIMIT = {
459
463
  TAG_LEN2: 65535,
460
464
  CONNECTION_CHECKER_PERIOD: 3000,
461
465
  CLIENT_PING_PERIOD: 40000,
466
+ // After a client PING (sent when nothing was received for CLIENT_PING_PERIOD): with no message
467
+ // from the server in this time the connection is taken as dead and closed, so the client
468
+ // reconnects. A lost Wi-Fi or mobile link may leave a socket open for many minutes otherwise.
469
+ PONG_TIMEOUT: 15000,
470
+ // Reconnecting (autoReconnect): the first attempt after a connection closes waits a random time
471
+ // up to RECONNECT_JITTER, so the clients of a restarted server do not all return at once; each
472
+ // further attempt without reaching ready waits RECONNECT_BASE, doubled each time up to
473
+ // RECONNECT_MAX (each +-20%). Reaching ready starts over.
474
+ RECONNECT_JITTER: 1000,
475
+ RECONNECT_BASE: 3000,
476
+ RECONNECT_MAX: 30000,
462
477
  // From starting a connection to the server's hello (SERVER_TIME_NONCE). A connection that hangs
463
478
  // longer is closed, so the client reconnects to its own URL (after a redirect: the original one).
464
479
  SERVER_HELLO_TIMEOUT: 15000,
@@ -779,6 +794,14 @@ function sendSubscription(io, tag) {
779
794
  ]));
780
795
  }
781
796
 
797
+ // Names the client emits itself. A signal, SERVER_SIGNAL or SET with one of these as its tag is not
798
+ // emitted under that name, so nothing from the network can pose as a connection event (a signal
799
+ // on a channel called 'close' would otherwise run the client's own close handling).
800
+ const INTERNAL_EVENTS = new Set(['open', 'close', 'closed', 'socket_data', 'change', 'error', 'message',
801
+ 'connecting', 'closing', 'server_ready', 'auth_req', 'auth_res', 'auth_fail', 'auth_clear',
802
+ 'cid_req', 'cid_res', 'ready', 'stop', 'redirecting', 'pong', 'echo', 'iam_res', 'over_size',
803
+ 'text_message']);
804
+
782
805
  function byteToUrl(buffer) {
783
806
  //ipv4(4bytes) , port(2bytes)
784
807
  if (buffer.byteLength != 6) return
@@ -856,6 +879,16 @@ class IOCore extends EventEmitter {
856
879
  * @type {number}
857
880
  */
858
881
  this.lastTxRxTime = Date.now();
882
+ /**
883
+ * Last time anything was received from the server (see keepAlive()).
884
+ * @type {number}
885
+ */
886
+ this.lastRxTime = Date.now();
887
+ /** @private Time of a PING that has had no answer yet; 0 when none is pending. */
888
+ this._pingSentAt = 0;
889
+ /** @private Connections closed since the last ready, and the earliest time of the next automatic attempt. */
890
+ this._reconnectAttempts = 0;
891
+ this._nextConnectAt = 0;
859
892
  /**
860
893
  * Period for connection checker.
861
894
  * @type {number}
@@ -971,6 +1004,7 @@ class IOCore extends EventEmitter {
971
1004
  close() {
972
1005
  // console.log('####### IOCOre.js close() called')
973
1006
  this.clearHelloTimer();
1007
+ this._pingSentAt = 0;
974
1008
  // If auto-reconnect is disabled, we must stop the keep-alive timer.
975
1009
  if (this.autoReconnect === false) {
976
1010
  clearInterval(this.connectionCheckerIntervalID);
@@ -978,6 +1012,7 @@ class IOCore extends EventEmitter {
978
1012
  }
979
1013
  if (this._closed) return;
980
1014
  this._closed = true;
1015
+ this.scheduleReconnect();
981
1016
 
982
1017
  // socket clean
983
1018
  if (this.socket) {
@@ -1051,12 +1086,37 @@ class IOCore extends EventEmitter {
1051
1086
  * is implemented keepConnection() in the child classes (IOWS, IOCongSocket, etc.).
1052
1087
  */
1053
1088
  keepAlive() {
1054
- this.keepConnection();
1055
- if( Date.now() - this.lastTxRxTime > SIZE_LIMIT.CLIENT_PING_PERIOD ){
1089
+ if (Date.now() >= this._nextConnectAt) this.keepConnection();
1090
+ if (!this.isLinkUp()) return;
1091
+ const now = Date.now();
1092
+ // A PING the server did not answer with anything: the connection is dead although the socket
1093
+ // still looks open (lost Wi-Fi, a sleeping phone, a NAT that dropped it). Close it; with
1094
+ // autoReconnect the next keepAlive() connects again.
1095
+ if (this._pingSentAt && now - this._pingSentAt > SIZE_LIMIT.PONG_TIMEOUT) {
1096
+ this.emit('error', new Error('no reply from the server in ' + SIZE_LIMIT.PONG_TIMEOUT / 1000 + ' s; reconnecting'));
1097
+ this.close();
1098
+ return;
1099
+ }
1100
+ // Sending does not show the server is there, so this follows what was received.
1101
+ if (!this._pingSentAt && now - this.lastRxTime > SIZE_LIMIT.CLIENT_PING_PERIOD) {
1056
1102
  this.ping();
1057
1103
  }
1058
1104
  }
1059
1105
 
1106
+ /** @private When keepAlive() may connect again after this close: see SIZE_LIMIT.RECONNECT_*. */
1107
+ scheduleReconnect() {
1108
+ const attempt = this._reconnectAttempts++;
1109
+ const delay = attempt === 0
1110
+ ? Math.random() * SIZE_LIMIT.RECONNECT_JITTER
1111
+ : Math.min(SIZE_LIMIT.RECONNECT_MAX, SIZE_LIMIT.RECONNECT_BASE * 2 ** (attempt - 1)) * (0.8 + Math.random() * 0.4);
1112
+ this._nextConnectAt = Date.now() + delay;
1113
+ }
1114
+
1115
+ /** @private True from the socket opening until it closes (any state a server message can arrive in). */
1116
+ isLinkUp() {
1117
+ return !!this.socket && !this._closed && (this.state === STATE.OPEN || this.state >= STATE.SERVER_READY);
1118
+ }
1119
+
1060
1120
  /**
1061
1121
  * Redirects the connection to a new URL.
1062
1122
  * @param {string} url2 - The new URL to redirect to.
@@ -1127,6 +1187,8 @@ class IOCore extends EventEmitter {
1127
1187
  */
1128
1188
  onOpen() {
1129
1189
  this._closed = false;
1190
+ this.lastRxTime = Date.now();
1191
+ this._pingSentAt = 0;
1130
1192
  if (this.url.includes("wss://")) {
1131
1193
  this.TLS = true;
1132
1194
  } else {
@@ -1153,6 +1215,8 @@ class IOCore extends EventEmitter {
1153
1215
  this.auth(id, key);
1154
1216
  this.useAuth = true;
1155
1217
  let auth_pack = this.boho.auth_req(this.serverTimeNonce );
1218
+ // false: no key was set (bad arguments), or the server has not said hello on this connection yet.
1219
+ if (!auth_pack) return this
1156
1220
  this.send(auth_pack);
1157
1221
  this.stateChange('auth_req', 'auth_req');
1158
1222
  }
@@ -1166,17 +1230,21 @@ class IOCore extends EventEmitter {
1166
1230
  * @returns {this}
1167
1231
  */
1168
1232
  auth(id, key) {
1169
- if (!id && !key) {
1170
- this.emit('error', new Error('auth failed. no id and key.'));
1233
+ if (key === null || key === '') key = undefined; // auth('id.key', '') from a form with one field
1234
+ if (typeof id !== 'string' || !id || (key === undefined ? !/^[^.]+\..+$/.test(id) : typeof key !== 'string')) {
1235
+ this.emit('error', new Error("auth failed. use auth('id', 'key') or auth('id.key')."));
1236
+ return this
1171
1237
  }
1172
-
1173
- if (!key && id.includes('.')) {
1238
+ // The ID travels as 8 bytes; a longer one is cut (as before), which the server may not know.
1239
+ const loginId = key === undefined ? id.slice(0, id.indexOf('.')) : id;
1240
+ if (encoder$2.encode(loginId).byteLength > SIZE_LIMIT.DID) {
1241
+ this.emit('error', new Error(`auth: login ID '${loginId}' is longer than ${SIZE_LIMIT.DID} bytes and is cut to them.`));
1242
+ }
1243
+ if (key === undefined) {
1174
1244
  this.boho.set_id_key(id);
1175
- } else if (id && key) {
1245
+ } else {
1176
1246
  this.boho.set_id8(id);
1177
1247
  this.boho.set_key(key);
1178
- } else {
1179
- this.emit('error', new Error('auth failed. no id or key.'));
1180
1248
  }
1181
1249
  this.useAuth = true;
1182
1250
  return this
@@ -1187,6 +1255,8 @@ class IOCore extends EventEmitter {
1187
1255
  * @param {Buffer} buffer - The incoming data buffer.
1188
1256
  */
1189
1257
  onData(buffer) {
1258
+ this.lastRxTime = Date.now();
1259
+ this._pingSentAt = 0;
1190
1260
  let msgType = buffer[0];
1191
1261
  let decoded;
1192
1262
 
@@ -1195,6 +1265,9 @@ class IOCore extends EventEmitter {
1195
1265
  if (decoded) {
1196
1266
  msgType = decoded[0];
1197
1267
  buffer = decoded;
1268
+ } else {
1269
+ // Not from this session (or damaged): dropped, never passed on as a text message.
1270
+ return
1198
1271
  }
1199
1272
  } else if (msgType === it.BohoMsg.ENC_E2E) {
1200
1273
 
@@ -1268,6 +1341,7 @@ class IOCore extends EventEmitter {
1268
1341
  // State first (subscribe_channels needs READY), then the stored subscriptions, and only then
1269
1342
  // 'ready': a signal sent from a ready handler reaches the server after our own subscriptions.
1270
1343
  // stateChange() without a message emits 'change' only; false means a handler moved the state on.
1344
+ this._reconnectAttempts = 0;
1271
1345
  if (!this.stateChange('ready')) break;
1272
1346
  this.subscribe_channels();
1273
1347
  this._readyDispatch = true;
@@ -1327,7 +1401,7 @@ class IOCore extends EventEmitter {
1327
1401
  let str = decoder$4.decode(buffer.subarray(1));
1328
1402
  let ss = JSON.parse(str);
1329
1403
 
1330
- if (ss.event && ss.data) {
1404
+ if (typeof ss.event === 'string' && ss.event && ss.data && !INTERNAL_EVENTS.has(ss.event)) {
1331
1405
  this.serverSet = ss.data;
1332
1406
  this.emit(ss.event, ss.data);
1333
1407
  }
@@ -1340,8 +1414,8 @@ class IOCore extends EventEmitter {
1340
1414
  case IOMsg.SET:
1341
1415
  try {
1342
1416
  let setPack = $$1.unpack(buffer);
1343
- if (setPack) {
1344
- this.emit(setPack.topic, ...setPack.args);
1417
+ if (setPack && typeof setPack.topic === 'string' && !INTERNAL_EVENTS.has(setPack.topic)) {
1418
+ this.emit(setPack.topic, ...(setPack.args ?? []));
1345
1419
  }
1346
1420
  } catch (error) {
1347
1421
  this.emit('error', new Error('SET parsing error'));
@@ -1369,7 +1443,8 @@ class IOCore extends EventEmitter {
1369
1443
  this.emit('@', tag, ...args);
1370
1444
  if (tag !== '@') this.emit(tag, tag, ...args);
1371
1445
  } else {
1372
- this.emit(tag, tag, ...args);
1446
+ // A channel whose name is one of the client's own events reaches 'message' only.
1447
+ if (!INTERNAL_EVENTS.has(tag)) this.emit(tag, tag, ...args);
1373
1448
  this.emit('message', tag, ...args);
1374
1449
  }
1375
1450
  }
@@ -1436,6 +1511,8 @@ class IOCore extends EventEmitter {
1436
1511
  * Sends a PING message to the server.
1437
1512
  */
1438
1513
  ping() {
1514
+ // Any message from the server answers it (see keepAlive()).
1515
+ if (!this._pingSentAt && this.isLinkUp()) this._pingSentAt = Date.now();
1439
1516
  this.send(Buffer$1.from([IOMsg.PING]));
1440
1517
  }
1441
1518
 
@@ -1994,6 +2071,9 @@ class IOCore extends EventEmitter {
1994
2071
 
1995
2072
  }
1996
2073
 
2074
+ // CongSocket framing without Node.js streams: pack() and the frame parser. The server's Remote
2075
+ // uses CongParser directly; CongRx (CongPacket.js) wraps the same parser in a stream Transform.
2076
+
1997
2077
  const CongType = {
1998
2078
  TYPE_LEN1: 1,
1999
2079
  TYPE_LEN2: 2,
@@ -2005,7 +2085,7 @@ const CongType = {
2005
2085
  function pack(payload) {
2006
2086
 
2007
2087
  if( payload.byteLength == undefined ) payload = Buffer.from(payload);
2008
-
2088
+
2009
2089
  if (payload.byteLength < 256) { //one byte len
2010
2090
  return $$1.pack(
2011
2091
  $$1.MB('#type', '8', CongType.TYPE_LEN1),
@@ -2040,6 +2120,130 @@ function pack(payload) {
2040
2120
 
2041
2121
  }
2042
2122
 
2123
+ /**
2124
+ * Adds a received chunk to a parser state and parses the complete frames into state.frames.
2125
+ * state: { buffer, frames, rxi, rxi_zero, maxFrameSize, skipBytes } (a CongParser or CongRx).
2126
+ * emit(event, value): 'wrong' (the unparsable buffer) or 'oversize' (payload size; the frame is
2127
+ * skipped without buffering). Shared by CongParser and CongRx so both parse alike.
2128
+ */
2129
+ function addCongData(state, chunk, emit) {
2130
+ let c = chunk.byteLength;
2131
+ let i = 0;
2132
+ while (c--) {
2133
+ state.rxi++;
2134
+ if (chunk[i++] == 0) {
2135
+ state.rxi_zero++;
2136
+ }
2137
+ }
2138
+
2139
+ if (state.skipBytes > 0) {
2140
+ if (chunk.byteLength <= state.skipBytes) {
2141
+ state.skipBytes -= chunk.byteLength;
2142
+ return;
2143
+ }
2144
+ chunk = chunk.subarray(state.skipBytes);
2145
+ state.skipBytes = 0;
2146
+ }
2147
+
2148
+ if (state.buffer.byteLength > 0) {
2149
+ state.buffer = Buffer.concat([state.buffer, chunk]);
2150
+ } else {
2151
+ state.buffer = chunk;
2152
+ }
2153
+ parseCongFrames(state, emit);
2154
+ }
2155
+
2156
+ function parseCongFrames(state, emit) {
2157
+ while (state.buffer.byteLength > 0) {
2158
+ const head = state.buffer[0];
2159
+ let headerLen;
2160
+ let payloadSize;
2161
+
2162
+ if (head === CongType.TYPE_LEN1) {
2163
+ headerLen = 2;
2164
+ if (state.buffer.byteLength < headerLen) return;
2165
+ payloadSize = state.buffer.readUint8(1);
2166
+ } else if (head === CongType.TYPE_LEN2) {
2167
+ headerLen = 3;
2168
+ if (state.buffer.byteLength < headerLen) return;
2169
+ payloadSize = state.buffer.readUint16LE(1);
2170
+ } else if (head === CongType.TYPE_LEN3) {
2171
+ headerLen = 4;
2172
+ if (state.buffer.byteLength < headerLen) return;
2173
+ payloadSize = state.buffer.readUint16LE(1) + state.buffer.readUint8(3) * 65536;
2174
+ } else if (head === CongType.TYPE_LEN4) {
2175
+ headerLen = 5;
2176
+ if (state.buffer.byteLength < headerLen) return;
2177
+ payloadSize = state.buffer.readUint32LE(1);
2178
+ } else {
2179
+ emit('wrong', state.buffer);
2180
+ state.buffer = Buffer.alloc(0);
2181
+ return;
2182
+ }
2183
+
2184
+ // Decide as soon as the length is known: the header can advertise up to 4 GiB.
2185
+ // Skipping keeps frame boundaries, so later frames still parse.
2186
+ if (payloadSize > state.maxFrameSize) {
2187
+ emit('oversize', payloadSize);
2188
+ const available = state.buffer.byteLength - headerLen;
2189
+ if (available < payloadSize) {
2190
+ state.skipBytes = payloadSize - available;
2191
+ state.buffer = Buffer.alloc(0);
2192
+ return;
2193
+ }
2194
+ state.buffer = state.buffer.subarray(headerLen + payloadSize);
2195
+ continue;
2196
+ }
2197
+
2198
+ const frameSize = headerLen + payloadSize;
2199
+ if (state.buffer.byteLength < frameSize) return;
2200
+
2201
+ state.frames.push(state.buffer.subarray(headerLen, frameSize));
2202
+ if (state.buffer.byteLength === frameSize) {
2203
+ state.buffer = Buffer.alloc(0);
2204
+ return;
2205
+ }
2206
+ // Consume each complete frame without growing the call stack.
2207
+ state.buffer = state.buffer.subarray(frameSize);
2208
+ }
2209
+ }
2210
+
2211
+ /**
2212
+ * CongSocket frame parser without streams: write(chunk) calls onFrame(payload) for each complete
2213
+ * frame, onWrong(buffer) for an unparsable stream and onOversize(payloadSize) for a frame larger
2214
+ * than maxFrameSize (skipped without buffering).
2215
+ */
2216
+ class CongParser {
2217
+ constructor({ maxFrameSize = Infinity, onFrame = null, onWrong = null, onOversize = null } = {}) {
2218
+ this.buffer = Buffer.alloc(0);
2219
+ this.frames = [];
2220
+ this.rxi = 0;
2221
+ this.rxi_zero = 0;
2222
+ this.maxFrameSize = maxFrameSize;
2223
+ this.skipBytes = 0; // remaining payload bytes of an oversized frame to discard
2224
+ this.onFrame = onFrame;
2225
+ this.onWrong = onWrong;
2226
+ this.onOversize = onOversize;
2227
+ }
2228
+
2229
+ write(chunk) {
2230
+ addCongData(this, chunk, (event, value) => {
2231
+ if (event === 'wrong') this.onWrong?.(value);
2232
+ else this.onOversize?.(value);
2233
+ });
2234
+ const frames = this.frames;
2235
+ this.frames = [];
2236
+ for (const frame of frames) this.onFrame?.(frame);
2237
+ }
2238
+
2239
+ /** Stops calling the handlers (the connection closed). */
2240
+ clear() {
2241
+ this.onFrame = this.onWrong = this.onOversize = null;
2242
+ this.buffer = Buffer.alloc(0);
2243
+ this.frames = [];
2244
+ }
2245
+ }
2246
+
2043
2247
  class CongRx extends require$$0.Transform {
2044
2248
  /**
2045
2249
  * @param {import('stream').TransformOptions & { maxFrameSize?: number }} [options] Stream options.
@@ -2072,86 +2276,7 @@ class CongRx extends require$$0.Transform {
2072
2276
 
2073
2277
 
2074
2278
  addData(chunk) {
2075
- let c = chunk.byteLength;
2076
- let i = 0;
2077
- while (c--) {
2078
- this.rxi++;
2079
- if (chunk[i++] == 0) {
2080
- this.rxi_zero++;
2081
- }
2082
- }
2083
-
2084
- if (this.skipBytes > 0) {
2085
- if (chunk.byteLength <= this.skipBytes) {
2086
- this.skipBytes -= chunk.byteLength;
2087
- return;
2088
- }
2089
- chunk = chunk.subarray(this.skipBytes);
2090
- this.skipBytes = 0;
2091
- }
2092
-
2093
- if (this.buffer.byteLength > 0) {
2094
- this.buffer = Buffer.concat([this.buffer, chunk]);
2095
- } else {
2096
- this.buffer = chunk;
2097
- }
2098
- this.parse();
2099
- }
2100
-
2101
-
2102
- parse() {
2103
- while (this.buffer.byteLength > 0) {
2104
- const head = this.buffer[0];
2105
- let headerLen;
2106
- let payloadSize;
2107
-
2108
- if (head === CongType.TYPE_LEN1) {
2109
- headerLen = 2;
2110
- if (this.buffer.byteLength < headerLen) return;
2111
- payloadSize = this.buffer.readUint8(1);
2112
- } else if (head === CongType.TYPE_LEN2) {
2113
- headerLen = 3;
2114
- if (this.buffer.byteLength < headerLen) return;
2115
- payloadSize = this.buffer.readUint16LE(1);
2116
- } else if (head === CongType.TYPE_LEN3) {
2117
- headerLen = 4;
2118
- if (this.buffer.byteLength < headerLen) return;
2119
- payloadSize = this.buffer.readUint16LE(1) + this.buffer.readUint8(3) * 65536;
2120
- } else if (head === CongType.TYPE_LEN4) {
2121
- headerLen = 5;
2122
- if (this.buffer.byteLength < headerLen) return;
2123
- payloadSize = this.buffer.readUint32LE(1);
2124
- } else {
2125
- this.emit('wrong', this.buffer);
2126
- this.buffer = Buffer.alloc(0);
2127
- return;
2128
- }
2129
-
2130
- // Decide as soon as the length is known: the header can advertise up to 4 GiB.
2131
- // Skipping keeps frame boundaries, so later frames still parse.
2132
- if (payloadSize > this.maxFrameSize) {
2133
- this.emit('oversize', payloadSize);
2134
- const available = this.buffer.byteLength - headerLen;
2135
- if (available < payloadSize) {
2136
- this.skipBytes = payloadSize - available;
2137
- this.buffer = Buffer.alloc(0);
2138
- return;
2139
- }
2140
- this.buffer = this.buffer.subarray(headerLen + payloadSize);
2141
- continue;
2142
- }
2143
-
2144
- const frameSize = headerLen + payloadSize;
2145
- if (this.buffer.byteLength < frameSize) return;
2146
-
2147
- this.frames.push(this.buffer.subarray(headerLen, frameSize));
2148
- if (this.buffer.byteLength === frameSize) {
2149
- this.buffer = Buffer.alloc(0);
2150
- return;
2151
- }
2152
- // Consume each complete frame without growing the call stack.
2153
- this.buffer = this.buffer.subarray(frameSize);
2154
- }
2279
+ addCongData(this, chunk, (event, value) => this.emit(event, value));
2155
2280
  }
2156
2281
  }
2157
2282
 
@@ -7400,7 +7525,8 @@ const serverOption = {
7400
7525
  // A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
7401
7526
  // letting its send queue grow without limit.
7402
7527
  maxBufferedBytes: 64 * 1024 * 1024,
7403
- // Drop signals from connections that are not authenticated.
7528
+ // Only authenticated connections may send signals or subscribe; an anonymous one that tries
7529
+ // gets AUTH_CLEAR and is closed.
7404
7530
  membersOnly: false,
7405
7531
  // Observability. logMessages: log each received message (type and tag, never the payload).
7406
7532
  // logStats: print a one-line summary every N ms (0 = off).
@@ -7412,7 +7538,11 @@ const serverOption = {
7412
7538
  security: {
7413
7539
  maxClockSkewMs: 60000,
7414
7540
  authChallengeMaxAgeMs: 60000,
7415
- maxReplayEntries: 65536
7541
+ maxReplayEntries: 65536,
7542
+ // true: a logged-in connection without TLS must send its signals, subscriptions and calls
7543
+ // encrypted (as clients do in ENC_MODE.AUTO); a plain one closes it (PLAINTEXT_AFTER_LOGIN).
7544
+ // Off by default: a client with encMode NO would be closed.
7545
+ requireEncryption: false
7416
7546
  },
7417
7547
  // Named quota profiles. A connection uses one: an anonymous connection the Server's
7418
7548
  // anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
@@ -7422,11 +7552,12 @@ const serverOption = {
7422
7552
  // fanout: most subscribers one channel publish is delivered to
7423
7553
  // msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
7424
7554
  // maxConnections: connections of one account (uid) at a time; over: the login fails
7555
+ // maxSubscriptions: tags one connection may be subscribed to at a time; over: the tag is left out
7425
7556
  quotas: {
7426
- anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null },
7427
- basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20 },
7428
- pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200 },
7429
- unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null }
7557
+ anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null, maxSubscriptions: 1000 },
7558
+ basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20, maxSubscriptions: 2000 },
7559
+ pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200, maxSubscriptions: 10000 },
7560
+ unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null, maxSubscriptions: null }
7430
7561
  },
7431
7562
  anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
7432
7563
 
@@ -7466,6 +7597,13 @@ const serverOption = {
7466
7597
 
7467
7598
  auth: {
7468
7599
  failDelay: 600, // ms before AUTH_FAIL is sent
7600
+ // Wrong logins: a connection is closed after maxFailuresPerConnection; a public address with
7601
+ // maxFailuresPerAddress in failureWindowMs gets its next logins closed unchecked until the window
7602
+ // has passed (closed, not AUTH_FAIL, so a device with the right key there connects again).
7603
+ // Loopback and private addresses are not counted (a proxy, a LAN, tests).
7604
+ maxFailuresPerConnection: 5,
7605
+ maxFailuresPerAddress: 30,
7606
+ failureWindowMs: 60000,
7469
7607
  // Default for BohoAuth, when the same authenticated CID is already online:
7470
7608
  // 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
7471
7609
  // Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
@@ -7483,6 +7621,11 @@ const serverOption = {
7483
7621
 
7484
7622
  const decoder$3 = new TextDecoder();
7485
7623
 
7624
+ // With security.requireEncryption, what a logged-in connection without TLS may not send in plain.
7625
+ // PING, PONG, CID_REQ, ECHO and CLOSE carry nothing and stay plain, as clients send them.
7626
+ const PLAINTEXT_REFUSED = new Set([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.SUBSCRIBE_REQ,
7627
+ IOMsg.UNSUBSCRIBE, IOMsg.CALL, IOMsg.IAM]);
7628
+
7486
7629
  $$1.NB;
7487
7630
  const MB = $$1.MB;
7488
7631
 
@@ -7521,6 +7664,7 @@ class RemoteCore {
7521
7664
  this.security = manager.server.security;
7522
7665
  this._challengeIssuedAt = null;
7523
7666
  this._challengeUsed = false;
7667
+ this.authFailures = 0; // failed logins on this connection (BohoAuth)
7524
7668
  this._replayBuckets = new Map();
7525
7669
  this._replayEntries = 0;
7526
7670
  this._replayExpiredBefore = 0;
@@ -7792,6 +7936,11 @@ class RemoteCore {
7792
7936
  }
7793
7937
 
7794
7938
  } else ;
7939
+ if (!encrypted && this.security.requireEncryption && this.boho.isAuthorized && !this.TLS &&
7940
+ PLAINTEXT_REFUSED.has(msgType)) {
7941
+ this.securityMismatch('PLAINTEXT_AFTER_LOGIN');
7942
+ return;
7943
+ }
7795
7944
  if (logMessages) this.logMessage(msgType, message, encrypted);
7796
7945
 
7797
7946
  switch (msgType) {
@@ -7905,8 +8054,10 @@ class RemoteCore {
7905
8054
  tag = decoder$3.decode(tag);
7906
8055
  let tagList = tag.split(',');
7907
8056
  // console.log('>> SUBSCRIBE_REQ from:', this.cid, tagList)
7908
- this.manager.subscribe(tagList, this);
7909
- this.response(msgID, 0);
8057
+ const rejected = this.subscriptionsRejected ?? 0;
8058
+ if (this.manager.subscribe(tagList, this) === false) return
8059
+ // 255: some tags were over the quota's maxSubscriptions and were not subscribed.
8060
+ this.response(msgID, (this.subscriptionsRejected ?? 0) > rejected ? 255 : 0);
7910
8061
  } else {
7911
8062
  this.response(msgID, 255);
7912
8063
  }
@@ -7941,7 +8092,11 @@ class RemoteCore {
7941
8092
 
7942
8093
  // client's auth requst
7943
8094
  case it.BohoMsg.AUTH_REQ:
7944
- if (!this.manager.authManager) return
8095
+ // No login on this server: say so, or the client would wait in auth_req forever.
8096
+ if (!this.manager.authManager) {
8097
+ this.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
8098
+ return
8099
+ }
7945
8100
  // A second request while verification is pending must not restart auth.
7946
8101
  if (this.state === STATE.AUTH_REQ) {
7947
8102
  this.securityMismatch('AUTH_IN_PROGRESS');
@@ -8153,6 +8308,15 @@ function getLocalAddress() {
8153
8308
  }
8154
8309
 
8155
8310
 
8311
+ // A login ID travels as 8 bytes (Boho id8): a longer one would be cut and could never match, or
8312
+ // match another entry. Key providers refuse it when it is added.
8313
+ function checkLoginId(id) {
8314
+ if (typeof id !== 'string' || !id || new TextEncoder().encode(id).byteLength > 8) {
8315
+ throw new RangeError(`login ID must be 1-8 bytes: ${typeof id === 'string' ? id : typeof id}`)
8316
+ }
8317
+ return id
8318
+ }
8319
+
8156
8320
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
8157
8321
 
8158
8322
  const decoder$2 = new TextDecoder();
@@ -8259,26 +8423,20 @@ class Remote extends RemoteCore {
8259
8423
  this.txDrainMaxMs = Math.max(this.txDrainMaxMs, node_perf_hooks.performance.now() - this.txBlockedSince);
8260
8424
  this.txBlockedSince = null;
8261
8425
  });
8262
- this.congRx = new CongRx({ maxFrameSize: this.rxFrameLimit() });
8426
+ // tcpSocket -> congRx (frame parser, no stream) -> onSocketMessage
8427
+ this.congRx = new CongParser({
8428
+ maxFrameSize: this.rxFrameLimit(),
8429
+ onFrame: (serverOption.debug.slow ? this.onTimeDelayMessage : this.onSocketMessage).bind(this),
8430
+ onWrong: this.onWrongCongPacketMessage.bind(this),
8431
+ onOversize: this.onOversizeCongPacket.bind(this)
8432
+ });
8263
8433
  socket.on('data', data => { this.congRx.write(data); });
8264
8434
 
8265
- this.congRx.on('wrong', this.onWrongCongPacketMessage.bind(this));
8266
- this.congRx.on('oversize', this.onOversizeCongPacket.bind(this));
8267
- // readable.pipe( destination )
8268
- // tcpSocket -> congRx(parser) -> onMessage
8269
- // socket.pipe( this.congRx )
8270
-
8271
- if (serverOption.debug.slow) {
8272
- this.congRx.on('data', this.onTimeDelayMessage.bind(this));
8273
- } else {
8274
- this.congRx.on('data', this.onSocketMessage.bind(this));
8275
- }
8276
-
8277
8435
  socket.on('error', e => { console.log('TCP Socket error', e); });
8278
8436
  socket.on('close', e => {
8279
8437
  // Clean up listeners on both the socket and the parser
8280
8438
  socket.removeAllListeners();
8281
- this.congRx.removeAllListeners();
8439
+ this.congRx.clear();
8282
8440
  this.manager.removeRemote(this);
8283
8441
  });
8284
8442
 
@@ -9156,6 +9314,7 @@ class Manager {
9156
9314
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
9157
9315
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
9158
9316
  peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
9317
+ subscriptionsRejected: 0, // subscriptions over a connection's quota maxSubscriptions, left out
9159
9318
  policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
9160
9319
  hostInbound: 0, // client signals handed to a host (server.host)
9161
9320
  hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
@@ -9702,7 +9861,16 @@ class Manager {
9702
9861
  if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
9703
9862
  }
9704
9863
 
9864
+ // Returns false when nothing was subscribed (membersOnly), else the connection's subscription count.
9865
+ // Tags over the quota's maxSubscriptions are left out and counted in subscriptionsRejected.
9705
9866
  subscribe(chArr, remote) {
9867
+ // Reading is closed to anonymous connections like sending (sender): same answer.
9868
+ if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
9869
+ remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
9870
+ remote.close();
9871
+ return false
9872
+ }
9873
+ const maxSubscriptions = remote.quota?.maxSubscriptions ?? null;
9706
9874
  chArr.forEach(tag => {
9707
9875
  if (tag.indexOf('#') === 0) {
9708
9876
  tag = remote.HOME_CHANNEL + tag;
@@ -9712,6 +9880,12 @@ class Manager {
9712
9880
  tag = this.CHANNEL_PREFIX + tag;
9713
9881
  }
9714
9882
 
9883
+ if (maxSubscriptions !== null && remote.channels.size >= maxSubscriptions && !remote.channels.has(tag)) {
9884
+ this.counters.subscriptionsRejected++;
9885
+ remote.subscriptionsRejected = (remote.subscriptionsRejected ?? 0) + 1;
9886
+ return
9887
+ }
9888
+
9715
9889
  // 1. set channel map
9716
9890
  if (this.channel_map.has(tag)) {
9717
9891
  this.channel_map.get(tag).add(remote);
@@ -9984,6 +10158,7 @@ class BohoAuth {
9984
10158
  if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
9985
10159
  this.onAuthEvent = options.onAuthEvent ?? null;
9986
10160
  this.resolveQuota = options.resolveQuota ?? defaultQuota;
10161
+ this.addressFailures = new Map(); // public address -> { count, since } of wrong logins
9987
10162
  this.authLogger;
9988
10163
  if (serverOption.fileLogger.auth.use) {
9989
10164
  this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
@@ -10024,9 +10199,46 @@ class BohoAuth {
10024
10199
  }
10025
10200
  }
10026
10201
 
10027
- send_auth_fail(peer, reason) {
10202
+ // Wrong logins of a public address in the current window (see serverOption.auth).
10203
+ #addressEntry(ip, now = Date.now()) {
10204
+ if (typeof ip !== 'string' || !ip || isPrivateIP(ip)) return null
10205
+ let entry = this.addressFailures.get(ip);
10206
+ if (entry && now - entry.since >= serverOption.auth.failureWindowMs) {
10207
+ this.addressFailures.delete(ip);
10208
+ entry = undefined;
10209
+ }
10210
+ return entry ?? { count: 0, since: now, fresh: true }
10211
+ }
10212
+
10213
+ /** True while this address has too many wrong logins: its logins are closed without a check. */
10214
+ addressBlocked(ip) {
10215
+ const entry = this.#addressEntry(ip);
10216
+ return !!entry && entry.count >= serverOption.auth.maxFailuresPerAddress
10217
+ }
10218
+
10219
+ #countFailure(peer) {
10220
+ peer.authFailures = (peer.authFailures ?? 0) + 1;
10221
+ const entry = this.#addressEntry(peer.ip);
10222
+ if (!entry) return
10223
+ if (entry.fresh) {
10224
+ delete entry.fresh;
10225
+ // Bounded: forget windows that have passed before adding another address.
10226
+ if (this.addressFailures.size >= 10000) {
10227
+ const now = Date.now();
10228
+ for (const [ip, e] of this.addressFailures) if (now - e.since >= serverOption.auth.failureWindowMs) this.addressFailures.delete(ip);
10229
+ if (this.addressFailures.size >= 10000) this.addressFailures.clear();
10230
+ }
10231
+ this.addressFailures.set(peer.ip, entry);
10232
+ }
10233
+ entry.count++;
10234
+ }
10235
+
10236
+ // countFailure: a wrong ID or key (not a refusal of a valid key, such as a duplicate login).
10237
+ send_auth_fail(peer, reason, countFailure = false) {
10028
10238
  if (peer._closing || peer.state === STATE.CLOSED) return;
10029
10239
  peer.boho.isAuthorized = false;
10240
+ if (countFailure) this.#countFailure(peer);
10241
+ const lastTry = countFailure && peer.authFailures >= serverOption.auth.maxFailuresPerConnection;
10030
10242
  if (this.authLogger) {
10031
10243
  let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
10032
10244
  this.authLogger.log(peerInfo);
@@ -10037,11 +10249,24 @@ class BohoAuth {
10037
10249
  setTimeout(e => {
10038
10250
  if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
10039
10251
  peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
10252
+ // Too many wrong logins on this connection: it has to connect again to go on.
10253
+ if (lastTry) peer.close();
10040
10254
  }
10041
10255
  }, serverOption.auth.failDelay);
10042
10256
  }
10043
10257
 
10044
10258
 
10259
+ // The login could not be checked (key store unreachable): not an answer about the key. The
10260
+ // connection is closed, so the client connects and logs in again, instead of AUTH_FAIL, which
10261
+ // clients take as "wrong key" and do not retry.
10262
+ close_unavailable(peer, reason) {
10263
+ if (peer._closing || peer.state === STATE.CLOSED) return;
10264
+ console.error('BohoAuth: login not checked, closing the connection:', reason);
10265
+ if (this.authLogger) this.authLogger.log(`UNAVAILABLE #${peer.ssid} reason:${reason} `);
10266
+ peer.boho.isAuthorized = false;
10267
+ peer.close();
10268
+ }
10269
+
10045
10270
  /**
10046
10271
  * Hook for a subclass: decide where a verified login belongs before it is accepted.
10047
10272
  * Called after the key and role checks, before quotas and the duplicate login check.
@@ -10090,11 +10315,23 @@ class BohoAuth {
10090
10315
  id = decoder.decode(infoPack.id8);
10091
10316
  }
10092
10317
 
10318
+ // Too many wrong logins from this address: not checked until its window has passed.
10319
+ if (this.addressBlocked(peer.ip)) {
10320
+ this.close_unavailable(peer, 'too many wrong logins from ' + peer.ip);
10321
+ return
10322
+ }
10323
+
10093
10324
  //2. get key of id from DB
10094
- let authInfo = await this.keyProvider.getAuth(id);
10325
+ let authInfo;
10326
+ try {
10327
+ authInfo = await this.keyProvider.getAuth(id);
10328
+ } catch (error) {
10329
+ this.close_unavailable(peer, 'key provider: ' + (error?.message ?? error));
10330
+ return
10331
+ }
10095
10332
  if (!peer.checkAuthChallenge()) return;
10096
10333
  if (!authInfo) {
10097
- this.send_auth_fail(peer, 'NO ID:' + id);
10334
+ this.send_auth_fail(peer, 'NO ID:' + id, true);
10098
10335
  return
10099
10336
  }
10100
10337
 
@@ -10119,7 +10356,7 @@ class BohoAuth {
10119
10356
  //3. check hmac
10120
10357
  let auth_res = peer.boho.verify_auth_req(infoPack);
10121
10358
  if (!auth_res) {
10122
- this.send_auth_fail(peer, 'hmac dismatched');
10359
+ this.send_auth_fail(peer, 'hmac dismatched', true);
10123
10360
  return
10124
10361
  }
10125
10362
 
@@ -10143,7 +10380,13 @@ class BohoAuth {
10143
10380
  peer.close();
10144
10381
  return
10145
10382
  }
10146
- const quotaName = await this.resolveQuota(authInfo, role);
10383
+ let quotaName;
10384
+ try {
10385
+ quotaName = await this.resolveQuota(authInfo, role);
10386
+ } catch (error) {
10387
+ this.close_unavailable(peer, 'quota: ' + (error?.message ?? error));
10388
+ return
10389
+ }
10147
10390
  const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
10148
10391
  if (!quota) {
10149
10392
  this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
@@ -10198,9 +10441,19 @@ class BohoAuth {
10198
10441
  }
10199
10442
 
10200
10443
  //6. delete current (or anonymouse)cid if exist.
10201
- if (peer.cid) {
10202
- // console.log('if peer has cid', peer.cid)
10203
- peer.manager.cid2remote.delete(peer.cid);
10444
+ if (peer.cid && peer.cid !== authInfo.cid) {
10445
+ // Subscribers of the CID it had (an anonymous one, before login()) are told it is gone, as when
10446
+ // a connection closes. Sent to them only: nothing is retained under the new CID.
10447
+ const manager = peer.manager;
10448
+ for (const topic of ['@state', '@$state']) {
10449
+ const tag = peer.cid + topic;
10450
+ manager.deliver(manager.CID_PREFIX + tag, getSignalPack(tag, 'close'), null);
10451
+ }
10452
+ // What it retained carries the old CID in its tag: dropped, the device publishes again when ready.
10453
+ for (const message of peer.retain_signal.values()) manager.retainBytes -= message.byteLength;
10454
+ peer.retain_signal.clear();
10455
+ peer.retainBytes = 0;
10456
+ manager.cid2remote.delete(peer.cid);
10204
10457
  }
10205
10458
 
10206
10459
  //7. setting info.
@@ -11073,7 +11326,7 @@ function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
11073
11326
  }
11074
11327
  const positive = (name, value) => integer(name, value, 1);
11075
11328
  const nonNegative = (name, value) => integer(name, value, 0);
11076
- const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
11329
+ const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections', 'maxSubscriptions'];
11077
11330
 
11078
11331
  // This Server's quota profiles: the defaults with each given profile merged over its default
11079
11332
  // (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
@@ -11138,13 +11391,13 @@ class Server extends require$$0$3 {
11138
11391
  * loopback/private peer, true always, false never, or N trusted proxy hops.
11139
11392
  * options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
11140
11393
  * options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
11141
- * options.membersOnly: drop signals from connections that are not authenticated.
11394
+ * options.membersOnly: only authenticated connections may send signals or subscribe.
11142
11395
  * options.logMessages: log each received message after decryption: type and tag, never the payload.
11143
11396
  * options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
11144
- * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
11397
+ * options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries, requireEncryption }.
11145
11398
  * options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
11146
11399
  * options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
11147
- * maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
11400
+ * maxConnections, maxSubscriptions } }, merged over serverOption.quotas; always enforced, null is unlimited.
11148
11401
  * Adjustable later on server.quotas. The client is told its maxMessageBytes.
11149
11402
  * options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
11150
11403
  * options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
@@ -11165,7 +11418,7 @@ class Server extends require$$0$3 {
11165
11418
  // never written, so servers in one process do not affect each other.
11166
11419
  checkRemoved(options);
11167
11420
  this.security = Object.freeze(group('security', options.security,
11168
- { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
11421
+ { maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive, requireEncryption: boolean }));
11169
11422
  // retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
11170
11423
  this.retain = group('retain', options.retain, {
11171
11424
  enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
@@ -11483,7 +11736,6 @@ class FileKeyProvider {
11483
11736
  //loaded when server start.
11484
11737
  loadAuthInfoFile_JS(path) {
11485
11738
  import(path).then((file) => {
11486
- console.log(file.authInfo);
11487
11739
  file.authInfo.forEach(item => {
11488
11740
  this.addAuth(...item);
11489
11741
  });
@@ -11513,6 +11765,7 @@ class FileKeyProvider {
11513
11765
 
11514
11766
  // Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
11515
11767
  addAuth(id, keyStr, cid, role, quota) {
11768
+ checkLoginId(id);
11516
11769
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11517
11770
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11518
11771
  }
@@ -11532,14 +11785,12 @@ class RedisKeyProvider {
11532
11785
  }
11533
11786
 
11534
11787
  // get device key from DB. (for Boho auth.)
11788
+ // null: no such device. A Redis failure throws, so BohoAuth closes the connection (the client
11789
+ // connects again) instead of answering AUTH_FAIL as if the ID were unknown.
11535
11790
  async getAuth(id) {
11536
- try {
11537
- let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11538
- if (result && result.key) return result
11539
- else return null;
11540
- } catch (error) {
11541
- console.log('getAuth', error);
11542
- }
11791
+ let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
11792
+ if (result && result.key) return result
11793
+ else return null;
11543
11794
  }
11544
11795
 
11545
11796
  //sudoService call
@@ -11550,13 +11801,18 @@ class RedisKeyProvider {
11550
11801
 
11551
11802
  // Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
11552
11803
  // Falls back to KEYS for a client without scan, or a redis-service from before 2026-11-17 that refuses it
11553
- // (RemoteRedisClient answers a refused command with undefined).
11804
+ // (RemoteRedisClient throws on a refused command; an undefined reply is treated the same).
11554
11805
  async scanKeys(pattern) {
11555
11806
  if (typeof this.redis.scan === 'function') {
11556
11807
  const keys = new Set(); // SCAN may return a key more than once
11557
11808
  let cursor = '0';
11558
11809
  do {
11559
- const reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11810
+ let reply;
11811
+ try {
11812
+ reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11813
+ } catch {
11814
+ break
11815
+ }
11560
11816
  if (!reply || !Array.isArray(reply.keys)) break
11561
11817
  for (const key of reply.keys) keys.add(key);
11562
11818
  cursor = String(reply.cursor);
@@ -11569,6 +11825,7 @@ class RedisKeyProvider {
11569
11825
  // add device auth info
11570
11826
  // role and quota are optional (see StringKeyProvider); an omitted one is not stored.
11571
11827
  async addAuth(id, keyStr, cid = '', role, quota) {
11828
+ checkLoginId(id);
11572
11829
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11573
11830
  const fields = { 'key': Base64hashKey, 'cid': cid };
11574
11831
  if (role) fields.role = role;
@@ -11637,6 +11894,7 @@ class StringKeyProvider {
11637
11894
  }
11638
11895
 
11639
11896
  addAuth(id, keyStr, cid, role, quota) {
11897
+ checkLoginId(id);
11640
11898
  let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
11641
11899
  this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
11642
11900
  }
@@ -11850,6 +12108,7 @@ exports.STATE = STATE;
11850
12108
  exports.STATUS = STATUS$1;
11851
12109
  exports.Server = Server;
11852
12110
  exports.StringKeyProvider = StringKeyProvider;
12111
+ exports.checkLoginId = checkLoginId;
11853
12112
  exports.defaultQuota = defaultQuota;
11854
12113
  exports.delay = delay;
11855
12114
  exports.getIPv4HexString = getIPv4HexString;