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