iosignal 8.1.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +48 -0
- package/README.md +55 -0
- package/dist/browser/esm/io.d.ts +6 -8
- package/dist/browser/esm/io.js +5 -5
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +5 -5
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +940 -517
- package/dist/node/iosignal.d.cts +293 -118
- package/dist/node/iosignal.d.ts +293 -118
- package/dist/node/iosignal.js +938 -519
- package/dist/types/client/IOCore.d.ts +6 -9
- package/dist/types/common/constants.d.ts +2 -2
- package/package.json +2 -3
- package/dist/types/common/quotaTable.d.ts +0 -47
package/dist/node/iosignal.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.0.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}
|
|
@@ -1267,12 +1196,12 @@ class IOCore extends EventEmitter {
|
|
|
1267
1196
|
this.subscribe_channels();
|
|
1268
1197
|
break;
|
|
1269
1198
|
|
|
1270
|
-
case IOMsg.
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
this.quota =
|
|
1274
|
-
// console.log('[QUOTA_LEVEL]', JSON.stringify(this.quota))
|
|
1199
|
+
case IOMsg.QUOTA: {
|
|
1200
|
+
if (buffer.byteLength < 5) break;
|
|
1201
|
+
const maxMessageBytes = (buffer[1] | buffer[2] << 8 | buffer[3] << 16) + buffer[4] * 0x1000000;
|
|
1202
|
+
this.quota = { maxMessageBytes: maxMessageBytes || null };
|
|
1275
1203
|
break;
|
|
1204
|
+
}
|
|
1276
1205
|
|
|
1277
1206
|
case IOMsg.AUTH_CLEAR:
|
|
1278
1207
|
this.useAuth = false;
|
|
@@ -1534,10 +1463,10 @@ class IOCore extends EventEmitter {
|
|
|
1534
1463
|
* @param {Buffer} data - The data buffer to send.
|
|
1535
1464
|
*/
|
|
1536
1465
|
send(data) {
|
|
1537
|
-
|
|
1466
|
+
const maxMessageBytes = this.quota.maxMessageBytes;
|
|
1467
|
+
if (maxMessageBytes !== null && data.byteLength > maxMessageBytes) {
|
|
1538
1468
|
this.emit('over_size');
|
|
1539
|
-
console.log(
|
|
1540
|
-
console.log('## your maximum signalSize(bytes) is:', this.quota.signalSize);
|
|
1469
|
+
console.log(`## quota: ${data.byteLength} bytes is over this connection's maxMessageBytes ${maxMessageBytes}`);
|
|
1541
1470
|
return
|
|
1542
1471
|
}
|
|
1543
1472
|
// console.log(`C->[${IOMsg[ data[0]]}]`)
|
|
@@ -2080,14 +2009,19 @@ function pack(payload) {
|
|
|
2080
2009
|
|
|
2081
2010
|
class CongRx extends Transform {
|
|
2082
2011
|
/**
|
|
2083
|
-
* @param {import('stream').TransformOptions} [options] Stream options.
|
|
2012
|
+
* @param {import('stream').TransformOptions & { maxFrameSize?: number }} [options] Stream options.
|
|
2013
|
+
* maxFrameSize: largest payload to buffer (default unlimited). A larger frame is
|
|
2014
|
+
* skipped without buffering and reported by an 'oversize' event (payloadSize).
|
|
2084
2015
|
*/
|
|
2085
|
-
constructor(options) {
|
|
2086
|
-
|
|
2016
|
+
constructor(options = {}) {
|
|
2017
|
+
const { maxFrameSize = Infinity, ...streamOptions } = options;
|
|
2018
|
+
super(streamOptions);
|
|
2087
2019
|
this.buffer = Buffer.alloc(0);
|
|
2088
2020
|
this.frames = [];
|
|
2089
2021
|
this.rxi = 0;
|
|
2090
2022
|
this.rxi_zero = 0;
|
|
2023
|
+
this.maxFrameSize = maxFrameSize;
|
|
2024
|
+
this.skipBytes = 0; // remaining payload bytes of an oversized frame to discard
|
|
2091
2025
|
}
|
|
2092
2026
|
|
|
2093
2027
|
|
|
@@ -2114,6 +2048,15 @@ class CongRx extends Transform {
|
|
|
2114
2048
|
}
|
|
2115
2049
|
}
|
|
2116
2050
|
|
|
2051
|
+
if (this.skipBytes > 0) {
|
|
2052
|
+
if (chunk.byteLength <= this.skipBytes) {
|
|
2053
|
+
this.skipBytes -= chunk.byteLength;
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
2056
|
+
chunk = chunk.subarray(this.skipBytes);
|
|
2057
|
+
this.skipBytes = 0;
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2117
2060
|
if (this.buffer.byteLength > 0) {
|
|
2118
2061
|
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
2119
2062
|
} else {
|
|
@@ -2151,6 +2094,20 @@ class CongRx extends Transform {
|
|
|
2151
2094
|
return;
|
|
2152
2095
|
}
|
|
2153
2096
|
|
|
2097
|
+
// Decide as soon as the length is known: the header can advertise up to 4 GiB.
|
|
2098
|
+
// Skipping keeps frame boundaries, so later frames still parse.
|
|
2099
|
+
if (payloadSize > this.maxFrameSize) {
|
|
2100
|
+
this.emit('oversize', payloadSize);
|
|
2101
|
+
const available = this.buffer.byteLength - headerLen;
|
|
2102
|
+
if (available < payloadSize) {
|
|
2103
|
+
this.skipBytes = payloadSize - available;
|
|
2104
|
+
this.buffer = Buffer.alloc(0);
|
|
2105
|
+
return;
|
|
2106
|
+
}
|
|
2107
|
+
this.buffer = this.buffer.subarray(headerLen + payloadSize);
|
|
2108
|
+
continue;
|
|
2109
|
+
}
|
|
2110
|
+
|
|
2154
2111
|
const frameSize = headerLen + payloadSize;
|
|
2155
2112
|
if (this.buffer.byteLength < frameSize) return;
|
|
2156
2113
|
|
|
@@ -2207,7 +2164,9 @@ class IOCongSocket extends IOCore {
|
|
|
2207
2164
|
if (urlObj.protocol != "cong:") {
|
|
2208
2165
|
urlObj = new URL('cong://' + url);
|
|
2209
2166
|
}
|
|
2210
|
-
|
|
2167
|
+
// URL keeps the brackets of an IPv6 literal ('[::1]'); net expects the bare address.
|
|
2168
|
+
const host = urlObj.hostname.replace(/^\[(.*)\]$/, '$1');
|
|
2169
|
+
const socket = this.socket = net.createConnection(urlObj.port, host);
|
|
2211
2170
|
// Signals are small frames; send each immediately instead of waiting on Nagle.
|
|
2212
2171
|
socket.setNoDelay(true);
|
|
2213
2172
|
this._closed = false;
|
|
@@ -7381,18 +7340,75 @@ class IOWS extends IOCore {
|
|
|
7381
7340
|
|
|
7382
7341
|
}
|
|
7383
7342
|
|
|
7384
|
-
|
|
7385
|
-
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
|
|
7390
|
-
|
|
7391
|
-
|
|
7392
|
-
|
|
7393
|
-
|
|
7394
|
-
|
|
7395
|
-
|
|
7343
|
+
// Defaults, read when a Server is created; a Server never modifies them. Change one before
|
|
7344
|
+
// creating servers to change the default for all of them, or pass the setting to new Server().
|
|
7345
|
+
|
|
7346
|
+
const serverOption = {
|
|
7347
|
+
|
|
7348
|
+
// --- Per Server: each of these can be given to new Server({ ... }) ---
|
|
7349
|
+
|
|
7350
|
+
heartbeatInterval: 50000, // ms between liveness checks
|
|
7351
|
+
heartbeatGrace: 5000, // extra ms a peer has to answer before it is closed
|
|
7352
|
+
// Max bytes for a single WebSocket message and CongSocket frame. Bounds pre-auth memory use per
|
|
7353
|
+
// connection (ws defaults to 100 MiB); see Remote.rxFrameLimit().
|
|
7354
|
+
maxPayload: 32 * 1024 * 1024,
|
|
7355
|
+
// When to use X-Forwarded-For / X-Forwarded-Proto of a WebSocket request:
|
|
7356
|
+
// 'private' only if the connecting peer is a loopback/private address, e.g. a reverse proxy on
|
|
7357
|
+
// the same host or network; true always; false never; a number N trusts N proxy hops. The entry
|
|
7358
|
+
// appended by the last trusted proxy is used; earlier entries can be forged by the client.
|
|
7359
|
+
trustProxy: 'private',
|
|
7360
|
+
// A peer whose unsent data exceeds this many bytes (it stopped reading) is closed instead of
|
|
7361
|
+
// letting its send queue grow without limit.
|
|
7362
|
+
maxBufferedBytes: 64 * 1024 * 1024,
|
|
7363
|
+
// Drop signals from connections that are not authenticated.
|
|
7364
|
+
membersOnly: false,
|
|
7365
|
+
// Observability. logMessages: log each received message (type and tag, never the payload).
|
|
7366
|
+
// logStats: print a one-line summary every N ms (0 = off).
|
|
7367
|
+
logMessages: false,
|
|
7368
|
+
logStats: 0,
|
|
7369
|
+
|
|
7370
|
+
// Nested groups: a Server merges its own options over these.
|
|
7371
|
+
// Packet layouts remain unchanged.
|
|
7372
|
+
security: {
|
|
7373
|
+
maxClockSkewMs: 60000,
|
|
7374
|
+
authChallengeMaxAgeMs: 60000,
|
|
7375
|
+
maxReplayEntries: 65536
|
|
7376
|
+
},
|
|
7377
|
+
// Named quota profiles. A connection uses one: an anonymous connection the Server's
|
|
7378
|
+
// anonymousQuota, an authenticated one the profile its account resolves to (see BohoAuth
|
|
7379
|
+
// resolveQuota). null is unlimited. A Server merges its quotas option over these per profile
|
|
7380
|
+
// and may add profiles; a running server's profiles can be adjusted (server.quotas.basic.fanout = 50).
|
|
7381
|
+
// maxMessageBytes: largest message the connection may send (larger: OVER_SIZE, dropped)
|
|
7382
|
+
// fanout: most subscribers one channel publish is delivered to
|
|
7383
|
+
// msgPerSec, bytesPerSec: sustained receive rate (token bucket, 1 s burst); over: dropped
|
|
7384
|
+
// maxConnections: connections of one account (uid) at a time; over: the login fails
|
|
7385
|
+
quotas: {
|
|
7386
|
+
anonymous: { maxMessageBytes: 256 * 1024, fanout: 1000, msgPerSec: 100, bytesPerSec: 2 * 1024 * 1024, maxConnections: null },
|
|
7387
|
+
basic: { maxMessageBytes: 1024 * 1024, fanout: 1000, msgPerSec: 200, bytesPerSec: 4 * 1024 * 1024, maxConnections: 20 },
|
|
7388
|
+
pro: { maxMessageBytes: 4 * 1024 * 1024, fanout: 10000, msgPerSec: 1000, bytesPerSec: 16 * 1024 * 1024, maxConnections: 200 },
|
|
7389
|
+
unlimited: { maxMessageBytes: null, fanout: null, msgPerSec: null, bytesPerSec: null, maxConnections: null }
|
|
7390
|
+
},
|
|
7391
|
+
anonymousQuota: 'anonymous', // profile of a connection that has not authenticated
|
|
7392
|
+
|
|
7393
|
+
retain: {
|
|
7394
|
+
enabled: true,
|
|
7395
|
+
limitSize: 100000, // a retained message must be smaller than this many bytes
|
|
7396
|
+
limitCounter: 1000, // channel retain tags per server, and CID retain tags per connection
|
|
7397
|
+
// A channel retain belongs to its last writer: an authenticated account (CID, shared by its
|
|
7398
|
+
// connections) or a live anonymous connection. Each owner holds at most tagsPerOwner tags and
|
|
7399
|
+
// bytesPerOwner bytes. An account's values stay until restart; a closed anonymous connection's
|
|
7400
|
+
// move to its network's grace pool (same budget) and are removed after anonymousGraceMs.
|
|
7401
|
+
tagsPerOwner: 32,
|
|
7402
|
+
bytesPerOwner: 1024 * 1024,
|
|
7403
|
+
anonymousGraceMs: 60 * 60 * 1000,
|
|
7404
|
+
// CID retains of one connection (removed with it), and all retained messages of the server.
|
|
7405
|
+
// A value over budget is not stored, and removes the value it would have replaced.
|
|
7406
|
+
bytesPerConnection: 1024 * 1024,
|
|
7407
|
+
bytesTotal: 256 * 1024 * 1024
|
|
7408
|
+
},
|
|
7409
|
+
|
|
7410
|
+
// --- Process-wide: read directly where used, not per Server ---
|
|
7411
|
+
|
|
7396
7412
|
fileLogger: {
|
|
7397
7413
|
connection: {
|
|
7398
7414
|
use: false,
|
|
@@ -7407,43 +7423,22 @@ let serverOption = {
|
|
|
7407
7423
|
path: 'attack.log'
|
|
7408
7424
|
}
|
|
7409
7425
|
},
|
|
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
7426
|
|
|
7438
7427
|
auth: {
|
|
7439
|
-
|
|
7440
|
-
//
|
|
7441
|
-
// 'keepNew'
|
|
7442
|
-
// Override per
|
|
7428
|
+
failDelay: 600, // ms before AUTH_FAIL is sent
|
|
7429
|
+
// Default for BohoAuth, when the same authenticated CID is already online:
|
|
7430
|
+
// 'keepNew' replaces the old connection, 'keepOld' rejects the new login.
|
|
7431
|
+
// Override per BohoAuth with its duplicateLogin option, and per Server with options.duplicateLogin
|
|
7432
|
+
// (which wins, and applies only to that Server's connections).
|
|
7443
7433
|
duplicateLogin: 'keepNew'
|
|
7444
7434
|
},
|
|
7445
|
-
membersOnly: false
|
|
7446
7435
|
|
|
7436
|
+
// Development aids.
|
|
7437
|
+
debug: {
|
|
7438
|
+
slow: false, // delay handling of every received message by `delay` ms
|
|
7439
|
+
delay: 500,
|
|
7440
|
+
showAuthInfo: false // log auth results and state traces (never keys)
|
|
7441
|
+
}
|
|
7447
7442
|
};
|
|
7448
7443
|
|
|
7449
7444
|
const decoder$3 = new TextDecoder();
|
|
@@ -7451,6 +7446,27 @@ const decoder$3 = new TextDecoder();
|
|
|
7451
7446
|
$$1.NB;
|
|
7452
7447
|
const MB = $$1.MB;
|
|
7453
7448
|
|
|
7449
|
+
// A one-byte CLOSE reason is a code, not text (Arduino IOSignal::close(uint8_t)): the message
|
|
7450
|
+
// that made the client close, or its CongPacket reader error state (ReadingState >= 250).
|
|
7451
|
+
// Its own table, because IOMsg gives 253 another meaning (TIME_OUT).
|
|
7452
|
+
const CLOSE_REASON = {
|
|
7453
|
+
[IOMsg.AUTH_CLEAR]: 'AUTH_CLEAR',
|
|
7454
|
+
[IOMsg.SERVER_REDIRECT]: 'SERVER_REDIRECT',
|
|
7455
|
+
253: 'CONG_UNKNOWN_TYPE',
|
|
7456
|
+
254: 'CONG_OVER_SIZE',
|
|
7457
|
+
255: 'CONG_OVER_FLOW'
|
|
7458
|
+
};
|
|
7459
|
+
|
|
7460
|
+
// Readable reason of a CLOSE message, e.g. 'AUTH_CLEAR(0xc4)'; longer reasons are text.
|
|
7461
|
+
function closeReason(message) {
|
|
7462
|
+
if (message.byteLength < 2) return 'none'
|
|
7463
|
+
if (message.byteLength === 2) {
|
|
7464
|
+
const code = '0x' + message[1].toString(16).padStart(2, '0');
|
|
7465
|
+
return CLOSE_REASON[message[1]] ? `${CLOSE_REASON[message[1]]}(${code})` : code
|
|
7466
|
+
}
|
|
7467
|
+
return decoder$3.decode(message.subarray(1))
|
|
7468
|
+
}
|
|
7469
|
+
|
|
7454
7470
|
|
|
7455
7471
|
class RemoteCore {
|
|
7456
7472
|
constructor(socket, manager) {
|
|
@@ -7469,9 +7485,11 @@ class RemoteCore {
|
|
|
7469
7485
|
this._replayEntries = 0;
|
|
7470
7486
|
this._replayExpiredBefore = 0;
|
|
7471
7487
|
this.securityFailure = null;
|
|
7488
|
+
this.closeReason = null; // reason of the client's CLOSE message, see closeReason()
|
|
7472
7489
|
this.encMode = ENC_MODE.AUTO;
|
|
7473
7490
|
this.channels = new Set(); // subscribed tags
|
|
7474
7491
|
this.retain_signal = new Map();
|
|
7492
|
+
this.retainBytes = 0; // bytes of its CID retains (retain_signal)
|
|
7475
7493
|
|
|
7476
7494
|
this.ssid = RemoteCore.ssid++; // ordered index number
|
|
7477
7495
|
this.manager = manager;
|
|
@@ -7483,9 +7501,18 @@ class RemoteCore {
|
|
|
7483
7501
|
|
|
7484
7502
|
this.privateNode = false;
|
|
7485
7503
|
this.HOME_CHANNEL = '';
|
|
7486
|
-
this.
|
|
7487
|
-
this.
|
|
7488
|
-
|
|
7504
|
+
this.role = 'anonymous'; // set on authentication; see ROLES in BohoAuth
|
|
7505
|
+
this.accountUid = null; // counted in manager.accountConnections while authenticated with a uid
|
|
7506
|
+
// Quota profile (a server.quotas entry, read live): the anonymous one until authenticated.
|
|
7507
|
+
this.quotaName = manager.anonymousQuota;
|
|
7508
|
+
this.quota = manager.quotas[this.quotaName];
|
|
7509
|
+
this._rateAt = null; // token buckets of quota msgPerSec / bytesPerSec
|
|
7510
|
+
this._msgTokens = 0;
|
|
7511
|
+
this._byteTokens = 0;
|
|
7512
|
+
// Largest message the peer can receive, if it said so in CID_REQ (e.g. an Arduino RX buffer);
|
|
7513
|
+
// larger messages are skipped instead of sent. null: no limit beyond maxPayload.
|
|
7514
|
+
this.peerRxLimit = null;
|
|
7515
|
+
this.peerRxLimitSkipped = 0;
|
|
7489
7516
|
|
|
7490
7517
|
this.state;
|
|
7491
7518
|
this.stateLog = [];
|
|
@@ -7495,6 +7522,11 @@ class RemoteCore {
|
|
|
7495
7522
|
|
|
7496
7523
|
static ssid = 1;
|
|
7497
7524
|
|
|
7525
|
+
/** Authenticated with role 'admin'. */
|
|
7526
|
+
get isAdmin() {
|
|
7527
|
+
return this.role === 'admin' && this.boho.isAuthorized === true;
|
|
7528
|
+
}
|
|
7529
|
+
|
|
7498
7530
|
setState(state) {
|
|
7499
7531
|
const previous = this.state;
|
|
7500
7532
|
this.state = state;
|
|
@@ -7518,43 +7550,79 @@ class RemoteCore {
|
|
|
7518
7550
|
}
|
|
7519
7551
|
|
|
7520
7552
|
|
|
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);
|
|
7553
|
+
// logMessages: one line per received message after decryption: type, routing tag or RPC
|
|
7554
|
+
// target, and size. Payloads are never printed; heartbeat PING/PONG are skipped.
|
|
7555
|
+
logMessage(msgType, message, encrypted = false) {
|
|
7556
|
+
if (msgType === IOMsg.PING || msgType === IOMsg.PONG) return
|
|
7557
|
+
let detail = '';
|
|
7558
|
+
try {
|
|
7559
|
+
if ([IOMsg.SIGNAL, IOMsg.SIGNAL_E2E, IOMsg.SUBSCRIBE, IOMsg.UNSUBSCRIBE].includes(msgType)) {
|
|
7560
|
+
detail = decoder$3.decode(message.subarray(2, 2 + message[1]));
|
|
7561
|
+
} else if (msgType === IOMsg.SUBSCRIBE_REQ && message.byteLength >= 5) {
|
|
7562
|
+
detail = decoder$3.decode(message.subarray(5, 5 + message.readUInt16BE(3)));
|
|
7563
|
+
} else if (msgType === IOMsg.CALL) {
|
|
7564
|
+
const req = $$1.unpack(message);
|
|
7565
|
+
if (req) detail = `${req.target}.${req.topic}`;
|
|
7537
7566
|
}
|
|
7538
|
-
|
|
7567
|
+
} catch { /* a malformed message is logged without detail */ }
|
|
7568
|
+
const type = msgType === undefined ? 'TEXT'
|
|
7569
|
+
: IOMsg[msgType] ?? it.BohoMsg[msgType] ?? '0x' + msgType.toString(16);
|
|
7570
|
+
const transport = this.socketType === 'websocket' ? 'WS' : 'CS';
|
|
7571
|
+
console.log(`[rx] #${this.ssid} ${this.cid || '-'} ${transport} ${type}${encrypted ? '(enc)' : ''}` +
|
|
7572
|
+
`${detail ? ' ' + detail : ''} ${message.byteLength}B`);
|
|
7573
|
+
}
|
|
7574
|
+
|
|
7575
|
+
// Switches to a server.quotas profile; tell: send it to the client (QUOTA: its maxMessageBytes).
|
|
7576
|
+
setQuota(name, tell) {
|
|
7577
|
+
this.quotaName = name;
|
|
7578
|
+
this.quota = this.manager.quotas[name];
|
|
7579
|
+
// The CongSocket frame ceiling follows maxMessageBytes.
|
|
7580
|
+
this.refreshRxFrameLimit?.();
|
|
7581
|
+
if (tell) {
|
|
7582
|
+
const packet = Buffer.alloc(5);
|
|
7583
|
+
packet[0] = IOMsg.QUOTA;
|
|
7584
|
+
packet.writeUInt32LE(this.quota.maxMessageBytes ?? 0, 1); // 0: unlimited
|
|
7585
|
+
this.send(packet);
|
|
7586
|
+
}
|
|
7587
|
+
}
|
|
7588
|
+
|
|
7589
|
+
// Quota msgPerSec / bytesPerSec: token buckets holding one second. A message larger than the
|
|
7590
|
+
// byte bucket passes when the bucket is full and leaves a debt.
|
|
7591
|
+
takeRateTokens(bytes) {
|
|
7592
|
+
const { msgPerSec, bytesPerSec } = this.quota;
|
|
7593
|
+
if (msgPerSec === null && bytesPerSec === null) return true;
|
|
7594
|
+
const now = performance.now();
|
|
7595
|
+
if (this._rateAt === null) {
|
|
7596
|
+
this._msgTokens = msgPerSec ?? 0;
|
|
7597
|
+
this._byteTokens = bytesPerSec ?? 0;
|
|
7539
7598
|
} else {
|
|
7540
|
-
|
|
7541
|
-
|
|
7599
|
+
const seconds = (now - this._rateAt) / 1000;
|
|
7600
|
+
if (msgPerSec !== null) this._msgTokens = Math.min(msgPerSec, this._msgTokens + seconds * msgPerSec);
|
|
7601
|
+
if (bytesPerSec !== null) this._byteTokens = Math.min(bytesPerSec, this._byteTokens + seconds * bytesPerSec);
|
|
7602
|
+
}
|
|
7603
|
+
this._rateAt = now;
|
|
7604
|
+
if (msgPerSec !== null && this._msgTokens < 1) return false;
|
|
7605
|
+
if (bytesPerSec !== null && this._byteTokens < Math.min(bytes, bytesPerSec)) return false;
|
|
7606
|
+
if (msgPerSec !== null) this._msgTokens -= 1;
|
|
7607
|
+
if (bytesPerSec !== null) this._byteTokens -= bytes;
|
|
7608
|
+
return true;
|
|
7542
7609
|
}
|
|
7543
7610
|
|
|
7544
7611
|
rxQuotaChecker(message) {
|
|
7545
7612
|
let rxBytes = message.byteLength;
|
|
7546
|
-
this.manager.rxBytes += rxBytes;
|
|
7547
|
-
|
|
7613
|
+
this.manager.counters.rxBytes += rxBytes;
|
|
7614
|
+
this.manager.counters.rxMessages++;
|
|
7548
7615
|
|
|
7549
|
-
|
|
7550
|
-
|
|
7616
|
+
const maxMessageBytes = this.quota.maxMessageBytes;
|
|
7617
|
+
if (maxMessageBytes !== null && rxBytes > maxMessageBytes) {
|
|
7618
|
+
this.manager.counters.oversizeRejected++;
|
|
7551
7619
|
this.send(Buffer.from([IOMsg.OVER_SIZE]));
|
|
7552
|
-
if (serverOption.useQuota.disconnect) this.close();
|
|
7553
7620
|
return false;
|
|
7554
7621
|
}
|
|
7555
|
-
|
|
7556
|
-
|
|
7557
|
-
|
|
7622
|
+
if (!this.takeRateTokens(rxBytes)) {
|
|
7623
|
+
this.manager.counters.rateLimited++;
|
|
7624
|
+
return false;
|
|
7625
|
+
}
|
|
7558
7626
|
return true;
|
|
7559
7627
|
}
|
|
7560
7628
|
|
|
@@ -7568,7 +7636,7 @@ class RemoteCore {
|
|
|
7568
7636
|
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7569
7637
|
this.securityFailure = reason;
|
|
7570
7638
|
this.boho.clearAuth();
|
|
7571
|
-
this.
|
|
7639
|
+
this.role = 'anonymous';
|
|
7572
7640
|
this._replayBuckets.clear();
|
|
7573
7641
|
this._replayEntries = 0;
|
|
7574
7642
|
this.close(true);
|
|
@@ -7650,9 +7718,8 @@ class RemoteCore {
|
|
|
7650
7718
|
this.receiveMonitor(); // rx-data, ping/pong and timeout check
|
|
7651
7719
|
if (!this.rxQuotaChecker(message)) return
|
|
7652
7720
|
|
|
7653
|
-
|
|
7654
|
-
|
|
7655
|
-
let msgType, decoded;
|
|
7721
|
+
const logMessages = this.manager.server?.logMessages;
|
|
7722
|
+
let msgType, decoded, encrypted = false;
|
|
7656
7723
|
|
|
7657
7724
|
if (isBinary) {
|
|
7658
7725
|
msgType = message[0];
|
|
@@ -7664,6 +7731,7 @@ class RemoteCore {
|
|
|
7664
7731
|
if (decoded) {
|
|
7665
7732
|
msgType = decoded[0];
|
|
7666
7733
|
message = decoded;
|
|
7734
|
+
encrypted = true;
|
|
7667
7735
|
} else {
|
|
7668
7736
|
return
|
|
7669
7737
|
}
|
|
@@ -7675,11 +7743,13 @@ class RemoteCore {
|
|
|
7675
7743
|
msgType = decoded[0];
|
|
7676
7744
|
message.set(decoded, it.MetaSize.ENC_488); // set decoded signal_e2e headaer.
|
|
7677
7745
|
message = message.subarray(it.MetaSize.ENC_488); // reset offset.
|
|
7746
|
+
encrypted = true;
|
|
7678
7747
|
} else {
|
|
7679
7748
|
return
|
|
7680
7749
|
}
|
|
7681
7750
|
|
|
7682
7751
|
} else ;
|
|
7752
|
+
if (logMessages) this.logMessage(msgType, message, encrypted);
|
|
7683
7753
|
|
|
7684
7754
|
switch (msgType) {
|
|
7685
7755
|
case IOMsg.PING:
|
|
@@ -7698,6 +7768,13 @@ class RemoteCore {
|
|
|
7698
7768
|
return;
|
|
7699
7769
|
}
|
|
7700
7770
|
|
|
7771
|
+
// Optional uint32 little endian after the type: the peer's RX buffer size. Set before
|
|
7772
|
+
// anything else is sent, so CID_RES, retained messages and signals respect it.
|
|
7773
|
+
if (message.byteLength >= 5) {
|
|
7774
|
+
const size = (message[1] | message[2] << 8 | message[3] << 16) + message[4] * 0x1000000;
|
|
7775
|
+
if (size > 0) this.peerRxLimit = size;
|
|
7776
|
+
}
|
|
7777
|
+
|
|
7701
7778
|
if (!this.cid) {
|
|
7702
7779
|
const cid = this.manager.issueAnonymousCid();
|
|
7703
7780
|
if (!cid) {
|
|
@@ -7707,6 +7784,8 @@ class RemoteCore {
|
|
|
7707
7784
|
}
|
|
7708
7785
|
this.cid = cid;
|
|
7709
7786
|
this.manager.cid2remote.set(this.cid, this);
|
|
7787
|
+
// The client limits its own sends to its quota (an authenticated one is sent on AUTH).
|
|
7788
|
+
this.setQuota(this.quotaName, true);
|
|
7710
7789
|
}
|
|
7711
7790
|
|
|
7712
7791
|
// console.log('<< SENDING CID_RES:', this.cid)
|
|
@@ -7810,11 +7889,10 @@ class RemoteCore {
|
|
|
7810
7889
|
|
|
7811
7890
|
|
|
7812
7891
|
case IOMsg.CLOSE:
|
|
7813
|
-
|
|
7814
|
-
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
}
|
|
7892
|
+
// The reason is only logged, so a CLOSE without one still closes.
|
|
7893
|
+
this.closeReason = closeReason(message);
|
|
7894
|
+
console.log(`>> CLOSE #${this.ssid} cid:${this.cid} reason: ${this.closeReason}`);
|
|
7895
|
+
this.close();
|
|
7818
7896
|
break;
|
|
7819
7897
|
|
|
7820
7898
|
|
|
@@ -7855,6 +7933,7 @@ class RemoteCore {
|
|
|
7855
7933
|
|
|
7856
7934
|
} else {
|
|
7857
7935
|
// TEXT FRAME
|
|
7936
|
+
if (logMessages) this.logMessage(undefined, message);
|
|
7858
7937
|
try {
|
|
7859
7938
|
let textMessage = decoder$3.decode(message);
|
|
7860
7939
|
// console.log('text buffer:',textMessage )
|
|
@@ -7937,7 +8016,8 @@ class RemoteCore {
|
|
|
7937
8016
|
"cid": this.cid,
|
|
7938
8017
|
"did": this.did,
|
|
7939
8018
|
"uid": this.uid,
|
|
7940
|
-
"
|
|
8019
|
+
"role": this.role,
|
|
8020
|
+
"quota": this.quotaName,
|
|
7941
8021
|
"nick": this.nick,
|
|
7942
8022
|
"ip": this.ip
|
|
7943
8023
|
, 'tag': channels
|
|
@@ -7955,31 +8035,45 @@ class RemoteCore {
|
|
|
7955
8035
|
|
|
7956
8036
|
}
|
|
7957
8037
|
|
|
8038
|
+
// 16 address bytes of an IPv6 string (with '::', an embedded IPv4 tail or a %zone), else null.
|
|
8039
|
+
function ipv6Bytes(ip) {
|
|
8040
|
+
if (!isIPv6(ip)) return null
|
|
8041
|
+
ip = ip.split('%')[0];
|
|
8042
|
+
const tailStart = ip.lastIndexOf(':') + 1;
|
|
8043
|
+
const tail = ip.slice(tailStart);
|
|
8044
|
+
if (isIPv4(tail)) {
|
|
8045
|
+
const [a, b, c, d] = tail.split('.').map(Number);
|
|
8046
|
+
ip = ip.slice(0, tailStart) + ((a << 8) | b).toString(16) + ':' + ((c << 8) | d).toString(16);
|
|
8047
|
+
}
|
|
8048
|
+
const words = s => s ? s.split(':').map(h => parseInt(h, 16)) : [];
|
|
8049
|
+
const [head, rest] = ip.split('::');
|
|
8050
|
+
const left = words(head), right = words(rest);
|
|
8051
|
+
const all = [...left, ...new Array(8 - left.length - right.length).fill(0), ...right];
|
|
8052
|
+
const bytes = Buffer.alloc(16);
|
|
8053
|
+
all.forEach((word, i) => bytes.writeUInt16BE(word, i * 2));
|
|
8054
|
+
return bytes
|
|
8055
|
+
}
|
|
8056
|
+
|
|
8057
|
+
function isPrivateIPv4(ip) {
|
|
8058
|
+
const [a, b] = ip.split('.').map(Number);
|
|
8059
|
+
return a === 0 || a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168)
|
|
8060
|
+
}
|
|
8061
|
+
|
|
8062
|
+
// Unspecified, loopback, RFC 1918, IPv6 unique-local (fc00::/7) and link-local (fe80::/10).
|
|
7958
8063
|
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
|
|
8064
|
+
if (isIPv4(ip)) return isPrivateIPv4(ip)
|
|
8065
|
+
const bytes = ipv6Bytes(ip);
|
|
8066
|
+
if (!bytes) return false
|
|
8067
|
+
if (bytes.subarray(0, 15).every(v => v === 0) && bytes[15] <= 1) return true // :: and ::1
|
|
8068
|
+
if (bytes.subarray(0, 10).every(v => v === 0) && bytes[10] === 0xff && bytes[11] === 0xff) {
|
|
8069
|
+
return isPrivateIPv4(bytes.subarray(12).join('.')) // IPv4-mapped
|
|
8070
|
+
}
|
|
8071
|
+
return (bytes[0] & 0xfe) === 0xfc || (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80)
|
|
8072
|
+
}
|
|
8073
|
+
|
|
8074
|
+
// Hosts on one IPv6 network share the /64 prefix, not the address: hex of those 8 bytes.
|
|
8075
|
+
function getIPv6PrefixHexString(ip) {
|
|
8076
|
+
return ipv6Bytes(ip)?.subarray(0, 8).toString('hex') ?? null
|
|
7983
8077
|
}
|
|
7984
8078
|
|
|
7985
8079
|
function numberWithCommas(x) {
|
|
@@ -8020,6 +8114,42 @@ const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
8020
8114
|
|
|
8021
8115
|
const decoder$2 = new TextDecoder();
|
|
8022
8116
|
|
|
8117
|
+
// Each proxy appends to a forwarding header, so the entry `hops` from the right was
|
|
8118
|
+
// written by the outermost trusted proxy; anything left of it came from the client.
|
|
8119
|
+
function forwardedValue(header, hops) {
|
|
8120
|
+
if (!hops || typeof header !== 'string') return undefined
|
|
8121
|
+
const values = header.split(',').map(v => v.trim()).filter(Boolean);
|
|
8122
|
+
return values[Math.max(0, values.length - hops)]
|
|
8123
|
+
}
|
|
8124
|
+
|
|
8125
|
+
// IPv4-mapped addresses as IPv4, '::1' as 127.0.0.1; undefined if not an IP address.
|
|
8126
|
+
function normalizeIP(ip) {
|
|
8127
|
+
if (typeof ip !== 'string') return undefined
|
|
8128
|
+
if (ip.startsWith('::ffff:') && isIPv4$1(ip.slice(7))) ip = ip.slice(7);
|
|
8129
|
+
if (ip === '::1') ip = '127.0.0.1';
|
|
8130
|
+
return isIP(ip) ? ip : undefined
|
|
8131
|
+
}
|
|
8132
|
+
|
|
8133
|
+
// Number of reverse proxies whose forwarding headers are trusted (see serverOption.trustProxy).
|
|
8134
|
+
function trustedProxyHops(peerIP, trust = serverOption.trustProxy) {
|
|
8135
|
+
if (trust === 'private') return peerIP && isPrivateIP(peerIP) ? 1 : 0
|
|
8136
|
+
if (trust === true) return 1
|
|
8137
|
+
return Number.isSafeInteger(trust) && trust > 0 ? trust : 0
|
|
8138
|
+
}
|
|
8139
|
+
|
|
8140
|
+
// Client address and TLS of a WebSocket upgrade request; exported for other servers that
|
|
8141
|
+
// accept the same proxied connections.
|
|
8142
|
+
function getClientAddress(req, trust = serverOption.trustProxy) {
|
|
8143
|
+
const peerIP = normalizeIP(req.socket?.remoteAddress);
|
|
8144
|
+
const hops = trustedProxyHops(peerIP, trust);
|
|
8145
|
+
return {
|
|
8146
|
+
ip: normalizeIP(forwardedValue(req.headers['x-forwarded-for'], hops)) ?? peerIP ?? '0.0.0.0',
|
|
8147
|
+
// X-Forwarded-Proto: https turns off server-side encryption (ENC_MODE.AUTO), so it is
|
|
8148
|
+
// only honored from a trusted proxy, like the client address.
|
|
8149
|
+
TLS: forwardedValue(req.headers['x-forwarded-proto'], hops) === 'https'
|
|
8150
|
+
}
|
|
8151
|
+
}
|
|
8152
|
+
|
|
8023
8153
|
class Remote extends RemoteCore {
|
|
8024
8154
|
constructor(socket, req, manager) {
|
|
8025
8155
|
super(socket, manager);
|
|
@@ -8030,11 +8160,12 @@ class Remote extends RemoteCore {
|
|
|
8030
8160
|
this.socketType = socket.socketType;
|
|
8031
8161
|
|
|
8032
8162
|
if (this.socketType === 'websocket') {
|
|
8033
|
-
|
|
8034
|
-
this.ip =
|
|
8163
|
+
const { ip, TLS } = getClientAddress(req, this.manager.server?.trustProxy);
|
|
8164
|
+
this.ip = ip;
|
|
8165
|
+
this.TLS = TLS;
|
|
8035
8166
|
} else {
|
|
8036
8167
|
this.TLS = false;
|
|
8037
|
-
this.ip =
|
|
8168
|
+
this.ip = normalizeIP(socket.remoteAddress) ?? '0.0.0.0';
|
|
8038
8169
|
}
|
|
8039
8170
|
|
|
8040
8171
|
|
|
@@ -8042,6 +8173,9 @@ class Remote extends RemoteCore {
|
|
|
8042
8173
|
// connection from local or private network has default private channel.
|
|
8043
8174
|
this.HOME_CHANNEL = 'PRIVATE:';
|
|
8044
8175
|
this.privateNode = true;
|
|
8176
|
+
} else if (isIPv6$1(this.ip)) {
|
|
8177
|
+
// An IPv6 network is its /64 prefix; each host there has its own address.
|
|
8178
|
+
this.HOME_CHANNEL = 'IP6:' + getIPv6PrefixHexString(this.ip);
|
|
8045
8179
|
} else {
|
|
8046
8180
|
// The HOME_CHANNEL is defined by the global IP address value.
|
|
8047
8181
|
this.HOME_CHANNEL = 'IP:' + getIPv4HexString(this.ip);
|
|
@@ -8068,10 +8202,11 @@ class Remote extends RemoteCore {
|
|
|
8068
8202
|
this.txDrainMaxMs = Math.max(this.txDrainMaxMs, performance.now() - this.txBlockedSince);
|
|
8069
8203
|
this.txBlockedSince = null;
|
|
8070
8204
|
});
|
|
8071
|
-
this.congRx = new CongRx();
|
|
8205
|
+
this.congRx = new CongRx({ maxFrameSize: this.rxFrameLimit() });
|
|
8072
8206
|
socket.on('data', data => { this.congRx.write(data); });
|
|
8073
8207
|
|
|
8074
8208
|
this.congRx.on('wrong', this.onWrongCongPacketMessage.bind(this));
|
|
8209
|
+
this.congRx.on('oversize', this.onOversizeCongPacket.bind(this));
|
|
8075
8210
|
// readable.pipe( destination )
|
|
8076
8211
|
// tcpSocket -> congRx(parser) -> onMessage
|
|
8077
8212
|
// socket.pipe( this.congRx )
|
|
@@ -8125,13 +8260,32 @@ class Remote extends RemoteCore {
|
|
|
8125
8260
|
}
|
|
8126
8261
|
|
|
8127
8262
|
|
|
8128
|
-
|
|
8129
|
-
|
|
8130
|
-
|
|
8131
|
-
|
|
8263
|
+
// Largest CongSocket frame the parser buffers: maxPayload (as for WebSocket), or the quota's
|
|
8264
|
+
// maxMessageBytes when smaller. A frame payload is the message rxQuotaChecker measures, so a
|
|
8265
|
+
// larger frame would be rejected after buffering anyway.
|
|
8266
|
+
rxFrameLimit() {
|
|
8267
|
+
const maxPayload = this.manager.server?.maxPayload ?? serverOption.maxPayload;
|
|
8268
|
+
const maxMessageBytes = this.quota?.maxMessageBytes ?? null;
|
|
8269
|
+
return maxMessageBytes === null ? maxPayload : Math.min(maxPayload, maxMessageBytes);
|
|
8270
|
+
}
|
|
8132
8271
|
|
|
8272
|
+
// Called after the quota changes (e.g. on successful auth).
|
|
8273
|
+
refreshRxFrameLimit() {
|
|
8274
|
+
if (this.congRx) this.congRx.maxFrameSize = this.rxFrameLimit();
|
|
8133
8275
|
}
|
|
8134
8276
|
|
|
8277
|
+
// The frame was skipped unbuffered; same response as rxQuotaChecker, except that a
|
|
8278
|
+
// connection without a CID is treated like a wrong packet (see onWrongCongPacketMessage).
|
|
8279
|
+
onOversizeCongPacket(payloadSize) {
|
|
8280
|
+
if (this._closing) return;
|
|
8281
|
+
if (!this.cid) {
|
|
8282
|
+
this.manager.attackLogger?.log(`> ${this.ssid} ${this.ip} OVERSIZE ${payloadSize}`);
|
|
8283
|
+
this.close(true);
|
|
8284
|
+
return;
|
|
8285
|
+
}
|
|
8286
|
+
this.manager.counters.oversizeRejected++;
|
|
8287
|
+
this.send(Buffer.from([IOMsg.OVER_SIZE]));
|
|
8288
|
+
}
|
|
8135
8289
|
|
|
8136
8290
|
// any type of received messages: message, ping, pong
|
|
8137
8291
|
receiveMonitor() {
|
|
@@ -8140,27 +8294,9 @@ class Remote extends RemoteCore {
|
|
|
8140
8294
|
this.socket.isAlive = true;
|
|
8141
8295
|
}
|
|
8142
8296
|
|
|
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;
|
|
8297
|
+
// Number of reverse proxies whose forwarding headers this server trusts.
|
|
8298
|
+
trustedProxyHops(peerIP) {
|
|
8299
|
+
return trustedProxyHops(peerIP, this.manager.server?.trustProxy)
|
|
8164
8300
|
}
|
|
8165
8301
|
|
|
8166
8302
|
ping() {
|
|
@@ -8182,15 +8318,15 @@ class Remote extends RemoteCore {
|
|
|
8182
8318
|
}
|
|
8183
8319
|
|
|
8184
8320
|
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;
|
|
8321
|
+
let txb = this.socket.bytesWritten || this.socket._socket?.bytesWritten;
|
|
8322
|
+
let rxb = this.socket.bytesRead || this.socket._socket?.bytesRead;
|
|
8323
|
+
let tx = this.socket.txCounter;
|
|
8324
|
+
let rx = this.socket.rxCounter;
|
|
8325
|
+
return { tx, txb, rx, rxb }
|
|
8189
8326
|
}
|
|
8190
8327
|
|
|
8191
8328
|
close(terminateNow = false) {
|
|
8192
8329
|
this._closing = true;
|
|
8193
|
-
this.getTraffic();
|
|
8194
8330
|
if (this.socketType === 'websocket') {
|
|
8195
8331
|
if (terminateNow) this.socket.terminate();
|
|
8196
8332
|
else this.socket.close();
|
|
@@ -8200,16 +8336,30 @@ class Remote extends RemoteCore {
|
|
|
8200
8336
|
}
|
|
8201
8337
|
}
|
|
8202
8338
|
|
|
8339
|
+
// A peer that stops reading would otherwise grow its send queue without limit.
|
|
8203
8340
|
recordTxQueue() {
|
|
8204
8341
|
const queued = this.socket.bufferedAmount ?? this.socket.writableLength ?? 0;
|
|
8205
8342
|
if (queued > this.txQueuePeakBytes) this.txQueuePeakBytes = queued;
|
|
8343
|
+
const limit = this.manager.server?.maxBufferedBytes ?? serverOption.maxBufferedBytes;
|
|
8344
|
+
if (queued > limit) {
|
|
8345
|
+
console.log(`slow peer #${this.ssid} cid:${this.cid} has ${queued} unsent bytes: closing`);
|
|
8346
|
+
this.close(true);
|
|
8347
|
+
}
|
|
8206
8348
|
}
|
|
8207
8349
|
|
|
8208
8350
|
// node.js server side remote.
|
|
8209
8351
|
send(message, isBinary) {
|
|
8352
|
+
// Sending to a closing peer can only fail; skip instead of logging each attempt.
|
|
8353
|
+
if (this._closing) return;
|
|
8354
|
+
// The peer cannot receive it (see peerRxLimit); a CongSocket Arduino would have to discard it.
|
|
8355
|
+
if (this.peerRxLimit !== null && message.byteLength > this.peerRxLimit) {
|
|
8356
|
+
this.peerRxLimitSkipped++;
|
|
8357
|
+
this.manager.counters.peerRxLimitSkipped++;
|
|
8358
|
+
return;
|
|
8359
|
+
}
|
|
8210
8360
|
// console.log(`<-S [${IOMsg[ message[0]]}]`)
|
|
8211
|
-
this.manager.txBytes += message.byteLength;
|
|
8212
|
-
|
|
8361
|
+
this.manager.counters.txBytes += message.byteLength;
|
|
8362
|
+
this.manager.counters.txMessages++;
|
|
8213
8363
|
this.socket.txCounter++;
|
|
8214
8364
|
if (this.socketType === 'websocket') {
|
|
8215
8365
|
if (this.socket.readyState === 1) {
|
|
@@ -8271,93 +8421,80 @@ class FileLogger {
|
|
|
8271
8421
|
|
|
8272
8422
|
}
|
|
8273
8423
|
|
|
8274
|
-
const
|
|
8275
|
-
|
|
8424
|
+
const KIB = 1024, MIB = 1024 * 1024;
|
|
8425
|
+
|
|
8426
|
+
function bytes(n) {
|
|
8427
|
+
if (n >= MIB) return (n / MIB).toFixed(1) + 'MB'
|
|
8428
|
+
if (n >= KIB) return (n / KIB).toFixed(1) + 'KB'
|
|
8429
|
+
return Math.round(n) + 'B'
|
|
8430
|
+
}
|
|
8276
8431
|
|
|
8432
|
+
// Read-only views of the manager for logStats, Server.stats() and the sudo service.
|
|
8433
|
+
// Nothing here runs on a timer or resets the manager's counters.
|
|
8277
8434
|
class Metrics {
|
|
8278
8435
|
constructor(manager) {
|
|
8279
8436
|
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);
|
|
8437
|
+
this.previous = null; // last summaryLine() sample, for rates
|
|
8312
8438
|
}
|
|
8313
8439
|
|
|
8314
|
-
|
|
8315
|
-
|
|
8316
8440
|
close() {
|
|
8317
|
-
|
|
8318
|
-
this.tickId = null;
|
|
8441
|
+
this.previous = null;
|
|
8319
8442
|
}
|
|
8320
8443
|
|
|
8321
|
-
|
|
8322
|
-
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
|
|
8444
|
+
// Current state; counters are cumulative since the server started. Enumerates connections once.
|
|
8445
|
+
snapshot() {
|
|
8446
|
+
const manager = this.manager;
|
|
8447
|
+
let authenticated = 0, websocket = 0;
|
|
8448
|
+
for (const remote of manager.remotes) {
|
|
8449
|
+
if (remote.boho.isAuthorized) authenticated++;
|
|
8450
|
+
if (remote.socketType === 'websocket') websocket++;
|
|
8451
|
+
}
|
|
8452
|
+
const total = manager.remotes.size;
|
|
8453
|
+
const memory = memoryUsage();
|
|
8454
|
+
return {
|
|
8455
|
+
at: Date.now(),
|
|
8456
|
+
connections: { total, authenticated, anonymous: total - authenticated, websocket, tcp: total - websocket },
|
|
8457
|
+
channels: manager.channel_map.size,
|
|
8458
|
+
retained: { channel: manager.retain_messages.size, bytes: manager.retainBytes },
|
|
8459
|
+
counters: { ...manager.counters },
|
|
8460
|
+
memory: { rss: memory.rss, heapUsed: memory.heapUsed }
|
|
8461
|
+
}
|
|
8462
|
+
}
|
|
8463
|
+
|
|
8464
|
+
// One logStats line; rates are per second since the previous line.
|
|
8465
|
+
summaryLine(now = performance.now()) {
|
|
8466
|
+
const s = this.snapshot(), previous = this.previous;
|
|
8467
|
+
const rate = key => previous ? (s.counters[key] - previous.counters[key]) * 1000 / Math.max(1, now - previous.time) : 0;
|
|
8468
|
+
this.previous = { time: now, counters: s.counters };
|
|
8469
|
+
const c = s.connections;
|
|
8470
|
+
return `[iosignal] conn ${c.total} (auth ${c.authenticated}, anon ${c.anonymous}, ws ${c.websocket}, tcp ${c.tcp})` +
|
|
8471
|
+
` ch ${s.channels} retained ${s.retained.channel}/${bytes(s.retained.bytes)}` +
|
|
8472
|
+
` | rx ${rate('rxMessages').toFixed(1)}/s ${bytes(rate('rxBytes'))}/s` +
|
|
8473
|
+
` tx ${rate('txMessages').toFixed(1)}/s ${bytes(rate('txBytes'))}/s pub ${rate('publishes').toFixed(1)}/s` +
|
|
8474
|
+
` | rss ${bytes(s.memory.rss)} heap ${bytes(s.memory.heapUsed)}`
|
|
8475
|
+
}
|
|
8476
|
+
|
|
8477
|
+
// Compact summary for metrics reports ('@$metrics'); byte counters are cumulative.
|
|
8478
|
+
oneline() {
|
|
8479
|
+
return {
|
|
8330
8480
|
lastSSID: this.manager.lastSSID,
|
|
8331
8481
|
remotes: this.manager.remotes.size,
|
|
8332
8482
|
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]
|
|
8483
|
+
txBytes: this.manager.counters.txBytes,
|
|
8484
|
+
rxBytes: this.manager.counters.rxBytes,
|
|
8485
|
+
}
|
|
8340
8486
|
}
|
|
8341
8487
|
|
|
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
|
|
8488
|
+
getRemotes() {
|
|
8489
|
+
return Array.from(this.manager.remotes, v => "#" + v.ssid + ":" + v.cid + "(" + v.getStateName() + ")")
|
|
8349
8490
|
}
|
|
8350
8491
|
|
|
8351
|
-
getCIdList(
|
|
8352
|
-
|
|
8353
|
-
if (prn) console.table(CIdList);
|
|
8354
|
-
return CIdList
|
|
8492
|
+
getCIdList() {
|
|
8493
|
+
return Array.from(this.manager.cid2remote.keys())
|
|
8355
8494
|
}
|
|
8356
8495
|
|
|
8357
|
-
getChannelList(
|
|
8358
|
-
|
|
8359
|
-
if (prn) console.table(chList);
|
|
8360
|
-
return chList
|
|
8496
|
+
getChannelList() {
|
|
8497
|
+
return Array.from(this.manager.channel_map.keys())
|
|
8361
8498
|
}
|
|
8362
8499
|
|
|
8363
8500
|
getSubscribers(ch) {
|
|
@@ -8368,7 +8505,6 @@ class Metrics {
|
|
|
8368
8505
|
list.push(c.cid);
|
|
8369
8506
|
});
|
|
8370
8507
|
}
|
|
8371
|
-
// console.log(list)
|
|
8372
8508
|
return list
|
|
8373
8509
|
}
|
|
8374
8510
|
|
|
@@ -8407,15 +8543,11 @@ class Metrics {
|
|
|
8407
8543
|
encMode: ENC_MODE[remote.encMode]
|
|
8408
8544
|
}
|
|
8409
8545
|
} 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
8546
|
return {
|
|
8414
8547
|
ip: remote.ip,
|
|
8415
8548
|
uptime: Math.trunc((Date.now() - remote.socket.openTime) / 1000),
|
|
8416
|
-
channels: channels,
|
|
8417
|
-
|
|
8418
|
-
retain: retain_signal
|
|
8549
|
+
channels: Array.from(remote.channels.keys()),
|
|
8550
|
+
retain: Array.from(remote.retain_signal.keys())
|
|
8419
8551
|
}
|
|
8420
8552
|
}
|
|
8421
8553
|
|
|
@@ -8435,14 +8567,17 @@ class Manager {
|
|
|
8435
8567
|
|
|
8436
8568
|
constructor(server, authManager) {
|
|
8437
8569
|
this.server = server;
|
|
8438
|
-
|
|
8439
|
-
this.
|
|
8570
|
+
// This server's settings; a Manager made without a Server (tests, checks) uses the defaults.
|
|
8571
|
+
this.pingPeriod = server?.heartbeatInterval ?? serverOption.heartbeatInterval;
|
|
8572
|
+
this.pingGrace = server?.heartbeatGrace ?? serverOption.heartbeatGrace;
|
|
8440
8573
|
if (!Number.isFinite(this.pingPeriod) || this.pingPeriod <= 0 ||
|
|
8441
8574
|
!Number.isFinite(this.pingGrace) || this.pingGrace < 0) {
|
|
8442
8575
|
throw new RangeError('Invalid heartbeat period or grace');
|
|
8443
8576
|
}
|
|
8444
|
-
|
|
8445
|
-
this.
|
|
8577
|
+
// Cumulative since the server started; never reset (readers compute rates from deltas).
|
|
8578
|
+
this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
|
|
8579
|
+
publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
|
|
8580
|
+
peerRxLimitSkipped: 0 }; // messages not sent: larger than the peer's advertised RX buffer
|
|
8446
8581
|
|
|
8447
8582
|
this.authManager = authManager;
|
|
8448
8583
|
|
|
@@ -8460,7 +8595,12 @@ class Manager {
|
|
|
8460
8595
|
|
|
8461
8596
|
this.remotes = new Set(); // total remotes
|
|
8462
8597
|
this.cid2remote = new Map(); // key: cid -> value: remote
|
|
8598
|
+
this.accountConnectionCounts = new Map(); // uid -> authenticated connections
|
|
8463
8599
|
this.retain_messages = new Map(); // key: tag, data: signalMessage
|
|
8600
|
+
this.retain_owner = new Map(); // key: channel retain tag -> its owner record (see retainOwner)
|
|
8601
|
+
this.retainOwners = new Map(); // key: 'cid:<cid>' | 'conn:<ssid>' | 'net:<HOME_CHANNEL>' -> owner
|
|
8602
|
+
this.retainExpiry = new Map(); // key: channel retain tag in a grace pool -> expiry time
|
|
8603
|
+
this.retainBytes = 0; // all retained messages, channel and CID
|
|
8464
8604
|
this.channel_map = new Map(); // key: channelName -> value: < remote : Set >
|
|
8465
8605
|
this.CHANNEL_PREFIX = 'CH:';
|
|
8466
8606
|
this.CID_PREFIX = 'CID:';
|
|
@@ -8482,18 +8622,49 @@ class Manager {
|
|
|
8482
8622
|
};
|
|
8483
8623
|
this.pingIntervalID = setTimeout(tick, this.pingTickMs);
|
|
8484
8624
|
|
|
8485
|
-
|
|
8486
|
-
|
|
8487
|
-
|
|
8488
|
-
}, serverOption.monitorPeriod);
|
|
8625
|
+
// logStats: one summary line per interval; it never clears the terminal, so other logs stay.
|
|
8626
|
+
if (server.logStats) {
|
|
8627
|
+
this.statsIntervalID = setInterval(() => console.log(this.metrics.summaryLine()), server.logStats);
|
|
8489
8628
|
}
|
|
8490
8629
|
|
|
8491
8630
|
|
|
8492
8631
|
}
|
|
8493
8632
|
|
|
8494
8633
|
|
|
8634
|
+
get retainOptions() {
|
|
8635
|
+
return this.server?.retain ?? serverOption.retain
|
|
8636
|
+
}
|
|
8637
|
+
|
|
8638
|
+
get quotas() {
|
|
8639
|
+
return this.server?.quotas ?? serverOption.quotas
|
|
8640
|
+
}
|
|
8641
|
+
|
|
8642
|
+
get anonymousQuota() {
|
|
8643
|
+
return this.server?.anonymousQuota ?? serverOption.anonymousQuota
|
|
8644
|
+
}
|
|
8645
|
+
|
|
8646
|
+
// Authenticated connections per account (uid), for the quota's maxConnections.
|
|
8647
|
+
accountConnections(uid) {
|
|
8648
|
+
return this.accountConnectionCounts.get(uid) ?? 0
|
|
8649
|
+
}
|
|
8650
|
+
|
|
8651
|
+
addAccountConnection(remote, uid) {
|
|
8652
|
+
remote.accountUid = uid;
|
|
8653
|
+
this.accountConnectionCounts.set(uid, this.accountConnections(uid) + 1);
|
|
8654
|
+
}
|
|
8655
|
+
|
|
8656
|
+
removeAccountConnection(remote) {
|
|
8657
|
+
const uid = remote.accountUid;
|
|
8658
|
+
if (!uid) return
|
|
8659
|
+
remote.accountUid = null;
|
|
8660
|
+
const count = this.accountConnections(uid) - 1;
|
|
8661
|
+
if (count > 0) this.accountConnectionCounts.set(uid, count);
|
|
8662
|
+
else this.accountConnectionCounts.delete(uid);
|
|
8663
|
+
}
|
|
8664
|
+
|
|
8495
8665
|
heartbeatTick() {
|
|
8496
8666
|
const now = performance.now();
|
|
8667
|
+
if (this.retainExpiry.size) this.expireChannelRetains(now);
|
|
8497
8668
|
// Process only expired requests, not every connected peer.
|
|
8498
8669
|
for (const [remote, deadline] of this.heartbeatPending) {
|
|
8499
8670
|
if (deadline > now) break;
|
|
@@ -8536,6 +8707,7 @@ class Manager {
|
|
|
8536
8707
|
removeRemote(remote) {
|
|
8537
8708
|
|
|
8538
8709
|
remote._closing = true;
|
|
8710
|
+
this.removeAccountConnection(remote);
|
|
8539
8711
|
this.pingGroups[remote.pingGroup]?.delete(remote);
|
|
8540
8712
|
this.heartbeatPending.delete(remote);
|
|
8541
8713
|
remote.setState(STATE.CLOSED);
|
|
@@ -8561,6 +8733,10 @@ class Manager {
|
|
|
8561
8733
|
|
|
8562
8734
|
// retain message policy
|
|
8563
8735
|
// type 1. ( isAuthorizedUser) ? keep : delete.
|
|
8736
|
+
// Channel retains: an authenticated writer's belong to its account and stay; an anonymous
|
|
8737
|
+
// connection's move to its network's grace pool and expire there.
|
|
8738
|
+
this.orphanChannelRetains(remote);
|
|
8739
|
+
|
|
8564
8740
|
if (remote.boho.isAuthorized) ; else {
|
|
8565
8741
|
// anonymouse: remove the cid publish channel
|
|
8566
8742
|
for (let ch of remote.retain_signal.keys()) {
|
|
@@ -8572,6 +8748,10 @@ class Manager {
|
|
|
8572
8748
|
}
|
|
8573
8749
|
}
|
|
8574
8750
|
}
|
|
8751
|
+
// CID retains live in the remote and go with it (after the '@$state' close above).
|
|
8752
|
+
for (const message of remote.retain_signal.values()) this.retainBytes -= message.byteLength;
|
|
8753
|
+
remote.retain_signal.clear();
|
|
8754
|
+
remote.retainBytes = 0;
|
|
8575
8755
|
|
|
8576
8756
|
|
|
8577
8757
|
// Service lifecycle hook. Called directly: RPC permission/command checks do not apply to cleanup.
|
|
@@ -8643,9 +8823,7 @@ class Manager {
|
|
|
8643
8823
|
let topic = tag.split('@')[1];
|
|
8644
8824
|
if (cid && this.cid2remote.has(cid)) {
|
|
8645
8825
|
let sigPack = getSignalPack('@' + topic, ...args);
|
|
8646
|
-
|
|
8647
|
-
console.log('target', targetRemote.state, targetRemote.cid);
|
|
8648
|
-
targetRemote.send_enc_mode(sigPack);
|
|
8826
|
+
this.cid2remote.get(cid).send_enc_mode(sigPack);
|
|
8649
8827
|
return
|
|
8650
8828
|
} else {
|
|
8651
8829
|
return "no cid"
|
|
@@ -8654,7 +8832,7 @@ class Manager {
|
|
|
8654
8832
|
|
|
8655
8833
|
sender(tag, remote, message) {
|
|
8656
8834
|
if (encoder.encode(tag).byteLength > SIZE_LIMIT.TAG_LEN1) return ['err', 'Tag exceeds 255 UTF-8 bytes']
|
|
8657
|
-
if (serverOption.membersOnly && !remote.boho.isAuthorized) {
|
|
8835
|
+
if ((this.server?.membersOnly ?? serverOption.membersOnly) && !remote.boho.isAuthorized) {
|
|
8658
8836
|
// console.log("### server reject client signal reason: [membersOnly]" ,tag, remote.cid )
|
|
8659
8837
|
remote.send(Buffer.from([IOMsg.AUTH_CLEAR]));
|
|
8660
8838
|
remote.close();
|
|
@@ -8708,35 +8886,26 @@ class Manager {
|
|
|
8708
8886
|
// retain signal message
|
|
8709
8887
|
if (tag.includes('$')
|
|
8710
8888
|
// && remote.boho.isAuthorized
|
|
8711
|
-
&&
|
|
8712
|
-
&& serverOption.retain.limitCounter > this.retain_messages.size
|
|
8713
|
-
&& serverOption.retain.limitSize > message.byteLength
|
|
8889
|
+
&& this.retainOptions.enabled
|
|
8714
8890
|
) {
|
|
8715
|
-
// cid retain signal
|
|
8716
8891
|
if (tag.includes('@')) {
|
|
8717
|
-
// cid retain signal stored inside remote.
|
|
8718
|
-
|
|
8719
|
-
remote.retain_signal.set(retainTag, message);
|
|
8892
|
+
// cid retain signal stored inside remote, counted per remote.
|
|
8893
|
+
this.storeCidRetain(tag.split('@')[1], message, remote);
|
|
8720
8894
|
} else {
|
|
8721
8895
|
// channel retain signal stored inside manager.
|
|
8722
|
-
this.
|
|
8896
|
+
this.storeChannelRetain(tag, message, remote);
|
|
8723
8897
|
}
|
|
8724
|
-
|
|
8725
8898
|
}
|
|
8726
8899
|
|
|
8727
|
-
|
|
8900
|
+
this.counters.publishes++;
|
|
8728
8901
|
let sentCounter = 0;
|
|
8729
8902
|
if (this.channel_map.has(tag)) {
|
|
8730
8903
|
// console.log('raw channel_map matched tag:', tag)
|
|
8731
8904
|
let remotes = this.channel_map.get(tag);
|
|
8732
8905
|
if (remotes.size >= 1) {
|
|
8733
|
-
|
|
8734
|
-
|
|
8735
|
-
|
|
8736
|
-
} else {
|
|
8737
|
-
limit = remotes.size;
|
|
8738
|
-
}
|
|
8739
|
-
if (this.telemetry) this.telemetry.quotaExcluded += remotes.size - limit;
|
|
8906
|
+
const fanout = remote.quota.fanout;
|
|
8907
|
+
const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
|
|
8908
|
+
this.counters.quotaExcluded += remotes.size - limit;
|
|
8740
8909
|
let peers = remotes.values();
|
|
8741
8910
|
while (sentCounter < limit) {
|
|
8742
8911
|
let c = peers.next().value;
|
|
@@ -8751,12 +8920,7 @@ class Manager {
|
|
|
8751
8920
|
// }
|
|
8752
8921
|
}
|
|
8753
8922
|
|
|
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;
|
|
8923
|
+
this.counters.deliveryAttempts += sentCounter;
|
|
8760
8924
|
return ['ok', sentCounter]
|
|
8761
8925
|
}
|
|
8762
8926
|
}
|
|
@@ -8766,6 +8930,123 @@ class Manager {
|
|
|
8766
8930
|
|
|
8767
8931
|
|
|
8768
8932
|
|
|
8933
|
+
// Retained messages are stored as exact-size copies (a subarray would keep a whole socket chunk
|
|
8934
|
+
// or 8 KiB Buffer pool slab alive), within an owner's budget and bytesTotal server-wide. A value
|
|
8935
|
+
// that cannot be stored (size, count or budget) also removes the value it would replace, so a
|
|
8936
|
+
// later subscriber never gets a stale one.
|
|
8937
|
+
retainFits(message, freed, ownerBytes, budget) {
|
|
8938
|
+
return this.retainOptions.limitSize > message.byteLength &&
|
|
8939
|
+
ownerBytes + message.byteLength <= budget &&
|
|
8940
|
+
this.retainBytes + message.byteLength - freed <= this.retainOptions.bytesTotal
|
|
8941
|
+
}
|
|
8942
|
+
|
|
8943
|
+
retainCopy(message) {
|
|
8944
|
+
const copy = Buffer.allocUnsafeSlow(message.byteLength);
|
|
8945
|
+
copy.set(message);
|
|
8946
|
+
this.retainBytes += copy.byteLength;
|
|
8947
|
+
return copy
|
|
8948
|
+
}
|
|
8949
|
+
|
|
8950
|
+
// A connection's CID retains go with it: within bytesPerConnection; limitCounter caps new tags.
|
|
8951
|
+
storeCidRetain(key, message, remote) {
|
|
8952
|
+
const map = remote.retain_signal;
|
|
8953
|
+
const old = map.get(key);
|
|
8954
|
+
const freed = old?.byteLength ?? 0;
|
|
8955
|
+
if ((old || map.size < this.retainOptions.limitCounter) &&
|
|
8956
|
+
this.retainFits(message, freed, remote.retainBytes - freed, this.retainOptions.bytesPerConnection)) {
|
|
8957
|
+
map.set(key, this.retainCopy(message));
|
|
8958
|
+
this.retainBytes -= freed;
|
|
8959
|
+
remote.retainBytes += message.byteLength - freed;
|
|
8960
|
+
} else if (old) {
|
|
8961
|
+
map.delete(key);
|
|
8962
|
+
this.retainBytes -= freed;
|
|
8963
|
+
remote.retainBytes -= freed;
|
|
8964
|
+
}
|
|
8965
|
+
}
|
|
8966
|
+
|
|
8967
|
+
// Channel retain owner: the last writer's account (an authenticated CID, shared by its
|
|
8968
|
+
// connections, so reconnecting does not reset its budget) or an anonymous writer's connection.
|
|
8969
|
+
// Each owner holds at most tagsPerOwner tags and bytesPerOwner bytes.
|
|
8970
|
+
retainOwner(key) {
|
|
8971
|
+
let owner = this.retainOwners.get(key);
|
|
8972
|
+
if (!owner) this.retainOwners.set(key, owner = { key, bytes: 0, tags: new Set() });
|
|
8973
|
+
return owner
|
|
8974
|
+
}
|
|
8975
|
+
|
|
8976
|
+
storeChannelRetain(tag, message, remote) {
|
|
8977
|
+
const owner = this.retainOwner(remote.boho.isAuthorized ? 'cid:' + remote.cid : 'conn:' + remote.ssid);
|
|
8978
|
+
const old = this.retain_messages.get(tag);
|
|
8979
|
+
const freed = old?.byteLength ?? 0;
|
|
8980
|
+
const room = old || (this.retain_messages.size < this.retainOptions.limitCounter &&
|
|
8981
|
+
owner.tags.size < this.retainOptions.tagsPerOwner);
|
|
8982
|
+
const ownerBytes = owner.bytes - (this.retain_owner.get(tag) === owner ? freed : 0);
|
|
8983
|
+
if (room && this.retainFits(message, freed, ownerBytes, this.retainOptions.bytesPerOwner)) {
|
|
8984
|
+
if (old) this.releaseChannelRetain(tag, freed);
|
|
8985
|
+
this.retain_messages.set(tag, this.retainCopy(message));
|
|
8986
|
+
owner.bytes += message.byteLength;
|
|
8987
|
+
owner.tags.add(tag);
|
|
8988
|
+
this.retain_owner.set(tag, owner);
|
|
8989
|
+
this.retainOwners.set(owner.key, owner); // releasing may have removed it when it emptied
|
|
8990
|
+
} else if (old) {
|
|
8991
|
+
this.dropChannelRetain(tag);
|
|
8992
|
+
}
|
|
8993
|
+
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
8994
|
+
}
|
|
8995
|
+
|
|
8996
|
+
// A closed anonymous connection's channel retains stay anonymousGraceMs in its network's pool
|
|
8997
|
+
// (by HOME_CHANNEL), which has the same owner budget: reconnecting cannot pile values up, and
|
|
8998
|
+
// when the pool is over budget the values closest to expiry go first, least recently written
|
|
8999
|
+
// first among equals (an update moves its tag to the end of the owner's set).
|
|
9000
|
+
orphanChannelRetains(remote) {
|
|
9001
|
+
const conn = this.retainOwners.get('conn:' + remote.ssid);
|
|
9002
|
+
if (!conn) return
|
|
9003
|
+
const grace = this.retainOptions.anonymousGraceMs;
|
|
9004
|
+
if (!(grace > 0)) {
|
|
9005
|
+
for (const tag of [...conn.tags]) this.dropChannelRetain(tag);
|
|
9006
|
+
return
|
|
9007
|
+
}
|
|
9008
|
+
this.retainOwners.delete(conn.key);
|
|
9009
|
+
const pool = this.retainOwner('net:' + remote.HOME_CHANNEL);
|
|
9010
|
+
const expires = performance.now() + grace;
|
|
9011
|
+
for (const tag of conn.tags) {
|
|
9012
|
+
pool.tags.add(tag);
|
|
9013
|
+
pool.bytes += this.retain_messages.get(tag).byteLength;
|
|
9014
|
+
this.retain_owner.set(tag, pool);
|
|
9015
|
+
this.retainExpiry.set(tag, expires);
|
|
9016
|
+
}
|
|
9017
|
+
while (pool.bytes > this.retainOptions.bytesPerOwner || pool.tags.size > this.retainOptions.tagsPerOwner) {
|
|
9018
|
+
let first;
|
|
9019
|
+
for (const tag of pool.tags) {
|
|
9020
|
+
if (first === undefined || this.retainExpiry.get(tag) < this.retainExpiry.get(first)) first = tag;
|
|
9021
|
+
}
|
|
9022
|
+
this.dropChannelRetain(first);
|
|
9023
|
+
}
|
|
9024
|
+
}
|
|
9025
|
+
|
|
9026
|
+
expireChannelRetains(now = performance.now()) {
|
|
9027
|
+
for (const [tag, expires] of this.retainExpiry) {
|
|
9028
|
+
if (expires <= now) this.dropChannelRetain(tag);
|
|
9029
|
+
}
|
|
9030
|
+
}
|
|
9031
|
+
|
|
9032
|
+
dropChannelRetain(tag) {
|
|
9033
|
+
const old = this.retain_messages.get(tag);
|
|
9034
|
+
if (!old) return
|
|
9035
|
+
this.releaseChannelRetain(tag, old.byteLength);
|
|
9036
|
+
this.retain_messages.delete(tag);
|
|
9037
|
+
}
|
|
9038
|
+
|
|
9039
|
+
releaseChannelRetain(tag, size) {
|
|
9040
|
+
const owner = this.retain_owner.get(tag);
|
|
9041
|
+
this.retain_owner.delete(tag);
|
|
9042
|
+
this.retainExpiry.delete(tag);
|
|
9043
|
+
this.retainBytes -= size;
|
|
9044
|
+
if (!owner) return
|
|
9045
|
+
owner.tags.delete(tag);
|
|
9046
|
+
owner.bytes -= size;
|
|
9047
|
+
if (owner.tags.size === 0) this.retainOwners.delete(owner.key);
|
|
9048
|
+
}
|
|
9049
|
+
|
|
8769
9050
|
subscribe(chArr, remote) {
|
|
8770
9051
|
chArr.forEach(tag => {
|
|
8771
9052
|
if (tag.indexOf('#') === 0) {
|
|
@@ -8788,7 +9069,7 @@ class Manager {
|
|
|
8788
9069
|
|
|
8789
9070
|
// 3. send retain message if available.
|
|
8790
9071
|
if (tag.includes('$')
|
|
8791
|
-
&&
|
|
9072
|
+
&& this.retainOptions.enabled
|
|
8792
9073
|
) {
|
|
8793
9074
|
let retainMessage;
|
|
8794
9075
|
if (tag.includes('@')) {
|
|
@@ -8854,31 +9135,6 @@ class Manager {
|
|
|
8854
9135
|
}
|
|
8855
9136
|
|
|
8856
9137
|
|
|
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
9138
|
anonymousCidRandom(size) {
|
|
8883
9139
|
return globalThis.crypto.getRandomValues(Buffer.alloc(size))
|
|
8884
9140
|
}
|
|
@@ -8911,8 +9167,8 @@ class Manager {
|
|
|
8911
9167
|
clearTimeout(this.pingIntervalID);
|
|
8912
9168
|
this.heartbeatPending.clear();
|
|
8913
9169
|
for (const group of this.pingGroups) group.clear();
|
|
8914
|
-
if (this.
|
|
8915
|
-
clearInterval(this.
|
|
9170
|
+
if (this.statsIntervalID) {
|
|
9171
|
+
clearInterval(this.statsIntervalID);
|
|
8916
9172
|
}
|
|
8917
9173
|
|
|
8918
9174
|
this.remotes.forEach(remote => {
|
|
@@ -8922,6 +9178,10 @@ class Manager {
|
|
|
8922
9178
|
this.remotes.clear();
|
|
8923
9179
|
this.cid2remote.clear();
|
|
8924
9180
|
this.retain_messages.clear();
|
|
9181
|
+
this.retain_owner.clear();
|
|
9182
|
+
this.retainOwners.clear();
|
|
9183
|
+
this.retainExpiry.clear();
|
|
9184
|
+
this.retainBytes = 0;
|
|
8925
9185
|
this.channel_map.clear();
|
|
8926
9186
|
|
|
8927
9187
|
}
|
|
@@ -8946,15 +9206,42 @@ function validateDuplicateLogin(policy) {
|
|
|
8946
9206
|
return policy
|
|
8947
9207
|
}
|
|
8948
9208
|
|
|
9209
|
+
// Connection roles, lowest to highest: what a connection may do. Its quota is separate.
|
|
9210
|
+
// 'anonymous' is the role of every connection until it authenticates.
|
|
9211
|
+
const ROLES = ['anonymous', 'device', 'service', 'admin'];
|
|
9212
|
+
|
|
9213
|
+
/** Role of a login: the account's role, 'device' when it has none; undefined if unknown. */
|
|
9214
|
+
function resolveRole(role) {
|
|
9215
|
+
if (role === undefined || role === null || role === '') return 'device'
|
|
9216
|
+
return ROLES.includes(role) && role !== 'anonymous' ? role : undefined
|
|
9217
|
+
}
|
|
9218
|
+
|
|
9219
|
+
/** True if the remote is authenticated with this role or a higher one ('anonymous': always). */
|
|
9220
|
+
function hasRole(remote, role) {
|
|
9221
|
+
const wanted = ROLES.indexOf(role);
|
|
9222
|
+
if (wanted < 0) throw new RangeError(`role must be one of: ${ROLES.join(', ')}`)
|
|
9223
|
+
if (wanted === 0) return true
|
|
9224
|
+
return remote?.boho?.isAuthorized === true && ROLES.indexOf(remote.role) >= wanted
|
|
9225
|
+
}
|
|
9226
|
+
|
|
9227
|
+
/** Default quota profile of a login: the account's quota, else 'basic' for a device, 'unlimited' otherwise. */
|
|
9228
|
+
function defaultQuota(authInfo, role) {
|
|
9229
|
+
return authInfo.quota || (role === 'device' ? 'basic' : 'unlimited')
|
|
9230
|
+
}
|
|
9231
|
+
|
|
8949
9232
|
class BohoAuth {
|
|
8950
9233
|
/**
|
|
8951
9234
|
* @param {object} keyProvider
|
|
8952
|
-
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any
|
|
9235
|
+
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any,
|
|
9236
|
+
* resolveQuota?: (authInfo: object, role: string) => string | Promise<string> }} [options]
|
|
8953
9237
|
* duplicateLogin: unset follows serverOption.auth.duplicateLogin (default 'keepNew').
|
|
9238
|
+
* A Server's duplicateLogin option takes precedence for that Server's connections.
|
|
8954
9239
|
* onAuthEvent: called with { type, did, cid, uid, ip, oldIp, socketType, oldSocketType, reason, at }
|
|
8955
9240
|
* for 'replaced' (keepNew evicted the old connection) and 'duplicate_rejected' (keepOld).
|
|
8956
9241
|
* socketType/oldSocketType are 'websocket' or 'congsocket'.
|
|
8957
9242
|
* Errors and rejected promises are logged and never affect authentication.
|
|
9243
|
+
* resolveQuota: name of the Server quota profile for a login (default: defaultQuota), e.g. from
|
|
9244
|
+
* the account owner's plan. An unknown name fails the login.
|
|
8958
9245
|
*/
|
|
8959
9246
|
constructor(keyProvider, options = {}) {
|
|
8960
9247
|
if (!keyProvider) {
|
|
@@ -8964,6 +9251,7 @@ class BohoAuth {
|
|
|
8964
9251
|
this._duplicateLogin = null;
|
|
8965
9252
|
if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
|
|
8966
9253
|
this.onAuthEvent = options.onAuthEvent ?? null;
|
|
9254
|
+
this.resolveQuota = options.resolveQuota ?? defaultQuota;
|
|
8967
9255
|
this.authLogger;
|
|
8968
9256
|
if (serverOption.fileLogger.auth.use) {
|
|
8969
9257
|
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
@@ -8981,6 +9269,11 @@ class BohoAuth {
|
|
|
8981
9269
|
this._duplicateLogin = policy === null ? null : validateDuplicateLogin(policy);
|
|
8982
9270
|
}
|
|
8983
9271
|
|
|
9272
|
+
/** Policy for a connection: its Server's duplicateLogin option, else this instance's policy. */
|
|
9273
|
+
duplicateLoginFor(peer) {
|
|
9274
|
+
return peer.manager?.server?.duplicateLogin ?? this.duplicateLogin;
|
|
9275
|
+
}
|
|
9276
|
+
|
|
8984
9277
|
// Backward-compatible boolean form of duplicateLogin.
|
|
8985
9278
|
get keepOldConnection() {
|
|
8986
9279
|
return this.duplicateLogin === 'keepOld';
|
|
@@ -9013,7 +9306,7 @@ class BohoAuth {
|
|
|
9013
9306
|
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
9014
9307
|
peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
9015
9308
|
}
|
|
9016
|
-
}, serverOption.auth.
|
|
9309
|
+
}, serverOption.auth.failDelay);
|
|
9017
9310
|
}
|
|
9018
9311
|
|
|
9019
9312
|
|
|
@@ -9047,8 +9340,9 @@ class BohoAuth {
|
|
|
9047
9340
|
return
|
|
9048
9341
|
}
|
|
9049
9342
|
|
|
9343
|
+
// Never the key: debug output ends up in shared logs.
|
|
9050
9344
|
if (serverOption.debug.showAuthInfo) {
|
|
9051
|
-
console.log('[debug]showAuthInfo', authInfo);
|
|
9345
|
+
console.log('[debug]showAuthInfo', { id, cid: authInfo.cid, uid: authInfo.uid, role: authInfo.role, quota: authInfo.quota });
|
|
9052
9346
|
}
|
|
9053
9347
|
|
|
9054
9348
|
peer.boho.copy_id8(infoPack.id8);
|
|
@@ -9075,7 +9369,29 @@ class BohoAuth {
|
|
|
9075
9369
|
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9076
9370
|
peer._challengeUsed = true;
|
|
9077
9371
|
|
|
9078
|
-
//4.
|
|
9372
|
+
//4. role and quota. Checked before a duplicate login replaces the old connection.
|
|
9373
|
+
const role = resolveRole(authInfo.role);
|
|
9374
|
+
if (role === undefined) {
|
|
9375
|
+
this.send_auth_fail(peer, 'unknown auth.role: ' + authInfo.role);
|
|
9376
|
+
return
|
|
9377
|
+
}
|
|
9378
|
+
const quotaName = await this.resolveQuota(authInfo, role);
|
|
9379
|
+
const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
|
|
9380
|
+
if (!quota) {
|
|
9381
|
+
this.send_auth_fail(peer, 'unknown quota: ' + quotaName);
|
|
9382
|
+
return
|
|
9383
|
+
}
|
|
9384
|
+
if (peer._closing) return; // closed while resolving
|
|
9385
|
+
const uid = authInfo.uid || null;
|
|
9386
|
+
if (uid && quota.maxConnections !== null) {
|
|
9387
|
+
// A connection this login replaces (keepNew) frees its place.
|
|
9388
|
+
const old = peer.manager.cid2remote.get(authInfo.cid);
|
|
9389
|
+
const replaced = old && old !== peer && old.accountUid === uid && this.duplicateLoginFor(peer) === 'keepNew' ? 1 : 0;
|
|
9390
|
+
if (peer.manager.accountConnections(uid) - replaced >= quota.maxConnections) {
|
|
9391
|
+
this.send_auth_fail(peer, 'too many connections');
|
|
9392
|
+
return
|
|
9393
|
+
}
|
|
9394
|
+
}
|
|
9079
9395
|
|
|
9080
9396
|
//5. check duplicate login.
|
|
9081
9397
|
if (peer.manager.cid2remote.has(authInfo.cid) && peer.manager.cid2remote.get(authInfo.cid) !== peer) {
|
|
@@ -9087,7 +9403,8 @@ class BohoAuth {
|
|
|
9087
9403
|
$$1.MB('#MsgType', '8', IOMsg.AUTH_CLEAR),
|
|
9088
9404
|
$$1.MB('#reason', 'duplicate login.')
|
|
9089
9405
|
);
|
|
9090
|
-
|
|
9406
|
+
const keepOld = this.duplicateLoginFor(peer) === 'keepOld';
|
|
9407
|
+
if (keepOld) {
|
|
9091
9408
|
peer.boho.isAuthorized = false;
|
|
9092
9409
|
// keep old connection. reject new connection by sending auth_fail signal.
|
|
9093
9410
|
// peer.send(authClearSignal)
|
|
@@ -9103,13 +9420,13 @@ class BohoAuth {
|
|
|
9103
9420
|
old.close();
|
|
9104
9421
|
}
|
|
9105
9422
|
this.emitAuthEvent({
|
|
9106
|
-
type:
|
|
9423
|
+
type: keepOld ? 'duplicate_rejected' : 'replaced',
|
|
9107
9424
|
did: id, cid: authInfo.cid, uid: authInfo.uid || null,
|
|
9108
9425
|
ip: peer.ip, oldIp: old.ip,
|
|
9109
9426
|
socketType: transportOf(peer), oldSocketType: transportOf(old),
|
|
9110
9427
|
reason: 'duplicate login', at: Date.now()
|
|
9111
9428
|
});
|
|
9112
|
-
if (
|
|
9429
|
+
if (keepOld) return
|
|
9113
9430
|
}
|
|
9114
9431
|
|
|
9115
9432
|
//6. delete current (or anonymouse)cid if exist.
|
|
@@ -9124,26 +9441,11 @@ class BohoAuth {
|
|
|
9124
9441
|
peer.nick = authInfo.cid; // temporary: nick as cid
|
|
9125
9442
|
if (authInfo.uid) peer.uid = authInfo.uid;
|
|
9126
9443
|
|
|
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]));
|
|
9444
|
+
//8. role and quota; the client is told its quota.
|
|
9445
|
+
peer.role = role;
|
|
9446
|
+
if (role === 'admin') console.log('## LOGIN ADMIN CID:', peer.cid);
|
|
9447
|
+
if (uid) peer.manager.addAccountConnection(peer, uid);
|
|
9448
|
+
peer.setQuota(quotaName, true);
|
|
9147
9449
|
|
|
9148
9450
|
//9. set cid2remote
|
|
9149
9451
|
peer.manager.cid2remote.set(peer.cid, peer);
|
|
@@ -9172,9 +9474,9 @@ class BohoAuth {
|
|
|
9172
9474
|
}
|
|
9173
9475
|
}
|
|
9174
9476
|
|
|
9175
|
-
async addAuth(id, keyStr, cid,
|
|
9477
|
+
async addAuth(id, keyStr, cid, role, quota) {
|
|
9176
9478
|
if (typeof this.keyProvider.addAuth === 'function') {
|
|
9177
|
-
return this.keyProvider.addAuth(id, keyStr, cid,
|
|
9479
|
+
return this.keyProvider.addAuth(id, keyStr, cid, role, quota);
|
|
9178
9480
|
}
|
|
9179
9481
|
}
|
|
9180
9482
|
|
|
@@ -9200,7 +9502,8 @@ class BohoAuth {
|
|
|
9200
9502
|
*
|
|
9201
9503
|
* mode 'idKey': the key equals the ID, e.g. io.auth('dev1', 'dev1').
|
|
9202
9504
|
* mode 'sharedKey': any ID with the one shared key, e.g. io.auth('dev1', 'lab2026').
|
|
9203
|
-
*
|
|
9505
|
+
* role: role of every login, default 'device' ('service' or 'admin' must be asked for).
|
|
9506
|
+
* quota: Server quotas profile of every login, default from BohoAuth resolveQuota.
|
|
9204
9507
|
*
|
|
9205
9508
|
* example => new BohoAuth(new LocalKeyProvider({ mode: 'sharedKey', key: 'lab2026' }))
|
|
9206
9509
|
*
|
|
@@ -9213,23 +9516,27 @@ const hashKey = keyStr => Buffer.from(it.sha256.hash(keyStr)).toString('base64')
|
|
|
9213
9516
|
|
|
9214
9517
|
class LocalKeyProvider {
|
|
9215
9518
|
/**
|
|
9216
|
-
* @param {'idKey' | { mode: 'idKey' | 'sharedKey', key?: string,
|
|
9519
|
+
* @param {'idKey' | { mode: 'idKey' | 'sharedKey', key?: string,
|
|
9520
|
+
* role?: 'device' | 'service' | 'admin', quota?: string }} options
|
|
9217
9521
|
* A string is the mode alone.
|
|
9218
9522
|
*/
|
|
9219
9523
|
constructor(options) {
|
|
9220
|
-
const { mode, key,
|
|
9524
|
+
const { mode, key, role = 'device', quota } = typeof options === 'string' ? { mode: options } : (options ?? {});
|
|
9221
9525
|
if (!MODES.includes(mode)) {
|
|
9222
9526
|
throw new TypeError(`LocalKeyProvider mode must be one of: ${MODES.join(', ')}`)
|
|
9223
9527
|
}
|
|
9224
9528
|
if (mode === 'sharedKey' && (typeof key !== 'string' || key.length === 0)) {
|
|
9225
9529
|
throw new TypeError("LocalKeyProvider mode 'sharedKey' needs a non-empty key")
|
|
9226
9530
|
}
|
|
9227
|
-
|
|
9228
|
-
|
|
9229
|
-
|
|
9531
|
+
if (quota !== undefined && (typeof quota !== 'string' || !quota)) {
|
|
9532
|
+
throw new TypeError('LocalKeyProvider quota must be a quotas profile name')
|
|
9533
|
+
}
|
|
9534
|
+
if (!ROLES.includes(role) || role === 'anonymous') {
|
|
9535
|
+
throw new RangeError(`LocalKeyProvider role must be one of: ${ROLES.slice(1).join(', ')}`)
|
|
9230
9536
|
}
|
|
9231
9537
|
this.mode = mode;
|
|
9232
|
-
this.
|
|
9538
|
+
this.role = role;
|
|
9539
|
+
this.quota = quota;
|
|
9233
9540
|
// Hashed like StringKeyProvider, so a 44-character shared key is not mistaken for a stored hash.
|
|
9234
9541
|
this.sharedKeyHash = mode === 'sharedKey' ? hashKey(key) : null;
|
|
9235
9542
|
}
|
|
@@ -9239,18 +9546,128 @@ class LocalKeyProvider {
|
|
|
9239
9546
|
return {
|
|
9240
9547
|
key: this.sharedKeyHash ?? hashKey(id),
|
|
9241
9548
|
cid: id,
|
|
9242
|
-
|
|
9549
|
+
role: this.role,
|
|
9550
|
+
...(this.quota && { quota: this.quota })
|
|
9243
9551
|
}
|
|
9244
9552
|
}
|
|
9245
9553
|
}
|
|
9246
9554
|
|
|
9555
|
+
// Removed or renamed in 9.0, as Server options and as serverOption keys ('global': only as a
|
|
9556
|
+
// serverOption key). An error names the replacement instead of the setting silently doing nothing.
|
|
9557
|
+
const REMOVED = [
|
|
9558
|
+
['showMessage', 'logMessages: true'],
|
|
9559
|
+
['showMetric', "logStats: <interval ms> (for lists, the sudo service's remotes/channels commands)"],
|
|
9560
|
+
['monitorPeriod', 'logStats: <interval ms>'],
|
|
9561
|
+
['timeout', 'heartbeatInterval'],
|
|
9562
|
+
['pingTimeoutGrace', 'heartbeatGrace'],
|
|
9563
|
+
['retain.isAvailable', 'retain.enabled'],
|
|
9564
|
+
['useQuota', 'quotas: named quota profiles, always enforced (null: unlimited)'],
|
|
9565
|
+
['defaultQuotaIndex', "anonymousQuota: a quotas profile name; logins use their account's quota"],
|
|
9566
|
+
['auth.delay_auth_fail', 'auth.failDelay', 'global'],
|
|
9567
|
+
['adminLevel', "role: 'admin' in the account (key entry)", 'global'],
|
|
9568
|
+
['clientTracking', 'nothing: it was never used', 'global'],
|
|
9569
|
+
...['port', 'congPort', 'httpServer', 'wsPath'].map(name => [name, `new Server({ ${name} })`, 'global'])
|
|
9570
|
+
];
|
|
9571
|
+
const lookup = (object, path) => path.split('.').reduce((value, key) => value?.[key], object);
|
|
9572
|
+
|
|
9573
|
+
function checkRemoved(options) {
|
|
9574
|
+
for (const [path, replacement, scope] of REMOVED) {
|
|
9575
|
+
const sources = scope === 'global' ? [['serverOption.', serverOption]] : [['', options], ['serverOption.', serverOption]];
|
|
9576
|
+
for (const [prefix, source] of sources) {
|
|
9577
|
+
if (lookup(source, path) !== undefined) {
|
|
9578
|
+
throw new TypeError(`${prefix}${path} was removed in iosignal 9.0; use ${replacement}`)
|
|
9579
|
+
}
|
|
9580
|
+
}
|
|
9581
|
+
}
|
|
9582
|
+
}
|
|
9583
|
+
|
|
9584
|
+
const MAX_TIMER_MS = 2147483647; // setTimeout limit
|
|
9585
|
+
|
|
9586
|
+
function integer(name, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
9587
|
+
if (!Number.isSafeInteger(value) || value < min || value > max) {
|
|
9588
|
+
throw new RangeError(`${name} must be an integer from ${min} to ${max}`)
|
|
9589
|
+
}
|
|
9590
|
+
return value
|
|
9591
|
+
}
|
|
9592
|
+
const positive = (name, value) => integer(name, value, 1);
|
|
9593
|
+
const nonNegative = (name, value) => integer(name, value, 0);
|
|
9594
|
+
const QUOTA_LIMITS = ['maxMessageBytes', 'fanout', 'msgPerSec', 'bytesPerSec', 'maxConnections'];
|
|
9595
|
+
|
|
9596
|
+
// This Server's quota profiles: the defaults with each given profile merged over its default
|
|
9597
|
+
// (a new name starts from no limits). Every limit is a positive integer or null (unlimited).
|
|
9598
|
+
function quotaProfiles(given) {
|
|
9599
|
+
if (given !== undefined && (given === null || typeof given !== 'object')) {
|
|
9600
|
+
throw new TypeError('quotas must be an object')
|
|
9601
|
+
}
|
|
9602
|
+
const profiles = {};
|
|
9603
|
+
for (const name of new Set([...Object.keys(serverOption.quotas), ...Object.keys(given ?? {})])) {
|
|
9604
|
+
const profile = given?.[name];
|
|
9605
|
+
if (profile !== undefined && (profile === null || typeof profile !== 'object')) {
|
|
9606
|
+
throw new TypeError(`quotas.${name} must be an object`)
|
|
9607
|
+
}
|
|
9608
|
+
for (const key of Object.keys(profile ?? {})) {
|
|
9609
|
+
if (!QUOTA_LIMITS.includes(key)) throw new TypeError(`unknown option quotas.${name}.${key}`)
|
|
9610
|
+
}
|
|
9611
|
+
const base = serverOption.quotas[name] ?? Object.fromEntries(QUOTA_LIMITS.map(key => [key, null]));
|
|
9612
|
+
profiles[name] = { ...base, ...profile };
|
|
9613
|
+
for (const key of QUOTA_LIMITS) {
|
|
9614
|
+
if (profiles[name][key] !== null) positive(`quotas.${name}.${key}`, profiles[name][key]);
|
|
9615
|
+
}
|
|
9616
|
+
}
|
|
9617
|
+
return profiles
|
|
9618
|
+
}
|
|
9619
|
+
function boolean(name, value) {
|
|
9620
|
+
if (typeof value !== 'boolean') throw new TypeError(`${name} must be a boolean`)
|
|
9621
|
+
return value
|
|
9622
|
+
}
|
|
9623
|
+
|
|
9624
|
+
// A nested option group: this Server's own copy of the serverOption defaults with its options
|
|
9625
|
+
// applied. Unknown keys are errors, so a typo does not silently do nothing.
|
|
9626
|
+
function group(name, given, checks) {
|
|
9627
|
+
if (given !== undefined && (given === null || typeof given !== 'object')) {
|
|
9628
|
+
throw new TypeError(`${name} must be an object`)
|
|
9629
|
+
}
|
|
9630
|
+
for (const key of Object.keys(given ?? {})) {
|
|
9631
|
+
if (!(key in checks)) throw new TypeError(`unknown option ${name}.${key}`)
|
|
9632
|
+
}
|
|
9633
|
+
const merged = { ...serverOption[name], ...given };
|
|
9634
|
+
for (const [key, check] of Object.entries(checks)) check(`${name}.${key}`, merged[key]);
|
|
9635
|
+
return merged
|
|
9636
|
+
}
|
|
9637
|
+
|
|
9638
|
+
function resolveLogStats(value) {
|
|
9639
|
+
if (value === 0 || value === false) return 0
|
|
9640
|
+
return integer('logStats', value, 1000, MAX_TIMER_MS)
|
|
9641
|
+
}
|
|
9642
|
+
|
|
9247
9643
|
class Server extends require$$0$3 {
|
|
9248
9644
|
|
|
9249
9645
|
/**
|
|
9250
9646
|
* @param {object} options Server configuration.
|
|
9251
9647
|
* options.localAuth: login without a key list, for local testing. 'idKey' (key = ID) or
|
|
9252
|
-
* { mode: 'idKey' | 'sharedKey', key,
|
|
9648
|
+
* { mode: 'idKey' | 'sharedKey', key, role, quota } (see LocalKeyProvider); the CID is the ID.
|
|
9253
9649
|
* Cannot be combined with authManager.
|
|
9650
|
+
* Every other setting is this Server's own: given here, else the serverOption default, which is
|
|
9651
|
+
* never modified. Nested groups (security, retain, quotas) are merged over their defaults;
|
|
9652
|
+
* unknown or removed names are errors.
|
|
9653
|
+
* options.heartbeatInterval: ms between liveness checks (default 50000).
|
|
9654
|
+
* options.heartbeatGrace: extra ms a peer has to answer before it is closed (default 5000).
|
|
9655
|
+
* options.trustProxy: when X-Forwarded-For/-Proto are used. 'private' (default) only from a
|
|
9656
|
+
* loopback/private peer, true always, false never, or N trusted proxy hops.
|
|
9657
|
+
* options.maxPayload: largest WebSocket message and CongSocket frame in bytes (default 32 MiB).
|
|
9658
|
+
* options.maxBufferedBytes: close a peer whose unsent data exceeds this (default 64 MiB).
|
|
9659
|
+
* options.membersOnly: drop signals from connections that are not authenticated.
|
|
9660
|
+
* options.logMessages: log each received message after decryption: type and tag, never the payload.
|
|
9661
|
+
* options.logStats: print a one-line summary every N ms (>= 1000; 0 = off); see stats().
|
|
9662
|
+
* options.security: { maxClockSkewMs, authChallengeMaxAgeMs, maxReplayEntries }.
|
|
9663
|
+
* options.retain: retained message limits, see serverOption.retain; adjustable later on server.retain.
|
|
9664
|
+
* options.quotas: named quota profiles { name: { maxMessageBytes, fanout, msgPerSec, bytesPerSec,
|
|
9665
|
+
* maxConnections } }, merged over serverOption.quotas; always enforced, null is unlimited.
|
|
9666
|
+
* Adjustable later on server.quotas. The client is told its maxMessageBytes.
|
|
9667
|
+
* options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
|
|
9668
|
+
* options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
|
|
9669
|
+
* manager's own policy without changing it, so an auth manager can be shared between servers.
|
|
9670
|
+
* A failed listen (e.g. EADDRINUSE) is emitted as 'error'.
|
|
9254
9671
|
* @param {any} [authManager] Optional authentication manager.
|
|
9255
9672
|
*/
|
|
9256
9673
|
constructor(options, authManager) {
|
|
@@ -9259,13 +9676,33 @@ class Server extends require$$0$3 {
|
|
|
9259
9676
|
if (authManager) throw new TypeError('localAuth cannot be combined with an authManager')
|
|
9260
9677
|
authManager = new BohoAuth(new LocalKeyProvider(options.localAuth));
|
|
9261
9678
|
}
|
|
9262
|
-
|
|
9263
|
-
|
|
9264
|
-
|
|
9265
|
-
|
|
9266
|
-
}
|
|
9267
|
-
|
|
9268
|
-
this.
|
|
9679
|
+
// Each Server resolves its settings once, here: serverOption only supplies the defaults and is
|
|
9680
|
+
// never written, so servers in one process do not affect each other.
|
|
9681
|
+
checkRemoved(options);
|
|
9682
|
+
this.security = Object.freeze(group('security', options.security,
|
|
9683
|
+
{ maxClockSkewMs: positive, authChallengeMaxAgeMs: positive, maxReplayEntries: positive }));
|
|
9684
|
+
// retain and quotas may be adjusted on a running server, e.g. server.quotas.basic.fanout = 50.
|
|
9685
|
+
this.retain = group('retain', options.retain, {
|
|
9686
|
+
enabled: boolean, limitSize: positive, limitCounter: positive, tagsPerOwner: positive,
|
|
9687
|
+
bytesPerOwner: positive, anonymousGraceMs: nonNegative, bytesPerConnection: positive, bytesTotal: positive });
|
|
9688
|
+
this.quotas = quotaProfiles(options.quotas);
|
|
9689
|
+
this.anonymousQuota = options.anonymousQuota ?? serverOption.anonymousQuota;
|
|
9690
|
+
if (!Object.hasOwn(this.quotas, this.anonymousQuota)) {
|
|
9691
|
+
throw new RangeError(`anonymousQuota must be one of the quotas: ${Object.keys(this.quotas).join(', ')}`)
|
|
9692
|
+
}
|
|
9693
|
+
this.heartbeatInterval = integer('heartbeatInterval',
|
|
9694
|
+
options.heartbeatInterval ?? serverOption.heartbeatInterval, 1, MAX_TIMER_MS);
|
|
9695
|
+
this.heartbeatGrace = integer('heartbeatGrace', options.heartbeatGrace ?? serverOption.heartbeatGrace, 0, MAX_TIMER_MS);
|
|
9696
|
+
this.maxPayload = positive('maxPayload', options.maxPayload ?? serverOption.maxPayload);
|
|
9697
|
+
this.maxBufferedBytes = positive('maxBufferedBytes', options.maxBufferedBytes ?? serverOption.maxBufferedBytes);
|
|
9698
|
+
this.logMessages = boolean('logMessages', options.logMessages ?? serverOption.logMessages);
|
|
9699
|
+
this.logStats = resolveLogStats(options.logStats ?? serverOption.logStats);
|
|
9700
|
+
this.trustProxy = options.trustProxy ?? serverOption.trustProxy;
|
|
9701
|
+
if (![true, false, 'private'].includes(this.trustProxy) &&
|
|
9702
|
+
!(Number.isSafeInteger(this.trustProxy) && this.trustProxy > 0)) {
|
|
9703
|
+
throw new RangeError("trustProxy must be true, false, 'private' or a positive integer");
|
|
9704
|
+
}
|
|
9705
|
+
this.membersOnly = boolean('membersOnly', options.membersOnly ?? serverOption.membersOnly);
|
|
9269
9706
|
this.serviceNames = new Set();
|
|
9270
9707
|
this.services = new Map(); // name -> service module (for lifecycle hooks)
|
|
9271
9708
|
// Stays null for a CongSocket-only server, so close() does not wait on a WebSocket server.
|
|
@@ -9273,38 +9710,13 @@ class Server extends require$$0$3 {
|
|
|
9273
9710
|
this.port = null;
|
|
9274
9711
|
this.congPort = null;
|
|
9275
9712
|
|
|
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.
|
|
9713
|
+
// Read by the auth manager for this server's connections; the auth manager itself is not
|
|
9714
|
+
// changed, since it may be shared. null: the auth manager's own policy.
|
|
9715
|
+
this.duplicateLogin = null;
|
|
9301
9716
|
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;
|
|
9717
|
+
this.duplicateLogin = validateDuplicateLogin(options.duplicateLogin);
|
|
9718
|
+
if (authManager && !('duplicateLogin' in authManager)) {
|
|
9719
|
+
throw new TypeError('duplicateLogin: the auth manager does not support this option')
|
|
9308
9720
|
}
|
|
9309
9721
|
}
|
|
9310
9722
|
|
|
@@ -9345,9 +9757,9 @@ class Server extends require$$0$3 {
|
|
|
9345
9757
|
startWSServer() {
|
|
9346
9758
|
// console.log('optoins', options )
|
|
9347
9759
|
if (this.port || this.port == 0) {
|
|
9348
|
-
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath });
|
|
9760
|
+
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath, maxPayload: this.maxPayload });
|
|
9349
9761
|
} else if (this.httpServer ) {
|
|
9350
|
-
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath });
|
|
9762
|
+
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath, maxPayload: this.maxPayload });
|
|
9351
9763
|
} else {
|
|
9352
9764
|
throw new TypeError(
|
|
9353
9765
|
'One and only one of the "port", "httpServer"' +
|
|
@@ -9365,12 +9777,7 @@ class Server extends require$$0$3 {
|
|
|
9365
9777
|
});
|
|
9366
9778
|
|
|
9367
9779
|
// 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
|
-
});
|
|
9780
|
+
this.wss.on('error', (err) => this.onListenerError('ws', err));
|
|
9374
9781
|
|
|
9375
9782
|
this.wss.on('close', () => {
|
|
9376
9783
|
// console.log('### WS server is closed.')
|
|
@@ -9390,12 +9797,8 @@ class Server extends require$$0$3 {
|
|
|
9390
9797
|
socket.setNoDelay(true);
|
|
9391
9798
|
this.manager.addRemote(socket);
|
|
9392
9799
|
})
|
|
9393
|
-
.on('error', (err) =>
|
|
9394
|
-
|
|
9395
|
-
if (err.code == 'EADDRINUSE') {
|
|
9396
|
-
process.exit();
|
|
9397
|
-
}
|
|
9398
|
-
}).on('close', () => {
|
|
9800
|
+
.on('error', (err) => this.onListenerError('cong', err))
|
|
9801
|
+
.on('close', () => {
|
|
9399
9802
|
// console.log('### congsocket server is closed.')
|
|
9400
9803
|
}).listen(this.congPort, () => {
|
|
9401
9804
|
this.congPort = this.congServer.address().port;
|
|
@@ -9407,6 +9810,26 @@ class Server extends require$$0$3 {
|
|
|
9407
9810
|
});
|
|
9408
9811
|
}
|
|
9409
9812
|
|
|
9813
|
+
// A failed listen (e.g. EADDRINUSE) is the application's to handle: emitted as 'error',
|
|
9814
|
+
// which, like any EventEmitter, throws when nothing listens. Other errors are logged.
|
|
9815
|
+
onListenerError(name, err) {
|
|
9816
|
+
console.error(`### ${name} server error:`, err.message);
|
|
9817
|
+
if (err.syscall === 'listen') this.emit('error', err);
|
|
9818
|
+
}
|
|
9819
|
+
|
|
9820
|
+
/**
|
|
9821
|
+
* Current server state, for monitoring. counters are cumulative since the server started
|
|
9822
|
+
* (rates are the reader's to compute from two snapshots). Enumerates connections once.
|
|
9823
|
+
* @returns {{ at: number, connections: { total: number, authenticated: number, anonymous: number,
|
|
9824
|
+
* websocket: number, tcp: number }, channels: number, retained: { channel: number, bytes: number },
|
|
9825
|
+
* counters: { rxMessages: number, rxBytes: number, txMessages: number, txBytes: number,
|
|
9826
|
+
* publishes: number, deliveryAttempts: number, quotaExcluded: number, peerRxLimitSkipped: number },
|
|
9827
|
+
* memory: { rss: number, heapUsed: number } }}
|
|
9828
|
+
*/
|
|
9829
|
+
stats() {
|
|
9830
|
+
return this.manager.metrics.snapshot()
|
|
9831
|
+
}
|
|
9832
|
+
|
|
9410
9833
|
/**
|
|
9411
9834
|
* RPC service register.
|
|
9412
9835
|
* service: service_name <string>
|
|
@@ -9560,9 +9983,10 @@ class FileKeyProvider {
|
|
|
9560
9983
|
return Array.from(this.AUTH.keys())
|
|
9561
9984
|
}
|
|
9562
9985
|
|
|
9563
|
-
|
|
9986
|
+
// Each item: [id, key, cid, role?, quota?]; see StringKeyProvider.
|
|
9987
|
+
addAuth(id, keyStr, cid, role, quota) {
|
|
9564
9988
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9565
|
-
this.AUTH.set(id, { key: Base64hashKey, cid
|
|
9989
|
+
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
9566
9990
|
}
|
|
9567
9991
|
}
|
|
9568
9992
|
|
|
@@ -9597,9 +10021,13 @@ class RedisKeyProvider {
|
|
|
9597
10021
|
}
|
|
9598
10022
|
|
|
9599
10023
|
// add device auth info
|
|
9600
|
-
|
|
10024
|
+
// role and quota are optional (see StringKeyProvider); an omitted one is not stored.
|
|
10025
|
+
async addAuth(id, keyStr, cid = '', role, quota) {
|
|
9601
10026
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9602
|
-
|
|
10027
|
+
const fields = { 'key': Base64hashKey, 'cid': cid };
|
|
10028
|
+
if (role) fields.role = role;
|
|
10029
|
+
if (quota) fields.quota = quota;
|
|
10030
|
+
return this.redis.hSet(DEVICE_PREFIX + id, fields)
|
|
9603
10031
|
}
|
|
9604
10032
|
|
|
9605
10033
|
//sudoService call
|
|
@@ -9614,43 +10042,39 @@ class RedisKeyProvider {
|
|
|
9614
10042
|
|
|
9615
10043
|
/**
|
|
9616
10044
|
* StringKeyProvider.js
|
|
9617
|
-
*
|
|
9618
|
-
* authInfo <String
|
|
9619
|
-
* id:
|
|
9620
|
-
* key:
|
|
9621
|
-
* cid:
|
|
9622
|
-
*
|
|
9623
|
-
*
|
|
9624
|
-
*
|
|
9625
|
-
* example => authInfo = 'id1.key1.cid1.
|
|
10045
|
+
*
|
|
10046
|
+
* authInfo <String>: entries 'id.key.cid[.role[.quota]]' separated by ','.
|
|
10047
|
+
* id: max 8 chars
|
|
10048
|
+
* key: ~44 base64 chars recommended
|
|
10049
|
+
* cid: client ID
|
|
10050
|
+
* role: 'device' (default) | 'service' | 'admin'
|
|
10051
|
+
* quota: a Server quotas profile name (default: BohoAuth resolveQuota)
|
|
10052
|
+
*
|
|
10053
|
+
* example => authInfo = 'id1.key1.cid1.admin,id2.key2.cid2.device.pro'
|
|
9626
10054
|
*/
|
|
9627
10055
|
|
|
9628
10056
|
|
|
10057
|
+
const ACCOUNT_ROLES = ROLES.filter(role => role !== 'anonymous');
|
|
10058
|
+
|
|
10059
|
+
/** Parses one 'id.key.cid[.role[.quota]]' entry; a malformed one is a TypeError (naming only the id). */
|
|
10060
|
+
function parseKeyEntry(entry) {
|
|
10061
|
+
const [id, key, cid, role, quota, ...rest] = entry.split('.');
|
|
10062
|
+
if (!id || !key || !cid || rest.length > 0 || (role && !ACCOUNT_ROLES.includes(role))) {
|
|
10063
|
+
throw new TypeError(`invalid key entry 'id.key.cid[.role[.quota]]' for id: ${id ?? ''}`)
|
|
10064
|
+
}
|
|
10065
|
+
return { id, key, cid, role: role || undefined, quota: quota || undefined }
|
|
10066
|
+
}
|
|
10067
|
+
|
|
9629
10068
|
class StringKeyProvider {
|
|
9630
10069
|
constructor(authInfo) {
|
|
9631
|
-
|
|
9632
10070
|
if (!authInfo) {
|
|
9633
10071
|
throw TypeError("StringKeyProvider constructor() missing authInfo.")
|
|
9634
10072
|
}
|
|
9635
|
-
|
|
9636
|
-
let id_keys = authInfo.split(',');
|
|
9637
|
-
|
|
9638
10073
|
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.")
|
|
10074
|
+
for (const entry of authInfo.split(',')) {
|
|
10075
|
+
const { id, key, cid, role, quota } = parseKeyEntry(entry);
|
|
10076
|
+
this.addAuth(id, key, cid, role, quota);
|
|
9652
10077
|
}
|
|
9653
|
-
|
|
9654
10078
|
}
|
|
9655
10079
|
|
|
9656
10080
|
async getAuth(id) {
|
|
@@ -9660,17 +10084,17 @@ class StringKeyProvider {
|
|
|
9660
10084
|
return Array.from(this.AUTH.keys())
|
|
9661
10085
|
}
|
|
9662
10086
|
|
|
9663
|
-
addAuth(id, keyStr, cid,
|
|
10087
|
+
addAuth(id, keyStr, cid, role, quota) {
|
|
9664
10088
|
let Base64hashKey = Buffer.from(it.sha256.hash(keyStr)).toString('base64');
|
|
9665
|
-
this.AUTH.set(id, { key: Base64hashKey, cid
|
|
10089
|
+
this.AUTH.set(id, { key: Base64hashKey, cid, ...(role && { role }), ...(quota && { quota }) });
|
|
9666
10090
|
}
|
|
9667
10091
|
}
|
|
9668
10092
|
|
|
9669
10093
|
const commands$1 = ['echo', 'date', 'unixtime'];
|
|
9670
10094
|
|
|
9671
|
-
|
|
10095
|
+
// Open to every connection.
|
|
9672
10096
|
function checkPermission$1(remote) {
|
|
9673
|
-
return
|
|
10097
|
+
return true;
|
|
9674
10098
|
}
|
|
9675
10099
|
|
|
9676
10100
|
/**
|
|
@@ -9717,10 +10141,9 @@ const commands = [
|
|
|
9717
10141
|
'adddevice', 'getdevice', 'deldevice'
|
|
9718
10142
|
];
|
|
9719
10143
|
|
|
9720
|
-
|
|
9721
|
-
// Only a Boho-authenticated device may use sudo; a raised level alone is not authentication.
|
|
10144
|
+
// Only a connection authenticated with role 'admin'.
|
|
9722
10145
|
function checkPermission(remote) {
|
|
9723
|
-
return remote
|
|
10146
|
+
return hasRole(remote, 'admin');
|
|
9724
10147
|
}
|
|
9725
10148
|
|
|
9726
10149
|
async function call(remote, req) {
|
|
@@ -9747,13 +10170,11 @@ async function call(remote, req) {
|
|
|
9747
10170
|
if (req.$[0]) result = remote.manager.closeRemoteByCId(req.$[0]);
|
|
9748
10171
|
|
|
9749
10172
|
} else if (cmd == 'addauth' || cmd == 'adddevice') {
|
|
9750
|
-
|
|
10173
|
+
// did, key, cid[, role[, quota]]
|
|
10174
|
+
if (remote.manager.authManager && req.$.length >= 3 && req.$.length <= 5) {
|
|
9751
10175
|
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);
|
|
10176
|
+
const [did, dkey, cid, role, quota] = req.$;
|
|
10177
|
+
result = await remote.manager.authManager.addAuth(did, dkey, cid, role, quota);
|
|
9757
10178
|
}
|
|
9758
10179
|
|
|
9759
10180
|
}
|
|
@@ -9808,7 +10229,6 @@ var sudoService = /*#__PURE__*/Object.freeze({
|
|
|
9808
10229
|
*
|
|
9809
10230
|
*/
|
|
9810
10231
|
|
|
9811
|
-
const MIN_LEVEL = 200;
|
|
9812
10232
|
const COMMANDS = [
|
|
9813
10233
|
'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
|
|
9814
10234
|
'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
|
|
@@ -9821,22 +10241,21 @@ const COMMANDS = [
|
|
|
9821
10241
|
class RedisService {
|
|
9822
10242
|
/**
|
|
9823
10243
|
* @param {object} redisClient
|
|
9824
|
-
* @param {
|
|
9825
|
-
*
|
|
10244
|
+
* @param {'anonymous' | 'device' | 'service' | 'admin'} [minRole='service'] lowest role allowed;
|
|
10245
|
+
* 'anonymous' allows every connection.
|
|
9826
10246
|
*/
|
|
9827
|
-
constructor(redisClient,
|
|
10247
|
+
constructor(redisClient, minRole = 'service') {
|
|
9828
10248
|
if (!redisClient) {
|
|
9829
10249
|
throw new Error("RedisService constructor: no redisClient")
|
|
9830
10250
|
}
|
|
10251
|
+
if (!ROLES.includes(minRole)) throw new RangeError(`minRole must be one of: ${ROLES.join(', ')}`)
|
|
9831
10252
|
this.redisClient = redisClient;
|
|
9832
|
-
this.
|
|
9833
|
-
this.requireAuth = options.requireAuth !== false;
|
|
10253
|
+
this.minRole = minRole;
|
|
9834
10254
|
this.commands = COMMANDS;
|
|
9835
10255
|
}
|
|
9836
10256
|
|
|
9837
10257
|
checkPermission(remote, req) {
|
|
9838
|
-
|
|
9839
|
-
return (remote.level >= this.minLevel) ? true : false;
|
|
10258
|
+
return hasRole(remote, this.minRole);
|
|
9840
10259
|
}
|
|
9841
10260
|
|
|
9842
10261
|
async call(remote, req) {
|
|
@@ -9858,4 +10277,4 @@ class RedisService {
|
|
|
9858
10277
|
|
|
9859
10278
|
const version = pkg.version;
|
|
9860
10279
|
|
|
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 };
|
|
10280
|
+
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 };
|