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