iosignal 9.0.0 → 9.6.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.6.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
 
@@ -7505,6 +7532,8 @@ class RemoteCore {
7505
7532
  this.HOME_CHANNEL = '';
7506
7533
  this.role = 'anonymous'; // set on authentication; see ROLES in BohoAuth
7507
7534
  this.accountUid = null; // counted in manager.accountConnections while authenticated with a uid
7535
+ this.ownerUid = null; // the device's owner (login uid); a web sign-in later changes uid, not this
7536
+ this.rxPolicy = null; // compiled delivery policy of an owned device, see deliveryPolicy.js
7508
7537
  // Quota profile (a server.quotas entry, read live): the anonymous one until authenticated.
7509
7538
  this.quotaName = manager.anonymousQuota;
7510
7539
  this.quota = manager.quotas[this.quotaName];
@@ -8562,6 +8591,145 @@ class Metrics {
8562
8591
 
8563
8592
  }
8564
8593
 
8594
+ /**
8595
+ * Delivery policy: which senders a device accepts CID unicast ('<cid>@topic') from.
8596
+ *
8597
+ * The policy belongs to an owned device (one whose login has a uid) and comes with its login
8598
+ * (authInfo.rxPolicy from the key provider, JSON text or an object) or later from
8599
+ * Manager.setDeliveryPolicy(). A device without an owner uid is never filtered.
8600
+ *
8601
+ * {
8602
+ * v: 1,
8603
+ * mode: 'open' | 'allowlist' | 'denylist', // open: everyone (the default)
8604
+ * anonymous: 'allow' | 'deny', // default: deny for allowlist, allow for denylist
8605
+ * publish: 'all' | 'policy', // who gets its CID publications ('@topic', '@$topic'):
8606
+ * // 'all' subscribers (default), or only those the policy allows
8607
+ * allow: { cids: [], uids: [] },
8608
+ * deny: { cids: [], uids: [] }
8609
+ * }
8610
+ *
8611
+ * Decision, first match wins:
8612
+ * 1. no owner, no policy, mode open -> allow
8613
+ * 2. the device itself, its owner's uid, or a connection with role 'admin' -> allow
8614
+ * 3. sender CID in deny.cids / allow.cids -> deny / allow
8615
+ * 4. sender uid in deny.uids / allow.uids -> deny / allow
8616
+ * 5. anonymous sender (not authenticated, no uid) -> anonymous setting
8617
+ * 6. mode default: allowlist denies, denylist allows
8618
+ *
8619
+ * With publish 'policy', the same decision (subscriber in the sender's place) filters the device's CID
8620
+ * publications and the retained ones a new subscriber would get. Its '@state' close notice included.
8621
+ *
8622
+ * The sender's uid is remote.uid: a device's owner, or the user of a web sign-in on that connection.
8623
+ * Only the server's own view of the sender is used, never anything in the message.
8624
+ */
8625
+
8626
+ const DELIVERY_POLICY_MODES = Object.freeze(['open', 'allowlist', 'denylist']);
8627
+ const DELIVERY_POLICY_MAX_ENTRIES = 200;
8628
+ const ENTRY_MAX_LENGTH = 64;
8629
+ const LISTS = ['cids', 'uids'];
8630
+
8631
+ function entries(name, value) {
8632
+ if (value === undefined || value === null) return []
8633
+ if (!Array.isArray(value)) throw new TypeError(`${name} must be an array`)
8634
+ if (value.length > DELIVERY_POLICY_MAX_ENTRIES) {
8635
+ throw new RangeError(`${name} has more than ${DELIVERY_POLICY_MAX_ENTRIES} entries`)
8636
+ }
8637
+ for (const entry of value) {
8638
+ if (typeof entry !== 'string' || !entry || entry.length > ENTRY_MAX_LENGTH) {
8639
+ throw new TypeError(`${name} entries must be non-empty strings of at most ${ENTRY_MAX_LENGTH} characters`)
8640
+ }
8641
+ }
8642
+ return [...new Set(value)]
8643
+ }
8644
+
8645
+ function lists(name, value) {
8646
+ if (value === undefined || value === null) return { cids: [], uids: [] }
8647
+ if (typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${name} must be an object`)
8648
+ for (const key of Object.keys(value)) {
8649
+ if (!LISTS.includes(key)) throw new TypeError(`unknown ${name}.${key}`)
8650
+ }
8651
+ return { cids: entries(`${name}.cids`, value.cids), uids: entries(`${name}.uids`, value.uids) }
8652
+ }
8653
+
8654
+ /**
8655
+ * A checked copy of a policy with every field present, or null for "no policy" (null, undefined, '').
8656
+ * Accepts JSON text. Throws TypeError/RangeError on an invalid policy.
8657
+ */
8658
+ function normalizeDeliveryPolicy(raw) {
8659
+ if (raw === undefined || raw === null || raw === '') return null
8660
+ let policy = raw;
8661
+ if (typeof raw === 'string') {
8662
+ try { policy = JSON.parse(raw); } catch { throw new TypeError('delivery policy is not valid JSON') }
8663
+ }
8664
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new TypeError('delivery policy must be an object')
8665
+ for (const key of Object.keys(policy)) {
8666
+ if (!['v', 'mode', 'anonymous', 'publish', 'allow', 'deny', 'updatedAt'].includes(key)) throw new TypeError(`unknown delivery policy field ${key}`)
8667
+ }
8668
+ if (policy.v !== undefined && policy.v !== 1) throw new TypeError('delivery policy version must be 1')
8669
+ const mode = policy.mode ?? 'open';
8670
+ if (!DELIVERY_POLICY_MODES.includes(mode)) throw new TypeError(`delivery policy mode must be one of: ${DELIVERY_POLICY_MODES.join(', ')}`)
8671
+ const anonymous = policy.anonymous ?? (mode === 'allowlist' ? 'deny' : 'allow');
8672
+ if (anonymous !== 'allow' && anonymous !== 'deny') throw new TypeError("delivery policy anonymous must be 'allow' or 'deny'")
8673
+ const publish = policy.publish ?? 'all';
8674
+ if (publish !== 'all' && publish !== 'policy') throw new TypeError("delivery policy publish must be 'all' or 'policy'")
8675
+ const normalized = { v: 1, mode, anonymous, publish, allow: lists('allow', policy.allow), deny: lists('deny', policy.deny) };
8676
+ if (policy.updatedAt !== undefined) {
8677
+ if (!Number.isSafeInteger(policy.updatedAt) || policy.updatedAt < 0) throw new TypeError('delivery policy updatedAt must be a time in ms')
8678
+ normalized.updatedAt = policy.updatedAt;
8679
+ }
8680
+ return normalized
8681
+ }
8682
+
8683
+ /**
8684
+ * The form Manager checks per message, or null when nothing is filtered (no owner, no policy, open).
8685
+ * Never throws: a stored policy that cannot be read only lets the owner's own senders through
8686
+ * (fail closed), since ignoring it would deliver what the owner asked to block.
8687
+ */
8688
+ function compileDeliveryPolicy(raw, ownerUid) {
8689
+ if (typeof ownerUid !== 'string' || !ownerUid) return null
8690
+ let policy;
8691
+ try {
8692
+ policy = normalizeDeliveryPolicy(raw);
8693
+ } catch (error) {
8694
+ console.warn(`[iosignal] unreadable delivery policy of uid ${ownerUid}, owner only:`, error.message);
8695
+ policy = { mode: 'allowlist', anonymous: 'deny', publish: 'policy', allow: { cids: [], uids: [] }, deny: { cids: [], uids: [] } };
8696
+ }
8697
+ if (!policy || policy.mode === 'open') return null
8698
+ return Object.freeze({
8699
+ owner: ownerUid,
8700
+ mode: policy.mode,
8701
+ defaultAllow: policy.mode === 'denylist',
8702
+ anonymousAllow: policy.anonymous === 'allow',
8703
+ filterPublish: policy.publish === 'policy',
8704
+ allowCids: new Set(policy.allow.cids),
8705
+ denyCids: new Set(policy.deny.cids),
8706
+ allowUids: new Set(policy.allow.uids),
8707
+ denyUids: new Set(policy.deny.uids)
8708
+ })
8709
+ }
8710
+
8711
+ /** True if `target` (whose compiled policy is target.rxPolicy) accepts a unicast from `sender`. */
8712
+ function deliveryAllowed(target, sender) {
8713
+ const policy = target.rxPolicy;
8714
+ if (!policy) return true
8715
+ if (sender === target) return true
8716
+ const authorized = sender.boho?.isAuthorized === true;
8717
+ const uid = typeof sender.uid === 'string' && sender.uid ? sender.uid : null;
8718
+ if (uid === policy.owner) return true
8719
+ if (authorized && sender.role === 'admin') return true
8720
+ // An anonymous connection's CID is random per connection, so CID rules are for authenticated ones.
8721
+ if (authorized) {
8722
+ if (policy.denyCids.has(sender.cid)) return false
8723
+ if (policy.allowCids.has(sender.cid)) return true
8724
+ }
8725
+ if (uid) {
8726
+ if (policy.denyUids.has(uid)) return false
8727
+ if (policy.allowUids.has(uid)) return true
8728
+ }
8729
+ if (!authorized && !uid) return policy.anonymousAllow
8730
+ return policy.defaultAllow
8731
+ }
8732
+
8565
8733
  const encoder = new TextEncoder();
8566
8734
  const decoder$1 = new TextDecoder();
8567
8735
 
@@ -8579,7 +8747,8 @@ class Manager {
8579
8747
  // Cumulative since the server started; never reset (readers compute rates from deltas).
8580
8748
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
8581
8749
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
8582
- peerRxLimitSkipped: 0 }; // messages not sent: larger than the peer's advertised RX buffer
8750
+ peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
8751
+ policyDenied: 0 }; // unicasts and CID publications a device's delivery policy kept back
8583
8752
 
8584
8753
  this.authManager = authManager;
8585
8754
 
@@ -8655,6 +8824,37 @@ class Manager {
8655
8824
  this.accountConnectionCounts.set(uid, this.accountConnections(uid) + 1);
8656
8825
  }
8657
8826
 
8827
+ /**
8828
+ * Replace the delivery policy of the connected, owned device with this CID (see deliveryPolicy.js);
8829
+ * the next unicast to it already uses the new one. A new login reads the stored policy again.
8830
+ * Returns false when no such connection is here or it has no owner (never filtered).
8831
+ * Throws on an invalid policy, so a caller cannot install one by mistake.
8832
+ */
8833
+ setDeliveryPolicy(cid, policy) {
8834
+ const remote = this.cid2remote.get(cid);
8835
+ if (!remote?.boho.isAuthorized || !remote.ownerUid) return false
8836
+ normalizeDeliveryPolicy(policy);
8837
+ remote.rxPolicy = compileDeliveryPolicy(policy, remote.ownerUid);
8838
+ return true
8839
+ }
8840
+
8841
+ /**
8842
+ * Count a message a delivery policy kept from `other` (unicast from it, or a publication to it) and,
8843
+ * when someone listens, emit 'delivery:denied' on the server with what the server knows of both:
8844
+ * { kind: 'unicast' | 'publish', cid, did, owner, other: { cid, uid, ip, authenticated }, at }.
8845
+ * An anonymous connection's CID is not reported (random per connection).
8846
+ */
8847
+ deliveryDenied(device, other, kind) {
8848
+ this.counters.policyDenied++;
8849
+ if (!this.server?.listenerCount?.('delivery:denied')) return
8850
+ const authenticated = other.boho?.isAuthorized === true;
8851
+ this.server.emit('delivery:denied', {
8852
+ kind, cid: device.cid, did: device.did, owner: device.ownerUid,
8853
+ other: { cid: authenticated ? other.cid : null, uid: other.uid || null, ip: other.ip ?? null, authenticated },
8854
+ at: Date.now()
8855
+ });
8856
+ }
8857
+
8658
8858
  removeAccountConnection(remote) {
8659
8859
  const uid = remote.accountUid;
8660
8860
  if (!uid) return
@@ -8844,6 +9044,8 @@ class Manager {
8844
9044
  if (tag.indexOf('$') == 0) return ['err', 'prefix $ is reserved for userSet tag.']
8845
9045
 
8846
9046
  let cidIndex = tag.indexOf('@');
9047
+ // A device whose policy also covers its publications: each subscriber is checked (see deliveryPolicy.js).
9048
+ const publisher = cidIndex === 0 && remote.rxPolicy?.filterPublish ? remote : null;
8847
9049
  if (cidIndex === 0) {
8848
9050
  // ** CID_PUB multi-cast
8849
9051
  // [cid_pub] @topic , @$retainTopic
@@ -8855,14 +9057,20 @@ class Manager {
8855
9057
  } else if (cidIndex > 0) {
8856
9058
  // uni-cast.
8857
9059
  let targetCId = tag.split('@')[0];
8858
- if (this.cid2remote.has(targetCId)) {
9060
+ const target = this.cid2remote.get(targetCId);
9061
+ if (target && !deliveryAllowed(target, remote)) {
9062
+ // Same answer as an offline CID: a sender cannot tell it is blocked, or probe the policy.
9063
+ this.deliveryDenied(target, remote, 'unicast');
9064
+ return ['err', 'Invalid cid']
9065
+ }
9066
+ if (target) {
8859
9067
  //rm cid from tag.
8860
9068
  let ommitCIdTag = '@' + tag.split('@')[1];
8861
9069
  // console.log('uni-cast tag change from', tag, 'to' , ommitCIdTag )
8862
9070
  message = this.getNewSignalTagMessage(message, ommitCIdTag);
8863
9071
  if (!message) return ['err', 'Tag exceeds 255 UTF-8 bytes']
8864
9072
  // console.log(`origin tag: ${tag} omitTag: ${this.getSignalTag(message)}`)
8865
- this.cid2remote.get(targetCId).send_enc_mode(message);
9073
+ target.send_enc_mode(message);
8866
9074
  return ['ok', 1]
8867
9075
  }
8868
9076
  return ['err', 'Invalid cid']
@@ -8915,11 +9123,13 @@ class Manager {
8915
9123
  // console.log('## null remote' )
8916
9124
  break;
8917
9125
  }
9126
+ if (publisher && !deliveryAllowed(publisher, c)) {
9127
+ this.deliveryDenied(publisher, c, 'publish');
9128
+ continue
9129
+ }
8918
9130
  // change: from v4.x allow receiveSelfMessages.
8919
- // if (c !== remote) {
8920
- c.send_enc_mode(message);
8921
- sentCounter++;
8922
- // }
9131
+ c.send_enc_mode(message);
9132
+ sentCounter++;
8923
9133
  }
8924
9134
 
8925
9135
  this.counters.deliveryAttempts += sentCounter;
@@ -9078,8 +9288,13 @@ class Manager {
9078
9288
  let cid = tag.split('@')[0];
9079
9289
  cid = cid.split(this.CID_PREFIX)[1];
9080
9290
  let retainTag = tag.split('@')[1];
9081
- if (this.cid2remote.has(cid)) {
9082
- retainMessage = this.cid2remote.get(cid).retain_signal.get(retainTag);
9291
+ const owner = this.cid2remote.get(cid);
9292
+ if (owner) {
9293
+ if (owner.rxPolicy?.filterPublish && !deliveryAllowed(owner, remote)) {
9294
+ this.deliveryDenied(owner, remote, 'publish');
9295
+ return;
9296
+ }
9297
+ retainMessage = owner.retain_signal.get(retainTag);
9083
9298
  } else {
9084
9299
  // console.log('cid subscribe is rejected. not online:', cid)
9085
9300
  return;
@@ -9442,6 +9657,9 @@ class BohoAuth {
9442
9657
  peer.cid = authInfo.cid;
9443
9658
  peer.nick = authInfo.cid; // temporary: nick as cid
9444
9659
  if (authInfo.uid) peer.uid = authInfo.uid;
9660
+ // Delivery policy of an owned device, in place before the CID is reachable (step 9).
9661
+ peer.ownerUid = uid;
9662
+ peer.rxPolicy = compileDeliveryPolicy(authInfo.rxPolicy, uid);
9445
9663
 
9446
9664
  //8. role and quota; the client is told its quota.
9447
9665
  peer.role = role;
@@ -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;