iosignal 7.2.0 → 8.1.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.2.0";
18
+ var version$1 = "8.1.0";
19
19
  var pkg = {
20
20
  version: version$1};
21
21
 
@@ -1049,7 +1049,9 @@ class IOCore extends EventEmitter {
1049
1049
 
1050
1050
  /**
1051
1051
  * Permanently destroys the instance, cleaning up all resources.
1052
- * 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'.
1053
1055
  */
1054
1056
  destroy() {
1055
1057
  this.stop();
@@ -1549,7 +1551,7 @@ class IOCore extends EventEmitter {
1549
1551
  getEncryptionMode() {
1550
1552
  if (this.encMode === ENC_MODE.YES ||
1551
1553
  this.encMode === ENC_MODE.AUTO &&
1552
- !this.TLS && this.boho.isAuthorized
1554
+ !this.TLS && this.boho?.isAuthorized
1553
1555
  ) {
1554
1556
  return true;
1555
1557
  } else {
@@ -1559,10 +1561,12 @@ class IOCore extends EventEmitter {
1559
1561
 
1560
1562
  /**
1561
1563
  * Sends data with encryption based on the encryption mode.
1564
+ * Like an unconnected socket, a destroyed instance silently drops the data.
1562
1565
  * @param {Buffer} data - The data buffer to send.
1563
1566
  * @param {boolean} [useEncryption] - Optional. Force encryption or not. If undefined, uses default policy.
1564
1567
  */
1565
1568
  send_enc_mode(data, useEncryption) {
1569
+ if (!this.boho) return; // destroyed
1566
1570
 
1567
1571
  // use default policy.
1568
1572
  if (useEncryption === undefined) {
@@ -1680,7 +1684,7 @@ class IOCore extends EventEmitter {
1680
1684
 
1681
1685
  const tagEncoded = encodeTag(tag);
1682
1686
  if (tag.startsWith('@') && this.cid) encodeTag(this.cid + tag);
1683
- if( !this.boho.isAuthorized ) return;
1687
+ if( !this.boho?.isAuthorized ) return;
1684
1688
  let dataPack = $$1.B8(data);
1685
1689
 
1686
1690
  //encrypt payload area with key
@@ -1737,6 +1741,12 @@ class IOCore extends EventEmitter {
1737
1741
  call(target, topic, ...args) {
1738
1742
  if (!target || !topic)
1739
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
+ }
1740
1750
  this.mid = (this.mid + 1) & 0xffff;
1741
1751
  let sigPack;
1742
1752
  if (args.length > 0) {
@@ -1980,7 +1990,7 @@ class IOCore extends EventEmitter {
1980
1990
  return {
1981
1991
  useAuth: this.useAuth,
1982
1992
  isTLS: this.TLS,
1983
- isAuthorized: this.boho.isAuthorized,
1993
+ isAuthorized: this.boho?.isAuthorized ?? false,
1984
1994
  encMode: this.encMode,
1985
1995
  usingEncryption: this.getEncryptionMode()
1986
1996
  }
@@ -2198,6 +2208,8 @@ class IOCongSocket extends IOCore {
2198
2208
  urlObj = new URL('cong://' + url);
2199
2209
  }
2200
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);
2201
2213
  this._closed = false;
2202
2214
 
2203
2215
  this.socket.on('connect', () => {
@@ -2238,8 +2250,6 @@ class IOCongSocket extends IOCore {
2238
2250
  this.txCounter++;
2239
2251
  this.txBytes += packData.byteLength;
2240
2252
  this.lastTxRxTime = Date.now();
2241
- } else {
2242
- console.log('.');
2243
2253
  }
2244
2254
  }
2245
2255
 
@@ -7366,8 +7376,6 @@ class IOWS extends IOCore {
7366
7376
  this.txCounter++;
7367
7377
  this.txBytes += data.byteLength;
7368
7378
  this.lastTxRxTime = Date.now();
7369
- } else {
7370
- console.log('.');
7371
7379
  }
7372
7380
  }
7373
7381
 
@@ -7428,7 +7436,11 @@ let serverOption = {
7428
7436
  },
7429
7437
 
7430
7438
  auth: {
7431
- 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'
7432
7444
  },
7433
7445
  membersOnly: false
7434
7446
 
@@ -7687,7 +7699,13 @@ class RemoteCore {
7687
7699
  }
7688
7700
 
7689
7701
  if (!this.cid) {
7690
- 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;
7691
7709
  this.manager.cid2remote.set(this.cid, this);
7692
7710
  }
7693
7711
 
@@ -8524,8 +8542,12 @@ class Manager {
8524
8542
 
8525
8543
  let remoteInfo = `- IP:${remote.ip} #${remote.ssid} cid:${remote.cid} ${remote?.socket.socketType === 'websocket' ? "WS" : "CS"} `;
8526
8544
  if (this.connectionLogger) this.connectionLogger.log(remoteInfo);
8527
- this.deligateSignal(remote, '@state', 'close');
8528
- 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
+ }
8529
8551
 
8530
8552
  // remove subscriber
8531
8553
  for (let ch of remote.channels.keys()) {
@@ -8552,10 +8574,14 @@ class Manager {
8552
8574
  }
8553
8575
 
8554
8576
 
8555
- if (remote.uid && this.server.serviceNames.has('account')) {
8556
- let req = { topic: 'detachUserRemote' };
8557
- req.args = ['caller:manager.removeRemote'];
8558
- 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
+ }
8559
8585
  }
8560
8586
 
8561
8587
  this.remotes.delete(remote);
@@ -8853,6 +8879,23 @@ class Manager {
8853
8879
  }
8854
8880
 
8855
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
+
8856
8899
  closeRemoteByCId(cid) {
8857
8900
  if (this.cid2remote.has(cid)) {
8858
8901
  this.cid2remote.get(cid).close();
@@ -8891,14 +8934,331 @@ const STATUS = {
8891
8934
  ERROR: 255
8892
8935
  };
8893
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
+
9196
+ /**
9197
+ * LocalKeyProvider.js
9198
+ *
9199
+ * Key provider for local testing: no key list, every non-empty ID logs in with its own ID as CID.
9200
+ *
9201
+ * mode 'idKey': the key equals the ID, e.g. io.auth('dev1', 'dev1').
9202
+ * mode 'sharedKey': any ID with the one shared key, e.g. io.auth('dev1', 'lab2026').
9203
+ * level: quota level of every login (a quotaTable index), default serverOption.defaultQuotaIndex.
9204
+ *
9205
+ * example => new BohoAuth(new LocalKeyProvider({ mode: 'sharedKey', key: 'lab2026' }))
9206
+ *
9207
+ * Anyone who knows the rule logs in under any ID, so use it only on a trusted local network.
9208
+ */
9209
+
9210
+
9211
+ const MODES = ['idKey', 'sharedKey'];
9212
+ const hashKey = keyStr => Buffer.from(it.sha256.hash(keyStr)).toString('base64');
9213
+
9214
+ class LocalKeyProvider {
9215
+ /**
9216
+ * @param {'idKey' | { mode: 'idKey' | 'sharedKey', key?: string, level?: number }} options
9217
+ * A string is the mode alone.
9218
+ */
9219
+ constructor(options) {
9220
+ const { mode, key, level } = typeof options === 'string' ? { mode: options } : (options ?? {});
9221
+ if (!MODES.includes(mode)) {
9222
+ throw new TypeError(`LocalKeyProvider mode must be one of: ${MODES.join(', ')}`)
9223
+ }
9224
+ if (mode === 'sharedKey' && (typeof key !== 'string' || key.length === 0)) {
9225
+ throw new TypeError("LocalKeyProvider mode 'sharedKey' needs a non-empty key")
9226
+ }
9227
+ // BohoAuth fails every login whose level has no quotaTable entry, so reject it here instead.
9228
+ if (level !== undefined && !(Number.isInteger(level) && quotaTable[level])) {
9229
+ throw new RangeError(`LocalKeyProvider level must be a quotaTable index: ${Object.keys(quotaTable).join(', ')}`)
9230
+ }
9231
+ this.mode = mode;
9232
+ this.level = level;
9233
+ // Hashed like StringKeyProvider, so a 44-character shared key is not mistaken for a stored hash.
9234
+ this.sharedKeyHash = mode === 'sharedKey' ? hashKey(key) : null;
9235
+ }
9236
+
9237
+ async getAuth(id) {
9238
+ if (!id) return undefined
9239
+ return {
9240
+ key: this.sharedKeyHash ?? hashKey(id),
9241
+ cid: id,
9242
+ level: this.level ?? serverOption.defaultQuotaIndex
9243
+ }
9244
+ }
9245
+ }
9246
+
8894
9247
  class Server extends require$$0$3 {
8895
9248
 
8896
9249
  /**
8897
9250
  * @param {object} options Server configuration.
9251
+ * options.localAuth: login without a key list, for local testing. 'idKey' (key = ID) or
9252
+ * { mode: 'idKey' | 'sharedKey', key, level } (see LocalKeyProvider); the CID is the ID.
9253
+ * Cannot be combined with authManager.
8898
9254
  * @param {any} [authManager] Optional authentication manager.
8899
9255
  */
8900
9256
  constructor(options, authManager) {
8901
9257
  super();
9258
+ if (options.localAuth !== undefined && options.localAuth !== null) {
9259
+ if (authManager) throw new TypeError('localAuth cannot be combined with an authManager')
9260
+ authManager = new BohoAuth(new LocalKeyProvider(options.localAuth));
9261
+ }
8902
9262
  const security = { ...serverOption.security, ...options.security };
8903
9263
  for (const name of ['maxClockSkewMs', 'authChallengeMaxAgeMs', 'maxReplayEntries']) {
8904
9264
  if (!Number.isSafeInteger(security[name]) || security[name] <= 0) {
@@ -8907,7 +9267,9 @@ class Server extends require$$0$3 {
8907
9267
  }
8908
9268
  this.security = Object.freeze(security);
8909
9269
  this.serviceNames = new Set();
8910
- this.wss = {};
9270
+ this.services = new Map(); // name -> service module (for lifecycle hooks)
9271
+ // Stays null for a CongSocket-only server, so close() does not wait on a WebSocket server.
9272
+ this.wss = null;
8911
9273
  this.port = null;
8912
9274
  this.congPort = null;
8913
9275
 
@@ -8935,6 +9297,16 @@ class Server extends require$$0$3 {
8935
9297
  if (options.membersOnly) {
8936
9298
  serverOption.membersOnly = options.membersOnly;
8937
9299
  }
9300
+ // Applies to this server's auth manager only; without auth there are no duplicate logins.
9301
+ if (options.duplicateLogin !== undefined) {
9302
+ validateDuplicateLogin(options.duplicateLogin);
9303
+ if (authManager) {
9304
+ if (!('duplicateLogin' in authManager)) {
9305
+ throw new TypeError('duplicateLogin: the auth manager does not support this option')
9306
+ }
9307
+ authManager.duplicateLogin = options.duplicateLogin;
9308
+ }
9309
+ }
8938
9310
 
8939
9311
 
8940
9312
  if (options.port || options.port == 0) {
@@ -9014,6 +9386,8 @@ class Server extends require$$0$3 {
9014
9386
 
9015
9387
  startCongServer() {
9016
9388
  this.congServer = net.createServer((socket) => {
9389
+ // Signals are small frames; send each immediately instead of waiting on Nagle.
9390
+ socket.setNoDelay(true);
9017
9391
  this.manager.addRemote(socket);
9018
9392
  })
9019
9393
  .on('error', (err) => {
@@ -9082,6 +9456,7 @@ class Server extends require$$0$3 {
9082
9456
  }
9083
9457
  });
9084
9458
  this.serviceNames.add(service);
9459
+ this.services.set(service, service_module);
9085
9460
  // console.log(`[Service attached: ${service} ] accept commands: ${service_module.commands}`)
9086
9461
  return this
9087
9462
  }
@@ -9097,6 +9472,7 @@ class Server extends require$$0$3 {
9097
9472
 
9098
9473
  this.serviceNames.forEach(v => this.removeAllListeners(v));
9099
9474
  this.serviceNames.clear();
9475
+ // this.services is kept so onRemoteClose cleanup still runs for sockets that close later.
9100
9476
 
9101
9477
  let serverCount = 0;
9102
9478
  if (this.wss) serverCount++;
@@ -9134,208 +9510,6 @@ class Server extends require$$0$3 {
9134
9510
 
9135
9511
  }
9136
9512
 
9137
- const decoder = new TextDecoder();
9138
- class BohoAuth {
9139
- constructor(keyProvider) {
9140
- if (!keyProvider) {
9141
- throw new Error('BohoAuth must be initialized with a keyProvider.');
9142
- }
9143
- this.keyProvider = keyProvider;
9144
- this.keepOldConnection = true;
9145
- this.authLogger;
9146
- if (serverOption.fileLogger.auth.use) {
9147
- this.authLogger = new FileLogger(serverOption.fileLogger.auth.path);
9148
- console.log('Auth: begin file logger.[auth]');
9149
- }
9150
- }
9151
-
9152
- send_auth_fail(peer, reason) {
9153
- if (peer._closing || peer.state === STATE.CLOSED) return;
9154
- peer.boho.isAuthorized = false;
9155
- if (this.authLogger) {
9156
- let peerInfo = `FAIL #${peer.ssid} reason:${reason} `;
9157
- this.authLogger.log(peerInfo);
9158
- }
9159
- // console.log('##### AUTH_FAIL reason: ', reason)
9160
- peer.setState(STATE.AUTH_FAIL);
9161
- // add some delay time.
9162
- setTimeout(e => {
9163
- if (!peer._closing && peer.state === STATE.AUTH_FAIL) {
9164
- peer.send(Buffer.from([it.BohoMsg.AUTH_FAIL]));
9165
- }
9166
- }, serverOption.auth.delay_auth_fail);
9167
- }
9168
-
9169
-
9170
- async verify_auth_req(auth_req, peer) {
9171
- try {
9172
- if (!peer.checkAuthChallenge()) return;
9173
- if (!(auth_req instanceof Uint8Array) || auth_req.length !== it.MetaSize.AUTH_REQ ||
9174
- auth_req[0] !== it.BohoMsg.AUTH_REQ) {
9175
- peer.securityMismatch('INVALID_AUTH_PACKET');
9176
- return;
9177
- }
9178
- //1. unpack
9179
- let infoPack = $$1.unpack(auth_req, it.Meta.AUTH_REQ);
9180
- if (!infoPack) {
9181
- this.send_auth_fail(peer, 'unpack auth_pack fail');
9182
- return
9183
- }
9184
-
9185
- let id = "";
9186
- if (infoPack.id8.includes(0)) {
9187
- id = decoder.decode(infoPack.id8.subarray(0, infoPack.id8.indexOf(0)));
9188
- } else {
9189
- id = decoder.decode(infoPack.id8);
9190
- }
9191
-
9192
- //2. get key of id from DB
9193
- let authInfo = await this.keyProvider.getAuth(id);
9194
- if (!peer.checkAuthChallenge()) return;
9195
- if (!authInfo) {
9196
- this.send_auth_fail(peer, 'NO ID:' + id);
9197
- return
9198
- }
9199
-
9200
- if (serverOption.debug.showAuthInfo) {
9201
- console.log('[debug]showAuthInfo', authInfo);
9202
- }
9203
-
9204
- peer.boho.copy_id8(infoPack.id8);
9205
- // type of key
9206
- let authKey;
9207
- const SHA256_HASH_BASE64_LEN = 44;
9208
- if (authInfo.key.length == SHA256_HASH_BASE64_LEN) {
9209
- // hashed key
9210
- authKey = Buffer.from(authInfo.key, 'base64');
9211
- peer.boho.copy_key(authKey);
9212
- } else {
9213
- // plain key
9214
- peer.boho.set_key(authInfo.key);
9215
- }
9216
-
9217
- //3. check hmac
9218
- let auth_res = peer.boho.verify_auth_req(infoPack);
9219
- if (!auth_res) {
9220
- this.send_auth_fail(peer, 'hmac dismatched');
9221
- return
9222
- }
9223
-
9224
- // A valid proof consumes this challenge even if account policy rejects it.
9225
- // Reauthentication requires a new connection, never a replay-state reset.
9226
- peer._challengeUsed = true;
9227
-
9228
- //4. get info
9229
-
9230
- //5. check duplicate login.
9231
- if (peer.manager.cid2remote.has(authInfo.cid) && peer.manager.cid2remote.get(authInfo.cid) !== peer) {
9232
- let old = peer.manager.cid2remote.get(authInfo.cid);
9233
- console.log('[WARN]DUPLICATE_LOGIN detected.', old.cid);
9234
- old.ping(); // check the connection.
9235
-
9236
- let authClearSignal = $$1.pack(
9237
- $$1.MB('#MsgType', '8', IOMsg.AUTH_CLEAR),
9238
- $$1.MB('#reason', 'duplicate login.')
9239
- );
9240
- if (this.keepOldConnection) { // default true
9241
- peer.boho.isAuthorized = false;
9242
- // keep old connection. reject new connection by sending auth_fail signal.
9243
- // peer.send(authClearSignal)
9244
- if( peer.socketType == 'websocket'){
9245
- this.send_auth_fail(peer, 'duplicate login');
9246
- }else {
9247
- peer.setState(STATE.AUTH_FAIL);
9248
- peer.close(); //arduino
9249
- }
9250
- } else {
9251
- // accept new connection. stop the old connection by sending auth_clear signal.
9252
- old.send(authClearSignal);
9253
- old.close();
9254
- }
9255
- if (this.keepOldConnection) return
9256
- }
9257
-
9258
- //6. delete current (or anonymouse)cid if exist.
9259
- if (peer.cid) {
9260
- // console.log('if peer has cid', peer.cid)
9261
- peer.manager.cid2remote.delete(peer.cid);
9262
- }
9263
-
9264
- //7. setting info.
9265
- peer.did = id;
9266
- peer.cid = authInfo.cid;
9267
- peer.nick = authInfo.cid; // temporary: nick as cid
9268
- if (authInfo.uid) peer.uid = authInfo.uid;
9269
-
9270
- //8. setting quota level.
9271
- let quotaLevel = serverOption.defaultQuotaIndex;
9272
- if (authInfo.level) quotaLevel = authInfo.level;
9273
- quotaLevel = parseInt(quotaLevel);
9274
- let newQuota = quotaTable[quotaLevel];
9275
- if (!newQuota) {
9276
- let err = 'no index quotaTable for auth.level: ' + quotaLevel;
9277
- this.send_auth_fail(peer, err);
9278
- return
9279
- } else {
9280
- peer.level = quotaLevel;
9281
- peer.quota = newQuota;
9282
- }
9283
-
9284
- if (peer.level === serverOption.adminLevel) {
9285
- console.log('## LOGIN ADMIN CID:', peer.cid);
9286
- peer.isAdmin = true;
9287
- }
9288
- // send quota.level
9289
- peer.send(Buffer.from([IOMsg.QUOTA_LEVEL, quotaLevel]));
9290
-
9291
- //9. set cid2remote
9292
- peer.manager.cid2remote.set(peer.cid, peer);
9293
- //10. send ack.
9294
- peer.send(auth_res);
9295
- peer.setState(STATE.AUTH_RES);
9296
- if (this.authLogger) {
9297
- let peerInfo = `OK #${peer.ssid} cid: ${peer.cid} did:${peer.did}`;
9298
- if (peer.isAdmin) peerInfo = "#ADMIN# " + peerInfo;
9299
- this.authLogger.log(peerInfo);
9300
- }
9301
- return authInfo
9302
- } catch (error) {
9303
- console.log('verify_auth_req error', error);
9304
- this.send_auth_fail(peer, '[BohoAuth]caught: unknown error:' + error);
9305
- }
9306
- }
9307
-
9308
- async getAuth(id) {
9309
- return this.keyProvider.getAuth(id);
9310
- }
9311
-
9312
- async getAuthIdList() {
9313
- if (typeof this.keyProvider.getAuthIdList === 'function') {
9314
- return this.keyProvider.getAuthIdList();
9315
- }
9316
- }
9317
-
9318
- async addAuth(id, keyStr, cid, level = 0) {
9319
- if (typeof this.keyProvider.addAuth === 'function') {
9320
- return this.keyProvider.addAuth(id, keyStr, cid, level);
9321
- }
9322
- }
9323
-
9324
- async delAuth(id) {
9325
- if (typeof this.keyProvider.delAuth === 'function') {
9326
- return this.keyProvider.delAuth(id);
9327
- }
9328
- }
9329
-
9330
- async save() {
9331
- if (typeof this.keyProvider.save === 'function') {
9332
- return this.keyProvider.save();
9333
- }
9334
- }
9335
-
9336
-
9337
- }
9338
-
9339
9513
  class FileKeyProvider {
9340
9514
  constructor(_path) {
9341
9515
  this.AUTH = new Map();
@@ -9544,8 +9718,9 @@ const commands = [
9544
9718
  ];
9545
9719
 
9546
9720
  const MIN_LEVEL$1 = 255;
9721
+ // Only a Boho-authenticated device may use sudo; a raised level alone is not authentication.
9547
9722
  function checkPermission(remote) {
9548
- return (remote.level >= MIN_LEVEL$1) ? true : false;
9723
+ return remote.boho?.isAuthorized === true && remote.level >= MIN_LEVEL$1;
9549
9724
  }
9550
9725
 
9551
9726
  async function call(remote, req) {
@@ -9637,21 +9812,30 @@ const MIN_LEVEL = 200;
9637
9812
  const COMMANDS = [
9638
9813
  'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
9639
9814
  'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
9815
+ 'LPUSH', 'LTRIM', 'LRANGE', 'LINDEX', 'LSET', 'EXPIRE',
9640
9816
  'get', 'set', 'hGetAll', 'hGet', 'hSet', 'sAdd', 'sIsMember',
9641
- 'sMembers', 'exists', 'sRem', 'del', 'keys', 'save'
9817
+ 'sMembers', 'exists', 'sRem', 'del', 'keys', 'save',
9818
+ 'lPush', 'lTrim', 'lRange', 'lIndex', 'lSet', 'expire'
9642
9819
  ];
9643
9820
 
9644
9821
  class RedisService {
9645
- constructor(redisClient, _minLevel) {
9822
+ /**
9823
+ * @param {object} redisClient
9824
+ * @param {number} [_minLevel=200]
9825
+ * @param {{ requireAuth?: boolean }} [options] requireAuth (default true): allow Boho-authenticated remotes only.
9826
+ */
9827
+ constructor(redisClient, _minLevel, options = {}) {
9646
9828
  if (!redisClient) {
9647
9829
  throw new Error("RedisService constructor: no redisClient")
9648
9830
  }
9649
9831
  this.redisClient = redisClient;
9650
9832
  this.minLevel = _minLevel ? _minLevel : MIN_LEVEL;
9833
+ this.requireAuth = options.requireAuth !== false;
9651
9834
  this.commands = COMMANDS;
9652
9835
  }
9653
9836
 
9654
9837
  checkPermission(remote, req) {
9838
+ if (this.requireAuth && remote.boho?.isAuthorized !== true) return false;
9655
9839
  return (remote.level >= this.minLevel) ? true : false;
9656
9840
  }
9657
9841
 
@@ -9674,4 +9858,4 @@ class RedisService {
9674
9858
 
9675
9859
  const version = pkg.version;
9676
9860
 
9677
- export { it as Boho, BohoAuth, CongRx, ENC_MODE, FileKeyProvider, FileLogger, IOWS as IO, IOCongSocket, IOMsg, $$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 };
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 };