@wtfalch/calls 0.1.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/browser.mjs ADDED
@@ -0,0 +1,607 @@
1
+ import { Rust, GenerationKeys } from './engine/generation-keys.mjs';
2
+ import { MediaLifecycle } from './engine/media-lifecycle.mjs';
3
+ import { CallLoop } from './engine/call-loop.mjs';
4
+
5
+ /** What this module itself needs from the engine it runs in. Capture and
6
+ * storage are injected, so their requirements are theirs to declare: an
7
+ * adapter says so through an optional `supported()`, and the store fails
8
+ * closed on its own. An engine missing any of these cannot run a call at all,
9
+ * and saying so here beats failing inside crypto or media later.
10
+ */
11
+ export function environmentSupport(scope = globalThis) {
12
+ const missing = [];
13
+ // Undefined means a host that does not report it, such as Node. Only an
14
+ // explicit false is an insecure context.
15
+ if (scope.isSecureContext === false) missing.push('secure_context');
16
+ for (const [name, value] of [
17
+ ['crypto_random_uuid', typeof scope.crypto?.randomUUID === 'function'],
18
+ ['crypto_random_values', typeof scope.crypto?.getRandomValues === 'function'],
19
+ ['web_crypto', !!scope.crypto?.subtle],
20
+ ['webassembly', typeof scope.WebAssembly?.instantiate === 'function'],
21
+ ['structured_clone', typeof scope.structuredClone === 'function'],
22
+ ['base64', typeof scope.btoa === 'function'],
23
+ ['abort_timeout', typeof scope.AbortSignal?.timeout === 'function'],
24
+ ]) if (!value) missing.push(name);
25
+ return missing;
26
+ }
27
+
28
+ /** A media-ready Calls endpoint. It owns provider bootstrap, key exchange,
29
+ * credential renewal and the media lease; the application only says what it
30
+ * wants. Media capture and endpoint storage are injected, so this module
31
+ * touches no device and picks no storage of its own.
32
+ */
33
+ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => fetch(...input), wasmUrl = '/crypto.wasm' }) {
34
+ for (const [name, value] of [['adapter', adapter], ['store', store]]) if (!value || typeof value !== 'object') throw new Error(`call_endpoint_${name}_required`);
35
+ for (const name of ['read', 'save', 'open']) if (typeof store[name] !== 'function') throw new Error('call_endpoint_store_required');
36
+ const missing = environmentSupport();
37
+ if (missing.length) throw Object.assign(new Error(`call_endpoint_unsupported_environment: ${missing.join(', ')}`), { code: 'call_endpoint_unsupported_environment', missing });
38
+ // The adapter owns capture and transforms, so only it can say whether this
39
+ // engine can encrypt media. An adapter that does not answer is taken at its
40
+ // word, because every adapter before this one worked without being asked.
41
+ if (typeof adapter.supported === 'function' && !adapter.supported()) throw Object.assign(new Error('call_endpoint_media_unsupported'), { code: 'call_endpoint_media_unsupported' });
42
+ const media = new MediaLifecycle(adapter, { onExpire: () => { desired = undefined; }, onMediaChange: () => notify() }), gate = new GenerationKeys();
43
+ // Key exchange runs itself: the loop distributes, pumps receipts, acknowledges
44
+ // and commits. No application or test controller drives those steps.
45
+ const loop = new CallLoop({
46
+ async status() {
47
+ if (!roster || !credential || !machine) return { active: false };
48
+ return {
49
+ active: true, hasOwnKey: !!ownKey, keyPins: ownKeyPins, rosterPins: rosterPins(),
50
+ pendingRotation: !!pendingKey, renewRequested, wantsMedia: !!desired && media.state === 'paused',
51
+ awaiting: pendingKey ? [...pendingKey.expected].filter(p => !pendingKey.acknowledgements.has(p)).length : 0,
52
+ };
53
+ },
54
+ receive: () => api.receive(),
55
+ distribute: () => api.distribute(),
56
+ commit: () => api.commitKey(),
57
+ resume: () => api.connect(desired),
58
+ });
59
+ let machine, identity, credential, roster, ownKey, ownKeyPins, since, control, poll;
60
+ let controlEpoch = 0, deviceKeys, endpoint, pendingKey;
61
+ let gatewayExpiresAt = 0, gatewaySpanMs = 0, controlExpiresAt = 0, controlSpanMs = 0, renewRequested = false;
62
+ // Credential renewal is independent of media: a paused or waiting endpoint
63
+ // still has to keep the credentials it needs to come back.
64
+ let credentialTimer, renewing, pollPass = Promise.resolve();
65
+ // What the application asked for. A roster or generation change pauses media;
66
+ // the loop uses this to come back by itself. An explicit pause clears it.
67
+ let desired;
68
+ // Why this endpoint's call is over, or null while it is not. The only
69
+ // ground truth a UI has for an ended screen. 'left' is this application
70
+ // calling leave(). 'admission_expired' is a guest whose wait for admission
71
+ // never resolved. 'control_refused' is a terminal control-plane refusal
72
+ // reaching join() before a call was ever established. 'connection_unavailable'
73
+ // is that same refusal reaching an endpoint whose call was already
74
+ // running -- the service's one code for "this endpoint's binding no longer
75
+ // holds" (control.mjs), covering the host ending the session, this
76
+ // participant being removed, and an admission or credential expiring or
77
+ // being revoked alike, because control.mjs never reports which one.
78
+ // join() clears it at the start of every attempt.
79
+ let endedCause = null;
80
+ // Every subscriber the application has registered, and the fingerprint of
81
+ // the last snapshot they were told about. notify() below is the only
82
+ // writer of either.
83
+ const subscribers = new Set();
84
+ let lastSnapshotKey;
85
+ async function httpCall(path, input, bearer, timeout = 3000) {
86
+ const epoch = controlEpoch;
87
+ try {
88
+ const response = await fetchImpl(path, { method: 'POST', credentials: 'same-origin', headers: { ...(bearer ? { authorization: bearer } : {}), 'content-type': 'application/json' }, body: JSON.stringify(input), signal: AbortSignal.timeout(timeout) });
89
+ // Carry the service's own code, so a caller can tell a transient refusal
90
+ // from a terminal one. Both are the same status.
91
+ if (!response.ok) {
92
+ const code = await response.json().then(value => value?.error?.code, () => undefined);
93
+ throw Object.assign(new Error(`control_refused_${response.status}`), { code });
94
+ }
95
+ const value = await response.json();
96
+ if (epoch !== controlEpoch) throw new Error('stale_control_response');
97
+ return value;
98
+ } catch (error) { if (epoch === controlEpoch) await api.pauseMedia(); throw error; }
99
+ }
100
+ function controlCall(action, input) { return httpCall(`/v1/sessions/${control.sessionId}/${action}`, input, control.bearer, action === 'bootstrap-finish' ? 30000 : 3000); }
101
+ async function send(peer, type, content) {
102
+ const device = await machine.getDevice(new Rust.UserId(peer.userId), new Rust.DeviceId(peer.deviceId));
103
+ const encrypted = JSON.parse(await device.encryptToDeviceEvent(type, content));
104
+ await call(`sendToDevice/m.room.encrypted/${crypto.randomUUID()}`, { messages: { [peer.userId]: { [peer.deviceId]: encrypted } } }, 'PUT');
105
+ }
106
+ function rosterPins() { return JSON.stringify(roster.peers.map(p => [p.userId, p.deviceId, p.curve25519Key, p.ed25519Key]).sort((a, b) => a[0].localeCompare(b[0]))); }
107
+ function keyContent(index) { return { session_id: roster.sessionId, generation_id: roster.generationId, sender_device: identity.deviceId, index }; }
108
+ // The public roster: a stable identity per participant, not the userId,
109
+ // deviceId or key pins above, which exist for key delivery and are not what
110
+ // draws a tile. self is derived locally, because nothing else says which
111
+ // entry is this endpoint's own. actorId is present on every entry or none,
112
+ // mirroring the service's own asymmetry: a member reader gets it, a guest
113
+ // reader never does. displayName is untrusted text: a guest declares its
114
+ // own and the service bounds it by length only, so whatever draws it owns
115
+ // the escaping. media comes from the adapter, not the roster -- the service
116
+ // carries no media state for a peer -- and is keyed by userId, the LiveKit
117
+ // identity, because that is the only key the adapter knows. It is present
118
+ // only when the adapter actually reports an entry, so an adapter without
119
+ // media() leaves the participant shape exactly as it was before media()
120
+ // existed.
121
+ function participants() {
122
+ const media = typeof adapter.media === 'function' ? adapter.media() : null;
123
+ return roster ? roster.peers.map(p => ({ participantId: p.participantId, self: p.userId === identity.userId, displayName: p.displayName ?? null, ...('actorId' in p ? { actorId: p.actorId } : {}), ...(media && media[p.userId] ? { media: media[p.userId] } : {}) })) : [];
124
+ }
125
+ // A cheap, synchronous stand-in for a snapshot: everything CallStats
126
+ // reports except the adapter's own numbers, which notify() never waits on
127
+ // unless this actually changed.
128
+ function snapshotKey() {
129
+ return JSON.stringify([media.state, media.microphoneEnabled, media.cameraEnabled, media.screenSharing, ownKey?.index, roster ? roster.peers.length : 0, roster ? roster.peers.filter(p => p.userId !== identity.userId && !!gate.entryFor(p.userId)).length : 0, participants(), gatewayExpiresAt, controlExpiresAt, pendingKey ? [...pendingKey.expected].filter(p => !pendingKey.acknowledgements.has(p)).length : null, endedCause]);
130
+ }
131
+ // Tells a real change apart from an internal tick: only one reaches
132
+ // adapter.stats() or a callback, and one subscriber throwing never stops
133
+ // another or the caller that triggered this.
134
+ //
135
+ // Deliveries are coalesced, never overlapped. stats() reads live fields
136
+ // after awaiting the adapter, so two overlapping deliveries would both read
137
+ // the later state and hand subscribers the same snapshot twice while
138
+ // claiming two changes. One delivery runs at a time; changes that arrive
139
+ // during it collapse into one more pass, which reports the newest state.
140
+ // A subscriber therefore sees current state, not every state on the way.
141
+ let delivering = false, deliveryPending = false, lastDelivered, deliverPromise = Promise.resolve();
142
+ async function deliver() {
143
+ delivering = true;
144
+ try {
145
+ while (deliveryPending) {
146
+ deliveryPending = false;
147
+ let snapshot;
148
+ // A failed stats() drops this pass only; the next change starts another.
149
+ try { snapshot = await api.stats(); } catch { continue; }
150
+ // snapshotKey() decided a change was worth reading stats() for, but
151
+ // stats() reads live fields after awaiting the adapter, so by now a
152
+ // pass can find the same state the pass before it delivered. The
153
+ // snapshot itself is the last word: an identical one is not a change.
154
+ const delivered = JSON.stringify(snapshot);
155
+ if (delivered === lastDelivered) continue;
156
+ lastDelivered = delivered;
157
+ for (const fn of [...subscribers]) { try { fn(snapshot); } catch {} }
158
+ }
159
+ } finally { delivering = false; }
160
+ }
161
+ // Returns a promise a caller can await to know delivery has caught up with
162
+ // this call, such as leave() making sure a final snapshot reaches every
163
+ // subscriber before it stops any of them. Most callers still fire this and
164
+ // forget it, which is unaffected: the promise settles on its own either way.
165
+ function notify() {
166
+ const key = snapshotKey();
167
+ if (key === lastSnapshotKey) return deliverPromise;
168
+ lastSnapshotKey = key;
169
+ if (!subscribers.size) return deliverPromise;
170
+ deliveryPending = true;
171
+ if (!delivering) deliverPromise = deliver();
172
+ return deliverPromise;
173
+ }
174
+ async function call(path, body, method = body ? 'POST' : 'GET') {
175
+ const response = await fetchImpl(`/_matrix/client/v3/${path}`, { method, headers: { authorization: `Bearer ${credential}`, 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
176
+ if (!response.ok) { await media.pause(); gate.stop(); ownKey = undefined; ownKeyPins = undefined; throw new Error(`gateway_refused_${response.status}`); }
177
+ return response.json();
178
+ }
179
+ const api = {
180
+ async redeem(value) {
181
+ await this.pause();
182
+ const response = await httpCall('/v1/guests/redeem', value);
183
+ control = { sessionId: response.sessionId, bearer: `Bearer ${response.credential}`, guest: true };
184
+ controlExpiresAt = response.expiresAt; controlSpanMs = Math.max(1, response.expiresAt - Date.now());
185
+ store.save({ control });
186
+ const { credential: secret, ...status } = response;
187
+ this.startRenewal();
188
+ notify();
189
+ return status;
190
+ },
191
+ async bootstrap(value) {
192
+ await this.pause();
193
+ control = value ?? control ?? store.read().control;
194
+ if (!control) throw new Error('endpoint_control_unavailable');
195
+ store.save({ ...store.read(), control });
196
+ const reserved = await controlCall('bootstrap', {});
197
+ // Retain the same keys when a successful finish response was lost.
198
+ if (!machine || identity.userId !== reserved.userId || identity.deviceId !== reserved.deviceId) await this.initialize(reserved);
199
+ const finished = await controlCall('bootstrap-finish', { bootstrapId: reserved.bootstrapId, deviceKeys });
200
+ credential = finished.credential;
201
+ gatewayExpiresAt = finished.expiresAt; gatewaySpanMs = Math.max(1, finished.expiresAt - Date.now());
202
+ this.startRenewal();
203
+ notify();
204
+ return { ...reserved, expiresAt: finished.expiresAt };
205
+ },
206
+ // Renewal of the credentials a live call holds. Neither call pauses media:
207
+ // the control credential is rotated by the service, and the gateway
208
+ // credential is re-issued for the same provider identity and device keys.
209
+ startRenewal() {
210
+ clearInterval(credentialTimer);
211
+ credentialTimer = setInterval(() => { this.renewCredentials().catch(() => {}); }, 500);
212
+ },
213
+ // fromLoop is true only for the call connect() makes on its own way in,
214
+ // which the loop's resume() step is the sole caller of (see tick()).
215
+ // That call already runs inside the loop's one in-flight pass, so
216
+ // quiescing here would await that very pass and never return -- the
217
+ // loop cannot be both mid-tick and finished draining at once. Nothing
218
+ // else can be concurrently in flight on the loop's behalf in that case,
219
+ // so only the independent lease poll still needs draining.
220
+ // A renewal already in flight from the timer is itself quiescing the
221
+ // loop, so it waits for the pass that is calling here: the loop's own
222
+ // call must not wait for it in turn. It goes on with the credentials it
223
+ // has, which stay valid until that renewal rotates them after this pass.
224
+ async renewCredentials(fromLoop = false) {
225
+ if (renewing) return fromLoop ? undefined : renewing;
226
+ const now = Date.now();
227
+ if (!((control?.guest && controlExpiresAt - now < controlSpanMs / 2) || (credential && gatewayExpiresAt - now < gatewaySpanMs / 2))) return;
228
+ renewing = this.renewNow(now, fromLoop).finally(() => { renewing = undefined; });
229
+ return renewing;
230
+ },
231
+ async renewNow(now, fromLoop = false) {
232
+ // Rotation invalidates the credential a request in flight is using, so the
233
+ // key loop is drained first and restarted afterwards.
234
+ // Drain BOTH schedulers. The lease poll uses the same credentials, so a
235
+ // request it already sent would be refused the moment rotation lands,
236
+ // and a refused control call drops a live call.
237
+ if (fromLoop) { await Promise.allSettled([pollPass]); await this.rotateCredentials(now); return; }
238
+ const resume = loop.running;
239
+ await Promise.allSettled([loop.quiesce(), pollPass]);
240
+ try { await this.rotateCredentials(now); } finally { if (resume) loop.start(); }
241
+ },
242
+ async rotateCredentials(now) {
243
+ if (control?.guest && controlExpiresAt - now < controlSpanMs / 2) {
244
+ const rotated = await httpCall('/v1/guests/rotate', {}, control.bearer);
245
+ control = { ...control, bearer: `Bearer ${rotated.credential}` };
246
+ controlExpiresAt = rotated.expiresAt; controlSpanMs = Math.max(1, rotated.expiresAt - now);
247
+ store.save({ ...store.read(), control });
248
+ }
249
+ if (credential && gatewayExpiresAt - now < gatewaySpanMs / 2) {
250
+ const reserved = await controlCall('bootstrap', {});
251
+ if (reserved.userId !== identity.userId || reserved.deviceId !== identity.deviceId) { await this.pause(); throw new Error('stale_provider_identity'); }
252
+ const finished = await controlCall('bootstrap-finish', { bootstrapId: reserved.bootstrapId, deviceKeys });
253
+ credential = finished.credential;
254
+ gatewayExpiresAt = finished.expiresAt; gatewaySpanMs = Math.max(1, finished.expiresAt - Date.now());
255
+ }
256
+ notify();
257
+ },
258
+ // A redeemed guest usually still has to be admitted by a member. Polling
259
+ // keeps the renewal timer running, so a long wait outlives the credential
260
+ // the redemption issued.
261
+ async awaitAdmission(ms = 60000) {
262
+ const deadline = Date.now() + ms;
263
+ try {
264
+ for (;;) {
265
+ const status = await httpCall('/v1/guests/status', {}, control.bearer);
266
+ if (status.state === 'admitted') return status;
267
+ if (Date.now() >= deadline) throw new Error('admission_pending');
268
+ await new Promise(done => setTimeout(done, 500));
269
+ }
270
+ } catch (error) {
271
+ // Either way out -- the local deadline, or the service itself
272
+ // refusing a redemption it no longer honours -- this guest was never
273
+ // admitted.
274
+ if (!endedCause) { endedCause = { reason: 'admission_expired' }; await notify(); }
275
+ throw error;
276
+ }
277
+ },
278
+ // An application asks for a fresh sender key; the loop performs the exchange.
279
+ renewKey() { renewRequested = true; },
280
+ // Take part in key exchange again after an explicit stop.
281
+ rejoin() { if (roster && credential && machine) loop.start(); },
282
+ async initialize(value) {
283
+ controlEpoch++;
284
+ clearInterval(poll); clearInterval(credentialTimer);
285
+ await media.pause(); gate.stop(); ownKey = undefined; ownKeyPins = undefined; credential = undefined; since = undefined;
286
+ endpoint?.close(); endpoint = undefined; machine = undefined;
287
+ await Rust.initAsync(wasmUrl);
288
+ identity = value;
289
+ endpoint = await store.open(Rust, value);
290
+ machine = endpoint.machine; deviceKeys = endpoint.deviceKeys;
291
+ this.upload = endpoint.upload;
292
+ },
293
+ async configure() {
294
+ loop.stop(); controlEpoch++; clearInterval(poll);
295
+ try {
296
+ await media.pause(); ownKey = undefined; ownKeyPins = undefined;
297
+ roster = await controlCall('state', { credential }); gate.setRoster(roster);
298
+ const saved = store.read().received;
299
+ if (saved?.generationId === roster.generationId) gate.restoreIndices(saved.indices);
300
+ if (this.upload) await machine.markRequestAsSent(this.upload.id, this.upload.type, JSON.stringify(await call('keys/upload', this.upload.body)));
301
+ delete this.upload;
302
+ since = (await call('sync')).next_batch;
303
+ } finally { notify(); }
304
+ },
305
+ async discover() {
306
+ // call('keys/query', ...) below pauses media on a gateway refusal, same
307
+ // as every other gateway call; a lifecycle change is worth a snapshot
308
+ // even here, where nothing else this function does changes one.
309
+ try {
310
+ const request = machine.queryKeysForUsers(roster.peers.map(p => new Rust.UserId(p.userId)));
311
+ const device_keys = Object.fromEntries(roster.peers.map(p => [p.userId, [p.deviceId]]));
312
+ await machine.markRequestAsSent(request.id, request.type, JSON.stringify(await call('keys/query', { device_keys })));
313
+ loop.start();
314
+ } finally { notify(); }
315
+ },
316
+ async distribute() {
317
+ await this.refresh();
318
+ try {
319
+ if (pendingKey) throw new Error('key_rotation_pending');
320
+ const epoch = controlEpoch, peers = roster.peers.filter(p => p.userId !== identity.userId);
321
+ renewRequested = false;
322
+ const state = store.read(), index = (state.crypto.senderIndex ?? -1) + 1;
323
+ if (!Number.isSafeInteger(index) || index > 255) throw new Error('key_index_exhausted');
324
+ // Burn the index before asynchronous work. Reload never reuses a sender slot.
325
+ store.save({ ...state, crypto: { ...state.crypto, senderIndex: index } });
326
+ const entry = { identity: identity.userId, key: btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))), index };
327
+ pendingKey = { entry, rotationId: crypto.randomUUID(), generationId: roster.generationId, rosterPins: rosterPins(), expected: new Set(peers.map(p => p.userId)), acknowledgements: new Set() };
328
+ const pending = pendingKey;
329
+ await this.sessionsFor(peers);
330
+ for (const peer of peers) {
331
+ if (epoch !== controlEpoch || pendingKey !== pending) throw new Error('stale_key_rotation');
332
+ await send(peer, 'io.wtfalch.calls.media_key', { ...keyContent(index), key: entry.key, rotation_id: pending.rotationId });
333
+ }
334
+ return { index, awaiting: pending.expected.size };
335
+ } finally { notify(); }
336
+ },
337
+ async commitKey() {
338
+ await this.refresh();
339
+ try {
340
+ const pending = pendingKey, epoch = controlEpoch;
341
+ if (!pending || pending.rosterPins !== rosterPins() || pending.generationId !== roster.generationId || [...pending.expected].some(p => !pending.acknowledgements.has(p))) throw new Error('key_acknowledgements_pending');
342
+ if (media.state === 'ready') await media.updateKeys([pending.entry]);
343
+ if (epoch !== controlEpoch || pendingKey !== pending) throw new Error('stale_key_rotation');
344
+ ownKey = pending.entry; ownKeyPins = pending.rosterPins; pendingKey = undefined;
345
+ return { index: ownKey.index };
346
+ } finally { notify(); }
347
+ },
348
+ async sessionsFor(peers) {
349
+ const request = await machine.getMissingSessions(peers.map(p => new Rust.UserId(p.userId)));
350
+ if (request) {
351
+ const body = JSON.parse(request.body); delete body.timeout;
352
+ await machine.markRequestAsSent(request.id, request.type, JSON.stringify(await call('keys/claim', body)));
353
+ }
354
+ },
355
+ async receive() {
356
+ await this.refresh();
357
+ try {
358
+ const epoch = controlEpoch, sync = await call(`sync?since=${since}`); since = sync.next_batch;
359
+ const requests = [];
360
+ const accepted = await gate.receive(machine, sync, { onRequest: ({ userId }) => requests.push(userId), onAck: ack => {
361
+ if (pendingKey && ack.forUserId === identity.userId && ack.rotationId === pendingKey.rotationId && ack.index === pendingKey.entry.index && pendingKey.expected.has(ack.userId)) pendingKey.acknowledgements.add(ack.userId);
362
+ } });
363
+ if (epoch !== controlEpoch) throw new Error('stale_key_delivery');
364
+ store.save({ ...store.read(), received: { generationId: roster.generationId, indices: [...gate.indices] } });
365
+ for (const entry of accepted) {
366
+ if (media.state === 'ready') await media.updateKeys([{ identity: entry.userId, key: entry.key, index: entry.index }]);
367
+ if (epoch !== controlEpoch) throw new Error('stale_key_delivery');
368
+ if (typeof entry.rotationId === 'string') await send(roster.peers.find(p => p.userId === entry.userId), 'io.wtfalch.calls.media_key_ack', { ...keyContent(entry.index), for_user_id: entry.userId, rotation_id: entry.rotationId });
369
+ }
370
+ // Re-deliver the current key to a peer that lost it, and ask for any key
371
+ // this endpoint is missing. Neither makes a new key or a new index.
372
+ const others = roster.peers.filter(p => p.userId !== identity.userId);
373
+ const wanted = others.filter(p => !gate.entryFor(p.userId));
374
+ if ((requests.length && ownKey) || wanted.length) await this.sessionsFor(others);
375
+ for (const userId of new Set(requests)) {
376
+ const peer = others.find(p => p.userId === userId);
377
+ if (peer && ownKey) await send(peer, 'io.wtfalch.calls.media_key', { ...keyContent(ownKey.index), key: ownKey.key });
378
+ }
379
+ for (const peer of wanted) await send(peer, 'io.wtfalch.calls.media_key_request', keyContent(0));
380
+ if (epoch !== controlEpoch) throw new Error('stale_key_delivery');
381
+ return accepted.length;
382
+ } finally { notify(); }
383
+ },
384
+ async refresh() {
385
+ let current;
386
+ try { current = await controlCall('state', { credential }); }
387
+ catch (error) {
388
+ // control.mjs's `state` action never refuses with anything but this
389
+ // one code (Control.read, packages/service/src/control.mjs): this
390
+ // endpoint's binding no longer holds. refresh() only runs once a call
391
+ // is already under way -- join()'s own bootstrap loop handles the
392
+ // same code before a call exists, as 'control_refused' instead.
393
+ // The poll below retries every tick, so one refusal is often a blip a
394
+ // later refresh() outlives, not a fact. Only once every credential
395
+ // this endpoint holds has passed its expiry is it permanent: each has
396
+ // had its own renewal window (rotateCredentials) and none came back.
397
+ // A member has no control expiry (it stays 0), so the gateway
398
+ // credential's is the one that counts for it.
399
+ if (error.code === 'connection_unavailable' && !endedCause && Date.now() >= Math.max(controlExpiresAt, gatewayExpiresAt)) { endedCause = { reason: 'connection_unavailable' }; await notify(); }
400
+ throw error;
401
+ }
402
+ try {
403
+ if (current.generationId !== roster.generationId || current.revision !== roster.revision) {
404
+ const wanted = desired;
405
+ await this.pause();
406
+ desired = wanted; roster = current; gate.setRoster(roster); ownKey = undefined; ownKeyPins = undefined;
407
+ if (wanted) loop.start();
408
+ throw new Error('stale_control_state');
409
+ }
410
+ // Refreshing a roster does not extend an active media lease. Reconnection
411
+ // requires a new server lease and the existing endpoint key gate.
412
+ roster = current; gate.setRoster(roster);
413
+ } finally { notify(); }
414
+ },
415
+ async connect({ mode = 'video', maxLeaseMs = 60000 } = {}) {
416
+ controlEpoch++; clearInterval(poll);
417
+ // Renew before use: a credential issued while waiting to be admitted may
418
+ // already be past its half life by the time media starts. Only the
419
+ // loop's own resume() step calls connect(), so this renewal is always
420
+ // already inside the loop's one in-flight pass (fromLoop: true).
421
+ await this.renewCredentials(true);
422
+ await this.refresh();
423
+ const keys = roster.peers.map(p => p.userId === identity.userId ? ownKey : gate.entryFor(p.userId));
424
+ if (keys.some(key => !key)) throw new Error('media_authority_unavailable');
425
+ const lease = await controlCall('media', { credential, generationId: roster.generationId, revision: roster.revision, mode, e2ee: true });
426
+ if (lease.generationId !== roster.generationId || lease.revision !== roster.revision || lease.requiresE2EE !== true) { await this.pause(); throw new Error('stale_control_state'); }
427
+ const expiresAt = Math.min(lease.expiresAt, roster.expiresAt, Date.now() + maxLeaseMs);
428
+ desired = { mode, maxLeaseMs }; loop.start();
429
+ try { await media.activate({ ...lease, keys, localIdentity: identity.userId, expiresAt }); } finally { notify(); }
430
+ let leaseSpanMs = expiresAt - Date.now(), pending = false;
431
+ poll = setInterval(() => {
432
+ if (pending || renewing) return; pending = true;
433
+ pollPass = (async () => {
434
+ try {
435
+ // A page that has lost its endpoint state schedules nothing.
436
+ if (!credential || !control) return;
437
+ await this.refresh();
438
+ // Renew once under half the lease's life remains. The epoch is
439
+ // captured before the round trip so a concurrent pause or reconnect
440
+ // is caught by extend()'s own guard rather than racing it here.
441
+ if (media.state === 'ready' && media.deadline - Date.now() < leaseSpanMs / 2) {
442
+ const epoch = media.epoch;
443
+ const renewed = await controlCall('media', { credential, generationId: roster.generationId, revision: roster.revision, mode, e2ee: true });
444
+ if (renewed.generationId !== roster.generationId || renewed.revision !== roster.revision || renewed.requiresE2EE !== true) { await this.pause(); throw new Error('stale_control_state'); }
445
+ const nextExpiresAt = Math.min(renewed.expiresAt, roster.expiresAt, Date.now() + maxLeaseMs);
446
+ media.extend({ expiresAt: nextExpiresAt, epoch });
447
+ leaseSpanMs = nextExpiresAt - Date.now();
448
+ }
449
+ } catch {} finally { pending = false; }
450
+ })();
451
+ }, 500);
452
+ },
453
+ // 'screen' starts a share the same way publish() adds a track, so it
454
+ // lives on the same verb; stopping one is not the other two's shape, so
455
+ // it gets its own.
456
+ publish(mode) { return (mode === 'screen' ? media.startShare() : media.publish(mode)).finally(() => notify()); },
457
+ stopShare() { return media.stopShare().finally(() => notify()); },
458
+ // Mute/unmute and camera on/off: local capture decisions, so they live
459
+ // beside publish() on the endpoint rather than being a call-only surface.
460
+ // The application says what it wants and this module owns the device --
461
+ // the same reason publish() and pauseMedia() are here and not on the loop.
462
+ setMicrophoneEnabled(enabled) { return media.setMicrophoneEnabled(enabled).finally(() => notify()); },
463
+ // 'mode' here is the live camera toggle the contract names setMode() for,
464
+ // distinct from connect()'s 'mode', which scopes the lease's video
465
+ // authority once at join time and is never revisited by this call.
466
+ async setMode(mode) {
467
+ try {
468
+ if (!['audio', 'video'].includes(mode)) throw new Error('invalid_media_mode');
469
+ return await media.setCameraEnabled(mode === 'video');
470
+ } finally { notify(); }
471
+ },
472
+ // Draws a participant's camera or screen track into element and returns a
473
+ // function that detaches it. The UI speaks participant ids, never LiveKit
474
+ // identities, so this maps participantId to the roster peer's userId
475
+ // before handing off to the adapter, which -- like media() above -- is
476
+ // keyed by identity. The local identity gives a local preview. This does
477
+ // not go through media.*: it draws a track the adapter already holds
478
+ // rather than granting new capture authority, so it needs no lease and no
479
+ // epoch of its own.
480
+ attach(participantId, source, element) {
481
+ if (typeof adapter.attach !== 'function') throw Object.assign(new Error('media_unsupported'), { code: 'media_unsupported' });
482
+ const peer = (roster ? roster.peers : []).find(p => p.participantId === participantId);
483
+ if (!peer) throw Object.assign(new Error('unknown_participant'), { code: 'unknown_participant' });
484
+ return adapter.attach(peer.userId, source, element);
485
+ },
486
+ // The devices this adapter can offer right now, and switching capture to
487
+ // one of them. Neither is a publish: no lease, no key rotation, no
488
+ // renegotiation, so neither goes through media.* either.
489
+ async devices() {
490
+ if (typeof adapter.devices !== 'function') throw Object.assign(new Error('media_unsupported'), { code: 'media_unsupported' });
491
+ return adapter.devices();
492
+ },
493
+ async useDevice(kind, deviceId) {
494
+ if (typeof adapter.useDevice !== 'function') throw Object.assign(new Error('media_unsupported'), { code: 'media_unsupported' });
495
+ return adapter.useDevice(kind, deviceId);
496
+ },
497
+ // pause() is the application saying stop. pauseMedia() is the endpoint
498
+ // losing authority for now and keeping what the application asked for.
499
+ async pauseMedia() { controlEpoch++; clearInterval(poll); ownKey = undefined; ownKeyPins = undefined; pendingKey = undefined; gate.stop(); try { await media.pause(); } finally { notify(); } },
500
+ // Awaiting notify() here, not firing it, is what lets leave() below
501
+ // guarantee a subscriber sees the final snapshot before anything
502
+ // unsubscribes it.
503
+ async pause() { desired = undefined; loop.stop(); controlEpoch++; clearInterval(poll); ownKey = undefined; ownKeyPins = undefined; pendingKey = undefined; gate.stop(); try { await media.pause(); } finally { await notify(); } },
504
+ // leave() is the application done with the call. It is the only stop that
505
+ // also ends renewal: pause() keeps it, because a paused endpoint still
506
+ // means to come back, and a roster change pauses one that is still live.
507
+ // It is the only stop that forgets a mute, for the same reason. It is
508
+ // also the one certain source of 'left': whatever the endpoint was doing,
509
+ // the application asking to leave is why this call is over, so nothing
510
+ // reported after this point may overwrite it.
511
+ async leave() { if (!endedCause) endedCause = { reason: 'left' }; clearInterval(credentialTimer); credentialTimer = undefined; await this.pause(); media.resetCapture(); await notify(); },
512
+ async stats() { return { ...(await adapter.stats()), lifecycle: media.state, microphoneEnabled: media.microphoneEnabled, cameraEnabled: media.cameraEnabled, screenSharing: media.screenSharing, senderIndex: ownKey?.index, peers: roster ? roster.peers.length : 0, keyedPeers: roster ? roster.peers.filter(p => p.userId !== identity.userId && !!gate.entryFor(p.userId)).length : 0, participants: participants(), gatewayExpiresAt, controlExpiresAt, awaitingKeys: pendingKey ? [...pendingKey.expected].filter(p => !pendingKey.acknowledgements.has(p)).length : null, ended: endedCause }; },
513
+ // Delivers the current snapshot at once, and again whenever notify() finds
514
+ // one of stats()'s fields changed. No event target: a Set of callbacks is
515
+ // the whole mechanism, and the returned function just removes one from it.
516
+ //
517
+ // This subscription belongs to the endpoint, not to any one call: it
518
+ // survives leave() and sees the next join() too, which is what a
519
+ // connection indicator wants. A subscription scoped to one call is what
520
+ // join()'s handle returns.
521
+ subscribe(fn) {
522
+ subscribers.add(fn);
523
+ api.stats().then(snapshot => { if (subscribers.has(fn)) { try { fn(snapshot); } catch {} } }).catch(() => {});
524
+ return () => { subscribers.delete(fn); };
525
+ },
526
+ // The application asks for media; the loop connects once the keys for the
527
+ // current roster are in place, and keeps the call after that.
528
+ connectWhenReady({ mode = 'video', maxLeaseMs = 60000 } = {}) { desired = { mode, maxLeaseMs }; loop.start(); },
529
+ async whenReady(ms = 30000) {
530
+ const deadline = Date.now() + ms;
531
+ while (Date.now() < deadline) {
532
+ if (media.state === 'ready') return true;
533
+ if (!desired) throw new Error('media_authority_unavailable');
534
+ await new Promise(done => setTimeout(done, 100));
535
+ }
536
+ throw new Error('media_not_ready');
537
+ },
538
+ retainedGatewayCredential() { return credential; },
539
+ retainedToken() { return adapter.retainedToken(); },
540
+ };
541
+
542
+ /** Everything an application needs to be in a call: admission if it is a
543
+ * guest, provider bootstrap, key exchange and media. The loop connects as
544
+ * soon as the keys for the current roster are in place.
545
+ */
546
+ api.join = async ({ sessionId, guest, mode = 'video', maxLeaseMs = 60000, readyMs = 30000, admissionMs = 60000, provisioningMs = 5000 } = {}) => {
547
+ // A fresh attempt starts with a clean slate: whatever ended the last call
548
+ // on this endpoint says nothing about this one.
549
+ endedCause = null;
550
+ if (guest && (await api.redeem(guest)).state !== 'admitted') await api.awaitAdmission(admissionMs);
551
+ // An endpoint admitted a moment ago can reach bootstrap before the
552
+ // coordinator has provisioned its generation. `connection_unavailable` is
553
+ // the service's universal refusal and says nothing about why, so this is a
554
+ // short wait for that scheduling gap and nothing more. An endpoint whose
555
+ // keys the admission will never accept, such as one that lost its store to
556
+ // a browser restart, is refused the same way and must fail quickly.
557
+ const deadline = Date.now() + provisioningMs;
558
+ for (;;) {
559
+ try { await api.bootstrap(sessionId ? { sessionId } : undefined); break; }
560
+ catch (error) {
561
+ if (error.code !== 'connection_unavailable' || Date.now() >= deadline) {
562
+ // A call that never got established, refused for good: the generic
563
+ // control_refused bucket, since join() cannot tell 'session_ended'
564
+ // from 'forbidden' from a connection_unavailable that outlived the
565
+ // provisioning wait, and none of them is any more specific once a
566
+ // call was never running to have ended.
567
+ if (!endedCause) { endedCause = { reason: 'control_refused' }; await notify(); }
568
+ throw error;
569
+ }
570
+ await new Promise(done => setTimeout(done, 500));
571
+ }
572
+ }
573
+ await api.configure();
574
+ await api.discover();
575
+ await api.connectWhenReady({ mode, maxLeaseMs });
576
+ // A handle's subscriptions end with the call. Without this they would sit
577
+ // in the endpoint's one registry, keep firing after leave(), and be handed
578
+ // the next join()'s snapshots -- a different call, to a callback written
579
+ // for this one. An application that wants that reach subscribes on the
580
+ // endpoint instead.
581
+ const subscriptions = new Set();
582
+ return {
583
+ state: () => api.stats(),
584
+ subscribe: fn => {
585
+ const off = api.subscribe(fn);
586
+ const stop = () => { subscriptions.delete(stop); off(); };
587
+ subscriptions.add(stop);
588
+ return stop;
589
+ },
590
+ publish: value => api.publish(value),
591
+ stopShare: () => api.stopShare(),
592
+ setMicrophoneEnabled: enabled => api.setMicrophoneEnabled(enabled),
593
+ setMode: mode => api.setMode(mode),
594
+ renewKey: () => api.renewKey(),
595
+ attach: (participantId, source, element) => api.attach(participantId, source, element),
596
+ devices: () => api.devices(),
597
+ useDevice: (kind, deviceId) => api.useDevice(kind, deviceId),
598
+ ready: (ms = readyMs) => api.whenReady(ms),
599
+ // api.leave() runs -- and, through its now-awaited notify() chain,
600
+ // finishes delivering the final ended snapshot -- before this handle's
601
+ // own subscriptions are torn down, so a subscriber here sees why the
602
+ // call ended, not silence.
603
+ leave: async () => { await api.leave(); for (const stop of [...subscriptions]) stop(); },
604
+ };
605
+ };
606
+ return api;
607
+ }