iosignal 9.0.0 → 9.12.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.
@@ -18,7 +18,7 @@ var fs = require('fs');
18
18
  var process$1 = require('process');
19
19
  var path = require('path');
20
20
 
21
- var version$1 = "9.0.0";
21
+ var version$1 = "9.12.0";
22
22
  var pkg = {
23
23
  version: version$1};
24
24
 
@@ -892,6 +892,7 @@ class IOCore extends EventEmitter {
892
892
  this._linkHandlers = new Map();
893
893
  /** @private @type {Set<string>} */
894
894
  this._listenTags = new Set();
895
+ this._readyDispatch = false; // true while 'ready' handlers run; see listen()
895
896
  /** @private @type {Set<string>} */
896
897
  this._manualSubscriptions = new Set();
897
898
 
@@ -1193,9 +1194,17 @@ class IOCore extends EventEmitter {
1193
1194
  let cidStr = decoder$4.decode(buffer.subarray(1));
1194
1195
  this.cid = cidStr;
1195
1196
 
1196
- // **IMPORTANT** change state before subscribe.
1197
- this.stateChange('ready', 'cid_ready');
1198
- this.subscribe_channels();
1197
+ // State first (subscribe_channels needs READY), then the stored subscriptions, and only then
1198
+ // 'ready': a signal sent from a ready handler reaches the server after our own subscriptions.
1199
+ // stateChange() without a message emits 'change' only; false means a handler moved the state on.
1200
+ if (!this.stateChange('ready')) break;
1201
+ this.subscribe_channels();
1202
+ this._readyDispatch = true;
1203
+ try {
1204
+ this.emit('ready', 'cid_ready');
1205
+ } finally {
1206
+ this._readyDispatch = false;
1207
+ }
1199
1208
  break;
1200
1209
 
1201
1210
  case IOMsg.QUOTA: {
@@ -1702,11 +1711,22 @@ class IOCore extends EventEmitter {
1702
1711
 
1703
1712
 
1704
1713
  /**
1705
- * Subscribes to a channel or channels.
1714
+ * Subscribes to a channel or channels on the current, ready connection, at once.
1715
+ * Call it from a ready handler (it runs on every connect) or later while ready; it is not
1716
+ * repeated after a reconnect. To subscribe before connecting, or for every connection
1717
+ * without a ready handler, use listen() or link().
1706
1718
  * @param {string} tag - The tag(s) of the channel(s) to subscribe to (comma-separated).
1707
1719
  * @throws {TypeError} If tag is invalid, exceeds the length limit, or contains a direct-receive subscription.
1720
+ * @throws {Error} If the connection is not ready (after destroy() it is a no-op instead).
1708
1721
  */
1709
1722
  subscribe(tag) {
1723
+ encodeSubscriptionTags(tag);
1724
+ if (!this.boho) return // destroyed: a no-op, like every send after destroy()
1725
+ if (this.state !== STATE.READY) {
1726
+ // Before the CID the request would go out unauthenticated and unencrypted; while
1727
+ // disconnected it would be lost. Neither should pass silently.
1728
+ throw new Error(`subscribe('${tag}') needs a ready connection (state: ${this.stateName}); call it from a ready handler, or use listen() or link()`)
1729
+ }
1710
1730
  sendSubscription(this, tag);
1711
1731
  for (const part of tag.split(',')) this._manualSubscriptions.add(part);
1712
1732
  }
@@ -1770,23 +1790,28 @@ class IOCore extends EventEmitter {
1770
1790
  * Convenience API for simple clients (for example, CLI tools): register a
1771
1791
  * tag handler once and remember its subscription in channels. For subscription
1772
1792
  * tags, register before connection readiness; the CID-ready flow subscribes on initial connection
1773
- * and again after reconnect, without application-level ready/subscribe code.
1793
+ * and again after reconnect, before 'ready' is emitted, so a ready handler may signal at once.
1774
1794
  * This does not send a subscription immediately, even if already ready.
1775
- * For precise subscription/send ordering or dynamic subscriptions, use
1776
- * on() with subscribe() in a ready handler instead.
1777
- * Direct signals need no subscription: use on/listen('@') for all direct
1778
- * signals, or on/listen('@topic') for an exact topic. Direct handlers can be
1779
- * registered before or after readiness, before the message arrives.
1795
+ * Do not call listen() inside a ready handler; it throws there, for any tag: a subscription tag
1796
+ * would be subscribed only after the next reconnect, and a handler registered on every
1797
+ * connect runs once more after each reconnect. In a ready handler use on() and subscribe();
1798
+ * for dynamic subscriptions use link().
1799
+ * Direct signals need no subscription: use listen('@') during setup, or on('@'), for all
1800
+ * direct signals, or '@topic' for an exact topic.
1780
1801
  * Dispatch is synchronous: '@' first, then '@topic' when tag is not '@'.
1781
1802
  * Returning false does not cancel dispatch; a thrown error interrupts it.
1782
1803
  * @param {string} tag - The tag to listen on.
1783
1804
  * @param {Function} handler - The callback function to handle the signal.
1784
1805
  * @throws {TypeError} If tag is not a string, handler is not a function, or tag length is invalid.
1806
+ * @throws {Error} If called inside a ready handler.
1785
1807
  */
1786
1808
  listen(tag, handler) {
1787
1809
  if (typeof tag !== 'string') throw TypeError('tag should be string.')
1788
1810
  encodeTag(tag, false);
1789
1811
  if (typeof handler !== 'function') throw TypeError('handler is not a function.')
1812
+ if (this._readyDispatch) {
1813
+ throw new Error(`listen('${tag}') inside a ready handler: call listen() in the setup code that runs before the connection is ready, or use on() and subscribe() in the ready handler`)
1814
+ }
1790
1815
 
1791
1816
  if (tag.indexOf('@') !== 0) {
1792
1817
  encodeSubscriptionTags(tag);
@@ -1803,8 +1828,8 @@ class IOCore extends EventEmitter {
1803
1828
 
1804
1829
  /**
1805
1830
  * Associates handlers with a local component for scoped teardown.
1806
- * Direct tags (@ or @topic) only register local handlers. Other tags also
1807
- * subscribe now and are remembered for reconnection.
1831
+ * Direct tags (@ or @topic) only register local handlers. Other tags are remembered for
1832
+ * reconnection and subscribed at once on a ready connection; before that, when it becomes ready.
1808
1833
  * @param {string} to - The local component identifier, not a server target.
1809
1834
  * @param {string} tag - The exact event tag.
1810
1835
  * @param {Function} handler - The callback receiving (tag, ...args).
@@ -1830,7 +1855,9 @@ class IOCore extends EventEmitter {
1830
1855
  this.on(tag, linkedHandler);
1831
1856
  if (!direct) {
1832
1857
  this.channels.add(tag);
1833
- sendSubscription(this, tag);
1858
+ // Not before the connection is ready: the request would go out before authentication
1859
+ // (unencrypted) and again from subscribe_channels(), repeating retained values.
1860
+ if (this.state === STATE.READY) sendSubscription(this, tag);
1834
1861
  }
1835
1862
  }
1836
1863
 
@@ -7500,11 +7527,14 @@ class RemoteCore {
7500
7527
  this.did = ''; // Device Id
7501
7528
  this.uid = ''; // User Id
7502
7529
  this.nick = '';
7530
+ this.site = ''; // the Origin host of a browser connection, set by Remote
7503
7531
 
7504
7532
  this.privateNode = false;
7505
7533
  this.HOME_CHANNEL = '';
7506
7534
  this.role = 'anonymous'; // set on authentication; see ROLES in BohoAuth
7507
7535
  this.accountUid = null; // counted in manager.accountConnections while authenticated with a uid
7536
+ this.ownerUid = null; // the device's owner (login uid); a web sign-in later changes uid, not this
7537
+ this.rxPolicy = null; // compiled delivery policy of an owned device, see deliveryPolicy.js
7508
7538
  // Quota profile (a server.quotas entry, read live): the anonymous one until authenticated.
7509
7539
  this.quotaName = manager.anonymousQuota;
7510
7540
  this.quota = manager.quotas[this.quotaName];
@@ -8152,6 +8182,19 @@ function getClientAddress(req, trust = serverOption.trustProxy) {
8152
8182
  }
8153
8183
  }
8154
8184
 
8185
+ // The site a browser connection came from: the host name of its Origin header ('bayo.tv'),
8186
+ // without scheme or port. '' when there is none (Node.js, apps, TCP) or it is 'null' (a file
8187
+ // page). A non-browser client can send any Origin, so this is for display only.
8188
+ function originHost(req) {
8189
+ const origin = req?.headers?.origin;
8190
+ if (typeof origin !== 'string' || !origin || origin === 'null' || origin.length > 512) return ''
8191
+ try {
8192
+ return new URL(origin).hostname.toLowerCase().replace(/^\[|\]$/g, '').slice(0, 253)
8193
+ } catch {
8194
+ return ''
8195
+ }
8196
+ }
8197
+
8155
8198
  class Remote extends RemoteCore {
8156
8199
  constructor(socket, req, manager) {
8157
8200
  super(socket, manager);
@@ -8165,6 +8208,7 @@ class Remote extends RemoteCore {
8165
8208
  const { ip, TLS } = getClientAddress(req, this.manager.server?.trustProxy);
8166
8209
  this.ip = ip;
8167
8210
  this.TLS = TLS;
8211
+ this.site = originHost(req);
8168
8212
  } else {
8169
8213
  this.TLS = false;
8170
8214
  this.ip = normalizeIP(socket.remoteAddress) ?? '0.0.0.0';
@@ -8562,6 +8606,148 @@ class Metrics {
8562
8606
 
8563
8607
  }
8564
8608
 
8609
+ /**
8610
+ * Delivery policy: which senders a device accepts CID unicast ('<cid>@topic') from.
8611
+ *
8612
+ * The policy belongs to an owned device (one whose login has a uid) and comes with its login
8613
+ * (authInfo.rxPolicy from the key provider, JSON text or an object) or later from
8614
+ * Manager.setDeliveryPolicy(). A device without an owner uid is never filtered.
8615
+ *
8616
+ * {
8617
+ * v: 1,
8618
+ * mode: 'open' | 'allowlist' | 'denylist', // open: everyone (the default)
8619
+ * anonymous: 'allow' | 'deny', // default: deny for allowlist, allow for denylist
8620
+ * publish: 'all' | 'policy', // who gets its CID publications ('@topic', '@$topic'):
8621
+ * // 'all' subscribers (default), or only those the policy allows
8622
+ * allow: { cids: [], uids: [] },
8623
+ * deny: { cids: [], uids: [] }
8624
+ * }
8625
+ *
8626
+ * Decision, first match wins:
8627
+ * 1. no owner, no policy, mode open -> allow
8628
+ * 2. the device itself, its owner's uid, or a connection with role 'admin' -> allow
8629
+ * 3. sender CID in deny.cids / allow.cids -> deny / allow
8630
+ * 4. sender uid in deny.uids / allow.uids -> deny / allow
8631
+ * 5. anonymous sender (not authenticated, no uid) -> anonymous setting
8632
+ * 6. mode default: allowlist denies, denylist allows
8633
+ *
8634
+ * With publish 'policy', the same decision (subscriber in the sender's place) filters the device's CID
8635
+ * publications and the retained ones a new subscriber would get. Its '@state' close notice included.
8636
+ *
8637
+ * The sender's uid is remote.uid: a device's owner, or the user of a web sign-in on that connection.
8638
+ * Only the server's own view of the sender is used, never anything in the message.
8639
+ */
8640
+
8641
+ const DELIVERY_POLICY_MODES = Object.freeze(['open', 'allowlist', 'denylist']);
8642
+ const DELIVERY_POLICY_MAX_ENTRIES = 200;
8643
+ const ENTRY_MAX_LENGTH = 64;
8644
+ const LISTS = ['cids', 'uids'];
8645
+
8646
+ function entries(name, value) {
8647
+ if (value === undefined || value === null) return []
8648
+ if (!Array.isArray(value)) throw new TypeError(`${name} must be an array`)
8649
+ if (value.length > DELIVERY_POLICY_MAX_ENTRIES) {
8650
+ throw new RangeError(`${name} has more than ${DELIVERY_POLICY_MAX_ENTRIES} entries`)
8651
+ }
8652
+ for (const entry of value) {
8653
+ if (typeof entry !== 'string' || !entry || entry.length > ENTRY_MAX_LENGTH) {
8654
+ throw new TypeError(`${name} entries must be non-empty strings of at most ${ENTRY_MAX_LENGTH} characters`)
8655
+ }
8656
+ }
8657
+ return [...new Set(value)]
8658
+ }
8659
+
8660
+ function lists(name, value) {
8661
+ if (value === undefined || value === null) return { cids: [], uids: [] }
8662
+ if (typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${name} must be an object`)
8663
+ for (const key of Object.keys(value)) {
8664
+ if (!LISTS.includes(key)) throw new TypeError(`unknown ${name}.${key}`)
8665
+ }
8666
+ return { cids: entries(`${name}.cids`, value.cids), uids: entries(`${name}.uids`, value.uids) }
8667
+ }
8668
+
8669
+ /**
8670
+ * A checked copy of a policy with every field present, or null for "no policy" (null, undefined, '').
8671
+ * Accepts JSON text. Throws TypeError/RangeError on an invalid policy.
8672
+ */
8673
+ function normalizeDeliveryPolicy(raw) {
8674
+ if (raw === undefined || raw === null || raw === '') return null
8675
+ let policy = raw;
8676
+ if (typeof raw === 'string') {
8677
+ try { policy = JSON.parse(raw); } catch { throw new TypeError('delivery policy is not valid JSON') }
8678
+ }
8679
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new TypeError('delivery policy must be an object')
8680
+ for (const key of Object.keys(policy)) {
8681
+ if (!['v', 'mode', 'anonymous', 'publish', 'allow', 'deny', 'updatedAt'].includes(key)) throw new TypeError(`unknown delivery policy field ${key}`)
8682
+ }
8683
+ if (policy.v !== undefined && policy.v !== 1) throw new TypeError('delivery policy version must be 1')
8684
+ const mode = policy.mode ?? 'open';
8685
+ if (!DELIVERY_POLICY_MODES.includes(mode)) throw new TypeError(`delivery policy mode must be one of: ${DELIVERY_POLICY_MODES.join(', ')}`)
8686
+ const anonymous = policy.anonymous ?? (mode === 'allowlist' ? 'deny' : 'allow');
8687
+ if (anonymous !== 'allow' && anonymous !== 'deny') throw new TypeError("delivery policy anonymous must be 'allow' or 'deny'")
8688
+ const publish = policy.publish ?? 'all';
8689
+ if (publish !== 'all' && publish !== 'policy') throw new TypeError("delivery policy publish must be 'all' or 'policy'")
8690
+ const normalized = { v: 1, mode, anonymous, publish, allow: lists('allow', policy.allow), deny: lists('deny', policy.deny) };
8691
+ if (policy.updatedAt !== undefined) {
8692
+ if (!Number.isSafeInteger(policy.updatedAt) || policy.updatedAt < 0) throw new TypeError('delivery policy updatedAt must be a time in ms')
8693
+ normalized.updatedAt = policy.updatedAt;
8694
+ }
8695
+ return normalized
8696
+ }
8697
+
8698
+ /**
8699
+ * The form Manager checks per message, or null when nothing is filtered (no owner, no policy, open).
8700
+ * Never throws: a stored policy that cannot be read only lets the owner's own senders through
8701
+ * (fail closed), since ignoring it would deliver what the owner asked to block.
8702
+ */
8703
+ function compileDeliveryPolicy(raw, ownerUid) {
8704
+ if (typeof ownerUid !== 'string' || !ownerUid) return null
8705
+ let policy;
8706
+ try {
8707
+ policy = normalizeDeliveryPolicy(raw);
8708
+ } catch (error) {
8709
+ console.warn(`[iosignal] unreadable delivery policy of uid ${ownerUid}, owner only:`, error.message);
8710
+ policy = { mode: 'allowlist', anonymous: 'deny', publish: 'policy', allow: { cids: [], uids: [] }, deny: { cids: [], uids: [] } };
8711
+ }
8712
+ if (!policy || policy.mode === 'open') return null
8713
+ return Object.freeze({
8714
+ owner: ownerUid,
8715
+ mode: policy.mode,
8716
+ defaultAllow: policy.mode === 'denylist',
8717
+ anonymousAllow: policy.anonymous === 'allow',
8718
+ filterPublish: policy.publish === 'policy',
8719
+ allowCids: new Set(policy.allow.cids),
8720
+ denyCids: new Set(policy.deny.cids),
8721
+ allowUids: new Set(policy.allow.uids),
8722
+ denyUids: new Set(policy.deny.uids)
8723
+ })
8724
+ }
8725
+
8726
+ /** True if `target` (whose compiled policy is target.rxPolicy) accepts a unicast from `sender`. */
8727
+ function deliveryAllowed(target, sender) {
8728
+ const policy = target.rxPolicy;
8729
+ if (!policy) return true
8730
+ if (sender === target) return true
8731
+ const authorized = sender.boho?.isAuthorized === true;
8732
+ const uid = typeof sender.uid === 'string' && sender.uid ? sender.uid : null;
8733
+ if (uid === policy.owner) return true
8734
+ if (authorized && sender.role === 'admin') return true
8735
+ // An anonymous connection's CID is random per connection, so CID rules are for authenticated ones.
8736
+ if (authorized) {
8737
+ if (policy.denyCids.has(sender.cid)) return false
8738
+ if (policy.allowCids.has(sender.cid)) return true
8739
+ }
8740
+ if (uid) {
8741
+ if (policy.denyUids.has(uid)) return false
8742
+ if (policy.allowUids.has(uid)) return true
8743
+ }
8744
+ if (!authorized && !uid) return policy.anonymousAllow
8745
+ return policy.defaultAllow
8746
+ }
8747
+
8748
+ // Characters of an anonymous CID after its '?': lowercase Crockford base32, easy to read aloud and type.
8749
+ const ANONYMOUS_CID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
8750
+
8565
8751
  const encoder = new TextEncoder();
8566
8752
  const decoder$1 = new TextDecoder();
8567
8753
 
@@ -8579,7 +8765,8 @@ class Manager {
8579
8765
  // Cumulative since the server started; never reset (readers compute rates from deltas).
8580
8766
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
8581
8767
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
8582
- peerRxLimitSkipped: 0 }; // messages not sent: larger than the peer's advertised RX buffer
8768
+ peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
8769
+ policyDenied: 0 }; // unicasts and CID publications a device's delivery policy kept back
8583
8770
 
8584
8771
  this.authManager = authManager;
8585
8772
 
@@ -8655,6 +8842,37 @@ class Manager {
8655
8842
  this.accountConnectionCounts.set(uid, this.accountConnections(uid) + 1);
8656
8843
  }
8657
8844
 
8845
+ /**
8846
+ * Replace the delivery policy of the connected, owned device with this CID (see deliveryPolicy.js);
8847
+ * the next unicast to it already uses the new one. A new login reads the stored policy again.
8848
+ * Returns false when no such connection is here or it has no owner (never filtered).
8849
+ * Throws on an invalid policy, so a caller cannot install one by mistake.
8850
+ */
8851
+ setDeliveryPolicy(cid, policy) {
8852
+ const remote = this.cid2remote.get(cid);
8853
+ if (!remote?.boho.isAuthorized || !remote.ownerUid) return false
8854
+ normalizeDeliveryPolicy(policy);
8855
+ remote.rxPolicy = compileDeliveryPolicy(policy, remote.ownerUid);
8856
+ return true
8857
+ }
8858
+
8859
+ /**
8860
+ * Count a message a delivery policy kept from `other` (unicast from it, or a publication to it) and,
8861
+ * when someone listens, emit 'delivery:denied' on the server with what the server knows of both:
8862
+ * { kind: 'unicast' | 'publish', cid, did, owner, other: { cid, uid, ip, authenticated }, at }.
8863
+ * An anonymous connection's CID is not reported (random per connection).
8864
+ */
8865
+ deliveryDenied(device, other, kind) {
8866
+ this.counters.policyDenied++;
8867
+ if (!this.server?.listenerCount?.('delivery:denied')) return
8868
+ const authenticated = other.boho?.isAuthorized === true;
8869
+ this.server.emit('delivery:denied', {
8870
+ kind, cid: device.cid, did: device.did, owner: device.ownerUid,
8871
+ other: { cid: authenticated ? other.cid : null, uid: other.uid || null, ip: other.ip ?? null, authenticated },
8872
+ at: Date.now()
8873
+ });
8874
+ }
8875
+
8658
8876
  removeAccountConnection(remote) {
8659
8877
  const uid = remote.accountUid;
8660
8878
  if (!uid) return
@@ -8844,6 +9062,8 @@ class Manager {
8844
9062
  if (tag.indexOf('$') == 0) return ['err', 'prefix $ is reserved for userSet tag.']
8845
9063
 
8846
9064
  let cidIndex = tag.indexOf('@');
9065
+ // A device whose policy also covers its publications: each subscriber is checked (see deliveryPolicy.js).
9066
+ const publisher = cidIndex === 0 && remote.rxPolicy?.filterPublish ? remote : null;
8847
9067
  if (cidIndex === 0) {
8848
9068
  // ** CID_PUB multi-cast
8849
9069
  // [cid_pub] @topic , @$retainTopic
@@ -8855,14 +9075,20 @@ class Manager {
8855
9075
  } else if (cidIndex > 0) {
8856
9076
  // uni-cast.
8857
9077
  let targetCId = tag.split('@')[0];
8858
- if (this.cid2remote.has(targetCId)) {
9078
+ const target = this.cid2remote.get(targetCId);
9079
+ if (target && !deliveryAllowed(target, remote)) {
9080
+ // Same answer as an offline CID: a sender cannot tell it is blocked, or probe the policy.
9081
+ this.deliveryDenied(target, remote, 'unicast');
9082
+ return ['err', 'Invalid cid']
9083
+ }
9084
+ if (target) {
8859
9085
  //rm cid from tag.
8860
9086
  let ommitCIdTag = '@' + tag.split('@')[1];
8861
9087
  // console.log('uni-cast tag change from', tag, 'to' , ommitCIdTag )
8862
9088
  message = this.getNewSignalTagMessage(message, ommitCIdTag);
8863
9089
  if (!message) return ['err', 'Tag exceeds 255 UTF-8 bytes']
8864
9090
  // console.log(`origin tag: ${tag} omitTag: ${this.getSignalTag(message)}`)
8865
- this.cid2remote.get(targetCId).send_enc_mode(message);
9091
+ target.send_enc_mode(message);
8866
9092
  return ['ok', 1]
8867
9093
  }
8868
9094
  return ['err', 'Invalid cid']
@@ -8915,11 +9141,13 @@ class Manager {
8915
9141
  // console.log('## null remote' )
8916
9142
  break;
8917
9143
  }
9144
+ if (publisher && !deliveryAllowed(publisher, c)) {
9145
+ this.deliveryDenied(publisher, c, 'publish');
9146
+ continue
9147
+ }
8918
9148
  // change: from v4.x allow receiveSelfMessages.
8919
- // if (c !== remote) {
8920
- c.send_enc_mode(message);
8921
- sentCounter++;
8922
- // }
9149
+ c.send_enc_mode(message);
9150
+ sentCounter++;
8923
9151
  }
8924
9152
 
8925
9153
  this.counters.deliveryAttempts += sentCounter;
@@ -9078,8 +9306,13 @@ class Manager {
9078
9306
  let cid = tag.split('@')[0];
9079
9307
  cid = cid.split(this.CID_PREFIX)[1];
9080
9308
  let retainTag = tag.split('@')[1];
9081
- if (this.cid2remote.has(cid)) {
9082
- retainMessage = this.cid2remote.get(cid).retain_signal.get(retainTag);
9309
+ const owner = this.cid2remote.get(cid);
9310
+ if (owner) {
9311
+ if (owner.rxPolicy?.filterPublish && !deliveryAllowed(owner, remote)) {
9312
+ this.deliveryDenied(owner, remote, 'publish');
9313
+ return;
9314
+ }
9315
+ retainMessage = owner.retain_signal.get(retainTag);
9083
9316
  } else {
9084
9317
  // console.log('cid subscribe is rejected. not online:', cid)
9085
9318
  return;
@@ -9137,17 +9370,20 @@ class Manager {
9137
9370
  }
9138
9371
 
9139
9372
 
9373
+ // One random byte per CID character.
9140
9374
  anonymousCidRandom(size) {
9141
9375
  return globalThis.crypto.getRandomValues(Buffer.alloc(size))
9142
9376
  }
9143
9377
 
9144
- // '?' + base64url random bytes, never one that is online. Check and set run in the same
9145
- // synchronous turn (CID_REQ handler), so concurrent requests cannot take the same CID.
9146
- // 3 bytes (4 chars) normally; 6 bytes (8 chars) if the short space keeps colliding.
9378
+ // '?' + lowercase Crockford base32 (ANONYMOUS_CID_ALPHABET: no i, l, o, u), never one that is
9379
+ // online. Check and set run in the same synchronous turn (CID_REQ handler), so concurrent
9380
+ // requests cannot take the same CID. 4 characters normally; 8 if the short space keeps colliding.
9147
9381
  issueAnonymousCid() {
9148
- for (const [size, tries] of [[3, 8], [6, 8]]) {
9382
+ for (const [size, tries] of [[4, 8], [8, 8]]) {
9149
9383
  for (let i = 0; i < tries; i++) {
9150
- const cid = '?' + Buffer.from(this.anonymousCidRandom(size)).toString('base64url');
9384
+ let cid = '?';
9385
+ // 32 divides 256, so the low 5 bits of a random byte are uniform.
9386
+ for (const byte of this.anonymousCidRandom(size)) cid += ANONYMOUS_CID_ALPHABET[byte & 31];
9151
9387
  if (!this.cid2remote.has(cid)) return cid
9152
9388
  }
9153
9389
  }
@@ -9440,8 +9676,10 @@ class BohoAuth {
9440
9676
  //7. setting info.
9441
9677
  peer.did = id;
9442
9678
  peer.cid = authInfo.cid;
9443
- peer.nick = authInfo.cid; // temporary: nick as cid
9444
9679
  if (authInfo.uid) peer.uid = authInfo.uid;
9680
+ // Delivery policy of an owned device, in place before the CID is reachable (step 9).
9681
+ peer.ownerUid = uid;
9682
+ peer.rxPolicy = compileDeliveryPolicy(authInfo.rxPolicy, uid);
9445
9683
 
9446
9684
  //8. role and quota; the client is told its quota.
9447
9685
  peer.role = role;
@@ -9993,6 +10231,9 @@ class FileKeyProvider {
9993
10231
  }
9994
10232
 
9995
10233
  const DEVICE_PREFIX = "device:";
10234
+ // Every device CID in use. The account service picks new CIDs outside it, so a device added here
10235
+ // is listed too and no member can be given its CID.
10236
+ const CID_SET = "sets_cid";
9996
10237
 
9997
10238
  class RedisKeyProvider {
9998
10239
  constructor(redisClient) {
@@ -10029,11 +10270,17 @@ class RedisKeyProvider {
10029
10270
  const fields = { 'key': Base64hashKey, 'cid': cid };
10030
10271
  if (role) fields.role = role;
10031
10272
  if (quota) fields.quota = quota;
10032
- return this.redis.hSet(DEVICE_PREFIX + id, fields)
10273
+ const old = await this.redis.hGet(DEVICE_PREFIX + id, 'cid');
10274
+ const result = await this.redis.hSet(DEVICE_PREFIX + id, fields);
10275
+ if (old && old !== cid) await this.redis.sRem(CID_SET, old);
10276
+ if (cid) await this.redis.sAdd(CID_SET, cid);
10277
+ return result
10033
10278
  }
10034
10279
 
10035
10280
  //sudoService call
10036
10281
  async delAuth(id) {
10282
+ const cid = await this.redis.hGet(DEVICE_PREFIX + id, 'cid');
10283
+ if (cid) await this.redis.sRem(CID_SET, cid);
10037
10284
  return this.redis.del(DEVICE_PREFIX + id)
10038
10285
  }
10039
10286
 
@@ -305,6 +305,7 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
305
305
  private _linkHandlers;
306
306
  /** @private @type {Set<string>} */
307
307
  private _listenTags;
308
+ _readyDispatch: boolean;
308
309
  /** @private @type {Set<string>} */
309
310
  private _manualSubscriptions;
310
311
  /**
@@ -485,9 +486,13 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
485
486
  */
486
487
  call(target: string, topic: string, ...args: any[]): Promise<any>;
487
488
  /**
488
- * Subscribes to a channel or channels.
489
+ * Subscribes to a channel or channels on the current, ready connection, at once.
490
+ * Call it from a ready handler (it runs on every connect) or later while ready; it is not
491
+ * repeated after a reconnect. To subscribe before connecting, or for every connection
492
+ * without a ready handler, use listen() or link().
489
493
  * @param {string} tag - The tag(s) of the channel(s) to subscribe to (comma-separated).
490
494
  * @throws {TypeError} If tag is invalid, exceeds the length limit, or contains a direct-receive subscription.
495
+ * @throws {Error} If the connection is not ready (after destroy() it is a no-op instead).
491
496
  */
492
497
  subscribe(tag: string): void;
493
498
  /**
@@ -505,24 +510,26 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
505
510
  * Convenience API for simple clients (for example, CLI tools): register a
506
511
  * tag handler once and remember its subscription in channels. For subscription
507
512
  * tags, register before connection readiness; the CID-ready flow subscribes on initial connection
508
- * and again after reconnect, without application-level ready/subscribe code.
513
+ * and again after reconnect, before 'ready' is emitted, so a ready handler may signal at once.
509
514
  * This does not send a subscription immediately, even if already ready.
510
- * For precise subscription/send ordering or dynamic subscriptions, use
511
- * on() with subscribe() in a ready handler instead.
512
- * Direct signals need no subscription: use on/listen('@') for all direct
513
- * signals, or on/listen('@topic') for an exact topic. Direct handlers can be
514
- * registered before or after readiness, before the message arrives.
515
+ * Do not call listen() inside a ready handler; it throws there, for any tag: a subscription tag
516
+ * would be subscribed only after the next reconnect, and a handler registered on every
517
+ * connect runs once more after each reconnect. In a ready handler use on() and subscribe();
518
+ * for dynamic subscriptions use link().
519
+ * Direct signals need no subscription: use listen('@') during setup, or on('@'), for all
520
+ * direct signals, or '@topic' for an exact topic.
515
521
  * Dispatch is synchronous: '@' first, then '@topic' when tag is not '@'.
516
522
  * Returning false does not cancel dispatch; a thrown error interrupts it.
517
523
  * @param {string} tag - The tag to listen on.
518
524
  * @param {Function} handler - The callback function to handle the signal.
519
525
  * @throws {TypeError} If tag is not a string, handler is not a function, or tag length is invalid.
526
+ * @throws {Error} If called inside a ready handler.
520
527
  */
521
528
  listen(tag: string, handler: Function): void;
522
529
  /**
523
530
  * Associates handlers with a local component for scoped teardown.
524
- * Direct tags (@ or @topic) only register local handlers. Other tags also
525
- * subscribe now and are remembered for reconnection.
531
+ * Direct tags (@ or @topic) only register local handlers. Other tags are remembered for
532
+ * reconnection and subscribed at once on a ready connection; before that, when it becomes ready.
526
533
  * @param {string} to - The local component identifier, not a server target.
527
534
  * @param {string} tag - The exact event tag.
528
535
  * @param {Function} handler - The callback receiving (tag, ...args).
@@ -785,6 +792,7 @@ declare class Manager {
785
792
  oversizeRejected: number;
786
793
  rateLimited: number;
787
794
  peerRxLimitSkipped: number;
795
+ policyDenied: number;
788
796
  };
789
797
  authManager: any;
790
798
  connectionLogger: FileLogger | undefined;
@@ -815,6 +823,20 @@ declare class Manager {
815
823
  get anonymousQuota(): any;
816
824
  accountConnections(uid: any): any;
817
825
  addAccountConnection(remote: any, uid: any): void;
826
+ /**
827
+ * Replace the delivery policy of the connected, owned device with this CID (see deliveryPolicy.js);
828
+ * the next unicast to it already uses the new one. A new login reads the stored policy again.
829
+ * Returns false when no such connection is here or it has no owner (never filtered).
830
+ * Throws on an invalid policy, so a caller cannot install one by mistake.
831
+ */
832
+ setDeliveryPolicy(cid: any, policy: any): boolean;
833
+ /**
834
+ * Count a message a delivery policy kept from `other` (unicast from it, or a publication to it) and,
835
+ * when someone listens, emit 'delivery:denied' on the server with what the server knows of both:
836
+ * { kind: 'unicast' | 'publish', cid, did, owner, other: { cid, uid, ip, authenticated }, at }.
837
+ * An anonymous connection's CID is not reported (random per connection).
838
+ */
839
+ deliveryDenied(device: any, other: any, kind: any): void;
818
840
  removeAccountConnection(remote: any): void;
819
841
  heartbeatTick(): void;
820
842
  addRemote(socket: any, req: any): void;
@@ -305,6 +305,7 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
305
305
  private _linkHandlers;
306
306
  /** @private @type {Set<string>} */
307
307
  private _listenTags;
308
+ _readyDispatch: boolean;
308
309
  /** @private @type {Set<string>} */
309
310
  private _manualSubscriptions;
310
311
  /**
@@ -485,9 +486,13 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
485
486
  */
486
487
  call(target: string, topic: string, ...args: any[]): Promise<any>;
487
488
  /**
488
- * Subscribes to a channel or channels.
489
+ * Subscribes to a channel or channels on the current, ready connection, at once.
490
+ * Call it from a ready handler (it runs on every connect) or later while ready; it is not
491
+ * repeated after a reconnect. To subscribe before connecting, or for every connection
492
+ * without a ready handler, use listen() or link().
489
493
  * @param {string} tag - The tag(s) of the channel(s) to subscribe to (comma-separated).
490
494
  * @throws {TypeError} If tag is invalid, exceeds the length limit, or contains a direct-receive subscription.
495
+ * @throws {Error} If the connection is not ready (after destroy() it is a no-op instead).
491
496
  */
492
497
  subscribe(tag: string): void;
493
498
  /**
@@ -505,24 +510,26 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
505
510
  * Convenience API for simple clients (for example, CLI tools): register a
506
511
  * tag handler once and remember its subscription in channels. For subscription
507
512
  * tags, register before connection readiness; the CID-ready flow subscribes on initial connection
508
- * and again after reconnect, without application-level ready/subscribe code.
513
+ * and again after reconnect, before 'ready' is emitted, so a ready handler may signal at once.
509
514
  * This does not send a subscription immediately, even if already ready.
510
- * For precise subscription/send ordering or dynamic subscriptions, use
511
- * on() with subscribe() in a ready handler instead.
512
- * Direct signals need no subscription: use on/listen('@') for all direct
513
- * signals, or on/listen('@topic') for an exact topic. Direct handlers can be
514
- * registered before or after readiness, before the message arrives.
515
+ * Do not call listen() inside a ready handler; it throws there, for any tag: a subscription tag
516
+ * would be subscribed only after the next reconnect, and a handler registered on every
517
+ * connect runs once more after each reconnect. In a ready handler use on() and subscribe();
518
+ * for dynamic subscriptions use link().
519
+ * Direct signals need no subscription: use listen('@') during setup, or on('@'), for all
520
+ * direct signals, or '@topic' for an exact topic.
515
521
  * Dispatch is synchronous: '@' first, then '@topic' when tag is not '@'.
516
522
  * Returning false does not cancel dispatch; a thrown error interrupts it.
517
523
  * @param {string} tag - The tag to listen on.
518
524
  * @param {Function} handler - The callback function to handle the signal.
519
525
  * @throws {TypeError} If tag is not a string, handler is not a function, or tag length is invalid.
526
+ * @throws {Error} If called inside a ready handler.
520
527
  */
521
528
  listen(tag: string, handler: Function): void;
522
529
  /**
523
530
  * Associates handlers with a local component for scoped teardown.
524
- * Direct tags (@ or @topic) only register local handlers. Other tags also
525
- * subscribe now and are remembered for reconnection.
531
+ * Direct tags (@ or @topic) only register local handlers. Other tags are remembered for
532
+ * reconnection and subscribed at once on a ready connection; before that, when it becomes ready.
526
533
  * @param {string} to - The local component identifier, not a server target.
527
534
  * @param {string} tag - The exact event tag.
528
535
  * @param {Function} handler - The callback receiving (tag, ...args).
@@ -785,6 +792,7 @@ declare class Manager {
785
792
  oversizeRejected: number;
786
793
  rateLimited: number;
787
794
  peerRxLimitSkipped: number;
795
+ policyDenied: number;
788
796
  };
789
797
  authManager: any;
790
798
  connectionLogger: FileLogger | undefined;
@@ -815,6 +823,20 @@ declare class Manager {
815
823
  get anonymousQuota(): any;
816
824
  accountConnections(uid: any): any;
817
825
  addAccountConnection(remote: any, uid: any): void;
826
+ /**
827
+ * Replace the delivery policy of the connected, owned device with this CID (see deliveryPolicy.js);
828
+ * the next unicast to it already uses the new one. A new login reads the stored policy again.
829
+ * Returns false when no such connection is here or it has no owner (never filtered).
830
+ * Throws on an invalid policy, so a caller cannot install one by mistake.
831
+ */
832
+ setDeliveryPolicy(cid: any, policy: any): boolean;
833
+ /**
834
+ * Count a message a delivery policy kept from `other` (unicast from it, or a publication to it) and,
835
+ * when someone listens, emit 'delivery:denied' on the server with what the server knows of both:
836
+ * { kind: 'unicast' | 'publish', cid, did, owner, other: { cid, uid, ip, authenticated }, at }.
837
+ * An anonymous connection's CID is not reported (random per connection).
838
+ */
839
+ deliveryDenied(device: any, other: any, kind: any): void;
818
840
  removeAccountConnection(remote: any): void;
819
841
  heartbeatTick(): void;
820
842
  addRemote(socket: any, req: any): void;