iosignal 8.1.0 → 9.6.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 +48 -0
- package/README.md +55 -0
- package/dist/browser/esm/io.d.ts +22 -17
- 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 +1179 -538
- package/dist/node/iosignal.d.cts +324 -127
- package/dist/node/iosignal.d.ts +324 -127
- package/dist/node/iosignal.js +1177 -540
- package/dist/types/client/IOCore.d.ts +22 -18
- 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.6.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
|
-
*
|
|
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 }}
|
|
945
879
|
*/
|
|
946
|
-
this.
|
|
947
|
-
/**
|
|
948
|
-
* Quota table for current level.
|
|
949
|
-
* @type {object}
|
|
950
|
-
*/
|
|
951
|
-
this.quota = quotaTable[this.level];
|
|
880
|
+
this.quota = { maxMessageBytes: null };
|
|
952
881
|
/**
|
|
953
882
|
* Server settings.
|
|
954
883
|
* @type {object}
|
|
@@ -963,6 +892,7 @@ class IOCore extends EventEmitter {
|
|
|
963
892
|
this._linkHandlers = new Map();
|
|
964
893
|
/** @private @type {Set<string>} */
|
|
965
894
|
this._listenTags = new Set();
|
|
895
|
+
this._readyDispatch = false; // true while 'ready' handlers run; see listen()
|
|
966
896
|
/** @private @type {Set<string>} */
|
|
967
897
|
this._manualSubscriptions = new Set();
|
|
968
898
|
|
|
@@ -1264,17 +1194,25 @@ class IOCore extends EventEmitter {
|
|
|
1264
1194
|
let cidStr = decoder$4.decode(buffer.subarray(1));
|
|
1265
1195
|
this.cid = cidStr;
|
|
1266
1196
|
|
|
1267
|
-
//
|
|
1268
|
-
|
|
1269
|
-
|
|
1197
|
+
// State first (subscribe_channels needs READY), then the stored subscriptions, and only then
|
|
1198
|
+
// 'ready': a signal sent from a ready handler reaches the server after our own subscriptions.
|
|
1199
|
+
// stateChange() without a message emits 'change' only; false means a handler moved the state on.
|
|
1200
|
+
if (!this.stateChange('ready')) break;
|
|
1201
|
+
this.subscribe_channels();
|
|
1202
|
+
this._readyDispatch = true;
|
|
1203
|
+
try {
|
|
1204
|
+
this.emit('ready', 'cid_ready');
|
|
1205
|
+
} finally {
|
|
1206
|
+
this._readyDispatch = false;
|
|
1207
|
+
}
|
|
1270
1208
|
break;
|
|
1271
1209
|
|
|
1272
|
-
case IOMsg.
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
this.quota =
|
|
1276
|
-
// console.log('[QUOTA_LEVEL]', JSON.stringify(this.quota))
|
|
1210
|
+
case IOMsg.QUOTA: {
|
|
1211
|
+
if (buffer.byteLength < 5) break;
|
|
1212
|
+
const maxMessageBytes = (buffer[1] | buffer[2] << 8 | buffer[3] << 16) + buffer[4] * 0x1000000;
|
|
1213
|
+
this.quota = { maxMessageBytes: maxMessageBytes || null };
|
|
1277
1214
|
break;
|
|
1215
|
+
}
|
|
1278
1216
|
|
|
1279
1217
|
case IOMsg.AUTH_CLEAR:
|
|
1280
1218
|
this.useAuth = false;
|
|
@@ -1536,10 +1474,10 @@ class IOCore extends EventEmitter {
|
|
|
1536
1474
|
* @param {Buffer} data - The data buffer to send.
|
|
1537
1475
|
*/
|
|
1538
1476
|
send(data) {
|
|
1539
|
-
|
|
1477
|
+
const maxMessageBytes = this.quota.maxMessageBytes;
|
|
1478
|
+
if (maxMessageBytes !== null && data.byteLength > maxMessageBytes) {
|
|
1540
1479
|
this.emit('over_size');
|
|
1541
|
-
console.log(
|
|
1542
|
-
console.log('## your maximum signalSize(bytes) is:', this.quota.signalSize);
|
|
1480
|
+
console.log(`## quota: ${data.byteLength} bytes is over this connection's maxMessageBytes ${maxMessageBytes}`);
|
|
1543
1481
|
return
|
|
1544
1482
|
}
|
|
1545
1483
|
// console.log(`C->[${IOMsg[ data[0]]}]`)
|
|
@@ -1773,11 +1711,22 @@ class IOCore extends EventEmitter {
|
|
|
1773
1711
|
|
|
1774
1712
|
|
|
1775
1713
|
/**
|
|
1776
|
-
* Subscribes to a channel or channels.
|
|
1714
|
+
* Subscribes to a channel or channels on the current, ready connection, at once.
|
|
1715
|
+
* Call it from a ready handler (it runs on every connect) or later while ready; it is not
|
|
1716
|
+
* repeated after a reconnect. To subscribe before connecting, or for every connection
|
|
1717
|
+
* without a ready handler, use listen() or link().
|
|
1777
1718
|
* @param {string} tag - The tag(s) of the channel(s) to subscribe to (comma-separated).
|
|
1778
1719
|
* @throws {TypeError} If tag is invalid, exceeds the length limit, or contains a direct-receive subscription.
|
|
1720
|
+
* @throws {Error} If the connection is not ready (after destroy() it is a no-op instead).
|
|
1779
1721
|
*/
|
|
1780
1722
|
subscribe(tag) {
|
|
1723
|
+
encodeSubscriptionTags(tag);
|
|
1724
|
+
if (!this.boho) return // destroyed: a no-op, like every send after destroy()
|
|
1725
|
+
if (this.state !== STATE.READY) {
|
|
1726
|
+
// Before the CID the request would go out unauthenticated and unencrypted; while
|
|
1727
|
+
// disconnected it would be lost. Neither should pass silently.
|
|
1728
|
+
throw new Error(`subscribe('${tag}') needs a ready connection (state: ${this.stateName}); call it from a ready handler, or use listen() or link()`)
|
|
1729
|
+
}
|
|
1781
1730
|
sendSubscription(this, tag);
|
|
1782
1731
|
for (const part of tag.split(',')) this._manualSubscriptions.add(part);
|
|
1783
1732
|
}
|
|
@@ -1841,23 +1790,28 @@ class IOCore extends EventEmitter {
|
|
|
1841
1790
|
* Convenience API for simple clients (for example, CLI tools): register a
|
|
1842
1791
|
* tag handler once and remember its subscription in channels. For subscription
|
|
1843
1792
|
* tags, register before connection readiness; the CID-ready flow subscribes on initial connection
|
|
1844
|
-
* and again after reconnect,
|
|
1793
|
+
* and again after reconnect, before 'ready' is emitted, so a ready handler may signal at once.
|
|
1845
1794
|
* This does not send a subscription immediately, even if already ready.
|
|
1846
|
-
*
|
|
1847
|
-
*
|
|
1848
|
-
*
|
|
1849
|
-
*
|
|
1850
|
-
*
|
|
1795
|
+
* Do not call listen() inside a ready handler; it throws there, for any tag: a subscription tag
|
|
1796
|
+
* would be subscribed only after the next reconnect, and a handler registered on every
|
|
1797
|
+
* connect runs once more after each reconnect. In a ready handler use on() and subscribe();
|
|
1798
|
+
* for dynamic subscriptions use link().
|
|
1799
|
+
* Direct signals need no subscription: use listen('@') during setup, or on('@'), for all
|
|
1800
|
+
* direct signals, or '@topic' for an exact topic.
|
|
1851
1801
|
* Dispatch is synchronous: '@' first, then '@topic' when tag is not '@'.
|
|
1852
1802
|
* Returning false does not cancel dispatch; a thrown error interrupts it.
|
|
1853
1803
|
* @param {string} tag - The tag to listen on.
|
|
1854
1804
|
* @param {Function} handler - The callback function to handle the signal.
|
|
1855
1805
|
* @throws {TypeError} If tag is not a string, handler is not a function, or tag length is invalid.
|
|
1806
|
+
* @throws {Error} If called inside a ready handler.
|
|
1856
1807
|
*/
|
|
1857
1808
|
listen(tag, handler) {
|
|
1858
1809
|
if (typeof tag !== 'string') throw TypeError('tag should be string.')
|
|
1859
1810
|
encodeTag(tag, false);
|
|
1860
1811
|
if (typeof handler !== 'function') throw TypeError('handler is not a function.')
|
|
1812
|
+
if (this._readyDispatch) {
|
|
1813
|
+
throw new Error(`listen('${tag}') inside a ready handler: call listen() in the setup code that runs before the connection is ready, or use on() and subscribe() in the ready handler`)
|
|
1814
|
+
}
|
|
1861
1815
|
|
|
1862
1816
|
if (tag.indexOf('@') !== 0) {
|
|
1863
1817
|
encodeSubscriptionTags(tag);
|
|
@@ -1874,8 +1828,8 @@ class IOCore extends EventEmitter {
|
|
|
1874
1828
|
|
|
1875
1829
|
/**
|
|
1876
1830
|
* Associates handlers with a local component for scoped teardown.
|
|
1877
|
-
* Direct tags (@ or @topic) only register local handlers. Other tags
|
|
1878
|
-
*
|
|
1831
|
+
* Direct tags (@ or @topic) only register local handlers. Other tags are remembered for
|
|
1832
|
+
* reconnection and subscribed at once on a ready connection; before that, when it becomes ready.
|
|
1879
1833
|
* @param {string} to - The local component identifier, not a server target.
|
|
1880
1834
|
* @param {string} tag - The exact event tag.
|
|
1881
1835
|
* @param {Function} handler - The callback receiving (tag, ...args).
|
|
@@ -1901,7 +1855,9 @@ class IOCore extends EventEmitter {
|
|
|
1901
1855
|
this.on(tag, linkedHandler);
|
|
1902
1856
|
if (!direct) {
|
|
1903
1857
|
this.channels.add(tag);
|
|
1904
|
-
|
|
1858
|
+
// Not before the connection is ready: the request would go out before authentication
|
|
1859
|
+
// (unencrypted) and again from subscribe_channels(), repeating retained values.
|
|
1860
|
+
if (this.state === STATE.READY) sendSubscription(this, tag);
|
|
1905
1861
|
}
|
|
1906
1862
|
}
|
|
1907
1863
|
|
|
@@ -2082,14 +2038,19 @@ function pack(payload) {
|
|
|
2082
2038
|
|
|
2083
2039
|
class CongRx extends require$$0.Transform {
|
|
2084
2040
|
/**
|
|
2085
|
-
* @param {import('stream').TransformOptions} [options] Stream options.
|
|
2041
|
+
* @param {import('stream').TransformOptions & { maxFrameSize?: number }} [options] Stream options.
|
|
2042
|
+
* maxFrameSize: largest payload to buffer (default unlimited). A larger frame is
|
|
2043
|
+
* skipped without buffering and reported by an 'oversize' event (payloadSize).
|
|
2086
2044
|
*/
|
|
2087
|
-
constructor(options) {
|
|
2088
|
-
|
|
2045
|
+
constructor(options = {}) {
|
|
2046
|
+
const { maxFrameSize = Infinity, ...streamOptions } = options;
|
|
2047
|
+
super(streamOptions);
|
|
2089
2048
|
this.buffer = Buffer.alloc(0);
|
|
2090
2049
|
this.frames = [];
|
|
2091
2050
|
this.rxi = 0;
|
|
2092
2051
|
this.rxi_zero = 0;
|
|
2052
|
+
this.maxFrameSize = maxFrameSize;
|
|
2053
|
+
this.skipBytes = 0; // remaining payload bytes of an oversized frame to discard
|
|
2093
2054
|
}
|
|
2094
2055
|
|
|
2095
2056
|
|
|
@@ -2116,6 +2077,15 @@ class CongRx extends require$$0.Transform {
|
|
|
2116
2077
|
}
|
|
2117
2078
|
}
|
|
2118
2079
|
|
|
2080
|
+
if (this.skipBytes > 0) {
|
|
2081
|
+
if (chunk.byteLength <= this.skipBytes) {
|
|
2082
|
+
this.skipBytes -= chunk.byteLength;
|
|
2083
|
+
return;
|
|
2084
|
+
}
|
|
2085
|
+
chunk = chunk.subarray(this.skipBytes);
|
|
2086
|
+
this.skipBytes = 0;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2119
2089
|
if (this.buffer.byteLength > 0) {
|
|
2120
2090
|
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
2121
2091
|
} else {
|
|
@@ -2153,6 +2123,20 @@ class CongRx extends require$$0.Transform {
|
|
|
2153
2123
|
return;
|
|
2154
2124
|
}
|
|
2155
2125
|
|
|
2126
|
+
// Decide as soon as the length is known: the header can advertise up to 4 GiB.
|
|
2127
|
+
// Skipping keeps frame boundaries, so later frames still parse.
|
|
2128
|
+
if (payloadSize > this.maxFrameSize) {
|
|
2129
|
+
this.emit('oversize', payloadSize);
|
|
2130
|
+
const available = this.buffer.byteLength - headerLen;
|
|
2131
|
+
if (available < payloadSize) {
|
|
2132
|
+
this.skipBytes = payloadSize - available;
|
|
2133
|
+
this.buffer = Buffer.alloc(0);
|
|
2134
|
+
return;
|
|
2135
|
+
}
|
|
2136
|
+
this.buffer = this.buffer.subarray(headerLen + payloadSize);
|
|
2137
|
+
continue;
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2156
2140
|
const frameSize = headerLen + payloadSize;
|
|
2157
2141
|
if (this.buffer.byteLength < frameSize) return;
|
|
2158
2142
|
|
|
@@ -2209,7 +2193,9 @@ class IOCongSocket extends IOCore {
|
|
|
2209
2193
|
if (urlObj.protocol != "cong:") {
|
|
2210
2194
|
urlObj = new URL('cong://' + url);
|
|
2211
2195
|
}
|
|
2212
|
-
|
|
2196
|
+
// URL keeps the brackets of an IPv6 literal ('[::1]'); net expects the bare address.
|
|
2197
|
+
const host = urlObj.hostname.replace(/^\[(.*)\]$/, '$1');
|
|
2198
|
+
const socket = this.socket = net.createConnection(urlObj.port, host);
|
|
2213
2199
|
// Signals are small frames; send each immediately instead of waiting on Nagle.
|
|
2214
2200
|
socket.setNoDelay(true);
|
|
2215
2201
|
this._closed = false;
|
|
@@ -7383,18 +7369,75 @@ class IOWS extends IOCore {
|
|
|
7383
7369
|
|
|
7384
7370
|
}
|
|
7385
7371
|
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
|
|
7390
|
-
|
|
7391
|
-
|
|
7392
|
-
|
|
7393
|
-
|
|
7394
|
-
|
|
7395
|
-
|
|
7396
|
-
|
|
7397
|
-
|
|
7372
|
+
// Defaults, read when a Server is created; a Server never modifies them. Change one before
|
|
7373
|
+
// creating servers to change the default for all of them, or pass the setting to new Server().
|
|
7374
|
+
|
|
7375
|
+
const serverOption = {
|
|
7376
|
+
|
|
7377
|
+
// --- Per Server: each of these can be given to new Server({ ... }) ---
|
|
7378
|
+
|
|
7379
|
+
heartbeatInterval: 50000, // ms between liveness checks
|
|
7380
|
+
heartbeatGrace: 5000, // extra ms a peer has to answer before it is closed
|
|
7381
|
+
// Max bytes for a single WebSocket message and CongSocket frame. Bounds pre-auth memory use per
|
|
7382
|
+
// connection (ws defaults to 100 MiB); see Remote.rxFrameLimit().
|
|
7383
|
+
maxPayload: 32 * 1024 * 1024,
|
|
7384
|
+
// When to use X-Forwarded-For / X-Forwarded-Proto of a WebSocket request:
|
|
7385
|
+
// 'private' only if the connecting peer is a loopback/private address, e.g. a reverse proxy on
|
|
7386
|
+
// the same host or network; true always; false never; a number N trusts N proxy hops. The entry
|
|
7387
|
+
// appended by the last trusted proxy is used; earlier entries can be forged by the client.
|
|
7388
|
+
trustProxy: 'private',
|
|
7389
|
+
// A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
|
|
7390
|
+
// letting its send queue grow without limit.
|
|
7391
|
+
maxBufferedBytes: 64 * 1024 * 1024,
|
|
7392
|
+
// Drop signals from connections that are not authenticated.
|
|
7393
|
+
membersOnly: false,
|
|
7394
|
+
// Observability. logMessages: log each received message (type and tag, never the payload).
|
|
7395
|
+
// logStats: print a one-line summary every N ms (0 = off).
|
|
7396
|
+
logMessages: false,
|
|
7397
|
+
logStats: 0,
|
|
7398
|
+
|
|
7399
|
+
// Nested groups: a Server merges its own options over these.
|
|
7400
|
+
// Packet layouts remain unchanged.
|
|
7401
|
+
security: {
|
|
7402
|
+
maxClockSkewMs: 60000,
|
|
7403
|
+
authChallengeMaxAgeMs: 60000,
|
|
7404
|
+
maxReplayEntries: 65536
|
|
7405
|
+
},
|
|
7406
|
+
// Named quota profiles. A connection uses one: an anonymous connection the Server's
|
|
7407
|
+
// anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
|
|
7408
|
+
// resolveQuota). null is unlimited. A Server merges its quotas option over these per profile
|
|
7409
|
+
// and may add profiles; a running server's profiles can be adjusted (server.quotas.basic.fanout = 50).
|
|
7410
|
+
// maxMessageBytes: largest message the connection may send (larger: OVER_SIZE, dropped)
|
|
7411
|
+
// fanout: most subscribers one channel publish is delivered to
|
|
7412
|
+
// msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
|
|
7413
|
+
// maxConnections: connections of one account (uid) at a time; over: the login fails
|
|
7414
|
+
quotas: {
|
|
7415
|
+
anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null },
|
|
7416
|
+
basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20 },
|
|
7417
|
+
pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200 },
|
|
7418
|
+
unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null }
|
|
7419
|
+
},
|
|
7420
|
+
anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
|
|
7421
|
+
|
|
7422
|
+
retain: {
|
|
7423
|
+
enabled: true,
|
|
7424
|
+
limitSize: 100000, // a retained message must be smaller than this many bytes
|
|
7425
|
+
limitCounter: 1000, // channel retain tags per server, and CID retain tags per connection
|
|
7426
|
+
// A channel retain belongs to its last writer: an authenticated account (CID, shared by its
|
|
7427
|
+
// connections) or a live anonymous connection. Each owner holds at most tagsPerOwner tags and
|
|
7428
|
+
// bytesPerOwner bytes. An account's values stay until restart; a closed anonymous connection's
|
|
7429
|
+
// move to its network's grace pool (same budget) and are removed after anonymousGraceMs.
|
|
7430
|
+
tagsPerOwner: 32,
|
|
7431
|
+
bytesPerOwner: 1024 * 1024,
|
|
7432
|
+
anonymousGraceMs: 60 * 60 * 1000,
|
|
7433
|
+
// CID retains of one connection (removed with it), and all retained messages of the server.
|
|
7434
|
+
// A value over budget is not stored, and removes the value it would have replaced.
|
|
7435
|
+
bytesPerConnection: 1024 * 1024,
|
|
7436
|
+
bytesTotal: 256 * 1024 * 1024
|
|
7437
|
+
},
|
|
7438
|
+
|
|
7439
|
+
// --- Process-wide: read directly where used, not per Server ---
|
|
7440
|
+
|
|
7398
7441
|
fileLogger: {
|
|
7399
7442
|
connection: {
|
|
7400
7443
|
use: false,
|
|
@@ -7409,43 +7452,22 @@ let serverOption = {
|
|
|
7409
7452
|
path: 'attack.log'
|
|
7410
7453
|
}
|
|
7411
7454
|
},
|
|
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
7455
|
|
|
7440
7456
|
auth: {
|
|
7441
|
-
|
|
7442
|
-
//
|
|
7443
|
-
// 'keepNew'
|
|
7444
|
-
// Override per
|
|
7457
|
+
failDelay: 600, // ms before AUTH_FAIL is sent
|
|
7458
|
+
// Default for BohoAuth, when the same authenticated CID is already online:
|
|
7459
|
+
// 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
|
|
7460
|
+
// Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
|
|
7461
|
+
// (which wins, and applies only to that Server's connections).
|
|
7445
7462
|
duplicateLogin: 'keepNew'
|
|
7446
7463
|
},
|
|
7447
|
-
membersOnly: false
|
|
7448
7464
|
|
|
7465
|
+
// Development aids.
|
|
7466
|
+
debug: {
|
|
7467
|
+
slow: false, // delay handling of every received message by `delay` ms
|
|
7468
|
+
delay: 500,
|
|
7469
|
+
showAuthInfo: false // log auth results and state traces (never keys)
|
|
7470
|
+
}
|
|
7449
7471
|
};
|
|
7450
7472
|
|
|
7451
7473
|
const decoder$3 = new TextDecoder();
|
|
@@ -7453,6 +7475,27 @@ const decoder$3 = new TextDecoder();
|
|
|
7453
7475
|
$$1.NB;
|
|
7454
7476
|
const MB = $$1.MB;
|
|
7455
7477
|
|
|
7478
|
+
// A one-byte CLOSE reason is a code, not text (Arduino IOSignal::close(uint8_t)): the message
|
|
7479
|
+
// that made the client close, or its CongPacket reader error state (ReadingState >= 250).
|
|
7480
|
+
// Its own table, because IOMsg gives 253 another meaning (TIME_OUT).
|
|
7481
|
+
const CLOSE_REASON = {
|
|
7482
|
+
[IOMsg.AUTH_CLEAR]: 'AUTH_CLEAR',
|
|
7483
|
+
[IOMsg.SERVER_REDIRECT]: 'SERVER_REDIRECT',
|
|
7484
|
+
253: 'CONG_UNKNOWN_TYPE',
|
|
7485
|
+
254: 'CONG_OVER_SIZE',
|
|
7486
|
+
255: 'CONG_OVER_FLOW'
|
|
7487
|
+
};
|
|
7488
|
+
|
|
7489
|
+
// Readable reason of a CLOSE message, e.g. 'AUTH_CLEAR(0xc4)'; longer reasons are text.
|
|
7490
|
+
function closeReason(message) {
|
|
7491
|
+
if (message.byteLength < 2) return 'none'
|
|
7492
|
+
if (message.byteLength === 2) {
|
|
7493
|
+
const code = '0x' + message[1].toString(16).padStart(2, '0');
|
|
7494
|
+
return CLOSE_REASON[message[1]] ? `${CLOSE_REASON[message[1]]}(${code})` : code
|
|
7495
|
+
}
|
|
7496
|
+
return decoder$3.decode(message.subarray(1))
|
|
7497
|
+
}
|
|
7498
|
+
|
|
7456
7499
|
|
|
7457
7500
|
class RemoteCore {
|
|
7458
7501
|
constructor(socket, manager) {
|
|
@@ -7471,9 +7514,11 @@ class RemoteCore {
|
|
|
7471
7514
|
this._replayEntries = 0;
|
|
7472
7515
|
this._replayExpiredBefore = 0;
|
|
7473
7516
|
this.securityFailure = null;
|
|
7517
|
+
this.closeReason = null; // reason of the client's CLOSE message, see closeReason()
|
|
7474
7518
|
this.encMode = ENC_MODE.AUTO;
|
|
7475
7519
|
this.channels = new Set(); // subscribed tags
|
|
7476
7520
|
this.retain_signal = new Map();
|
|
7521
|
+
this.retainBytes = 0; // bytes of its CID retains (retain_signal)
|
|
7477
7522
|
|
|
7478
7523
|
this.ssid = RemoteCore.ssid++; // ordered index number
|
|
7479
7524
|
this.manager = manager;
|
|
@@ -7485,9 +7530,20 @@ class RemoteCore {
|
|
|
7485
7530
|
|
|
7486
7531
|
this.privateNode = false;
|
|
7487
7532
|
this.HOME_CHANNEL = '';
|
|
7488
|
-
this.
|
|
7489
|
-
this.
|
|
7490
|
-
this.
|
|
7533
|
+
this.role = 'anonymous'; // set on authentication; see ROLES in BohoAuth
|
|
7534
|
+
this.accountUid = null; // counted in manager.accountConnections while authenticated with a uid
|
|
7535
|
+
this.ownerUid = null; // the device's owner (login uid); a web sign-in later changes uid, not this
|
|
7536
|
+
this.rxPolicy = null; // compiled delivery policy of an owned device, see deliveryPolicy.js
|
|
7537
|
+
// Quota profile (a server.quotas entry, read live): the anonymous one until authenticated.
|
|
7538
|
+
this.quotaName = manager.anonymousQuota;
|
|
7539
|
+
this.quota = manager.quotas[this.quotaName];
|
|
7540
|
+
this._rateAt = null; // token buckets of quota msgPerSec / bytesPerSec
|
|
7541
|
+
this._msgTokens = 0;
|
|
7542
|
+
this._byteTokens = 0;
|
|
7543
|
+
// Largest message the peer can receive, if it said so in CID_REQ (e.g. an Arduino RX buffer);
|
|
7544
|
+
// larger messages are skipped instead of sent. null: no limit beyond maxPayload.
|
|
7545
|
+
this.peerRxLimit = null;
|
|
7546
|
+
this.peerRxLimitSkipped = 0;
|
|
7491
7547
|
|
|
7492
7548
|
this.state;
|
|
7493
7549
|
this.stateLog = [];
|
|
@@ -7497,6 +7553,11 @@ class RemoteCore {
|
|
|
7497
7553
|
|
|
7498
7554
|
static ssid = 1;
|
|
7499
7555
|
|
|
7556
|
+
/** Authenticated with role 'admin'. */
|
|
7557
|
+
get isAdmin() {
|
|
7558
|
+
return this.role === 'admin' && this.boho.isAuthorized === true;
|
|
7559
|
+
}
|
|
7560
|
+
|
|
7500
7561
|
setState(state) {
|
|
7501
7562
|
const previous = this.state;
|
|
7502
7563
|
this.state = state;
|
|
@@ -7520,43 +7581,79 @@ class RemoteCore {
|
|
|
7520
7581
|
}
|
|
7521
7582
|
|
|
7522
7583
|
|
|
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);
|
|
7584
|
+
// logMessages: one line per received message after decryption: type, routing tag or RPC
|
|
7585
|
+
// target, and size. Payloads are never printed; heartbeat PING/PONG are skipped.
|
|
7586
|
+
logMessage(msgType, message, encrypted = false) {
|
|
7587
|
+
if (msgType === IOMsg.PING || msgType === IOMsg.PONG) return
|
|
7588
|
+
let detail = '';
|
|
7589
|
+
try {
|
|
7590
|
+
if ([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.UNSUBSCRIBE].includes(msgType)) {
|
|
7591
|
+
detail = decoder$3.decode(message.subarray(2, 2 + message[1]));
|
|
7592
|
+
} else if (msgType === IOMsg.SUBSCRIBE_REQ && message.byteLength >= 5) {
|
|
7593
|
+
detail = decoder$3.decode(message.subarray(5, 5 + message.readUInt16BE(3)));
|
|
7594
|
+
} else if (msgType === IOMsg.CALL) {
|
|
7595
|
+
const req = $$1.unpack(message);
|
|
7596
|
+
if (req) detail = `${req.target}.${req.topic}`;
|
|
7539
7597
|
}
|
|
7540
|
-
|
|
7598
|
+
} catch { /* a malformed message is logged without detail */ }
|
|
7599
|
+
const type = msgType === undefined ? 'TEXT'
|
|
7600
|
+
: IOMsg[msgType] ?? it.BohoMsg[msgType] ?? '0x' + msgType.toString(16);
|
|
7601
|
+
const transport = this.socketType === 'websocket' ? 'WS' : 'CS';
|
|
7602
|
+
console.log(`[rx] #${this.ssid} ${this.cid || '-'} ${transport} ${type}${encrypted ? '(enc)' : ''}` +
|
|
7603
|
+
`${detail ? ' ' + detail : ''} ${message.byteLength}B`);
|
|
7604
|
+
}
|
|
7605
|
+
|
|
7606
|
+
// Switches to a server.quotas profile; tell: send it to the client (QUOTA: its maxMessageBytes).
|
|
7607
|
+
setQuota(name, tell) {
|
|
7608
|
+
this.quotaName = name;
|
|
7609
|
+
this.quota = this.manager.quotas[name];
|
|
7610
|
+
// The CongSocket frame ceiling follows maxMessageBytes.
|
|
7611
|
+
this.refreshRxFrameLimit?.();
|
|
7612
|
+
if (tell) {
|
|
7613
|
+
const packet = Buffer.alloc(5);
|
|
7614
|
+
packet[0] = IOMsg.QUOTA;
|
|
7615
|
+
packet.writeUInt32LE(this.quota.maxMessageBytes ?? 0, 1); // 0: unlimited
|
|
7616
|
+
this.send(packet);
|
|
7617
|
+
}
|
|
7618
|
+
}
|
|
7619
|
+
|
|
7620
|
+
// Quota msgPerSec / bytesPerSec: token buckets holding one second. A message larger than the
|
|
7621
|
+
// byte bucket passes when the bucket is full and leaves a debt.
|
|
7622
|
+
takeRateTokens(bytes) {
|
|
7623
|
+
const { msgPerSec, bytesPerSec } = this.quota;
|
|
7624
|
+
if (msgPerSec === null && bytesPerSec === null) return true;
|
|
7625
|
+
const now = node_perf_hooks.performance.now();
|
|
7626
|
+
if (this._rateAt === null) {
|
|
7627
|
+
this._msgTokens = msgPerSec ?? 0;
|
|
7628
|
+
this._byteTokens = bytesPerSec ?? 0;
|
|
7541
7629
|
} else {
|
|
7542
|
-
|
|
7543
|
-
|
|
7630
|
+
const seconds = (now - this._rateAt) / 1000;
|
|
7631
|
+
if (msgPerSec !== null) this._msgTokens = Math.min(msgPerSec, this._msgTokens + seconds * msgPerSec);
|
|
7632
|
+
if (bytesPerSec !== null) this._byteTokens = Math.min(bytesPerSec, this._byteTokens + seconds * bytesPerSec);
|
|
7633
|
+
}
|
|
7634
|
+
this._rateAt = now;
|
|
7635
|
+
if (msgPerSec !== null && this._msgTokens < 1) return false;
|
|
7636
|
+
if (bytesPerSec !== null && this._byteTokens < Math.min(bytes, bytesPerSec)) return false;
|
|
7637
|
+
if (msgPerSec !== null) this._msgTokens -= 1;
|
|
7638
|
+
if (bytesPerSec !== null) this._byteTokens -= bytes;
|
|
7639
|
+
return true;
|
|
7544
7640
|
}
|
|
7545
7641
|
|
|
7546
7642
|
rxQuotaChecker(message) {
|
|
7547
7643
|
let rxBytes = message.byteLength;
|
|
7548
|
-
this.manager.rxBytes += rxBytes;
|
|
7549
|
-
|
|
7644
|
+
this.manager.counters.rxBytes += rxBytes;
|
|
7645
|
+
this.manager.counters.rxMessages++;
|
|
7550
7646
|
|
|
7551
|
-
|
|
7552
|
-
|
|
7647
|
+
const maxMessageBytes = this.quota.maxMessageBytes;
|
|
7648
|
+
if (maxMessageBytes !== null && rxBytes > maxMessageBytes) {
|
|
7649
|
+
this.manager.counters.oversizeRejected++;
|
|
7553
7650
|
this.send(Buffer.from([IOMsg.OVER_SIZE]));
|
|
7554
|
-
if (serverOption.useQuota.disconnect) this.close();
|
|
7555
7651
|
return false;
|
|
7556
7652
|
}
|
|
7557
|
-
|
|
7558
|
-
|
|
7559
|
-
|
|
7653
|
+
if (!this.takeRateTokens(rxBytes)) {
|
|
7654
|
+
this.manager.counters.rateLimited++;
|
|
7655
|
+
return false;
|
|
7656
|
+
}
|
|
7560
7657
|
return true;
|
|
7561
7658
|
}
|
|
7562
7659
|
|
|
@@ -7570,7 +7667,7 @@ class RemoteCore {
|
|
|
7570
7667
|
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7571
7668
|
this.securityFailure = reason;
|
|
7572
7669
|
this.boho.clearAuth();
|
|
7573
|
-
this.
|
|
7670
|
+
this.role = 'anonymous';
|
|
7574
7671
|
this._replayBuckets.clear();
|
|
7575
7672
|
this._replayEntries = 0;
|
|
7576
7673
|
this.close(true);
|
|
@@ -7652,9 +7749,8 @@ class RemoteCore {
|
|
|
7652
7749
|
this.receiveMonitor(); // rx-data, ping/pong and timeout check
|
|
7653
7750
|
if (!this.rxQuotaChecker(message)) return
|
|
7654
7751
|
|
|
7655
|
-
|
|
7656
|
-
|
|
7657
|
-
let msgType, decoded;
|
|
7752
|
+
const logMessages = this.manager.server?.logMessages;
|
|
7753
|
+
let msgType, decoded, encrypted = false;
|
|
7658
7754
|
|
|
7659
7755
|
if (isBinary) {
|
|
7660
7756
|
msgType = message[0];
|
|
@@ -7666,6 +7762,7 @@ class RemoteCore {
|
|
|
7666
7762
|
if (decoded) {
|
|
7667
7763
|
msgType = decoded[0];
|
|
7668
7764
|
message = decoded;
|
|
7765
|
+
encrypted = true;
|
|
7669
7766
|
} else {
|
|
7670
7767
|
return
|
|
7671
7768
|
}
|
|
@@ -7677,11 +7774,13 @@ class RemoteCore {
|
|
|
7677
7774
|
msgType = decoded[0];
|
|
7678
7775
|
message.set(decoded, it.MetaSize.ENC_488); // set decoded signal_e2e headaer.
|
|
7679
7776
|
message = message.subarray(it.MetaSize.ENC_488); // reset offset.
|
|
7777
|
+
encrypted = true;
|
|
7680
7778
|
} else {
|
|
7681
7779
|
return
|
|
7682
7780
|
}
|
|
7683
7781
|
|
|
7684
7782
|
} else ;
|
|
7783
|
+
if (logMessages) this.logMessage(msgType, message, encrypted);
|
|
7685
7784
|
|
|
7686
7785
|
switch (msgType) {
|
|
7687
7786
|
case IOMsg.PING:
|
|
@@ -7700,6 +7799,13 @@ class RemoteCore {
|
|
|
7700
7799
|
return;
|
|
7701
7800
|
}
|
|
7702
7801
|
|
|
7802
|
+
// Optional uint32 little endian after the type: the peer's RX buffer size. Set before
|
|
7803
|
+
// anything else is sent, so CID_RES, retained messages and signals respect it.
|
|
7804
|
+
if (message.byteLength >= 5) {
|
|
7805
|
+
const size = (message[1] | message[2] << 8 | message[3] << 16) + message[4] * 0x1000000;
|
|
7806
|
+
if (size > 0) this.peerRxLimit = size;
|
|
7807
|
+
}
|
|
7808
|
+
|
|
7703
7809
|
if (!this.cid) {
|
|
7704
7810
|
const cid = this.manager.issueAnonymousCid();
|
|
7705
7811
|
if (!cid) {
|
|
@@ -7709,6 +7815,8 @@ class RemoteCore {
|
|
|
7709
7815
|
}
|
|
7710
7816
|
this.cid = cid;
|
|
7711
7817
|
this.manager.cid2remote.set(this.cid, this);
|
|
7818
|
+
// The client limits its own sends to its quota (an authenticated one is sent on AUTH).
|
|
7819
|
+
this.setQuota(this.quotaName, true);
|
|
7712
7820
|
}
|
|
7713
7821
|
|
|
7714
7822
|
// console.log('<< SENDING CID_RES:', this.cid)
|
|
@@ -7812,11 +7920,10 @@ class RemoteCore {
|
|
|
7812
7920
|
|
|
7813
7921
|
|
|
7814
7922
|
case IOMsg.CLOSE:
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
}
|
|
7923
|
+
// The reason is only logged, so a CLOSE without one still closes.
|
|
7924
|
+
this.closeReason = closeReason(message);
|
|
7925
|
+
console.log(`>> CLOSE #${this.ssid} cid:${this.cid} reason: ${this.closeReason}`);
|
|
7926
|
+
this.close();
|
|
7820
7927
|
break;
|
|
7821
7928
|
|
|
7822
7929
|
|
|
@@ -7857,6 +7964,7 @@ class RemoteCore {
|
|
|
7857
7964
|
|
|
7858
7965
|
} else {
|
|
7859
7966
|
// TEXT FRAME
|
|
7967
|
+
if (logMessages) this.logMessage(undefined, message);
|
|
7860
7968
|
try {
|
|
7861
7969
|
let textMessage = decoder$3.decode(message);
|
|
7862
7970
|
// console.log('text buffer:',textMessage )
|
|
@@ -7939,7 +8047,8 @@ class RemoteCore {
|
|
|
7939
8047
|
"cid": this.cid,
|
|
7940
8048
|
"did": this.did,
|
|
7941
8049
|
"uid": this.uid,
|
|
7942
|
-
"
|
|
8050
|
+
"role": this.role,
|
|
8051
|
+
"quota": this.quotaName,
|
|
7943
8052
|
"nick": this.nick,
|
|
7944
8053
|
"ip": this.ip
|
|
7945
8054
|
, 'tag': channels
|
|
@@ -7957,31 +8066,45 @@ class RemoteCore {
|
|
|
7957
8066
|
|
|
7958
8067
|
}
|
|
7959
8068
|
|
|
8069
|
+
// 16 address bytes of an IPv6 string (with '::', an embedded IPv4 tail or a %zone), else null.
|
|
8070
|
+
function ipv6Bytes(ip) {
|
|
8071
|
+
if (!net.isIPv6(ip)) return null
|
|
8072
|
+
ip = ip.split('%')[0];
|
|
8073
|
+
const tailStart = ip.lastIndexOf(':') + 1;
|
|
8074
|
+
const tail = ip.slice(tailStart);
|
|
8075
|
+
if (net.isIPv4(tail)) {
|
|
8076
|
+
const [a, b, c, d] = tail.split('.').map(Number);
|
|
8077
|
+
ip = ip.slice(0, tailStart) + ((a << 8) | b).toString(16) + ':' + ((c << 8) | d).toString(16);
|
|
8078
|
+
}
|
|
8079
|
+
const words = s => s ? s.split(':').map(h => parseInt(h, 16)) : [];
|
|
8080
|
+
const [head, rest] = ip.split('::');
|
|
8081
|
+
const left = words(head), right = words(rest);
|
|
8082
|
+
const all = [...left, ...new Array(8 - left.length - right.length).fill(0), ...right];
|
|
8083
|
+
const bytes = Buffer.alloc(16);
|
|
8084
|
+
all.forEach((word, i) => bytes.writeUInt16BE(word, i * 2));
|
|
8085
|
+
return bytes
|
|
8086
|
+
}
|
|
8087
|
+
|
|
8088
|
+
function isPrivateIPv4(ip) {
|
|
8089
|
+
const [a, b] = ip.split('.').map(Number);
|
|
8090
|
+
return a === 0 || a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168)
|
|
8091
|
+
}
|
|
8092
|
+
|
|
8093
|
+
// Unspecified, loopback, RFC 1918, IPv6 unique-local (fc00::/7) and link-local (fe80::/10).
|
|
7960
8094
|
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
|
|
8095
|
+
if (net.isIPv4(ip)) return isPrivateIPv4(ip)
|
|
8096
|
+
const bytes = ipv6Bytes(ip);
|
|
8097
|
+
if (!bytes) return false
|
|
8098
|
+
if (bytes.subarray(0, 15).every(v => v === 0) && bytes[15] <= 1) return true // :: and ::1
|
|
8099
|
+
if (bytes.subarray(0, 10).every(v => v === 0) && bytes[10] === 0xff && bytes[11] === 0xff) {
|
|
8100
|
+
return isPrivateIPv4(bytes.subarray(12).join('.')) // IPv4-mapped
|
|
8101
|
+
}
|
|
8102
|
+
return (bytes[0] & 0xfe) === 0xfc || (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80)
|
|
8103
|
+
}
|
|
8104
|
+
|
|
8105
|
+
// Hosts on one IPv6 network share the /64 prefix, not the address: hex of those 8 bytes.
|
|
8106
|
+
function getIPv6PrefixHexString(ip) {
|
|
8107
|
+
return ipv6Bytes(ip)?.subarray(0, 8).toString('hex') ?? null
|
|
7985
8108
|
}
|
|
7986
8109
|
|
|
7987
8110
|
function numberWithCommas(x) {
|
|
@@ -8022,6 +8145,42 @@ const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
8022
8145
|
|
|
8023
8146
|
const decoder$2 = new TextDecoder();
|
|
8024
8147
|
|
|
8148
|
+
// Each proxy appends to a forwarding header, so the entry `hops` from the right was
|
|
8149
|
+
// written by the outermost trusted proxy; anything left of it came from the client.
|
|
8150
|
+
function forwardedValue(header, hops) {
|
|
8151
|
+
if (!hops || typeof header !== 'string') return undefined
|
|
8152
|
+
const values = header.split(',').map(v => v.trim()).filter(Boolean);
|
|
8153
|
+
return values[Math.max(0, values.length - hops)]
|
|
8154
|
+
}
|
|
8155
|
+
|
|
8156
|
+
// IPv4-mapped addresses as IPv4, '::1' as 127.0.0.1; undefined if not an IP address.
|
|
8157
|
+
function normalizeIP(ip) {
|
|
8158
|
+
if (typeof ip !== 'string') return undefined
|
|
8159
|
+
if (ip.startsWith('::ffff:') && node_net.isIPv4(ip.slice(7))) ip = ip.slice(7);
|
|
8160
|
+
if (ip === '::1') ip = '127.0.0.1';
|
|
8161
|
+
return node_net.isIP(ip) ? ip : undefined
|
|
8162
|
+
}
|
|
8163
|
+
|
|
8164
|
+
// Number of reverse proxies whose forwarding headers are trusted (see serverOption.trustProxy).
|
|
8165
|
+
function trustedProxyHops(peerIP, trust = serverOption.trustProxy) {
|
|
8166
|
+
if (trust === 'private') return peerIP && isPrivateIP(peerIP) ? 1 : 0
|
|
8167
|
+
if (trust === true) return 1
|
|
8168
|
+
return Number.isSafeInteger(trust) && trust > 0 ? trust : 0
|
|
8169
|
+
}
|
|
8170
|
+
|
|
8171
|
+
// Client address and TLS of a WebSocket upgrade request; exported for other servers that
|
|
8172
|
+
// accept the same proxied connections.
|
|
8173
|
+
function getClientAddress(req, trust = serverOption.trustProxy) {
|
|
8174
|
+
const peerIP = normalizeIP(req.socket?.remoteAddress);
|
|
8175
|
+
const hops = trustedProxyHops(peerIP, trust);
|
|
8176
|
+
return {
|
|
8177
|
+
ip: normalizeIP(forwardedValue(req.headers['x-forwarded-for'], hops)) ?? peerIP ?? '0.0.0.0',
|
|
8178
|
+
// X-Forwarded-Proto: https turns off server-side encryption (ENC_MODE.AUTO), so it is
|
|
8179
|
+
// only honored from a trusted proxy, like the client address.
|
|
8180
|
+
TLS: forwardedValue(req.headers['x-forwarded-proto'], hops) === 'https'
|
|
8181
|
+
}
|
|
8182
|
+
}
|
|
8183
|
+
|
|
8025
8184
|
class Remote extends RemoteCore {
|
|
8026
8185
|
constructor(socket, req, manager) {
|
|
8027
8186
|
super(socket, manager);
|
|
@@ -8032,11 +8191,12 @@ class Remote extends RemoteCore {
|
|
|
8032
8191
|
this.socketType = socket.socketType;
|
|
8033
8192
|
|
|
8034
8193
|
if (this.socketType === 'websocket') {
|
|
8035
|
-
|
|
8036
|
-
this.ip =
|
|
8194
|
+
const { ip, TLS } = getClientAddress(req, this.manager.server?.trustProxy);
|
|
8195
|
+
this.ip = ip;
|
|
8196
|
+
this.TLS = TLS;
|
|
8037
8197
|
} else {
|
|
8038
8198
|
this.TLS = false;
|
|
8039
|
-
this.ip =
|
|
8199
|
+
this.ip = normalizeIP(socket.remoteAddress) ?? '0.0.0.0';
|
|
8040
8200
|
}
|
|
8041
8201
|
|
|
8042
8202
|
|
|
@@ -8044,6 +8204,9 @@ class Remote extends RemoteCore {
|
|
|
8044
8204
|
// connection from local or private network has default private channel.
|
|
8045
8205
|
this.HOME_CHANNEL = 'PRIVATE:';
|
|
8046
8206
|
this.privateNode = true;
|
|
8207
|
+
} else if (node_net.isIPv6(this.ip)) {
|
|
8208
|
+
// An IPv6 network is its /64 prefix; each host there has its own address.
|
|
8209
|
+
this.HOME_CHANNEL = 'IP6:' + getIPv6PrefixHexString(this.ip);
|
|
8047
8210
|
} else {
|
|
8048
8211
|
// The HOME_CHANNEL is defined by the global IP address value.
|
|
8049
8212
|
this.HOME_CHANNEL = 'IP:' + getIPv4HexString(this.ip);
|
|
@@ -8070,10 +8233,11 @@ class Remote extends RemoteCore {
|
|
|
8070
8233
|
this.txDrainMaxMs = Math.max(this.txDrainMaxMs, node_perf_hooks.performance.now() - this.txBlockedSince);
|
|
8071
8234
|
this.txBlockedSince = null;
|
|
8072
8235
|
});
|
|
8073
|
-
this.congRx = new CongRx();
|
|
8236
|
+
this.congRx = new CongRx({ maxFrameSize: this.rxFrameLimit() });
|
|
8074
8237
|
socket.on('data', data => { this.congRx.write(data); });
|
|
8075
8238
|
|
|
8076
8239
|
this.congRx.on('wrong', this.onWrongCongPacketMessage.bind(this));
|
|
8240
|
+
this.congRx.on('oversize', this.onOversizeCongPacket.bind(this));
|
|
8077
8241
|
// readable.pipe( destination )
|
|
8078
8242
|
// tcpSocket -> congRx(parser) -> onMessage
|
|
8079
8243
|
// socket.pipe( this.congRx )
|
|
@@ -8127,13 +8291,32 @@ class Remote extends RemoteCore {
|
|
|
8127
8291
|
}
|
|
8128
8292
|
|
|
8129
8293
|
|
|
8130
|
-
|
|
8131
|
-
|
|
8132
|
-
|
|
8133
|
-
|
|
8294
|
+
// Largest CongSocket frame the parser buffers: maxPayload (as for WebSocket), or the quota's
|
|
8295
|
+
// maxMessageBytes when smaller. A frame payload is the message rxQuotaChecker measures, so a
|
|
8296
|
+
// larger frame would be rejected after buffering anyway.
|
|
8297
|
+
rxFrameLimit() {
|
|
8298
|
+
const maxPayload = this.manager.server?.maxPayload ?? serverOption.maxPayload;
|
|
8299
|
+
const maxMessageBytes = this.quota?.maxMessageBytes ?? null;
|
|
8300
|
+
return maxMessageBytes === null ? maxPayload : Math.min(maxPayload, maxMessageBytes);
|
|
8301
|
+
}
|
|
8134
8302
|
|
|
8303
|
+
// Called after the quota changes (e.g. on successful auth).
|
|
8304
|
+
refreshRxFrameLimit() {
|
|
8305
|
+
if (this.congRx) this.congRx.maxFrameSize = this.rxFrameLimit();
|
|
8135
8306
|
}
|
|
8136
8307
|
|
|
8308
|
+
// The frame was skipped unbuffered; same response as rxQuotaChecker, except that a
|
|
8309
|
+
// connection without a CID is treated like a wrong packet (see onWrongCongPacketMessage).
|
|
8310
|
+
onOversizeCongPacket(payloadSize) {
|
|
8311
|
+
if (this._closing) return;
|
|
8312
|
+
if (!this.cid) {
|
|
8313
|
+
this.manager.attackLogger?.log(`> ${this.ssid} ${this.ip} OVERSIZE ${payloadSize}`);
|
|
8314
|
+
this.close(true);
|
|
8315
|
+
return;
|
|
8316
|
+
}
|
|
8317
|
+
this.manager.counters.oversizeRejected++;
|
|
8318
|
+
this.send(Buffer.from([IOMsg.OVER_SIZE]));
|
|
8319
|
+
}
|
|
8137
8320
|
|
|
8138
8321
|
// any type of received messages: message, ping, pong
|
|
8139
8322
|
receiveMonitor() {
|
|
@@ -8142,27 +8325,9 @@ class Remote extends RemoteCore {
|
|
|
8142
8325
|
this.socket.isAlive = true;
|
|
8143
8326
|
}
|
|
8144
8327
|
|
|
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;
|
|
8328
|
+
// Number of reverse proxies whose forwarding headers this server trusts.
|
|
8329
|
+
trustedProxyHops(peerIP) {
|
|
8330
|
+
return trustedProxyHops(peerIP, this.manager.server?.trustProxy)
|
|
8166
8331
|
}
|
|
8167
8332
|
|
|
8168
8333
|
ping() {
|
|
@@ -8184,15 +8349,15 @@ class Remote extends RemoteCore {
|
|
|
8184
8349
|
}
|
|
8185
8350
|
|
|
8186
8351
|
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;
|
|
8352
|
+
let txb = this.socket.bytesWritten || this.socket._socket?.bytesWritten;
|
|
8353
|
+
let rxb = this.socket.bytesRead || this.socket._socket?.bytesRead;
|
|
8354
|
+
let tx = this.socket.txCounter;
|
|
8355
|
+
let rx = this.socket.rxCounter;
|
|
8356
|
+
return { tx, txb, rx, rxb }
|
|
8191
8357
|
}
|
|
8192
8358
|
|
|
8193
8359
|
close(terminateNow = false) {
|
|
8194
8360
|
this._closing = true;
|
|
8195
|
-
this.getTraffic();
|
|
8196
8361
|
if (this.socketType === 'websocket') {
|
|
8197
8362
|
if (terminateNow) this.socket.terminate();
|
|
8198
8363
|
else this.socket.close();
|
|
@@ -8202,16 +8367,30 @@ class Remote extends RemoteCore {
|
|
|
8202
8367
|
}
|
|
8203
8368
|
}
|
|
8204
8369
|
|
|
8370
|
+
// A peer that stops reading would otherwise grow its send queue without limit.
|
|
8205
8371
|
recordTxQueue() {
|
|
8206
8372
|
const queued = this.socket.bufferedAmount ?? this.socket.writableLength ?? 0;
|
|
8207
8373
|
if (queued > this.txQueuePeakBytes) this.txQueuePeakBytes = queued;
|
|
8374
|
+
const limit = this.manager.server?.maxBufferedBytes ?? serverOption.maxBufferedBytes;
|
|
8375
|
+
if (queued > limit) {
|
|
8376
|
+
console.log(`slow peer #${this.ssid} cid:${this.cid} has ${queued} unsent bytes: closing`);
|
|
8377
|
+
this.close(true);
|
|
8378
|
+
}
|
|
8208
8379
|
}
|
|
8209
8380
|
|
|
8210
8381
|
// node.js server side remote.
|
|
8211
8382
|
send(message, isBinary) {
|
|
8383
|
+
// Sending to a closing peer can only fail; skip instead of logging each attempt.
|
|
8384
|
+
if (this._closing) return;
|
|
8385
|
+
// The peer cannot receive it (see peerRxLimit); a CongSocket Arduino would have to discard it.
|
|
8386
|
+
if (this.peerRxLimit !== null && message.byteLength > this.peerRxLimit) {
|
|
8387
|
+
this.peerRxLimitSkipped++;
|
|
8388
|
+
this.manager.counters.peerRxLimitSkipped++;
|
|
8389
|
+
return;
|
|
8390
|
+
}
|
|
8212
8391
|
// console.log(`<-S [${IOMsg[ message[0]]}]`)
|
|
8213
|
-
this.manager.txBytes += message.byteLength;
|
|
8214
|
-
|
|
8392
|
+
this.manager.counters.txBytes += message.byteLength;
|
|
8393
|
+
this.manager.counters.txMessages++;
|
|
8215
8394
|
this.socket.txCounter++;
|
|
8216
8395
|
if (this.socketType === 'websocket') {
|
|
8217
8396
|
if (this.socket.readyState === 1) {
|
|
@@ -8273,93 +8452,80 @@ class FileLogger {
|
|
|
8273
8452
|
|
|
8274
8453
|
}
|
|
8275
8454
|
|
|
8276
|
-
const
|
|
8277
|
-
let period = 10000;
|
|
8455
|
+
const KIB = 1024, MIB = 1024 * 1024;
|
|
8278
8456
|
|
|
8457
|
+
function bytes(n) {
|
|
8458
|
+
if (n >= MIB) return (n / MIB).toFixed(1) + 'MB'
|
|
8459
|
+
if (n >= KIB) return (n / KIB).toFixed(1) + 'KB'
|
|
8460
|
+
return Math.round(n) + 'B'
|
|
8461
|
+
}
|
|
8462
|
+
|
|
8463
|
+
// Read-only views of the manager for logStats, Server.stats() and the sudo service.
|
|
8464
|
+
// Nothing here runs on a timer or resets the manager's counters.
|
|
8279
8465
|
class Metrics {
|
|
8280
8466
|
constructor(manager) {
|
|
8281
8467
|
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);
|
|
8468
|
+
this.previous = null; // last summaryLine() sample, for rates
|
|
8314
8469
|
}
|
|
8315
8470
|
|
|
8316
|
-
|
|
8317
|
-
|
|
8318
8471
|
close() {
|
|
8319
|
-
|
|
8320
|
-
this.tickId = null;
|
|
8472
|
+
this.previous = null;
|
|
8321
8473
|
}
|
|
8322
8474
|
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8475
|
+
// Current state; counters are cumulative since the server started. Enumerates connections once.
|
|
8476
|
+
snapshot() {
|
|
8477
|
+
const manager = this.manager;
|
|
8478
|
+
let authenticated = 0, websocket = 0;
|
|
8479
|
+
for (const remote of manager.remotes) {
|
|
8480
|
+
if (remote.boho.isAuthorized) authenticated++;
|
|
8481
|
+
if (remote.socketType === 'websocket') websocket++;
|
|
8482
|
+
}
|
|
8483
|
+
const total = manager.remotes.size;
|
|
8484
|
+
const memory = process$1.memoryUsage();
|
|
8485
|
+
return {
|
|
8486
|
+
at: Date.now(),
|
|
8487
|
+
connections: { total, authenticated, anonymous: total - authenticated, websocket, tcp: total - websocket },
|
|
8488
|
+
channels: manager.channel_map.size,
|
|
8489
|
+
retained: { channel: manager.retain_messages.size, bytes: manager.retainBytes },
|
|
8490
|
+
counters: { ...manager.counters },
|
|
8491
|
+
memory: { rss: memory.rss, heapUsed: memory.heapUsed }
|
|
8492
|
+
}
|
|
8493
|
+
}
|
|
8494
|
+
|
|
8495
|
+
// One logStats line; rates are per second since the previous line.
|
|
8496
|
+
summaryLine(now = node_perf_hooks.performance.now()) {
|
|
8497
|
+
const s = this.snapshot(), previous = this.previous;
|
|
8498
|
+
const rate = key => previous ? (s.counters[key] - previous.counters[key]) * 1000 / Math.max(1, now - previous.time) : 0;
|
|
8499
|
+
this.previous = { time: now, counters: s.counters };
|
|
8500
|
+
const c = s.connections;
|
|
8501
|
+
return `[iosignal] conn ${c.total} (auth ${c.authenticated}, anon ${c.anonymous}, ws ${c.websocket}, tcp ${c.tcp})` +
|
|
8502
|
+
` ch ${s.channels} retained ${s.retained.channel}/${bytes(s.retained.bytes)}` +
|
|
8503
|
+
` | rx ${rate('rxMessages').toFixed(1)}/s ${bytes(rate('rxBytes'))}/s` +
|
|
8504
|
+
` tx ${rate('txMessages').toFixed(1)}/s ${bytes(rate('txBytes'))}/s pub ${rate('publishes').toFixed(1)}/s` +
|
|
8505
|
+
` | rss ${bytes(s.memory.rss)} heap ${bytes(s.memory.heapUsed)}`
|
|
8506
|
+
}
|
|
8507
|
+
|
|
8508
|
+
// Compact summary for metrics reports ('@$metrics'); byte counters are cumulative.
|
|
8509
|
+
oneline() {
|
|
8510
|
+
return {
|
|
8332
8511
|
lastSSID: this.manager.lastSSID,
|
|
8333
8512
|
remotes: this.manager.remotes.size,
|
|
8334
8513
|
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]
|
|
8514
|
+
txBytes: this.manager.counters.txBytes,
|
|
8515
|
+
rxBytes: this.manager.counters.rxBytes,
|
|
8516
|
+
}
|
|
8342
8517
|
}
|
|
8343
8518
|
|
|
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
|
|
8519
|
+
getRemotes() {
|
|
8520
|
+
return Array.from(this.manager.remotes, v => "#" + v.ssid + ":" + v.cid + "(" + v.getStateName() + ")")
|
|
8351
8521
|
}
|
|
8352
8522
|
|
|
8353
|
-
getCIdList(
|
|
8354
|
-
|
|
8355
|
-
if (prn) console.table(CIdList);
|
|
8356
|
-
return CIdList
|
|
8523
|
+
getCIdList() {
|
|
8524
|
+
return Array.from(this.manager.cid2remote.keys())
|
|
8357
8525
|
}
|
|
8358
8526
|
|
|
8359
|
-
getChannelList(
|
|
8360
|
-
|
|
8361
|
-
if (prn) console.table(chList);
|
|
8362
|
-
return chList
|
|
8527
|
+
getChannelList() {
|
|
8528
|
+
return Array.from(this.manager.channel_map.keys())
|
|
8363
8529
|
}
|
|
8364
8530
|
|
|
8365
8531
|
getSubscribers(ch) {
|
|
@@ -8370,7 +8536,6 @@ class Metrics {
|
|
|
8370
8536
|
list.push(c.cid);
|
|
8371
8537
|
});
|
|
8372
8538
|
}
|
|
8373
|
-
// console.log(list)
|
|
8374
8539
|
return list
|
|
8375
8540
|
}
|
|
8376
8541
|
|
|
@@ -8409,15 +8574,11 @@ class Metrics {
|
|
|
8409
8574
|
encMode: ENC_MODE[remote.encMode]
|
|
8410
8575
|
}
|
|
8411
8576
|
} 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
8577
|
return {
|
|
8416
8578
|
ip: remote.ip,
|
|
8417
8579
|
uptime: Math.trunc((Date.now() - remote.socket.openTime) / 1000),
|
|
8418
|
-
channels: channels,
|
|
8419
|
-
|
|
8420
|
-
retain: retain_signal
|
|
8580
|
+
channels: Array.from(remote.channels.keys()),
|
|
8581
|
+
retain: Array.from(remote.retain_signal.keys())
|
|
8421
8582
|
}
|
|
8422
8583
|
}
|
|
8423
8584
|
|
|
@@ -8430,6 +8591,145 @@ class Metrics {
|
|
|
8430
8591
|
|
|
8431
8592
|
}
|
|
8432
8593
|
|
|
8594
|
+
/**
|
|
8595
|
+
* Delivery policy: which senders a device accepts CID unicast ('<cid>@topic') from.
|
|
8596
|
+
*
|
|
8597
|
+
* The policy belongs to an owned device (one whose login has a uid) and comes with its login
|
|
8598
|
+
* (authInfo.rxPolicy from the key provider, JSON text or an object) or later from
|
|
8599
|
+
* Manager.setDeliveryPolicy(). A device without an owner uid is never filtered.
|
|
8600
|
+
*
|
|
8601
|
+
* {
|
|
8602
|
+
* v: 1,
|
|
8603
|
+
* mode: 'open' | 'allowlist' | 'denylist', // open: everyone (the default)
|
|
8604
|
+
* anonymous: 'allow' | 'deny', // default: deny for allowlist, allow for denylist
|
|
8605
|
+
* publish: 'all' | 'policy', // who gets its CID publications ('@topic', '@$topic'):
|
|
8606
|
+
* // 'all' subscribers (default), or only those the policy allows
|
|
8607
|
+
* allow: { cids: [], uids: [] },
|
|
8608
|
+
* deny: { cids: [], uids: [] }
|
|
8609
|
+
* }
|
|
8610
|
+
*
|
|
8611
|
+
* Decision, first match wins:
|
|
8612
|
+
* 1. no owner, no policy, mode open -> allow
|
|
8613
|
+
* 2. the device itself, its owner's uid, or a connection with role 'admin' -> allow
|
|
8614
|
+
* 3. sender CID in deny.cids / allow.cids -> deny / allow
|
|
8615
|
+
* 4. sender uid in deny.uids / allow.uids -> deny / allow
|
|
8616
|
+
* 5. anonymous sender (not authenticated, no uid) -> anonymous setting
|
|
8617
|
+
* 6. mode default: allowlist denies, denylist allows
|
|
8618
|
+
*
|
|
8619
|
+
* With publish 'policy', the same decision (subscriber in the sender's place) filters the device's CID
|
|
8620
|
+
* publications and the retained ones a new subscriber would get. Its '@state' close notice included.
|
|
8621
|
+
*
|
|
8622
|
+
* The sender's uid is remote.uid: a device's owner, or the user of a web sign-in on that connection.
|
|
8623
|
+
* Only the server's own view of the sender is used, never anything in the message.
|
|
8624
|
+
*/
|
|
8625
|
+
|
|
8626
|
+
const DELIVERY_POLICY_MODES = Object.freeze(['open', 'allowlist', 'denylist']);
|
|
8627
|
+
const DELIVERY_POLICY_MAX_ENTRIES = 200;
|
|
8628
|
+
const ENTRY_MAX_LENGTH = 64;
|
|
8629
|
+
const LISTS = ['cids', 'uids'];
|
|
8630
|
+
|
|
8631
|
+
function entries(name, value) {
|
|
8632
|
+
if (value === undefined || value === null) return []
|
|
8633
|
+
if (!Array.isArray(value)) throw new TypeError(`${name} must be an array`)
|
|
8634
|
+
if (value.length > DELIVERY_POLICY_MAX_ENTRIES) {
|
|
8635
|
+
throw new RangeError(`${name} has more than ${DELIVERY_POLICY_MAX_ENTRIES} entries`)
|
|
8636
|
+
}
|
|
8637
|
+
for (const entry of value) {
|
|
8638
|
+
if (typeof entry !== 'string' || !entry || entry.length > ENTRY_MAX_LENGTH) {
|
|
8639
|
+
throw new TypeError(`${name} entries must be non-empty strings of at most ${ENTRY_MAX_LENGTH} characters`)
|
|
8640
|
+
}
|
|
8641
|
+
}
|
|
8642
|
+
return [...new Set(value)]
|
|
8643
|
+
}
|
|
8644
|
+
|
|
8645
|
+
function lists(name, value) {
|
|
8646
|
+
if (value === undefined || value === null) return { cids: [], uids: [] }
|
|
8647
|
+
if (typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${name} must be an object`)
|
|
8648
|
+
for (const key of Object.keys(value)) {
|
|
8649
|
+
if (!LISTS.includes(key)) throw new TypeError(`unknown ${name}.${key}`)
|
|
8650
|
+
}
|
|
8651
|
+
return { cids: entries(`${name}.cids`, value.cids), uids: entries(`${name}.uids`, value.uids) }
|
|
8652
|
+
}
|
|
8653
|
+
|
|
8654
|
+
/**
|
|
8655
|
+
* A checked copy of a policy with every field present, or null for "no policy" (null, undefined, '').
|
|
8656
|
+
* Accepts JSON text. Throws TypeError/RangeError on an invalid policy.
|
|
8657
|
+
*/
|
|
8658
|
+
function normalizeDeliveryPolicy(raw) {
|
|
8659
|
+
if (raw === undefined || raw === null || raw === '') return null
|
|
8660
|
+
let policy = raw;
|
|
8661
|
+
if (typeof raw === 'string') {
|
|
8662
|
+
try { policy = JSON.parse(raw); } catch { throw new TypeError('delivery policy is not valid JSON') }
|
|
8663
|
+
}
|
|
8664
|
+
if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new TypeError('delivery policy must be an object')
|
|
8665
|
+
for (const key of Object.keys(policy)) {
|
|
8666
|
+
if (!['v', 'mode', 'anonymous', 'publish', 'allow', 'deny', 'updatedAt'].includes(key)) throw new TypeError(`unknown delivery policy field ${key}`)
|
|
8667
|
+
}
|
|
8668
|
+
if (policy.v !== undefined && policy.v !== 1) throw new TypeError('delivery policy version must be 1')
|
|
8669
|
+
const mode = policy.mode ?? 'open';
|
|
8670
|
+
if (!DELIVERY_POLICY_MODES.includes(mode)) throw new TypeError(`delivery policy mode must be one of: ${DELIVERY_POLICY_MODES.join(', ')}`)
|
|
8671
|
+
const anonymous = policy.anonymous ?? (mode === 'allowlist' ? 'deny' : 'allow');
|
|
8672
|
+
if (anonymous !== 'allow' && anonymous !== 'deny') throw new TypeError("delivery policy anonymous must be 'allow' or 'deny'")
|
|
8673
|
+
const publish = policy.publish ?? 'all';
|
|
8674
|
+
if (publish !== 'all' && publish !== 'policy') throw new TypeError("delivery policy publish must be 'all' or 'policy'")
|
|
8675
|
+
const normalized = { v: 1, mode, anonymous, publish, allow: lists('allow', policy.allow), deny: lists('deny', policy.deny) };
|
|
8676
|
+
if (policy.updatedAt !== undefined) {
|
|
8677
|
+
if (!Number.isSafeInteger(policy.updatedAt) || policy.updatedAt < 0) throw new TypeError('delivery policy updatedAt must be a time in ms')
|
|
8678
|
+
normalized.updatedAt = policy.updatedAt;
|
|
8679
|
+
}
|
|
8680
|
+
return normalized
|
|
8681
|
+
}
|
|
8682
|
+
|
|
8683
|
+
/**
|
|
8684
|
+
* The form Manager checks per message, or null when nothing is filtered (no owner, no policy, open).
|
|
8685
|
+
* Never throws: a stored policy that cannot be read only lets the owner's own senders through
|
|
8686
|
+
* (fail closed), since ignoring it would deliver what the owner asked to block.
|
|
8687
|
+
*/
|
|
8688
|
+
function compileDeliveryPolicy(raw, ownerUid) {
|
|
8689
|
+
if (typeof ownerUid !== 'string' || !ownerUid) return null
|
|
8690
|
+
let policy;
|
|
8691
|
+
try {
|
|
8692
|
+
policy = normalizeDeliveryPolicy(raw);
|
|
8693
|
+
} catch (error) {
|
|
8694
|
+
console.warn(`[iosignal] unreadable delivery policy of uid ${ownerUid}, owner only:`, error.message);
|
|
8695
|
+
policy = { mode: 'allowlist', anonymous: 'deny', publish: 'policy', allow: { cids: [], uids: [] }, deny: { cids: [], uids: [] } };
|
|
8696
|
+
}
|
|
8697
|
+
if (!policy || policy.mode === 'open') return null
|
|
8698
|
+
return Object.freeze({
|
|
8699
|
+
owner: ownerUid,
|
|
8700
|
+
mode: policy.mode,
|
|
8701
|
+
defaultAllow: policy.mode === 'denylist',
|
|
8702
|
+
anonymousAllow: policy.anonymous === 'allow',
|
|
8703
|
+
filterPublish: policy.publish === 'policy',
|
|
8704
|
+
allowCids: new Set(policy.allow.cids),
|
|
8705
|
+
denyCids: new Set(policy.deny.cids),
|
|
8706
|
+
allowUids: new Set(policy.allow.uids),
|
|
8707
|
+
denyUids: new Set(policy.deny.uids)
|
|
8708
|
+
})
|
|
8709
|
+
}
|
|
8710
|
+
|
|
8711
|
+
/** True if `target` (whose compiled policy is target.rxPolicy) accepts a unicast from `sender`. */
|
|
8712
|
+
function deliveryAllowed(target, sender) {
|
|
8713
|
+
const policy = target.rxPolicy;
|
|
8714
|
+
if (!policy) return true
|
|
8715
|
+
if (sender === target) return true
|
|
8716
|
+
const authorized = sender.boho?.isAuthorized === true;
|
|
8717
|
+
const uid = typeof sender.uid === 'string' && sender.uid ? sender.uid : null;
|
|
8718
|
+
if (uid === policy.owner) return true
|
|
8719
|
+
if (authorized && sender.role === 'admin') return true
|
|
8720
|
+
// An anonymous connection's CID is random per connection, so CID rules are for authenticated ones.
|
|
8721
|
+
if (authorized) {
|
|
8722
|
+
if (policy.denyCids.has(sender.cid)) return false
|
|
8723
|
+
if (policy.allowCids.has(sender.cid)) return true
|
|
8724
|
+
}
|
|
8725
|
+
if (uid) {
|
|
8726
|
+
if (policy.denyUids.has(uid)) return false
|
|
8727
|
+
if (policy.allowUids.has(uid)) return true
|
|
8728
|
+
}
|
|
8729
|
+
if (!authorized && !uid) return policy.anonymousAllow
|
|
8730
|
+
return policy.defaultAllow
|
|
8731
|
+
}
|
|
8732
|
+
|
|
8433
8733
|
const encoder = new TextEncoder();
|
|
8434
8734
|
const decoder$1 = new TextDecoder();
|
|
8435
8735
|
|
|
@@ -8437,14 +8737,18 @@ class Manager {
|
|
|
8437
8737
|
|
|
8438
8738
|
constructor(server, authManager) {
|
|
8439
8739
|
this.server = server;
|
|
8440
|
-
|
|
8441
|
-
this.
|
|
8740
|
+
// This server's settings; a Manager made without a Server (tests, checks) uses the defaults.
|
|
8741
|
+
this.pingPeriod = server?.heartbeatInterval ?? serverOption.heartbeatInterval;
|
|
8742
|
+
this.pingGrace = server?.heartbeatGrace ?? serverOption.heartbeatGrace;
|
|
8442
8743
|
if (!Number.isFinite(this.pingPeriod) || this.pingPeriod <= 0 ||
|
|
8443
8744
|
!Number.isFinite(this.pingGrace) || this.pingGrace < 0) {
|
|
8444
8745
|
throw new RangeError('Invalid heartbeat period or grace');
|
|
8445
8746
|
}
|
|
8446
|
-
|
|
8447
|
-
this.
|
|
8747
|
+
// Cumulative since the server started; never reset (readers compute rates from deltas).
|
|
8748
|
+
this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
|
|
8749
|
+
publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
|
|
8750
|
+
peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
|
|
8751
|
+
policyDenied: 0 }; // unicasts and CID publications a device's delivery policy kept back
|
|
8448
8752
|
|
|
8449
8753
|
this.authManager = authManager;
|
|
8450
8754
|
|
|
@@ -8462,7 +8766,12 @@ class Manager {
|
|
|
8462
8766
|
|
|
8463
8767
|
this.remotes = new Set(); // total remotes
|
|
8464
8768
|
this.cid2remote = new Map(); // key: cid -> value: remote
|
|
8769
|
+
this.accountConnectionCounts = new Map(); // uid -> authenticated connections
|
|
8465
8770
|
this.retain_messages = new Map(); // key: tag, data: signalMessage
|
|
8771
|
+
this.retain_owner = new Map(); // key: channel retain tag -> its owner record (see retainOwner)
|
|
8772
|
+
this.retainOwners = new Map(); // key: 'cid:<cid>' | 'conn:<ssid>' | 'net:<HOME_CHANNEL>' -> owner
|
|
8773
|
+
this.retainExpiry = new Map(); // key: channel retain tag in a grace pool -> expiry time
|
|
8774
|
+
this.retainBytes = 0; // all retained messages, channel and CID
|
|
8466
8775
|
this.channel_map = new Map(); // key: channelName -> value: < remote : Set >
|
|
8467
8776
|
this.CHANNEL_PREFIX = 'CH:';
|
|
8468
8777
|
this.CID_PREFIX = 'CID:';
|
|
@@ -8484,18 +8793,80 @@ class Manager {
|
|
|
8484
8793
|
};
|
|
8485
8794
|
this.pingIntervalID = setTimeout(tick, this.pingTickMs);
|
|
8486
8795
|
|
|
8487
|
-
|
|
8488
|
-
|
|
8489
|
-
|
|
8490
|
-
}, serverOption.monitorPeriod);
|
|
8796
|
+
// logStats: one summary line per interval; it never clears the terminal, so other logs stay.
|
|
8797
|
+
if (server.logStats) {
|
|
8798
|
+
this.statsIntervalID = setInterval(() => console.log(this.metrics.summaryLine()), server.logStats);
|
|
8491
8799
|
}
|
|
8492
8800
|
|
|
8493
8801
|
|
|
8494
8802
|
}
|
|
8495
8803
|
|
|
8496
8804
|
|
|
8805
|
+
get retainOptions() {
|
|
8806
|
+
return this.server?.retain ?? serverOption.retain
|
|
8807
|
+
}
|
|
8808
|
+
|
|
8809
|
+
get quotas() {
|
|
8810
|
+
return this.server?.quotas ?? serverOption.quotas
|
|
8811
|
+
}
|
|
8812
|
+
|
|
8813
|
+
get anonymousQuota() {
|
|
8814
|
+
return this.server?.anonymousQuota ?? serverOption.anonymousQuota
|
|
8815
|
+
}
|
|
8816
|
+
|
|
8817
|
+
// Authenticated connections per account (uid), for the quota's maxConnections.
|
|
8818
|
+
accountConnections(uid) {
|
|
8819
|
+
return this.accountConnectionCounts.get(uid) ?? 0
|
|
8820
|
+
}
|
|
8821
|
+
|
|
8822
|
+
addAccountConnection(remote, uid) {
|
|
8823
|
+
remote.accountUid = uid;
|
|
8824
|
+
this.accountConnectionCounts.set(uid, this.accountConnections(uid) + 1);
|
|
8825
|
+
}
|
|
8826
|
+
|
|
8827
|
+
/**
|
|
8828
|
+
* Replace the delivery policy of the connected, owned device with this CID (see deliveryPolicy.js);
|
|
8829
|
+
* the next unicast to it already uses the new one. A new login reads the stored policy again.
|
|
8830
|
+
* Returns false when no such connection is here or it has no owner (never filtered).
|
|
8831
|
+
* Throws on an invalid policy, so a caller cannot install one by mistake.
|
|
8832
|
+
*/
|
|
8833
|
+
setDeliveryPolicy(cid, policy) {
|
|
8834
|
+
const remote = this.cid2remote.get(cid);
|
|
8835
|
+
if (!remote?.boho.isAuthorized || !remote.ownerUid) return false
|
|
8836
|
+
normalizeDeliveryPolicy(policy);
|
|
8837
|
+
remote.rxPolicy = compileDeliveryPolicy(policy, remote.ownerUid);
|
|
8838
|
+
return true
|
|
8839
|
+
}
|
|
8840
|
+
|
|
8841
|
+
/**
|
|
8842
|
+
* Count a message a delivery policy kept from `other` (unicast from it, or a publication to it) and,
|
|
8843
|
+
* when someone listens, emit 'delivery:denied' on the server with what the server knows of both:
|
|
8844
|
+
* { kind: 'unicast' | 'publish', cid, did, owner, other: { cid, uid, ip, authenticated }, at }.
|
|
8845
|
+
* An anonymous connection's CID is not reported (random per connection).
|
|
8846
|
+
*/
|
|
8847
|
+
deliveryDenied(device, other, kind) {
|
|
8848
|
+
this.counters.policyDenied++;
|
|
8849
|
+
if (!this.server?.listenerCount?.('delivery:denied')) return
|
|
8850
|
+
const authenticated = other.boho?.isAuthorized === true;
|
|
8851
|
+
this.server.emit('delivery:denied', {
|
|
8852
|
+
kind, cid: device.cid, did: device.did, owner: device.ownerUid,
|
|
8853
|
+
other: { cid: authenticated ? other.cid : null, uid: other.uid || null, ip: other.ip ?? null, authenticated },
|
|
8854
|
+
at: Date.now()
|
|
8855
|
+
});
|
|
8856
|
+
}
|
|
8857
|
+
|
|
8858
|
+
removeAccountConnection(remote) {
|
|
8859
|
+
const uid = remote.accountUid;
|
|
8860
|
+
if (!uid) return
|
|
8861
|
+
remote.accountUid = null;
|
|
8862
|
+
const count = this.accountConnections(uid) - 1;
|
|
8863
|
+
if (count > 0) this.accountConnectionCounts.set(uid, count);
|
|
8864
|
+
else this.accountConnectionCounts.delete(uid);
|
|
8865
|
+
}
|
|
8866
|
+
|
|
8497
8867
|
heartbeatTick() {
|
|
8498
8868
|
const now = node_perf_hooks.performance.now();
|
|
8869
|
+
if (this.retainExpiry.size) this.expireChannelRetains(now);
|
|
8499
8870
|
// Process only expired requests, not every connected peer.
|
|
8500
8871
|
for (const [remote, deadline] of this.heartbeatPending) {
|
|
8501
8872
|
if (deadline > now) break;
|
|
@@ -8538,6 +8909,7 @@ class Manager {
|
|
|
8538
8909
|
removeRemote(remote) {
|
|
8539
8910
|
|
|
8540
8911
|
remote._closing = true;
|
|
8912
|
+
this.removeAccountConnection(remote);
|
|
8541
8913
|
this.pingGroups[remote.pingGroup]?.delete(remote);
|
|
8542
8914
|
this.heartbeatPending.delete(remote);
|
|
8543
8915
|
remote.setState(STATE.CLOSED);
|
|
@@ -8563,6 +8935,10 @@ class Manager {
|
|
|
8563
8935
|
|
|
8564
8936
|
// retain message policy
|
|
8565
8937
|
// type 1. ( isAuthorizedUser) ? keep : delete.
|
|
8938
|
+
// Channel retains: an authenticated writer's belong to its account and stay; an anonymous
|
|
8939
|
+
// connection's move to its network's grace pool and expire there.
|
|
8940
|
+
this.orphanChannelRetains(remote);
|
|
8941
|
+
|
|
8566
8942
|
if (remote.boho.isAuthorized) ; else {
|
|
8567
8943
|
// anonymouse: remove the cid publish channel
|
|
8568
8944
|
for (let ch of remote.retain_signal.keys()) {
|
|
@@ -8574,6 +8950,10 @@ class Manager {
|
|
|
8574
8950
|
}
|
|
8575
8951
|
}
|
|
8576
8952
|
}
|
|
8953
|
+
// CID retains live in the remote and go with it (after the '@$state' close above).
|
|
8954
|
+
for (const message of remote.retain_signal.values()) this.retainBytes -= message.byteLength;
|
|
8955
|
+
remote.retain_signal.clear();
|
|
8956
|
+
remote.retainBytes = 0;
|
|
8577
8957
|
|
|
8578
8958
|
|
|
8579
8959
|
// Service lifecycle hook. Called directly: RPC permission/command checks do not apply to cleanup.
|
|
@@ -8645,9 +9025,7 @@ class Manager {
|
|
|
8645
9025
|
let topic = tag.split('@')[1];
|
|
8646
9026
|
if (cid && this.cid2remote.has(cid)) {
|
|
8647
9027
|
let sigPack = getSignalPack('@' + topic, ...args);
|
|
8648
|
-
|
|
8649
|
-
console.log('target', targetRemote.state, targetRemote.cid);
|
|
8650
|
-
targetRemote.send_enc_mode(sigPack);
|
|
9028
|
+
this.cid2remote.get(cid).send_enc_mode(sigPack);
|
|
8651
9029
|
return
|
|
8652
9030
|
} else {
|
|
8653
9031
|
return "no cid"
|
|
@@ -8656,7 +9034,7 @@ class Manager {
|
|
|
8656
9034
|
|
|
8657
9035
|
sender(tag, remote, message) {
|
|
8658
9036
|
if (encoder.encode(tag).byteLength > SIZE_LIMIT.TAG_LEN1) return ['err', 'Tag exceeds 255 UTF-8 bytes']
|
|
8659
|
-
if (serverOption.membersOnly && !remote.boho.isAuthorized) {
|
|
9037
|
+
if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
|
|
8660
9038
|
// console.log("### server reject client signal reason: [membersOnly]" ,tag, remote.cid )
|
|
8661
9039
|
remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
|
|
8662
9040
|
remote.close();
|
|
@@ -8666,6 +9044,8 @@ class Manager {
|
|
|
8666
9044
|
if (tag.indexOf('$') == 0) return ['err', 'prefix $ is reserved for userSet tag.']
|
|
8667
9045
|
|
|
8668
9046
|
let cidIndex = tag.indexOf('@');
|
|
9047
|
+
// A device whose policy also covers its publications: each subscriber is checked (see deliveryPolicy.js).
|
|
9048
|
+
const publisher = cidIndex === 0 && remote.rxPolicy?.filterPublish ? remote : null;
|
|
8669
9049
|
if (cidIndex === 0) {
|
|
8670
9050
|
// ** CID_PUB multi-cast
|
|
8671
9051
|
// [cid_pub] @topic , @$retainTopic
|
|
@@ -8677,14 +9057,20 @@ class Manager {
|
|
|
8677
9057
|
} else if (cidIndex > 0) {
|
|
8678
9058
|
// uni-cast.
|
|
8679
9059
|
let targetCId = tag.split('@')[0];
|
|
8680
|
-
|
|
9060
|
+
const target = this.cid2remote.get(targetCId);
|
|
9061
|
+
if (target && !deliveryAllowed(target, remote)) {
|
|
9062
|
+
// Same answer as an offline CID: a sender cannot tell it is blocked, or probe the policy.
|
|
9063
|
+
this.deliveryDenied(target, remote, 'unicast');
|
|
9064
|
+
return ['err', 'Invalid cid']
|
|
9065
|
+
}
|
|
9066
|
+
if (target) {
|
|
8681
9067
|
//rm cid from tag.
|
|
8682
9068
|
let ommitCIdTag = '@' + tag.split('@')[1];
|
|
8683
9069
|
// console.log('uni-cast tag change from', tag, 'to' , ommitCIdTag )
|
|
8684
9070
|
message = this.getNewSignalTagMessage(message, ommitCIdTag);
|
|
8685
9071
|
if (!message) return ['err', 'Tag exceeds 255 UTF-8 bytes']
|
|
8686
9072
|
// console.log(`origin tag: ${tag} omitTag: ${this.getSignalTag(message)}`)
|
|
8687
|
-
|
|
9073
|
+
target.send_enc_mode(message);
|
|
8688
9074
|
return ['ok', 1]
|
|
8689
9075
|
}
|
|
8690
9076
|
return ['err', 'Invalid cid']
|
|
@@ -8710,35 +9096,26 @@ class Manager {
|
|
|
8710
9096
|
// retain signal message
|
|
8711
9097
|
if (tag.includes('$')
|
|
8712
9098
|
// && remote.boho.isAuthorized
|
|
8713
|
-
&&
|
|
8714
|
-
&& serverOption.retain.limitCounter > this.retain_messages.size
|
|
8715
|
-
&& serverOption.retain.limitSize > message.byteLength
|
|
9099
|
+
&& this.retainOptions.enabled
|
|
8716
9100
|
) {
|
|
8717
|
-
// cid retain signal
|
|
8718
9101
|
if (tag.includes('@')) {
|
|
8719
|
-
// cid retain signal stored inside remote.
|
|
8720
|
-
|
|
8721
|
-
remote.retain_signal.set(retainTag, message);
|
|
9102
|
+
// cid retain signal stored inside remote, counted per remote.
|
|
9103
|
+
this.storeCidRetain(tag.split('@')[1], message, remote);
|
|
8722
9104
|
} else {
|
|
8723
9105
|
// channel retain signal stored inside manager.
|
|
8724
|
-
this.
|
|
9106
|
+
this.storeChannelRetain(tag, message, remote);
|
|
8725
9107
|
}
|
|
8726
|
-
|
|
8727
9108
|
}
|
|
8728
9109
|
|
|
8729
|
-
|
|
9110
|
+
this.counters.publishes++;
|
|
8730
9111
|
let sentCounter = 0;
|
|
8731
9112
|
if (this.channel_map.has(tag)) {
|
|
8732
9113
|
// console.log('raw channel_map matched tag:', tag)
|
|
8733
9114
|
let remotes = this.channel_map.get(tag);
|
|
8734
9115
|
if (remotes.size >= 1) {
|
|
8735
|
-
|
|
8736
|
-
|
|
8737
|
-
|
|
8738
|
-
} else {
|
|
8739
|
-
limit = remotes.size;
|
|
8740
|
-
}
|
|
8741
|
-
if (this.telemetry) this.telemetry.quotaExcluded += remotes.size - limit;
|
|
9116
|
+
const fanout = remote.quota.fanout;
|
|
9117
|
+
const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
|
|
9118
|
+
this.counters.quotaExcluded += remotes.size - limit;
|
|
8742
9119
|
let peers = remotes.values();
|
|
8743
9120
|
while (sentCounter < limit) {
|
|
8744
9121
|
let c = peers.next().value;
|
|
@@ -8746,19 +9123,16 @@ class Manager {
|
|
|
8746
9123
|
// console.log('## null remote' )
|
|
8747
9124
|
break;
|
|
8748
9125
|
}
|
|
9126
|
+
if (publisher && !deliveryAllowed(publisher, c)) {
|
|
9127
|
+
this.deliveryDenied(publisher, c, 'publish');
|
|
9128
|
+
continue
|
|
9129
|
+
}
|
|
8749
9130
|
// change: from v4.x allow receiveSelfMessages.
|
|
8750
|
-
|
|
8751
|
-
|
|
8752
|
-
sentCounter++;
|
|
8753
|
-
// }
|
|
9131
|
+
c.send_enc_mode(message);
|
|
9132
|
+
sentCounter++;
|
|
8754
9133
|
}
|
|
8755
9134
|
|
|
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;
|
|
9135
|
+
this.counters.deliveryAttempts += sentCounter;
|
|
8762
9136
|
return ['ok', sentCounter]
|
|
8763
9137
|
}
|
|
8764
9138
|
}
|
|
@@ -8768,6 +9142,123 @@ class Manager {
|
|
|
8768
9142
|
|
|
8769
9143
|
|
|
8770
9144
|
|
|
9145
|
+
// Retained messages are stored as exact-size copies (a subarray would keep a whole socket chunk
|
|
9146
|
+
// or 8 KiB Buffer pool slab alive), within an owner's budget and bytesTotal server-wide. A value
|
|
9147
|
+
// that cannot be stored (size, count or budget) also removes the value it would replace, so a
|
|
9148
|
+
// later subscriber never gets a stale one.
|
|
9149
|
+
retainFits(message, freed, ownerBytes, budget) {
|
|
9150
|
+
return this.retainOptions.limitSize > message.byteLength &&
|
|
9151
|
+
ownerBytes + message.byteLength <= budget &&
|
|
9152
|
+
this.retainBytes + message.byteLength - freed <= this.retainOptions.bytesTotal
|
|
9153
|
+
}
|
|
9154
|
+
|
|
9155
|
+
retainCopy(message) {
|
|
9156
|
+
const copy = Buffer.allocUnsafeSlow(message.byteLength);
|
|
9157
|
+
copy.set(message);
|
|
9158
|
+
this.retainBytes += copy.byteLength;
|
|
9159
|
+
return copy
|
|
9160
|
+
}
|
|
9161
|
+
|
|
9162
|
+
// A connection's CID retains go with it: within bytesPerConnection; limitCounter caps new tags.
|
|
9163
|
+
storeCidRetain(key, message, remote) {
|
|
9164
|
+
const map = remote.retain_signal;
|
|
9165
|
+
const old = map.get(key);
|
|
9166
|
+
const freed = old?.byteLength ?? 0;
|
|
9167
|
+
if ((old || map.size < this.retainOptions.limitCounter) &&
|
|
9168
|
+
this.retainFits(message, freed, remote.retainBytes - freed, this.retainOptions.bytesPerConnection)) {
|
|
9169
|
+
map.set(key, this.retainCopy(message));
|
|
9170
|
+
this.retainBytes -= freed;
|
|
9171
|
+
remote.retainBytes += message.byteLength - freed;
|
|
9172
|
+
} else if (old) {
|
|
9173
|
+
map.delete(key);
|
|
9174
|
+
this.retainBytes -= freed;
|
|
9175
|
+
remote.retainBytes -= freed;
|
|
9176
|
+
}
|
|
9177
|
+
}
|
|
9178
|
+
|
|
9179
|
+
// Channel retain owner: the last writer's account (an authenticated CID, shared by its
|
|
9180
|
+
// connections, so reconnecting does not reset its budget) or an anonymous writer's connection.
|
|
9181
|
+
// Each owner holds at most tagsPerOwner tags and bytesPerOwner bytes.
|
|
9182
|
+
retainOwner(key) {
|
|
9183
|
+
let owner = this.retainOwners.get(key);
|
|
9184
|
+
if (!owner) this.retainOwners.set(key, owner = { key, bytes: 0, tags: new Set() });
|
|
9185
|
+
return owner
|
|
9186
|
+
}
|
|
9187
|
+
|
|
9188
|
+
storeChannelRetain(tag, message, remote) {
|
|
9189
|
+
const owner = this.retainOwner(remote.boho.isAuthorized ? 'cid:' + remote.cid : 'conn:' + remote.ssid);
|
|
9190
|
+
const old = this.retain_messages.get(tag);
|
|
9191
|
+
const freed = old?.byteLength ?? 0;
|
|
9192
|
+
const room = old || (this.retain_messages.size < this.retainOptions.limitCounter &&
|
|
9193
|
+
owner.tags.size < this.retainOptions.tagsPerOwner);
|
|
9194
|
+
const ownerBytes = owner.bytes - (this.retain_owner.get(tag) === owner ? freed : 0);
|
|
9195
|
+
if (room && this.retainFits(message, freed, ownerBytes, this.retainOptions.bytesPerOwner)) {
|
|
9196
|
+
if (old) this.releaseChannelRetain(tag, freed);
|
|
9197
|
+
this.retain_messages.set(tag, this.retainCopy(message));
|
|
9198
|
+
owner.bytes += message.byteLength;
|
|
9199
|
+
owner.tags.add(tag);
|
|
9200
|
+
this.retain_owner.set(tag, owner);
|
|
9201
|
+
this.retainOwners.set(owner.key, owner); // releasing may have removed it when it emptied
|
|
9202
|
+
} else if (old) {
|
|
9203
|
+
this.dropChannelRetain(tag);
|
|
9204
|
+
}
|
|
9205
|
+
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
9206
|
+
}
|
|
9207
|
+
|
|
9208
|
+
// A closed anonymous connection's channel retains stay anonymousGraceMs in its network's pool
|
|
9209
|
+
// (by HOME_CHANNEL), which has the same owner budget: reconnecting cannot pile values up, and
|
|
9210
|
+
// when the pool is over budget the values closest to expiry go first, least recently written
|
|
9211
|
+
// first among equals (an update moves its tag to the end of the owner's set).
|
|
9212
|
+
orphanChannelRetains(remote) {
|
|
9213
|
+
const conn = this.retainOwners.get('conn:' + remote.ssid);
|
|
9214
|
+
if (!conn) return
|
|
9215
|
+
const grace = this.retainOptions.anonymousGraceMs;
|
|
9216
|
+
if (!(grace > 0)) {
|
|
9217
|
+
for (const tag of [...conn.tags]) this.dropChannelRetain(tag);
|
|
9218
|
+
return
|
|
9219
|
+
}
|
|
9220
|
+
this.retainOwners.delete(conn.key);
|
|
9221
|
+
const pool = this.retainOwner('net:' + remote.HOME_CHANNEL);
|
|
9222
|
+
const expires = node_perf_hooks.performance.now() + grace;
|
|
9223
|
+
for (const tag of conn.tags) {
|
|
9224
|
+
pool.tags.add(tag);
|
|
9225
|
+
pool.bytes += this.retain_messages.get(tag).byteLength;
|
|
9226
|
+
this.retain_owner.set(tag, pool);
|
|
9227
|
+
this.retainExpiry.set(tag, expires);
|
|
9228
|
+
}
|
|
9229
|
+
while (pool.bytes > this.retainOptions.bytesPerOwner || pool.tags.size > this.retainOptions.tagsPerOwner) {
|
|
9230
|
+
let first;
|
|
9231
|
+
for (const tag of pool.tags) {
|
|
9232
|
+
if (first === undefined || this.retainExpiry.get(tag) < this.retainExpiry.get(first)) first = tag;
|
|
9233
|
+
}
|
|
9234
|
+
this.dropChannelRetain(first);
|
|
9235
|
+
}
|
|
9236
|
+
}
|
|
9237
|
+
|
|
9238
|
+
expireChannelRetains(now = node_perf_hooks.performance.now()) {
|
|
9239
|
+
for (const [tag, expires] of this.retainExpiry) {
|
|
9240
|
+
if (expires <= now) this.dropChannelRetain(tag);
|
|
9241
|
+
}
|
|
9242
|
+
}
|
|
9243
|
+
|
|
9244
|
+
dropChannelRetain(tag) {
|
|
9245
|
+
const old = this.retain_messages.get(tag);
|
|
9246
|
+
if (!old) return
|
|
9247
|
+
this.releaseChannelRetain(tag, old.byteLength);
|
|
9248
|
+
this.retain_messages.delete(tag);
|
|
9249
|
+
}
|
|
9250
|
+
|
|
9251
|
+
releaseChannelRetain(tag, size) {
|
|
9252
|
+
const owner = this.retain_owner.get(tag);
|
|
9253
|
+
this.retain_owner.delete(tag);
|
|
9254
|
+
this.retainExpiry.delete(tag);
|
|
9255
|
+
this.retainBytes -= size;
|
|
9256
|
+
if (!owner) return
|
|
9257
|
+
owner.tags.delete(tag);
|
|
9258
|
+
owner.bytes -= size;
|
|
9259
|
+
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
9260
|
+
}
|
|
9261
|
+
|
|
8771
9262
|
subscribe(chArr, remote) {
|
|
8772
9263
|
chArr.forEach(tag => {
|
|
8773
9264
|
if (tag.indexOf('#') === 0) {
|
|
@@ -8790,15 +9281,20 @@ class Manager {
|
|
|
8790
9281
|
|
|
8791
9282
|
// 3. send retain message if available.
|
|
8792
9283
|
if (tag.includes('$')
|
|
8793
|
-
&&
|
|
9284
|
+
&& this.retainOptions.enabled
|
|
8794
9285
|
) {
|
|
8795
9286
|
let retainMessage;
|
|
8796
9287
|
if (tag.includes('@')) {
|
|
8797
9288
|
let cid = tag.split('@')[0];
|
|
8798
9289
|
cid = cid.split(this.CID_PREFIX)[1];
|
|
8799
9290
|
let retainTag = tag.split('@')[1];
|
|
8800
|
-
|
|
8801
|
-
|
|
9291
|
+
const owner = this.cid2remote.get(cid);
|
|
9292
|
+
if (owner) {
|
|
9293
|
+
if (owner.rxPolicy?.filterPublish && !deliveryAllowed(owner, remote)) {
|
|
9294
|
+
this.deliveryDenied(owner, remote, 'publish');
|
|
9295
|
+
return;
|
|
9296
|
+
}
|
|
9297
|
+
retainMessage = owner.retain_signal.get(retainTag);
|
|
8802
9298
|
} else {
|
|
8803
9299
|
// console.log('cid subscribe is rejected. not online:', cid)
|
|
8804
9300
|
return;
|
|
@@ -8856,31 +9352,6 @@ class Manager {
|
|
|
8856
9352
|
}
|
|
8857
9353
|
|
|
8858
9354
|
|
|
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
9355
|
anonymousCidRandom(size) {
|
|
8885
9356
|
return globalThis.crypto.getRandomValues(Buffer.alloc(size))
|
|
8886
9357
|
}
|
|
@@ -8913,8 +9384,8 @@ class Manager {
|
|
|
8913
9384
|
clearTimeout(this.pingIntervalID);
|
|
8914
9385
|
this.heartbeatPending.clear();
|
|
8915
9386
|
for (const group of this.pingGroups) group.clear();
|
|
8916
|
-
if (this.
|
|
8917
|
-
clearInterval(this.
|
|
9387
|
+
if (this.statsIntervalID) {
|
|
9388
|
+
clearInterval(this.statsIntervalID);
|
|
8918
9389
|
}
|
|
8919
9390
|
|
|
8920
9391
|
this.remotes.forEach(remote => {
|
|
@@ -8924,6 +9395,10 @@ class Manager {
|
|
|
8924
9395
|
this.remotes.clear();
|
|
8925
9396
|
this.cid2remote.clear();
|
|
8926
9397
|
this.retain_messages.clear();
|
|
9398
|
+
this.retain_owner.clear();
|
|
9399
|
+
this.retainOwners.clear();
|
|
9400
|
+
this.retainExpiry.clear();
|
|
9401
|
+
this.retainBytes = 0;
|
|
8927
9402
|
this.channel_map.clear();
|
|
8928
9403
|
|
|
8929
9404
|
}
|
|
@@ -8948,15 +9423,42 @@ function validateDuplicateLogin(policy) {
|
|
|
8948
9423
|
return policy
|
|
8949
9424
|
}
|
|
8950
9425
|
|
|
9426
|
+
// Connection roles, lowest to highest: what a connection may do. Its quota is separate.
|
|
9427
|
+
// 'anonymous' is the role of every connection until it authenticates.
|
|
9428
|
+
const ROLES = ['anonymous', 'device', 'service', 'admin'];
|
|
9429
|
+
|
|
9430
|
+
/** Role of a login: the account's role, 'device' when it has none; undefined if unknown. */
|
|
9431
|
+
function resolveRole(role) {
|
|
9432
|
+
if (role === undefined || role === null || role === '') return 'device'
|
|
9433
|
+
return ROLES.includes(role) && role !== 'anonymous' ? role : undefined
|
|
9434
|
+
}
|
|
9435
|
+
|
|
9436
|
+
/** True if the remote is authenticated with this role or a higher one ('anonymous': always). */
|
|
9437
|
+
function hasRole(remote, role) {
|
|
9438
|
+
const wanted = ROLES.indexOf(role);
|
|
9439
|
+
if (wanted < 0) throw new RangeError(`role must be one of: ${ROLES.join(', ')}`)
|
|
9440
|
+
if (wanted === 0) return true
|
|
9441
|
+
return remote?.boho?.isAuthorized === true && ROLES.indexOf(remote.role) >= wanted
|
|
9442
|
+
}
|
|
9443
|
+
|
|
9444
|
+
/** Default quota profile of a login: the account's quota, else 'basic' for a device, 'unlimited' otherwise. */
|
|
9445
|
+
function defaultQuota(authInfo, role) {
|
|
9446
|
+
return authInfo.quota || (role === 'device' ? 'basic' : 'unlimited')
|
|
9447
|
+
}
|
|
9448
|
+
|
|
8951
9449
|
class BohoAuth {
|
|
8952
9450
|
/**
|
|
8953
9451
|
* @param {object} keyProvider
|
|
8954
|
-
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any
|
|
9452
|
+
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any,
|
|
9453
|
+
* resolveQuota?: (authInfo: object, role: string) => string | Promise<string> }} [options]
|
|
8955
9454
|
* duplicateLogin: unset follows serverOption.auth.duplicateLogin (default 'keepNew').
|
|
9455
|
+
* A Server's duplicateLogin option takes precedence for that Server's connections.
|
|
8956
9456
|
* onAuthEvent: called with { type, did, cid, uid, ip, oldIp, socketType, oldSocketType, reason, at }
|
|
8957
9457
|
* for 'replaced' (keepNew evicted the old connection) and 'duplicate_rejected' (keepOld).
|
|
8958
9458
|
* socketType/oldSocketType are 'websocket' or 'congsocket'.
|
|
8959
9459
|
* Errors and rejected promises are logged and never affect authentication.
|
|
9460
|
+
* resolveQuota: name of the Server quota profile for a login (default: defaultQuota), e.g. from
|
|
9461
|
+
* the account owner's plan. An unknown name fails the login.
|
|
8960
9462
|
*/
|
|
8961
9463
|
constructor(keyProvider, options = {}) {
|
|
8962
9464
|
if (!keyProvider) {
|
|
@@ -8966,6 +9468,7 @@ class BohoAuth {
|
|
|
8966
9468
|
this._duplicateLogin = null;
|
|
8967
9469
|
if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
|
|
8968
9470
|
this.onAuthEvent = options.onAuthEvent ?? null;
|
|
9471
|
+
this.resolveQuota = options.resolveQuota ?? defaultQuota;
|
|
8969
9472
|
this.authLogger;
|
|
8970
9473
|
if (serverOption.fileLogger.auth.use) {
|
|
8971
9474
|
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
@@ -8983,6 +9486,11 @@ class BohoAuth {
|
|
|
8983
9486
|
this._duplicateLogin = policy === null ? null : validateDuplicateLogin(policy);
|
|
8984
9487
|
}
|
|
8985
9488
|
|
|
9489
|
+
/** Policy for a connection: its Server's duplicateLogin option, else this instance's policy. */
|
|
9490
|
+
duplicateLoginFor(peer) {
|
|
9491
|
+
return peer.manager?.server?.duplicateLogin ?? this.duplicateLogin;
|
|
9492
|
+
}
|
|
9493
|
+
|
|
8986
9494
|
// Backward-compatible boolean form of duplicateLogin.
|
|
8987
9495
|
get keepOldConnection() {
|
|
8988
9496
|
return this.duplicateLogin === 'keepOld';
|
|
@@ -9015,7 +9523,7 @@ class BohoAuth {
|
|
|
9015
9523
|
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
9016
9524
|
peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
9017
9525
|
}
|
|
9018
|
-
}, serverOption.auth.
|
|
9526
|
+
}, serverOption.auth.failDelay);
|
|
9019
9527
|
}
|
|
9020
9528
|
|
|
9021
9529
|
|
|
@@ -9049,8 +9557,9 @@ class BohoAuth {
|
|
|
9049
9557
|
return
|
|
9050
9558
|
}
|
|
9051
9559
|
|
|
9560
|
+
// Never the key: debug output ends up in shared logs.
|
|
9052
9561
|
if (serverOption.debug.showAuthInfo) {
|
|
9053
|
-
console.log('[debug]showAuthInfo', authInfo);
|
|
9562
|
+
console.log('[debug]showAuthInfo', { id, cid: authInfo.cid, uid: authInfo.uid, role: authInfo.role, quota: authInfo.quota });
|
|
9054
9563
|
}
|
|
9055
9564
|
|
|
9056
9565
|
peer.boho.copy_id8(infoPack.id8);
|
|
@@ -9077,7 +9586,29 @@ class BohoAuth {
|
|
|
9077
9586
|
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9078
9587
|
peer._challengeUsed = true;
|
|
9079
9588
|
|
|
9080
|
-
//4.
|
|
9589
|
+
//4. role and quota. Checked before a duplicate login replaces the old connection.
|
|
9590
|
+
const role = resolveRole(authInfo.role);
|
|
9591
|
+
if (role === undefined) {
|
|
9592
|
+
this.send_auth_fail(peer, 'unknown auth.role: ' + authInfo.role);
|
|
9593
|
+
return
|
|
9594
|
+
}
|
|
9595
|
+
const quotaName = await this.resolveQuota(authInfo, role);
|
|
9596
|
+
const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
|
|
9597
|
+
if (!quota) {
|
|
9598
|
+
this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
|
|
9599
|
+
return
|
|
9600
|
+
}
|
|
9601
|
+
if (peer._closing) return; // closed while resolving
|
|
9602
|
+
const uid = authInfo.uid || null;
|
|
9603
|
+
if (uid && quota.maxConnections !== null) {
|
|
9604
|
+
// A connection this login replaces (keepNew) frees its place.
|
|
9605
|
+
const old = peer.manager.cid2remote.get(authInfo.cid);
|
|
9606
|
+
const replaced = old && old !== peer && old.accountUid === uid && this.duplicateLoginFor(peer) === 'keepNew' ? 1 : 0;
|
|
9607
|
+
if (peer.manager.accountConnections(uid) - replaced >= quota.maxConnections) {
|
|
9608
|
+
this.send_auth_fail(peer, 'too many connections');
|
|
9609
|
+
return
|
|
9610
|
+
}
|
|
9611
|
+
}
|
|
9081
9612
|
|
|
9082
9613
|
//5. check duplicate login.
|
|
9083
9614
|
if (peer.manager.cid2remote.has(authInfo.cid) && peer.manager.cid2remote.get(authInfo.cid) !== peer) {
|
|
@@ -9089,7 +9620,8 @@ class BohoAuth {
|
|
|
9089
9620
|
$$1.MB('#MsgType', '8', IOMsg.AUTH_CLEAR),
|
|
9090
9621
|
$$1.MB('#reason', 'duplicate login.')
|
|
9091
9622
|
);
|
|
9092
|
-
|
|
9623
|
+
const keepOld = this.duplicateLoginFor(peer) === 'keepOld';
|
|
9624
|
+
if (keepOld) {
|
|
9093
9625
|
peer.boho.isAuthorized = false;
|
|
9094
9626
|
// keep old connection. reject new connection by sending auth_fail signal.
|
|
9095
9627
|
// peer.send(authClearSignal)
|
|
@@ -9105,13 +9637,13 @@ class BohoAuth {
|
|
|
9105
9637
|
old.close();
|
|
9106
9638
|
}
|
|
9107
9639
|
this.emitAuthEvent({
|
|
9108
|
-
type:
|
|
9640
|
+
type: keepOld ? 'duplicate_rejected' : 'replaced',
|
|
9109
9641
|
did: id, cid: authInfo.cid, uid: authInfo.uid || null,
|
|
9110
9642
|
ip: peer.ip, oldIp: old.ip,
|
|
9111
9643
|
socketType: transportOf(peer), oldSocketType: transportOf(old),
|
|
9112
9644
|
reason: 'duplicate login', at: Date.now()
|
|
9113
9645
|
});
|
|
9114
|
-
if (
|
|
9646
|
+
if (keepOld) return
|
|
9115
9647
|
}
|
|
9116
9648
|
|
|
9117
9649
|
//6. delete current (or anonymouse)cid if exist.
|
|
@@ -9125,27 +9657,15 @@ class BohoAuth {
|
|
|
9125
9657
|
peer.cid = authInfo.cid;
|
|
9126
9658
|
peer.nick = authInfo.cid; // temporary: nick as cid
|
|
9127
9659
|
if (authInfo.uid) peer.uid = authInfo.uid;
|
|
9660
|
+
// Delivery policy of an owned device, in place before the CID is reachable (step 9).
|
|
9661
|
+
peer.ownerUid = uid;
|
|
9662
|
+
peer.rxPolicy = compileDeliveryPolicy(authInfo.rxPolicy, uid);
|
|
9128
9663
|
|
|
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]));
|
|
9664
|
+
//8. role and quota; the client is told its quota.
|
|
9665
|
+
peer.role = role;
|
|
9666
|
+
if (role === 'admin') console.log('## LOGIN ADMIN CID:', peer.cid);
|
|
9667
|
+
if (uid) peer.manager.addAccountConnection(peer, uid);
|
|
9668
|
+
peer.setQuota(quotaName, true);
|
|
9149
9669
|
|
|
9150
9670
|
//9. set cid2remote
|
|
9151
9671
|
peer.manager.cid2remote.set(peer.cid, peer);
|
|
@@ -9174,9 +9694,9 @@ class BohoAuth {
|
|
|
9174
9694
|
}
|
|
9175
9695
|
}
|
|
9176
9696
|
|
|
9177
|
-
async addAuth(id, keyStr, cid,
|
|
9697
|
+
async addAuth(id, keyStr, cid, role, quota) {
|
|
9178
9698
|
if (typeof this.keyProvider.addAuth === 'function') {
|
|
9179
|
-
return this.keyProvider.addAuth(id, keyStr, cid,
|
|
9699
|
+
return this.keyProvider.addAuth(id, keyStr, cid, role, quota);
|
|
9180
9700
|
}
|
|
9181
9701
|
}
|
|
9182
9702
|
|
|
@@ -9202,7 +9722,8 @@ class BohoAuth {
|
|
|
9202
9722
|
*
|
|
9203
9723
|
* mode 'idKey': the key equals the ID, e.g. io.auth('dev1', 'dev1').
|
|
9204
9724
|
* mode 'sharedKey': any ID with the one shared key, e.g. io.auth('dev1', 'lab2026').
|
|
9205
|
-
*
|
|
9725
|
+
* role: role of every login, default 'device' ('service' or 'admin' must be asked for).
|
|
9726
|
+
* quota: Server quotas profile of every login, default from BohoAuth resolveQuota.
|
|
9206
9727
|
*
|
|
9207
9728
|
* example => new BohoAuth(new LocalKeyProvider({ mode: 'sharedKey', key: 'lab2026' }))
|
|
9208
9729
|
*
|
|
@@ -9215,23 +9736,27 @@ const hashKey = keyStr => Buffer.from(it.sha256.hash(keyStr)).toString('base64')
|
|
|
9215
9736
|
|
|
9216
9737
|
class LocalKeyProvider {
|
|
9217
9738
|
/**
|
|
9218
|
-
* @param {'idKey' | { mode: 'idKey' | 'sharedKey', key?: string,
|
|
9739
|
+
* @param {'idKey' | { mode: 'idKey' | 'sharedKey', key?: string,
|
|
9740
|
+
* role?: 'device' | 'service' | 'admin', quota?: string }} options
|
|
9219
9741
|
* A string is the mode alone.
|
|
9220
9742
|
*/
|
|
9221
9743
|
constructor(options) {
|
|
9222
|
-
const { mode, key,
|
|
9744
|
+
const { mode, key, role = 'device', quota } = typeof options === 'string' ? { mode: options } : (options ?? {});
|
|
9223
9745
|
if (!MODES.includes(mode)) {
|
|
9224
9746
|
throw new TypeError(`LocalKeyProvider mode must be one of: ${MODES.join(', ')}`)
|
|
9225
9747
|
}
|
|
9226
9748
|
if (mode === 'sharedKey' && (typeof key !== 'string' || key.length === 0)) {
|
|
9227
9749
|
throw new TypeError("LocalKeyProvider mode 'sharedKey' needs a non-empty key")
|
|
9228
9750
|
}
|
|
9229
|
-
|
|
9230
|
-
|
|
9231
|
-
|
|
9751
|
+
if (quota !== undefined && (typeof quota !== 'string' || !quota)) {
|
|
9752
|
+
throw new TypeError('LocalKeyProvider quota must be a quotas profile name')
|
|
9753
|
+
}
|
|
9754
|
+
if (!ROLES.includes(role) || role === 'anonymous') {
|
|
9755
|
+
throw new RangeError(`LocalKeyProvider role must be one of: ${ROLES.slice(1).join(', ')}`)
|
|
9232
9756
|
}
|
|
9233
9757
|
this.mode = mode;
|
|
9234
|
-
this.
|
|
9758
|
+
this.role = role;
|
|
9759
|
+
this.quota = quota;
|
|
9235
9760
|
// Hashed like StringKeyProvider, so a 44-character shared key is not mistaken for a stored hash.
|
|
9236
9761
|
this.sharedKeyHash = mode === 'sharedKey' ? hashKey(key) : null;
|
|
9237
9762
|
}
|
|
@@ -9241,18 +9766,128 @@ class LocalKeyProvider {
|
|
|
9241
9766
|
return {
|
|
9242
9767
|
key: this.sharedKeyHash ?? hashKey(id),
|
|
9243
9768
|
cid: id,
|
|
9244
|
-
|
|
9769
|
+
role: this.role,
|
|
9770
|
+
...(this.quota && { quota: this.quota })
|
|
9245
9771
|
}
|
|
9246
9772
|
}
|
|
9247
9773
|
}
|
|
9248
9774
|
|
|
9775
|
+
// Removed or renamed in 9.0, as Server options and as serverOption keys ('global': only as a
|
|
9776
|
+
// serverOption key). An error names the replacement instead of the setting silently doing nothing.
|
|
9777
|
+
const REMOVED = [
|
|
9778
|
+
['showMessage', 'logMessages: true'],
|
|
9779
|
+
['showMetric', "logStats: <interval ms> (for lists, the sudo service's remotes/channels commands)"],
|
|
9780
|
+
['monitorPeriod', 'logStats: <interval ms>'],
|
|
9781
|
+
['timeout', 'heartbeatInterval'],
|
|
9782
|
+
['pingTimeoutGrace', 'heartbeatGrace'],
|
|
9783
|
+
['retain.isAvailable', 'retain.enabled'],
|
|
9784
|
+
['useQuota', 'quotas: named quota profiles, always enforced (null: unlimited)'],
|
|
9785
|
+
['defaultQuotaIndex', "anonymousQuota: a quotas profile name; logins use their account's quota"],
|
|
9786
|
+
['auth.delay_auth_fail', 'auth.failDelay', 'global'],
|
|
9787
|
+
['adminLevel', "role: 'admin' in the account (key entry)", 'global'],
|
|
9788
|
+
['clientTracking', 'nothing: it was never used', 'global'],
|
|
9789
|
+
...['port', 'congPort', 'httpServer', 'wsPath'].map(name => [name, `new Server({ ${name} })`, 'global'])
|
|
9790
|
+
];
|
|
9791
|
+
const lookup = (object, path) => path.split('.').reduce((value, key) => value?.[key], object);
|
|
9792
|
+
|
|
9793
|
+
function checkRemoved(options) {
|
|
9794
|
+
for (const [path, replacement, scope] of REMOVED) {
|
|
9795
|
+
const sources = scope === 'global' ? [['serverOption.', serverOption]] : [['', options], ['serverOption.', serverOption]];
|
|
9796
|
+
for (const [prefix, source] of sources) {
|
|
9797
|
+
if (lookup(source, path) !== undefined) {
|
|
9798
|
+
throw new TypeError(`${prefix}${path} was removed in iosignal 9.0; use ${replacement}`)
|
|
9799
|
+
}
|
|
9800
|
+
}
|
|
9801
|
+
}
|
|
9802
|
+
}
|
|
9803
|
+
|
|
9804
|
+
const MAX_TIMER_MS = 2147483647; // setTimeout limit
|
|
9805
|
+
|
|
9806
|
+
function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
9807
|
+
if (!Number.isSafeInteger(value) || value < min || value > max) {
|
|
9808
|
+
throw new RangeError(`${name} must be an integer from ${min} to ${max}`)
|
|
9809
|
+
}
|
|
9810
|
+
return value
|
|
9811
|
+
}
|
|
9812
|
+
const positive = (name, value) => integer(name, value, 1);
|
|
9813
|
+
const nonNegative = (name, value) => integer(name, value, 0);
|
|
9814
|
+
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
|
|
9815
|
+
|
|
9816
|
+
// This Server's quota profiles: the defaults with each given profile merged over its default
|
|
9817
|
+
// (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
|
|
9818
|
+
function quotaProfiles(given) {
|
|
9819
|
+
if (given !== undefined && (given === null || typeof given !== 'object')) {
|
|
9820
|
+
throw new TypeError('quotas must be an object')
|
|
9821
|
+
}
|
|
9822
|
+
const profiles = {};
|
|
9823
|
+
for (const name of new Set([...Object.keys(serverOption.quotas), ...Object.keys(given ?? {})])) {
|
|
9824
|
+
const profile = given?.[name];
|
|
9825
|
+
if (profile !== undefined && (profile === null || typeof profile !== 'object')) {
|
|
9826
|
+
throw new TypeError(`quotas.${name} must be an object`)
|
|
9827
|
+
}
|
|
9828
|
+
for (const key of Object.keys(profile ?? {})) {
|
|
9829
|
+
if (!QUOTA_LIMITS.includes(key)) throw new TypeError(`unknown option quotas.${name}.${key}`)
|
|
9830
|
+
}
|
|
9831
|
+
const base = serverOption.quotas[name] ?? Object.fromEntries(QUOTA_LIMITS.map(key => [key, null]));
|
|
9832
|
+
profiles[name] = { ...base, ...profile };
|
|
9833
|
+
for (const key of QUOTA_LIMITS) {
|
|
9834
|
+
if (profiles[name][key] !== null) positive(`quotas.${name}.${key}`, profiles[name][key]);
|
|
9835
|
+
}
|
|
9836
|
+
}
|
|
9837
|
+
return profiles
|
|
9838
|
+
}
|
|
9839
|
+
function boolean(name, value) {
|
|
9840
|
+
if (typeof value !== 'boolean') throw new TypeError(`${name} must be a boolean`)
|
|
9841
|
+
return value
|
|
9842
|
+
}
|
|
9843
|
+
|
|
9844
|
+
// A nested option group: this Server's own copy of the serverOption defaults with its options
|
|
9845
|
+
// applied. Unknown keys are errors, so a typo does not silently do nothing.
|
|
9846
|
+
function group(name, given, checks) {
|
|
9847
|
+
if (given !== undefined && (given === null || typeof given !== 'object')) {
|
|
9848
|
+
throw new TypeError(`${name} must be an object`)
|
|
9849
|
+
}
|
|
9850
|
+
for (const key of Object.keys(given ?? {})) {
|
|
9851
|
+
if (!(key in checks)) throw new TypeError(`unknown option ${name}.${key}`)
|
|
9852
|
+
}
|
|
9853
|
+
const merged = { ...serverOption[name], ...given };
|
|
9854
|
+
for (const [key, check] of Object.entries(checks)) check(`${name}.${key}`, merged[key]);
|
|
9855
|
+
return merged
|
|
9856
|
+
}
|
|
9857
|
+
|
|
9858
|
+
function resolveLogStats(value) {
|
|
9859
|
+
if (value === 0 || value === false) return 0
|
|
9860
|
+
return integer('logStats', value, 1000, MAX_TIMER_MS)
|
|
9861
|
+
}
|
|
9862
|
+
|
|
9249
9863
|
class Server extends require$$0$3 {
|
|
9250
9864
|
|
|
9251
9865
|
/**
|
|
9252
9866
|
* @param {object} options Server configuration.
|
|
9253
9867
|
* options.localAuth: login without a key list, for local testing. 'idKey' (key = ID) or
|
|
9254
|
-
* { mode: 'idKey' | 'sharedKey', key,
|
|
9868
|
+
* { mode: 'idKey' | 'sharedKey', key, role, quota } (see LocalKeyProvider); the CID is the ID.
|
|
9255
9869
|
* Cannot be combined with authManager.
|
|
9870
|
+
* Every other setting is this Server's own: given here, else the serverOption default, which is
|
|
9871
|
+
* never modified. Nested groups (security, retain, quotas) are merged over their defaults;
|
|
9872
|
+
* unknown or removed names are errors.
|
|
9873
|
+
* options.heartbeatInterval: ms between liveness checks (default 50000).
|
|
9874
|
+
* options.heartbeatGrace: extra ms a peer has to answer before it is closed (default 5000).
|
|
9875
|
+
* options.trustProxy: when X-Forwarded-For/-Proto are used. 'private' (default) only from a
|
|
9876
|
+
* loopback/private peer, true always, false never, or N trusted proxy hops.
|
|
9877
|
+
* options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
|
|
9878
|
+
* options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
|
|
9879
|
+
* options.membersOnly: drop signals from connections that are not authenticated.
|
|
9880
|
+
* options.logMessages: log each received message after decryption: type and tag, never the payload.
|
|
9881
|
+
* options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
|
|
9882
|
+
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
|
|
9883
|
+
* options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
|
|
9884
|
+
* options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
|
|
9885
|
+
* maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
9886
|
+
* Adjustable later on server.quotas. The client is told its maxMessageBytes.
|
|
9887
|
+
* options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
|
|
9888
|
+
* options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
|
|
9889
|
+
* manager's own policy without changing it, so an auth manager can be shared between servers.
|
|
9890
|
+
* A failed listen (e.g. EADDRINUSE) is emitted as 'error'.
|
|
9256
9891
|
* @param {any} [authManager] Optional authentication manager.
|
|
9257
9892
|
*/
|
|
9258
9893
|
constructor(options, authManager) {
|
|
@@ -9261,13 +9896,33 @@ class Server extends require$$0$3 {
|
|
|
9261
9896
|
if (authManager) throw new TypeError('localAuth cannot be combined with an authManager')
|
|
9262
9897
|
authManager = new BohoAuth(new LocalKeyProvider(options.localAuth));
|
|
9263
9898
|
}
|
|
9264
|
-
|
|
9265
|
-
|
|
9266
|
-
|
|
9267
|
-
|
|
9268
|
-
}
|
|
9269
|
-
|
|
9270
|
-
this.
|
|
9899
|
+
// Each Server resolves its settings once, here: serverOption only supplies the defaults and is
|
|
9900
|
+
// never written, so servers in one process do not affect each other.
|
|
9901
|
+
checkRemoved(options);
|
|
9902
|
+
this.security = Object.freeze(group('security', options.security,
|
|
9903
|
+
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
|
|
9904
|
+
// retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
|
|
9905
|
+
this.retain = group('retain', options.retain, {
|
|
9906
|
+
enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
|
|
9907
|
+
bytesPerOwner: positive, anonymousGraceMs: nonNegative, bytesPerConnection: positive, bytesTotal: positive });
|
|
9908
|
+
this.quotas = quotaProfiles(options.quotas);
|
|
9909
|
+
this.anonymousQuota = options.anonymousQuota ?? serverOption.anonymousQuota;
|
|
9910
|
+
if (!Object.hasOwn(this.quotas, this.anonymousQuota)) {
|
|
9911
|
+
throw new RangeError(`anonymousQuota must be one of the quotas: ${Object.keys(this.quotas).join(', ')}`)
|
|
9912
|
+
}
|
|
9913
|
+
this.heartbeatInterval = integer('heartbeatInterval',
|
|
9914
|
+
options.heartbeatInterval ?? serverOption.heartbeatInterval, 1, MAX_TIMER_MS);
|
|
9915
|
+
this.heartbeatGrace = integer('heartbeatGrace', options.heartbeatGrace ?? serverOption.heartbeatGrace, 0, MAX_TIMER_MS);
|
|
9916
|
+
this.maxPayload = positive('maxPayload', options.maxPayload ?? serverOption.maxPayload);
|
|
9917
|
+
this.maxBufferedBytes = positive('maxBufferedBytes', options.maxBufferedBytes ?? serverOption.maxBufferedBytes);
|
|
9918
|
+
this.logMessages = boolean('logMessages', options.logMessages ?? serverOption.logMessages);
|
|
9919
|
+
this.logStats = resolveLogStats(options.logStats ?? serverOption.logStats);
|
|
9920
|
+
this.trustProxy = options.trustProxy ?? serverOption.trustProxy;
|
|
9921
|
+
if (![true, false, 'private'].includes(this.trustProxy) &&
|
|
9922
|
+
!(Number.isSafeInteger(this.trustProxy) && this.trustProxy > 0)) {
|
|
9923
|
+
throw new RangeError("trustProxy must be true, false, 'private' or a positive integer");
|
|
9924
|
+
}
|
|
9925
|
+
this.membersOnly = boolean('membersOnly', options.membersOnly ?? serverOption.membersOnly);
|
|
9271
9926
|
this.serviceNames = new Set();
|
|
9272
9927
|
this.services = new Map(); // name -> service module (for lifecycle hooks)
|
|
9273
9928
|
// Stays null for a CongSocket-only server, so close() does not wait on a WebSocket server.
|
|
@@ -9275,38 +9930,13 @@ class Server extends require$$0$3 {
|
|
|
9275
9930
|
this.port = null;
|
|
9276
9931
|
this.congPort = null;
|
|
9277
9932
|
|
|
9278
|
-
|
|
9279
|
-
|
|
9280
|
-
|
|
9281
|
-
}
|
|
9282
|
-
serverOption.pingTimeoutGrace = options.pingTimeoutGrace;
|
|
9283
|
-
}
|
|
9284
|
-
|
|
9285
|
-
if (options.timeout) {
|
|
9286
|
-
let pingT = parseInt(options.timeout);
|
|
9287
|
-
if (pingT && pingT >= 1000) serverOption.timeout = pingT;
|
|
9288
|
-
}
|
|
9289
|
-
if (options.monitorPeriod) {
|
|
9290
|
-
let monitorT = parseInt(options.monitorPeriod);
|
|
9291
|
-
if (monitorT && monitorT >= 1000) serverOption.monitorPeriod = monitorT;
|
|
9292
|
-
}
|
|
9293
|
-
if (options.showMessage) {
|
|
9294
|
-
serverOption.showMessage = options.showMessage;
|
|
9295
|
-
}
|
|
9296
|
-
if (options.showMetric) {
|
|
9297
|
-
serverOption.showMetric = options.showMetric;
|
|
9298
|
-
}
|
|
9299
|
-
if (options.membersOnly) {
|
|
9300
|
-
serverOption.membersOnly = options.membersOnly;
|
|
9301
|
-
}
|
|
9302
|
-
// Applies to this server's auth manager only; without auth there are no duplicate logins.
|
|
9933
|
+
// Read by the auth manager for this server's connections; the auth manager itself is not
|
|
9934
|
+
// changed, since it may be shared. null: the auth manager's own policy.
|
|
9935
|
+
this.duplicateLogin = null;
|
|
9303
9936
|
if (options.duplicateLogin !== undefined) {
|
|
9304
|
-
validateDuplicateLogin(options.duplicateLogin);
|
|
9305
|
-
if (authManager) {
|
|
9306
|
-
|
|
9307
|
-
throw new TypeError('duplicateLogin: the auth manager does not support this option')
|
|
9308
|
-
}
|
|
9309
|
-
authManager.duplicateLogin = options.duplicateLogin;
|
|
9937
|
+
this.duplicateLogin = validateDuplicateLogin(options.duplicateLogin);
|
|
9938
|
+
if (authManager && !('duplicateLogin' in authManager)) {
|
|
9939
|
+
throw new TypeError('duplicateLogin: the auth manager does not support this option')
|
|
9310
9940
|
}
|
|
9311
9941
|
}
|
|
9312
9942
|
|
|
@@ -9347,9 +9977,9 @@ class Server extends require$$0$3 {
|
|
|
9347
9977
|
startWSServer() {
|
|
9348
9978
|
// console.log('optoins', options )
|
|
9349
9979
|
if (this.port || this.port == 0) {
|
|
9350
|
-
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath });
|
|
9980
|
+
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath, maxPayload: this.maxPayload });
|
|
9351
9981
|
} else if (this.httpServer ) {
|
|
9352
|
-
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath });
|
|
9982
|
+
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath, maxPayload: this.maxPayload });
|
|
9353
9983
|
} else {
|
|
9354
9984
|
throw new TypeError(
|
|
9355
9985
|
'One and only one of the "port", "httpServer"' +
|
|
@@ -9367,12 +9997,7 @@ class Server extends require$$0$3 {
|
|
|
9367
9997
|
});
|
|
9368
9998
|
|
|
9369
9999
|
// this.wss.setMaxListeners(0)
|
|
9370
|
-
this.wss.on('error', (err) =>
|
|
9371
|
-
console.error('### ws server error:', err.message);
|
|
9372
|
-
if (err.code == 'EADDRINUSE') {
|
|
9373
|
-
process.exit();
|
|
9374
|
-
}
|
|
9375
|
-
});
|
|
10000
|
+
this.wss.on('error', (err) => this.onListenerError('ws', err));
|
|
9376
10001
|
|
|
9377
10002
|
this.wss.on('close', () => {
|
|
9378
10003
|
// console.log('### WS server is closed.')
|
|
@@ -9392,12 +10017,8 @@ class Server extends require$$0$3 {
|
|
|
9392
10017
|
socket.setNoDelay(true);
|
|
9393
10018
|
this.manager.addRemote(socket);
|
|
9394
10019
|
})
|
|
9395
|
-
.on('error', (err) =>
|
|
9396
|
-
|
|
9397
|
-
if (err.code == 'EADDRINUSE') {
|
|
9398
|
-
process.exit();
|
|
9399
|
-
}
|
|
9400
|
-
}).on('close', () => {
|
|
10020
|
+
.on('error', (err) => this.onListenerError('cong', err))
|
|
10021
|
+
.on('close', () => {
|
|
9401
10022
|
// console.log('### congsocket server is closed.')
|
|
9402
10023
|
}).listen(this.congPort, () => {
|
|
9403
10024
|
this.congPort = this.congServer.address().port;
|
|
@@ -9409,6 +10030,26 @@ class Server extends require$$0$3 {
|
|
|
9409
10030
|
});
|
|
9410
10031
|
}
|
|
9411
10032
|
|
|
10033
|
+
// A failed listen (e.g. EADDRINUSE) is the application's to handle: emitted as 'error',
|
|
10034
|
+
// which, like any EventEmitter, throws when nothing listens. Other errors are logged.
|
|
10035
|
+
onListenerError(name, err) {
|
|
10036
|
+
console.error(`### ${name} server error:`, err.message);
|
|
10037
|
+
if (err.syscall === 'listen') this.emit('error', err);
|
|
10038
|
+
}
|
|
10039
|
+
|
|
10040
|
+
/**
|
|
10041
|
+
* Current server state, for monitoring. counters are cumulative since the server started
|
|
10042
|
+
* (rates are the reader's to compute from two snapshots). Enumerates connections once.
|
|
10043
|
+
* @returns {{ at: number, connections: { total: number, authenticated: number, anonymous: number,
|
|
10044
|
+
* websocket: number, tcp: number }, channels: number, retained: { channel: number, bytes: number },
|
|
10045
|
+
* counters: { rxMessages: number, rxBytes: number, txMessages: number, txBytes: number,
|
|
10046
|
+
* publishes: number, deliveryAttempts: number, quotaExcluded: number, peerRxLimitSkipped: number },
|
|
10047
|
+
* memory: { rss: number, heapUsed: number } }}
|
|
10048
|
+
*/
|
|
10049
|
+
stats() {
|
|
10050
|
+
return this.manager.metrics.snapshot()
|
|
10051
|
+
}
|
|
10052
|
+
|
|
9412
10053
|
/**
|
|
9413
10054
|
* RPC service register.
|
|
9414
10055
|
* service: service_name <string>
|
|
@@ -9562,9 +10203,10 @@ class FileKeyProvider {
|
|
|
9562
10203
|
return Array.from(this.AUTH.keys())
|
|
9563
10204
|
}
|
|
9564
10205
|
|
|
9565
|
-
|
|
10206
|
+
// Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
|
|
10207
|
+
addAuth(id, keyStr, cid, role, quota) {
|
|
9566
10208
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9567
|
-
this.AUTH.set(id, { key: Base64hashKey, cid
|
|
10209
|
+
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
9568
10210
|
}
|
|
9569
10211
|
}
|
|
9570
10212
|
|
|
@@ -9599,9 +10241,13 @@ class RedisKeyProvider {
|
|
|
9599
10241
|
}
|
|
9600
10242
|
|
|
9601
10243
|
// add device auth info
|
|
9602
|
-
|
|
10244
|
+
// role and quota are optional (see StringKeyProvider); an omitted one is not stored.
|
|
10245
|
+
async addAuth(id, keyStr, cid = '', role, quota) {
|
|
9603
10246
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9604
|
-
|
|
10247
|
+
const fields = { 'key': Base64hashKey, 'cid': cid };
|
|
10248
|
+
if (role) fields.role = role;
|
|
10249
|
+
if (quota) fields.quota = quota;
|
|
10250
|
+
return this.redis.hSet(DEVICE_PREFIX + id, fields)
|
|
9605
10251
|
}
|
|
9606
10252
|
|
|
9607
10253
|
//sudoService call
|
|
@@ -9616,43 +10262,39 @@ class RedisKeyProvider {
|
|
|
9616
10262
|
|
|
9617
10263
|
/**
|
|
9618
10264
|
* StringKeyProvider.js
|
|
9619
|
-
*
|
|
9620
|
-
* authInfo <String
|
|
9621
|
-
* id:
|
|
9622
|
-
* key:
|
|
9623
|
-
* cid:
|
|
9624
|
-
*
|
|
9625
|
-
*
|
|
9626
|
-
*
|
|
9627
|
-
* example => authInfo = 'id1.key1.cid1.
|
|
10265
|
+
*
|
|
10266
|
+
* authInfo <String>: entries 'id.key.cid[.role[.quota]]' separated by ','.
|
|
10267
|
+
* id: max 8 chars
|
|
10268
|
+
* key: ~44 base64 chars recommended
|
|
10269
|
+
* cid: client ID
|
|
10270
|
+
* role: 'device' (default) | 'service' | 'admin'
|
|
10271
|
+
* quota: a Server quotas profile name (default: BohoAuth resolveQuota)
|
|
10272
|
+
*
|
|
10273
|
+
* example => authInfo = 'id1.key1.cid1.admin,id2.key2.cid2.device.pro'
|
|
9628
10274
|
*/
|
|
9629
10275
|
|
|
9630
10276
|
|
|
10277
|
+
const ACCOUNT_ROLES = ROLES.filter(role => role !== 'anonymous');
|
|
10278
|
+
|
|
10279
|
+
/** Parses one 'id.key.cid[.role[.quota]]' entry; a malformed one is a TypeError (naming only the id). */
|
|
10280
|
+
function parseKeyEntry(entry) {
|
|
10281
|
+
const [id, key, cid, role, quota, ...rest] = entry.split('.');
|
|
10282
|
+
if (!id || !key || !cid || rest.length > 0 || (role && !ACCOUNT_ROLES.includes(role))) {
|
|
10283
|
+
throw new TypeError(`invalid key entry 'id.key.cid[.role[.quota]]' for id: ${id ?? ''}`)
|
|
10284
|
+
}
|
|
10285
|
+
return { id, key, cid, role: role || undefined, quota: quota || undefined }
|
|
10286
|
+
}
|
|
10287
|
+
|
|
9631
10288
|
class StringKeyProvider {
|
|
9632
10289
|
constructor(authInfo) {
|
|
9633
|
-
|
|
9634
10290
|
if (!authInfo) {
|
|
9635
10291
|
throw TypeError("StringKeyProvider constructor() missing authInfo.")
|
|
9636
10292
|
}
|
|
9637
|
-
|
|
9638
|
-
let id_keys = authInfo.split(',');
|
|
9639
|
-
|
|
9640
10293
|
this.AUTH = new Map();
|
|
9641
|
-
|
|
9642
|
-
|
|
9643
|
-
|
|
9644
|
-
let [ did, key, cid, level ] = v.split('.');
|
|
9645
|
-
level = parseInt(level);
|
|
9646
|
-
if (did && key && cid && typeof level == 'number') {
|
|
9647
|
-
this.addAuth(did, key, cid, level);
|
|
9648
|
-
} else {
|
|
9649
|
-
throw TypeError("StringKeyProvider invalid authInfo.")
|
|
9650
|
-
}
|
|
9651
|
-
});
|
|
9652
|
-
} else {
|
|
9653
|
-
throw TypeError("StringKeyProvider invalid authInfo.")
|
|
10294
|
+
for (const entry of authInfo.split(',')) {
|
|
10295
|
+
const { id, key, cid, role, quota } = parseKeyEntry(entry);
|
|
10296
|
+
this.addAuth(id, key, cid, role, quota);
|
|
9654
10297
|
}
|
|
9655
|
-
|
|
9656
10298
|
}
|
|
9657
10299
|
|
|
9658
10300
|
async getAuth(id) {
|
|
@@ -9662,17 +10304,17 @@ class StringKeyProvider {
|
|
|
9662
10304
|
return Array.from(this.AUTH.keys())
|
|
9663
10305
|
}
|
|
9664
10306
|
|
|
9665
|
-
addAuth(id, keyStr, cid,
|
|
10307
|
+
addAuth(id, keyStr, cid, role, quota) {
|
|
9666
10308
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9667
|
-
this.AUTH.set(id, { key: Base64hashKey, cid
|
|
10309
|
+
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
9668
10310
|
}
|
|
9669
10311
|
}
|
|
9670
10312
|
|
|
9671
10313
|
const commands$1 = ['echo', 'date', 'unixtime'];
|
|
9672
10314
|
|
|
9673
|
-
|
|
10315
|
+
// Open to every connection.
|
|
9674
10316
|
function checkPermission$1(remote) {
|
|
9675
|
-
return
|
|
10317
|
+
return true;
|
|
9676
10318
|
}
|
|
9677
10319
|
|
|
9678
10320
|
/**
|
|
@@ -9719,10 +10361,9 @@ const commands = [
|
|
|
9719
10361
|
'adddevice', 'getdevice', 'deldevice'
|
|
9720
10362
|
];
|
|
9721
10363
|
|
|
9722
|
-
|
|
9723
|
-
// Only a Boho-authenticated device may use sudo; a raised level alone is not authentication.
|
|
10364
|
+
// Only a connection authenticated with role 'admin'.
|
|
9724
10365
|
function checkPermission(remote) {
|
|
9725
|
-
return remote
|
|
10366
|
+
return hasRole(remote, 'admin');
|
|
9726
10367
|
}
|
|
9727
10368
|
|
|
9728
10369
|
async function call(remote, req) {
|
|
@@ -9749,13 +10390,11 @@ async function call(remote, req) {
|
|
|
9749
10390
|
if (req.$[0]) result = remote.manager.closeRemoteByCId(req.$[0]);
|
|
9750
10391
|
|
|
9751
10392
|
} else if (cmd == 'addauth' || cmd == 'adddevice') {
|
|
9752
|
-
|
|
10393
|
+
// did, key, cid[, role[, quota]]
|
|
10394
|
+
if (remote.manager.authManager && req.$.length >= 3 && req.$.length <= 5) {
|
|
9753
10395
|
if (remote.manager.authManager.addAuth) {
|
|
9754
|
-
|
|
9755
|
-
|
|
9756
|
-
let cid = req.$[2];
|
|
9757
|
-
let level = req.$[3];
|
|
9758
|
-
result = await remote.manager.authManager.addAuth(did, dkey, cid, level);
|
|
10396
|
+
const [did, dkey, cid, role, quota] = req.$;
|
|
10397
|
+
result = await remote.manager.authManager.addAuth(did, dkey, cid, role, quota);
|
|
9759
10398
|
}
|
|
9760
10399
|
|
|
9761
10400
|
}
|
|
@@ -9810,7 +10449,6 @@ var sudoService = /*#__PURE__*/Object.freeze({
|
|
|
9810
10449
|
*
|
|
9811
10450
|
*/
|
|
9812
10451
|
|
|
9813
|
-
const MIN_LEVEL = 200;
|
|
9814
10452
|
const COMMANDS = [
|
|
9815
10453
|
'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
|
|
9816
10454
|
'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
|
|
@@ -9823,22 +10461,21 @@ const COMMANDS = [
|
|
|
9823
10461
|
class RedisService {
|
|
9824
10462
|
/**
|
|
9825
10463
|
* @param {object} redisClient
|
|
9826
|
-
* @param {
|
|
9827
|
-
*
|
|
10464
|
+
* @param {'anonymous' | 'device' | 'service' | 'admin'} [minRole='service'] lowest role allowed;
|
|
10465
|
+
* 'anonymous' allows every connection.
|
|
9828
10466
|
*/
|
|
9829
|
-
constructor(redisClient,
|
|
10467
|
+
constructor(redisClient, minRole = 'service') {
|
|
9830
10468
|
if (!redisClient) {
|
|
9831
10469
|
throw new Error("RedisService constructor: no redisClient")
|
|
9832
10470
|
}
|
|
10471
|
+
if (!ROLES.includes(minRole)) throw new RangeError(`minRole must be one of: ${ROLES.join(', ')}`)
|
|
9833
10472
|
this.redisClient = redisClient;
|
|
9834
|
-
this.
|
|
9835
|
-
this.requireAuth = options.requireAuth !== false;
|
|
10473
|
+
this.minRole = minRole;
|
|
9836
10474
|
this.commands = COMMANDS;
|
|
9837
10475
|
}
|
|
9838
10476
|
|
|
9839
10477
|
checkPermission(remote, req) {
|
|
9840
|
-
|
|
9841
|
-
return (remote.level >= this.minLevel) ? true : false;
|
|
10478
|
+
return hasRole(remote, this.minRole);
|
|
9842
10479
|
}
|
|
9843
10480
|
|
|
9844
10481
|
async call(remote, req) {
|
|
@@ -9872,6 +10509,7 @@ exports.IOMsg = IOMsg;
|
|
|
9872
10509
|
exports.LocalKeyProvider = LocalKeyProvider;
|
|
9873
10510
|
exports.MBP = $$1;
|
|
9874
10511
|
exports.PAYLOAD_TYPE = PAYLOAD_TYPE;
|
|
10512
|
+
exports.ROLES = ROLES;
|
|
9875
10513
|
exports.RedisKeyProvider = RedisKeyProvider;
|
|
9876
10514
|
exports.RedisService = RedisService;
|
|
9877
10515
|
exports.SIZE_LIMIT = SIZE_LIMIT;
|
|
@@ -9879,11 +10517,14 @@ exports.STATE = STATE;
|
|
|
9879
10517
|
exports.STATUS = STATUS$1;
|
|
9880
10518
|
exports.Server = Server;
|
|
9881
10519
|
exports.StringKeyProvider = StringKeyProvider;
|
|
10520
|
+
exports.defaultQuota = defaultQuota;
|
|
9882
10521
|
exports.delay = delay;
|
|
9883
10522
|
exports.getIPv4HexString = getIPv4HexString;
|
|
10523
|
+
exports.getIPv6PrefixHexString = getIPv6PrefixHexString;
|
|
9884
10524
|
exports.getLocalAddress = getLocalAddress;
|
|
9885
10525
|
exports.getPayloadFromSignalPack = getPayloadFromSignalPack;
|
|
9886
10526
|
exports.getSignalPack = getSignalPack;
|
|
10527
|
+
exports.hasRole = hasRole;
|
|
9887
10528
|
exports.isPrivateIP = isPrivateIP;
|
|
9888
10529
|
exports.numberWithCommas = numberWithCommas;
|
|
9889
10530
|
exports.pack = pack;
|