iosignal 8.0.0 → 9.0.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 +61 -0
- package/README.md +68 -0
- package/dist/browser/esm/io.d.ts +6 -8
- package/dist/browser/esm/io.js +5 -5
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +5 -5
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +992 -509
- package/dist/node/iosignal.d.cts +312 -114
- package/dist/node/iosignal.d.ts +312 -114
- package/dist/node/iosignal.js +989 -511
- package/dist/types/client/IOCore.d.ts +6 -9
- package/dist/types/common/constants.d.ts +2 -2
- package/package.json +2 -3
- package/dist/types/common/quotaTable.d.ts +0 -47
package/dist/node/iosignal.cjs
CHANGED
|
@@ -12,12 +12,13 @@ var require$$0$1 = require('zlib');
|
|
|
12
12
|
var require$$0$2 = require('buffer');
|
|
13
13
|
var require$$2 = require('util');
|
|
14
14
|
var node_perf_hooks = require('node:perf_hooks');
|
|
15
|
+
var node_net = require('node:net');
|
|
15
16
|
var os = require('os');
|
|
16
17
|
var fs = require('fs');
|
|
17
18
|
var process$1 = require('process');
|
|
18
19
|
var path = require('path');
|
|
19
20
|
|
|
20
|
-
var version$1 = "
|
|
21
|
+
var version$1 = "9.0.0";
|
|
21
22
|
var pkg = {
|
|
22
23
|
version: version$1};
|
|
23
24
|
|
|
@@ -482,7 +483,7 @@ for (let c in PAYLOAD_TYPE) { PAYLOAD_TYPE[PAYLOAD_TYPE[c]] = c; }
|
|
|
482
483
|
* @property {number} SERVER_READY
|
|
483
484
|
* @property {number} CID_REQ
|
|
484
485
|
* @property {number} CID_RES
|
|
485
|
-
* @property {number}
|
|
486
|
+
* @property {number} QUOTA
|
|
486
487
|
* @property {number} AUTH_CLEAR
|
|
487
488
|
* @property {number} SERVER_REDIRECT
|
|
488
489
|
* @property {number} LOOP
|
|
@@ -532,9 +533,10 @@ let IOMsg = {
|
|
|
532
533
|
SERVER_READY: 0xC0,
|
|
533
534
|
CID_REQ: 0xC1,
|
|
534
535
|
CID_RES: 0xC2,
|
|
535
|
-
QUOTA_LEVEL:
|
|
536
|
+
// 0xC3: QUOTA_LEVEL before 9.0. Not reused: older clients would read QUOTA as a quota level.
|
|
536
537
|
AUTH_CLEAR: 0xC4,
|
|
537
538
|
SERVER_REDIRECT: 0xC5,
|
|
539
|
+
QUOTA: 0xC6, // u32 LE maxMessageBytes of the connection (0: unlimited)
|
|
538
540
|
// ..
|
|
539
541
|
LOOP: 0xCB,
|
|
540
542
|
ECHO: 0xCC,
|
|
@@ -594,74 +596,6 @@ const STATUS$1 = {
|
|
|
594
596
|
ERROR: 255
|
|
595
597
|
};
|
|
596
598
|
|
|
597
|
-
// table index related with:
|
|
598
|
-
// - AUTH database level
|
|
599
|
-
// - serverOption.defaultQuotaIndex
|
|
600
|
-
|
|
601
|
-
// quota example
|
|
602
|
-
// index range: 0~255.
|
|
603
|
-
let quotaTable = {
|
|
604
|
-
// CongSocket
|
|
605
|
-
0: { // default. anonymouse:
|
|
606
|
-
signalSize: 1500,
|
|
607
|
-
publishCounter: 10,
|
|
608
|
-
trafficRate: 10000
|
|
609
|
-
},
|
|
610
|
-
1: { // auth_ultralight: eg. Arduino Uno.
|
|
611
|
-
signalSize: 255,
|
|
612
|
-
publishCounter: 10,
|
|
613
|
-
trafficRate: 100000
|
|
614
|
-
},
|
|
615
|
-
2: { // auth_light: eg. authorized ESP.
|
|
616
|
-
signalSize: 65535,
|
|
617
|
-
publishCounter: 10,
|
|
618
|
-
trafficRate: 1048576
|
|
619
|
-
},
|
|
620
|
-
|
|
621
|
-
// WebSocket (browser and node app)
|
|
622
|
-
3: { // authorized basic.
|
|
623
|
-
signalSize: 1048576,
|
|
624
|
-
publishCounter: 10,
|
|
625
|
-
trafficRate: 1048576 * 20
|
|
626
|
-
},
|
|
627
|
-
|
|
628
|
-
// WebSocket (browser and node app)
|
|
629
|
-
10: { // anonymouse
|
|
630
|
-
signalSize: 1500,
|
|
631
|
-
publishCounter: 5,
|
|
632
|
-
trafficRate: 1048576 * 20
|
|
633
|
-
},
|
|
634
|
-
|
|
635
|
-
11: { // authorized basic.
|
|
636
|
-
signalSize: 65535,
|
|
637
|
-
publishCounter: 10,
|
|
638
|
-
trafficRate: 1048576 * 20
|
|
639
|
-
},
|
|
640
|
-
|
|
641
|
-
12: { // authorized power.
|
|
642
|
-
signalSize: 1048576,
|
|
643
|
-
publishCounter: 100,
|
|
644
|
-
trafficRate: 1048576 * 20
|
|
645
|
-
},
|
|
646
|
-
|
|
647
|
-
// you can add your custom quota levels.
|
|
648
|
-
|
|
649
|
-
// Remote service node
|
|
650
|
-
// High Quota, No root permission.
|
|
651
|
-
200: {
|
|
652
|
-
signalSize: 1048576 * 20,
|
|
653
|
-
publishCounter: 10000,
|
|
654
|
-
trafficRate: 1048576 * 100
|
|
655
|
-
},
|
|
656
|
-
// super admin or root user.
|
|
657
|
-
// to monitor, metric, sudo command, db access.
|
|
658
|
-
255: {
|
|
659
|
-
signalSize: 1048576 * 20,
|
|
660
|
-
publishCounter: 10000,
|
|
661
|
-
trafficRate: 1048576 * 100
|
|
662
|
-
}
|
|
663
|
-
};
|
|
664
|
-
|
|
665
599
|
const encoder$2 = new TextEncoder();
|
|
666
600
|
|
|
667
601
|
|
|
@@ -766,7 +700,6 @@ const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1
|
|
|
766
700
|
* @typedef {import('../common/constants.js').SIZE_LIMIT} SIZE_LIMIT
|
|
767
701
|
* @typedef {import('../common/constants.js').ENC_MODE} ENC_MODE
|
|
768
702
|
* @typedef {import('../common/constants.js').STATE} STATE
|
|
769
|
-
* @typedef {import('../common/quotaTable.js').quotaTable} quotaTable
|
|
770
703
|
|
|
771
704
|
* @typedef {import('boho').Buffer} Buffer
|
|
772
705
|
*/
|
|
@@ -940,15 +873,11 @@ class IOCore extends EventEmitter {
|
|
|
940
873
|
this.mid = 0; // promise message id
|
|
941
874
|
|
|
942
875
|
/**
|
|
943
|
-
*
|
|
944
|
-
*
|
|
945
|
-
|
|
946
|
-
this.level = 3; // also defaultQuotaLevel
|
|
947
|
-
/**
|
|
948
|
-
* Quota table for current level.
|
|
949
|
-
* @type {object}
|
|
876
|
+
* This connection's quota as told by the server (QUOTA). maxMessageBytes: largest message
|
|
877
|
+
* send() passes on; null: no limit (also until the server tells).
|
|
878
|
+
* @type {{ maxMessageBytes: number | null }}
|
|
950
879
|
*/
|
|
951
|
-
this.quota =
|
|
880
|
+
this.quota = { maxMessageBytes: null };
|
|
952
881
|
/**
|
|
953
882
|
* Server settings.
|
|
954
883
|
* @type {object}
|
|
@@ -1269,12 +1198,12 @@ class IOCore extends EventEmitter {
|
|
|
1269
1198
|
this.subscribe_channels();
|
|
1270
1199
|
break;
|
|
1271
1200
|
|
|
1272
|
-
case IOMsg.
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
this.quota =
|
|
1276
|
-
// console.log('[QUOTA_LEVEL]', JSON.stringify(this.quota))
|
|
1201
|
+
case IOMsg.QUOTA: {
|
|
1202
|
+
if (buffer.byteLength < 5) break;
|
|
1203
|
+
const maxMessageBytes = (buffer[1] | buffer[2] << 8 | buffer[3] << 16) + buffer[4] * 0x1000000;
|
|
1204
|
+
this.quota = { maxMessageBytes: maxMessageBytes || null };
|
|
1277
1205
|
break;
|
|
1206
|
+
}
|
|
1278
1207
|
|
|
1279
1208
|
case IOMsg.AUTH_CLEAR:
|
|
1280
1209
|
this.useAuth = false;
|
|
@@ -1536,10 +1465,10 @@ class IOCore extends EventEmitter {
|
|
|
1536
1465
|
* @param {Buffer} data - The data buffer to send.
|
|
1537
1466
|
*/
|
|
1538
1467
|
send(data) {
|
|
1539
|
-
|
|
1468
|
+
const maxMessageBytes = this.quota.maxMessageBytes;
|
|
1469
|
+
if (maxMessageBytes !== null && data.byteLength > maxMessageBytes) {
|
|
1540
1470
|
this.emit('over_size');
|
|
1541
|
-
console.log(
|
|
1542
|
-
console.log('## your maximum signalSize(bytes) is:', this.quota.signalSize);
|
|
1471
|
+
console.log(`## quota: ${data.byteLength} bytes is over this connection's maxMessageBytes ${maxMessageBytes}`);
|
|
1543
1472
|
return
|
|
1544
1473
|
}
|
|
1545
1474
|
// console.log(`C->[${IOMsg[ data[0]]}]`)
|
|
@@ -2082,14 +2011,19 @@ function pack(payload) {
|
|
|
2082
2011
|
|
|
2083
2012
|
class CongRx extends require$$0.Transform {
|
|
2084
2013
|
/**
|
|
2085
|
-
* @param {import('stream').TransformOptions} [options] Stream options.
|
|
2014
|
+
* @param {import('stream').TransformOptions & { maxFrameSize?: number }} [options] Stream options.
|
|
2015
|
+
* maxFrameSize: largest payload to buffer (default unlimited). A larger frame is
|
|
2016
|
+
* skipped without buffering and reported by an 'oversize' event (payloadSize).
|
|
2086
2017
|
*/
|
|
2087
|
-
constructor(options) {
|
|
2088
|
-
|
|
2018
|
+
constructor(options = {}) {
|
|
2019
|
+
const { maxFrameSize = Infinity, ...streamOptions } = options;
|
|
2020
|
+
super(streamOptions);
|
|
2089
2021
|
this.buffer = Buffer.alloc(0);
|
|
2090
2022
|
this.frames = [];
|
|
2091
2023
|
this.rxi = 0;
|
|
2092
2024
|
this.rxi_zero = 0;
|
|
2025
|
+
this.maxFrameSize = maxFrameSize;
|
|
2026
|
+
this.skipBytes = 0; // remaining payload bytes of an oversized frame to discard
|
|
2093
2027
|
}
|
|
2094
2028
|
|
|
2095
2029
|
|
|
@@ -2116,6 +2050,15 @@ class CongRx extends require$$0.Transform {
|
|
|
2116
2050
|
}
|
|
2117
2051
|
}
|
|
2118
2052
|
|
|
2053
|
+
if (this.skipBytes > 0) {
|
|
2054
|
+
if (chunk.byteLength <= this.skipBytes) {
|
|
2055
|
+
this.skipBytes -= chunk.byteLength;
|
|
2056
|
+
return;
|
|
2057
|
+
}
|
|
2058
|
+
chunk = chunk.subarray(this.skipBytes);
|
|
2059
|
+
this.skipBytes = 0;
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2119
2062
|
if (this.buffer.byteLength > 0) {
|
|
2120
2063
|
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
2121
2064
|
} else {
|
|
@@ -2153,6 +2096,20 @@ class CongRx extends require$$0.Transform {
|
|
|
2153
2096
|
return;
|
|
2154
2097
|
}
|
|
2155
2098
|
|
|
2099
|
+
// Decide as soon as the length is known: the header can advertise up to 4 GiB.
|
|
2100
|
+
// Skipping keeps frame boundaries, so later frames still parse.
|
|
2101
|
+
if (payloadSize > this.maxFrameSize) {
|
|
2102
|
+
this.emit('oversize', payloadSize);
|
|
2103
|
+
const available = this.buffer.byteLength - headerLen;
|
|
2104
|
+
if (available < payloadSize) {
|
|
2105
|
+
this.skipBytes = payloadSize - available;
|
|
2106
|
+
this.buffer = Buffer.alloc(0);
|
|
2107
|
+
return;
|
|
2108
|
+
}
|
|
2109
|
+
this.buffer = this.buffer.subarray(headerLen + payloadSize);
|
|
2110
|
+
continue;
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2156
2113
|
const frameSize = headerLen + payloadSize;
|
|
2157
2114
|
if (this.buffer.byteLength < frameSize) return;
|
|
2158
2115
|
|
|
@@ -2209,7 +2166,9 @@ class IOCongSocket extends IOCore {
|
|
|
2209
2166
|
if (urlObj.protocol != "cong:") {
|
|
2210
2167
|
urlObj = new URL('cong://' + url);
|
|
2211
2168
|
}
|
|
2212
|
-
|
|
2169
|
+
// URL keeps the brackets of an IPv6 literal ('[::1]'); net expects the bare address.
|
|
2170
|
+
const host = urlObj.hostname.replace(/^\[(.*)\]$/, '$1');
|
|
2171
|
+
const socket = this.socket = net.createConnection(urlObj.port, host);
|
|
2213
2172
|
// Signals are small frames; send each immediately instead of waiting on Nagle.
|
|
2214
2173
|
socket.setNoDelay(true);
|
|
2215
2174
|
this._closed = false;
|
|
@@ -7383,18 +7342,75 @@ class IOWS extends IOCore {
|
|
|
7383
7342
|
|
|
7384
7343
|
}
|
|
7385
7344
|
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
|
|
7390
|
-
|
|
7391
|
-
|
|
7392
|
-
|
|
7393
|
-
|
|
7394
|
-
|
|
7395
|
-
|
|
7396
|
-
|
|
7397
|
-
|
|
7345
|
+
// Defaults, read when a Server is created; a Server never modifies them. Change one before
|
|
7346
|
+
// creating servers to change the default for all of them, or pass the setting to new Server().
|
|
7347
|
+
|
|
7348
|
+
const serverOption = {
|
|
7349
|
+
|
|
7350
|
+
// --- Per Server: each of these can be given to new Server({ ... }) ---
|
|
7351
|
+
|
|
7352
|
+
heartbeatInterval: 50000, // ms between liveness checks
|
|
7353
|
+
heartbeatGrace: 5000, // extra ms a peer has to answer before it is closed
|
|
7354
|
+
// Max bytes for a single WebSocket message and CongSocket frame. Bounds pre-auth memory use per
|
|
7355
|
+
// connection (ws defaults to 100 MiB); see Remote.rxFrameLimit().
|
|
7356
|
+
maxPayload: 32 * 1024 * 1024,
|
|
7357
|
+
// When to use X-Forwarded-For / X-Forwarded-Proto of a WebSocket request:
|
|
7358
|
+
// 'private' only if the connecting peer is a loopback/private address, e.g. a reverse proxy on
|
|
7359
|
+
// the same host or network; true always; false never; a number N trusts N proxy hops. The entry
|
|
7360
|
+
// appended by the last trusted proxy is used; earlier entries can be forged by the client.
|
|
7361
|
+
trustProxy: 'private',
|
|
7362
|
+
// A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
|
|
7363
|
+
// letting its send queue grow without limit.
|
|
7364
|
+
maxBufferedBytes: 64 * 1024 * 1024,
|
|
7365
|
+
// Drop signals from connections that are not authenticated.
|
|
7366
|
+
membersOnly: false,
|
|
7367
|
+
// Observability. logMessages: log each received message (type and tag, never the payload).
|
|
7368
|
+
// logStats: print a one-line summary every N ms (0 = off).
|
|
7369
|
+
logMessages: false,
|
|
7370
|
+
logStats: 0,
|
|
7371
|
+
|
|
7372
|
+
// Nested groups: a Server merges its own options over these.
|
|
7373
|
+
// Packet layouts remain unchanged.
|
|
7374
|
+
security: {
|
|
7375
|
+
maxClockSkewMs: 60000,
|
|
7376
|
+
authChallengeMaxAgeMs: 60000,
|
|
7377
|
+
maxReplayEntries: 65536
|
|
7378
|
+
},
|
|
7379
|
+
// Named quota profiles. A connection uses one: an anonymous connection the Server's
|
|
7380
|
+
// anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
|
|
7381
|
+
// resolveQuota). null is unlimited. A Server merges its quotas option over these per profile
|
|
7382
|
+
// and may add profiles; a running server's profiles can be adjusted (server.quotas.basic.fanout = 50).
|
|
7383
|
+
// maxMessageBytes: largest message the connection may send (larger: OVER_SIZE, dropped)
|
|
7384
|
+
// fanout: most subscribers one channel publish is delivered to
|
|
7385
|
+
// msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
|
|
7386
|
+
// maxConnections: connections of one account (uid) at a time; over: the login fails
|
|
7387
|
+
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 }
|
|
7392
|
+
},
|
|
7393
|
+
anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
|
|
7394
|
+
|
|
7395
|
+
retain: {
|
|
7396
|
+
enabled: true,
|
|
7397
|
+
limitSize: 100000, // a retained message must be smaller than this many bytes
|
|
7398
|
+
limitCounter: 1000, // channel retain tags per server, and CID retain tags per connection
|
|
7399
|
+
// A channel retain belongs to its last writer: an authenticated account (CID, shared by its
|
|
7400
|
+
// connections) or a live anonymous connection. Each owner holds at most tagsPerOwner tags and
|
|
7401
|
+
// bytesPerOwner bytes. An account's values stay until restart; a closed anonymous connection's
|
|
7402
|
+
// move to its network's grace pool (same budget) and are removed after anonymousGraceMs.
|
|
7403
|
+
tagsPerOwner: 32,
|
|
7404
|
+
bytesPerOwner: 1024 * 1024,
|
|
7405
|
+
anonymousGraceMs: 60 * 60 * 1000,
|
|
7406
|
+
// CID retains of one connection (removed with it), and all retained messages of the server.
|
|
7407
|
+
// A value over budget is not stored, and removes the value it would have replaced.
|
|
7408
|
+
bytesPerConnection: 1024 * 1024,
|
|
7409
|
+
bytesTotal: 256 * 1024 * 1024
|
|
7410
|
+
},
|
|
7411
|
+
|
|
7412
|
+
// --- Process-wide: read directly where used, not per Server ---
|
|
7413
|
+
|
|
7398
7414
|
fileLogger: {
|
|
7399
7415
|
connection: {
|
|
7400
7416
|
use: false,
|
|
@@ -7409,43 +7425,22 @@ let serverOption = {
|
|
|
7409
7425
|
path: 'attack.log'
|
|
7410
7426
|
}
|
|
7411
7427
|
},
|
|
7412
|
-
useQuota: {
|
|
7413
|
-
signalSize: false,
|
|
7414
|
-
publishCounter: false,
|
|
7415
|
-
trafficRate: false,
|
|
7416
|
-
disconnect: false
|
|
7417
|
-
},
|
|
7418
|
-
defaultQuotaIndex: 3,
|
|
7419
|
-
adminLevel: 255,
|
|
7420
|
-
|
|
7421
|
-
debug: {
|
|
7422
|
-
slow: false,
|
|
7423
|
-
delay: 500,
|
|
7424
|
-
showAuthInfo: false
|
|
7425
|
-
},
|
|
7426
|
-
|
|
7427
|
-
retain: {
|
|
7428
|
-
isAvailable: true,
|
|
7429
|
-
limitSize: 100000,
|
|
7430
|
-
limitCounter: 1000
|
|
7431
|
-
},
|
|
7432
|
-
|
|
7433
|
-
// Applied to each new Server instance; packet layouts remain unchanged.
|
|
7434
|
-
security: {
|
|
7435
|
-
maxClockSkewMs: 60000,
|
|
7436
|
-
authChallengeMaxAgeMs: 60000,
|
|
7437
|
-
maxReplayEntries: 65536
|
|
7438
|
-
},
|
|
7439
7428
|
|
|
7440
7429
|
auth: {
|
|
7441
|
-
|
|
7442
|
-
//
|
|
7443
|
-
// 'keepNew'
|
|
7444
|
-
// Override per
|
|
7430
|
+
failDelay: 600, // ms before AUTH_FAIL is sent
|
|
7431
|
+
// Default for BohoAuth, when the same authenticated CID is already online:
|
|
7432
|
+
// 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
|
|
7433
|
+
// Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
|
|
7434
|
+
// (which wins, and applies only to that Server's connections).
|
|
7445
7435
|
duplicateLogin: 'keepNew'
|
|
7446
7436
|
},
|
|
7447
|
-
membersOnly: false
|
|
7448
7437
|
|
|
7438
|
+
// Development aids.
|
|
7439
|
+
debug: {
|
|
7440
|
+
slow: false, // delay handling of every received message by `delay` ms
|
|
7441
|
+
delay: 500,
|
|
7442
|
+
showAuthInfo: false // log auth results and state traces (never keys)
|
|
7443
|
+
}
|
|
7449
7444
|
};
|
|
7450
7445
|
|
|
7451
7446
|
const decoder$3 = new TextDecoder();
|
|
@@ -7453,6 +7448,27 @@ const decoder$3 = new TextDecoder();
|
|
|
7453
7448
|
$$1.NB;
|
|
7454
7449
|
const MB = $$1.MB;
|
|
7455
7450
|
|
|
7451
|
+
// A one-byte CLOSE reason is a code, not text (Arduino IOSignal::close(uint8_t)): the message
|
|
7452
|
+
// that made the client close, or its CongPacket reader error state (ReadingState >= 250).
|
|
7453
|
+
// Its own table, because IOMsg gives 253 another meaning (TIME_OUT).
|
|
7454
|
+
const CLOSE_REASON = {
|
|
7455
|
+
[IOMsg.AUTH_CLEAR]: 'AUTH_CLEAR',
|
|
7456
|
+
[IOMsg.SERVER_REDIRECT]: 'SERVER_REDIRECT',
|
|
7457
|
+
253: 'CONG_UNKNOWN_TYPE',
|
|
7458
|
+
254: 'CONG_OVER_SIZE',
|
|
7459
|
+
255: 'CONG_OVER_FLOW'
|
|
7460
|
+
};
|
|
7461
|
+
|
|
7462
|
+
// Readable reason of a CLOSE message, e.g. 'AUTH_CLEAR(0xc4)'; longer reasons are text.
|
|
7463
|
+
function closeReason(message) {
|
|
7464
|
+
if (message.byteLength < 2) return 'none'
|
|
7465
|
+
if (message.byteLength === 2) {
|
|
7466
|
+
const code = '0x' + message[1].toString(16).padStart(2, '0');
|
|
7467
|
+
return CLOSE_REASON[message[1]] ? `${CLOSE_REASON[message[1]]}(${code})` : code
|
|
7468
|
+
}
|
|
7469
|
+
return decoder$3.decode(message.subarray(1))
|
|
7470
|
+
}
|
|
7471
|
+
|
|
7456
7472
|
|
|
7457
7473
|
class RemoteCore {
|
|
7458
7474
|
constructor(socket, manager) {
|
|
@@ -7471,9 +7487,11 @@ class RemoteCore {
|
|
|
7471
7487
|
this._replayEntries = 0;
|
|
7472
7488
|
this._replayExpiredBefore = 0;
|
|
7473
7489
|
this.securityFailure = null;
|
|
7490
|
+
this.closeReason = null; // reason of the client's CLOSE message, see closeReason()
|
|
7474
7491
|
this.encMode = ENC_MODE.AUTO;
|
|
7475
7492
|
this.channels = new Set(); // subscribed tags
|
|
7476
7493
|
this.retain_signal = new Map();
|
|
7494
|
+
this.retainBytes = 0; // bytes of its CID retains (retain_signal)
|
|
7477
7495
|
|
|
7478
7496
|
this.ssid = RemoteCore.ssid++; // ordered index number
|
|
7479
7497
|
this.manager = manager;
|
|
@@ -7485,9 +7503,18 @@ class RemoteCore {
|
|
|
7485
7503
|
|
|
7486
7504
|
this.privateNode = false;
|
|
7487
7505
|
this.HOME_CHANNEL = '';
|
|
7488
|
-
this.
|
|
7489
|
-
this.
|
|
7490
|
-
|
|
7506
|
+
this.role = 'anonymous'; // set on authentication; see ROLES in BohoAuth
|
|
7507
|
+
this.accountUid = null; // counted in manager.accountConnections while authenticated with a uid
|
|
7508
|
+
// Quota profile (a server.quotas entry, read live): the anonymous one until authenticated.
|
|
7509
|
+
this.quotaName = manager.anonymousQuota;
|
|
7510
|
+
this.quota = manager.quotas[this.quotaName];
|
|
7511
|
+
this._rateAt = null; // token buckets of quota msgPerSec / bytesPerSec
|
|
7512
|
+
this._msgTokens = 0;
|
|
7513
|
+
this._byteTokens = 0;
|
|
7514
|
+
// Largest message the peer can receive, if it said so in CID_REQ (e.g. an Arduino RX buffer);
|
|
7515
|
+
// larger messages are skipped instead of sent. null: no limit beyond maxPayload.
|
|
7516
|
+
this.peerRxLimit = null;
|
|
7517
|
+
this.peerRxLimitSkipped = 0;
|
|
7491
7518
|
|
|
7492
7519
|
this.state;
|
|
7493
7520
|
this.stateLog = [];
|
|
@@ -7497,6 +7524,11 @@ class RemoteCore {
|
|
|
7497
7524
|
|
|
7498
7525
|
static ssid = 1;
|
|
7499
7526
|
|
|
7527
|
+
/** Authenticated with role 'admin'. */
|
|
7528
|
+
get isAdmin() {
|
|
7529
|
+
return this.role === 'admin' && this.boho.isAuthorized === true;
|
|
7530
|
+
}
|
|
7531
|
+
|
|
7500
7532
|
setState(state) {
|
|
7501
7533
|
const previous = this.state;
|
|
7502
7534
|
this.state = state;
|
|
@@ -7520,43 +7552,79 @@ class RemoteCore {
|
|
|
7520
7552
|
}
|
|
7521
7553
|
|
|
7522
7554
|
|
|
7523
|
-
|
|
7524
|
-
|
|
7525
|
-
|
|
7526
|
-
|
|
7527
|
-
|
|
7528
|
-
|
|
7529
|
-
if (
|
|
7530
|
-
|
|
7531
|
-
|
|
7532
|
-
|
|
7533
|
-
if (
|
|
7534
|
-
|
|
7535
|
-
|
|
7536
|
-
let elseLen = size - prnLimit;
|
|
7537
|
-
let some = message.subarray(0,prnLimit);
|
|
7538
|
-
console.log( h + msgTypeName + from +` [${size}]` , some , ' ... else: ', elseLen);
|
|
7555
|
+
// logMessages: one line per received message after decryption: type, routing tag or RPC
|
|
7556
|
+
// target, and size. Payloads are never printed; heartbeat PING/PONG are skipped.
|
|
7557
|
+
logMessage(msgType, message, encrypted = false) {
|
|
7558
|
+
if (msgType === IOMsg.PING || msgType === IOMsg.PONG) return
|
|
7559
|
+
let detail = '';
|
|
7560
|
+
try {
|
|
7561
|
+
if ([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.UNSUBSCRIBE].includes(msgType)) {
|
|
7562
|
+
detail = decoder$3.decode(message.subarray(2, 2 + message[1]));
|
|
7563
|
+
} else if (msgType === IOMsg.SUBSCRIBE_REQ && message.byteLength >= 5) {
|
|
7564
|
+
detail = decoder$3.decode(message.subarray(5, 5 + message.readUInt16BE(3)));
|
|
7565
|
+
} else if (msgType === IOMsg.CALL) {
|
|
7566
|
+
const req = $$1.unpack(message);
|
|
7567
|
+
if (req) detail = `${req.target}.${req.topic}`;
|
|
7539
7568
|
}
|
|
7540
|
-
|
|
7569
|
+
} catch { /* a malformed message is logged without detail */ }
|
|
7570
|
+
const type = msgType === undefined ? 'TEXT'
|
|
7571
|
+
: IOMsg[msgType] ?? it.BohoMsg[msgType] ?? '0x' + msgType.toString(16);
|
|
7572
|
+
const transport = this.socketType === 'websocket' ? 'WS' : 'CS';
|
|
7573
|
+
console.log(`[rx] #${this.ssid} ${this.cid || '-'} ${transport} ${type}${encrypted ? '(enc)' : ''}` +
|
|
7574
|
+
`${detail ? ' ' + detail : ''} ${message.byteLength}B`);
|
|
7575
|
+
}
|
|
7576
|
+
|
|
7577
|
+
// Switches to a server.quotas profile; tell: send it to the client (QUOTA: its maxMessageBytes).
|
|
7578
|
+
setQuota(name, tell) {
|
|
7579
|
+
this.quotaName = name;
|
|
7580
|
+
this.quota = this.manager.quotas[name];
|
|
7581
|
+
// The CongSocket frame ceiling follows maxMessageBytes.
|
|
7582
|
+
this.refreshRxFrameLimit?.();
|
|
7583
|
+
if (tell) {
|
|
7584
|
+
const packet = Buffer.alloc(5);
|
|
7585
|
+
packet[0] = IOMsg.QUOTA;
|
|
7586
|
+
packet.writeUInt32LE(this.quota.maxMessageBytes ?? 0, 1); // 0: unlimited
|
|
7587
|
+
this.send(packet);
|
|
7588
|
+
}
|
|
7589
|
+
}
|
|
7590
|
+
|
|
7591
|
+
// Quota msgPerSec / bytesPerSec: token buckets holding one second. A message larger than the
|
|
7592
|
+
// byte bucket passes when the bucket is full and leaves a debt.
|
|
7593
|
+
takeRateTokens(bytes) {
|
|
7594
|
+
const { msgPerSec, bytesPerSec } = this.quota;
|
|
7595
|
+
if (msgPerSec === null && bytesPerSec === null) return true;
|
|
7596
|
+
const now = node_perf_hooks.performance.now();
|
|
7597
|
+
if (this._rateAt === null) {
|
|
7598
|
+
this._msgTokens = msgPerSec ?? 0;
|
|
7599
|
+
this._byteTokens = bytesPerSec ?? 0;
|
|
7541
7600
|
} else {
|
|
7542
|
-
|
|
7543
|
-
|
|
7601
|
+
const seconds = (now - this._rateAt) / 1000;
|
|
7602
|
+
if (msgPerSec !== null) this._msgTokens = Math.min(msgPerSec, this._msgTokens + seconds * msgPerSec);
|
|
7603
|
+
if (bytesPerSec !== null) this._byteTokens = Math.min(bytesPerSec, this._byteTokens + seconds * bytesPerSec);
|
|
7604
|
+
}
|
|
7605
|
+
this._rateAt = now;
|
|
7606
|
+
if (msgPerSec !== null && this._msgTokens < 1) return false;
|
|
7607
|
+
if (bytesPerSec !== null && this._byteTokens < Math.min(bytes, bytesPerSec)) return false;
|
|
7608
|
+
if (msgPerSec !== null) this._msgTokens -= 1;
|
|
7609
|
+
if (bytesPerSec !== null) this._byteTokens -= bytes;
|
|
7610
|
+
return true;
|
|
7544
7611
|
}
|
|
7545
7612
|
|
|
7546
7613
|
rxQuotaChecker(message) {
|
|
7547
7614
|
let rxBytes = message.byteLength;
|
|
7548
|
-
this.manager.rxBytes += rxBytes;
|
|
7549
|
-
|
|
7615
|
+
this.manager.counters.rxBytes += rxBytes;
|
|
7616
|
+
this.manager.counters.rxMessages++;
|
|
7550
7617
|
|
|
7551
|
-
|
|
7552
|
-
|
|
7618
|
+
const maxMessageBytes = this.quota.maxMessageBytes;
|
|
7619
|
+
if (maxMessageBytes !== null && rxBytes > maxMessageBytes) {
|
|
7620
|
+
this.manager.counters.oversizeRejected++;
|
|
7553
7621
|
this.send(Buffer.from([IOMsg.OVER_SIZE]));
|
|
7554
|
-
if (serverOption.useQuota.disconnect) this.close();
|
|
7555
7622
|
return false;
|
|
7556
7623
|
}
|
|
7557
|
-
|
|
7558
|
-
|
|
7559
|
-
|
|
7624
|
+
if (!this.takeRateTokens(rxBytes)) {
|
|
7625
|
+
this.manager.counters.rateLimited++;
|
|
7626
|
+
return false;
|
|
7627
|
+
}
|
|
7560
7628
|
return true;
|
|
7561
7629
|
}
|
|
7562
7630
|
|
|
@@ -7570,7 +7638,7 @@ class RemoteCore {
|
|
|
7570
7638
|
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7571
7639
|
this.securityFailure = reason;
|
|
7572
7640
|
this.boho.clearAuth();
|
|
7573
|
-
this.
|
|
7641
|
+
this.role = 'anonymous';
|
|
7574
7642
|
this._replayBuckets.clear();
|
|
7575
7643
|
this._replayEntries = 0;
|
|
7576
7644
|
this.close(true);
|
|
@@ -7652,9 +7720,8 @@ class RemoteCore {
|
|
|
7652
7720
|
this.receiveMonitor(); // rx-data, ping/pong and timeout check
|
|
7653
7721
|
if (!this.rxQuotaChecker(message)) return
|
|
7654
7722
|
|
|
7655
|
-
|
|
7656
|
-
|
|
7657
|
-
let msgType, decoded;
|
|
7723
|
+
const logMessages = this.manager.server?.logMessages;
|
|
7724
|
+
let msgType, decoded, encrypted = false;
|
|
7658
7725
|
|
|
7659
7726
|
if (isBinary) {
|
|
7660
7727
|
msgType = message[0];
|
|
@@ -7666,6 +7733,7 @@ class RemoteCore {
|
|
|
7666
7733
|
if (decoded) {
|
|
7667
7734
|
msgType = decoded[0];
|
|
7668
7735
|
message = decoded;
|
|
7736
|
+
encrypted = true;
|
|
7669
7737
|
} else {
|
|
7670
7738
|
return
|
|
7671
7739
|
}
|
|
@@ -7677,11 +7745,13 @@ class RemoteCore {
|
|
|
7677
7745
|
msgType = decoded[0];
|
|
7678
7746
|
message.set(decoded, it.MetaSize.ENC_488); // set decoded signal_e2e headaer.
|
|
7679
7747
|
message = message.subarray(it.MetaSize.ENC_488); // reset offset.
|
|
7748
|
+
encrypted = true;
|
|
7680
7749
|
} else {
|
|
7681
7750
|
return
|
|
7682
7751
|
}
|
|
7683
7752
|
|
|
7684
7753
|
} else ;
|
|
7754
|
+
if (logMessages) this.logMessage(msgType, message, encrypted);
|
|
7685
7755
|
|
|
7686
7756
|
switch (msgType) {
|
|
7687
7757
|
case IOMsg.PING:
|
|
@@ -7700,6 +7770,13 @@ class RemoteCore {
|
|
|
7700
7770
|
return;
|
|
7701
7771
|
}
|
|
7702
7772
|
|
|
7773
|
+
// Optional uint32 little endian after the type: the peer's RX buffer size. Set before
|
|
7774
|
+
// anything else is sent, so CID_RES, retained messages and signals respect it.
|
|
7775
|
+
if (message.byteLength >= 5) {
|
|
7776
|
+
const size = (message[1] | message[2] << 8 | message[3] << 16) + message[4] * 0x1000000;
|
|
7777
|
+
if (size > 0) this.peerRxLimit = size;
|
|
7778
|
+
}
|
|
7779
|
+
|
|
7703
7780
|
if (!this.cid) {
|
|
7704
7781
|
const cid = this.manager.issueAnonymousCid();
|
|
7705
7782
|
if (!cid) {
|
|
@@ -7709,6 +7786,8 @@ class RemoteCore {
|
|
|
7709
7786
|
}
|
|
7710
7787
|
this.cid = cid;
|
|
7711
7788
|
this.manager.cid2remote.set(this.cid, this);
|
|
7789
|
+
// The client limits its own sends to its quota (an authenticated one is sent on AUTH).
|
|
7790
|
+
this.setQuota(this.quotaName, true);
|
|
7712
7791
|
}
|
|
7713
7792
|
|
|
7714
7793
|
// console.log('<< SENDING CID_RES:', this.cid)
|
|
@@ -7812,11 +7891,10 @@ class RemoteCore {
|
|
|
7812
7891
|
|
|
7813
7892
|
|
|
7814
7893
|
case IOMsg.CLOSE:
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
}
|
|
7894
|
+
// The reason is only logged, so a CLOSE without one still closes.
|
|
7895
|
+
this.closeReason = closeReason(message);
|
|
7896
|
+
console.log(`>> CLOSE #${this.ssid} cid:${this.cid} reason: ${this.closeReason}`);
|
|
7897
|
+
this.close();
|
|
7820
7898
|
break;
|
|
7821
7899
|
|
|
7822
7900
|
|
|
@@ -7857,6 +7935,7 @@ class RemoteCore {
|
|
|
7857
7935
|
|
|
7858
7936
|
} else {
|
|
7859
7937
|
// TEXT FRAME
|
|
7938
|
+
if (logMessages) this.logMessage(undefined, message);
|
|
7860
7939
|
try {
|
|
7861
7940
|
let textMessage = decoder$3.decode(message);
|
|
7862
7941
|
// console.log('text buffer:',textMessage )
|
|
@@ -7939,7 +8018,8 @@ class RemoteCore {
|
|
|
7939
8018
|
"cid": this.cid,
|
|
7940
8019
|
"did": this.did,
|
|
7941
8020
|
"uid": this.uid,
|
|
7942
|
-
"
|
|
8021
|
+
"role": this.role,
|
|
8022
|
+
"quota": this.quotaName,
|
|
7943
8023
|
"nick": this.nick,
|
|
7944
8024
|
"ip": this.ip
|
|
7945
8025
|
, 'tag': channels
|
|
@@ -7957,31 +8037,45 @@ class RemoteCore {
|
|
|
7957
8037
|
|
|
7958
8038
|
}
|
|
7959
8039
|
|
|
8040
|
+
// 16 address bytes of an IPv6 string (with '::', an embedded IPv4 tail or a %zone), else null.
|
|
8041
|
+
function ipv6Bytes(ip) {
|
|
8042
|
+
if (!net.isIPv6(ip)) return null
|
|
8043
|
+
ip = ip.split('%')[0];
|
|
8044
|
+
const tailStart = ip.lastIndexOf(':') + 1;
|
|
8045
|
+
const tail = ip.slice(tailStart);
|
|
8046
|
+
if (net.isIPv4(tail)) {
|
|
8047
|
+
const [a, b, c, d] = tail.split('.').map(Number);
|
|
8048
|
+
ip = ip.slice(0, tailStart) + ((a << 8) | b).toString(16) + ':' + ((c << 8) | d).toString(16);
|
|
8049
|
+
}
|
|
8050
|
+
const words = s => s ? s.split(':').map(h => parseInt(h, 16)) : [];
|
|
8051
|
+
const [head, rest] = ip.split('::');
|
|
8052
|
+
const left = words(head), right = words(rest);
|
|
8053
|
+
const all = [...left, ...new Array(8 - left.length - right.length).fill(0), ...right];
|
|
8054
|
+
const bytes = Buffer.alloc(16);
|
|
8055
|
+
all.forEach((word, i) => bytes.writeUInt16BE(word, i * 2));
|
|
8056
|
+
return bytes
|
|
8057
|
+
}
|
|
8058
|
+
|
|
8059
|
+
function isPrivateIPv4(ip) {
|
|
8060
|
+
const [a, b] = ip.split('.').map(Number);
|
|
8061
|
+
return a === 0 || a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168)
|
|
8062
|
+
}
|
|
8063
|
+
|
|
8064
|
+
// Unspecified, loopback, RFC 1918, IPv6 unique-local (fc00::/7) and link-local (fe80::/10).
|
|
7960
8065
|
function isPrivateIP(ip) {
|
|
7961
|
-
if (
|
|
7962
|
-
|
|
7963
|
-
if (
|
|
7964
|
-
if (
|
|
7965
|
-
if (
|
|
7966
|
-
|
|
7967
|
-
|
|
7968
|
-
|
|
7969
|
-
|
|
7970
|
-
|
|
7971
|
-
|
|
7972
|
-
|
|
7973
|
-
|
|
7974
|
-
if (ip.indexOf("172.24.") === 0) return true
|
|
7975
|
-
if (ip.indexOf("172.25.") === 0) return true
|
|
7976
|
-
if (ip.indexOf("172.26.") === 0) return true
|
|
7977
|
-
if (ip.indexOf("172.27.") === 0) return true
|
|
7978
|
-
if (ip.indexOf("172.28.") === 0) return true
|
|
7979
|
-
if (ip.indexOf("172.29.") === 0) return true
|
|
7980
|
-
if (ip.indexOf("172.30.") === 0) return true
|
|
7981
|
-
if (ip.indexOf("172.31.") === 0) return true
|
|
7982
|
-
}
|
|
7983
|
-
|
|
7984
|
-
return false
|
|
8066
|
+
if (net.isIPv4(ip)) return isPrivateIPv4(ip)
|
|
8067
|
+
const bytes = ipv6Bytes(ip);
|
|
8068
|
+
if (!bytes) return false
|
|
8069
|
+
if (bytes.subarray(0, 15).every(v => v === 0) && bytes[15] <= 1) return true // :: and ::1
|
|
8070
|
+
if (bytes.subarray(0, 10).every(v => v === 0) && bytes[10] === 0xff && bytes[11] === 0xff) {
|
|
8071
|
+
return isPrivateIPv4(bytes.subarray(12).join('.')) // IPv4-mapped
|
|
8072
|
+
}
|
|
8073
|
+
return (bytes[0] & 0xfe) === 0xfc || (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80)
|
|
8074
|
+
}
|
|
8075
|
+
|
|
8076
|
+
// Hosts on one IPv6 network share the /64 prefix, not the address: hex of those 8 bytes.
|
|
8077
|
+
function getIPv6PrefixHexString(ip) {
|
|
8078
|
+
return ipv6Bytes(ip)?.subarray(0, 8).toString('hex') ?? null
|
|
7985
8079
|
}
|
|
7986
8080
|
|
|
7987
8081
|
function numberWithCommas(x) {
|
|
@@ -8022,6 +8116,42 @@ const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
8022
8116
|
|
|
8023
8117
|
const decoder$2 = new TextDecoder();
|
|
8024
8118
|
|
|
8119
|
+
// Each proxy appends to a forwarding header, so the entry `hops` from the right was
|
|
8120
|
+
// written by the outermost trusted proxy; anything left of it came from the client.
|
|
8121
|
+
function forwardedValue(header, hops) {
|
|
8122
|
+
if (!hops || typeof header !== 'string') return undefined
|
|
8123
|
+
const values = header.split(',').map(v => v.trim()).filter(Boolean);
|
|
8124
|
+
return values[Math.max(0, values.length - hops)]
|
|
8125
|
+
}
|
|
8126
|
+
|
|
8127
|
+
// IPv4-mapped addresses as IPv4, '::1' as 127.0.0.1; undefined if not an IP address.
|
|
8128
|
+
function normalizeIP(ip) {
|
|
8129
|
+
if (typeof ip !== 'string') return undefined
|
|
8130
|
+
if (ip.startsWith('::ffff:') && node_net.isIPv4(ip.slice(7))) ip = ip.slice(7);
|
|
8131
|
+
if (ip === '::1') ip = '127.0.0.1';
|
|
8132
|
+
return node_net.isIP(ip) ? ip : undefined
|
|
8133
|
+
}
|
|
8134
|
+
|
|
8135
|
+
// Number of reverse proxies whose forwarding headers are trusted (see serverOption.trustProxy).
|
|
8136
|
+
function trustedProxyHops(peerIP, trust = serverOption.trustProxy) {
|
|
8137
|
+
if (trust === 'private') return peerIP && isPrivateIP(peerIP) ? 1 : 0
|
|
8138
|
+
if (trust === true) return 1
|
|
8139
|
+
return Number.isSafeInteger(trust) && trust > 0 ? trust : 0
|
|
8140
|
+
}
|
|
8141
|
+
|
|
8142
|
+
// Client address and TLS of a WebSocket upgrade request; exported for other servers that
|
|
8143
|
+
// accept the same proxied connections.
|
|
8144
|
+
function getClientAddress(req, trust = serverOption.trustProxy) {
|
|
8145
|
+
const peerIP = normalizeIP(req.socket?.remoteAddress);
|
|
8146
|
+
const hops = trustedProxyHops(peerIP, trust);
|
|
8147
|
+
return {
|
|
8148
|
+
ip: normalizeIP(forwardedValue(req.headers['x-forwarded-for'], hops)) ?? peerIP ?? '0.0.0.0',
|
|
8149
|
+
// X-Forwarded-Proto: https turns off server-side encryption (ENC_MODE.AUTO), so it is
|
|
8150
|
+
// only honored from a trusted proxy, like the client address.
|
|
8151
|
+
TLS: forwardedValue(req.headers['x-forwarded-proto'], hops) === 'https'
|
|
8152
|
+
}
|
|
8153
|
+
}
|
|
8154
|
+
|
|
8025
8155
|
class Remote extends RemoteCore {
|
|
8026
8156
|
constructor(socket, req, manager) {
|
|
8027
8157
|
super(socket, manager);
|
|
@@ -8032,11 +8162,12 @@ class Remote extends RemoteCore {
|
|
|
8032
8162
|
this.socketType = socket.socketType;
|
|
8033
8163
|
|
|
8034
8164
|
if (this.socketType === 'websocket') {
|
|
8035
|
-
|
|
8036
|
-
this.ip =
|
|
8165
|
+
const { ip, TLS } = getClientAddress(req, this.manager.server?.trustProxy);
|
|
8166
|
+
this.ip = ip;
|
|
8167
|
+
this.TLS = TLS;
|
|
8037
8168
|
} else {
|
|
8038
8169
|
this.TLS = false;
|
|
8039
|
-
this.ip =
|
|
8170
|
+
this.ip = normalizeIP(socket.remoteAddress) ?? '0.0.0.0';
|
|
8040
8171
|
}
|
|
8041
8172
|
|
|
8042
8173
|
|
|
@@ -8044,6 +8175,9 @@ class Remote extends RemoteCore {
|
|
|
8044
8175
|
// connection from local or private network has default private channel.
|
|
8045
8176
|
this.HOME_CHANNEL = 'PRIVATE:';
|
|
8046
8177
|
this.privateNode = true;
|
|
8178
|
+
} else if (node_net.isIPv6(this.ip)) {
|
|
8179
|
+
// An IPv6 network is its /64 prefix; each host there has its own address.
|
|
8180
|
+
this.HOME_CHANNEL = 'IP6:' + getIPv6PrefixHexString(this.ip);
|
|
8047
8181
|
} else {
|
|
8048
8182
|
// The HOME_CHANNEL is defined by the global IP address value.
|
|
8049
8183
|
this.HOME_CHANNEL = 'IP:' + getIPv4HexString(this.ip);
|
|
@@ -8070,10 +8204,11 @@ class Remote extends RemoteCore {
|
|
|
8070
8204
|
this.txDrainMaxMs = Math.max(this.txDrainMaxMs, node_perf_hooks.performance.now() - this.txBlockedSince);
|
|
8071
8205
|
this.txBlockedSince = null;
|
|
8072
8206
|
});
|
|
8073
|
-
this.congRx = new CongRx();
|
|
8207
|
+
this.congRx = new CongRx({ maxFrameSize: this.rxFrameLimit() });
|
|
8074
8208
|
socket.on('data', data => { this.congRx.write(data); });
|
|
8075
8209
|
|
|
8076
8210
|
this.congRx.on('wrong', this.onWrongCongPacketMessage.bind(this));
|
|
8211
|
+
this.congRx.on('oversize', this.onOversizeCongPacket.bind(this));
|
|
8077
8212
|
// readable.pipe( destination )
|
|
8078
8213
|
// tcpSocket -> congRx(parser) -> onMessage
|
|
8079
8214
|
// socket.pipe( this.congRx )
|
|
@@ -8127,13 +8262,32 @@ class Remote extends RemoteCore {
|
|
|
8127
8262
|
}
|
|
8128
8263
|
|
|
8129
8264
|
|
|
8130
|
-
|
|
8131
|
-
|
|
8132
|
-
|
|
8133
|
-
|
|
8265
|
+
// Largest CongSocket frame the parser buffers: maxPayload (as for WebSocket), or the quota's
|
|
8266
|
+
// maxMessageBytes when smaller. A frame payload is the message rxQuotaChecker measures, so a
|
|
8267
|
+
// larger frame would be rejected after buffering anyway.
|
|
8268
|
+
rxFrameLimit() {
|
|
8269
|
+
const maxPayload = this.manager.server?.maxPayload ?? serverOption.maxPayload;
|
|
8270
|
+
const maxMessageBytes = this.quota?.maxMessageBytes ?? null;
|
|
8271
|
+
return maxMessageBytes === null ? maxPayload : Math.min(maxPayload, maxMessageBytes);
|
|
8272
|
+
}
|
|
8134
8273
|
|
|
8274
|
+
// Called after the quota changes (e.g. on successful auth).
|
|
8275
|
+
refreshRxFrameLimit() {
|
|
8276
|
+
if (this.congRx) this.congRx.maxFrameSize = this.rxFrameLimit();
|
|
8135
8277
|
}
|
|
8136
8278
|
|
|
8279
|
+
// The frame was skipped unbuffered; same response as rxQuotaChecker, except that a
|
|
8280
|
+
// connection without a CID is treated like a wrong packet (see onWrongCongPacketMessage).
|
|
8281
|
+
onOversizeCongPacket(payloadSize) {
|
|
8282
|
+
if (this._closing) return;
|
|
8283
|
+
if (!this.cid) {
|
|
8284
|
+
this.manager.attackLogger?.log(`> ${this.ssid} ${this.ip} OVERSIZE ${payloadSize}`);
|
|
8285
|
+
this.close(true);
|
|
8286
|
+
return;
|
|
8287
|
+
}
|
|
8288
|
+
this.manager.counters.oversizeRejected++;
|
|
8289
|
+
this.send(Buffer.from([IOMsg.OVER_SIZE]));
|
|
8290
|
+
}
|
|
8137
8291
|
|
|
8138
8292
|
// any type of received messages: message, ping, pong
|
|
8139
8293
|
receiveMonitor() {
|
|
@@ -8142,27 +8296,9 @@ class Remote extends RemoteCore {
|
|
|
8142
8296
|
this.socket.isAlive = true;
|
|
8143
8297
|
}
|
|
8144
8298
|
|
|
8145
|
-
|
|
8146
|
-
|
|
8147
|
-
return
|
|
8148
|
-
}
|
|
8149
|
-
|
|
8150
|
-
getRemoteIP(req) { //req or ip string
|
|
8151
|
-
let ip;
|
|
8152
|
-
if (req && req.headers) {
|
|
8153
|
-
ip = req.headers["x-forwarded-for"];
|
|
8154
|
-
if (ip == undefined) ip = req.socket.remoteAddress;
|
|
8155
|
-
} else {
|
|
8156
|
-
ip = req;
|
|
8157
|
-
}
|
|
8158
|
-
|
|
8159
|
-
if (ip) {
|
|
8160
|
-
if (ip.indexOf("::ffff:") == 0) ip = ip.substring(7);
|
|
8161
|
-
if (ip == "::1") ip = "127.0.0.1";
|
|
8162
|
-
} else {
|
|
8163
|
-
ip = "0.0.0.0";
|
|
8164
|
-
}
|
|
8165
|
-
return ip;
|
|
8299
|
+
// Number of reverse proxies whose forwarding headers this server trusts.
|
|
8300
|
+
trustedProxyHops(peerIP) {
|
|
8301
|
+
return trustedProxyHops(peerIP, this.manager.server?.trustProxy)
|
|
8166
8302
|
}
|
|
8167
8303
|
|
|
8168
8304
|
ping() {
|
|
@@ -8184,15 +8320,15 @@ class Remote extends RemoteCore {
|
|
|
8184
8320
|
}
|
|
8185
8321
|
|
|
8186
8322
|
getTraffic() {
|
|
8187
|
-
this.socket.bytesWritten || this.socket._socket?.bytesWritten;
|
|
8188
|
-
this.socket.bytesRead || this.socket._socket?.bytesRead;
|
|
8189
|
-
this.socket.txCounter;
|
|
8190
|
-
this.socket.rxCounter;
|
|
8323
|
+
let txb = this.socket.bytesWritten || this.socket._socket?.bytesWritten;
|
|
8324
|
+
let rxb = this.socket.bytesRead || this.socket._socket?.bytesRead;
|
|
8325
|
+
let tx = this.socket.txCounter;
|
|
8326
|
+
let rx = this.socket.rxCounter;
|
|
8327
|
+
return { tx, txb, rx, rxb }
|
|
8191
8328
|
}
|
|
8192
8329
|
|
|
8193
8330
|
close(terminateNow = false) {
|
|
8194
8331
|
this._closing = true;
|
|
8195
|
-
this.getTraffic();
|
|
8196
8332
|
if (this.socketType === 'websocket') {
|
|
8197
8333
|
if (terminateNow) this.socket.terminate();
|
|
8198
8334
|
else this.socket.close();
|
|
@@ -8202,16 +8338,30 @@ class Remote extends RemoteCore {
|
|
|
8202
8338
|
}
|
|
8203
8339
|
}
|
|
8204
8340
|
|
|
8341
|
+
// A peer that stops reading would otherwise grow its send queue without limit.
|
|
8205
8342
|
recordTxQueue() {
|
|
8206
8343
|
const queued = this.socket.bufferedAmount ?? this.socket.writableLength ?? 0;
|
|
8207
8344
|
if (queued > this.txQueuePeakBytes) this.txQueuePeakBytes = queued;
|
|
8345
|
+
const limit = this.manager.server?.maxBufferedBytes ?? serverOption.maxBufferedBytes;
|
|
8346
|
+
if (queued > limit) {
|
|
8347
|
+
console.log(`slow peer #${this.ssid} cid:${this.cid} has ${queued} unsent bytes: closing`);
|
|
8348
|
+
this.close(true);
|
|
8349
|
+
}
|
|
8208
8350
|
}
|
|
8209
8351
|
|
|
8210
8352
|
// node.js server side remote.
|
|
8211
8353
|
send(message, isBinary) {
|
|
8354
|
+
// Sending to a closing peer can only fail; skip instead of logging each attempt.
|
|
8355
|
+
if (this._closing) return;
|
|
8356
|
+
// The peer cannot receive it (see peerRxLimit); a CongSocket Arduino would have to discard it.
|
|
8357
|
+
if (this.peerRxLimit !== null && message.byteLength > this.peerRxLimit) {
|
|
8358
|
+
this.peerRxLimitSkipped++;
|
|
8359
|
+
this.manager.counters.peerRxLimitSkipped++;
|
|
8360
|
+
return;
|
|
8361
|
+
}
|
|
8212
8362
|
// console.log(`<-S [${IOMsg[ message[0]]}]`)
|
|
8213
|
-
this.manager.txBytes += message.byteLength;
|
|
8214
|
-
|
|
8363
|
+
this.manager.counters.txBytes += message.byteLength;
|
|
8364
|
+
this.manager.counters.txMessages++;
|
|
8215
8365
|
this.socket.txCounter++;
|
|
8216
8366
|
if (this.socketType === 'websocket') {
|
|
8217
8367
|
if (this.socket.readyState === 1) {
|
|
@@ -8273,93 +8423,80 @@ class FileLogger {
|
|
|
8273
8423
|
|
|
8274
8424
|
}
|
|
8275
8425
|
|
|
8276
|
-
const
|
|
8277
|
-
|
|
8426
|
+
const KIB = 1024, MIB = 1024 * 1024;
|
|
8427
|
+
|
|
8428
|
+
function bytes(n) {
|
|
8429
|
+
if (n >= MIB) return (n / MIB).toFixed(1) + 'MB'
|
|
8430
|
+
if (n >= KIB) return (n / KIB).toFixed(1) + 'KB'
|
|
8431
|
+
return Math.round(n) + 'B'
|
|
8432
|
+
}
|
|
8278
8433
|
|
|
8434
|
+
// Read-only views of the manager for logStats, Server.stats() and the sudo service.
|
|
8435
|
+
// Nothing here runs on a timer or resets the manager's counters.
|
|
8279
8436
|
class Metrics {
|
|
8280
8437
|
constructor(manager) {
|
|
8281
8438
|
this.manager = manager;
|
|
8282
|
-
|
|
8283
|
-
this.metricsPack = {
|
|
8284
|
-
remotes: [0],
|
|
8285
|
-
channels: [0],
|
|
8286
|
-
txBytes: [0],
|
|
8287
|
-
rxBytes: [0],
|
|
8288
|
-
unixTime: [Math.floor(Date.now() / 1000)],
|
|
8289
|
-
period: 0
|
|
8290
|
-
};
|
|
8291
|
-
|
|
8292
|
-
this.tickId = setInterval(e => {
|
|
8293
|
-
|
|
8294
|
-
this.metricsPack.remotes.push(this.manager.remotes.size);
|
|
8295
|
-
if (this.metricsPack.remotes.length > MAX) this.metricsPack.remotes.shift();
|
|
8296
|
-
|
|
8297
|
-
this.metricsPack.channels.push(this.manager.channel_map.size);
|
|
8298
|
-
if (this.metricsPack.channels.length > MAX) this.metricsPack.channels.shift();
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
this.metricsPack.txBytes.push(this.manager.txBytes);
|
|
8302
|
-
if (this.metricsPack.txBytes.length > MAX) this.metricsPack.txBytes.shift();
|
|
8303
|
-
|
|
8304
|
-
this.metricsPack.rxBytes.push(this.manager.rxBytes);
|
|
8305
|
-
if (this.metricsPack.rxBytes.length > MAX) this.metricsPack.rxBytes.shift();
|
|
8306
|
-
|
|
8307
|
-
this.metricsPack.unixTime = Math.floor(Date.now() / 1000);
|
|
8308
|
-
this.metricsPack.period = period;
|
|
8309
|
-
this.manager.txBytes = 0;
|
|
8310
|
-
this.manager.rxBytes = 0;
|
|
8311
|
-
|
|
8312
|
-
|
|
8313
|
-
}, 10000);
|
|
8439
|
+
this.previous = null; // last summaryLine() sample, for rates
|
|
8314
8440
|
}
|
|
8315
8441
|
|
|
8316
|
-
|
|
8317
|
-
|
|
8318
8442
|
close() {
|
|
8319
|
-
|
|
8320
|
-
this.tickId = null;
|
|
8443
|
+
this.previous = null;
|
|
8321
8444
|
}
|
|
8322
8445
|
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8446
|
+
// Current state; counters are cumulative since the server started. Enumerates connections once.
|
|
8447
|
+
snapshot() {
|
|
8448
|
+
const manager = this.manager;
|
|
8449
|
+
let authenticated = 0, websocket = 0;
|
|
8450
|
+
for (const remote of manager.remotes) {
|
|
8451
|
+
if (remote.boho.isAuthorized) authenticated++;
|
|
8452
|
+
if (remote.socketType === 'websocket') websocket++;
|
|
8453
|
+
}
|
|
8454
|
+
const total = manager.remotes.size;
|
|
8455
|
+
const memory = process$1.memoryUsage();
|
|
8456
|
+
return {
|
|
8457
|
+
at: Date.now(),
|
|
8458
|
+
connections: { total, authenticated, anonymous: total - authenticated, websocket, tcp: total - websocket },
|
|
8459
|
+
channels: manager.channel_map.size,
|
|
8460
|
+
retained: { channel: manager.retain_messages.size, bytes: manager.retainBytes },
|
|
8461
|
+
counters: { ...manager.counters },
|
|
8462
|
+
memory: { rss: memory.rss, heapUsed: memory.heapUsed }
|
|
8463
|
+
}
|
|
8464
|
+
}
|
|
8465
|
+
|
|
8466
|
+
// One logStats line; rates are per second since the previous line.
|
|
8467
|
+
summaryLine(now = node_perf_hooks.performance.now()) {
|
|
8468
|
+
const s = this.snapshot(), previous = this.previous;
|
|
8469
|
+
const rate = key => previous ? (s.counters[key] - previous.counters[key]) * 1000 / Math.max(1, now - previous.time) : 0;
|
|
8470
|
+
this.previous = { time: now, counters: s.counters };
|
|
8471
|
+
const c = s.connections;
|
|
8472
|
+
return `[iosignal] conn ${c.total} (auth ${c.authenticated}, anon ${c.anonymous}, ws ${c.websocket}, tcp ${c.tcp})` +
|
|
8473
|
+
` ch ${s.channels} retained ${s.retained.channel}/${bytes(s.retained.bytes)}` +
|
|
8474
|
+
` | rx ${rate('rxMessages').toFixed(1)}/s ${bytes(rate('rxBytes'))}/s` +
|
|
8475
|
+
` tx ${rate('txMessages').toFixed(1)}/s ${bytes(rate('txBytes'))}/s pub ${rate('publishes').toFixed(1)}/s` +
|
|
8476
|
+
` | rss ${bytes(s.memory.rss)} heap ${bytes(s.memory.heapUsed)}`
|
|
8477
|
+
}
|
|
8478
|
+
|
|
8479
|
+
// Compact summary for metrics reports ('@$metrics'); byte counters are cumulative.
|
|
8480
|
+
oneline() {
|
|
8481
|
+
return {
|
|
8332
8482
|
lastSSID: this.manager.lastSSID,
|
|
8333
8483
|
remotes: this.manager.remotes.size,
|
|
8334
8484
|
channels: this.manager.channel_map.size,
|
|
8335
|
-
txBytes: this.manager.txBytes,
|
|
8336
|
-
rxBytes: this.manager.rxBytes,
|
|
8337
|
-
}
|
|
8338
|
-
|
|
8339
|
-
if (prn) console.table(metric, ['lastSSID', 'remotes', 'channels', 'txBytes', 'rxBytes']);
|
|
8340
|
-
|
|
8341
|
-
return metric[0]
|
|
8485
|
+
txBytes: this.manager.counters.txBytes,
|
|
8486
|
+
rxBytes: this.manager.counters.rxBytes,
|
|
8487
|
+
}
|
|
8342
8488
|
}
|
|
8343
8489
|
|
|
8344
|
-
getRemotes(
|
|
8345
|
-
|
|
8346
|
-
let remoteStates = remoteList.map(v => {
|
|
8347
|
-
return "#" + v.ssid + ":" + v.cid + "(" + v.state + ")"
|
|
8348
|
-
});
|
|
8349
|
-
if (prn) console.table(remoteStates);
|
|
8350
|
-
return remoteStates
|
|
8490
|
+
getRemotes() {
|
|
8491
|
+
return Array.from(this.manager.remotes, v => "#" + v.ssid + ":" + v.cid + "(" + v.getStateName() + ")")
|
|
8351
8492
|
}
|
|
8352
8493
|
|
|
8353
|
-
getCIdList(
|
|
8354
|
-
|
|
8355
|
-
if (prn) console.table(CIdList);
|
|
8356
|
-
return CIdList
|
|
8494
|
+
getCIdList() {
|
|
8495
|
+
return Array.from(this.manager.cid2remote.keys())
|
|
8357
8496
|
}
|
|
8358
8497
|
|
|
8359
|
-
getChannelList(
|
|
8360
|
-
|
|
8361
|
-
if (prn) console.table(chList);
|
|
8362
|
-
return chList
|
|
8498
|
+
getChannelList() {
|
|
8499
|
+
return Array.from(this.manager.channel_map.keys())
|
|
8363
8500
|
}
|
|
8364
8501
|
|
|
8365
8502
|
getSubscribers(ch) {
|
|
@@ -8370,7 +8507,6 @@ class Metrics {
|
|
|
8370
8507
|
list.push(c.cid);
|
|
8371
8508
|
});
|
|
8372
8509
|
}
|
|
8373
|
-
// console.log(list)
|
|
8374
8510
|
return list
|
|
8375
8511
|
}
|
|
8376
8512
|
|
|
@@ -8409,15 +8545,11 @@ class Metrics {
|
|
|
8409
8545
|
encMode: ENC_MODE[remote.encMode]
|
|
8410
8546
|
}
|
|
8411
8547
|
} else if (mode == 4) {
|
|
8412
|
-
let channels = Array.from(remote.channels.keys());
|
|
8413
|
-
let set_memory = Array.from(remote.memory.keys());
|
|
8414
|
-
let retain_signal = Array.from(remote.retain_signal.keys());
|
|
8415
8548
|
return {
|
|
8416
8549
|
ip: remote.ip,
|
|
8417
8550
|
uptime: Math.trunc((Date.now() - remote.socket.openTime) / 1000),
|
|
8418
|
-
channels: channels,
|
|
8419
|
-
|
|
8420
|
-
retain: retain_signal
|
|
8551
|
+
channels: Array.from(remote.channels.keys()),
|
|
8552
|
+
retain: Array.from(remote.retain_signal.keys())
|
|
8421
8553
|
}
|
|
8422
8554
|
}
|
|
8423
8555
|
|
|
@@ -8437,14 +8569,17 @@ class Manager {
|
|
|
8437
8569
|
|
|
8438
8570
|
constructor(server, authManager) {
|
|
8439
8571
|
this.server = server;
|
|
8440
|
-
|
|
8441
|
-
this.
|
|
8572
|
+
// This server's settings; a Manager made without a Server (tests, checks) uses the defaults.
|
|
8573
|
+
this.pingPeriod = server?.heartbeatInterval ?? serverOption.heartbeatInterval;
|
|
8574
|
+
this.pingGrace = server?.heartbeatGrace ?? serverOption.heartbeatGrace;
|
|
8442
8575
|
if (!Number.isFinite(this.pingPeriod) || this.pingPeriod <= 0 ||
|
|
8443
8576
|
!Number.isFinite(this.pingGrace) || this.pingGrace < 0) {
|
|
8444
8577
|
throw new RangeError('Invalid heartbeat period or grace');
|
|
8445
8578
|
}
|
|
8446
|
-
|
|
8447
|
-
this.
|
|
8579
|
+
// Cumulative since the server started; never reset (readers compute rates from deltas).
|
|
8580
|
+
this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
|
|
8581
|
+
publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
|
|
8582
|
+
peerRxLimitSkipped: 0 }; // messages not sent: larger than the peer's advertised RX buffer
|
|
8448
8583
|
|
|
8449
8584
|
this.authManager = authManager;
|
|
8450
8585
|
|
|
@@ -8462,7 +8597,12 @@ class Manager {
|
|
|
8462
8597
|
|
|
8463
8598
|
this.remotes = new Set(); // total remotes
|
|
8464
8599
|
this.cid2remote = new Map(); // key: cid -> value: remote
|
|
8600
|
+
this.accountConnectionCounts = new Map(); // uid -> authenticated connections
|
|
8465
8601
|
this.retain_messages = new Map(); // key: tag, data: signalMessage
|
|
8602
|
+
this.retain_owner = new Map(); // key: channel retain tag -> its owner record (see retainOwner)
|
|
8603
|
+
this.retainOwners = new Map(); // key: 'cid:<cid>' | 'conn:<ssid>' | 'net:<HOME_CHANNEL>' -> owner
|
|
8604
|
+
this.retainExpiry = new Map(); // key: channel retain tag in a grace pool -> expiry time
|
|
8605
|
+
this.retainBytes = 0; // all retained messages, channel and CID
|
|
8466
8606
|
this.channel_map = new Map(); // key: channelName -> value: < remote : Set >
|
|
8467
8607
|
this.CHANNEL_PREFIX = 'CH:';
|
|
8468
8608
|
this.CID_PREFIX = 'CID:';
|
|
@@ -8484,18 +8624,49 @@ class Manager {
|
|
|
8484
8624
|
};
|
|
8485
8625
|
this.pingIntervalID = setTimeout(tick, this.pingTickMs);
|
|
8486
8626
|
|
|
8487
|
-
|
|
8488
|
-
|
|
8489
|
-
|
|
8490
|
-
}, serverOption.monitorPeriod);
|
|
8627
|
+
// logStats: one summary line per interval; it never clears the terminal, so other logs stay.
|
|
8628
|
+
if (server.logStats) {
|
|
8629
|
+
this.statsIntervalID = setInterval(() => console.log(this.metrics.summaryLine()), server.logStats);
|
|
8491
8630
|
}
|
|
8492
8631
|
|
|
8493
8632
|
|
|
8494
8633
|
}
|
|
8495
8634
|
|
|
8496
8635
|
|
|
8636
|
+
get retainOptions() {
|
|
8637
|
+
return this.server?.retain ?? serverOption.retain
|
|
8638
|
+
}
|
|
8639
|
+
|
|
8640
|
+
get quotas() {
|
|
8641
|
+
return this.server?.quotas ?? serverOption.quotas
|
|
8642
|
+
}
|
|
8643
|
+
|
|
8644
|
+
get anonymousQuota() {
|
|
8645
|
+
return this.server?.anonymousQuota ?? serverOption.anonymousQuota
|
|
8646
|
+
}
|
|
8647
|
+
|
|
8648
|
+
// Authenticated connections per account (uid), for the quota's maxConnections.
|
|
8649
|
+
accountConnections(uid) {
|
|
8650
|
+
return this.accountConnectionCounts.get(uid) ?? 0
|
|
8651
|
+
}
|
|
8652
|
+
|
|
8653
|
+
addAccountConnection(remote, uid) {
|
|
8654
|
+
remote.accountUid = uid;
|
|
8655
|
+
this.accountConnectionCounts.set(uid, this.accountConnections(uid) + 1);
|
|
8656
|
+
}
|
|
8657
|
+
|
|
8658
|
+
removeAccountConnection(remote) {
|
|
8659
|
+
const uid = remote.accountUid;
|
|
8660
|
+
if (!uid) return
|
|
8661
|
+
remote.accountUid = null;
|
|
8662
|
+
const count = this.accountConnections(uid) - 1;
|
|
8663
|
+
if (count > 0) this.accountConnectionCounts.set(uid, count);
|
|
8664
|
+
else this.accountConnectionCounts.delete(uid);
|
|
8665
|
+
}
|
|
8666
|
+
|
|
8497
8667
|
heartbeatTick() {
|
|
8498
8668
|
const now = node_perf_hooks.performance.now();
|
|
8669
|
+
if (this.retainExpiry.size) this.expireChannelRetains(now);
|
|
8499
8670
|
// Process only expired requests, not every connected peer.
|
|
8500
8671
|
for (const [remote, deadline] of this.heartbeatPending) {
|
|
8501
8672
|
if (deadline > now) break;
|
|
@@ -8538,6 +8709,7 @@ class Manager {
|
|
|
8538
8709
|
removeRemote(remote) {
|
|
8539
8710
|
|
|
8540
8711
|
remote._closing = true;
|
|
8712
|
+
this.removeAccountConnection(remote);
|
|
8541
8713
|
this.pingGroups[remote.pingGroup]?.delete(remote);
|
|
8542
8714
|
this.heartbeatPending.delete(remote);
|
|
8543
8715
|
remote.setState(STATE.CLOSED);
|
|
@@ -8563,6 +8735,10 @@ class Manager {
|
|
|
8563
8735
|
|
|
8564
8736
|
// retain message policy
|
|
8565
8737
|
// type 1. ( isAuthorizedUser) ? keep : delete.
|
|
8738
|
+
// Channel retains: an authenticated writer's belong to its account and stay; an anonymous
|
|
8739
|
+
// connection's move to its network's grace pool and expire there.
|
|
8740
|
+
this.orphanChannelRetains(remote);
|
|
8741
|
+
|
|
8566
8742
|
if (remote.boho.isAuthorized) ; else {
|
|
8567
8743
|
// anonymouse: remove the cid publish channel
|
|
8568
8744
|
for (let ch of remote.retain_signal.keys()) {
|
|
@@ -8574,6 +8750,10 @@ class Manager {
|
|
|
8574
8750
|
}
|
|
8575
8751
|
}
|
|
8576
8752
|
}
|
|
8753
|
+
// CID retains live in the remote and go with it (after the '@$state' close above).
|
|
8754
|
+
for (const message of remote.retain_signal.values()) this.retainBytes -= message.byteLength;
|
|
8755
|
+
remote.retain_signal.clear();
|
|
8756
|
+
remote.retainBytes = 0;
|
|
8577
8757
|
|
|
8578
8758
|
|
|
8579
8759
|
// Service lifecycle hook. Called directly: RPC permission/command checks do not apply to cleanup.
|
|
@@ -8645,9 +8825,7 @@ class Manager {
|
|
|
8645
8825
|
let topic = tag.split('@')[1];
|
|
8646
8826
|
if (cid && this.cid2remote.has(cid)) {
|
|
8647
8827
|
let sigPack = getSignalPack('@' + topic, ...args);
|
|
8648
|
-
|
|
8649
|
-
console.log('target', targetRemote.state, targetRemote.cid);
|
|
8650
|
-
targetRemote.send_enc_mode(sigPack);
|
|
8828
|
+
this.cid2remote.get(cid).send_enc_mode(sigPack);
|
|
8651
8829
|
return
|
|
8652
8830
|
} else {
|
|
8653
8831
|
return "no cid"
|
|
@@ -8656,7 +8834,7 @@ class Manager {
|
|
|
8656
8834
|
|
|
8657
8835
|
sender(tag, remote, message) {
|
|
8658
8836
|
if (encoder.encode(tag).byteLength > SIZE_LIMIT.TAG_LEN1) return ['err', 'Tag exceeds 255 UTF-8 bytes']
|
|
8659
|
-
if (serverOption.membersOnly && !remote.boho.isAuthorized) {
|
|
8837
|
+
if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
|
|
8660
8838
|
// console.log("### server reject client signal reason: [membersOnly]" ,tag, remote.cid )
|
|
8661
8839
|
remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
|
|
8662
8840
|
remote.close();
|
|
@@ -8710,35 +8888,26 @@ class Manager {
|
|
|
8710
8888
|
// retain signal message
|
|
8711
8889
|
if (tag.includes('$')
|
|
8712
8890
|
// && remote.boho.isAuthorized
|
|
8713
|
-
&&
|
|
8714
|
-
&& serverOption.retain.limitCounter > this.retain_messages.size
|
|
8715
|
-
&& serverOption.retain.limitSize > message.byteLength
|
|
8891
|
+
&& this.retainOptions.enabled
|
|
8716
8892
|
) {
|
|
8717
|
-
// cid retain signal
|
|
8718
8893
|
if (tag.includes('@')) {
|
|
8719
|
-
// cid retain signal stored inside remote.
|
|
8720
|
-
|
|
8721
|
-
remote.retain_signal.set(retainTag, message);
|
|
8894
|
+
// cid retain signal stored inside remote, counted per remote.
|
|
8895
|
+
this.storeCidRetain(tag.split('@')[1], message, remote);
|
|
8722
8896
|
} else {
|
|
8723
8897
|
// channel retain signal stored inside manager.
|
|
8724
|
-
this.
|
|
8898
|
+
this.storeChannelRetain(tag, message, remote);
|
|
8725
8899
|
}
|
|
8726
|
-
|
|
8727
8900
|
}
|
|
8728
8901
|
|
|
8729
|
-
|
|
8902
|
+
this.counters.publishes++;
|
|
8730
8903
|
let sentCounter = 0;
|
|
8731
8904
|
if (this.channel_map.has(tag)) {
|
|
8732
8905
|
// console.log('raw channel_map matched tag:', tag)
|
|
8733
8906
|
let remotes = this.channel_map.get(tag);
|
|
8734
8907
|
if (remotes.size >= 1) {
|
|
8735
|
-
|
|
8736
|
-
|
|
8737
|
-
|
|
8738
|
-
} else {
|
|
8739
|
-
limit = remotes.size;
|
|
8740
|
-
}
|
|
8741
|
-
if (this.telemetry) this.telemetry.quotaExcluded += remotes.size - limit;
|
|
8908
|
+
const fanout = remote.quota.fanout;
|
|
8909
|
+
const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
|
|
8910
|
+
this.counters.quotaExcluded += remotes.size - limit;
|
|
8742
8911
|
let peers = remotes.values();
|
|
8743
8912
|
while (sentCounter < limit) {
|
|
8744
8913
|
let c = peers.next().value;
|
|
@@ -8753,12 +8922,7 @@ class Manager {
|
|
|
8753
8922
|
// }
|
|
8754
8923
|
}
|
|
8755
8924
|
|
|
8756
|
-
|
|
8757
|
-
// // console.log(`pub >> [${tag}] sent: ${sentCounter} [use quota limit: ${remote.quota.publishCounter }] total: ${remotes.size} subscribers. ` )
|
|
8758
|
-
// } else {
|
|
8759
|
-
// // console.log(`pub >> [${tag}] sent: ${sentCounter} [no quota limit] total: ${remotes.size} subscribers. ` )
|
|
8760
|
-
// }
|
|
8761
|
-
if (this.telemetry) this.telemetry.deliveryAttempts += sentCounter;
|
|
8925
|
+
this.counters.deliveryAttempts += sentCounter;
|
|
8762
8926
|
return ['ok', sentCounter]
|
|
8763
8927
|
}
|
|
8764
8928
|
}
|
|
@@ -8768,6 +8932,123 @@ class Manager {
|
|
|
8768
8932
|
|
|
8769
8933
|
|
|
8770
8934
|
|
|
8935
|
+
// Retained messages are stored as exact-size copies (a subarray would keep a whole socket chunk
|
|
8936
|
+
// or 8 KiB Buffer pool slab alive), within an owner's budget and bytesTotal server-wide. A value
|
|
8937
|
+
// that cannot be stored (size, count or budget) also removes the value it would replace, so a
|
|
8938
|
+
// later subscriber never gets a stale one.
|
|
8939
|
+
retainFits(message, freed, ownerBytes, budget) {
|
|
8940
|
+
return this.retainOptions.limitSize > message.byteLength &&
|
|
8941
|
+
ownerBytes + message.byteLength <= budget &&
|
|
8942
|
+
this.retainBytes + message.byteLength - freed <= this.retainOptions.bytesTotal
|
|
8943
|
+
}
|
|
8944
|
+
|
|
8945
|
+
retainCopy(message) {
|
|
8946
|
+
const copy = Buffer.allocUnsafeSlow(message.byteLength);
|
|
8947
|
+
copy.set(message);
|
|
8948
|
+
this.retainBytes += copy.byteLength;
|
|
8949
|
+
return copy
|
|
8950
|
+
}
|
|
8951
|
+
|
|
8952
|
+
// A connection's CID retains go with it: within bytesPerConnection; limitCounter caps new tags.
|
|
8953
|
+
storeCidRetain(key, message, remote) {
|
|
8954
|
+
const map = remote.retain_signal;
|
|
8955
|
+
const old = map.get(key);
|
|
8956
|
+
const freed = old?.byteLength ?? 0;
|
|
8957
|
+
if ((old || map.size < this.retainOptions.limitCounter) &&
|
|
8958
|
+
this.retainFits(message, freed, remote.retainBytes - freed, this.retainOptions.bytesPerConnection)) {
|
|
8959
|
+
map.set(key, this.retainCopy(message));
|
|
8960
|
+
this.retainBytes -= freed;
|
|
8961
|
+
remote.retainBytes += message.byteLength - freed;
|
|
8962
|
+
} else if (old) {
|
|
8963
|
+
map.delete(key);
|
|
8964
|
+
this.retainBytes -= freed;
|
|
8965
|
+
remote.retainBytes -= freed;
|
|
8966
|
+
}
|
|
8967
|
+
}
|
|
8968
|
+
|
|
8969
|
+
// Channel retain owner: the last writer's account (an authenticated CID, shared by its
|
|
8970
|
+
// connections, so reconnecting does not reset its budget) or an anonymous writer's connection.
|
|
8971
|
+
// Each owner holds at most tagsPerOwner tags and bytesPerOwner bytes.
|
|
8972
|
+
retainOwner(key) {
|
|
8973
|
+
let owner = this.retainOwners.get(key);
|
|
8974
|
+
if (!owner) this.retainOwners.set(key, owner = { key, bytes: 0, tags: new Set() });
|
|
8975
|
+
return owner
|
|
8976
|
+
}
|
|
8977
|
+
|
|
8978
|
+
storeChannelRetain(tag, message, remote) {
|
|
8979
|
+
const owner = this.retainOwner(remote.boho.isAuthorized ? 'cid:' + remote.cid : 'conn:' + remote.ssid);
|
|
8980
|
+
const old = this.retain_messages.get(tag);
|
|
8981
|
+
const freed = old?.byteLength ?? 0;
|
|
8982
|
+
const room = old || (this.retain_messages.size < this.retainOptions.limitCounter &&
|
|
8983
|
+
owner.tags.size < this.retainOptions.tagsPerOwner);
|
|
8984
|
+
const ownerBytes = owner.bytes - (this.retain_owner.get(tag) === owner ? freed : 0);
|
|
8985
|
+
if (room && this.retainFits(message, freed, ownerBytes, this.retainOptions.bytesPerOwner)) {
|
|
8986
|
+
if (old) this.releaseChannelRetain(tag, freed);
|
|
8987
|
+
this.retain_messages.set(tag, this.retainCopy(message));
|
|
8988
|
+
owner.bytes += message.byteLength;
|
|
8989
|
+
owner.tags.add(tag);
|
|
8990
|
+
this.retain_owner.set(tag, owner);
|
|
8991
|
+
this.retainOwners.set(owner.key, owner); // releasing may have removed it when it emptied
|
|
8992
|
+
} else if (old) {
|
|
8993
|
+
this.dropChannelRetain(tag);
|
|
8994
|
+
}
|
|
8995
|
+
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
8996
|
+
}
|
|
8997
|
+
|
|
8998
|
+
// A closed anonymous connection's channel retains stay anonymousGraceMs in its network's pool
|
|
8999
|
+
// (by HOME_CHANNEL), which has the same owner budget: reconnecting cannot pile values up, and
|
|
9000
|
+
// when the pool is over budget the values closest to expiry go first, least recently written
|
|
9001
|
+
// first among equals (an update moves its tag to the end of the owner's set).
|
|
9002
|
+
orphanChannelRetains(remote) {
|
|
9003
|
+
const conn = this.retainOwners.get('conn:' + remote.ssid);
|
|
9004
|
+
if (!conn) return
|
|
9005
|
+
const grace = this.retainOptions.anonymousGraceMs;
|
|
9006
|
+
if (!(grace > 0)) {
|
|
9007
|
+
for (const tag of [...conn.tags]) this.dropChannelRetain(tag);
|
|
9008
|
+
return
|
|
9009
|
+
}
|
|
9010
|
+
this.retainOwners.delete(conn.key);
|
|
9011
|
+
const pool = this.retainOwner('net:' + remote.HOME_CHANNEL);
|
|
9012
|
+
const expires = node_perf_hooks.performance.now() + grace;
|
|
9013
|
+
for (const tag of conn.tags) {
|
|
9014
|
+
pool.tags.add(tag);
|
|
9015
|
+
pool.bytes += this.retain_messages.get(tag).byteLength;
|
|
9016
|
+
this.retain_owner.set(tag, pool);
|
|
9017
|
+
this.retainExpiry.set(tag, expires);
|
|
9018
|
+
}
|
|
9019
|
+
while (pool.bytes > this.retainOptions.bytesPerOwner || pool.tags.size > this.retainOptions.tagsPerOwner) {
|
|
9020
|
+
let first;
|
|
9021
|
+
for (const tag of pool.tags) {
|
|
9022
|
+
if (first === undefined || this.retainExpiry.get(tag) < this.retainExpiry.get(first)) first = tag;
|
|
9023
|
+
}
|
|
9024
|
+
this.dropChannelRetain(first);
|
|
9025
|
+
}
|
|
9026
|
+
}
|
|
9027
|
+
|
|
9028
|
+
expireChannelRetains(now = node_perf_hooks.performance.now()) {
|
|
9029
|
+
for (const [tag, expires] of this.retainExpiry) {
|
|
9030
|
+
if (expires <= now) this.dropChannelRetain(tag);
|
|
9031
|
+
}
|
|
9032
|
+
}
|
|
9033
|
+
|
|
9034
|
+
dropChannelRetain(tag) {
|
|
9035
|
+
const old = this.retain_messages.get(tag);
|
|
9036
|
+
if (!old) return
|
|
9037
|
+
this.releaseChannelRetain(tag, old.byteLength);
|
|
9038
|
+
this.retain_messages.delete(tag);
|
|
9039
|
+
}
|
|
9040
|
+
|
|
9041
|
+
releaseChannelRetain(tag, size) {
|
|
9042
|
+
const owner = this.retain_owner.get(tag);
|
|
9043
|
+
this.retain_owner.delete(tag);
|
|
9044
|
+
this.retainExpiry.delete(tag);
|
|
9045
|
+
this.retainBytes -= size;
|
|
9046
|
+
if (!owner) return
|
|
9047
|
+
owner.tags.delete(tag);
|
|
9048
|
+
owner.bytes -= size;
|
|
9049
|
+
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
9050
|
+
}
|
|
9051
|
+
|
|
8771
9052
|
subscribe(chArr, remote) {
|
|
8772
9053
|
chArr.forEach(tag => {
|
|
8773
9054
|
if (tag.indexOf('#') === 0) {
|
|
@@ -8790,7 +9071,7 @@ class Manager {
|
|
|
8790
9071
|
|
|
8791
9072
|
// 3. send retain message if available.
|
|
8792
9073
|
if (tag.includes('$')
|
|
8793
|
-
&&
|
|
9074
|
+
&& this.retainOptions.enabled
|
|
8794
9075
|
) {
|
|
8795
9076
|
let retainMessage;
|
|
8796
9077
|
if (tag.includes('@')) {
|
|
@@ -8856,31 +9137,6 @@ class Manager {
|
|
|
8856
9137
|
}
|
|
8857
9138
|
|
|
8858
9139
|
|
|
8859
|
-
monitor() {
|
|
8860
|
-
if (process.stdout.isTTY) {
|
|
8861
|
-
process.stdout.cursorTo(0, 0);
|
|
8862
|
-
process.stdout.clearScreenDown();
|
|
8863
|
-
}
|
|
8864
|
-
|
|
8865
|
-
if (serverOption.showChannel > 0) {
|
|
8866
|
-
this.metrics.channels(serverOption.showChannel);
|
|
8867
|
-
}
|
|
8868
|
-
let mode = parseInt(serverOption.showMetric);
|
|
8869
|
-
switch (mode) {
|
|
8870
|
-
case 1:
|
|
8871
|
-
this.metrics.oneline(true);
|
|
8872
|
-
break;
|
|
8873
|
-
case 2:
|
|
8874
|
-
this.metrics.getRemotes(true);
|
|
8875
|
-
break;
|
|
8876
|
-
case 3:
|
|
8877
|
-
this.metrics.getChannelList(true);
|
|
8878
|
-
break;
|
|
8879
|
-
}
|
|
8880
|
-
|
|
8881
|
-
}
|
|
8882
|
-
|
|
8883
|
-
|
|
8884
9140
|
anonymousCidRandom(size) {
|
|
8885
9141
|
return globalThis.crypto.getRandomValues(Buffer.alloc(size))
|
|
8886
9142
|
}
|
|
@@ -8913,8 +9169,8 @@ class Manager {
|
|
|
8913
9169
|
clearTimeout(this.pingIntervalID);
|
|
8914
9170
|
this.heartbeatPending.clear();
|
|
8915
9171
|
for (const group of this.pingGroups) group.clear();
|
|
8916
|
-
if (this.
|
|
8917
|
-
clearInterval(this.
|
|
9172
|
+
if (this.statsIntervalID) {
|
|
9173
|
+
clearInterval(this.statsIntervalID);
|
|
8918
9174
|
}
|
|
8919
9175
|
|
|
8920
9176
|
this.remotes.forEach(remote => {
|
|
@@ -8924,6 +9180,10 @@ class Manager {
|
|
|
8924
9180
|
this.remotes.clear();
|
|
8925
9181
|
this.cid2remote.clear();
|
|
8926
9182
|
this.retain_messages.clear();
|
|
9183
|
+
this.retain_owner.clear();
|
|
9184
|
+
this.retainOwners.clear();
|
|
9185
|
+
this.retainExpiry.clear();
|
|
9186
|
+
this.retainBytes = 0;
|
|
8927
9187
|
this.channel_map.clear();
|
|
8928
9188
|
|
|
8929
9189
|
}
|
|
@@ -8948,15 +9208,42 @@ function validateDuplicateLogin(policy) {
|
|
|
8948
9208
|
return policy
|
|
8949
9209
|
}
|
|
8950
9210
|
|
|
9211
|
+
// Connection roles, lowest to highest: what a connection may do. Its quota is separate.
|
|
9212
|
+
// 'anonymous' is the role of every connection until it authenticates.
|
|
9213
|
+
const ROLES = ['anonymous', 'device', 'service', 'admin'];
|
|
9214
|
+
|
|
9215
|
+
/** Role of a login: the account's role, 'device' when it has none; undefined if unknown. */
|
|
9216
|
+
function resolveRole(role) {
|
|
9217
|
+
if (role === undefined || role === null || role === '') return 'device'
|
|
9218
|
+
return ROLES.includes(role) && role !== 'anonymous' ? role : undefined
|
|
9219
|
+
}
|
|
9220
|
+
|
|
9221
|
+
/** True if the remote is authenticated with this role or a higher one ('anonymous': always). */
|
|
9222
|
+
function hasRole(remote, role) {
|
|
9223
|
+
const wanted = ROLES.indexOf(role);
|
|
9224
|
+
if (wanted < 0) throw new RangeError(`role must be one of: ${ROLES.join(', ')}`)
|
|
9225
|
+
if (wanted === 0) return true
|
|
9226
|
+
return remote?.boho?.isAuthorized === true && ROLES.indexOf(remote.role) >= wanted
|
|
9227
|
+
}
|
|
9228
|
+
|
|
9229
|
+
/** Default quota profile of a login: the account's quota, else 'basic' for a device, 'unlimited' otherwise. */
|
|
9230
|
+
function defaultQuota(authInfo, role) {
|
|
9231
|
+
return authInfo.quota || (role === 'device' ? 'basic' : 'unlimited')
|
|
9232
|
+
}
|
|
9233
|
+
|
|
8951
9234
|
class BohoAuth {
|
|
8952
9235
|
/**
|
|
8953
9236
|
* @param {object} keyProvider
|
|
8954
|
-
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any
|
|
9237
|
+
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any,
|
|
9238
|
+
* resolveQuota?: (authInfo: object, role: string) => string | Promise<string> }} [options]
|
|
8955
9239
|
* duplicateLogin: unset follows serverOption.auth.duplicateLogin (default 'keepNew').
|
|
9240
|
+
* A Server's duplicateLogin option takes precedence for that Server's connections.
|
|
8956
9241
|
* onAuthEvent: called with { type, did, cid, uid, ip, oldIp, socketType, oldSocketType, reason, at }
|
|
8957
9242
|
* for 'replaced' (keepNew evicted the old connection) and 'duplicate_rejected' (keepOld).
|
|
8958
9243
|
* socketType/oldSocketType are 'websocket' or 'congsocket'.
|
|
8959
9244
|
* Errors and rejected promises are logged and never affect authentication.
|
|
9245
|
+
* resolveQuota: name of the Server quota profile for a login (default: defaultQuota), e.g. from
|
|
9246
|
+
* the account owner's plan. An unknown name fails the login.
|
|
8960
9247
|
*/
|
|
8961
9248
|
constructor(keyProvider, options = {}) {
|
|
8962
9249
|
if (!keyProvider) {
|
|
@@ -8966,6 +9253,7 @@ class BohoAuth {
|
|
|
8966
9253
|
this._duplicateLogin = null;
|
|
8967
9254
|
if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
|
|
8968
9255
|
this.onAuthEvent = options.onAuthEvent ?? null;
|
|
9256
|
+
this.resolveQuota = options.resolveQuota ?? defaultQuota;
|
|
8969
9257
|
this.authLogger;
|
|
8970
9258
|
if (serverOption.fileLogger.auth.use) {
|
|
8971
9259
|
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
@@ -8983,6 +9271,11 @@ class BohoAuth {
|
|
|
8983
9271
|
this._duplicateLogin = policy === null ? null : validateDuplicateLogin(policy);
|
|
8984
9272
|
}
|
|
8985
9273
|
|
|
9274
|
+
/** Policy for a connection: its Server's duplicateLogin option, else this instance's policy. */
|
|
9275
|
+
duplicateLoginFor(peer) {
|
|
9276
|
+
return peer.manager?.server?.duplicateLogin ?? this.duplicateLogin;
|
|
9277
|
+
}
|
|
9278
|
+
|
|
8986
9279
|
// Backward-compatible boolean form of duplicateLogin.
|
|
8987
9280
|
get keepOldConnection() {
|
|
8988
9281
|
return this.duplicateLogin === 'keepOld';
|
|
@@ -9015,7 +9308,7 @@ class BohoAuth {
|
|
|
9015
9308
|
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
9016
9309
|
peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
9017
9310
|
}
|
|
9018
|
-
}, serverOption.auth.
|
|
9311
|
+
}, serverOption.auth.failDelay);
|
|
9019
9312
|
}
|
|
9020
9313
|
|
|
9021
9314
|
|
|
@@ -9049,8 +9342,9 @@ class BohoAuth {
|
|
|
9049
9342
|
return
|
|
9050
9343
|
}
|
|
9051
9344
|
|
|
9345
|
+
// Never the key: debug output ends up in shared logs.
|
|
9052
9346
|
if (serverOption.debug.showAuthInfo) {
|
|
9053
|
-
console.log('[debug]showAuthInfo', authInfo);
|
|
9347
|
+
console.log('[debug]showAuthInfo', { id, cid: authInfo.cid, uid: authInfo.uid, role: authInfo.role, quota: authInfo.quota });
|
|
9054
9348
|
}
|
|
9055
9349
|
|
|
9056
9350
|
peer.boho.copy_id8(infoPack.id8);
|
|
@@ -9077,7 +9371,29 @@ class BohoAuth {
|
|
|
9077
9371
|
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9078
9372
|
peer._challengeUsed = true;
|
|
9079
9373
|
|
|
9080
|
-
//4.
|
|
9374
|
+
//4. role and quota. Checked before a duplicate login replaces the old connection.
|
|
9375
|
+
const role = resolveRole(authInfo.role);
|
|
9376
|
+
if (role === undefined) {
|
|
9377
|
+
this.send_auth_fail(peer, 'unknown auth.role: ' + authInfo.role);
|
|
9378
|
+
return
|
|
9379
|
+
}
|
|
9380
|
+
const quotaName = await this.resolveQuota(authInfo, role);
|
|
9381
|
+
const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
|
|
9382
|
+
if (!quota) {
|
|
9383
|
+
this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
|
|
9384
|
+
return
|
|
9385
|
+
}
|
|
9386
|
+
if (peer._closing) return; // closed while resolving
|
|
9387
|
+
const uid = authInfo.uid || null;
|
|
9388
|
+
if (uid && quota.maxConnections !== null) {
|
|
9389
|
+
// A connection this login replaces (keepNew) frees its place.
|
|
9390
|
+
const old = peer.manager.cid2remote.get(authInfo.cid);
|
|
9391
|
+
const replaced = old && old !== peer && old.accountUid === uid && this.duplicateLoginFor(peer) === 'keepNew' ? 1 : 0;
|
|
9392
|
+
if (peer.manager.accountConnections(uid) - replaced >= quota.maxConnections) {
|
|
9393
|
+
this.send_auth_fail(peer, 'too many connections');
|
|
9394
|
+
return
|
|
9395
|
+
}
|
|
9396
|
+
}
|
|
9081
9397
|
|
|
9082
9398
|
//5. check duplicate login.
|
|
9083
9399
|
if (peer.manager.cid2remote.has(authInfo.cid) && peer.manager.cid2remote.get(authInfo.cid) !== peer) {
|
|
@@ -9089,7 +9405,8 @@ class BohoAuth {
|
|
|
9089
9405
|
$$1.MB('#MsgType', '8', IOMsg.AUTH_CLEAR),
|
|
9090
9406
|
$$1.MB('#reason', 'duplicate login.')
|
|
9091
9407
|
);
|
|
9092
|
-
|
|
9408
|
+
const keepOld = this.duplicateLoginFor(peer) === 'keepOld';
|
|
9409
|
+
if (keepOld) {
|
|
9093
9410
|
peer.boho.isAuthorized = false;
|
|
9094
9411
|
// keep old connection. reject new connection by sending auth_fail signal.
|
|
9095
9412
|
// peer.send(authClearSignal)
|
|
@@ -9105,13 +9422,13 @@ class BohoAuth {
|
|
|
9105
9422
|
old.close();
|
|
9106
9423
|
}
|
|
9107
9424
|
this.emitAuthEvent({
|
|
9108
|
-
type:
|
|
9425
|
+
type: keepOld ? 'duplicate_rejected' : 'replaced',
|
|
9109
9426
|
did: id, cid: authInfo.cid, uid: authInfo.uid || null,
|
|
9110
9427
|
ip: peer.ip, oldIp: old.ip,
|
|
9111
9428
|
socketType: transportOf(peer), oldSocketType: transportOf(old),
|
|
9112
9429
|
reason: 'duplicate login', at: Date.now()
|
|
9113
9430
|
});
|
|
9114
|
-
if (
|
|
9431
|
+
if (keepOld) return
|
|
9115
9432
|
}
|
|
9116
9433
|
|
|
9117
9434
|
//6. delete current (or anonymouse)cid if exist.
|
|
@@ -9126,26 +9443,11 @@ class BohoAuth {
|
|
|
9126
9443
|
peer.nick = authInfo.cid; // temporary: nick as cid
|
|
9127
9444
|
if (authInfo.uid) peer.uid = authInfo.uid;
|
|
9128
9445
|
|
|
9129
|
-
//8.
|
|
9130
|
-
|
|
9131
|
-
if (
|
|
9132
|
-
|
|
9133
|
-
|
|
9134
|
-
if (!newQuota) {
|
|
9135
|
-
let err = 'no index quotaTable for auth.level: ' + quotaLevel;
|
|
9136
|
-
this.send_auth_fail(peer, err);
|
|
9137
|
-
return
|
|
9138
|
-
} else {
|
|
9139
|
-
peer.level = quotaLevel;
|
|
9140
|
-
peer.quota = newQuota;
|
|
9141
|
-
}
|
|
9142
|
-
|
|
9143
|
-
if (peer.level === serverOption.adminLevel) {
|
|
9144
|
-
console.log('## LOGIN ADMIN CID:', peer.cid);
|
|
9145
|
-
peer.isAdmin = true;
|
|
9146
|
-
}
|
|
9147
|
-
// send quota.level
|
|
9148
|
-
peer.send(Buffer.from([IOMsg.QUOTA_LEVEL, quotaLevel]));
|
|
9446
|
+
//8. role and quota; the client is told its quota.
|
|
9447
|
+
peer.role = role;
|
|
9448
|
+
if (role === 'admin') console.log('## LOGIN ADMIN CID:', peer.cid);
|
|
9449
|
+
if (uid) peer.manager.addAccountConnection(peer, uid);
|
|
9450
|
+
peer.setQuota(quotaName, true);
|
|
9149
9451
|
|
|
9150
9452
|
//9. set cid2remote
|
|
9151
9453
|
peer.manager.cid2remote.set(peer.cid, peer);
|
|
@@ -9174,9 +9476,9 @@ class BohoAuth {
|
|
|
9174
9476
|
}
|
|
9175
9477
|
}
|
|
9176
9478
|
|
|
9177
|
-
async addAuth(id, keyStr, cid,
|
|
9479
|
+
async addAuth(id, keyStr, cid, role, quota) {
|
|
9178
9480
|
if (typeof this.keyProvider.addAuth === 'function') {
|
|
9179
|
-
return this.keyProvider.addAuth(id, keyStr, cid,
|
|
9481
|
+
return this.keyProvider.addAuth(id, keyStr, cid, role, quota);
|
|
9180
9482
|
}
|
|
9181
9483
|
}
|
|
9182
9484
|
|
|
@@ -9195,59 +9497,228 @@ class BohoAuth {
|
|
|
9195
9497
|
|
|
9196
9498
|
}
|
|
9197
9499
|
|
|
9500
|
+
/**
|
|
9501
|
+
* LocalKeyProvider.js
|
|
9502
|
+
*
|
|
9503
|
+
* Key provider for local testing: no key list, every non-empty ID logs in with its own ID as CID.
|
|
9504
|
+
*
|
|
9505
|
+
* mode 'idKey': the key equals the ID, e.g. io.auth('dev1', 'dev1').
|
|
9506
|
+
* mode 'sharedKey': any ID with the one shared key, e.g. io.auth('dev1', 'lab2026').
|
|
9507
|
+
* role: role of every login, default 'device' ('service' or 'admin' must be asked for).
|
|
9508
|
+
* quota: Server quotas profile of every login, default from BohoAuth resolveQuota.
|
|
9509
|
+
*
|
|
9510
|
+
* example => new BohoAuth(new LocalKeyProvider({ mode: 'sharedKey', key: 'lab2026' }))
|
|
9511
|
+
*
|
|
9512
|
+
* Anyone who knows the rule logs in under any ID, so use it only on a trusted local network.
|
|
9513
|
+
*/
|
|
9514
|
+
|
|
9515
|
+
|
|
9516
|
+
const MODES = ['idKey', 'sharedKey'];
|
|
9517
|
+
const hashKey = keyStr => Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9518
|
+
|
|
9519
|
+
class LocalKeyProvider {
|
|
9520
|
+
/**
|
|
9521
|
+
* @param {'idKey' | { mode: 'idKey' | 'sharedKey', key?: string,
|
|
9522
|
+
* role?: 'device' | 'service' | 'admin', quota?: string }} options
|
|
9523
|
+
* A string is the mode alone.
|
|
9524
|
+
*/
|
|
9525
|
+
constructor(options) {
|
|
9526
|
+
const { mode, key, role = 'device', quota } = typeof options === 'string' ? { mode: options } : (options ?? {});
|
|
9527
|
+
if (!MODES.includes(mode)) {
|
|
9528
|
+
throw new TypeError(`LocalKeyProvider mode must be one of: ${MODES.join(', ')}`)
|
|
9529
|
+
}
|
|
9530
|
+
if (mode === 'sharedKey' && (typeof key !== 'string' || key.length === 0)) {
|
|
9531
|
+
throw new TypeError("LocalKeyProvider mode 'sharedKey' needs a non-empty key")
|
|
9532
|
+
}
|
|
9533
|
+
if (quota !== undefined && (typeof quota !== 'string' || !quota)) {
|
|
9534
|
+
throw new TypeError('LocalKeyProvider quota must be a quotas profile name')
|
|
9535
|
+
}
|
|
9536
|
+
if (!ROLES.includes(role) || role === 'anonymous') {
|
|
9537
|
+
throw new RangeError(`LocalKeyProvider role must be one of: ${ROLES.slice(1).join(', ')}`)
|
|
9538
|
+
}
|
|
9539
|
+
this.mode = mode;
|
|
9540
|
+
this.role = role;
|
|
9541
|
+
this.quota = quota;
|
|
9542
|
+
// Hashed like StringKeyProvider, so a 44-character shared key is not mistaken for a stored hash.
|
|
9543
|
+
this.sharedKeyHash = mode === 'sharedKey' ? hashKey(key) : null;
|
|
9544
|
+
}
|
|
9545
|
+
|
|
9546
|
+
async getAuth(id) {
|
|
9547
|
+
if (!id) return undefined
|
|
9548
|
+
return {
|
|
9549
|
+
key: this.sharedKeyHash ?? hashKey(id),
|
|
9550
|
+
cid: id,
|
|
9551
|
+
role: this.role,
|
|
9552
|
+
...(this.quota && { quota: this.quota })
|
|
9553
|
+
}
|
|
9554
|
+
}
|
|
9555
|
+
}
|
|
9556
|
+
|
|
9557
|
+
// Removed or renamed in 9.0, as Server options and as serverOption keys ('global': only as a
|
|
9558
|
+
// serverOption key). An error names the replacement instead of the setting silently doing nothing.
|
|
9559
|
+
const REMOVED = [
|
|
9560
|
+
['showMessage', 'logMessages: true'],
|
|
9561
|
+
['showMetric', "logStats: <interval ms> (for lists, the sudo service's remotes/channels commands)"],
|
|
9562
|
+
['monitorPeriod', 'logStats: <interval ms>'],
|
|
9563
|
+
['timeout', 'heartbeatInterval'],
|
|
9564
|
+
['pingTimeoutGrace', 'heartbeatGrace'],
|
|
9565
|
+
['retain.isAvailable', 'retain.enabled'],
|
|
9566
|
+
['useQuota', 'quotas: named quota profiles, always enforced (null: unlimited)'],
|
|
9567
|
+
['defaultQuotaIndex', "anonymousQuota: a quotas profile name; logins use their account's quota"],
|
|
9568
|
+
['auth.delay_auth_fail', 'auth.failDelay', 'global'],
|
|
9569
|
+
['adminLevel', "role: 'admin' in the account (key entry)", 'global'],
|
|
9570
|
+
['clientTracking', 'nothing: it was never used', 'global'],
|
|
9571
|
+
...['port', 'congPort', 'httpServer', 'wsPath'].map(name => [name, `new Server({ ${name} })`, 'global'])
|
|
9572
|
+
];
|
|
9573
|
+
const lookup = (object, path) => path.split('.').reduce((value, key) => value?.[key], object);
|
|
9574
|
+
|
|
9575
|
+
function checkRemoved(options) {
|
|
9576
|
+
for (const [path, replacement, scope] of REMOVED) {
|
|
9577
|
+
const sources = scope === 'global' ? [['serverOption.', serverOption]] : [['', options], ['serverOption.', serverOption]];
|
|
9578
|
+
for (const [prefix, source] of sources) {
|
|
9579
|
+
if (lookup(source, path) !== undefined) {
|
|
9580
|
+
throw new TypeError(`${prefix}${path} was removed in iosignal 9.0; use ${replacement}`)
|
|
9581
|
+
}
|
|
9582
|
+
}
|
|
9583
|
+
}
|
|
9584
|
+
}
|
|
9585
|
+
|
|
9586
|
+
const MAX_TIMER_MS = 2147483647; // setTimeout limit
|
|
9587
|
+
|
|
9588
|
+
function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
9589
|
+
if (!Number.isSafeInteger(value) || value < min || value > max) {
|
|
9590
|
+
throw new RangeError(`${name} must be an integer from ${min} to ${max}`)
|
|
9591
|
+
}
|
|
9592
|
+
return value
|
|
9593
|
+
}
|
|
9594
|
+
const positive = (name, value) => integer(name, value, 1);
|
|
9595
|
+
const nonNegative = (name, value) => integer(name, value, 0);
|
|
9596
|
+
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
|
|
9597
|
+
|
|
9598
|
+
// This Server's quota profiles: the defaults with each given profile merged over its default
|
|
9599
|
+
// (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
|
|
9600
|
+
function quotaProfiles(given) {
|
|
9601
|
+
if (given !== undefined && (given === null || typeof given !== 'object')) {
|
|
9602
|
+
throw new TypeError('quotas must be an object')
|
|
9603
|
+
}
|
|
9604
|
+
const profiles = {};
|
|
9605
|
+
for (const name of new Set([...Object.keys(serverOption.quotas), ...Object.keys(given ?? {})])) {
|
|
9606
|
+
const profile = given?.[name];
|
|
9607
|
+
if (profile !== undefined && (profile === null || typeof profile !== 'object')) {
|
|
9608
|
+
throw new TypeError(`quotas.${name} must be an object`)
|
|
9609
|
+
}
|
|
9610
|
+
for (const key of Object.keys(profile ?? {})) {
|
|
9611
|
+
if (!QUOTA_LIMITS.includes(key)) throw new TypeError(`unknown option quotas.${name}.${key}`)
|
|
9612
|
+
}
|
|
9613
|
+
const base = serverOption.quotas[name] ?? Object.fromEntries(QUOTA_LIMITS.map(key => [key, null]));
|
|
9614
|
+
profiles[name] = { ...base, ...profile };
|
|
9615
|
+
for (const key of QUOTA_LIMITS) {
|
|
9616
|
+
if (profiles[name][key] !== null) positive(`quotas.${name}.${key}`, profiles[name][key]);
|
|
9617
|
+
}
|
|
9618
|
+
}
|
|
9619
|
+
return profiles
|
|
9620
|
+
}
|
|
9621
|
+
function boolean(name, value) {
|
|
9622
|
+
if (typeof value !== 'boolean') throw new TypeError(`${name} must be a boolean`)
|
|
9623
|
+
return value
|
|
9624
|
+
}
|
|
9625
|
+
|
|
9626
|
+
// A nested option group: this Server's own copy of the serverOption defaults with its options
|
|
9627
|
+
// applied. Unknown keys are errors, so a typo does not silently do nothing.
|
|
9628
|
+
function group(name, given, checks) {
|
|
9629
|
+
if (given !== undefined && (given === null || typeof given !== 'object')) {
|
|
9630
|
+
throw new TypeError(`${name} must be an object`)
|
|
9631
|
+
}
|
|
9632
|
+
for (const key of Object.keys(given ?? {})) {
|
|
9633
|
+
if (!(key in checks)) throw new TypeError(`unknown option ${name}.${key}`)
|
|
9634
|
+
}
|
|
9635
|
+
const merged = { ...serverOption[name], ...given };
|
|
9636
|
+
for (const [key, check] of Object.entries(checks)) check(`${name}.${key}`, merged[key]);
|
|
9637
|
+
return merged
|
|
9638
|
+
}
|
|
9639
|
+
|
|
9640
|
+
function resolveLogStats(value) {
|
|
9641
|
+
if (value === 0 || value === false) return 0
|
|
9642
|
+
return integer('logStats', value, 1000, MAX_TIMER_MS)
|
|
9643
|
+
}
|
|
9644
|
+
|
|
9198
9645
|
class Server extends require$$0$3 {
|
|
9199
9646
|
|
|
9200
9647
|
/**
|
|
9201
9648
|
* @param {object} options Server configuration.
|
|
9649
|
+
* options.localAuth: login without a key list, for local testing. 'idKey' (key = ID) or
|
|
9650
|
+
* { mode: 'idKey' | 'sharedKey', key, role, quota } (see LocalKeyProvider); the CID is the ID.
|
|
9651
|
+
* Cannot be combined with authManager.
|
|
9652
|
+
* Every other setting is this Server's own: given here, else the serverOption default, which is
|
|
9653
|
+
* never modified. Nested groups (security, retain, quotas) are merged over their defaults;
|
|
9654
|
+
* unknown or removed names are errors.
|
|
9655
|
+
* options.heartbeatInterval: ms between liveness checks (default 50000).
|
|
9656
|
+
* options.heartbeatGrace: extra ms a peer has to answer before it is closed (default 5000).
|
|
9657
|
+
* options.trustProxy: when X-Forwarded-For/-Proto are used. 'private' (default) only from a
|
|
9658
|
+
* loopback/private peer, true always, false never, or N trusted proxy hops.
|
|
9659
|
+
* options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
|
|
9660
|
+
* options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
|
|
9661
|
+
* options.membersOnly: drop signals from connections that are not authenticated.
|
|
9662
|
+
* options.logMessages: log each received message after decryption: type and tag, never the payload.
|
|
9663
|
+
* options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
|
|
9664
|
+
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
|
|
9665
|
+
* options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
|
|
9666
|
+
* options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
|
|
9667
|
+
* maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
9668
|
+
* Adjustable later on server.quotas. The client is told its maxMessageBytes.
|
|
9669
|
+
* options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
|
|
9670
|
+
* options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
|
|
9671
|
+
* manager's own policy without changing it, so an auth manager can be shared between servers.
|
|
9672
|
+
* A failed listen (e.g. EADDRINUSE) is emitted as 'error'.
|
|
9202
9673
|
* @param {any} [authManager] Optional authentication manager.
|
|
9203
9674
|
*/
|
|
9204
9675
|
constructor(options, authManager) {
|
|
9205
9676
|
super();
|
|
9206
|
-
|
|
9207
|
-
|
|
9208
|
-
|
|
9209
|
-
|
|
9210
|
-
|
|
9211
|
-
|
|
9212
|
-
|
|
9677
|
+
if (options.localAuth !== undefined && options.localAuth !== null) {
|
|
9678
|
+
if (authManager) throw new TypeError('localAuth cannot be combined with an authManager')
|
|
9679
|
+
authManager = new BohoAuth(new LocalKeyProvider(options.localAuth));
|
|
9680
|
+
}
|
|
9681
|
+
// Each Server resolves its settings once, here: serverOption only supplies the defaults and is
|
|
9682
|
+
// never written, so servers in one process do not affect each other.
|
|
9683
|
+
checkRemoved(options);
|
|
9684
|
+
this.security = Object.freeze(group('security', options.security,
|
|
9685
|
+
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
|
|
9686
|
+
// retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
|
|
9687
|
+
this.retain = group('retain', options.retain, {
|
|
9688
|
+
enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
|
|
9689
|
+
bytesPerOwner: positive, anonymousGraceMs: nonNegative, bytesPerConnection: positive, bytesTotal: positive });
|
|
9690
|
+
this.quotas = quotaProfiles(options.quotas);
|
|
9691
|
+
this.anonymousQuota = options.anonymousQuota ?? serverOption.anonymousQuota;
|
|
9692
|
+
if (!Object.hasOwn(this.quotas, this.anonymousQuota)) {
|
|
9693
|
+
throw new RangeError(`anonymousQuota must be one of the quotas: ${Object.keys(this.quotas).join(', ')}`)
|
|
9694
|
+
}
|
|
9695
|
+
this.heartbeatInterval = integer('heartbeatInterval',
|
|
9696
|
+
options.heartbeatInterval ?? serverOption.heartbeatInterval, 1, MAX_TIMER_MS);
|
|
9697
|
+
this.heartbeatGrace = integer('heartbeatGrace', options.heartbeatGrace ?? serverOption.heartbeatGrace, 0, MAX_TIMER_MS);
|
|
9698
|
+
this.maxPayload = positive('maxPayload', options.maxPayload ?? serverOption.maxPayload);
|
|
9699
|
+
this.maxBufferedBytes = positive('maxBufferedBytes', options.maxBufferedBytes ?? serverOption.maxBufferedBytes);
|
|
9700
|
+
this.logMessages = boolean('logMessages', options.logMessages ?? serverOption.logMessages);
|
|
9701
|
+
this.logStats = resolveLogStats(options.logStats ?? serverOption.logStats);
|
|
9702
|
+
this.trustProxy = options.trustProxy ?? serverOption.trustProxy;
|
|
9703
|
+
if (![true, false, 'private'].includes(this.trustProxy) &&
|
|
9704
|
+
!(Number.isSafeInteger(this.trustProxy) && this.trustProxy > 0)) {
|
|
9705
|
+
throw new RangeError("trustProxy must be true, false, 'private' or a positive integer");
|
|
9706
|
+
}
|
|
9707
|
+
this.membersOnly = boolean('membersOnly', options.membersOnly ?? serverOption.membersOnly);
|
|
9213
9708
|
this.serviceNames = new Set();
|
|
9214
9709
|
this.services = new Map(); // name -> service module (for lifecycle hooks)
|
|
9215
|
-
|
|
9710
|
+
// Stays null for a CongSocket-only server, so close() does not wait on a WebSocket server.
|
|
9711
|
+
this.wss = null;
|
|
9216
9712
|
this.port = null;
|
|
9217
9713
|
this.congPort = null;
|
|
9218
9714
|
|
|
9219
|
-
|
|
9220
|
-
|
|
9221
|
-
|
|
9222
|
-
}
|
|
9223
|
-
serverOption.pingTimeoutGrace = options.pingTimeoutGrace;
|
|
9224
|
-
}
|
|
9225
|
-
|
|
9226
|
-
if (options.timeout) {
|
|
9227
|
-
let pingT = parseInt(options.timeout);
|
|
9228
|
-
if (pingT && pingT >= 1000) serverOption.timeout = pingT;
|
|
9229
|
-
}
|
|
9230
|
-
if (options.monitorPeriod) {
|
|
9231
|
-
let monitorT = parseInt(options.monitorPeriod);
|
|
9232
|
-
if (monitorT && monitorT >= 1000) serverOption.monitorPeriod = monitorT;
|
|
9233
|
-
}
|
|
9234
|
-
if (options.showMessage) {
|
|
9235
|
-
serverOption.showMessage = options.showMessage;
|
|
9236
|
-
}
|
|
9237
|
-
if (options.showMetric) {
|
|
9238
|
-
serverOption.showMetric = options.showMetric;
|
|
9239
|
-
}
|
|
9240
|
-
if (options.membersOnly) {
|
|
9241
|
-
serverOption.membersOnly = options.membersOnly;
|
|
9242
|
-
}
|
|
9243
|
-
// Applies to this server's auth manager only; without auth there are no duplicate logins.
|
|
9715
|
+
// Read by the auth manager for this server's connections; the auth manager itself is not
|
|
9716
|
+
// changed, since it may be shared. null: the auth manager's own policy.
|
|
9717
|
+
this.duplicateLogin = null;
|
|
9244
9718
|
if (options.duplicateLogin !== undefined) {
|
|
9245
|
-
validateDuplicateLogin(options.duplicateLogin);
|
|
9246
|
-
if (authManager) {
|
|
9247
|
-
|
|
9248
|
-
throw new TypeError('duplicateLogin: the auth manager does not support this option')
|
|
9249
|
-
}
|
|
9250
|
-
authManager.duplicateLogin = options.duplicateLogin;
|
|
9719
|
+
this.duplicateLogin = validateDuplicateLogin(options.duplicateLogin);
|
|
9720
|
+
if (authManager && !('duplicateLogin' in authManager)) {
|
|
9721
|
+
throw new TypeError('duplicateLogin: the auth manager does not support this option')
|
|
9251
9722
|
}
|
|
9252
9723
|
}
|
|
9253
9724
|
|
|
@@ -9288,9 +9759,9 @@ class Server extends require$$0$3 {
|
|
|
9288
9759
|
startWSServer() {
|
|
9289
9760
|
// console.log('optoins', options )
|
|
9290
9761
|
if (this.port || this.port == 0) {
|
|
9291
|
-
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath });
|
|
9762
|
+
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath, maxPayload: this.maxPayload });
|
|
9292
9763
|
} else if (this.httpServer ) {
|
|
9293
|
-
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath });
|
|
9764
|
+
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath, maxPayload: this.maxPayload });
|
|
9294
9765
|
} else {
|
|
9295
9766
|
throw new TypeError(
|
|
9296
9767
|
'One and only one of the "port", "httpServer"' +
|
|
@@ -9308,12 +9779,7 @@ class Server extends require$$0$3 {
|
|
|
9308
9779
|
});
|
|
9309
9780
|
|
|
9310
9781
|
// this.wss.setMaxListeners(0)
|
|
9311
|
-
this.wss.on('error', (err) =>
|
|
9312
|
-
console.error('### ws server error:', err.message);
|
|
9313
|
-
if (err.code == 'EADDRINUSE') {
|
|
9314
|
-
process.exit();
|
|
9315
|
-
}
|
|
9316
|
-
});
|
|
9782
|
+
this.wss.on('error', (err) => this.onListenerError('ws', err));
|
|
9317
9783
|
|
|
9318
9784
|
this.wss.on('close', () => {
|
|
9319
9785
|
// console.log('### WS server is closed.')
|
|
@@ -9333,12 +9799,8 @@ class Server extends require$$0$3 {
|
|
|
9333
9799
|
socket.setNoDelay(true);
|
|
9334
9800
|
this.manager.addRemote(socket);
|
|
9335
9801
|
})
|
|
9336
|
-
.on('error', (err) =>
|
|
9337
|
-
|
|
9338
|
-
if (err.code == 'EADDRINUSE') {
|
|
9339
|
-
process.exit();
|
|
9340
|
-
}
|
|
9341
|
-
}).on('close', () => {
|
|
9802
|
+
.on('error', (err) => this.onListenerError('cong', err))
|
|
9803
|
+
.on('close', () => {
|
|
9342
9804
|
// console.log('### congsocket server is closed.')
|
|
9343
9805
|
}).listen(this.congPort, () => {
|
|
9344
9806
|
this.congPort = this.congServer.address().port;
|
|
@@ -9350,6 +9812,26 @@ class Server extends require$$0$3 {
|
|
|
9350
9812
|
});
|
|
9351
9813
|
}
|
|
9352
9814
|
|
|
9815
|
+
// A failed listen (e.g. EADDRINUSE) is the application's to handle: emitted as 'error',
|
|
9816
|
+
// which, like any EventEmitter, throws when nothing listens. Other errors are logged.
|
|
9817
|
+
onListenerError(name, err) {
|
|
9818
|
+
console.error(`### ${name} server error:`, err.message);
|
|
9819
|
+
if (err.syscall === 'listen') this.emit('error', err);
|
|
9820
|
+
}
|
|
9821
|
+
|
|
9822
|
+
/**
|
|
9823
|
+
* Current server state, for monitoring. counters are cumulative since the server started
|
|
9824
|
+
* (rates are the reader's to compute from two snapshots). Enumerates connections once.
|
|
9825
|
+
* @returns {{ at: number, connections: { total: number, authenticated: number, anonymous: number,
|
|
9826
|
+
* websocket: number, tcp: number }, channels: number, retained: { channel: number, bytes: number },
|
|
9827
|
+
* counters: { rxMessages: number, rxBytes: number, txMessages: number, txBytes: number,
|
|
9828
|
+
* publishes: number, deliveryAttempts: number, quotaExcluded: number, peerRxLimitSkipped: number },
|
|
9829
|
+
* memory: { rss: number, heapUsed: number } }}
|
|
9830
|
+
*/
|
|
9831
|
+
stats() {
|
|
9832
|
+
return this.manager.metrics.snapshot()
|
|
9833
|
+
}
|
|
9834
|
+
|
|
9353
9835
|
/**
|
|
9354
9836
|
* RPC service register.
|
|
9355
9837
|
* service: service_name <string>
|
|
@@ -9503,9 +9985,10 @@ class FileKeyProvider {
|
|
|
9503
9985
|
return Array.from(this.AUTH.keys())
|
|
9504
9986
|
}
|
|
9505
9987
|
|
|
9506
|
-
|
|
9988
|
+
// Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
|
|
9989
|
+
addAuth(id, keyStr, cid, role, quota) {
|
|
9507
9990
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9508
|
-
this.AUTH.set(id, { key: Base64hashKey, cid
|
|
9991
|
+
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
9509
9992
|
}
|
|
9510
9993
|
}
|
|
9511
9994
|
|
|
@@ -9540,9 +10023,13 @@ class RedisKeyProvider {
|
|
|
9540
10023
|
}
|
|
9541
10024
|
|
|
9542
10025
|
// add device auth info
|
|
9543
|
-
|
|
10026
|
+
// role and quota are optional (see StringKeyProvider); an omitted one is not stored.
|
|
10027
|
+
async addAuth(id, keyStr, cid = '', role, quota) {
|
|
9544
10028
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9545
|
-
|
|
10029
|
+
const fields = { 'key': Base64hashKey, 'cid': cid };
|
|
10030
|
+
if (role) fields.role = role;
|
|
10031
|
+
if (quota) fields.quota = quota;
|
|
10032
|
+
return this.redis.hSet(DEVICE_PREFIX + id, fields)
|
|
9546
10033
|
}
|
|
9547
10034
|
|
|
9548
10035
|
//sudoService call
|
|
@@ -9557,43 +10044,39 @@ class RedisKeyProvider {
|
|
|
9557
10044
|
|
|
9558
10045
|
/**
|
|
9559
10046
|
* StringKeyProvider.js
|
|
9560
|
-
*
|
|
9561
|
-
* authInfo <String
|
|
9562
|
-
* id:
|
|
9563
|
-
* key:
|
|
9564
|
-
* cid:
|
|
9565
|
-
*
|
|
9566
|
-
*
|
|
9567
|
-
*
|
|
9568
|
-
* example => authInfo = 'id1.key1.cid1.
|
|
10047
|
+
*
|
|
10048
|
+
* authInfo <String>: entries 'id.key.cid[.role[.quota]]' separated by ','.
|
|
10049
|
+
* id: max 8 chars
|
|
10050
|
+
* key: ~44 base64 chars recommended
|
|
10051
|
+
* cid: client ID
|
|
10052
|
+
* role: 'device' (default) | 'service' | 'admin'
|
|
10053
|
+
* quota: a Server quotas profile name (default: BohoAuth resolveQuota)
|
|
10054
|
+
*
|
|
10055
|
+
* example => authInfo = 'id1.key1.cid1.admin,id2.key2.cid2.device.pro'
|
|
9569
10056
|
*/
|
|
9570
10057
|
|
|
9571
10058
|
|
|
10059
|
+
const ACCOUNT_ROLES = ROLES.filter(role => role !== 'anonymous');
|
|
10060
|
+
|
|
10061
|
+
/** Parses one 'id.key.cid[.role[.quota]]' entry; a malformed one is a TypeError (naming only the id). */
|
|
10062
|
+
function parseKeyEntry(entry) {
|
|
10063
|
+
const [id, key, cid, role, quota, ...rest] = entry.split('.');
|
|
10064
|
+
if (!id || !key || !cid || rest.length > 0 || (role && !ACCOUNT_ROLES.includes(role))) {
|
|
10065
|
+
throw new TypeError(`invalid key entry 'id.key.cid[.role[.quota]]' for id: ${id ?? ''}`)
|
|
10066
|
+
}
|
|
10067
|
+
return { id, key, cid, role: role || undefined, quota: quota || undefined }
|
|
10068
|
+
}
|
|
10069
|
+
|
|
9572
10070
|
class StringKeyProvider {
|
|
9573
10071
|
constructor(authInfo) {
|
|
9574
|
-
|
|
9575
10072
|
if (!authInfo) {
|
|
9576
10073
|
throw TypeError("StringKeyProvider constructor() missing authInfo.")
|
|
9577
10074
|
}
|
|
9578
|
-
|
|
9579
|
-
let id_keys = authInfo.split(',');
|
|
9580
|
-
|
|
9581
10075
|
this.AUTH = new Map();
|
|
9582
|
-
|
|
9583
|
-
|
|
9584
|
-
|
|
9585
|
-
let [ did, key, cid, level ] = v.split('.');
|
|
9586
|
-
level = parseInt(level);
|
|
9587
|
-
if (did && key && cid && typeof level == 'number') {
|
|
9588
|
-
this.addAuth(did, key, cid, level);
|
|
9589
|
-
} else {
|
|
9590
|
-
throw TypeError("StringKeyProvider invalid authInfo.")
|
|
9591
|
-
}
|
|
9592
|
-
});
|
|
9593
|
-
} else {
|
|
9594
|
-
throw TypeError("StringKeyProvider invalid authInfo.")
|
|
10076
|
+
for (const entry of authInfo.split(',')) {
|
|
10077
|
+
const { id, key, cid, role, quota } = parseKeyEntry(entry);
|
|
10078
|
+
this.addAuth(id, key, cid, role, quota);
|
|
9595
10079
|
}
|
|
9596
|
-
|
|
9597
10080
|
}
|
|
9598
10081
|
|
|
9599
10082
|
async getAuth(id) {
|
|
@@ -9603,17 +10086,17 @@ class StringKeyProvider {
|
|
|
9603
10086
|
return Array.from(this.AUTH.keys())
|
|
9604
10087
|
}
|
|
9605
10088
|
|
|
9606
|
-
addAuth(id, keyStr, cid,
|
|
10089
|
+
addAuth(id, keyStr, cid, role, quota) {
|
|
9607
10090
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9608
|
-
this.AUTH.set(id, { key: Base64hashKey, cid
|
|
10091
|
+
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
9609
10092
|
}
|
|
9610
10093
|
}
|
|
9611
10094
|
|
|
9612
10095
|
const commands$1 = ['echo', 'date', 'unixtime'];
|
|
9613
10096
|
|
|
9614
|
-
|
|
10097
|
+
// Open to every connection.
|
|
9615
10098
|
function checkPermission$1(remote) {
|
|
9616
|
-
return
|
|
10099
|
+
return true;
|
|
9617
10100
|
}
|
|
9618
10101
|
|
|
9619
10102
|
/**
|
|
@@ -9660,10 +10143,9 @@ const commands = [
|
|
|
9660
10143
|
'adddevice', 'getdevice', 'deldevice'
|
|
9661
10144
|
];
|
|
9662
10145
|
|
|
9663
|
-
|
|
9664
|
-
// Only a Boho-authenticated device may use sudo; a raised level alone is not authentication.
|
|
10146
|
+
// Only a connection authenticated with role 'admin'.
|
|
9665
10147
|
function checkPermission(remote) {
|
|
9666
|
-
return remote
|
|
10148
|
+
return hasRole(remote, 'admin');
|
|
9667
10149
|
}
|
|
9668
10150
|
|
|
9669
10151
|
async function call(remote, req) {
|
|
@@ -9690,13 +10172,11 @@ async function call(remote, req) {
|
|
|
9690
10172
|
if (req.$[0]) result = remote.manager.closeRemoteByCId(req.$[0]);
|
|
9691
10173
|
|
|
9692
10174
|
} else if (cmd == 'addauth' || cmd == 'adddevice') {
|
|
9693
|
-
|
|
10175
|
+
// did, key, cid[, role[, quota]]
|
|
10176
|
+
if (remote.manager.authManager && req.$.length >= 3 && req.$.length <= 5) {
|
|
9694
10177
|
if (remote.manager.authManager.addAuth) {
|
|
9695
|
-
|
|
9696
|
-
|
|
9697
|
-
let cid = req.$[2];
|
|
9698
|
-
let level = req.$[3];
|
|
9699
|
-
result = await remote.manager.authManager.addAuth(did, dkey, cid, level);
|
|
10178
|
+
const [did, dkey, cid, role, quota] = req.$;
|
|
10179
|
+
result = await remote.manager.authManager.addAuth(did, dkey, cid, role, quota);
|
|
9700
10180
|
}
|
|
9701
10181
|
|
|
9702
10182
|
}
|
|
@@ -9751,7 +10231,6 @@ var sudoService = /*#__PURE__*/Object.freeze({
|
|
|
9751
10231
|
*
|
|
9752
10232
|
*/
|
|
9753
10233
|
|
|
9754
|
-
const MIN_LEVEL = 200;
|
|
9755
10234
|
const COMMANDS = [
|
|
9756
10235
|
'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
|
|
9757
10236
|
'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
|
|
@@ -9764,22 +10243,21 @@ const COMMANDS = [
|
|
|
9764
10243
|
class RedisService {
|
|
9765
10244
|
/**
|
|
9766
10245
|
* @param {object} redisClient
|
|
9767
|
-
* @param {
|
|
9768
|
-
*
|
|
10246
|
+
* @param {'anonymous' | 'device' | 'service' | 'admin'} [minRole='service'] lowest role allowed;
|
|
10247
|
+
* 'anonymous' allows every connection.
|
|
9769
10248
|
*/
|
|
9770
|
-
constructor(redisClient,
|
|
10249
|
+
constructor(redisClient, minRole = 'service') {
|
|
9771
10250
|
if (!redisClient) {
|
|
9772
10251
|
throw new Error("RedisService constructor: no redisClient")
|
|
9773
10252
|
}
|
|
10253
|
+
if (!ROLES.includes(minRole)) throw new RangeError(`minRole must be one of: ${ROLES.join(', ')}`)
|
|
9774
10254
|
this.redisClient = redisClient;
|
|
9775
|
-
this.
|
|
9776
|
-
this.requireAuth = options.requireAuth !== false;
|
|
10255
|
+
this.minRole = minRole;
|
|
9777
10256
|
this.commands = COMMANDS;
|
|
9778
10257
|
}
|
|
9779
10258
|
|
|
9780
10259
|
checkPermission(remote, req) {
|
|
9781
|
-
|
|
9782
|
-
return (remote.level >= this.minLevel) ? true : false;
|
|
10260
|
+
return hasRole(remote, this.minRole);
|
|
9783
10261
|
}
|
|
9784
10262
|
|
|
9785
10263
|
async call(remote, req) {
|
|
@@ -9810,8 +10288,10 @@ exports.FileLogger = FileLogger;
|
|
|
9810
10288
|
exports.IO = IOWS;
|
|
9811
10289
|
exports.IOCongSocket = IOCongSocket;
|
|
9812
10290
|
exports.IOMsg = IOMsg;
|
|
10291
|
+
exports.LocalKeyProvider = LocalKeyProvider;
|
|
9813
10292
|
exports.MBP = $$1;
|
|
9814
10293
|
exports.PAYLOAD_TYPE = PAYLOAD_TYPE;
|
|
10294
|
+
exports.ROLES = ROLES;
|
|
9815
10295
|
exports.RedisKeyProvider = RedisKeyProvider;
|
|
9816
10296
|
exports.RedisService = RedisService;
|
|
9817
10297
|
exports.SIZE_LIMIT = SIZE_LIMIT;
|
|
@@ -9819,11 +10299,14 @@ exports.STATE = STATE;
|
|
|
9819
10299
|
exports.STATUS = STATUS$1;
|
|
9820
10300
|
exports.Server = Server;
|
|
9821
10301
|
exports.StringKeyProvider = StringKeyProvider;
|
|
10302
|
+
exports.defaultQuota = defaultQuota;
|
|
9822
10303
|
exports.delay = delay;
|
|
9823
10304
|
exports.getIPv4HexString = getIPv4HexString;
|
|
10305
|
+
exports.getIPv6PrefixHexString = getIPv6PrefixHexString;
|
|
9824
10306
|
exports.getLocalAddress = getLocalAddress;
|
|
9825
10307
|
exports.getPayloadFromSignalPack = getPayloadFromSignalPack;
|
|
9826
10308
|
exports.getSignalPack = getSignalPack;
|
|
10309
|
+
exports.hasRole = hasRole;
|
|
9827
10310
|
exports.isPrivateIP = isPrivateIP;
|
|
9828
10311
|
exports.numberWithCommas = numberWithCommas;
|
|
9829
10312
|
exports.pack = pack;
|