zero-query 1.1.1 → 1.2.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.
Files changed (154) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +2 -0
  3. package/cli/args.js +33 -33
  4. package/cli/commands/build-api.js +443 -442
  5. package/cli/commands/build.js +254 -247
  6. package/cli/commands/bundle.js +1228 -1224
  7. package/cli/commands/create.js +137 -121
  8. package/cli/commands/dev/devtools/index.js +56 -56
  9. package/cli/commands/dev/devtools/js/components.js +49 -49
  10. package/cli/commands/dev/devtools/js/core.js +423 -423
  11. package/cli/commands/dev/devtools/js/elements.js +421 -421
  12. package/cli/commands/dev/devtools/js/network.js +166 -166
  13. package/cli/commands/dev/devtools/js/performance.js +73 -73
  14. package/cli/commands/dev/devtools/js/router.js +105 -105
  15. package/cli/commands/dev/devtools/js/source.js +132 -132
  16. package/cli/commands/dev/devtools/js/stats.js +35 -35
  17. package/cli/commands/dev/devtools/js/tabs.js +79 -79
  18. package/cli/commands/dev/devtools/panel.html +95 -95
  19. package/cli/commands/dev/devtools/styles.css +244 -244
  20. package/cli/commands/dev/index.js +107 -107
  21. package/cli/commands/dev/logger.js +75 -75
  22. package/cli/commands/dev/overlay.js +858 -858
  23. package/cli/commands/dev/server.js +220 -220
  24. package/cli/commands/dev/validator.js +94 -94
  25. package/cli/commands/dev/watcher.js +172 -172
  26. package/cli/help.js +114 -112
  27. package/cli/index.js +52 -52
  28. package/cli/scaffold/default/LICENSE +21 -21
  29. package/cli/scaffold/default/app/app.js +207 -207
  30. package/cli/scaffold/default/app/components/about.js +201 -201
  31. package/cli/scaffold/default/app/components/api-demo.js +143 -143
  32. package/cli/scaffold/default/app/components/contact-card.js +231 -231
  33. package/cli/scaffold/default/app/components/contacts/contacts.css +706 -706
  34. package/cli/scaffold/default/app/components/contacts/contacts.html +200 -200
  35. package/cli/scaffold/default/app/components/contacts/contacts.js +196 -196
  36. package/cli/scaffold/default/app/components/counter.js +127 -127
  37. package/cli/scaffold/default/app/components/home.js +249 -249
  38. package/cli/scaffold/default/app/components/not-found.js +16 -16
  39. package/cli/scaffold/default/app/components/playground/playground.css +115 -115
  40. package/cli/scaffold/default/app/components/playground/playground.html +161 -161
  41. package/cli/scaffold/default/app/components/playground/playground.js +116 -116
  42. package/cli/scaffold/default/app/components/todos.js +225 -225
  43. package/cli/scaffold/default/app/components/toolkit/toolkit.css +97 -97
  44. package/cli/scaffold/default/app/components/toolkit/toolkit.html +146 -146
  45. package/cli/scaffold/default/app/components/toolkit/toolkit.js +280 -280
  46. package/cli/scaffold/default/app/routes.js +15 -15
  47. package/cli/scaffold/default/app/store.js +101 -101
  48. package/cli/scaffold/default/global.css +552 -552
  49. package/cli/scaffold/default/index.html +99 -99
  50. package/cli/scaffold/minimal/app/app.js +85 -85
  51. package/cli/scaffold/minimal/app/components/about.js +68 -68
  52. package/cli/scaffold/minimal/app/components/counter.js +122 -122
  53. package/cli/scaffold/minimal/app/components/home.js +68 -68
  54. package/cli/scaffold/minimal/app/components/not-found.js +16 -16
  55. package/cli/scaffold/minimal/app/routes.js +9 -9
  56. package/cli/scaffold/minimal/app/store.js +36 -36
  57. package/cli/scaffold/minimal/global.css +300 -300
  58. package/cli/scaffold/minimal/index.html +44 -44
  59. package/cli/scaffold/ssr/app/app.js +41 -41
  60. package/cli/scaffold/ssr/app/components/about.js +55 -55
  61. package/cli/scaffold/ssr/app/components/blog/index.js +65 -65
  62. package/cli/scaffold/ssr/app/components/blog/post.js +86 -86
  63. package/cli/scaffold/ssr/app/components/home.js +37 -37
  64. package/cli/scaffold/ssr/app/components/not-found.js +15 -15
  65. package/cli/scaffold/ssr/app/routes.js +8 -8
  66. package/cli/scaffold/ssr/global.css +228 -228
  67. package/cli/scaffold/ssr/index.html +37 -37
  68. package/cli/scaffold/ssr/package.json +8 -8
  69. package/cli/scaffold/ssr/server/data/posts.js +144 -144
  70. package/cli/scaffold/ssr/server/index.js +213 -213
  71. package/cli/scaffold/webrtc/app/app.js +11 -0
  72. package/cli/scaffold/webrtc/app/components/video-room.js +295 -0
  73. package/cli/scaffold/webrtc/app/lib/room.js +252 -0
  74. package/cli/scaffold/webrtc/assets/.gitkeep +0 -0
  75. package/cli/scaffold/webrtc/global.css +250 -0
  76. package/cli/scaffold/webrtc/index.html +21 -0
  77. package/cli/utils.js +305 -287
  78. package/dist/API.md +661 -0
  79. package/dist/zquery.dist.zip +0 -0
  80. package/dist/zquery.js +10313 -6614
  81. package/dist/zquery.min.js +8 -631
  82. package/index.d.ts +570 -371
  83. package/index.js +311 -240
  84. package/package.json +76 -70
  85. package/src/component.js +1709 -1691
  86. package/src/core.js +921 -921
  87. package/src/diff.js +497 -497
  88. package/src/errors.js +209 -209
  89. package/src/expression.js +922 -922
  90. package/src/http.js +242 -242
  91. package/src/package.json +1 -1
  92. package/src/reactive.js +255 -255
  93. package/src/router.js +843 -843
  94. package/src/ssr.js +418 -418
  95. package/src/store.js +318 -318
  96. package/src/utils.js +515 -515
  97. package/src/webrtc/e2ee.js +351 -0
  98. package/src/webrtc/errors.js +116 -0
  99. package/src/webrtc/ice.js +301 -0
  100. package/src/webrtc/index.js +131 -0
  101. package/src/webrtc/joinToken.js +119 -0
  102. package/src/webrtc/observe.js +172 -0
  103. package/src/webrtc/peer.js +351 -0
  104. package/src/webrtc/reactive.js +268 -0
  105. package/src/webrtc/room.js +625 -0
  106. package/src/webrtc/sdp.js +302 -0
  107. package/src/webrtc/sfu/index.js +43 -0
  108. package/src/webrtc/sfu/livekit.js +131 -0
  109. package/src/webrtc/sfu/mediasoup.js +150 -0
  110. package/src/webrtc/signaling.js +373 -0
  111. package/src/webrtc/turn.js +237 -0
  112. package/tests/_helpers/webrtcFakes.js +289 -0
  113. package/tests/audit.test.js +4158 -4158
  114. package/tests/cli.test.js +1136 -1103
  115. package/tests/compare.test.js +497 -486
  116. package/tests/component.test.js +3969 -3938
  117. package/tests/core.test.js +1910 -1910
  118. package/tests/dev-server.test.js +489 -489
  119. package/tests/diff.test.js +1416 -1416
  120. package/tests/docs.test.js +1664 -1650
  121. package/tests/electron-features.test.js +864 -864
  122. package/tests/errors.test.js +619 -619
  123. package/tests/expression.test.js +1056 -1056
  124. package/tests/http.test.js +648 -648
  125. package/tests/reactive.test.js +819 -819
  126. package/tests/router.test.js +2327 -2327
  127. package/tests/ssr.test.js +870 -870
  128. package/tests/store.test.js +830 -830
  129. package/tests/test-minifier.js +153 -153
  130. package/tests/test-ssr.js +27 -27
  131. package/tests/utils.test.js +1377 -1377
  132. package/tests/webrtc/e2ee.test.js +283 -0
  133. package/tests/webrtc/ice.test.js +202 -0
  134. package/tests/webrtc/joinToken.test.js +89 -0
  135. package/tests/webrtc/observe.test.js +111 -0
  136. package/tests/webrtc/peer.test.js +373 -0
  137. package/tests/webrtc/reactive.test.js +235 -0
  138. package/tests/webrtc/room.test.js +406 -0
  139. package/tests/webrtc/sdp.test.js +151 -0
  140. package/tests/webrtc/sfu-livekit.test.js +119 -0
  141. package/tests/webrtc/sfu.test.js +160 -0
  142. package/tests/webrtc/signaling.test.js +251 -0
  143. package/tests/webrtc/turn.test.js +256 -0
  144. package/types/collection.d.ts +383 -383
  145. package/types/component.d.ts +186 -186
  146. package/types/errors.d.ts +135 -135
  147. package/types/http.d.ts +92 -92
  148. package/types/misc.d.ts +201 -201
  149. package/types/reactive.d.ts +98 -98
  150. package/types/router.d.ts +190 -190
  151. package/types/ssr.d.ts +102 -102
  152. package/types/store.d.ts +146 -146
  153. package/types/utils.d.ts +245 -245
  154. package/types/webrtc.d.ts +653 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * src/webrtc/ice.js - read-only ICE candidate helpers
3
+ *
4
+ * Mirrors the parsing / classification surface of the server-side
5
+ * `@zero-server/webrtc` ice module, trimmed to the subset the client
6
+ * actually needs (no policy enforcement - the server is the
7
+ * source of truth for cross-peer filtering).
8
+ *
9
+ * Exposes:
10
+ * - `parseCandidate(line)` -> structured object
11
+ * - `stringifyCandidate(obj)` -> canonical `candidate:...` line
12
+ * - address classifiers: `isPrivateIp`, `isLoopbackIp`, `isLinkLocalIp`, `isMdnsHostname`
13
+ * - `filterCandidates(list, policy)` for local-side trimming.
14
+ *
15
+ * SSR-safe: pure functions, no globals touched at module load.
16
+ */
17
+
18
+ import { IceError } from './errors.js';
19
+
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Constants
23
+ // ---------------------------------------------------------------------------
24
+
25
+ /** Recognized ICE candidate types (RFC 5245). */
26
+ export const CANDIDATE_TYPES = Object.freeze(['host', 'srflx', 'prflx', 'relay']);
27
+
28
+ /** Recognized TCP candidate types (RFC 6544 §4.5). */
29
+ export const TCP_TYPES = Object.freeze(['active', 'passive', 'so']);
30
+
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Parser
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Parse a single ICE candidate line. Accepts inputs with or without the
38
+ * `a=` SDP-attribute prefix. Throws `IceError` on any structural problem.
39
+ *
40
+ * @param {string} line
41
+ * @returns {{
42
+ * foundation: string,
43
+ * component: number,
44
+ * transport: string,
45
+ * priority: number,
46
+ * address: string,
47
+ * port: number,
48
+ * type: string,
49
+ * relatedAddress?: string,
50
+ * relatedPort?: number,
51
+ * tcpType?: string,
52
+ * extensions: Object<string,string>,
53
+ * }}
54
+ */
55
+ export function parseCandidate(line) {
56
+ if (typeof line !== 'string') {
57
+ throw new IceError('parseCandidate: input must be a string', { code: 'ZQ_WEBRTC_ICE_PARSE' });
58
+ }
59
+
60
+ let s = line.trim();
61
+ if (s.indexOf('a=') === 0) s = s.slice(2);
62
+ if (s.indexOf('candidate:') !== 0) {
63
+ throw new IceError('parseCandidate: missing "candidate:" prefix', {
64
+ code: 'ZQ_WEBRTC_ICE_PARSE',
65
+ context: { candidate: line },
66
+ });
67
+ }
68
+ s = s.slice('candidate:'.length);
69
+
70
+ const tok = s.split(/\s+/);
71
+ if (tok.length < 8) {
72
+ throw new IceError('parseCandidate: too few tokens', {
73
+ code: 'ZQ_WEBRTC_ICE_PARSE',
74
+ context: { candidate: line },
75
+ });
76
+ }
77
+
78
+ const foundation = tok[0];
79
+ const componentStr = tok[1];
80
+ const transportRaw = tok[2];
81
+ const priorityStr = tok[3];
82
+ const address = tok[4];
83
+ const portStr = tok[5];
84
+ const typKw = tok[6];
85
+ const type = tok[7];
86
+ const rest = tok.slice(8);
87
+
88
+ if (typKw !== 'typ') {
89
+ throw new IceError('parseCandidate: expected "typ" keyword', {
90
+ code: 'ZQ_WEBRTC_ICE_PARSE',
91
+ context: { candidate: line },
92
+ });
93
+ }
94
+ if (CANDIDATE_TYPES.indexOf(type) === -1) {
95
+ throw new IceError(`parseCandidate: unknown type "${type}"`, {
96
+ code: 'ZQ_WEBRTC_ICE_PARSE',
97
+ context: { candidate: line },
98
+ });
99
+ }
100
+
101
+ const component = Number(componentStr);
102
+ const priority = Number(priorityStr);
103
+ const port = Number(portStr);
104
+ if (!Number.isInteger(component) || component < 0) {
105
+ throw new IceError('parseCandidate: invalid component', {
106
+ code: 'ZQ_WEBRTC_ICE_PARSE',
107
+ context: { candidate: line },
108
+ });
109
+ }
110
+ if (!Number.isFinite(priority)) {
111
+ throw new IceError('parseCandidate: invalid priority', {
112
+ code: 'ZQ_WEBRTC_ICE_PARSE',
113
+ context: { candidate: line },
114
+ });
115
+ }
116
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
117
+ throw new IceError('parseCandidate: invalid port', {
118
+ code: 'ZQ_WEBRTC_ICE_PARSE',
119
+ context: { candidate: line },
120
+ });
121
+ }
122
+
123
+ const out = {
124
+ foundation,
125
+ component,
126
+ transport: transportRaw.toLowerCase(),
127
+ priority,
128
+ address,
129
+ port,
130
+ type,
131
+ extensions: {},
132
+ };
133
+
134
+ for (let i = 0; i < rest.length - 1; i += 2) {
135
+ const k = rest[i];
136
+ const v = rest[i + 1];
137
+ if (k === 'raddr') out.relatedAddress = v;
138
+ else if (k === 'rport') out.relatedPort = Number(v);
139
+ else if (k === 'tcptype') out.tcpType = v;
140
+ else out.extensions[k] = v;
141
+ }
142
+
143
+ return out;
144
+ }
145
+
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // Serializer
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /**
152
+ * Serialize a parsed candidate back to its canonical line format (no `a=` prefix).
153
+ * Round-trips outputs of `parseCandidate` exactly.
154
+ *
155
+ * @param {object} c - Output of `parseCandidate`.
156
+ * @returns {string}
157
+ */
158
+ export function stringifyCandidate(c) {
159
+ if (!c || typeof c !== 'object') {
160
+ throw new IceError('stringifyCandidate: input must be an object', { code: 'ZQ_WEBRTC_ICE_SERIALIZE' });
161
+ }
162
+ const required = ['foundation', 'component', 'transport', 'priority', 'address', 'port', 'type'];
163
+ for (const k of required) {
164
+ if (c[k] === undefined || c[k] === null) {
165
+ throw new IceError(`stringifyCandidate: missing "${k}"`, { code: 'ZQ_WEBRTC_ICE_SERIALIZE' });
166
+ }
167
+ }
168
+
169
+ let s = `candidate:${c.foundation} ${c.component} ${c.transport} ${c.priority} ${c.address} ${c.port} typ ${c.type}`;
170
+ if (c.relatedAddress !== undefined) s += ` raddr ${c.relatedAddress}`;
171
+ if (c.relatedPort !== undefined) s += ` rport ${c.relatedPort}`;
172
+ if (c.tcpType !== undefined) s += ` tcptype ${c.tcpType}`;
173
+ if (c.extensions) {
174
+ for (const k of Object.keys(c.extensions)) {
175
+ s += ` ${k} ${c.extensions[k]}`;
176
+ }
177
+ }
178
+ return s;
179
+ }
180
+
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // Address classifiers
184
+ // ---------------------------------------------------------------------------
185
+
186
+ function _isIPv4(addr) {
187
+ if (typeof addr !== 'string') return false;
188
+ const m = addr.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
189
+ if (!m) return false;
190
+ for (let i = 1; i <= 4; i++) if (Number(m[i]) > 255) return false;
191
+ return true;
192
+ }
193
+
194
+ function _isIPv6(addr) {
195
+ if (typeof addr !== 'string') return false;
196
+ return addr.indexOf(':') !== -1 && /^[0-9a-fA-F:]+$/.test(addr);
197
+ }
198
+
199
+ /** RFC 1918, RFC 6598 CGNAT, and IPv6 ULA (fc00::/7). */
200
+ export function isPrivateIp(addr) {
201
+ if (_isIPv4(addr)) {
202
+ const parts = addr.split('.').map(Number);
203
+ const a = parts[0]; const b = parts[1];
204
+ if (a === 10) return true;
205
+ if (a === 172 && b >= 16 && b <= 31) return true;
206
+ if (a === 192 && b === 168) return true;
207
+ if (a === 100 && b >= 64 && b <= 127) return true;
208
+ return false;
209
+ }
210
+ if (_isIPv6(addr)) {
211
+ const head = addr.toLowerCase().split(':')[0];
212
+ if (head.length === 0) return false;
213
+ const n = parseInt(head, 16);
214
+ return (n & 0xfe00) === 0xfc00;
215
+ }
216
+ return false;
217
+ }
218
+
219
+ /** IPv4 127.0.0.0/8 and IPv6 ::1. */
220
+ export function isLoopbackIp(addr) {
221
+ if (_isIPv4(addr)) return addr.indexOf('127.') === 0;
222
+ if (_isIPv6(addr)) return addr === '::1' || /^0*:0*:0*:0*:0*:0*:0*:0*1$/.test(addr);
223
+ return false;
224
+ }
225
+
226
+ /** IPv4 169.254/16 and IPv6 fe80::/10. */
227
+ export function isLinkLocalIp(addr) {
228
+ if (_isIPv4(addr)) return addr.indexOf('169.254.') === 0;
229
+ if (_isIPv6(addr)) {
230
+ const head = addr.toLowerCase().split(':')[0];
231
+ if (head.length === 0) return false;
232
+ const n = parseInt(head, 16);
233
+ return (n & 0xffc0) === 0xfe80;
234
+ }
235
+ return false;
236
+ }
237
+
238
+ /** mDNS `.local` hostname (Chrome's IP-hiding ICE candidates). */
239
+ export function isMdnsHostname(host) {
240
+ if (typeof host !== 'string') return false;
241
+ if (_isIPv4(host) || _isIPv6(host)) return false;
242
+ return host.toLowerCase().endsWith('.local');
243
+ }
244
+
245
+
246
+ // ---------------------------------------------------------------------------
247
+ // Policy filter
248
+ // ---------------------------------------------------------------------------
249
+
250
+ /**
251
+ * Filter a list of candidate lines (or parsed objects) against a policy.
252
+ * Returns the same shape it was given. Unparseable lines are silently
253
+ * dropped so a single bad candidate never poisons the whole batch.
254
+ *
255
+ * @param {Array<string|object>} candidates
256
+ * @param {object} [policy]
257
+ * @param {boolean} [policy.blockPrivate]
258
+ * @param {boolean} [policy.blockLoopback]
259
+ * @param {boolean} [policy.blockLinkLocal]
260
+ * @param {boolean} [policy.blockMdns]
261
+ * @param {boolean} [policy.blockTcp]
262
+ * @param {ReadonlyArray<string>} [policy.allowedTypes]
263
+ * @param {number} [policy.maxCandidates]
264
+ * @param {(c: object) => boolean} [policy.predicate]
265
+ * @returns {Array<string|object>}
266
+ */
267
+ export function filterCandidates(candidates, policy = {}) {
268
+ if (!Array.isArray(candidates)) return [];
269
+
270
+ const blockPrivate = !!policy.blockPrivate;
271
+ const blockLoopback = !!policy.blockLoopback;
272
+ const blockLinkLocal = !!policy.blockLinkLocal;
273
+ const blockMdns = !!policy.blockMdns;
274
+ const blockTcp = !!policy.blockTcp;
275
+ const allowedTypes = policy.allowedTypes || null;
276
+ const maxCandidates = typeof policy.maxCandidates === 'number' ? policy.maxCandidates : Infinity;
277
+ const predicate = typeof policy.predicate === 'function' ? policy.predicate : null;
278
+
279
+ const out = [];
280
+ for (const item of candidates) {
281
+ if (out.length >= maxCandidates) break;
282
+ const isString = typeof item === 'string';
283
+ let parsed;
284
+ if (isString) {
285
+ try { parsed = parseCandidate(item); }
286
+ catch (_) { continue; }
287
+ } else {
288
+ parsed = item;
289
+ }
290
+ if (!parsed) continue;
291
+ if (allowedTypes && allowedTypes.indexOf(parsed.type) === -1) continue;
292
+ if (blockTcp && parsed.transport === 'tcp') continue;
293
+ if (blockMdns && isMdnsHostname(parsed.address)) continue;
294
+ if (blockPrivate && isPrivateIp(parsed.address)) continue;
295
+ if (blockLoopback && isLoopbackIp(parsed.address)) continue;
296
+ if (blockLinkLocal && isLinkLocalIp(parsed.address)) continue;
297
+ if (predicate && !predicate(parsed)) continue;
298
+ out.push(item);
299
+ }
300
+ return out;
301
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * src/webrtc/index.js - WebRTC public barrel
3
+ *
4
+ * Re-exports the WebRTC error family, low-level building blocks
5
+ * (`SignalingClient`, `Peer`, SDP/ICE helpers), and the high-level
6
+ * `Room` + reactive composables on the `webrtc` namespace.
7
+ */
8
+
9
+ import { SignalingClient } from './signaling.js';
10
+ import { Peer } from './peer.js';
11
+ import {
12
+ parseSdp, validateSdp, SDP_DIRECTIONS,
13
+ } from './sdp.js';
14
+ import {
15
+ parseCandidate, stringifyCandidate, filterCandidates,
16
+ isPrivateIp, isLoopbackIp, isLinkLocalIp, isMdnsHostname,
17
+ CANDIDATE_TYPES, TCP_TYPES,
18
+ } from './ice.js';
19
+ import { Room, join } from './room.js';
20
+ import {
21
+ useRoom, usePeer, useTracks, useDataChannel, useConnectionQuality,
22
+ } from './reactive.js';
23
+ import {
24
+ fetchTurnCredentials, mergeIceServers, createTurnRefresher,
25
+ } from './turn.js';
26
+ import {
27
+ deriveSFrameKey, generateSFrameKey, SFrameContext,
28
+ encryptFrame, decryptFrame, attachE2ee,
29
+ } from './e2ee.js';
30
+ import { loadSfuAdapter } from './sfu/index.js';
31
+ import { decodeJoinToken, isJoinTokenExpired } from './joinToken.js';
32
+ import { samplePeerStats, createStatsSampler, classifyStats } from './observe.js';
33
+ import {
34
+ WebRtcError, SignalingError, IceError, SdpError, TurnError, E2eeError, SfuError,
35
+ } from './errors.js';
36
+
37
+
38
+ export { SignalingClient } from './signaling.js';
39
+ export { Peer } from './peer.js';
40
+ export {
41
+ parseSdp, validateSdp, SDP_DIRECTIONS,
42
+ } from './sdp.js';
43
+ export {
44
+ parseCandidate, stringifyCandidate, filterCandidates,
45
+ isPrivateIp, isLoopbackIp, isLinkLocalIp, isMdnsHostname,
46
+ CANDIDATE_TYPES, TCP_TYPES,
47
+ } from './ice.js';
48
+ export { Room, join } from './room.js';
49
+ export {
50
+ useRoom, usePeer, useTracks, useDataChannel, useConnectionQuality,
51
+ } from './reactive.js';
52
+ export {
53
+ fetchTurnCredentials, mergeIceServers, createTurnRefresher,
54
+ } from './turn.js';
55
+ export {
56
+ deriveSFrameKey, generateSFrameKey, SFrameContext,
57
+ encryptFrame, decryptFrame, attachE2ee,
58
+ } from './e2ee.js';
59
+ export { loadSfuAdapter } from './sfu/index.js';
60
+ export { createMediasoupAdapter } from './sfu/mediasoup.js';
61
+ export { createLivekitAdapter } from './sfu/livekit.js';
62
+ export { decodeJoinToken, isJoinTokenExpired } from './joinToken.js';
63
+ export { samplePeerStats, createStatsSampler, classifyStats } from './observe.js';
64
+ export {
65
+ WebRtcError, SignalingError, IceError, SdpError, TurnError, E2eeError, SfuError,
66
+ } from './errors.js';
67
+
68
+
69
+ /**
70
+ * High-level WebRTC namespace exposed as `$.webrtc`. Bundles every public
71
+ * member from this module so consumers can reach the full surface through
72
+ * a single import.
73
+ */
74
+ export const webrtc = {
75
+ SignalingClient,
76
+ Peer,
77
+ Room,
78
+ join,
79
+
80
+ // Composables
81
+ useRoom,
82
+ usePeer,
83
+ useTracks,
84
+ useDataChannel,
85
+ useConnectionQuality,
86
+
87
+ // TURN client
88
+ fetchTurnCredentials,
89
+ mergeIceServers,
90
+ createTurnRefresher,
91
+
92
+ // E2EE
93
+ deriveSFrameKey,
94
+ generateSFrameKey,
95
+ SFrameContext,
96
+ encryptFrame,
97
+ decryptFrame,
98
+ attachE2ee,
99
+
100
+ // SFU adapters
101
+ loadSfuAdapter,
102
+
103
+ // Join tokens
104
+ decodeJoinToken,
105
+ isJoinTokenExpired,
106
+
107
+ // Observability
108
+ samplePeerStats,
109
+ createStatsSampler,
110
+ classifyStats,
111
+
112
+ // SDP / ICE helpers
113
+ parseSdp,
114
+ validateSdp,
115
+ parseCandidate,
116
+ stringifyCandidate,
117
+ filterCandidates,
118
+ isPrivateIp,
119
+ isLoopbackIp,
120
+ isLinkLocalIp,
121
+ isMdnsHostname,
122
+
123
+ // Errors
124
+ WebRtcError,
125
+ SignalingError,
126
+ IceError,
127
+ SdpError,
128
+ TurnError,
129
+ E2eeError,
130
+ SfuError,
131
+ };
@@ -0,0 +1,119 @@
1
+ /**
2
+ * src/webrtc/joinToken.js
3
+ *
4
+ * UX-only decoder for the opaque join tokens minted server-side by
5
+ * `signJoinToken({ secret, user, room, exp, ... })` in
6
+ * `@zero-server/webrtc`. The client never trusts the payload — the
7
+ * server re-validates the signature on every `join` — but it's useful to
8
+ * surface things like "expires in 5 minutes" or "room name preview" in
9
+ * the UI before sending the token.
10
+ *
11
+ * Supported formats (all base64url-encoded segments separated by `.`):
12
+ * - 1 segment : `<payload>`
13
+ * - 2 segments: `<payload>.<sig>`
14
+ * - 3 segments: `<header>.<payload>.<sig>` (JWT-like)
15
+ */
16
+
17
+ import { WebRtcError } from './errors.js';
18
+
19
+
20
+ /**
21
+ * Decode a join token issued by the server.
22
+ *
23
+ * @param {string} token
24
+ * @returns {{ user: { id: string } | null, room: string | null, exp: number | null, raw: any }}
25
+ */
26
+ export function decodeJoinToken(token) {
27
+ if (typeof token !== 'string' || !token) {
28
+ throw new WebRtcError('decodeJoinToken(token): token must be a non-empty string', {
29
+ code: 'ZQ_WEBRTC_TOKEN_BAD_INPUT',
30
+ });
31
+ }
32
+
33
+ const segments = token.split('.');
34
+ if (segments.length < 1 || segments.length > 3) {
35
+ throw new WebRtcError(`decodeJoinToken(token): expected 1-3 base64url segments, got ${segments.length}`, {
36
+ code: 'ZQ_WEBRTC_TOKEN_BAD_SHAPE',
37
+ context: { segments: segments.length },
38
+ });
39
+ }
40
+
41
+ const payloadSegment = segments.length === 3 ? segments[1] : segments[0];
42
+ let payload;
43
+ try {
44
+ const json = _base64UrlDecode(payloadSegment);
45
+ payload = JSON.parse(json);
46
+ } catch (cause) {
47
+ throw new WebRtcError('decodeJoinToken(token): payload is not valid base64url-encoded JSON', {
48
+ code: 'ZQ_WEBRTC_TOKEN_BAD_PAYLOAD',
49
+ cause,
50
+ });
51
+ }
52
+
53
+ if (!payload || typeof payload !== 'object') {
54
+ throw new WebRtcError('decodeJoinToken(token): payload must be a JSON object', {
55
+ code: 'ZQ_WEBRTC_TOKEN_BAD_PAYLOAD',
56
+ });
57
+ }
58
+
59
+ return {
60
+ user: _readUser(payload),
61
+ room: typeof payload.room === 'string' ? payload.room : null,
62
+ exp: typeof payload.exp === 'number' ? payload.exp : null,
63
+ raw: payload,
64
+ };
65
+ }
66
+
67
+
68
+ /**
69
+ * `true` if the token's `exp` (seconds since epoch) is in the past.
70
+ * Tokens without an `exp` are reported as not expired. Clock skew defaults to 0.
71
+ *
72
+ * @param {{ exp: number | null }} decoded Output of `decodeJoinToken()`.
73
+ * @param {{ nowMs?: number, skewMs?: number }} [opts]
74
+ * @returns {boolean}
75
+ */
76
+ export function isJoinTokenExpired(decoded, opts = {}) {
77
+ if (!decoded || typeof decoded !== 'object') return false;
78
+ if (typeof decoded.exp !== 'number') return false;
79
+ const nowMs = typeof opts.nowMs === 'number' ? opts.nowMs : Date.now();
80
+ const skewMs = typeof opts.skewMs === 'number' ? opts.skewMs : 0;
81
+ return (decoded.exp * 1000) <= (nowMs - skewMs);
82
+ }
83
+
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Internals
87
+ // ---------------------------------------------------------------------------
88
+
89
+ function _readUser(payload) {
90
+ const u = payload.user;
91
+ if (u && typeof u === 'object' && typeof u.id === 'string') {
92
+ return { id: u.id, ...u };
93
+ }
94
+ if (typeof payload.sub === 'string') {
95
+ return { id: payload.sub };
96
+ }
97
+ return null;
98
+ }
99
+
100
+
101
+ function _base64UrlDecode(segment) {
102
+ // Restore standard base64 alphabet + padding.
103
+ let b64 = segment.replace(/-/g, '+').replace(/_/g, '/');
104
+ const pad = b64.length % 4;
105
+ if (pad === 2) b64 += '==';
106
+ else if (pad === 3) b64 += '=';
107
+ else if (pad === 1) throw new Error('invalid base64url length');
108
+
109
+ if (typeof atob === 'function') {
110
+ const bin = atob(b64);
111
+ // Decode as UTF-8.
112
+ const bytes = new Uint8Array(bin.length);
113
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
114
+ return new TextDecoder().decode(bytes);
115
+ }
116
+ // Node fallback.
117
+
118
+ return Buffer.from(b64, 'base64').toString('utf8');
119
+ }