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