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