iosignal 7.1.0 → 8.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 +64 -191
- package/README.md +68 -226
- package/dist/browser/esm/io.d.ts +36 -19
- package/dist/browser/esm/io.js +3 -3
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +3 -3
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +467 -295
- package/dist/node/iosignal.d.cts +73 -24
- package/dist/node/iosignal.d.ts +73 -24
- package/dist/node/iosignal.js +467 -295
- package/dist/types/client/IOCore.d.ts +35 -18
- package/dist/types/client/browser/IOWebSocket.d.ts +1 -1
- package/package.json +1 -1
package/dist/node/iosignal.cjs
CHANGED
|
@@ -17,7 +17,7 @@ var fs = require('fs');
|
|
|
17
17
|
var process$1 = require('process');
|
|
18
18
|
var path = require('path');
|
|
19
19
|
|
|
20
|
-
var version$1 = "
|
|
20
|
+
var version$1 = "8.0.0";
|
|
21
21
|
var pkg = {
|
|
22
22
|
version: version$1};
|
|
23
23
|
|
|
@@ -785,6 +785,22 @@ function encodeTag(tag, allowEmpty = true) {
|
|
|
785
785
|
return encoded
|
|
786
786
|
}
|
|
787
787
|
|
|
788
|
+
// Direct-receive tags are local event names, never server subscriptions.
|
|
789
|
+
function encodeSubscriptionTags(tag) {
|
|
790
|
+
const encoded = encodeTag(tag);
|
|
791
|
+
if (tag.split(',').some(part => part.startsWith('@'))) {
|
|
792
|
+
throw TypeError("direct signal tags need no subscription; use on/listen/link and off/unlink")
|
|
793
|
+
}
|
|
794
|
+
return encoded
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function sendSubscription(io, tag) {
|
|
798
|
+
const encoded = encodeSubscriptionTags(tag);
|
|
799
|
+
io.send_enc_mode(Buffer$1.concat([
|
|
800
|
+
$$1.NB('8', IOMsg.SUBSCRIBE), $$1.NB('8', encoded.byteLength), encoded
|
|
801
|
+
]));
|
|
802
|
+
}
|
|
803
|
+
|
|
788
804
|
function byteToUrl(buffer) {
|
|
789
805
|
//ipv4(4bytes) , port(2bytes)
|
|
790
806
|
if (buffer.byteLength != 6) return
|
|
@@ -943,6 +959,12 @@ class IOCore extends EventEmitter {
|
|
|
943
959
|
* @type {Map<string, Set<string>>}
|
|
944
960
|
*/
|
|
945
961
|
this.linkMap = new Map();
|
|
962
|
+
/** @private @type {Map<string, Map<string, Set<Function>>>} */
|
|
963
|
+
this._linkHandlers = new Map();
|
|
964
|
+
/** @private @type {Set<string>} */
|
|
965
|
+
this._listenTags = new Set();
|
|
966
|
+
/** @private @type {Set<string>} */
|
|
967
|
+
this._manualSubscriptions = new Set();
|
|
946
968
|
|
|
947
969
|
/**
|
|
948
970
|
* Indicates if auto-reconnect is enabled.
|
|
@@ -1008,6 +1030,7 @@ class IOCore extends EventEmitter {
|
|
|
1008
1030
|
reject(error);
|
|
1009
1031
|
}
|
|
1010
1032
|
this.promiseMap.clear();
|
|
1033
|
+
this._manualSubscriptions.clear();
|
|
1011
1034
|
this.cid = '';
|
|
1012
1035
|
if (this.boho) this.boho.isAuthorized = false;
|
|
1013
1036
|
if (this.state !== STATE.STOP && this.stateChange('closed')) {
|
|
@@ -1028,7 +1051,9 @@ class IOCore extends EventEmitter {
|
|
|
1028
1051
|
|
|
1029
1052
|
/**
|
|
1030
1053
|
* Permanently destroys the instance, cleaning up all resources.
|
|
1031
|
-
* The instance will not be usable after this.
|
|
1054
|
+
* The instance will not be usable after this. Later signal()/publish()/subscribe()
|
|
1055
|
+
* calls are silently dropped, the same as sends while disconnected, and call()
|
|
1056
|
+
* rejects with code 'CONNECTION_CLOSED'.
|
|
1032
1057
|
*/
|
|
1033
1058
|
destroy() {
|
|
1034
1059
|
this.stop();
|
|
@@ -1036,6 +1061,9 @@ class IOCore extends EventEmitter {
|
|
|
1036
1061
|
|
|
1037
1062
|
this.channels.clear();
|
|
1038
1063
|
this.linkMap.clear();
|
|
1064
|
+
this._linkHandlers.clear();
|
|
1065
|
+
this._listenTags.clear();
|
|
1066
|
+
this._manualSubscriptions.clear();
|
|
1039
1067
|
|
|
1040
1068
|
// Help GC
|
|
1041
1069
|
this.boho = null;
|
|
@@ -1329,8 +1357,10 @@ class IOCore extends EventEmitter {
|
|
|
1329
1357
|
switch (payloadType) {
|
|
1330
1358
|
|
|
1331
1359
|
case PAYLOAD_TYPE.EMPTY:
|
|
1332
|
-
if (tag.indexOf('@') === 0)
|
|
1333
|
-
|
|
1360
|
+
if (tag.indexOf('@') === 0) {
|
|
1361
|
+
this.emit('@', tag);
|
|
1362
|
+
if (tag !== '@') this.emit(tag, tag);
|
|
1363
|
+
} else {
|
|
1334
1364
|
this.emit(tag, tag);
|
|
1335
1365
|
this.emit('message', tag);
|
|
1336
1366
|
}
|
|
@@ -1344,16 +1374,20 @@ class IOCore extends EventEmitter {
|
|
|
1344
1374
|
payloadStringWithoutNull = payloadBuffer.subarray(0, payloadBuffer.byteLength - 1);
|
|
1345
1375
|
}
|
|
1346
1376
|
let oneString = decoder$4.decode(payloadStringWithoutNull);
|
|
1347
|
-
if (tag.indexOf('@') === 0)
|
|
1348
|
-
|
|
1377
|
+
if (tag.indexOf('@') === 0) {
|
|
1378
|
+
this.emit('@', tag, oneString);
|
|
1379
|
+
if (tag !== '@') this.emit(tag, tag, oneString);
|
|
1380
|
+
} else {
|
|
1349
1381
|
this.emit(tag, tag, oneString);
|
|
1350
1382
|
this.emit('message', tag, oneString);
|
|
1351
1383
|
}
|
|
1352
1384
|
break;
|
|
1353
1385
|
|
|
1354
1386
|
case PAYLOAD_TYPE.BINARY:
|
|
1355
|
-
if (tag.indexOf('@') === 0)
|
|
1356
|
-
|
|
1387
|
+
if (tag.indexOf('@') === 0) {
|
|
1388
|
+
this.emit('@', tag, payloadBuffer);
|
|
1389
|
+
if (tag !== '@') this.emit(tag, tag, payloadBuffer);
|
|
1390
|
+
} else {
|
|
1357
1391
|
this.emit(tag, tag, payloadBuffer);
|
|
1358
1392
|
this.emit('message', tag, payloadBuffer);
|
|
1359
1393
|
}
|
|
@@ -1362,8 +1396,10 @@ class IOCore extends EventEmitter {
|
|
|
1362
1396
|
case PAYLOAD_TYPE.OBJECT:
|
|
1363
1397
|
let oneObjectBuffer = decoder$4.decode(payloadBuffer);
|
|
1364
1398
|
let oneJSONObject = JSON.parse(oneObjectBuffer);
|
|
1365
|
-
if (tag.indexOf('@') === 0)
|
|
1366
|
-
|
|
1399
|
+
if (tag.indexOf('@') === 0) {
|
|
1400
|
+
this.emit('@', tag, oneJSONObject);
|
|
1401
|
+
if (tag !== '@') this.emit(tag, tag, oneJSONObject);
|
|
1402
|
+
} else {
|
|
1367
1403
|
this.emit(tag, tag, oneJSONObject);
|
|
1368
1404
|
this.emit('message', tag, oneJSONObject);
|
|
1369
1405
|
}
|
|
@@ -1372,8 +1408,10 @@ class IOCore extends EventEmitter {
|
|
|
1372
1408
|
case PAYLOAD_TYPE.MJSON:
|
|
1373
1409
|
let mjsonBuffer = decoder$4.decode(payloadBuffer);
|
|
1374
1410
|
let mjson = JSON.parse(mjsonBuffer);
|
|
1375
|
-
if (tag.indexOf('@') === 0)
|
|
1376
|
-
|
|
1411
|
+
if (tag.indexOf('@') === 0) {
|
|
1412
|
+
this.emit('@', tag, ...mjson);
|
|
1413
|
+
if (tag !== '@') this.emit(tag, tag, ...mjson);
|
|
1414
|
+
} else {
|
|
1377
1415
|
this.emit(tag, tag, ...mjson);
|
|
1378
1416
|
this.emit('message', tag, ...mjson);
|
|
1379
1417
|
}
|
|
@@ -1381,8 +1419,10 @@ class IOCore extends EventEmitter {
|
|
|
1381
1419
|
|
|
1382
1420
|
case PAYLOAD_TYPE.MBA:
|
|
1383
1421
|
let mbaObject = $$1.unpack(payloadBuffer);
|
|
1384
|
-
if (tag.indexOf('@') === 0)
|
|
1385
|
-
|
|
1422
|
+
if (tag.indexOf('@') === 0) {
|
|
1423
|
+
this.emit('@', tag, ...mbaObject.args);
|
|
1424
|
+
if (tag !== '@') this.emit(tag, tag, ...mbaObject.args);
|
|
1425
|
+
} else {
|
|
1386
1426
|
this.emit(tag, tag, ...mbaObject.args);
|
|
1387
1427
|
this.emit('message', tag, ...mbaObject.args);
|
|
1388
1428
|
}
|
|
@@ -1513,7 +1553,7 @@ class IOCore extends EventEmitter {
|
|
|
1513
1553
|
getEncryptionMode() {
|
|
1514
1554
|
if (this.encMode === ENC_MODE.YES ||
|
|
1515
1555
|
this.encMode === ENC_MODE.AUTO &&
|
|
1516
|
-
!this.TLS && this.boho
|
|
1556
|
+
!this.TLS && this.boho?.isAuthorized
|
|
1517
1557
|
) {
|
|
1518
1558
|
return true;
|
|
1519
1559
|
} else {
|
|
@@ -1523,10 +1563,12 @@ class IOCore extends EventEmitter {
|
|
|
1523
1563
|
|
|
1524
1564
|
/**
|
|
1525
1565
|
* Sends data with encryption based on the encryption mode.
|
|
1566
|
+
* Like an unconnected socket, a destroyed instance silently drops the data.
|
|
1526
1567
|
* @param {Buffer} data - The data buffer to send.
|
|
1527
1568
|
* @param {boolean} [useEncryption] - Optional. Force encryption or not. If undefined, uses default policy.
|
|
1528
1569
|
*/
|
|
1529
1570
|
send_enc_mode(data, useEncryption) {
|
|
1571
|
+
if (!this.boho) return; // destroyed
|
|
1530
1572
|
|
|
1531
1573
|
// use default policy.
|
|
1532
1574
|
if (useEncryption === undefined) {
|
|
@@ -1644,7 +1686,7 @@ class IOCore extends EventEmitter {
|
|
|
1644
1686
|
|
|
1645
1687
|
const tagEncoded = encodeTag(tag);
|
|
1646
1688
|
if (tag.startsWith('@') && this.cid) encodeTag(this.cid + tag);
|
|
1647
|
-
if( !this.boho
|
|
1689
|
+
if( !this.boho?.isAuthorized ) return;
|
|
1648
1690
|
let dataPack = $$1.B8(data);
|
|
1649
1691
|
|
|
1650
1692
|
//encrypt payload area with key
|
|
@@ -1701,6 +1743,12 @@ class IOCore extends EventEmitter {
|
|
|
1701
1743
|
call(target, topic, ...args) {
|
|
1702
1744
|
if (!target || !topic)
|
|
1703
1745
|
return Promise.reject(new Error('request need target and topic)'))
|
|
1746
|
+
if (!this.boho) {
|
|
1747
|
+
// destroyed: reject like close() does for pending calls instead of waiting for a timeout.
|
|
1748
|
+
const error = new Error('Connection closed');
|
|
1749
|
+
error.code = 'CONNECTION_CLOSED';
|
|
1750
|
+
return Promise.reject(error);
|
|
1751
|
+
}
|
|
1704
1752
|
this.mid = (this.mid + 1) & 0xffff;
|
|
1705
1753
|
let sigPack;
|
|
1706
1754
|
if (args.length > 0) {
|
|
@@ -1727,14 +1775,11 @@ class IOCore extends EventEmitter {
|
|
|
1727
1775
|
/**
|
|
1728
1776
|
* Subscribes to a channel or channels.
|
|
1729
1777
|
* @param {string} tag - The tag(s) of the channel(s) to subscribe to (comma-separated).
|
|
1730
|
-
* @throws {TypeError} If tag is
|
|
1778
|
+
* @throws {TypeError} If tag is invalid, exceeds the length limit, or contains a direct-receive subscription.
|
|
1731
1779
|
*/
|
|
1732
1780
|
subscribe(tag) {
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
$$1.NB('8', IOMsg.SUBSCRIBE),
|
|
1736
|
-
$$1.NB('8', tagEncoded.byteLength),
|
|
1737
|
-
tagEncoded]));
|
|
1781
|
+
sendSubscription(this, tag);
|
|
1782
|
+
for (const part of tag.split(',')) this._manualSubscriptions.add(part);
|
|
1738
1783
|
}
|
|
1739
1784
|
|
|
1740
1785
|
|
|
@@ -1747,7 +1792,7 @@ class IOCore extends EventEmitter {
|
|
|
1747
1792
|
// Validate the entire list first, then split only at tag boundaries.
|
|
1748
1793
|
// Preserve comma-separated entries accepted by existing registration APIs.
|
|
1749
1794
|
const tags = Array.from(this.channels).join(',').split(',');
|
|
1750
|
-
const sizes = tags.map(tag =>
|
|
1795
|
+
const sizes = tags.map(tag => encodeSubscriptionTags(tag).byteLength);
|
|
1751
1796
|
const batches = [];
|
|
1752
1797
|
let batch = [], bytes = 0;
|
|
1753
1798
|
tags.forEach((tag, i) => {
|
|
@@ -1760,23 +1805,27 @@ class IOCore extends EventEmitter {
|
|
|
1760
1805
|
batch.push(tag);
|
|
1761
1806
|
});
|
|
1762
1807
|
if (batch.length) batches.push(batch.join(','));
|
|
1763
|
-
batches.forEach(tag => this
|
|
1808
|
+
batches.forEach(tag => sendSubscription(this, tag));
|
|
1764
1809
|
}
|
|
1765
1810
|
|
|
1766
1811
|
/**
|
|
1767
1812
|
* Unsubscribes from a channel or channels.
|
|
1768
1813
|
* @param {string} [tag=""] - The tag(s) of the channel(s) to unsubscribe from (comma-separated). If empty, unsubscribes from all.
|
|
1769
|
-
* @throws {TypeError} If tag is
|
|
1814
|
+
* @throws {TypeError} If tag is invalid, exceeds the length limit, or contains a direct-receive subscription.
|
|
1770
1815
|
*/
|
|
1771
1816
|
unsubscribe(tag = "") {
|
|
1772
|
-
const tagEncoded =
|
|
1817
|
+
const tagEncoded = encodeSubscriptionTags(tag);
|
|
1773
1818
|
|
|
1774
1819
|
if (tag == "") { // blank tag means unsubscribe all
|
|
1775
1820
|
this.channels.clear();
|
|
1821
|
+
this._listenTags.clear();
|
|
1822
|
+
this._manualSubscriptions.clear();
|
|
1776
1823
|
} else {
|
|
1777
1824
|
let tagList = tag.split(',');
|
|
1778
1825
|
tagList.forEach(tag => {
|
|
1779
1826
|
this.channels.delete(tag);
|
|
1827
|
+
this._listenTags.delete(tag);
|
|
1828
|
+
this._manualSubscriptions.delete(tag);
|
|
1780
1829
|
});
|
|
1781
1830
|
}
|
|
1782
1831
|
|
|
@@ -1790,12 +1839,17 @@ class IOCore extends EventEmitter {
|
|
|
1790
1839
|
|
|
1791
1840
|
/**
|
|
1792
1841
|
* Convenience API for simple clients (for example, CLI tools): register a
|
|
1793
|
-
* tag handler once and remember its subscription in channels.
|
|
1794
|
-
* connection readiness; the CID-ready flow subscribes on initial connection
|
|
1842
|
+
* tag handler once and remember its subscription in channels. For subscription
|
|
1843
|
+
* tags, register before connection readiness; the CID-ready flow subscribes on initial connection
|
|
1795
1844
|
* and again after reconnect, without application-level ready/subscribe code.
|
|
1796
1845
|
* This does not send a subscription immediately, even if already ready.
|
|
1797
1846
|
* For precise subscription/send ordering or dynamic subscriptions, use
|
|
1798
|
-
* on() with subscribe() in a ready handler instead.
|
|
1847
|
+
* on() with subscribe() in a ready handler instead.
|
|
1848
|
+
* Direct signals need no subscription: use on/listen('@') for all direct
|
|
1849
|
+
* signals, or on/listen('@topic') for an exact topic. Direct handlers can be
|
|
1850
|
+
* registered before or after readiness, before the message arrives.
|
|
1851
|
+
* Dispatch is synchronous: '@' first, then '@topic' when tag is not '@'.
|
|
1852
|
+
* Returning false does not cancel dispatch; a thrown error interrupts it.
|
|
1799
1853
|
* @param {string} tag - The tag to listen on.
|
|
1800
1854
|
* @param {Function} handler - The callback function to handle the signal.
|
|
1801
1855
|
* @throws {TypeError} If tag is not a string, handler is not a function, or tag length is invalid.
|
|
@@ -1806,7 +1860,9 @@ class IOCore extends EventEmitter {
|
|
|
1806
1860
|
if (typeof handler !== 'function') throw TypeError('handler is not a function.')
|
|
1807
1861
|
|
|
1808
1862
|
if (tag.indexOf('@') !== 0) {
|
|
1863
|
+
encodeSubscriptionTags(tag);
|
|
1809
1864
|
this.channels.add(tag);
|
|
1865
|
+
this._listenTags.add(tag);
|
|
1810
1866
|
}
|
|
1811
1867
|
this.on(tag, handler);
|
|
1812
1868
|
// Subscribe from the CID-ready flow, initially and after reconnect.
|
|
@@ -1817,81 +1873,82 @@ class IOCore extends EventEmitter {
|
|
|
1817
1873
|
|
|
1818
1874
|
|
|
1819
1875
|
/**
|
|
1820
|
-
*
|
|
1821
|
-
* @
|
|
1822
|
-
*
|
|
1823
|
-
* @param {
|
|
1824
|
-
* @
|
|
1876
|
+
* Associates handlers with a local component for scoped teardown.
|
|
1877
|
+
* Direct tags (@ or @topic) only register local handlers. Other tags also
|
|
1878
|
+
* subscribe now and are remembered for reconnection.
|
|
1879
|
+
* @param {string} to - The local component identifier, not a server target.
|
|
1880
|
+
* @param {string} tag - The exact event tag.
|
|
1881
|
+
* @param {Function} handler - The callback receiving (tag, ...args).
|
|
1882
|
+
* @throws {TypeError} If the arguments or subscription tags are invalid.
|
|
1825
1883
|
*/
|
|
1826
1884
|
link(to, tag, handler) {
|
|
1827
1885
|
if (typeof to !== 'string') throw TypeError('to(local link target) is not a string.')
|
|
1828
|
-
if (typeof tag !== 'string') throw TypeError('tag is not a string.')
|
|
1829
1886
|
encodeTag(tag, false);
|
|
1830
1887
|
if (typeof handler !== 'function') throw TypeError('handler is not a function.')
|
|
1831
|
-
|
|
1832
|
-
if (
|
|
1888
|
+
const direct = tag.startsWith('@');
|
|
1889
|
+
if (!direct) encodeSubscriptionTags(tag);
|
|
1890
|
+
|
|
1891
|
+
let tags = this._linkHandlers.get(to);
|
|
1892
|
+
if (!tags) this._linkHandlers.set(to, tags = new Map());
|
|
1893
|
+
let handlers = tags.get(tag);
|
|
1894
|
+
if (!handlers) tags.set(tag, handlers = new Set());
|
|
1895
|
+
// Each registration owns its wrapper, even if components share a callback.
|
|
1896
|
+
const linkedHandler = (...args) => handler.apply(this, args);
|
|
1897
|
+
handlers.add(linkedHandler);
|
|
1898
|
+
let linkSet = this.linkMap.get(to);
|
|
1899
|
+
if (!linkSet) this.linkMap.set(to, linkSet = new Set());
|
|
1900
|
+
linkSet.add(tag);
|
|
1901
|
+
this.on(tag, linkedHandler);
|
|
1902
|
+
if (!direct) {
|
|
1833
1903
|
this.channels.add(tag);
|
|
1904
|
+
sendSubscription(this, tag);
|
|
1834
1905
|
}
|
|
1835
|
-
|
|
1836
|
-
let linkSet;
|
|
1837
|
-
if (this.linkMap.has(to)) {
|
|
1838
|
-
linkSet = this.linkMap.get(to);
|
|
1839
|
-
} else {
|
|
1840
|
-
linkSet = new Set();
|
|
1841
|
-
}
|
|
1842
|
-
|
|
1843
|
-
linkSet.add(tag);
|
|
1844
|
-
this.linkMap.set(to, linkSet);
|
|
1845
|
-
this.on(tag, handler);
|
|
1846
|
-
this.subscribe(tag);
|
|
1847
|
-
|
|
1848
1906
|
}
|
|
1849
1907
|
|
|
1850
|
-
|
|
1851
1908
|
/**
|
|
1852
|
-
*
|
|
1853
|
-
*
|
|
1854
|
-
* @param {string}
|
|
1855
|
-
* @
|
|
1909
|
+
* Removes only one local component's handlers for a tag. Direct tags never
|
|
1910
|
+
* send an unsubscribe. Shared subscriptions and explicit subscriptions remain.
|
|
1911
|
+
* @param {string} to - The local component identifier.
|
|
1912
|
+
* @param {string} tag - The exact linked tag.
|
|
1913
|
+
* @throws {TypeError} If the arguments are invalid.
|
|
1856
1914
|
*/
|
|
1857
1915
|
unlink(to, tag) {
|
|
1858
1916
|
if (typeof to !== 'string') throw TypeError('to(local link target) is not a string.')
|
|
1859
|
-
if (typeof tag !== 'string') throw TypeError('tag is not a string.')
|
|
1860
1917
|
encodeTag(tag, false);
|
|
1861
|
-
|
|
1918
|
+
const tags = this._linkHandlers.get(to);
|
|
1919
|
+
const handlers = tags?.get(tag);
|
|
1920
|
+
if (!handlers) return
|
|
1921
|
+
for (const handler of handlers) this.removeListener(tag, handler);
|
|
1922
|
+
tags.delete(tag);
|
|
1862
1923
|
const linkSet = this.linkMap.get(to);
|
|
1863
|
-
if (!linkSet || !linkSet.has(tag)) return;
|
|
1864
|
-
|
|
1865
|
-
this.unsubscribe(tag);
|
|
1866
|
-
this.removeAllListeners(tag);
|
|
1867
1924
|
linkSet.delete(tag);
|
|
1868
|
-
|
|
1869
|
-
|
|
1925
|
+
if (tags.size === 0) {
|
|
1926
|
+
this._linkHandlers.delete(to);
|
|
1870
1927
|
this.linkMap.delete(to);
|
|
1871
1928
|
}
|
|
1929
|
+
if (tag.startsWith('@')) return
|
|
1930
|
+
|
|
1931
|
+
const linkedElsewhere = [...this._linkHandlers.values()].some(other => other.has(tag));
|
|
1932
|
+
if (!linkedElsewhere && !this._listenTags.has(tag)) this.channels.delete(tag);
|
|
1933
|
+
const remembered = new Set([...this.channels].flatMap(entry => entry.split(',')));
|
|
1934
|
+
const unused = tag.split(',').filter(part =>
|
|
1935
|
+
!remembered.has(part) && !this._manualSubscriptions.has(part));
|
|
1936
|
+
if (unused.length) this.unsubscribe(unused.join(','));
|
|
1872
1937
|
}
|
|
1873
1938
|
|
|
1874
1939
|
/**
|
|
1875
|
-
*
|
|
1876
|
-
* @param {string} to - The local
|
|
1877
|
-
* @throws {TypeError} If
|
|
1940
|
+
* Removes this local component's links without removing other listeners.
|
|
1941
|
+
* @param {string} to - The local component identifier.
|
|
1942
|
+
* @throws {TypeError} If the component identifier is not a string.
|
|
1878
1943
|
*/
|
|
1879
1944
|
unlinkAll(to) {
|
|
1880
1945
|
if (typeof to !== 'string') throw TypeError('to(local link target) is not a string.')
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
for (const tag of linkSet) {
|
|
1886
|
-
this.unsubscribe(tag);
|
|
1887
|
-
this.removeAllListeners(tag);
|
|
1888
|
-
}
|
|
1889
|
-
|
|
1890
|
-
this.linkMap.delete(to);
|
|
1946
|
+
const tags = this._linkHandlers.get(to);
|
|
1947
|
+
if (!tags) return
|
|
1948
|
+
for (const tag of [...tags.keys()]) this.unlink(to, tag);
|
|
1891
1949
|
}
|
|
1892
1950
|
|
|
1893
1951
|
|
|
1894
|
-
|
|
1895
1952
|
/**
|
|
1896
1953
|
* Gets connection metrics.
|
|
1897
1954
|
* @returns {{tx: number, rx: number, txb: number, rxb: number, last: number}}
|
|
@@ -1935,7 +1992,7 @@ class IOCore extends EventEmitter {
|
|
|
1935
1992
|
return {
|
|
1936
1993
|
useAuth: this.useAuth,
|
|
1937
1994
|
isTLS: this.TLS,
|
|
1938
|
-
isAuthorized: this.boho
|
|
1995
|
+
isAuthorized: this.boho?.isAuthorized ?? false,
|
|
1939
1996
|
encMode: this.encMode,
|
|
1940
1997
|
usingEncryption: this.getEncryptionMode()
|
|
1941
1998
|
}
|
|
@@ -2153,6 +2210,8 @@ class IOCongSocket extends IOCore {
|
|
|
2153
2210
|
urlObj = new URL('cong://' + url);
|
|
2154
2211
|
}
|
|
2155
2212
|
const socket = this.socket = net.createConnection(urlObj.port, urlObj.hostname);
|
|
2213
|
+
// Signals are small frames; send each immediately instead of waiting on Nagle.
|
|
2214
|
+
socket.setNoDelay(true);
|
|
2156
2215
|
this._closed = false;
|
|
2157
2216
|
|
|
2158
2217
|
this.socket.on('connect', () => {
|
|
@@ -2193,8 +2252,6 @@ class IOCongSocket extends IOCore {
|
|
|
2193
2252
|
this.txCounter++;
|
|
2194
2253
|
this.txBytes += packData.byteLength;
|
|
2195
2254
|
this.lastTxRxTime = Date.now();
|
|
2196
|
-
} else {
|
|
2197
|
-
console.log('.');
|
|
2198
2255
|
}
|
|
2199
2256
|
}
|
|
2200
2257
|
|
|
@@ -7321,8 +7378,6 @@ class IOWS extends IOCore {
|
|
|
7321
7378
|
this.txCounter++;
|
|
7322
7379
|
this.txBytes += data.byteLength;
|
|
7323
7380
|
this.lastTxRxTime = Date.now();
|
|
7324
|
-
} else {
|
|
7325
|
-
console.log('.');
|
|
7326
7381
|
}
|
|
7327
7382
|
}
|
|
7328
7383
|
|
|
@@ -7383,7 +7438,11 @@ let serverOption = {
|
|
|
7383
7438
|
},
|
|
7384
7439
|
|
|
7385
7440
|
auth: {
|
|
7386
|
-
delay_auth_fail: 600
|
|
7441
|
+
delay_auth_fail: 600,
|
|
7442
|
+
// Same authenticated CID already online:
|
|
7443
|
+
// 'keepNew' (default) replaces the old connection, 'keepOld' rejects the new login.
|
|
7444
|
+
// Override per Server with options.duplicateLogin, or per BohoAuth with its duplicateLogin option.
|
|
7445
|
+
duplicateLogin: 'keepNew'
|
|
7387
7446
|
},
|
|
7388
7447
|
membersOnly: false
|
|
7389
7448
|
|
|
@@ -7642,7 +7701,13 @@ class RemoteCore {
|
|
|
7642
7701
|
}
|
|
7643
7702
|
|
|
7644
7703
|
if (!this.cid) {
|
|
7645
|
-
|
|
7704
|
+
const cid = this.manager.issueAnonymousCid();
|
|
7705
|
+
if (!cid) {
|
|
7706
|
+
console.log('anonymous CID space exhausted');
|
|
7707
|
+
this.close();
|
|
7708
|
+
return;
|
|
7709
|
+
}
|
|
7710
|
+
this.cid = cid;
|
|
7646
7711
|
this.manager.cid2remote.set(this.cid, this);
|
|
7647
7712
|
}
|
|
7648
7713
|
|
|
@@ -8479,8 +8544,12 @@ class Manager {
|
|
|
8479
8544
|
|
|
8480
8545
|
let remoteInfo = `- IP:${remote.ip} #${remote.ssid} cid:${remote.cid} ${remote?.socket.socketType === 'websocket' ? "WS" : "CS"} `;
|
|
8481
8546
|
if (this.connectionLogger) this.connectionLogger.log(remoteInfo);
|
|
8482
|
-
|
|
8483
|
-
this.
|
|
8547
|
+
// A replaced duplicate login no longer owns its CID; the new connection is still online.
|
|
8548
|
+
const cidOwner = this.cid2remote.get(remote.cid);
|
|
8549
|
+
if (!remote.cid || !cidOwner || cidOwner === remote) {
|
|
8550
|
+
this.deligateSignal(remote, '@state', 'close');
|
|
8551
|
+
this.deligateSignal(remote, '@$state', 'close');
|
|
8552
|
+
}
|
|
8484
8553
|
|
|
8485
8554
|
// remove subscriber
|
|
8486
8555
|
for (let ch of remote.channels.keys()) {
|
|
@@ -8507,10 +8576,14 @@ class Manager {
|
|
|
8507
8576
|
}
|
|
8508
8577
|
|
|
8509
8578
|
|
|
8510
|
-
|
|
8511
|
-
|
|
8512
|
-
|
|
8513
|
-
|
|
8579
|
+
// Service lifecycle hook. Called directly: RPC permission/command checks do not apply to cleanup.
|
|
8580
|
+
for (const service of new Set(this.server.services?.values() ?? [])) {
|
|
8581
|
+
if (typeof service.onRemoteClose !== 'function') continue
|
|
8582
|
+
try {
|
|
8583
|
+
service.onRemoteClose(remote);
|
|
8584
|
+
} catch (error) {
|
|
8585
|
+
console.error('service onRemoteClose error:', error);
|
|
8586
|
+
}
|
|
8514
8587
|
}
|
|
8515
8588
|
|
|
8516
8589
|
this.remotes.delete(remote);
|
|
@@ -8808,6 +8881,23 @@ class Manager {
|
|
|
8808
8881
|
}
|
|
8809
8882
|
|
|
8810
8883
|
|
|
8884
|
+
anonymousCidRandom(size) {
|
|
8885
|
+
return globalThis.crypto.getRandomValues(Buffer.alloc(size))
|
|
8886
|
+
}
|
|
8887
|
+
|
|
8888
|
+
// '?' + base64url random bytes, never one that is online. Check and set run in the same
|
|
8889
|
+
// synchronous turn (CID_REQ handler), so concurrent requests cannot take the same CID.
|
|
8890
|
+
// 3 bytes (4 chars) normally; 6 bytes (8 chars) if the short space keeps colliding.
|
|
8891
|
+
issueAnonymousCid() {
|
|
8892
|
+
for (const [size, tries] of [[3, 8], [6, 8]]) {
|
|
8893
|
+
for (let i = 0; i < tries; i++) {
|
|
8894
|
+
const cid = '?' + Buffer.from(this.anonymousCidRandom(size)).toString('base64url');
|
|
8895
|
+
if (!this.cid2remote.has(cid)) return cid
|
|
8896
|
+
}
|
|
8897
|
+
}
|
|
8898
|
+
return null
|
|
8899
|
+
}
|
|
8900
|
+
|
|
8811
8901
|
closeRemoteByCId(cid) {
|
|
8812
8902
|
if (this.cid2remote.has(cid)) {
|
|
8813
8903
|
this.cid2remote.get(cid).close();
|
|
@@ -8846,6 +8936,265 @@ const STATUS = {
|
|
|
8846
8936
|
ERROR: 255
|
|
8847
8937
|
};
|
|
8848
8938
|
|
|
8939
|
+
const decoder = new TextDecoder();
|
|
8940
|
+
const DUPLICATE_LOGIN_POLICIES = ['keepOld', 'keepNew'];
|
|
8941
|
+
// Only WebSocket remotes carry socketType; CongSocket remotes leave it unset.
|
|
8942
|
+
const transportOf = remote => remote.socketType === 'websocket' ? 'websocket' : 'congsocket';
|
|
8943
|
+
|
|
8944
|
+
function validateDuplicateLogin(policy) {
|
|
8945
|
+
if (!DUPLICATE_LOGIN_POLICIES.includes(policy)) {
|
|
8946
|
+
throw new RangeError(`duplicateLogin must be one of: ${DUPLICATE_LOGIN_POLICIES.join(', ')}`)
|
|
8947
|
+
}
|
|
8948
|
+
return policy
|
|
8949
|
+
}
|
|
8950
|
+
|
|
8951
|
+
class BohoAuth {
|
|
8952
|
+
/**
|
|
8953
|
+
* @param {object} keyProvider
|
|
8954
|
+
* @param {{ duplicateLogin?: 'keepOld' | 'keepNew', onAuthEvent?: (event: object) => any }} [options]
|
|
8955
|
+
* duplicateLogin: unset follows serverOption.auth.duplicateLogin (default 'keepNew').
|
|
8956
|
+
* onAuthEvent: called with { type, did, cid, uid, ip, oldIp, socketType, oldSocketType, reason, at }
|
|
8957
|
+
* for 'replaced' (keepNew evicted the old connection) and 'duplicate_rejected' (keepOld).
|
|
8958
|
+
* socketType/oldSocketType are 'websocket' or 'congsocket'.
|
|
8959
|
+
* Errors and rejected promises are logged and never affect authentication.
|
|
8960
|
+
*/
|
|
8961
|
+
constructor(keyProvider, options = {}) {
|
|
8962
|
+
if (!keyProvider) {
|
|
8963
|
+
throw new Error('BohoAuth must be initialized with a keyProvider.');
|
|
8964
|
+
}
|
|
8965
|
+
this.keyProvider = keyProvider;
|
|
8966
|
+
this._duplicateLogin = null;
|
|
8967
|
+
if (options.duplicateLogin !== undefined) this.duplicateLogin = options.duplicateLogin;
|
|
8968
|
+
this.onAuthEvent = options.onAuthEvent ?? null;
|
|
8969
|
+
this.authLogger;
|
|
8970
|
+
if (serverOption.fileLogger.auth.use) {
|
|
8971
|
+
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
8972
|
+
console.log('Auth: begin file logger.[auth]');
|
|
8973
|
+
}
|
|
8974
|
+
}
|
|
8975
|
+
|
|
8976
|
+
/** Effective duplicate login policy: this instance's setting, else serverOption.auth.duplicateLogin. */
|
|
8977
|
+
get duplicateLogin() {
|
|
8978
|
+
return this._duplicateLogin ?? serverOption.auth.duplicateLogin;
|
|
8979
|
+
}
|
|
8980
|
+
|
|
8981
|
+
/** @param {'keepOld' | 'keepNew' | null} policy null returns to the serverOption default. */
|
|
8982
|
+
set duplicateLogin(policy) {
|
|
8983
|
+
this._duplicateLogin = policy === null ? null : validateDuplicateLogin(policy);
|
|
8984
|
+
}
|
|
8985
|
+
|
|
8986
|
+
// Backward-compatible boolean form of duplicateLogin.
|
|
8987
|
+
get keepOldConnection() {
|
|
8988
|
+
return this.duplicateLogin === 'keepOld';
|
|
8989
|
+
}
|
|
8990
|
+
|
|
8991
|
+
set keepOldConnection(keepOld) {
|
|
8992
|
+
this.duplicateLogin = keepOld ? 'keepOld' : 'keepNew';
|
|
8993
|
+
}
|
|
8994
|
+
|
|
8995
|
+
emitAuthEvent(event) {
|
|
8996
|
+
if (typeof this.onAuthEvent !== 'function') return;
|
|
8997
|
+
try {
|
|
8998
|
+
Promise.resolve(this.onAuthEvent(event)).catch(error => console.error('onAuthEvent error:', error));
|
|
8999
|
+
} catch (error) {
|
|
9000
|
+
console.error('onAuthEvent error:', error);
|
|
9001
|
+
}
|
|
9002
|
+
}
|
|
9003
|
+
|
|
9004
|
+
send_auth_fail(peer, reason) {
|
|
9005
|
+
if (peer._closing || peer.state === STATE.CLOSED) return;
|
|
9006
|
+
peer.boho.isAuthorized = false;
|
|
9007
|
+
if (this.authLogger) {
|
|
9008
|
+
let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
|
|
9009
|
+
this.authLogger.log(peerInfo);
|
|
9010
|
+
}
|
|
9011
|
+
// console.log('##### AUTH_FAIL reason: ', reason)
|
|
9012
|
+
peer.setState(STATE.AUTH_FAIL);
|
|
9013
|
+
// add some delay time.
|
|
9014
|
+
setTimeout(e => {
|
|
9015
|
+
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
9016
|
+
peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
9017
|
+
}
|
|
9018
|
+
}, serverOption.auth.delay_auth_fail);
|
|
9019
|
+
}
|
|
9020
|
+
|
|
9021
|
+
|
|
9022
|
+
async verify_auth_req(auth_req, peer) {
|
|
9023
|
+
try {
|
|
9024
|
+
if (!peer.checkAuthChallenge()) return;
|
|
9025
|
+
if (!(auth_req instanceof Uint8Array) || auth_req.length !== it.MetaSize.AUTH_REQ ||
|
|
9026
|
+
auth_req[0] !== it.BohoMsg.AUTH_REQ) {
|
|
9027
|
+
peer.securityMismatch('INVALID_AUTH_PACKET');
|
|
9028
|
+
return;
|
|
9029
|
+
}
|
|
9030
|
+
//1. unpack
|
|
9031
|
+
let infoPack = $$1.unpack(auth_req, it.Meta.AUTH_REQ);
|
|
9032
|
+
if (!infoPack) {
|
|
9033
|
+
this.send_auth_fail(peer, 'unpack auth_pack fail');
|
|
9034
|
+
return
|
|
9035
|
+
}
|
|
9036
|
+
|
|
9037
|
+
let id = "";
|
|
9038
|
+
if (infoPack.id8.includes(0)) {
|
|
9039
|
+
id = decoder.decode(infoPack.id8.subarray(0, infoPack.id8.indexOf(0)));
|
|
9040
|
+
} else {
|
|
9041
|
+
id = decoder.decode(infoPack.id8);
|
|
9042
|
+
}
|
|
9043
|
+
|
|
9044
|
+
//2. get key of id from DB
|
|
9045
|
+
let authInfo = await this.keyProvider.getAuth(id);
|
|
9046
|
+
if (!peer.checkAuthChallenge()) return;
|
|
9047
|
+
if (!authInfo) {
|
|
9048
|
+
this.send_auth_fail(peer, 'NO ID:' + id);
|
|
9049
|
+
return
|
|
9050
|
+
}
|
|
9051
|
+
|
|
9052
|
+
if (serverOption.debug.showAuthInfo) {
|
|
9053
|
+
console.log('[debug]showAuthInfo', authInfo);
|
|
9054
|
+
}
|
|
9055
|
+
|
|
9056
|
+
peer.boho.copy_id8(infoPack.id8);
|
|
9057
|
+
// type of key
|
|
9058
|
+
let authKey;
|
|
9059
|
+
const SHA256_HASH_BASE64_LEN = 44;
|
|
9060
|
+
if (authInfo.key.length == SHA256_HASH_BASE64_LEN) {
|
|
9061
|
+
// hashed key
|
|
9062
|
+
authKey = Buffer.from(authInfo.key, 'base64');
|
|
9063
|
+
peer.boho.copy_key(authKey);
|
|
9064
|
+
} else {
|
|
9065
|
+
// plain key
|
|
9066
|
+
peer.boho.set_key(authInfo.key);
|
|
9067
|
+
}
|
|
9068
|
+
|
|
9069
|
+
//3. check hmac
|
|
9070
|
+
let auth_res = peer.boho.verify_auth_req(infoPack);
|
|
9071
|
+
if (!auth_res) {
|
|
9072
|
+
this.send_auth_fail(peer, 'hmac dismatched');
|
|
9073
|
+
return
|
|
9074
|
+
}
|
|
9075
|
+
|
|
9076
|
+
// A valid proof consumes this challenge even if account policy rejects it.
|
|
9077
|
+
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9078
|
+
peer._challengeUsed = true;
|
|
9079
|
+
|
|
9080
|
+
//4. get info
|
|
9081
|
+
|
|
9082
|
+
//5. check duplicate login.
|
|
9083
|
+
if (peer.manager.cid2remote.has(authInfo.cid) && peer.manager.cid2remote.get(authInfo.cid) !== peer) {
|
|
9084
|
+
let old = peer.manager.cid2remote.get(authInfo.cid);
|
|
9085
|
+
console.log('[WARN]DUPLICATE_LOGIN detected.', old.cid);
|
|
9086
|
+
old.ping(); // check the connection.
|
|
9087
|
+
|
|
9088
|
+
let authClearSignal = $$1.pack(
|
|
9089
|
+
$$1.MB('#MsgType', '8', IOMsg.AUTH_CLEAR),
|
|
9090
|
+
$$1.MB('#reason', 'duplicate login.')
|
|
9091
|
+
);
|
|
9092
|
+
if (this.keepOldConnection) { // duplicateLogin 'keepOld'
|
|
9093
|
+
peer.boho.isAuthorized = false;
|
|
9094
|
+
// keep old connection. reject new connection by sending auth_fail signal.
|
|
9095
|
+
// peer.send(authClearSignal)
|
|
9096
|
+
if( peer.socketType == 'websocket'){
|
|
9097
|
+
this.send_auth_fail(peer, 'duplicate login');
|
|
9098
|
+
}else {
|
|
9099
|
+
peer.setState(STATE.AUTH_FAIL);
|
|
9100
|
+
peer.close(); //arduino
|
|
9101
|
+
}
|
|
9102
|
+
} else {
|
|
9103
|
+
// accept new connection. stop the old connection by sending auth_clear signal.
|
|
9104
|
+
old.send(authClearSignal);
|
|
9105
|
+
old.close();
|
|
9106
|
+
}
|
|
9107
|
+
this.emitAuthEvent({
|
|
9108
|
+
type: this.keepOldConnection ? 'duplicate_rejected' : 'replaced',
|
|
9109
|
+
did: id, cid: authInfo.cid, uid: authInfo.uid || null,
|
|
9110
|
+
ip: peer.ip, oldIp: old.ip,
|
|
9111
|
+
socketType: transportOf(peer), oldSocketType: transportOf(old),
|
|
9112
|
+
reason: 'duplicate login', at: Date.now()
|
|
9113
|
+
});
|
|
9114
|
+
if (this.keepOldConnection) return
|
|
9115
|
+
}
|
|
9116
|
+
|
|
9117
|
+
//6. delete current (or anonymouse)cid if exist.
|
|
9118
|
+
if (peer.cid) {
|
|
9119
|
+
// console.log('if peer has cid', peer.cid)
|
|
9120
|
+
peer.manager.cid2remote.delete(peer.cid);
|
|
9121
|
+
}
|
|
9122
|
+
|
|
9123
|
+
//7. setting info.
|
|
9124
|
+
peer.did = id;
|
|
9125
|
+
peer.cid = authInfo.cid;
|
|
9126
|
+
peer.nick = authInfo.cid; // temporary: nick as cid
|
|
9127
|
+
if (authInfo.uid) peer.uid = authInfo.uid;
|
|
9128
|
+
|
|
9129
|
+
//8. setting quota level.
|
|
9130
|
+
let quotaLevel = serverOption.defaultQuotaIndex;
|
|
9131
|
+
if (authInfo.level) quotaLevel = authInfo.level;
|
|
9132
|
+
quotaLevel = parseInt(quotaLevel);
|
|
9133
|
+
let newQuota = quotaTable[quotaLevel];
|
|
9134
|
+
if (!newQuota) {
|
|
9135
|
+
let err = 'no index quotaTable for auth.level: ' + quotaLevel;
|
|
9136
|
+
this.send_auth_fail(peer, err);
|
|
9137
|
+
return
|
|
9138
|
+
} else {
|
|
9139
|
+
peer.level = quotaLevel;
|
|
9140
|
+
peer.quota = newQuota;
|
|
9141
|
+
}
|
|
9142
|
+
|
|
9143
|
+
if (peer.level === serverOption.adminLevel) {
|
|
9144
|
+
console.log('## LOGIN ADMIN CID:', peer.cid);
|
|
9145
|
+
peer.isAdmin = true;
|
|
9146
|
+
}
|
|
9147
|
+
// send quota.level
|
|
9148
|
+
peer.send(Buffer.from([IOMsg.QUOTA_LEVEL, quotaLevel]));
|
|
9149
|
+
|
|
9150
|
+
//9. set cid2remote
|
|
9151
|
+
peer.manager.cid2remote.set(peer.cid, peer);
|
|
9152
|
+
//10. send ack.
|
|
9153
|
+
peer.send(auth_res);
|
|
9154
|
+
peer.setState(STATE.AUTH_RES);
|
|
9155
|
+
if (this.authLogger) {
|
|
9156
|
+
let peerInfo = `OK #${peer.ssid} cid: ${peer.cid} did:${peer.did}`;
|
|
9157
|
+
if (peer.isAdmin) peerInfo = "#ADMIN# " + peerInfo;
|
|
9158
|
+
this.authLogger.log(peerInfo);
|
|
9159
|
+
}
|
|
9160
|
+
return authInfo
|
|
9161
|
+
} catch (error) {
|
|
9162
|
+
console.log('verify_auth_req error', error);
|
|
9163
|
+
this.send_auth_fail(peer, '[BohoAuth]caught: unknown error:' + error);
|
|
9164
|
+
}
|
|
9165
|
+
}
|
|
9166
|
+
|
|
9167
|
+
async getAuth(id) {
|
|
9168
|
+
return this.keyProvider.getAuth(id);
|
|
9169
|
+
}
|
|
9170
|
+
|
|
9171
|
+
async getAuthIdList() {
|
|
9172
|
+
if (typeof this.keyProvider.getAuthIdList === 'function') {
|
|
9173
|
+
return this.keyProvider.getAuthIdList();
|
|
9174
|
+
}
|
|
9175
|
+
}
|
|
9176
|
+
|
|
9177
|
+
async addAuth(id, keyStr, cid, level = 0) {
|
|
9178
|
+
if (typeof this.keyProvider.addAuth === 'function') {
|
|
9179
|
+
return this.keyProvider.addAuth(id, keyStr, cid, level);
|
|
9180
|
+
}
|
|
9181
|
+
}
|
|
9182
|
+
|
|
9183
|
+
async delAuth(id) {
|
|
9184
|
+
if (typeof this.keyProvider.delAuth === 'function') {
|
|
9185
|
+
return this.keyProvider.delAuth(id);
|
|
9186
|
+
}
|
|
9187
|
+
}
|
|
9188
|
+
|
|
9189
|
+
async save() {
|
|
9190
|
+
if (typeof this.keyProvider.save === 'function') {
|
|
9191
|
+
return this.keyProvider.save();
|
|
9192
|
+
}
|
|
9193
|
+
}
|
|
9194
|
+
|
|
9195
|
+
|
|
9196
|
+
}
|
|
9197
|
+
|
|
8849
9198
|
class Server extends require$$0$3 {
|
|
8850
9199
|
|
|
8851
9200
|
/**
|
|
@@ -8862,6 +9211,7 @@ class Server extends require$$0$3 {
|
|
|
8862
9211
|
}
|
|
8863
9212
|
this.security = Object.freeze(security);
|
|
8864
9213
|
this.serviceNames = new Set();
|
|
9214
|
+
this.services = new Map(); // name -> service module (for lifecycle hooks)
|
|
8865
9215
|
this.wss = {};
|
|
8866
9216
|
this.port = null;
|
|
8867
9217
|
this.congPort = null;
|
|
@@ -8890,6 +9240,16 @@ class Server extends require$$0$3 {
|
|
|
8890
9240
|
if (options.membersOnly) {
|
|
8891
9241
|
serverOption.membersOnly = options.membersOnly;
|
|
8892
9242
|
}
|
|
9243
|
+
// Applies to this server's auth manager only; without auth there are no duplicate logins.
|
|
9244
|
+
if (options.duplicateLogin !== undefined) {
|
|
9245
|
+
validateDuplicateLogin(options.duplicateLogin);
|
|
9246
|
+
if (authManager) {
|
|
9247
|
+
if (!('duplicateLogin' in authManager)) {
|
|
9248
|
+
throw new TypeError('duplicateLogin: the auth manager does not support this option')
|
|
9249
|
+
}
|
|
9250
|
+
authManager.duplicateLogin = options.duplicateLogin;
|
|
9251
|
+
}
|
|
9252
|
+
}
|
|
8893
9253
|
|
|
8894
9254
|
|
|
8895
9255
|
if (options.port || options.port == 0) {
|
|
@@ -8969,6 +9329,8 @@ class Server extends require$$0$3 {
|
|
|
8969
9329
|
|
|
8970
9330
|
startCongServer() {
|
|
8971
9331
|
this.congServer = net.createServer((socket) => {
|
|
9332
|
+
// Signals are small frames; send each immediately instead of waiting on Nagle.
|
|
9333
|
+
socket.setNoDelay(true);
|
|
8972
9334
|
this.manager.addRemote(socket);
|
|
8973
9335
|
})
|
|
8974
9336
|
.on('error', (err) => {
|
|
@@ -9037,6 +9399,7 @@ class Server extends require$$0$3 {
|
|
|
9037
9399
|
}
|
|
9038
9400
|
});
|
|
9039
9401
|
this.serviceNames.add(service);
|
|
9402
|
+
this.services.set(service, service_module);
|
|
9040
9403
|
// console.log(`[Service attached: ${service} ] accept commands: ${service_module.commands}`)
|
|
9041
9404
|
return this
|
|
9042
9405
|
}
|
|
@@ -9052,6 +9415,7 @@ class Server extends require$$0$3 {
|
|
|
9052
9415
|
|
|
9053
9416
|
this.serviceNames.forEach(v => this.removeAllListeners(v));
|
|
9054
9417
|
this.serviceNames.clear();
|
|
9418
|
+
// this.services is kept so onRemoteClose cleanup still runs for sockets that close later.
|
|
9055
9419
|
|
|
9056
9420
|
let serverCount = 0;
|
|
9057
9421
|
if (this.wss) serverCount++;
|
|
@@ -9089,208 +9453,6 @@ class Server extends require$$0$3 {
|
|
|
9089
9453
|
|
|
9090
9454
|
}
|
|
9091
9455
|
|
|
9092
|
-
const decoder = new TextDecoder();
|
|
9093
|
-
class BohoAuth {
|
|
9094
|
-
constructor(keyProvider) {
|
|
9095
|
-
if (!keyProvider) {
|
|
9096
|
-
throw new Error('BohoAuth must be initialized with a keyProvider.');
|
|
9097
|
-
}
|
|
9098
|
-
this.keyProvider = keyProvider;
|
|
9099
|
-
this.keepOldConnection = true;
|
|
9100
|
-
this.authLogger;
|
|
9101
|
-
if (serverOption.fileLogger.auth.use) {
|
|
9102
|
-
this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
|
|
9103
|
-
console.log('Auth: begin file logger.[auth]');
|
|
9104
|
-
}
|
|
9105
|
-
}
|
|
9106
|
-
|
|
9107
|
-
send_auth_fail(peer, reason) {
|
|
9108
|
-
if (peer._closing || peer.state === STATE.CLOSED) return;
|
|
9109
|
-
peer.boho.isAuthorized = false;
|
|
9110
|
-
if (this.authLogger) {
|
|
9111
|
-
let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
|
|
9112
|
-
this.authLogger.log(peerInfo);
|
|
9113
|
-
}
|
|
9114
|
-
// console.log('##### AUTH_FAIL reason: ', reason)
|
|
9115
|
-
peer.setState(STATE.AUTH_FAIL);
|
|
9116
|
-
// add some delay time.
|
|
9117
|
-
setTimeout(e => {
|
|
9118
|
-
if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
|
|
9119
|
-
peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
|
|
9120
|
-
}
|
|
9121
|
-
}, serverOption.auth.delay_auth_fail);
|
|
9122
|
-
}
|
|
9123
|
-
|
|
9124
|
-
|
|
9125
|
-
async verify_auth_req(auth_req, peer) {
|
|
9126
|
-
try {
|
|
9127
|
-
if (!peer.checkAuthChallenge()) return;
|
|
9128
|
-
if (!(auth_req instanceof Uint8Array) || auth_req.length !== it.MetaSize.AUTH_REQ ||
|
|
9129
|
-
auth_req[0] !== it.BohoMsg.AUTH_REQ) {
|
|
9130
|
-
peer.securityMismatch('INVALID_AUTH_PACKET');
|
|
9131
|
-
return;
|
|
9132
|
-
}
|
|
9133
|
-
//1. unpack
|
|
9134
|
-
let infoPack = $$1.unpack(auth_req, it.Meta.AUTH_REQ);
|
|
9135
|
-
if (!infoPack) {
|
|
9136
|
-
this.send_auth_fail(peer, 'unpack auth_pack fail');
|
|
9137
|
-
return
|
|
9138
|
-
}
|
|
9139
|
-
|
|
9140
|
-
let id = "";
|
|
9141
|
-
if (infoPack.id8.includes(0)) {
|
|
9142
|
-
id = decoder.decode(infoPack.id8.subarray(0, infoPack.id8.indexOf(0)));
|
|
9143
|
-
} else {
|
|
9144
|
-
id = decoder.decode(infoPack.id8);
|
|
9145
|
-
}
|
|
9146
|
-
|
|
9147
|
-
//2. get key of id from DB
|
|
9148
|
-
let authInfo = await this.keyProvider.getAuth(id);
|
|
9149
|
-
if (!peer.checkAuthChallenge()) return;
|
|
9150
|
-
if (!authInfo) {
|
|
9151
|
-
this.send_auth_fail(peer, 'NO ID:' + id);
|
|
9152
|
-
return
|
|
9153
|
-
}
|
|
9154
|
-
|
|
9155
|
-
if (serverOption.debug.showAuthInfo) {
|
|
9156
|
-
console.log('[debug]showAuthInfo', authInfo);
|
|
9157
|
-
}
|
|
9158
|
-
|
|
9159
|
-
peer.boho.copy_id8(infoPack.id8);
|
|
9160
|
-
// type of key
|
|
9161
|
-
let authKey;
|
|
9162
|
-
const SHA256_HASH_BASE64_LEN = 44;
|
|
9163
|
-
if (authInfo.key.length == SHA256_HASH_BASE64_LEN) {
|
|
9164
|
-
// hashed key
|
|
9165
|
-
authKey = Buffer.from(authInfo.key, 'base64');
|
|
9166
|
-
peer.boho.copy_key(authKey);
|
|
9167
|
-
} else {
|
|
9168
|
-
// plain key
|
|
9169
|
-
peer.boho.set_key(authInfo.key);
|
|
9170
|
-
}
|
|
9171
|
-
|
|
9172
|
-
//3. check hmac
|
|
9173
|
-
let auth_res = peer.boho.verify_auth_req(infoPack);
|
|
9174
|
-
if (!auth_res) {
|
|
9175
|
-
this.send_auth_fail(peer, 'hmac dismatched');
|
|
9176
|
-
return
|
|
9177
|
-
}
|
|
9178
|
-
|
|
9179
|
-
// A valid proof consumes this challenge even if account policy rejects it.
|
|
9180
|
-
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9181
|
-
peer._challengeUsed = true;
|
|
9182
|
-
|
|
9183
|
-
//4. get info
|
|
9184
|
-
|
|
9185
|
-
//5. check duplicate login.
|
|
9186
|
-
if (peer.manager.cid2remote.has(authInfo.cid) && peer.manager.cid2remote.get(authInfo.cid) !== peer) {
|
|
9187
|
-
let old = peer.manager.cid2remote.get(authInfo.cid);
|
|
9188
|
-
console.log('[WARN]DUPLICATE_LOGIN detected.', old.cid);
|
|
9189
|
-
old.ping(); // check the connection.
|
|
9190
|
-
|
|
9191
|
-
let authClearSignal = $$1.pack(
|
|
9192
|
-
$$1.MB('#MsgType', '8', IOMsg.AUTH_CLEAR),
|
|
9193
|
-
$$1.MB('#reason', 'duplicate login.')
|
|
9194
|
-
);
|
|
9195
|
-
if (this.keepOldConnection) { // default true
|
|
9196
|
-
peer.boho.isAuthorized = false;
|
|
9197
|
-
// keep old connection. reject new connection by sending auth_fail signal.
|
|
9198
|
-
// peer.send(authClearSignal)
|
|
9199
|
-
if( peer.socketType == 'websocket'){
|
|
9200
|
-
this.send_auth_fail(peer, 'duplicate login');
|
|
9201
|
-
}else {
|
|
9202
|
-
peer.setState(STATE.AUTH_FAIL);
|
|
9203
|
-
peer.close(); //arduino
|
|
9204
|
-
}
|
|
9205
|
-
} else {
|
|
9206
|
-
// accept new connection. stop the old connection by sending auth_clear signal.
|
|
9207
|
-
old.send(authClearSignal);
|
|
9208
|
-
old.close();
|
|
9209
|
-
}
|
|
9210
|
-
if (this.keepOldConnection) return
|
|
9211
|
-
}
|
|
9212
|
-
|
|
9213
|
-
//6. delete current (or anonymouse)cid if exist.
|
|
9214
|
-
if (peer.cid) {
|
|
9215
|
-
// console.log('if peer has cid', peer.cid)
|
|
9216
|
-
peer.manager.cid2remote.delete(peer.cid);
|
|
9217
|
-
}
|
|
9218
|
-
|
|
9219
|
-
//7. setting info.
|
|
9220
|
-
peer.did = id;
|
|
9221
|
-
peer.cid = authInfo.cid;
|
|
9222
|
-
peer.nick = authInfo.cid; // temporary: nick as cid
|
|
9223
|
-
if (authInfo.uid) peer.uid = authInfo.uid;
|
|
9224
|
-
|
|
9225
|
-
//8. setting quota level.
|
|
9226
|
-
let quotaLevel = serverOption.defaultQuotaIndex;
|
|
9227
|
-
if (authInfo.level) quotaLevel = authInfo.level;
|
|
9228
|
-
quotaLevel = parseInt(quotaLevel);
|
|
9229
|
-
let newQuota = quotaTable[quotaLevel];
|
|
9230
|
-
if (!newQuota) {
|
|
9231
|
-
let err = 'no index quotaTable for auth.level: ' + quotaLevel;
|
|
9232
|
-
this.send_auth_fail(peer, err);
|
|
9233
|
-
return
|
|
9234
|
-
} else {
|
|
9235
|
-
peer.level = quotaLevel;
|
|
9236
|
-
peer.quota = newQuota;
|
|
9237
|
-
}
|
|
9238
|
-
|
|
9239
|
-
if (peer.level === serverOption.adminLevel) {
|
|
9240
|
-
console.log('## LOGIN ADMIN CID:', peer.cid);
|
|
9241
|
-
peer.isAdmin = true;
|
|
9242
|
-
}
|
|
9243
|
-
// send quota.level
|
|
9244
|
-
peer.send(Buffer.from([IOMsg.QUOTA_LEVEL, quotaLevel]));
|
|
9245
|
-
|
|
9246
|
-
//9. set cid2remote
|
|
9247
|
-
peer.manager.cid2remote.set(peer.cid, peer);
|
|
9248
|
-
//10. send ack.
|
|
9249
|
-
peer.send(auth_res);
|
|
9250
|
-
peer.setState(STATE.AUTH_RES);
|
|
9251
|
-
if (this.authLogger) {
|
|
9252
|
-
let peerInfo = `OK #${peer.ssid} cid: ${peer.cid} did:${peer.did}`;
|
|
9253
|
-
if (peer.isAdmin) peerInfo = "#ADMIN# " + peerInfo;
|
|
9254
|
-
this.authLogger.log(peerInfo);
|
|
9255
|
-
}
|
|
9256
|
-
return authInfo
|
|
9257
|
-
} catch (error) {
|
|
9258
|
-
console.log('verify_auth_req error', error);
|
|
9259
|
-
this.send_auth_fail(peer, '[BohoAuth]caught: unknown error:' + error);
|
|
9260
|
-
}
|
|
9261
|
-
}
|
|
9262
|
-
|
|
9263
|
-
async getAuth(id) {
|
|
9264
|
-
return this.keyProvider.getAuth(id);
|
|
9265
|
-
}
|
|
9266
|
-
|
|
9267
|
-
async getAuthIdList() {
|
|
9268
|
-
if (typeof this.keyProvider.getAuthIdList === 'function') {
|
|
9269
|
-
return this.keyProvider.getAuthIdList();
|
|
9270
|
-
}
|
|
9271
|
-
}
|
|
9272
|
-
|
|
9273
|
-
async addAuth(id, keyStr, cid, level = 0) {
|
|
9274
|
-
if (typeof this.keyProvider.addAuth === 'function') {
|
|
9275
|
-
return this.keyProvider.addAuth(id, keyStr, cid, level);
|
|
9276
|
-
}
|
|
9277
|
-
}
|
|
9278
|
-
|
|
9279
|
-
async delAuth(id) {
|
|
9280
|
-
if (typeof this.keyProvider.delAuth === 'function') {
|
|
9281
|
-
return this.keyProvider.delAuth(id);
|
|
9282
|
-
}
|
|
9283
|
-
}
|
|
9284
|
-
|
|
9285
|
-
async save() {
|
|
9286
|
-
if (typeof this.keyProvider.save === 'function') {
|
|
9287
|
-
return this.keyProvider.save();
|
|
9288
|
-
}
|
|
9289
|
-
}
|
|
9290
|
-
|
|
9291
|
-
|
|
9292
|
-
}
|
|
9293
|
-
|
|
9294
9456
|
class FileKeyProvider {
|
|
9295
9457
|
constructor(_path) {
|
|
9296
9458
|
this.AUTH = new Map();
|
|
@@ -9499,8 +9661,9 @@ const commands = [
|
|
|
9499
9661
|
];
|
|
9500
9662
|
|
|
9501
9663
|
const MIN_LEVEL$1 = 255;
|
|
9664
|
+
// Only a Boho-authenticated device may use sudo; a raised level alone is not authentication.
|
|
9502
9665
|
function checkPermission(remote) {
|
|
9503
|
-
return
|
|
9666
|
+
return remote.boho?.isAuthorized === true && remote.level >= MIN_LEVEL$1;
|
|
9504
9667
|
}
|
|
9505
9668
|
|
|
9506
9669
|
async function call(remote, req) {
|
|
@@ -9592,21 +9755,30 @@ const MIN_LEVEL = 200;
|
|
|
9592
9755
|
const COMMANDS = [
|
|
9593
9756
|
'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
|
|
9594
9757
|
'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
|
|
9758
|
+
'LPUSH', 'LTRIM', 'LRANGE', 'LINDEX', 'LSET', 'EXPIRE',
|
|
9595
9759
|
'get', 'set', 'hGetAll', 'hGet', 'hSet', 'sAdd', 'sIsMember',
|
|
9596
|
-
'sMembers', 'exists', 'sRem', 'del', 'keys', 'save'
|
|
9760
|
+
'sMembers', 'exists', 'sRem', 'del', 'keys', 'save',
|
|
9761
|
+
'lPush', 'lTrim', 'lRange', 'lIndex', 'lSet', 'expire'
|
|
9597
9762
|
];
|
|
9598
9763
|
|
|
9599
9764
|
class RedisService {
|
|
9600
|
-
|
|
9765
|
+
/**
|
|
9766
|
+
* @param {object} redisClient
|
|
9767
|
+
* @param {number} [_minLevel=200]
|
|
9768
|
+
* @param {{ requireAuth?: boolean }} [options] requireAuth (default true): allow Boho-authenticated remotes only.
|
|
9769
|
+
*/
|
|
9770
|
+
constructor(redisClient, _minLevel, options = {}) {
|
|
9601
9771
|
if (!redisClient) {
|
|
9602
9772
|
throw new Error("RedisService constructor: no redisClient")
|
|
9603
9773
|
}
|
|
9604
9774
|
this.redisClient = redisClient;
|
|
9605
9775
|
this.minLevel = _minLevel ? _minLevel : MIN_LEVEL;
|
|
9776
|
+
this.requireAuth = options.requireAuth !== false;
|
|
9606
9777
|
this.commands = COMMANDS;
|
|
9607
9778
|
}
|
|
9608
9779
|
|
|
9609
9780
|
checkPermission(remote, req) {
|
|
9781
|
+
if (this.requireAuth && remote.boho?.isAuthorized !== true) return false;
|
|
9610
9782
|
return (remote.level >= this.minLevel) ? true : false;
|
|
9611
9783
|
}
|
|
9612
9784
|
|