iosignal 9.14.0 → 9.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +17 -3
- package/README.md +26 -3
- package/dist/browser/esm/io.d.ts +23 -0
- package/dist/browser/esm/io.js +3 -3
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +3 -3
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +360 -53
- package/dist/node/iosignal.d.cts +69 -5
- package/dist/node/iosignal.d.ts +69 -5
- package/dist/node/iosignal.js +360 -54
- package/dist/types/client/IOCore.d.ts +23 -0
- package/dist/types/common/constants.d.ts +10 -0
- package/package.json +1 -1
package/dist/node/iosignal.cjs
CHANGED
|
@@ -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.
|
|
26
|
+
var version$1 = "9.21.0";
|
|
27
27
|
var pkg = {
|
|
28
28
|
version: version$1};
|
|
29
29
|
|
|
@@ -449,6 +449,11 @@ 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
|
|
456
|
+
* @property {number} SERVER_HELLO_TIMEOUT
|
|
452
457
|
* @property {number} PROMISE_TIMEOUT
|
|
453
458
|
* @property {number} DID
|
|
454
459
|
* @property {number} CID
|
|
@@ -458,6 +463,20 @@ const SIZE_LIMIT = {
|
|
|
458
463
|
TAG_LEN2: 65535,
|
|
459
464
|
CONNECTION_CHECKER_PERIOD: 3000,
|
|
460
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,
|
|
477
|
+
// From starting a connection to the server's hello (SERVER_TIME_NONCE). A connection that hangs
|
|
478
|
+
// longer is closed, so the client reconnects to its own URL (after a redirect: the original one).
|
|
479
|
+
SERVER_HELLO_TIMEOUT: 15000,
|
|
461
480
|
PROMISE_TIMEOUT: 5000,
|
|
462
481
|
DID: 8,
|
|
463
482
|
CID: 12
|
|
@@ -775,6 +794,14 @@ function sendSubscription(io, tag) {
|
|
|
775
794
|
]));
|
|
776
795
|
}
|
|
777
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
|
+
|
|
778
805
|
function byteToUrl(buffer) {
|
|
779
806
|
//ipv4(4bytes) , port(2bytes)
|
|
780
807
|
if (buffer.byteLength != 6) return
|
|
@@ -852,6 +879,16 @@ class IOCore extends EventEmitter {
|
|
|
852
879
|
* @type {number}
|
|
853
880
|
*/
|
|
854
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;
|
|
855
892
|
/**
|
|
856
893
|
* Period for connection checker.
|
|
857
894
|
* @type {number}
|
|
@@ -966,6 +1003,8 @@ class IOCore extends EventEmitter {
|
|
|
966
1003
|
*/
|
|
967
1004
|
close() {
|
|
968
1005
|
// console.log('####### IOCOre.js close() called')
|
|
1006
|
+
this.clearHelloTimer();
|
|
1007
|
+
this._pingSentAt = 0;
|
|
969
1008
|
// If auto-reconnect is disabled, we must stop the keep-alive timer.
|
|
970
1009
|
if (this.autoReconnect === false) {
|
|
971
1010
|
clearInterval(this.connectionCheckerIntervalID);
|
|
@@ -973,6 +1012,7 @@ class IOCore extends EventEmitter {
|
|
|
973
1012
|
}
|
|
974
1013
|
if (this._closed) return;
|
|
975
1014
|
this._closed = true;
|
|
1015
|
+
this.scheduleReconnect();
|
|
976
1016
|
|
|
977
1017
|
// socket clean
|
|
978
1018
|
if (this.socket) {
|
|
@@ -1046,12 +1086,37 @@ class IOCore extends EventEmitter {
|
|
|
1046
1086
|
* is implemented keepConnection() in the child classes (IOWS, IOCongSocket, etc.).
|
|
1047
1087
|
*/
|
|
1048
1088
|
keepAlive() {
|
|
1049
|
-
this.keepConnection();
|
|
1050
|
-
if(
|
|
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) {
|
|
1051
1102
|
this.ping();
|
|
1052
1103
|
}
|
|
1053
1104
|
}
|
|
1054
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
|
+
|
|
1055
1120
|
/**
|
|
1056
1121
|
* Redirects the connection to a new URL.
|
|
1057
1122
|
* @param {string} url2 - The new URL to redirect to.
|
|
@@ -1060,6 +1125,30 @@ class IOCore extends EventEmitter {
|
|
|
1060
1125
|
this.stateChange('redirecting','redirecting');
|
|
1061
1126
|
this.close();
|
|
1062
1127
|
this.createConnection(url2);
|
|
1128
|
+
this.armHelloTimer();
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/**
|
|
1132
|
+
* Closes a connection that has not got the server's hello in SIZE_LIMIT.SERVER_HELLO_TIMEOUT
|
|
1133
|
+
* (a server that cannot be reached, or a connection that opens but never answers). With
|
|
1134
|
+
* autoReconnect the client then reconnects to this.url, so a failed redirect falls back to the
|
|
1135
|
+
* original server, as the Arduino library does.
|
|
1136
|
+
*/
|
|
1137
|
+
armHelloTimer() {
|
|
1138
|
+
this.clearHelloTimer();
|
|
1139
|
+
if (this._closed || !this.socket) return;
|
|
1140
|
+
const socket = this.socket;
|
|
1141
|
+
this.helloTimerID = setTimeout(() => {
|
|
1142
|
+
this.helloTimerID = null;
|
|
1143
|
+
if (this.socket !== socket) return;
|
|
1144
|
+
this.emit('error', new Error('no reply from the server in ' + SIZE_LIMIT.SERVER_HELLO_TIMEOUT / 1000 + ' s'));
|
|
1145
|
+
this.close();
|
|
1146
|
+
}, SIZE_LIMIT.SERVER_HELLO_TIMEOUT);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
clearHelloTimer() {
|
|
1150
|
+
if (this.helloTimerID) clearTimeout(this.helloTimerID);
|
|
1151
|
+
this.helloTimerID = null;
|
|
1063
1152
|
}
|
|
1064
1153
|
|
|
1065
1154
|
/**
|
|
@@ -1085,6 +1174,7 @@ class IOCore extends EventEmitter {
|
|
|
1085
1174
|
// The actual connection is created here.
|
|
1086
1175
|
this.createConnection(this.url);
|
|
1087
1176
|
if (this._closed) return; // A connecting listener may have stopped the client.
|
|
1177
|
+
this.armHelloTimer();
|
|
1088
1178
|
|
|
1089
1179
|
// Ensure the keep-alive timer is running.
|
|
1090
1180
|
if (!this.connectionCheckerIntervalID) {
|
|
@@ -1097,6 +1187,8 @@ class IOCore extends EventEmitter {
|
|
|
1097
1187
|
*/
|
|
1098
1188
|
onOpen() {
|
|
1099
1189
|
this._closed = false;
|
|
1190
|
+
this.lastRxTime = Date.now();
|
|
1191
|
+
this._pingSentAt = 0;
|
|
1100
1192
|
if (this.url.includes("wss://")) {
|
|
1101
1193
|
this.TLS = true;
|
|
1102
1194
|
} else {
|
|
@@ -1123,6 +1215,8 @@ class IOCore extends EventEmitter {
|
|
|
1123
1215
|
this.auth(id, key);
|
|
1124
1216
|
this.useAuth = true;
|
|
1125
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
|
|
1126
1220
|
this.send(auth_pack);
|
|
1127
1221
|
this.stateChange('auth_req', 'auth_req');
|
|
1128
1222
|
}
|
|
@@ -1136,17 +1230,21 @@ class IOCore extends EventEmitter {
|
|
|
1136
1230
|
* @returns {this}
|
|
1137
1231
|
*/
|
|
1138
1232
|
auth(id, key) {
|
|
1139
|
-
if (
|
|
1140
|
-
|
|
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
|
|
1141
1237
|
}
|
|
1142
|
-
|
|
1143
|
-
|
|
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) {
|
|
1144
1244
|
this.boho.set_id_key(id);
|
|
1145
|
-
} else
|
|
1245
|
+
} else {
|
|
1146
1246
|
this.boho.set_id8(id);
|
|
1147
1247
|
this.boho.set_key(key);
|
|
1148
|
-
} else {
|
|
1149
|
-
this.emit('error', new Error('auth failed. no id or key.'));
|
|
1150
1248
|
}
|
|
1151
1249
|
this.useAuth = true;
|
|
1152
1250
|
return this
|
|
@@ -1157,6 +1255,8 @@ class IOCore extends EventEmitter {
|
|
|
1157
1255
|
* @param {Buffer} buffer - The incoming data buffer.
|
|
1158
1256
|
*/
|
|
1159
1257
|
onData(buffer) {
|
|
1258
|
+
this.lastRxTime = Date.now();
|
|
1259
|
+
this._pingSentAt = 0;
|
|
1160
1260
|
let msgType = buffer[0];
|
|
1161
1261
|
let decoded;
|
|
1162
1262
|
|
|
@@ -1165,6 +1265,9 @@ class IOCore extends EventEmitter {
|
|
|
1165
1265
|
if (decoded) {
|
|
1166
1266
|
msgType = decoded[0];
|
|
1167
1267
|
buffer = decoded;
|
|
1268
|
+
} else {
|
|
1269
|
+
// Not from this session (or damaged): dropped, never passed on as a text message.
|
|
1270
|
+
return
|
|
1168
1271
|
}
|
|
1169
1272
|
} else if (msgType === it.BohoMsg.ENC_E2E) {
|
|
1170
1273
|
|
|
@@ -1238,6 +1341,7 @@ class IOCore extends EventEmitter {
|
|
|
1238
1341
|
// State first (subscribe_channels needs READY), then the stored subscriptions, and only then
|
|
1239
1342
|
// 'ready': a signal sent from a ready handler reaches the server after our own subscriptions.
|
|
1240
1343
|
// stateChange() without a message emits 'change' only; false means a handler moved the state on.
|
|
1344
|
+
this._reconnectAttempts = 0;
|
|
1241
1345
|
if (!this.stateChange('ready')) break;
|
|
1242
1346
|
this.subscribe_channels();
|
|
1243
1347
|
this._readyDispatch = true;
|
|
@@ -1279,6 +1383,7 @@ class IOCore extends EventEmitter {
|
|
|
1279
1383
|
break;
|
|
1280
1384
|
|
|
1281
1385
|
case it.BohoMsg.SERVER_TIME_NONCE: // SERVER_READY
|
|
1386
|
+
this.clearHelloTimer();
|
|
1282
1387
|
buffer.copy(this.serverTimeNonce);
|
|
1283
1388
|
if (!this.stateChange('server_ready', 'server_ready')) break;
|
|
1284
1389
|
if (this.useAuth) {
|
|
@@ -1296,7 +1401,7 @@ class IOCore extends EventEmitter {
|
|
|
1296
1401
|
let str = decoder$4.decode(buffer.subarray(1));
|
|
1297
1402
|
let ss = JSON.parse(str);
|
|
1298
1403
|
|
|
1299
|
-
if (ss.event && ss.data) {
|
|
1404
|
+
if (typeof ss.event === 'string' && ss.event && ss.data && !INTERNAL_EVENTS.has(ss.event)) {
|
|
1300
1405
|
this.serverSet = ss.data;
|
|
1301
1406
|
this.emit(ss.event, ss.data);
|
|
1302
1407
|
}
|
|
@@ -1309,8 +1414,8 @@ class IOCore extends EventEmitter {
|
|
|
1309
1414
|
case IOMsg.SET:
|
|
1310
1415
|
try {
|
|
1311
1416
|
let setPack = $$1.unpack(buffer);
|
|
1312
|
-
if (setPack) {
|
|
1313
|
-
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 ?? []));
|
|
1314
1419
|
}
|
|
1315
1420
|
} catch (error) {
|
|
1316
1421
|
this.emit('error', new Error('SET parsing error'));
|
|
@@ -1338,7 +1443,8 @@ class IOCore extends EventEmitter {
|
|
|
1338
1443
|
this.emit('@', tag, ...args);
|
|
1339
1444
|
if (tag !== '@') this.emit(tag, tag, ...args);
|
|
1340
1445
|
} else {
|
|
1341
|
-
|
|
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);
|
|
1342
1448
|
this.emit('message', tag, ...args);
|
|
1343
1449
|
}
|
|
1344
1450
|
}
|
|
@@ -1405,6 +1511,8 @@ class IOCore extends EventEmitter {
|
|
|
1405
1511
|
* Sends a PING message to the server.
|
|
1406
1512
|
*/
|
|
1407
1513
|
ping() {
|
|
1514
|
+
// Any message from the server answers it (see keepAlive()).
|
|
1515
|
+
if (!this._pingSentAt && this.isLinkUp()) this._pingSentAt = Date.now();
|
|
1408
1516
|
this.send(Buffer$1.from([IOMsg.PING]));
|
|
1409
1517
|
}
|
|
1410
1518
|
|
|
@@ -2162,8 +2270,15 @@ class IOCongSocket extends IOCore {
|
|
|
2162
2270
|
|
|
2163
2271
|
createConnection(url) {
|
|
2164
2272
|
// TCP Socket
|
|
2165
|
-
|
|
2166
|
-
|
|
2273
|
+
// 'host:port', 'ip:port' or 'cong://host:port'. 'ip:port' alone is not a URL (a scheme cannot
|
|
2274
|
+
// start with a digit), and 'host:port' parses with 'host:' as its scheme.
|
|
2275
|
+
let urlObj;
|
|
2276
|
+
try {
|
|
2277
|
+
urlObj = new URL(url);
|
|
2278
|
+
} catch {
|
|
2279
|
+
urlObj = null;
|
|
2280
|
+
}
|
|
2281
|
+
if (urlObj?.protocol != "cong:") {
|
|
2167
2282
|
urlObj = new URL('cong://' + url);
|
|
2168
2283
|
}
|
|
2169
2284
|
// URL keeps the brackets of an IPv6 literal ('[::1]'); net expects the bare address.
|
|
@@ -7362,7 +7477,8 @@ const serverOption = {
|
|
|
7362
7477
|
// A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
|
|
7363
7478
|
// letting its send queue grow without limit.
|
|
7364
7479
|
maxBufferedBytes: 64 * 1024 * 1024,
|
|
7365
|
-
//
|
|
7480
|
+
// Only authenticated connections may send signals or subscribe; an anonymous one that tries
|
|
7481
|
+
// gets AUTH_CLEAR and is closed.
|
|
7366
7482
|
membersOnly: false,
|
|
7367
7483
|
// Observability. logMessages: log each received message (type and tag, never the payload).
|
|
7368
7484
|
// logStats: print a one-line summary every N ms (0 = off).
|
|
@@ -7374,7 +7490,11 @@ const serverOption = {
|
|
|
7374
7490
|
security: {
|
|
7375
7491
|
maxClockSkewMs: 60000,
|
|
7376
7492
|
authChallengeMaxAgeMs: 60000,
|
|
7377
|
-
maxReplayEntries: 65536
|
|
7493
|
+
maxReplayEntries: 65536,
|
|
7494
|
+
// true: a logged-in connection without TLS must send its signals, subscriptions and calls
|
|
7495
|
+
// encrypted (as clients do in ENC_MODE.AUTO); a plain one closes it (PLAINTEXT_AFTER_LOGIN).
|
|
7496
|
+
// Off by default: a client with encMode NO would be closed.
|
|
7497
|
+
requireEncryption: false
|
|
7378
7498
|
},
|
|
7379
7499
|
// Named quota profiles. A connection uses one: an anonymous connection the Server's
|
|
7380
7500
|
// anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
|
|
@@ -7384,11 +7504,12 @@ const serverOption = {
|
|
|
7384
7504
|
// fanout: most subscribers one channel publish is delivered to
|
|
7385
7505
|
// msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
|
|
7386
7506
|
// maxConnections: connections of one account (uid) at a time; over: the login fails
|
|
7507
|
+
// maxSubscriptions: tags one connection may be subscribed to at a time; over: the tag is left out
|
|
7387
7508
|
quotas: {
|
|
7388
|
-
anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null },
|
|
7389
|
-
basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20 },
|
|
7390
|
-
pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200 },
|
|
7391
|
-
unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null }
|
|
7509
|
+
anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null, maxSubscriptions: 1000 },
|
|
7510
|
+
basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20, maxSubscriptions: 2000 },
|
|
7511
|
+
pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200, maxSubscriptions: 10000 },
|
|
7512
|
+
unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null, maxSubscriptions: null }
|
|
7392
7513
|
},
|
|
7393
7514
|
anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
|
|
7394
7515
|
|
|
@@ -7428,6 +7549,13 @@ const serverOption = {
|
|
|
7428
7549
|
|
|
7429
7550
|
auth: {
|
|
7430
7551
|
failDelay: 600, // ms before AUTH_FAIL is sent
|
|
7552
|
+
// Wrong logins: a connection is closed after maxFailuresPerConnection; a public address with
|
|
7553
|
+
// maxFailuresPerAddress in failureWindowMs gets its next logins closed unchecked until the window
|
|
7554
|
+
// has passed (closed, not AUTH_FAIL, so a device with the right key there connects again).
|
|
7555
|
+
// Loopback and private addresses are not counted (a proxy, a LAN, tests).
|
|
7556
|
+
maxFailuresPerConnection: 5,
|
|
7557
|
+
maxFailuresPerAddress: 30,
|
|
7558
|
+
failureWindowMs: 60000,
|
|
7431
7559
|
// Default for BohoAuth, when the same authenticated CID is already online:
|
|
7432
7560
|
// 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
|
|
7433
7561
|
// Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
|
|
@@ -7445,6 +7573,11 @@ const serverOption = {
|
|
|
7445
7573
|
|
|
7446
7574
|
const decoder$3 = new TextDecoder();
|
|
7447
7575
|
|
|
7576
|
+
// With security.requireEncryption, what a logged-in connection without TLS may not send in plain.
|
|
7577
|
+
// PING, PONG, CID_REQ, ECHO and CLOSE carry nothing and stay plain, as clients send them.
|
|
7578
|
+
const PLAINTEXT_REFUSED = new Set([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.SUBSCRIBE_REQ,
|
|
7579
|
+
IOMsg.UNSUBSCRIBE, IOMsg.CALL, IOMsg.IAM]);
|
|
7580
|
+
|
|
7448
7581
|
$$1.NB;
|
|
7449
7582
|
const MB = $$1.MB;
|
|
7450
7583
|
|
|
@@ -7483,6 +7616,7 @@ class RemoteCore {
|
|
|
7483
7616
|
this.security = manager.server.security;
|
|
7484
7617
|
this._challengeIssuedAt = null;
|
|
7485
7618
|
this._challengeUsed = false;
|
|
7619
|
+
this.authFailures = 0; // failed logins on this connection (BohoAuth)
|
|
7486
7620
|
this._replayBuckets = new Map();
|
|
7487
7621
|
this._replayEntries = 0;
|
|
7488
7622
|
this._replayExpiredBefore = 0;
|
|
@@ -7754,6 +7888,11 @@ class RemoteCore {
|
|
|
7754
7888
|
}
|
|
7755
7889
|
|
|
7756
7890
|
} else ;
|
|
7891
|
+
if (!encrypted && this.security.requireEncryption && this.boho.isAuthorized && !this.TLS &&
|
|
7892
|
+
PLAINTEXT_REFUSED.has(msgType)) {
|
|
7893
|
+
this.securityMismatch('PLAINTEXT_AFTER_LOGIN');
|
|
7894
|
+
return;
|
|
7895
|
+
}
|
|
7757
7896
|
if (logMessages) this.logMessage(msgType, message, encrypted);
|
|
7758
7897
|
|
|
7759
7898
|
switch (msgType) {
|
|
@@ -7867,8 +8006,10 @@ class RemoteCore {
|
|
|
7867
8006
|
tag = decoder$3.decode(tag);
|
|
7868
8007
|
let tagList = tag.split(',');
|
|
7869
8008
|
// console.log('>> SUBSCRIBE_REQ from:', this.cid, tagList)
|
|
7870
|
-
this.
|
|
7871
|
-
this.
|
|
8009
|
+
const rejected = this.subscriptionsRejected ?? 0;
|
|
8010
|
+
if (this.manager.subscribe(tagList, this) === false) return
|
|
8011
|
+
// 255: some tags were over the quota's maxSubscriptions and were not subscribed.
|
|
8012
|
+
this.response(msgID, (this.subscriptionsRejected ?? 0) > rejected ? 255 : 0);
|
|
7872
8013
|
} else {
|
|
7873
8014
|
this.response(msgID, 255);
|
|
7874
8015
|
}
|
|
@@ -7903,7 +8044,11 @@ class RemoteCore {
|
|
|
7903
8044
|
|
|
7904
8045
|
// client's auth requst
|
|
7905
8046
|
case it.BohoMsg.AUTH_REQ:
|
|
7906
|
-
|
|
8047
|
+
// No login on this server: say so, or the client would wait in auth_req forever.
|
|
8048
|
+
if (!this.manager.authManager) {
|
|
8049
|
+
this.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
8050
|
+
return
|
|
8051
|
+
}
|
|
7907
8052
|
// A second request while verification is pending must not restart auth.
|
|
7908
8053
|
if (this.state === STATE.AUTH_REQ) {
|
|
7909
8054
|
this.securityMismatch('AUTH_IN_PROGRESS');
|
|
@@ -8115,6 +8260,15 @@ function getLocalAddress() {
|
|
|
8115
8260
|
}
|
|
8116
8261
|
|
|
8117
8262
|
|
|
8263
|
+
// A login ID travels as 8 bytes (Boho id8): a longer one would be cut and could never match, or
|
|
8264
|
+
// match another entry. Key providers refuse it when it is added.
|
|
8265
|
+
function checkLoginId(id) {
|
|
8266
|
+
if (typeof id !== 'string' || !id || new TextEncoder().encode(id).byteLength > 8) {
|
|
8267
|
+
throw new RangeError(`login ID must be 1-8 bytes: ${typeof id === 'string' ? id : typeof id}`)
|
|
8268
|
+
}
|
|
8269
|
+
return id
|
|
8270
|
+
}
|
|
8271
|
+
|
|
8118
8272
|
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
8119
8273
|
|
|
8120
8274
|
const decoder$2 = new TextDecoder();
|
|
@@ -9118,6 +9272,7 @@ class Manager {
|
|
|
9118
9272
|
this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
|
|
9119
9273
|
publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
|
|
9120
9274
|
peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
|
|
9275
|
+
subscriptionsRejected: 0, // subscriptions over a connection's quota maxSubscriptions, left out
|
|
9121
9276
|
policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
|
|
9122
9277
|
hostInbound: 0, // client signals handed to a host (server.host)
|
|
9123
9278
|
hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
|
|
@@ -9664,7 +9819,16 @@ class Manager {
|
|
|
9664
9819
|
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
9665
9820
|
}
|
|
9666
9821
|
|
|
9822
|
+
// Returns false when nothing was subscribed (membersOnly), else the connection's subscription count.
|
|
9823
|
+
// Tags over the quota's maxSubscriptions are left out and counted in subscriptionsRejected.
|
|
9667
9824
|
subscribe(chArr, remote) {
|
|
9825
|
+
// Reading is closed to anonymous connections like sending (sender): same answer.
|
|
9826
|
+
if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
|
|
9827
|
+
remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
|
|
9828
|
+
remote.close();
|
|
9829
|
+
return false
|
|
9830
|
+
}
|
|
9831
|
+
const maxSubscriptions = remote.quota?.maxSubscriptions ?? null;
|
|
9668
9832
|
chArr.forEach(tag => {
|
|
9669
9833
|
if (tag.indexOf('#') === 0) {
|
|
9670
9834
|
tag = remote.HOME_CHANNEL + tag;
|
|
@@ -9674,6 +9838,12 @@ class Manager {
|
|
|
9674
9838
|
tag = this.CHANNEL_PREFIX + tag;
|
|
9675
9839
|
}
|
|
9676
9840
|
|
|
9841
|
+
if (maxSubscriptions !== null && remote.channels.size >= maxSubscriptions && !remote.channels.has(tag)) {
|
|
9842
|
+
this.counters.subscriptionsRejected++;
|
|
9843
|
+
remote.subscriptionsRejected = (remote.subscriptionsRejected ?? 0) + 1;
|
|
9844
|
+
return
|
|
9845
|
+
}
|
|
9846
|
+
|
|
9677
9847
|
// 1. set channel map
|
|
9678
9848
|
if (this.channel_map.has(tag)) {
|
|
9679
9849
|
this.channel_map.get(tag).add(remote);
|
|
@@ -9946,6 +10116,7 @@ class BohoAuth {
|
|
|
9946
10116
|
if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
|
|
9947
10117
|
this.onAuthEvent = options.onAuthEvent ?? null;
|
|
9948
10118
|
this.resolveQuota = options.resolveQuota ?? defaultQuota;
|
|
10119
|
+
this.addressFailures = new Map(); // public address -> { count, since } of wrong logins
|
|
9949
10120
|
this.authLogger;
|
|
9950
10121
|
if (serverOption.fileLogger.auth.use) {
|
|
9951
10122
|
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
@@ -9986,9 +10157,46 @@ class BohoAuth {
|
|
|
9986
10157
|
}
|
|
9987
10158
|
}
|
|
9988
10159
|
|
|
9989
|
-
|
|
10160
|
+
// Wrong logins of a public address in the current window (see serverOption.auth).
|
|
10161
|
+
#addressEntry(ip, now = Date.now()) {
|
|
10162
|
+
if (typeof ip !== 'string' || !ip || isPrivateIP(ip)) return null
|
|
10163
|
+
let entry = this.addressFailures.get(ip);
|
|
10164
|
+
if (entry && now - entry.since >= serverOption.auth.failureWindowMs) {
|
|
10165
|
+
this.addressFailures.delete(ip);
|
|
10166
|
+
entry = undefined;
|
|
10167
|
+
}
|
|
10168
|
+
return entry ?? { count: 0, since: now, fresh: true }
|
|
10169
|
+
}
|
|
10170
|
+
|
|
10171
|
+
/** True while this address has too many wrong logins: its logins are closed without a check. */
|
|
10172
|
+
addressBlocked(ip) {
|
|
10173
|
+
const entry = this.#addressEntry(ip);
|
|
10174
|
+
return !!entry && entry.count >= serverOption.auth.maxFailuresPerAddress
|
|
10175
|
+
}
|
|
10176
|
+
|
|
10177
|
+
#countFailure(peer) {
|
|
10178
|
+
peer.authFailures = (peer.authFailures ?? 0) + 1;
|
|
10179
|
+
const entry = this.#addressEntry(peer.ip);
|
|
10180
|
+
if (!entry) return
|
|
10181
|
+
if (entry.fresh) {
|
|
10182
|
+
delete entry.fresh;
|
|
10183
|
+
// Bounded: forget windows that have passed before adding another address.
|
|
10184
|
+
if (this.addressFailures.size >= 10000) {
|
|
10185
|
+
const now = Date.now();
|
|
10186
|
+
for (const [ip, e] of this.addressFailures) if (now - e.since >= serverOption.auth.failureWindowMs) this.addressFailures.delete(ip);
|
|
10187
|
+
if (this.addressFailures.size >= 10000) this.addressFailures.clear();
|
|
10188
|
+
}
|
|
10189
|
+
this.addressFailures.set(peer.ip, entry);
|
|
10190
|
+
}
|
|
10191
|
+
entry.count++;
|
|
10192
|
+
}
|
|
10193
|
+
|
|
10194
|
+
// countFailure: a wrong ID or key (not a refusal of a valid key, such as a duplicate login).
|
|
10195
|
+
send_auth_fail(peer, reason, countFailure = false) {
|
|
9990
10196
|
if (peer._closing || peer.state === STATE.CLOSED) return;
|
|
9991
10197
|
peer.boho.isAuthorized = false;
|
|
10198
|
+
if (countFailure) this.#countFailure(peer);
|
|
10199
|
+
const lastTry = countFailure && peer.authFailures >= serverOption.auth.maxFailuresPerConnection;
|
|
9992
10200
|
if (this.authLogger) {
|
|
9993
10201
|
let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
|
|
9994
10202
|
this.authLogger.log(peerInfo);
|
|
@@ -9999,11 +10207,50 @@ class BohoAuth {
|
|
|
9999
10207
|
setTimeout(e => {
|
|
10000
10208
|
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
10001
10209
|
peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
10210
|
+
// Too many wrong logins on this connection: it has to connect again to go on.
|
|
10211
|
+
if (lastTry) peer.close();
|
|
10002
10212
|
}
|
|
10003
10213
|
}, serverOption.auth.failDelay);
|
|
10004
10214
|
}
|
|
10005
10215
|
|
|
10006
10216
|
|
|
10217
|
+
// The login could not be checked (key store unreachable): not an answer about the key. The
|
|
10218
|
+
// connection is closed, so the client connects and logs in again, instead of AUTH_FAIL, which
|
|
10219
|
+
// clients take as "wrong key" and do not retry.
|
|
10220
|
+
close_unavailable(peer, reason) {
|
|
10221
|
+
if (peer._closing || peer.state === STATE.CLOSED) return;
|
|
10222
|
+
console.error('BohoAuth: login not checked, closing the connection:', reason);
|
|
10223
|
+
if (this.authLogger) this.authLogger.log(`UNAVAILABLE #${peer.ssid} reason:${reason} `);
|
|
10224
|
+
peer.boho.isAuthorized = false;
|
|
10225
|
+
peer.close();
|
|
10226
|
+
}
|
|
10227
|
+
|
|
10228
|
+
/**
|
|
10229
|
+
* Hook for a subclass: decide where a verified login belongs before it is accepted.
|
|
10230
|
+
* Called after the key and role checks, before quotas and the duplicate login check.
|
|
10231
|
+
* Return null to accept the login here, or a message (e.g. SERVER_REDIRECT) that is sent to the
|
|
10232
|
+
* client instead of AUTH_RES before the connection is closed. The default accepts every login.
|
|
10233
|
+
* @param {object} peer the connection
|
|
10234
|
+
* @param {object} authInfo the key provider's entry for the login ID (cid, uid, role, quota, ...)
|
|
10235
|
+
* @param {string} role resolved role
|
|
10236
|
+
* @param {string} id login ID
|
|
10237
|
+
* @returns {Promise<Uint8Array | null> | Uint8Array | null}
|
|
10238
|
+
*/
|
|
10239
|
+
beforeAccept(peer, authInfo, role, id) {
|
|
10240
|
+
return null
|
|
10241
|
+
}
|
|
10242
|
+
|
|
10243
|
+
// An error in the hook accepts the login: placement must never lock clients out.
|
|
10244
|
+
async #beforeAcceptSafe(peer, authInfo, role, id) {
|
|
10245
|
+
try {
|
|
10246
|
+
const result = await this.beforeAccept(peer, authInfo, role, id);
|
|
10247
|
+
return result instanceof Uint8Array && result.byteLength > 0 ? result : null
|
|
10248
|
+
} catch (error) {
|
|
10249
|
+
console.error('BohoAuth.beforeAccept error:', error);
|
|
10250
|
+
return null
|
|
10251
|
+
}
|
|
10252
|
+
}
|
|
10253
|
+
|
|
10007
10254
|
async verify_auth_req(auth_req, peer) {
|
|
10008
10255
|
try {
|
|
10009
10256
|
if (!peer.checkAuthChallenge()) return;
|
|
@@ -10026,11 +10273,23 @@ class BohoAuth {
|
|
|
10026
10273
|
id = decoder.decode(infoPack.id8);
|
|
10027
10274
|
}
|
|
10028
10275
|
|
|
10276
|
+
// Too many wrong logins from this address: not checked until its window has passed.
|
|
10277
|
+
if (this.addressBlocked(peer.ip)) {
|
|
10278
|
+
this.close_unavailable(peer, 'too many wrong logins from ' + peer.ip);
|
|
10279
|
+
return
|
|
10280
|
+
}
|
|
10281
|
+
|
|
10029
10282
|
//2. get key of id from DB
|
|
10030
|
-
let authInfo
|
|
10283
|
+
let authInfo;
|
|
10284
|
+
try {
|
|
10285
|
+
authInfo = await this.keyProvider.getAuth(id);
|
|
10286
|
+
} catch (error) {
|
|
10287
|
+
this.close_unavailable(peer, 'key provider: ' + (error?.message ?? error));
|
|
10288
|
+
return
|
|
10289
|
+
}
|
|
10031
10290
|
if (!peer.checkAuthChallenge()) return;
|
|
10032
10291
|
if (!authInfo) {
|
|
10033
|
-
this.send_auth_fail(peer, 'NO ID:' + id);
|
|
10292
|
+
this.send_auth_fail(peer, 'NO ID:' + id, true);
|
|
10034
10293
|
return
|
|
10035
10294
|
}
|
|
10036
10295
|
|
|
@@ -10055,7 +10314,7 @@ class BohoAuth {
|
|
|
10055
10314
|
//3. check hmac
|
|
10056
10315
|
let auth_res = peer.boho.verify_auth_req(infoPack);
|
|
10057
10316
|
if (!auth_res) {
|
|
10058
|
-
this.send_auth_fail(peer, 'hmac dismatched');
|
|
10317
|
+
this.send_auth_fail(peer, 'hmac dismatched', true);
|
|
10059
10318
|
return
|
|
10060
10319
|
}
|
|
10061
10320
|
|
|
@@ -10069,7 +10328,23 @@ class BohoAuth {
|
|
|
10069
10328
|
this.send_auth_fail(peer, 'unknown auth.role: ' + authInfo.role);
|
|
10070
10329
|
return
|
|
10071
10330
|
}
|
|
10072
|
-
|
|
10331
|
+
// A login another server should take (beforeAccept) goes there before it is counted here or
|
|
10332
|
+
// replaces a connection here.
|
|
10333
|
+
const redirect = await this.#beforeAcceptSafe(peer, authInfo, role, id);
|
|
10334
|
+
if (peer._closing) return; // closed while deciding
|
|
10335
|
+
if (redirect) {
|
|
10336
|
+
peer.boho.isAuthorized = false;
|
|
10337
|
+
peer.send(redirect);
|
|
10338
|
+
peer.close();
|
|
10339
|
+
return
|
|
10340
|
+
}
|
|
10341
|
+
let quotaName;
|
|
10342
|
+
try {
|
|
10343
|
+
quotaName = await this.resolveQuota(authInfo, role);
|
|
10344
|
+
} catch (error) {
|
|
10345
|
+
this.close_unavailable(peer, 'quota: ' + (error?.message ?? error));
|
|
10346
|
+
return
|
|
10347
|
+
}
|
|
10073
10348
|
const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
|
|
10074
10349
|
if (!quota) {
|
|
10075
10350
|
this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
|
|
@@ -10124,9 +10399,19 @@ class BohoAuth {
|
|
|
10124
10399
|
}
|
|
10125
10400
|
|
|
10126
10401
|
//6. delete current (or anonymouse)cid if exist.
|
|
10127
|
-
if (peer.cid) {
|
|
10128
|
-
//
|
|
10129
|
-
|
|
10402
|
+
if (peer.cid && peer.cid !== authInfo.cid) {
|
|
10403
|
+
// Subscribers of the CID it had (an anonymous one, before login()) are told it is gone, as when
|
|
10404
|
+
// a connection closes. Sent to them only: nothing is retained under the new CID.
|
|
10405
|
+
const manager = peer.manager;
|
|
10406
|
+
for (const topic of ['@state', '@$state']) {
|
|
10407
|
+
const tag = peer.cid + topic;
|
|
10408
|
+
manager.deliver(manager.CID_PREFIX + tag, getSignalPack(tag, 'close'), null);
|
|
10409
|
+
}
|
|
10410
|
+
// What it retained carries the old CID in its tag: dropped, the device publishes again when ready.
|
|
10411
|
+
for (const message of peer.retain_signal.values()) manager.retainBytes -= message.byteLength;
|
|
10412
|
+
peer.retain_signal.clear();
|
|
10413
|
+
peer.retainBytes = 0;
|
|
10414
|
+
manager.cid2remote.delete(peer.cid);
|
|
10130
10415
|
}
|
|
10131
10416
|
|
|
10132
10417
|
//7. setting info.
|
|
@@ -10999,7 +11284,7 @@ function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
|
10999
11284
|
}
|
|
11000
11285
|
const positive = (name, value) => integer(name, value, 1);
|
|
11001
11286
|
const nonNegative = (name, value) => integer(name, value, 0);
|
|
11002
|
-
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
|
|
11287
|
+
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections', 'maxSubscriptions'];
|
|
11003
11288
|
|
|
11004
11289
|
// This Server's quota profiles: the defaults with each given profile merged over its default
|
|
11005
11290
|
// (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
|
|
@@ -11064,13 +11349,13 @@ class Server extends require$$0$3 {
|
|
|
11064
11349
|
* loopback/private peer, true always, false never, or N trusted proxy hops.
|
|
11065
11350
|
* options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
|
|
11066
11351
|
* options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
|
|
11067
|
-
* options.membersOnly:
|
|
11352
|
+
* options.membersOnly: only authenticated connections may send signals or subscribe.
|
|
11068
11353
|
* options.logMessages: log each received message after decryption: type and tag, never the payload.
|
|
11069
11354
|
* options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
|
|
11070
|
-
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
|
|
11355
|
+
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries, requireEncryption }.
|
|
11071
11356
|
* options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
|
|
11072
11357
|
* options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
|
|
11073
|
-
* maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
11358
|
+
* maxConnections, maxSubscriptions } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
11074
11359
|
* Adjustable later on server.quotas. The client is told its maxMessageBytes.
|
|
11075
11360
|
* options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
|
|
11076
11361
|
* options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
|
|
@@ -11091,7 +11376,7 @@ class Server extends require$$0$3 {
|
|
|
11091
11376
|
// never written, so servers in one process do not affect each other.
|
|
11092
11377
|
checkRemoved(options);
|
|
11093
11378
|
this.security = Object.freeze(group('security', options.security,
|
|
11094
|
-
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
|
|
11379
|
+
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive, requireEncryption: boolean }));
|
|
11095
11380
|
// retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
|
|
11096
11381
|
this.retain = group('retain', options.retain, {
|
|
11097
11382
|
enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
|
|
@@ -11409,7 +11694,6 @@ class FileKeyProvider {
|
|
|
11409
11694
|
//loaded when server start.
|
|
11410
11695
|
loadAuthInfoFile_JS(path) {
|
|
11411
11696
|
import(path).then((file) => {
|
|
11412
|
-
console.log(file.authInfo);
|
|
11413
11697
|
file.authInfo.forEach(item => {
|
|
11414
11698
|
this.addAuth(...item);
|
|
11415
11699
|
});
|
|
@@ -11439,6 +11723,7 @@ class FileKeyProvider {
|
|
|
11439
11723
|
|
|
11440
11724
|
// Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
|
|
11441
11725
|
addAuth(id, keyStr, cid, role, quota) {
|
|
11726
|
+
checkLoginId(id);
|
|
11442
11727
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
11443
11728
|
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
11444
11729
|
}
|
|
@@ -11458,28 +11743,47 @@ class RedisKeyProvider {
|
|
|
11458
11743
|
}
|
|
11459
11744
|
|
|
11460
11745
|
// get device key from DB. (for Boho auth.)
|
|
11746
|
+
// null: no such device. A Redis failure throws, so BohoAuth closes the connection (the client
|
|
11747
|
+
// connects again) instead of answering AUTH_FAIL as if the ID were unknown.
|
|
11461
11748
|
async getAuth(id) {
|
|
11462
|
-
|
|
11463
|
-
|
|
11464
|
-
|
|
11465
|
-
else return null;
|
|
11466
|
-
} catch (error) {
|
|
11467
|
-
console.log('getAuth', error);
|
|
11468
|
-
}
|
|
11749
|
+
let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
|
|
11750
|
+
if (result && result.key) return result
|
|
11751
|
+
else return null;
|
|
11469
11752
|
}
|
|
11470
11753
|
|
|
11471
11754
|
//sudoService call
|
|
11472
11755
|
async getAuthIdList() {
|
|
11473
|
-
|
|
11474
|
-
|
|
11475
|
-
|
|
11476
|
-
|
|
11477
|
-
|
|
11756
|
+
const keys = await this.scanKeys(DEVICE_PREFIX + '*');
|
|
11757
|
+
return keys.map(key => key.slice(DEVICE_PREFIX.length))
|
|
11758
|
+
}
|
|
11759
|
+
|
|
11760
|
+
// Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
|
|
11761
|
+
// Falls back to KEYS for a client without scan, or a redis-service from before 2026-11-17 that refuses it
|
|
11762
|
+
// (RemoteRedisClient throws on a refused command; an undefined reply is treated the same).
|
|
11763
|
+
async scanKeys(pattern) {
|
|
11764
|
+
if (typeof this.redis.scan === 'function') {
|
|
11765
|
+
const keys = new Set(); // SCAN may return a key more than once
|
|
11766
|
+
let cursor = '0';
|
|
11767
|
+
do {
|
|
11768
|
+
let reply;
|
|
11769
|
+
try {
|
|
11770
|
+
reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
|
|
11771
|
+
} catch {
|
|
11772
|
+
break
|
|
11773
|
+
}
|
|
11774
|
+
if (!reply || !Array.isArray(reply.keys)) break
|
|
11775
|
+
for (const key of reply.keys) keys.add(key);
|
|
11776
|
+
cursor = String(reply.cursor);
|
|
11777
|
+
if (cursor === '0') return [...keys]
|
|
11778
|
+
} while (true)
|
|
11779
|
+
}
|
|
11780
|
+
return (await this.redis.keys(pattern)) ?? []
|
|
11478
11781
|
}
|
|
11479
11782
|
|
|
11480
11783
|
// add device auth info
|
|
11481
11784
|
// role and quota are optional (see StringKeyProvider); an omitted one is not stored.
|
|
11482
11785
|
async addAuth(id, keyStr, cid = '', role, quota) {
|
|
11786
|
+
checkLoginId(id);
|
|
11483
11787
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
11484
11788
|
const fields = { 'key': Base64hashKey, 'cid': cid };
|
|
11485
11789
|
if (role) fields.role = role;
|
|
@@ -11548,6 +11852,7 @@ class StringKeyProvider {
|
|
|
11548
11852
|
}
|
|
11549
11853
|
|
|
11550
11854
|
addAuth(id, keyStr, cid, role, quota) {
|
|
11855
|
+
checkLoginId(id);
|
|
11551
11856
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
11552
11857
|
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
11553
11858
|
}
|
|
@@ -11692,12 +11997,13 @@ var sudoService = /*#__PURE__*/Object.freeze({
|
|
|
11692
11997
|
*
|
|
11693
11998
|
*/
|
|
11694
11999
|
|
|
12000
|
+
// KEYS stays for older clients; new ones list keys with SCAN (RedisKeyProvider.scanKeys).
|
|
11695
12001
|
const COMMANDS = [
|
|
11696
12002
|
'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
|
|
11697
|
-
'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
|
|
12003
|
+
'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SCAN', 'SAVE',
|
|
11698
12004
|
'LPUSH', 'LTRIM', 'LRANGE', 'LINDEX', 'LSET', 'EXPIRE',
|
|
11699
12005
|
'get', 'set', 'hGetAll', 'hGet', 'hSet', 'sAdd', 'sIsMember',
|
|
11700
|
-
'sMembers', 'exists', 'sRem', 'del', 'keys', 'save',
|
|
12006
|
+
'sMembers', 'exists', 'sRem', 'del', 'keys', 'scan', 'save',
|
|
11701
12007
|
'lPush', 'lTrim', 'lRange', 'lIndex', 'lSet', 'expire'
|
|
11702
12008
|
];
|
|
11703
12009
|
|
|
@@ -11760,6 +12066,7 @@ exports.STATE = STATE;
|
|
|
11760
12066
|
exports.STATUS = STATUS$1;
|
|
11761
12067
|
exports.Server = Server;
|
|
11762
12068
|
exports.StringKeyProvider = StringKeyProvider;
|
|
12069
|
+
exports.checkLoginId = checkLoginId;
|
|
11763
12070
|
exports.defaultQuota = defaultQuota;
|
|
11764
12071
|
exports.delay = delay;
|
|
11765
12072
|
exports.getIPv4HexString = getIPv4HexString;
|