@cero-base/core 3.4.1 → 3.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.
package/README.md CHANGED
@@ -24,9 +24,9 @@ Each primitive but `Identity` is a `ReadyResource`: construct it, `await x.ready
24
24
 
25
25
  | Subpath | What it gives you |
26
26
  | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
- | `@cero-base/core` | Every subpath below in one import, but `/database/encryption` and `/blobs/server` |
27
+ | `@cero-base/core` | Every subpath below in one import, but `/database/encryption`, `/blobs/server` and `/call` |
28
28
  | `@cero-base/core/identity` | `Identity`: a keypair from a seed; signs, verifies, seals, names a swarm topic |
29
- | `@cero-base/core/network` | `Network`: Hyperswarm plus wakeup, with managed discovery sessions; `channelTopic` |
29
+ | `@cero-base/core/network` | `Network`: Hyperjoin plus wakeup, one discovery session per topic; `channelTopic` |
30
30
  | `@cero-base/core/database` | `Database`: multi-writer, permissions checked at apply, hooks, key rotation |
31
31
  | `@cero-base/core/database/encryption` | `Keyring`, `EpochAutobee`, `blobEpochKey`, `loadEpochs`, `seal`, `opened`, `wraps`, `epochEntries`: the key epochs a `Database` rotates through |
32
32
  | `@cero-base/core/mailbox` | `Mailbox`: messages to an address, delivered directly or held by a mirror |
@@ -36,6 +36,7 @@ Each primitive but `Identity` is a `ReadyResource`: construct it, `await x.ready
36
36
  | `@cero-base/core/blobs` | `Blobs`: bytes in a Hyperblobs core, addressed by position, encrypted; `encodeId`, `decodeId` |
37
37
  | `@cero-base/core/blobs/codec` | `encodeId`, `decodeId`: a core key, blob id and type as one string |
38
38
  | `@cero-base/core/blobs/server` | `FileServer`: a file id served at a local url |
39
+ | `@cero-base/core/call` | `Call`, `Peers`, `Bridge`: connections by key and a local UDP port per device for a call's media |
39
40
  | `@cero-base/core/rpc` | `RPCServer`, `RPCClient`, `bindCodec`: a typed channel over any duplex stream |
40
41
  | `@cero-base/core/schema` | `t`, `schema`: the field types and the wrapper a build takes |
41
42
  | `@cero-base/core/utils` | `WRITE`, `INVITE`, `ASSIGN`, `REMOVE`, `can`, `grants`, `outranks`, `isRank`, `filter`, `searchHit`, `onAbort`, `subscribe`, `admission`, `joining`, `checkFields`, `checkRequired`, `stamp` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "3.4.1",
3
+ "version": "3.6.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -77,6 +77,10 @@
77
77
  "types": "./types/push/index.d.ts",
78
78
  "default": "./src/push/index.js"
79
79
  },
80
+ "./call": {
81
+ "types": "./types/call/index.d.ts",
82
+ "default": "./src/call/index.js"
83
+ },
80
84
  "./invite": {
81
85
  "types": "./types/pairing/invite.d.ts",
82
86
  "default": "./src/pairing/invite.js"
@@ -152,32 +156,33 @@
152
156
  },
153
157
  "dependencies": {
154
158
  "@hyperswarm/secret-stream": "^6.9.2",
155
- "autobee": "2.14.0",
159
+ "autobee": "2.15.0",
156
160
  "b4a": "^1.9.0",
157
161
  "bare-crypto": "^1.16.1",
158
- "bare-fs": "^4.8.5",
162
+ "bare-fs": "^4.8.7",
159
163
  "bare-path": "^3.1.3",
160
164
  "bip39-mnemonic": "^2.5.0",
161
- "blind-peering": "^2.14.0",
162
- "blind-push": "^1.2.1",
163
- "compact-encoding": "^3.7.0",
165
+ "blind-peering": "^2.15.0",
166
+ "blind-push": "^1.3.0",
167
+ "compact-encoding": "^3.7.1",
164
168
  "corestore": "^7.16.1",
165
169
  "framed-stream": "^1.0.1",
166
170
  "hrpc": "^4.3.2",
167
171
  "hyperblobs": "^2.13.0",
168
- "hypercore": "^11.40.4",
172
+ "hypercore": "^11.40.5",
169
173
  "hypercore-blob-server": "^1.15.1",
170
174
  "hypercore-crypto": "^3.7.0",
171
175
  "hypercore-id-encoding": "^1.3.0",
172
176
  "hypercore-storage": "^3.4.0",
173
177
  "hyperdb": "^6.11.2",
174
- "hyperdht": "^6.36.0",
178
+ "hyperdht": "^6.37.0",
175
179
  "hyperdispatch": "^1.6.0",
180
+ "hyperjoin": "^1.5.0",
176
181
  "hyperschema": "^1.26.2",
177
- "hyperswarm": "^4.17.2",
178
182
  "keet-identity-key": "^3.2.0",
179
183
  "ms": "^2.1.3",
180
- "protomux-wakeup": "^2.9.2",
184
+ "protomux": "^3.13.1",
185
+ "protomux-wakeup": "^2.9.3",
181
186
  "ready-resource": "^1.2.0",
182
187
  "safety-catch": "^1.0.3",
183
188
  "sodium-universal": "^5.0.1",
@@ -190,12 +195,13 @@
190
195
  "bare-events": "^2.9.2",
191
196
  "bare-fetch": "^3.5.0",
192
197
  "bare-process": "^4.5.1",
193
- "bare-subprocess": "^6.2.2",
198
+ "bare-subprocess": "^6.2.3",
194
199
  "bare-url": "^2.5.8",
195
- "blind-peer": "^3.18.3",
200
+ "blind-peer": "^3.20.1",
196
201
  "blind-push-gateway": "^1.0.0",
197
- "brittle": "^4.5.0",
198
- "protomux": "^3.13.1",
202
+ "blind-relay": "^1.6.1",
203
+ "brittle": "^4.6.0",
204
+ "hyperswarm": "^4.17.2",
199
205
  "protomux-rpc-router": "^1.3.0",
200
206
  "typescript": "^7.0.2",
201
207
  "which-runtime": "^1.4.0"
@@ -0,0 +1,262 @@
1
+ import EventEmitter from 'events'
2
+ import Protomux from 'protomux'
3
+ import c from 'compact-encoding'
4
+ import b4a from 'b4a'
5
+ import safetyCatch from 'safety-catch'
6
+
7
+ import { CeroError } from '../lib/errors.js'
8
+ import { getEncoding } from '../lib/spec/index.js'
9
+
10
+ const HOST = '127.0.0.1'
11
+ const PROTOCOL = 'cero/call'
12
+ const MARKER = 0xca
13
+ const ALIASES = 256
14
+ // an offer or an answer for three lanes is a few KB
15
+ const SIGNAL = 65536
16
+ const TYPES = ['offer', 'answer']
17
+ const Open = getEncoding('@cero/call-open')
18
+ const Signal = getEncoding('@cero/call-signal')
19
+ // a negotiation is a handful of signals: more waiting than this, the channel is not coming
20
+ const SIGNALS = 32
21
+ // the first handshake packets and a few hundred ms of audio: older media is too late to play
22
+ const DATAGRAMS = 64
23
+
24
+ /** @type {WeakMap<object, Link>} */
25
+ const links = new WeakMap()
26
+
27
+ // the datagrams of one connection, routed to its bridges by the alias they carry
28
+ class Link {
29
+ constructor(stream) {
30
+ this.stream = stream
31
+ /** @type {Map<number, Bridge>} By the other side's alias. */
32
+ this.bridges = new Map()
33
+ /** @type {Set<number>} This side's aliases in use. */
34
+ this.aliases = new Set()
35
+ /** @type {Set<string>} The ids of the bridges, in hex. */
36
+ this.ids = new Set()
37
+ this.last = ALIASES - 1
38
+ this._onmessage = (msg) => {
39
+ if (msg[1] !== MARKER) return
40
+ this.bridges.get(msg[0])?._inbound(msg.subarray(2))
41
+ }
42
+ // as they are: what an app's WebRTC sends is encrypted end to end already
43
+ stream.rawStream.on('message', this._onmessage)
44
+ }
45
+
46
+ static from(stream) {
47
+ let link = links.get(stream)
48
+ if (!link) {
49
+ link = new Link(stream)
50
+ links.set(stream, link)
51
+ }
52
+ return link
53
+ }
54
+
55
+ // the one least recently handed out, so a late datagram for a closed bridge misses the next one
56
+ alias() {
57
+ for (let i = 1; i <= ALIASES; i++) {
58
+ const alias = (this.last + i) % ALIASES
59
+ if (this.aliases.has(alias)) continue
60
+ this.aliases.add(alias)
61
+ this.last = alias
62
+ return alias
63
+ }
64
+ throw CeroError.CONFLICT(`a connection carries at most ${ALIASES} bridges`)
65
+ }
66
+
67
+ release(bridge) {
68
+ this.aliases.delete(bridge.alias)
69
+ this.ids.delete(bridge._key)
70
+ this.bridges.delete(bridge.remote)
71
+ if (this.aliases.size > 0) return
72
+ this.stream.rawStream.off('message', this._onmessage)
73
+ links.delete(this.stream)
74
+ }
75
+ }
76
+
77
+ function keep(queue, item, cap) {
78
+ if (queue.length === cap) queue.shift()
79
+ queue.push(item)
80
+ }
81
+
82
+ /**
83
+ * A signal as it crosses: `INVALID` for what is no offer or answer, or is over 64 KiB.
84
+ *
85
+ * @param {{ type: 'offer' | 'answer', sdp: string }} signal
86
+ * @returns {{ type: number, sdp: string }}
87
+ */
88
+ export function encode(signal) {
89
+ const type = TYPES.indexOf(signal?.type)
90
+ if (type < 0 || typeof signal.sdp !== 'string') {
91
+ throw CeroError.INVALID('a signal is an offer or an answer')
92
+ }
93
+ if (b4a.byteLength(signal.sdp) > SIGNAL) {
94
+ throw CeroError.INVALID(`a signal is at most ${SIGNAL} bytes`)
95
+ }
96
+ return { type, sdp: signal.sdp }
97
+ }
98
+
99
+ /**
100
+ * A local UDP port for one call over one open connection: what is sent to `port` from this host
101
+ * reaches the bridge of the same `id` on the other end, which hands it to the local port that last
102
+ * sent to it. Media goes as it is, may be dropped and never waits behind other media. Signals are
103
+ * WebRTC descriptions, in order.
104
+ */
105
+ export class Bridge extends EventEmitter {
106
+ /**
107
+ * @param {import('@hyperswarm/secret-stream')} stream An open connection.
108
+ * @param {{ id: Uint8Array, udx: import('udx-native') }} opts `id` names the call on both ends; `udx` makes the socket, the DHT's.
109
+ */
110
+ constructor(stream, { id, udx }) {
111
+ super()
112
+ if (!id) throw CeroError.REQUIRED('id')
113
+ if (!udx) throw CeroError.REQUIRED('udx')
114
+ const link = Link.from(stream)
115
+ const key = b4a.toString(id, 'hex')
116
+ if (link.ids.has(key)) throw CeroError.CONFLICT('this connection has a bridge for this id')
117
+ /** @type {import('@hyperswarm/secret-stream')} */
118
+ this.stream = stream
119
+ this.id = id
120
+ /** This side's alias, at the head of each datagram it sends. */
121
+ this.alias = link.alias()
122
+ /** The other side's, -1 until the channel opens. */
123
+ this.remote = -1
124
+ this.opened = false
125
+ /** The other end routes this side's datagrams: media flows. */
126
+ this.routed = false
127
+ this.closed = false
128
+ /** The local port media last came from; 0 before any. */
129
+ this.sender = 0
130
+ /** @type {import('udx-native/lib/socket.js')} */
131
+ this.socket = udx.createSocket()
132
+ this.socket.bind(0, HOST)
133
+ /** @type {number} The port to send media to. */
134
+ this.port = this.socket.address().port
135
+ /** @private */
136
+ this._key = key
137
+ /** @private */
138
+ this._link = link
139
+ /** @private */
140
+ this._prefix = b4a.from([this.alias, MARKER])
141
+ /** @private */
142
+ this._out = []
143
+ /** @private */
144
+ this._in = []
145
+ /** @private */
146
+ this._signals = []
147
+ /** @private */
148
+ this._closing = null
149
+ /** @private */
150
+ this._channel = null
151
+ /** @private */
152
+ this._mux = Protomux.from(stream)
153
+ /** @private */
154
+ this._onclose = () => this.close()
155
+ link.ids.add(key)
156
+ this.socket.on('message', (buf, { host, port }) => this._outbound(buf, host, port))
157
+ stream.once('close', this._onclose)
158
+ // the other end turns this open down while it has no bridge for the id, and opens itself once it has
159
+ this._mux.pair({ protocol: PROTOCOL, id }, () => this._connect())
160
+ this._connect()
161
+ }
162
+
163
+ /**
164
+ * Send a description to the other end, in order; kept until the channel opens.
165
+ *
166
+ * @param {{ type: 'offer' | 'answer', sdp: string }} signal
167
+ * @returns {void}
168
+ */
169
+ signal(signal) {
170
+ const message = encode(signal)
171
+ if (this.opened) this._channel.messages[0].send(message)
172
+ else keep(this._signals, message, SIGNALS)
173
+ }
174
+
175
+ /** @returns {Promise<void>} Resolves once the socket is closed. */
176
+ close() {
177
+ if (this._closing) return this._closing
178
+ this._closing = this.socket.close().catch(safetyCatch)
179
+ this.closed = true
180
+ this.stream.off('close', this._onclose)
181
+ this._mux.unpair({ protocol: PROTOCOL, id: this.id })
182
+ this._link.release(this)
183
+ this._channel?.close()
184
+ this._out = []
185
+ this._in = []
186
+ this._signals = []
187
+ this.emit('close')
188
+ return this._closing
189
+ }
190
+
191
+ /** @private */
192
+ _connect() {
193
+ const channel = this._mux.createChannel({
194
+ protocol: PROTOCOL,
195
+ id: this.id,
196
+ handshake: Open,
197
+ onopen: ({ alias }) => this._open(alias),
198
+ onclose: () => this.opened && this.close(),
199
+ messages: [
200
+ { encoding: Signal, onmessage: (message) => this._signal(message) },
201
+ { encoding: c.none, onmessage: () => this._routed() }
202
+ ]
203
+ })
204
+ // the other end opened a second channel for the id while this one is open
205
+ if (!channel) return
206
+ this._channel = channel
207
+ channel.open({ alias: this.alias })
208
+ }
209
+
210
+ // a type this side does not know, or a description past the cap, closes the bridge
211
+ /** @private */
212
+ _signal({ type, sdp }) {
213
+ if (!TYPES[type] || b4a.byteLength(sdp) > SIGNAL) this.close()
214
+ else this.emit('signal', { type: TYPES[type], sdp })
215
+ }
216
+
217
+ /** @private */
218
+ _open(alias) {
219
+ this.remote = alias
220
+ this._link.bridges.set(alias, this)
221
+ this.opened = true
222
+ for (const data of this._signals) this._channel.messages[0].send(data)
223
+ this._signals = []
224
+ // a datagram is not ordered with the stream, so one sent at the open could beat it there
225
+ this._channel.messages[1].send(null)
226
+ this.emit('open')
227
+ }
228
+
229
+ /** @private */
230
+ _routed() {
231
+ this.routed = true
232
+ for (const buf of this._out) this._forward(buf)
233
+ this._out = []
234
+ }
235
+
236
+ /** @private */
237
+ _outbound(buf, host, port) {
238
+ if (host !== HOST) return
239
+ // an app's connection made over sends from a new port: media goes back to the live one
240
+ if (port !== this.sender) this._follow(port)
241
+ if (this.routed) this._forward(buf)
242
+ else keep(this._out, buf, DATAGRAMS)
243
+ }
244
+
245
+ /** @private */
246
+ _follow(port) {
247
+ this.sender = port
248
+ for (const queued of this._in) this.socket.trySend(queued, port, HOST)
249
+ this._in = []
250
+ }
251
+
252
+ /** @private */
253
+ _inbound(buf) {
254
+ if (this.sender) this.socket.trySend(buf, this.sender, HOST)
255
+ else keep(this._in, buf, DATAGRAMS)
256
+ }
257
+
258
+ /** @private */
259
+ _forward(buf) {
260
+ this.stream.rawStream.trySend(b4a.concat([this._prefix, buf]))
261
+ }
262
+ }
@@ -0,0 +1,150 @@
1
+ import ReadyResource from 'ready-resource'
2
+ import b4a from 'b4a'
3
+
4
+ import { CeroError } from '../lib/errors.js'
5
+ import { Peers, toId } from './peers.js'
6
+ import { Bridge, encode } from './bridge.js'
7
+
8
+ export { Peers, Bridge }
9
+
10
+ /**
11
+ * @typedef {object} CallOpts
12
+ * @property {import('hyperdht')} dht The DHT to connect on, the network's.
13
+ * @property {{ publicKey: Uint8Array, secretKey: Uint8Array }} keyPair This device's call key pair: the key the others hold.
14
+ * @property {string | Uint8Array} id Names the call on every device in it.
15
+ * @property {Array<string | Uint8Array> | null} [relayThrough] Blind relay keys, the network's.
16
+ */
17
+
18
+ /**
19
+ * The media transport of one call: a connection to each device in it and, over each, a local port
20
+ * for the app's WebRTC to send to. Events: `'peer'(key, port)` when a device's port opens or
21
+ * changes, also for the ones already open when a listener is added; `'peer-close'(key)` once no
22
+ * connection to it is open or opening; `'signal'(key, { type, sdp })`.
23
+ */
24
+ export class Call extends ReadyResource {
25
+ /** @param {CallOpts} opts */
26
+ constructor({ dht, keyPair, id, relayThrough } = /** @type {CallOpts} */ ({})) {
27
+ super()
28
+ if (!id) throw CeroError.REQUIRED('id')
29
+ /** @private */
30
+ this._peers = new Peers(dht, keyPair, { relayThrough })
31
+ /** @type {import('hyperdht')} */
32
+ this.dht = dht
33
+ this.id = typeof id === 'string' ? b4a.from(id) : id
34
+ /** @type {Map<string, number>} The local port of each device, by key in hex, from its `'peer'` to its `'peer-close'`. */
35
+ this.peers = new Map()
36
+ /** @private @type {Map<Bridge, string>} Oldest first. */
37
+ this._bridges = new Map()
38
+ this._peers.on('connection', (stream) => this._bridge(stream))
39
+ this._peers.on('gone', (id) => this._announce(id))
40
+ this.on('newListener', (event, fn) => event === 'peer' && this._replay(fn))
41
+ }
42
+
43
+ /** @returns {Map<string, import('@hyperswarm/secret-stream')>} The open connection to each device. */
44
+ get connections() {
45
+ return this._peers.connections
46
+ }
47
+
48
+ /** @private */
49
+ async _open() {
50
+ await this._peers.ready()
51
+ }
52
+
53
+ /** @private */
54
+ async _close() {
55
+ const bridges = [...this._bridges.keys()]
56
+ await this._peers.close()
57
+ await Promise.all(bridges.map((bridge) => bridge.close()))
58
+ }
59
+
60
+ /**
61
+ * The devices to hold: the call's other participants, by their call keys.
62
+ *
63
+ * @param {Array<string | Uint8Array>} keys
64
+ * @returns {void}
65
+ */
66
+ set(keys) {
67
+ this._peers.set(keys)
68
+ }
69
+
70
+ /**
71
+ * Send a WebRTC description to a device, on its newest connection; dropped when there is none.
72
+ *
73
+ * @param {string | Uint8Array} key
74
+ * @param {{ type: 'offer' | 'answer', sdp: string }} signal
75
+ * @returns {void}
76
+ */
77
+ signal(key, signal) {
78
+ const bridge = this._current(key)
79
+ if (bridge) bridge.signal(signal)
80
+ else encode(signal) // one that is no description throws, whether or not it would be sent
81
+ }
82
+
83
+ /** @returns {Promise<void>} */
84
+ suspend() {
85
+ return this._peers.suspend()
86
+ }
87
+
88
+ /** @returns {Promise<void>} */
89
+ resume() {
90
+ return this._peers.resume()
91
+ }
92
+
93
+ /** @private */
94
+ _bridge(stream) {
95
+ const id = b4a.toString(stream.remotePublicKey, 'hex')
96
+ const bridge = new Bridge(stream, { id: this.id, udx: this.dht.udx })
97
+ this._bridges.set(bridge, id)
98
+ bridge.on('open', () => this._announce(id))
99
+ bridge.on('signal', (data) => this._heard(bridge, id, data))
100
+ bridge.on('close', () => {
101
+ this._bridges.delete(bridge)
102
+ this._announce(id)
103
+ })
104
+ }
105
+
106
+ // a connection another took over from carries nothing more: what comes on it late is for the
107
+ // WebRTC made over it, which both sides let go
108
+ /** @private */
109
+ _heard(bridge, id, data) {
110
+ if (this.peers.get(id) === bridge.port) this.emit('signal', id, data)
111
+ }
112
+
113
+ /** @private */
114
+ _current(key) {
115
+ const id = toId(key)
116
+ return this._newest(id, true) || this._newest(id, false)
117
+ }
118
+
119
+ /** @private */
120
+ _newest(id, open) {
121
+ let found = null
122
+ for (const [bridge, key] of this._bridges) {
123
+ if (key === id && (bridge.opened || !open)) found = bridge
124
+ }
125
+ return found
126
+ }
127
+
128
+ // a connection still opening keeps the device on its last port: it opens, or closes within its own
129
+ // timeouts and the 3 s the hello has
130
+ /** @private */
131
+ _announce(id) {
132
+ let port = this._newest(id, true)?.port
133
+ if (port === undefined && (this._newest(id, false) || this._peers.connecting(id))) {
134
+ port = this.peers.get(id)
135
+ }
136
+ if (port === this.peers.get(id)) return
137
+ if (port === undefined) {
138
+ this.peers.delete(id)
139
+ this.emit('peer-close', id)
140
+ } else {
141
+ this.peers.set(id, port)
142
+ this.emit('peer', id, port)
143
+ }
144
+ }
145
+
146
+ /** @private */
147
+ _replay(fn) {
148
+ for (const [id, port] of this.peers) queueMicrotask(() => fn(id, port))
149
+ }
150
+ }