@zero-server/webrtc 0.9.7

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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +37 -0
  3. package/index.d.ts +2 -0
  4. package/index.js +53 -0
  5. package/lib/auth/index.js +1 -0
  6. package/lib/debug.js +372 -0
  7. package/lib/errors.js +1 -0
  8. package/lib/middleware/index.js +1 -0
  9. package/lib/observe/index.js +1 -0
  10. package/lib/webrtc/bot.js +361 -0
  11. package/lib/webrtc/cli.js +182 -0
  12. package/lib/webrtc/cluster.js +350 -0
  13. package/lib/webrtc/e2ee.js +282 -0
  14. package/lib/webrtc/ice.js +370 -0
  15. package/lib/webrtc/index.js +132 -0
  16. package/lib/webrtc/joinToken.js +116 -0
  17. package/lib/webrtc/observe.js +229 -0
  18. package/lib/webrtc/peer.js +116 -0
  19. package/lib/webrtc/room.js +171 -0
  20. package/lib/webrtc/sdp.js +508 -0
  21. package/lib/webrtc/sfu/index.js +201 -0
  22. package/lib/webrtc/sfu/livekit.js +301 -0
  23. package/lib/webrtc/sfu/mediasoup.js +317 -0
  24. package/lib/webrtc/sfu/memory.js +204 -0
  25. package/lib/webrtc/signaling.js +546 -0
  26. package/lib/webrtc/stun.js +492 -0
  27. package/lib/webrtc/turn/codec.js +370 -0
  28. package/lib/webrtc/turn/credentials.js +141 -0
  29. package/lib/webrtc/turn/server.js +633 -0
  30. package/lib/ws/index.js +1 -0
  31. package/package.json +62 -0
  32. package/types/app.d.ts +223 -0
  33. package/types/auth.d.ts +520 -0
  34. package/types/body.d.ts +14 -0
  35. package/types/cli.d.ts +2 -0
  36. package/types/cluster.d.ts +75 -0
  37. package/types/env.d.ts +80 -0
  38. package/types/errors.d.ts +316 -0
  39. package/types/fetch.d.ts +43 -0
  40. package/types/grpc.d.ts +432 -0
  41. package/types/index.d.ts +396 -0
  42. package/types/lifecycle.d.ts +60 -0
  43. package/types/middleware.d.ts +320 -0
  44. package/types/observe.d.ts +304 -0
  45. package/types/orm.d.ts +1887 -0
  46. package/types/request.d.ts +109 -0
  47. package/types/response.d.ts +157 -0
  48. package/types/router.d.ts +78 -0
  49. package/types/sse.d.ts +78 -0
  50. package/types/webrtc.d.ts +501 -0
  51. package/types/websocket.d.ts +126 -0
@@ -0,0 +1,361 @@
1
+ /**
2
+ * @module webrtc/bot
3
+ * @description Server-side WebRTC peer ("bot") built on the `wrtc`
4
+ * peerDependency.
5
+ *
6
+ * `spawnBotPeer({hub, room, ...})` attaches an in-process peer to a
7
+ * {@link SignalingHub}, joins a room, and drives a real
8
+ * {@link RTCPeerConnection} per remote peer (using the Node.js `wrtc`
9
+ * binding). It implements the standard JSEP perfect-negotiation
10
+ * pattern and is designed for headless workloads such as recording,
11
+ * transcription, AI agents, and SFU verification harnesses.
12
+ *
13
+ * The `wrtc` peerDependency is loaded lazily; in production any of
14
+ * `wrtc` or `@roamhq/wrtc` is acceptable. Tests inject a fake via
15
+ * `opts.wrtc`.
16
+ */
17
+ 'use strict';
18
+
19
+ const { EventEmitter } = require('node:events');
20
+ const { WebRTCError } = require('../errors');
21
+
22
+ /**
23
+ * Spawn a server-side bot peer that joins `room` on the given hub.
24
+ *
25
+ * @param {object} opts
26
+ * @param {object} opts.hub The {@link SignalingHub} instance.
27
+ * @param {string} opts.room Room name to join.
28
+ * @param {*} [opts.user] Opaque user object attached to the peer.
29
+ * @param {string} [opts.ip='127.0.0.1'] IP recorded on the attached peer.
30
+ * @param {string} [opts.joinToken] Optional join token forwarded to the hub.
31
+ * @param {Array} [opts.iceServers=[]] RTCConfiguration.iceServers.
32
+ * @param {object} [opts.rtcConfig] Additional RTCConfiguration fields.
33
+ * @param {object} [opts.wrtc] Injected `wrtc` module (testing).
34
+ * @param {Function} [opts.onTrack] (track, streams, fromPeerId) => void
35
+ * @param {Function} [opts.onDataChannel] (channel, fromPeerId) => void
36
+ * @param {Function} [opts.onPeerJoin] (remotePeerId) => void
37
+ * @param {Function} [opts.onPeerLeave] (remotePeerId) => void
38
+ * @param {Function} [opts.onError] (err) => void (non-fatal errors)
39
+ * @returns {{
40
+ * peer: object,
41
+ * peerConnections: Map<string, object>,
42
+ * getPeerConnection: (remotePeerId: string) => object | undefined,
43
+ * ready: Promise<{ peerId: string }>,
44
+ * close: () => void,
45
+ * }}
46
+ */
47
+ function spawnBotPeer(opts)
48
+ {
49
+ const o = opts || {};
50
+ if (!o.hub || typeof o.hub.attach !== 'function')
51
+ {
52
+ throw new WebRTCError('spawnBotPeer requires { hub }', { code: 'WEBRTC_BOT_INVALID_CONFIG' });
53
+ }
54
+ if (!o.room || typeof o.room !== 'string')
55
+ {
56
+ throw new WebRTCError('spawnBotPeer requires { room }', { code: 'WEBRTC_BOT_INVALID_CONFIG' });
57
+ }
58
+
59
+ const wrtc = o.wrtc || _tryRequireWrtc();
60
+ const { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } = wrtc;
61
+ if (typeof RTCPeerConnection !== 'function')
62
+ {
63
+ throw new WebRTCError(
64
+ "spawnBotPeer: provided 'wrtc' module is missing RTCPeerConnection",
65
+ { code: 'WEBRTC_BOT_INVALID_WRTC' },
66
+ );
67
+ }
68
+
69
+ const rtcConfig = {
70
+ iceServers: Array.isArray(o.iceServers) ? o.iceServers : [],
71
+ ...(o.rtcConfig || {}),
72
+ };
73
+
74
+ const onTrack = typeof o.onTrack === 'function' ? o.onTrack : null;
75
+ const onDataChannel = typeof o.onDataChannel === 'function' ? o.onDataChannel : null;
76
+ const onPeerJoin = typeof o.onPeerJoin === 'function' ? o.onPeerJoin : null;
77
+ const onPeerLeave = typeof o.onPeerLeave === 'function' ? o.onPeerLeave : null;
78
+ const onError = typeof o.onError === 'function' ? o.onError : (() => {});
79
+
80
+ // In-process transport that satisfies the hub's contract.
81
+ const transport = new BotTransport();
82
+
83
+ const pcs = new Map(); // remotePeerId -> RTCPeerConnection
84
+ let myPeerId = null;
85
+ let closed = false;
86
+ let resolveReady;
87
+ let rejectReady;
88
+ const ready = new Promise((res, rej) => { resolveReady = res; rejectReady = rej; });
89
+
90
+ function pushToHub(msg)
91
+ {
92
+ if (closed) return;
93
+ try { transport._inject(msg); }
94
+ catch (err) { onError(err); }
95
+ }
96
+
97
+ function getOrCreatePc(remoteId)
98
+ {
99
+ let pc = pcs.get(remoteId);
100
+ if (pc) return pc;
101
+ pc = new RTCPeerConnection(rtcConfig);
102
+ pcs.set(remoteId, pc);
103
+
104
+ pc.onicecandidate = (ev) =>
105
+ {
106
+ if (ev && ev.candidate && ev.candidate.candidate)
107
+ {
108
+ pushToHub({
109
+ type: 'ice',
110
+ target: remoteId,
111
+ candidate: ev.candidate.candidate,
112
+ });
113
+ }
114
+ };
115
+ if (onTrack)
116
+ {
117
+ pc.ontrack = (ev) =>
118
+ {
119
+ try { onTrack(ev.track, ev.streams || [], remoteId); }
120
+ catch (err) { onError(err); }
121
+ };
122
+ }
123
+ if (onDataChannel)
124
+ {
125
+ pc.ondatachannel = (ev) =>
126
+ {
127
+ try { onDataChannel(ev.channel, remoteId); }
128
+ catch (err) { onError(err); }
129
+ };
130
+ }
131
+ return pc;
132
+ }
133
+
134
+ async function offerTo(remoteId)
135
+ {
136
+ try
137
+ {
138
+ const pc = getOrCreatePc(remoteId);
139
+ const offer = await pc.createOffer();
140
+ await pc.setLocalDescription(offer);
141
+ pushToHub({ type: 'offer', target: remoteId, sdp: pc.localDescription.sdp });
142
+ }
143
+ catch (err) { onError(err); }
144
+ }
145
+
146
+ async function answerTo(remoteId, sdp)
147
+ {
148
+ try
149
+ {
150
+ const pc = getOrCreatePc(remoteId);
151
+ await pc.setRemoteDescription(new RTCSessionDescription({ type: 'offer', sdp }));
152
+ const answer = await pc.createAnswer();
153
+ await pc.setLocalDescription(answer);
154
+ pushToHub({ type: 'answer', target: remoteId, sdp: pc.localDescription.sdp });
155
+ }
156
+ catch (err) { onError(err); }
157
+ }
158
+
159
+ async function applyAnswer(remoteId, sdp)
160
+ {
161
+ try
162
+ {
163
+ const pc = pcs.get(remoteId);
164
+ if (!pc) return;
165
+ await pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp }));
166
+ }
167
+ catch (err) { onError(err); }
168
+ }
169
+
170
+ async function applyIce(remoteId, candidate)
171
+ {
172
+ try
173
+ {
174
+ const pc = pcs.get(remoteId);
175
+ if (!pc || !candidate) return;
176
+ await pc.addIceCandidate(new RTCIceCandidate({ candidate, sdpMid: '0', sdpMLineIndex: 0 }));
177
+ }
178
+ catch (err) { onError(err); }
179
+ }
180
+
181
+ function dropPc(remoteId)
182
+ {
183
+ const pc = pcs.get(remoteId);
184
+ if (!pc) return;
185
+ try { pc.close(); } catch (_) { /* noop */ }
186
+ pcs.delete(remoteId);
187
+ }
188
+
189
+ // The hub calls `transport.send(json)` for every outbound message.
190
+ // We intercept those, parse them, and drive the negotiation state machine.
191
+ transport._onOutbound = (data) =>
192
+ {
193
+ let msg;
194
+ try { msg = JSON.parse(data); }
195
+ catch (err) { onError(err); return; }
196
+
197
+ switch (msg.type)
198
+ {
199
+ case 'hello':
200
+ myPeerId = msg.peerId;
201
+ pushToHub({ type: 'join', room: o.room, token: o.joinToken });
202
+ break;
203
+
204
+ case 'joined':
205
+ if (resolveReady)
206
+ {
207
+ resolveReady({ peerId: myPeerId });
208
+ resolveReady = null;
209
+ rejectReady = null;
210
+ }
211
+ // Existing peers in the room - bot is the newcomer, so it offers first.
212
+ // The hub's `peers` list includes the bot itself; skip self.
213
+ if (Array.isArray(msg.peers))
214
+ {
215
+ for (const id of msg.peers)
216
+ {
217
+ if (id !== myPeerId) offerTo(id);
218
+ }
219
+ }
220
+ break;
221
+
222
+ case 'peer-joined':
223
+ if (onPeerJoin)
224
+ {
225
+ try { onPeerJoin(msg.id); }
226
+ catch (err) { onError(err); }
227
+ }
228
+ // New peer joined after us - they are the newcomer and will offer; we wait.
229
+ break;
230
+
231
+ case 'peer-left':
232
+ dropPc(msg.id);
233
+ if (onPeerLeave)
234
+ {
235
+ try { onPeerLeave(msg.id); }
236
+ catch (err) { onError(err); }
237
+ }
238
+ break;
239
+
240
+ case 'offer':
241
+ answerTo(msg.from, msg.sdp);
242
+ break;
243
+
244
+ case 'answer':
245
+ applyAnswer(msg.from, msg.sdp);
246
+ break;
247
+
248
+ case 'ice':
249
+ applyIce(msg.from, msg.candidate);
250
+ break;
251
+
252
+ case 'error':
253
+ if (rejectReady)
254
+ {
255
+ rejectReady(new WebRTCError(
256
+ `bot peer error: ${msg.message || msg.code}`,
257
+ { code: msg.code || 'WEBRTC_BOT_HUB_ERROR' },
258
+ ));
259
+ rejectReady = null;
260
+ resolveReady = null;
261
+ }
262
+ onError(new WebRTCError(msg.message || msg.code, { code: msg.code || 'WEBRTC_BOT_HUB_ERROR' }));
263
+ break;
264
+
265
+ default:
266
+ // Unhandled message types are passed through silently; tests / consumers
267
+ // can subscribe to `peer` events on the hub if they need them.
268
+ break;
269
+ }
270
+ };
271
+
272
+ // Attach AFTER the outbound handler is wired so that the synchronous
273
+ // `hello` frame the hub sends inside attach() is delivered to us.
274
+ const peer = o.hub.attach(transport, { user: o.user || null, ip: o.ip || '127.0.0.1' });
275
+
276
+ function close()
277
+ {
278
+ if (closed) return;
279
+ closed = true;
280
+ for (const id of Array.from(pcs.keys())) dropPc(id);
281
+ try { transport.close(1000, 'bot-close'); } catch (_) { /* noop */ }
282
+ if (rejectReady)
283
+ {
284
+ rejectReady(new WebRTCError('bot peer closed before ready', { code: 'WEBRTC_BOT_CLOSED' }));
285
+ rejectReady = null;
286
+ resolveReady = null;
287
+ }
288
+ }
289
+
290
+ return {
291
+ peer,
292
+ peerConnections: pcs,
293
+ getPeerConnection: (remoteId) => pcs.get(remoteId),
294
+ ready,
295
+ close,
296
+ };
297
+ }
298
+
299
+ /**
300
+ * @private
301
+ * In-process transport that bridges the hub <-> bot peer.
302
+ *
303
+ * The hub calls `send(string)` for every outbound message; the bot
304
+ * sets `_onOutbound` to receive those messages. The bot uses
305
+ * `_inject(obj)` to push inbound messages back to the hub (which
306
+ * listens via the standard `'message'` event).
307
+ */
308
+ class BotTransport extends EventEmitter
309
+ {
310
+ constructor()
311
+ {
312
+ super();
313
+ this.closed = false;
314
+ this._onOutbound = null;
315
+ }
316
+
317
+ send(data)
318
+ {
319
+ if (this.closed) return;
320
+ if (typeof this._onOutbound === 'function')
321
+ {
322
+ try { this._onOutbound(data); }
323
+ catch (_) { /* swallow */ }
324
+ }
325
+ }
326
+
327
+ _inject(obj)
328
+ {
329
+ if (this.closed) return;
330
+ const data = typeof obj === 'string' ? obj : JSON.stringify(obj);
331
+ this.emit('message', data);
332
+ }
333
+
334
+ close(code, reason)
335
+ {
336
+ if (this.closed) return;
337
+ this.closed = true;
338
+ this.emit('close', code || 1000, reason || '');
339
+ }
340
+ }
341
+
342
+ /**
343
+ * @private
344
+ * Try to `require('wrtc')` then `require('@roamhq/wrtc')`.
345
+ * Throws a clean `WEBRTC_BOT_NOT_INSTALLED` error if neither is present.
346
+ */
347
+ function _tryRequireWrtc()
348
+ {
349
+ const tried = [];
350
+ for (const name of ['wrtc', '@roamhq/wrtc'])
351
+ {
352
+ try { return require(name); }
353
+ catch (err) { tried.push(`${name} (${err.code || err.message})`); }
354
+ }
355
+ throw new WebRTCError(
356
+ `spawnBotPeer requires the 'wrtc' (or '@roamhq/wrtc') peerDependency: npm install wrtc - tried: ${tried.join(', ')}`,
357
+ { code: 'WEBRTC_BOT_NOT_INSTALLED' },
358
+ );
359
+ }
360
+
361
+ module.exports = { spawnBotPeer };
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @module webrtc/cli
3
+ * @description CLI subcommands for the `zh webrtc:*` namespace.
4
+ *
5
+ * Pure-function entry point `runWebRTCCommand(subcmd, flags, deps)` so
6
+ * the dispatch can be exercised in tests without spawning a child
7
+ * process or hitting the network. All side effects (stdout / stderr /
8
+ * process.exitCode) are injected through `deps`, defaulting to the
9
+ * real globals when called from `lib/cli.js`.
10
+ *
11
+ * @example
12
+ * // From the shell, via the top-level CLI:
13
+ * // npx zh webrtc:stun --host stun.l.google.com --port 19302
14
+ * // npx zh webrtc:turn-creds --secret $SECRET --user alice \
15
+ * // --servers turn:turn.example.com:3478
16
+ * // npx zh webrtc:join-token --secret $JT_SECRET --room lobby --sub u1
17
+ * // npx zh webrtc:verify-token --secret $JT_SECRET --token $TOKEN
18
+ *
19
+ * // Programmatically:
20
+ * const { runWebRTCCommand } = require('@zero-server/webrtc/cli');
21
+ * await runWebRTCCommand('join-token', new Map([
22
+ * ['secret', 's'], ['room', 'lobby'], ['sub', 'u1'],
23
+ * ]));
24
+ */
25
+
26
+ 'use strict';
27
+
28
+ const defaultStun = require('./stun').stunBinding;
29
+ const { issueTurnCredentials } = require('./turn/credentials');
30
+ const { signJoinToken, verifyJoinToken } = require('./joinToken');
31
+
32
+ const SUBCOMMANDS = ['stun', 'turn-creds', 'join-token', 'verify-token', 'help'];
33
+
34
+ /**
35
+ * @private
36
+ * Coerce a flag Map value to a number; return defaultValue if undefined.
37
+ */
38
+ function flagNumber(flags, key, defaultValue)
39
+ {
40
+ if (!flags.has(key)) return defaultValue;
41
+ const raw = flags.get(key);
42
+ const n = Number(raw);
43
+ if (!Number.isFinite(n))
44
+ throw new Error(`--${key} must be a number, got "${raw}"`);
45
+ return n;
46
+ }
47
+
48
+ /**
49
+ * @private
50
+ * Split a comma-separated flag into a trimmed, non-empty list.
51
+ */
52
+ function flagList(flags, key)
53
+ {
54
+ if (!flags.has(key)) return [];
55
+ return String(flags.get(key))
56
+ .split(',')
57
+ .map((s) => s.trim())
58
+ .filter(Boolean);
59
+ }
60
+
61
+ /**
62
+ * @private
63
+ * Require a flag, throwing a friendly error otherwise.
64
+ */
65
+ function flagRequired(flags, key)
66
+ {
67
+ if (!flags.has(key) || flags.get(key) === 'true')
68
+ throw new Error(`--${key} is required`);
69
+ return flags.get(key);
70
+ }
71
+
72
+ /**
73
+ * Run a single `webrtc:*` subcommand.
74
+ *
75
+ * @param {string} subcmd
76
+ * One of `stun`, `turn-creds`, `join-token`, `verify-token`, `help`.
77
+ * @param {Map<string,string>} flags
78
+ * @param {object} [deps]
79
+ * Injection seam for tests.
80
+ * @param {(line: string) => void} [deps.out]
81
+ * @param {(line: string) => void} [deps.err]
82
+ * @param {(code: number) => void} [deps.setExit]
83
+ * @param {typeof defaultStun} [deps.stunBinding]
84
+ * @returns {Promise<number>} The exit code that would have been set.
85
+ */
86
+ async function runWebRTCCommand(subcmd, flags = new Map(), deps = {})
87
+ {
88
+ const out = deps.out || ((line) => console.log(line));
89
+ const err = deps.err || ((line) => console.error(line));
90
+ const setExit = deps.setExit || ((code) => { process.exitCode = code; });
91
+ const stunFn = deps.stunBinding || defaultStun;
92
+
93
+ const name = String(subcmd || '').trim();
94
+ if (!name || name === 'help' || name === '--help' || name === '-h')
95
+ {
96
+ out(helpText());
97
+ return 0;
98
+ }
99
+ if (!SUBCOMMANDS.includes(name))
100
+ {
101
+ err(`Unknown webrtc subcommand: "${name}"`);
102
+ out(helpText());
103
+ setExit(1);
104
+ return 1;
105
+ }
106
+
107
+ try
108
+ {
109
+ switch (name)
110
+ {
111
+ case 'stun': await runStun(flags, { out, stunFn }); break;
112
+ case 'turn-creds': runTurnCreds(flags, { out }); break;
113
+ case 'join-token': runJoinToken(flags, { out }); break;
114
+ case 'verify-token': runVerifyToken(flags, { out }); break;
115
+ }
116
+ return 0;
117
+ }
118
+ catch (e)
119
+ {
120
+ err(`webrtc:${name} failed: ${e.message}`);
121
+ setExit(1);
122
+ return 1;
123
+ }
124
+ }
125
+
126
+ async function runStun(flags, { out, stunFn })
127
+ {
128
+ const host = flagRequired(flags, 'host');
129
+ const port = flagNumber(flags, 'port', 3478);
130
+ const timeout = flagNumber(flags, 'timeout', 1000);
131
+ const retries = flagNumber(flags, 'retries', 1);
132
+ const result = await stunFn({ host, port, timeoutMs: timeout, retries });
133
+ out(JSON.stringify(result));
134
+ }
135
+
136
+ function runTurnCreds(flags, { out })
137
+ {
138
+ const secret = flagRequired(flags, 'secret');
139
+ const userId = flagRequired(flags, 'user');
140
+ const servers = flagList(flags, 'servers');
141
+ if (servers.length === 0)
142
+ throw new Error('--servers is required (comma-separated turn: or turns: URIs)');
143
+ const ttl = flags.has('ttl') ? flags.get('ttl') : 3600;
144
+ const realm = flags.has('realm') ? flags.get('realm') : undefined;
145
+ const creds = issueTurnCredentials({ secret, userId, servers, ttl, realm });
146
+ out(JSON.stringify(creds));
147
+ }
148
+
149
+ function runJoinToken(flags, { out })
150
+ {
151
+ const secret = flagRequired(flags, 'secret');
152
+ const room = flagRequired(flags, 'room');
153
+ const user = flagRequired(flags, 'user');
154
+ const ttl = flagNumber(flags, 'ttl', 300);
155
+ const token = signJoinToken({ secret, user, room, ttl });
156
+ out(token);
157
+ }
158
+
159
+ function runVerifyToken(flags, { out })
160
+ {
161
+ const secret = flagRequired(flags, 'secret');
162
+ const token = flagRequired(flags, 'token');
163
+ const room = flags.has('room') ? flags.get('room') : undefined;
164
+ const payload = verifyJoinToken(token, { secret, room });
165
+ out(JSON.stringify(payload));
166
+ }
167
+
168
+ function helpText()
169
+ {
170
+ return [
171
+ 'zh webrtc:* - WebRTC tooling',
172
+ '',
173
+ 'Subcommands:',
174
+ ' webrtc:stun --host H [--port 3478] [--timeout 1000] [--retries 1]',
175
+ ' webrtc:turn-creds --secret S --user U --servers turn:host:port[,...] [--ttl 3600] [--realm R]',
176
+ ' webrtc:join-token --secret S --room R --user U [--ttl 300]',
177
+ ' webrtc:verify-token --secret S --token T [--room R]',
178
+ ' webrtc:help Show this message',
179
+ ].join('\n');
180
+ }
181
+
182
+ module.exports = { runWebRTCCommand, SUBCOMMANDS };