iosignal 9.19.0 → 9.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +16 -2
- package/README.md +25 -2
- package/dist/browser/esm/io.d.ts +14 -0
- package/dist/browser/esm/io.js +4 -4
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +4 -4
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +263 -46
- package/dist/node/iosignal.d.cts +44 -5
- package/dist/node/iosignal.d.ts +44 -5
- package/dist/node/iosignal.js +263 -47
- package/dist/types/client/IOCore.d.ts +14 -0
- package/dist/types/common/constants.d.ts +8 -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,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(
|
|
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 (
|
|
1170
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
|
@@ -7400,7 +7477,8 @@ const serverOption = {
|
|
|
7400
7477
|
// A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
|
|
7401
7478
|
// letting its send queue grow without limit.
|
|
7402
7479
|
maxBufferedBytes: 64 * 1024 * 1024,
|
|
7403
|
-
//
|
|
7480
|
+
// Only authenticated connections may send signals or subscribe; an anonymous one that tries
|
|
7481
|
+
// gets AUTH_CLEAR and is closed.
|
|
7404
7482
|
membersOnly: false,
|
|
7405
7483
|
// Observability. logMessages: log each received message (type and tag, never the payload).
|
|
7406
7484
|
// logStats: print a one-line summary every N ms (0 = off).
|
|
@@ -7412,7 +7490,11 @@ const serverOption = {
|
|
|
7412
7490
|
security: {
|
|
7413
7491
|
maxClockSkewMs: 60000,
|
|
7414
7492
|
authChallengeMaxAgeMs: 60000,
|
|
7415
|
-
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
|
|
7416
7498
|
},
|
|
7417
7499
|
// Named quota profiles. A connection uses one: an anonymous connection the Server's
|
|
7418
7500
|
// anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
|
|
@@ -7422,11 +7504,12 @@ const serverOption = {
|
|
|
7422
7504
|
// fanout: most subscribers one channel publish is delivered to
|
|
7423
7505
|
// msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
|
|
7424
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
|
|
7425
7508
|
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 }
|
|
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 }
|
|
7430
7513
|
},
|
|
7431
7514
|
anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
|
|
7432
7515
|
|
|
@@ -7466,6 +7549,13 @@ const serverOption = {
|
|
|
7466
7549
|
|
|
7467
7550
|
auth: {
|
|
7468
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,
|
|
7469
7559
|
// Default for BohoAuth, when the same authenticated CID is already online:
|
|
7470
7560
|
// 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
|
|
7471
7561
|
// Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
|
|
@@ -7483,6 +7573,11 @@ const serverOption = {
|
|
|
7483
7573
|
|
|
7484
7574
|
const decoder$3 = new TextDecoder();
|
|
7485
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
|
+
|
|
7486
7581
|
$$1.NB;
|
|
7487
7582
|
const MB = $$1.MB;
|
|
7488
7583
|
|
|
@@ -7521,6 +7616,7 @@ class RemoteCore {
|
|
|
7521
7616
|
this.security = manager.server.security;
|
|
7522
7617
|
this._challengeIssuedAt = null;
|
|
7523
7618
|
this._challengeUsed = false;
|
|
7619
|
+
this.authFailures = 0; // failed logins on this connection (BohoAuth)
|
|
7524
7620
|
this._replayBuckets = new Map();
|
|
7525
7621
|
this._replayEntries = 0;
|
|
7526
7622
|
this._replayExpiredBefore = 0;
|
|
@@ -7792,6 +7888,11 @@ class RemoteCore {
|
|
|
7792
7888
|
}
|
|
7793
7889
|
|
|
7794
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
|
+
}
|
|
7795
7896
|
if (logMessages) this.logMessage(msgType, message, encrypted);
|
|
7796
7897
|
|
|
7797
7898
|
switch (msgType) {
|
|
@@ -7905,8 +8006,10 @@ class RemoteCore {
|
|
|
7905
8006
|
tag = decoder$3.decode(tag);
|
|
7906
8007
|
let tagList = tag.split(',');
|
|
7907
8008
|
// console.log('>> SUBSCRIBE_REQ from:', this.cid, tagList)
|
|
7908
|
-
this.
|
|
7909
|
-
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);
|
|
7910
8013
|
} else {
|
|
7911
8014
|
this.response(msgID, 255);
|
|
7912
8015
|
}
|
|
@@ -7941,7 +8044,11 @@ class RemoteCore {
|
|
|
7941
8044
|
|
|
7942
8045
|
// client's auth requst
|
|
7943
8046
|
case it.BohoMsg.AUTH_REQ:
|
|
7944
|
-
|
|
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
|
+
}
|
|
7945
8052
|
// A second request while verification is pending must not restart auth.
|
|
7946
8053
|
if (this.state === STATE.AUTH_REQ) {
|
|
7947
8054
|
this.securityMismatch('AUTH_IN_PROGRESS');
|
|
@@ -8153,6 +8260,15 @@ function getLocalAddress() {
|
|
|
8153
8260
|
}
|
|
8154
8261
|
|
|
8155
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
|
+
|
|
8156
8272
|
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
8157
8273
|
|
|
8158
8274
|
const decoder$2 = new TextDecoder();
|
|
@@ -9156,6 +9272,7 @@ class Manager {
|
|
|
9156
9272
|
this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
|
|
9157
9273
|
publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
|
|
9158
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
|
|
9159
9276
|
policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
|
|
9160
9277
|
hostInbound: 0, // client signals handed to a host (server.host)
|
|
9161
9278
|
hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
|
|
@@ -9702,7 +9819,16 @@ class Manager {
|
|
|
9702
9819
|
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
9703
9820
|
}
|
|
9704
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.
|
|
9705
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;
|
|
9706
9832
|
chArr.forEach(tag => {
|
|
9707
9833
|
if (tag.indexOf('#') === 0) {
|
|
9708
9834
|
tag = remote.HOME_CHANNEL + tag;
|
|
@@ -9712,6 +9838,12 @@ class Manager {
|
|
|
9712
9838
|
tag = this.CHANNEL_PREFIX + tag;
|
|
9713
9839
|
}
|
|
9714
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
|
+
|
|
9715
9847
|
// 1. set channel map
|
|
9716
9848
|
if (this.channel_map.has(tag)) {
|
|
9717
9849
|
this.channel_map.get(tag).add(remote);
|
|
@@ -9984,6 +10116,7 @@ class BohoAuth {
|
|
|
9984
10116
|
if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
|
|
9985
10117
|
this.onAuthEvent = options.onAuthEvent ?? null;
|
|
9986
10118
|
this.resolveQuota = options.resolveQuota ?? defaultQuota;
|
|
10119
|
+
this.addressFailures = new Map(); // public address -> { count, since } of wrong logins
|
|
9987
10120
|
this.authLogger;
|
|
9988
10121
|
if (serverOption.fileLogger.auth.use) {
|
|
9989
10122
|
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
@@ -10024,9 +10157,46 @@ class BohoAuth {
|
|
|
10024
10157
|
}
|
|
10025
10158
|
}
|
|
10026
10159
|
|
|
10027
|
-
|
|
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) {
|
|
10028
10196
|
if (peer._closing || peer.state === STATE.CLOSED) return;
|
|
10029
10197
|
peer.boho.isAuthorized = false;
|
|
10198
|
+
if (countFailure) this.#countFailure(peer);
|
|
10199
|
+
const lastTry = countFailure && peer.authFailures >= serverOption.auth.maxFailuresPerConnection;
|
|
10030
10200
|
if (this.authLogger) {
|
|
10031
10201
|
let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
|
|
10032
10202
|
this.authLogger.log(peerInfo);
|
|
@@ -10037,11 +10207,24 @@ class BohoAuth {
|
|
|
10037
10207
|
setTimeout(e => {
|
|
10038
10208
|
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
10039
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();
|
|
10040
10212
|
}
|
|
10041
10213
|
}, serverOption.auth.failDelay);
|
|
10042
10214
|
}
|
|
10043
10215
|
|
|
10044
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
|
+
|
|
10045
10228
|
/**
|
|
10046
10229
|
* Hook for a subclass: decide where a verified login belongs before it is accepted.
|
|
10047
10230
|
* Called after the key and role checks, before quotas and the duplicate login check.
|
|
@@ -10090,11 +10273,23 @@ class BohoAuth {
|
|
|
10090
10273
|
id = decoder.decode(infoPack.id8);
|
|
10091
10274
|
}
|
|
10092
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
|
+
|
|
10093
10282
|
//2. get key of id from DB
|
|
10094
|
-
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
|
+
}
|
|
10095
10290
|
if (!peer.checkAuthChallenge()) return;
|
|
10096
10291
|
if (!authInfo) {
|
|
10097
|
-
this.send_auth_fail(peer, 'NO ID:' + id);
|
|
10292
|
+
this.send_auth_fail(peer, 'NO ID:' + id, true);
|
|
10098
10293
|
return
|
|
10099
10294
|
}
|
|
10100
10295
|
|
|
@@ -10119,7 +10314,7 @@ class BohoAuth {
|
|
|
10119
10314
|
//3. check hmac
|
|
10120
10315
|
let auth_res = peer.boho.verify_auth_req(infoPack);
|
|
10121
10316
|
if (!auth_res) {
|
|
10122
|
-
this.send_auth_fail(peer, 'hmac dismatched');
|
|
10317
|
+
this.send_auth_fail(peer, 'hmac dismatched', true);
|
|
10123
10318
|
return
|
|
10124
10319
|
}
|
|
10125
10320
|
|
|
@@ -10143,7 +10338,13 @@ class BohoAuth {
|
|
|
10143
10338
|
peer.close();
|
|
10144
10339
|
return
|
|
10145
10340
|
}
|
|
10146
|
-
|
|
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
|
+
}
|
|
10147
10348
|
const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
|
|
10148
10349
|
if (!quota) {
|
|
10149
10350
|
this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
|
|
@@ -10198,9 +10399,19 @@ class BohoAuth {
|
|
|
10198
10399
|
}
|
|
10199
10400
|
|
|
10200
10401
|
//6. delete current (or anonymouse)cid if exist.
|
|
10201
|
-
if (peer.cid) {
|
|
10202
|
-
//
|
|
10203
|
-
|
|
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);
|
|
10204
10415
|
}
|
|
10205
10416
|
|
|
10206
10417
|
//7. setting info.
|
|
@@ -11073,7 +11284,7 @@ function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
|
11073
11284
|
}
|
|
11074
11285
|
const positive = (name, value) => integer(name, value, 1);
|
|
11075
11286
|
const nonNegative = (name, value) => integer(name, value, 0);
|
|
11076
|
-
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
|
|
11287
|
+
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections', 'maxSubscriptions'];
|
|
11077
11288
|
|
|
11078
11289
|
// This Server's quota profiles: the defaults with each given profile merged over its default
|
|
11079
11290
|
// (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
|
|
@@ -11138,13 +11349,13 @@ class Server extends require$$0$3 {
|
|
|
11138
11349
|
* loopback/private peer, true always, false never, or N trusted proxy hops.
|
|
11139
11350
|
* options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
|
|
11140
11351
|
* options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
|
|
11141
|
-
* options.membersOnly:
|
|
11352
|
+
* options.membersOnly: only authenticated connections may send signals or subscribe.
|
|
11142
11353
|
* options.logMessages: log each received message after decryption: type and tag, never the payload.
|
|
11143
11354
|
* options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
|
|
11144
|
-
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
|
|
11355
|
+
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries, requireEncryption }.
|
|
11145
11356
|
* options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
|
|
11146
11357
|
* options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
|
|
11147
|
-
* maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
11358
|
+
* maxConnections, maxSubscriptions } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
11148
11359
|
* Adjustable later on server.quotas. The client is told its maxMessageBytes.
|
|
11149
11360
|
* options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
|
|
11150
11361
|
* options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
|
|
@@ -11165,7 +11376,7 @@ class Server extends require$$0$3 {
|
|
|
11165
11376
|
// never written, so servers in one process do not affect each other.
|
|
11166
11377
|
checkRemoved(options);
|
|
11167
11378
|
this.security = Object.freeze(group('security', options.security,
|
|
11168
|
-
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
|
|
11379
|
+
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive, requireEncryption: boolean }));
|
|
11169
11380
|
// retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
|
|
11170
11381
|
this.retain = group('retain', options.retain, {
|
|
11171
11382
|
enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
|
|
@@ -11483,7 +11694,6 @@ class FileKeyProvider {
|
|
|
11483
11694
|
//loaded when server start.
|
|
11484
11695
|
loadAuthInfoFile_JS(path) {
|
|
11485
11696
|
import(path).then((file) => {
|
|
11486
|
-
console.log(file.authInfo);
|
|
11487
11697
|
file.authInfo.forEach(item => {
|
|
11488
11698
|
this.addAuth(...item);
|
|
11489
11699
|
});
|
|
@@ -11513,6 +11723,7 @@ class FileKeyProvider {
|
|
|
11513
11723
|
|
|
11514
11724
|
// Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
|
|
11515
11725
|
addAuth(id, keyStr, cid, role, quota) {
|
|
11726
|
+
checkLoginId(id);
|
|
11516
11727
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
11517
11728
|
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
11518
11729
|
}
|
|
@@ -11532,14 +11743,12 @@ class RedisKeyProvider {
|
|
|
11532
11743
|
}
|
|
11533
11744
|
|
|
11534
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.
|
|
11535
11748
|
async getAuth(id) {
|
|
11536
|
-
|
|
11537
|
-
|
|
11538
|
-
|
|
11539
|
-
else return null;
|
|
11540
|
-
} catch (error) {
|
|
11541
|
-
console.log('getAuth', error);
|
|
11542
|
-
}
|
|
11749
|
+
let result = await this.redis.hGetAll(DEVICE_PREFIX + id);
|
|
11750
|
+
if (result && result.key) return result
|
|
11751
|
+
else return null;
|
|
11543
11752
|
}
|
|
11544
11753
|
|
|
11545
11754
|
//sudoService call
|
|
@@ -11550,13 +11759,18 @@ class RedisKeyProvider {
|
|
|
11550
11759
|
|
|
11551
11760
|
// Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
|
|
11552
11761
|
// Falls back to KEYS for a client without scan, or a redis-service from before 2026-11-17 that refuses it
|
|
11553
|
-
// (RemoteRedisClient
|
|
11762
|
+
// (RemoteRedisClient throws on a refused command; an undefined reply is treated the same).
|
|
11554
11763
|
async scanKeys(pattern) {
|
|
11555
11764
|
if (typeof this.redis.scan === 'function') {
|
|
11556
11765
|
const keys = new Set(); // SCAN may return a key more than once
|
|
11557
11766
|
let cursor = '0';
|
|
11558
11767
|
do {
|
|
11559
|
-
|
|
11768
|
+
let reply;
|
|
11769
|
+
try {
|
|
11770
|
+
reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
|
|
11771
|
+
} catch {
|
|
11772
|
+
break
|
|
11773
|
+
}
|
|
11560
11774
|
if (!reply || !Array.isArray(reply.keys)) break
|
|
11561
11775
|
for (const key of reply.keys) keys.add(key);
|
|
11562
11776
|
cursor = String(reply.cursor);
|
|
@@ -11569,6 +11783,7 @@ class RedisKeyProvider {
|
|
|
11569
11783
|
// add device auth info
|
|
11570
11784
|
// role and quota are optional (see StringKeyProvider); an omitted one is not stored.
|
|
11571
11785
|
async addAuth(id, keyStr, cid = '', role, quota) {
|
|
11786
|
+
checkLoginId(id);
|
|
11572
11787
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
11573
11788
|
const fields = { 'key': Base64hashKey, 'cid': cid };
|
|
11574
11789
|
if (role) fields.role = role;
|
|
@@ -11637,6 +11852,7 @@ class StringKeyProvider {
|
|
|
11637
11852
|
}
|
|
11638
11853
|
|
|
11639
11854
|
addAuth(id, keyStr, cid, role, quota) {
|
|
11855
|
+
checkLoginId(id);
|
|
11640
11856
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
11641
11857
|
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
11642
11858
|
}
|
|
@@ -11850,6 +12066,7 @@ exports.STATE = STATE;
|
|
|
11850
12066
|
exports.STATUS = STATUS$1;
|
|
11851
12067
|
exports.Server = Server;
|
|
11852
12068
|
exports.StringKeyProvider = StringKeyProvider;
|
|
12069
|
+
exports.checkLoginId = checkLoginId;
|
|
11853
12070
|
exports.defaultQuota = defaultQuota;
|
|
11854
12071
|
exports.delay = delay;
|
|
11855
12072
|
exports.getIPv4HexString = getIPv4HexString;
|