@wtfalch/calls 0.3.1 → 0.5.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
@@ -12,7 +12,7 @@ await calls.joinAdmission(sessionId, { video: false, requestId: crypto.randomUUI
12
12
 
13
13
  `waiting(sessionId)` lists the guests waiting in the lobby, oldest first, for a host who holds `calls.participants:admit`. `record(sessionId)` reads what happened in a call: when it started and ended, and when each participant was admitted and left. Anyone who was in the call can read it, and so can holders of `calls.records:read`. A guest's copy carries no member's `actorId`.
14
14
 
15
- Member requests use same-origin cookies and exact-origin requests, unless `token` supplies a bearer instead. `baseUrl` may carry a path prefix, and `deviceId` is sent as `x-calls-device` on member requests. `createCallEndpoint` in the browser entry takes the same three options and sends every request, gateway included, under the prefix; see `docs/control-sdk.md`. Guest link redemption returns a handle whose opaque credential remains private to the handle. Errors are typed `CallsError`; requests are bounded and are never retried automatically.
15
+ Member requests use same-origin cookies and exact-origin requests, unless `token` supplies a bearer instead. `baseUrl` may carry a path prefix, and `deviceId` is sent as `x-calls-device` on member requests. `createCallEndpoint` in the browser entry takes the same three options and sends every request, gateway included, under the prefix; see `docs/control-sdk.md`. Guest link redemption returns a handle whose opaque credential remains private to the handle. `guestPreview(secret)` answers for a valid guest link, without a name and without using up the link, `{ companyName, roomName, hostName, inCall: { displayName }[], expiresAt, recording }`; it needs the host to supply a `directory`, and answers `not_configured` until it does. Errors are typed `CallsError`; requests are bounded and are never retried automatically.
16
16
 
17
17
  `@wtfalch/calls/browser` is the media-ready call handle. `join()` returns a `CallHandle` with:
18
18
 
@@ -30,13 +30,13 @@ The handle renders nothing itself. You inject the media adapter; `@wtfalch/calls
30
30
 
31
31
  `displayName` is untrusted text. A guest declares its own and the service bounds it by length only, so whatever draws it owns the escaping.
32
32
 
33
- The handle also takes an endpoint store, so this entry touches no device and picks no storage itself. It needs the peer dependency `@matrix-org/matrix-sdk-crypto-wasm@18.8.0`, which is required rather than optional: `browser.mjs` imports the crypto machine statically, so importing this entry without the peer throws `ERR_MODULE_NOT_FOUND` before any of your code runs. It is a peer and not a dependency because the engine needs exactly one instance of it.
33
+ The handle also takes an endpoint store, so this entry touches no device and picks no storage itself. A call on a transit-only service (`CALLS_ENCRYPTION=transit`, the default) connects with just the media lease: the bootstrap answer carries the credential and `requiresE2EE: false`, so the endpoint skips device keys, key exchange, the key store and the Matrix gateway, never loads the crypto wasm and does not ask the adapter whether it can encrypt media. Your store's `open` is never called and `wasmUrl` is not read. When the service still answers with end-to-end keys (`CALLS_ENCRYPTION=e2ee`), the old options work as before. The peer dependency `@matrix-org/matrix-sdk-crypto-wasm@18.8.0` is still required rather than optional, even for a transit-only call: `browser.mjs` imports the crypto machine statically, so importing this entry without the peer throws `ERR_MODULE_NOT_FOUND` before any of your code runs. It is a peer and not a dependency because the engine needs exactly one instance of it.
34
34
 
35
35
  ## `@wtfalch/calls/livekit`
36
36
 
37
37
  A real media adapter for `@wtfalch/calls/browser`, built on `livekit-client`. It owns devices, tracks and the LiveKit room; `createCallEndpoint` owns authority, keys and lifecycle. It needs the peer dependency `livekit-client@2.22.3`, and it is optional: only import this entry if you use it.
38
38
 
39
- `livekit-client`'s E2EE worker is your file to serve, not this package's. Create it once and hand it in:
39
+ `livekit-client`'s E2EE worker is your file to serve, not this package's. A transit-only call does not use it, so you can omit `worker` there. If the service requires end-to-end keys, create it once and hand it in:
40
40
 
41
41
  ```js
42
42
  import { createLiveKitAdapter } from '@wtfalch/calls/livekit';
package/browser.d.ts CHANGED
@@ -6,7 +6,9 @@ export interface CallEndpointAdapter {
6
6
  // onMediaChange fires whenever anything media() below would now report
7
7
  // differently. A call from a connection this engine has since replaced is
8
8
  // harmless -- the engine itself guards that, not the adapter.
9
- connect(input: { url: string; token: string; keys: MediaKey[]; localIdentity: string; controlled: true; onUnsafe: () => void; onMediaChange: () => void }): Promise<{ encryption: boolean }>;
9
+ // keys is absent for a transit-only call (the lease said requiresE2EE false); the adapter then connects with the token alone and
10
+ // answers encryption false.
11
+ connect(input: { url: string; token: string; keys?: MediaKey[]; localIdentity: string; controlled: true; onUnsafe: () => void; onMediaChange: () => void }): Promise<{ encryption: boolean }>;
10
12
  installKeys(entries: MediaKey[]): Promise<void>;
11
13
  publishAudio(authority: { canPublish(): boolean }): Promise<void>;
12
14
  publishVideo(authority: { canPublish(): boolean }): Promise<void>;
@@ -57,6 +59,9 @@ export interface CallEndpointOptions {
57
59
  store: CallEndpointStore;
58
60
  fetchImpl?: typeof fetch;
59
61
  // Not prefixed by baseUrl: the host serves this file and passes its own URL.
62
+ // Only read for a call whose lease needs end-to-end keys; a transit-only call
63
+ // (the default service mode) never loads the wasm, opens the store's key
64
+ // machine or needs a media-encrypting adapter.
60
65
  wasmUrl?: string;
61
66
  // Where the Calls service is reached, with the same rules as the control
62
67
  // client's baseUrl: HTTPS (HTTP for loopback), an optional path prefix, no
package/browser.mjs CHANGED
@@ -42,31 +42,42 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
42
42
  const resolveToken = tokenResolver(token, () => Object.assign(new Error('invalid_token'), { code: 'invalid_token' }));
43
43
  const configured = base !== undefined || token !== undefined;
44
44
  const url = path => base ? new URL(path.replace(/^\/+/, ''), base).href : path;
45
- const missing = environmentSupport();
45
+ // WebAssembly is only for the end-to-end key machine, so a call that needs
46
+ // no keys runs without it; requireE2EE() checks it when a call does.
47
+ const unsupported = environmentSupport(), missing = unsupported.filter(name => name !== 'webassembly');
46
48
  if (missing.length) throw Object.assign(new Error(`call_endpoint_unsupported_environment: ${missing.join(', ')}`), { code: 'call_endpoint_unsupported_environment', missing });
47
49
  // The adapter owns capture and transforms, so only it can say whether this
48
50
  // engine can encrypt media. An adapter that does not answer is taken at its
49
51
  // word, because every adapter before this one worked without being asked.
50
- if (typeof adapter.supported === 'function' && !adapter.supported()) throw Object.assign(new Error('call_endpoint_media_unsupported'), { code: 'call_endpoint_media_unsupported' });
52
+ // A transit-only call (the service says requiresE2EE false) never asks.
53
+ function requireE2EE() {
54
+ if (unsupported.includes('webassembly')) throw Object.assign(new Error('call_endpoint_unsupported_environment: webassembly'), { code: 'call_endpoint_unsupported_environment', missing: ['webassembly'] });
55
+ if (typeof adapter.supported === 'function' && !adapter.supported()) throw Object.assign(new Error('call_endpoint_media_unsupported'), { code: 'call_endpoint_media_unsupported' });
56
+ }
51
57
  const media = new MediaLifecycle(adapter, { onExpire: () => { desired = undefined; }, onMediaChange: () => notify() }), gate = new GenerationKeys();
52
58
  // Key exchange runs itself: the loop distributes, pumps receipts, acknowledges
53
59
  // and commits. No application or test controller drives those steps.
54
60
  const loop = new CallLoop({
55
61
  async status() {
56
- if (!roster || !credential || !machine) return { active: false };
62
+ if (!roster || !credential || !(machine || transit)) return { active: false };
63
+ // Transit: nothing to exchange, so the loop only refreshes the roster and brings media back.
64
+ if (transit) return { active: true, hasOwnKey: true, keyPins: 'transit', rosterPins: 'transit', pendingRotation: false, renewRequested: false, wantsMedia: !!desired && media.state === 'paused', awaiting: 0 };
57
65
  return {
58
66
  active: true, hasOwnKey: !!ownKey, keyPins: ownKeyPins, rosterPins: rosterPins(),
59
67
  pendingRotation: !!pendingKey, renewRequested, wantsMedia: !!desired && media.state === 'paused',
60
68
  awaiting: pendingKey ? [...pendingKey.expected].filter(p => !pendingKey.acknowledgements.has(p)).length : 0,
61
69
  };
62
70
  },
63
- receive: () => api.receive(),
71
+ receive: () => transit ? api.refresh() : api.receive(),
64
72
  distribute: () => api.distribute(),
65
73
  commit: () => api.commitKey(),
66
74
  resume: () => api.connect(desired),
67
75
  });
68
76
  let machine, identity, credential, roster, ownKey, ownKeyPins, since, control, poll;
69
77
  let controlEpoch = 0, deviceKeys, endpoint, pendingKey;
78
+ // True once the service has said this call needs no end-to-end keys: no
79
+ // device keys, key store, key exchange or gateway, only the media lease.
80
+ let transit = false;
70
81
  let gatewayExpiresAt = 0, gatewaySpanMs = 0, controlExpiresAt = 0, controlSpanMs = 0, renewRequested = false;
71
82
  // Credential renewal is independent of media: a paused or waiting endpoint
72
83
  // still has to keep the credentials it needs to come back.
@@ -154,7 +165,7 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
154
165
  // reports except the adapter's own numbers, which notify() never waits on
155
166
  // unless this actually changed.
156
167
  function snapshotKey() {
157
- 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]);
168
+ 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 && (transit || !!gate.entryFor(p.userId))).length : 0, participants(), gatewayExpiresAt, controlExpiresAt, pendingKey ? [...pendingKey.expected].filter(p => !pendingKey.acknowledgements.has(p)).length : null, endedCause]);
158
169
  }
159
170
  // Tells a real change apart from an internal tick: only one reaches
160
171
  // adapter.stats() or a callback, and one subscriber throwing never stops
@@ -222,6 +233,8 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
222
233
  if (!control) throw new Error('endpoint_control_unavailable');
223
234
  store.save({ ...store.read(), control });
224
235
  const reserved = await controlCall('bootstrap', {});
236
+ if (reserved.requiresE2EE === false) return this.adoptTransit(reserved);
237
+ requireE2EE();
225
238
  // Retain the same keys when a successful finish response was lost.
226
239
  if (!machine || identity.userId !== reserved.userId || identity.deviceId !== reserved.deviceId) await this.initialize(reserved);
227
240
  const finished = await controlCall('bootstrap-finish', { bootstrapId: reserved.bootstrapId, deviceKeys });
@@ -231,6 +244,34 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
231
244
  notify();
232
245
  return { ...reserved, expiresAt: finished.expiresAt };
233
246
  },
247
+ // The service issued the media credential straight from the admission.
248
+ // Everything the key path owns is dropped, so a transit call never opens
249
+ // the key store or loads the crypto machine.
250
+ async adoptTransit(reserved) {
251
+ controlEpoch++;
252
+ clearInterval(poll); clearInterval(credentialTimer);
253
+ await media.pause(); gate.stop(); ownKey = undefined; ownKeyPins = undefined; pendingKey = undefined; since = undefined;
254
+ endpoint?.close(); endpoint = undefined; machine = undefined; deviceKeys = undefined;
255
+ transit = true;
256
+ identity = { userId: reserved.userId, deviceId: reserved.deviceId };
257
+ credential = reserved.credential;
258
+ gatewayExpiresAt = reserved.expiresAt; gatewaySpanMs = Math.max(1, reserved.expiresAt - Date.now());
259
+ this.startRenewal();
260
+ notify();
261
+ return { userId: reserved.userId, deviceId: reserved.deviceId, expiresAt: reserved.expiresAt };
262
+ },
263
+ // A transit credential is renewed by asking again. A roster change moves
264
+ // the call to a new generation, and the same request returns its new
265
+ // identity for a seat that is still admitted; a removed seat is refused.
266
+ async renewTransit() {
267
+ const renewed = await controlCall('bootstrap', {});
268
+ if (renewed.requiresE2EE !== false || typeof renewed.credential !== 'string') throw new Error('stale_provider_identity');
269
+ const moved = renewed.userId !== identity.userId;
270
+ identity = { userId: renewed.userId, deviceId: renewed.deviceId };
271
+ credential = renewed.credential;
272
+ gatewayExpiresAt = renewed.expiresAt; gatewaySpanMs = Math.max(1, renewed.expiresAt - Date.now());
273
+ return moved;
274
+ },
234
275
  // Renewal of the credentials a live call holds. Neither call pauses media:
235
276
  // the control credential is rotated by the service, and the gateway
236
277
  // credential is re-issued for the same provider identity and device keys.
@@ -274,7 +315,10 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
274
315
  controlExpiresAt = rotated.expiresAt; controlSpanMs = Math.max(1, rotated.expiresAt - now);
275
316
  store.save({ ...store.read(), control });
276
317
  }
277
- if (credential && gatewayExpiresAt - now < gatewaySpanMs / 2) {
318
+ if (credential && transit && gatewayExpiresAt - now < gatewaySpanMs / 2) {
319
+ // Media stays up when the identity is unchanged; a new identity means a new generation, so media comes back through the loop.
320
+ if (await this.renewTransit()) await this.pauseMedia();
321
+ } else if (credential && gatewayExpiresAt - now < gatewaySpanMs / 2) {
278
322
  const reserved = await controlCall('bootstrap', {});
279
323
  if (reserved.userId !== identity.userId || reserved.deviceId !== identity.deviceId) { await this.pause(); throw new Error('stale_provider_identity'); }
280
324
  const finished = await controlCall('bootstrap-finish', { bootstrapId: reserved.bootstrapId, deviceKeys });
@@ -306,9 +350,10 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
306
350
  // An application asks for a fresh sender key; the loop performs the exchange.
307
351
  renewKey() { renewRequested = true; },
308
352
  // Take part in key exchange again after an explicit stop.
309
- rejoin() { if (roster && credential && machine) loop.start(); },
353
+ rejoin() { if (roster && credential && (machine || transit)) loop.start(); },
310
354
  async initialize(value) {
311
355
  controlEpoch++;
356
+ transit = false;
312
357
  clearInterval(poll); clearInterval(credentialTimer);
313
358
  await media.pause(); gate.stop(); ownKey = undefined; ownKeyPins = undefined; credential = undefined; since = undefined;
314
359
  endpoint?.close(); endpoint = undefined; machine = undefined;
@@ -323,6 +368,7 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
323
368
  try {
324
369
  await media.pause(); ownKey = undefined; ownKeyPins = undefined;
325
370
  roster = await controlCall('state', { credential }); gate.setRoster(roster);
371
+ if (transit) return;
326
372
  const saved = store.read().received;
327
373
  if (saved?.generationId === roster.generationId) gate.restoreIndices(saved.indices);
328
374
  if (this.upload) await machine.markRequestAsSent(this.upload.id, this.upload.type, JSON.stringify(await call('keys/upload', this.upload.body)));
@@ -335,6 +381,7 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
335
381
  // as every other gateway call; a lifecycle change is worth a snapshot
336
382
  // even here, where nothing else this function does changes one.
337
383
  try {
384
+ if (transit) { loop.start(); return; }
338
385
  const request = machine.queryKeysForUsers(roster.peers.map(p => new Rust.UserId(p.userId)));
339
386
  const device_keys = Object.fromEntries(roster.peers.map(p => [p.userId, [p.deviceId]]));
340
387
  await machine.markRequestAsSent(request.id, request.type, JSON.stringify(await call('keys/query', { device_keys })));
@@ -409,10 +456,18 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
409
456
  return accepted.length;
410
457
  } finally { notify(); }
411
458
  },
412
- async refresh() {
459
+ async refresh(renewed = false) {
413
460
  let current;
414
461
  try { current = await controlCall('state', { credential }); }
415
- catch (error) {
462
+ catch (failure) {
463
+ let error = failure;
464
+ // The credential of a transit call is bound to one generation. When a
465
+ // roster change ends it, one renewal either moves this seat to the new
466
+ // generation or is refused, and the refusal is handled as below.
467
+ if (transit && !renewed && error.code === 'conflict' && error.reason === 'connection_unavailable') {
468
+ try { await this.renewTransit(); return await this.refresh(true); }
469
+ catch (inner) { if (inner.message === 'stale_control_state') throw inner; error = inner; }
470
+ }
416
471
  // control.mjs's `state` action never refuses with anything but this
417
472
  // one code (Control.read, packages/service/src/control.mjs): this
418
473
  // endpoint's binding no longer holds. refresh() only runs once a call
@@ -455,13 +510,13 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
455
510
  // already inside the loop's one in-flight pass (fromLoop: true).
456
511
  await this.renewCredentials(true);
457
512
  await this.refresh();
458
- const keys = roster.peers.map(p => p.userId === identity.userId ? ownKey : gate.entryFor(p.userId));
459
- if (keys.some(key => !key)) throw new Error('media_authority_unavailable');
460
- const lease = await controlCall('media', { credential, generationId: roster.generationId, revision: roster.revision, mode, e2ee: true });
461
- if (lease.generationId !== roster.generationId || lease.revision !== roster.revision || lease.requiresE2EE !== true) { await this.pause(); throw new Error('stale_control_state'); }
513
+ const keys = transit ? undefined : roster.peers.map(p => p.userId === identity.userId ? ownKey : gate.entryFor(p.userId));
514
+ if (keys?.some(key => !key)) throw new Error('media_authority_unavailable');
515
+ const lease = await controlCall('media', { credential, generationId: roster.generationId, revision: roster.revision, mode, e2ee: !transit });
516
+ if (lease.generationId !== roster.generationId || lease.revision !== roster.revision || lease.requiresE2EE !== !transit) { await this.pause(); throw new Error('stale_control_state'); }
462
517
  const expiresAt = Math.min(lease.expiresAt, roster.expiresAt, Date.now() + maxLeaseMs);
463
518
  desired = { mode, maxLeaseMs }; loop.start();
464
- try { await media.activate({ ...lease, keys, localIdentity: identity.userId, expiresAt }); } finally { notify(); }
519
+ try { await media.activate({ ...lease, keys, localIdentity: identity.userId, expiresAt, e2ee: !transit }); } finally { notify(); }
465
520
  let leaseSpanMs = expiresAt - Date.now(), pending = false;
466
521
  poll = setInterval(() => {
467
522
  if (pending || renewing) return; pending = true;
@@ -475,8 +530,8 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
475
530
  // is caught by extend()'s own guard rather than racing it here.
476
531
  if (media.state === 'ready' && media.deadline - Date.now() < leaseSpanMs / 2) {
477
532
  const epoch = media.epoch;
478
- const renewed = await controlCall('media', { credential, generationId: roster.generationId, revision: roster.revision, mode, e2ee: true });
479
- if (renewed.generationId !== roster.generationId || renewed.revision !== roster.revision || renewed.requiresE2EE !== true) { await this.pause(); throw new Error('stale_control_state'); }
533
+ const renewed = await controlCall('media', { credential, generationId: roster.generationId, revision: roster.revision, mode, e2ee: !transit });
534
+ if (renewed.generationId !== roster.generationId || renewed.revision !== roster.revision || renewed.requiresE2EE !== !transit) { await this.pause(); throw new Error('stale_control_state'); }
480
535
  const nextExpiresAt = Math.min(renewed.expiresAt, roster.expiresAt, Date.now() + maxLeaseMs);
481
536
  media.extend({ expiresAt: nextExpiresAt, epoch });
482
537
  leaseSpanMs = nextExpiresAt - Date.now();
@@ -552,7 +607,7 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
552
607
  // once (configure()), which 'admission_expired' and 'control_refused'
553
608
  // never reach. Neither is cleared once set, so both keep answering after
554
609
  // leave() and pause() the same way they did before it.
555
- 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 ? { ...endedCause, callId: control?.sessionId ?? roster?.sessionId ?? null, roomId: roster?.roomId ?? null } : null }; },
610
+ 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 && (transit || !!gate.entryFor(p.userId))).length : 0, participants: participants(), gatewayExpiresAt, controlExpiresAt, awaitingKeys: pendingKey ? [...pendingKey.expected].filter(p => !pendingKey.acknowledgements.has(p)).length : null, ended: endedCause ? { ...endedCause, callId: control?.sessionId ?? roster?.sessionId ?? null, roomId: roster?.roomId ?? null } : null }; },
556
611
  // Delivers the current snapshot at once, and again whenever notify() finds
557
612
  // one of stats()'s fields changed. No event target: a Set of callbacks is
558
613
  // the whole mechanism, and the returned function just removes one from it.
@@ -44,12 +44,18 @@ export class MediaLifecycle {
44
44
  this.adapter.stopCapture();
45
45
  return this.enqueue(() => this.adapter.leave());
46
46
  }
47
- async activate({ url, token, expiresAt, key, keys, localIdentity }) {
47
+ // e2ee false is a transit-only lease: no key of any kind may come with it.
48
+ async activate({ url, token, expiresAt, key, keys, localIdentity, e2ee = true }) {
48
49
  const draining = this.pause(); const epoch = this.epoch;
49
50
  await draining;
50
51
  if (epoch !== this.epoch) throw new Error('stale_media_transition');
51
- if (!Number.isFinite(expiresAt) || expiresAt <= this.now() || (keys !== undefined && key !== undefined) || (keys === undefined && (typeof key !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(key)))) throw new Error('media_authority_unavailable');
52
- if (keys !== undefined) this.validateKeys(keys, localIdentity);
52
+ if (!Number.isFinite(expiresAt) || expiresAt <= this.now()) throw new Error('media_authority_unavailable');
53
+ if (!e2ee) {
54
+ if (key !== undefined || keys !== undefined || typeof localIdentity !== 'string' || !localIdentity) throw new Error('media_authority_unavailable');
55
+ } else {
56
+ if ((keys !== undefined && key !== undefined) || (keys === undefined && (typeof key !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(key)))) throw new Error('media_authority_unavailable');
57
+ if (keys !== undefined) this.validateKeys(keys, localIdentity);
58
+ }
53
59
  this.deadline = expiresAt; this.state = 'connecting';
54
60
  // An expiring lease is lost authority, not a pause to recover from.
55
61
  this.timer = setTimeout(() => { this.onExpire(); this.pause().catch(() => {}); }, Math.min(2147483647, expiresAt - this.now()));
@@ -70,7 +76,7 @@ export class MediaLifecycle {
70
76
  // refresh(), which pauses on a new roster revision
71
77
  // (packages/sdk/browser.mjs refresh()); the loop then retries.
72
78
  if (!this.valid(epoch)) throw new Error('stale_media_transition');
73
- if (!result.encryption) throw new Error('media_authority_unavailable');
79
+ if (e2ee && !result.encryption) throw new Error('media_authority_unavailable');
74
80
  // A fresh connection captures everything by default, so a mute the
75
81
  // application set before this reconnect has to be said again. It is
76
82
  // said before the state reaches 'ready', so nothing observes a window
package/index.d.ts CHANGED
@@ -46,6 +46,8 @@ export interface CallsClient {
46
46
  createGuestLink(sessionId: string, input: { validFrom: number; expiresAt: number; maxRedemptions: number; requestId: string }): Promise<OperationResult & { linkId: string; expiresAt: number; secret: string | null }>;
47
47
  revokeGuestLink(sessionId: string, input: { linkId: string; requestId: string }): Promise<OperationResult & { linkId: string }>;
48
48
  redeemGuestLink(input: { secret: string; displayName: string }): Promise<GuestHandle>;
49
+ guestPreview(secret: string): Promise<GuestPreview>;
49
50
  dispose(): void;
50
51
  }
52
+ export interface GuestPreview { companyName: string; roomName: string; hostName: string | null; inCall: { displayName: string }[]; expiresAt: number; recording: boolean; }
51
53
  export interface GuestHandle { readonly sessionId: string; readonly admissionId: string; readonly expiresAt: number; readonly state: 'waiting' | 'admitted'; status(): Promise<{ sessionId: string; admissionId: string; state: 'waiting' | 'admitted'; expiresAt: number }>; rotate(): Promise<{ sessionId: string; admissionId: string; expiresAt: number }>; leave(input: { requestId: string }): Promise<OperationResult & { admissionId: string }>; dispose(): void; }
package/index.mjs CHANGED
@@ -224,6 +224,14 @@ export function createCallsClient(options) {
224
224
  };
225
225
  });
226
226
  },
227
+ guestPreview(secret) {
228
+ if (typeof secret !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(secret)) throw new TypeError('invalid guest link');
229
+ return wire.call('/v1/guests/preview', { secret }, undefined, undefined, true).then(v => {
230
+ const str = x => { if (typeof x !== 'string') throw new CallsError('invalid_response'); return x; };
231
+ if (!v || typeof v !== 'object' || !Array.isArray(v.inCall) || typeof v.recording !== 'boolean' || !(v.hostName === null || typeof v.hostName === 'string')) throw new CallsError('invalid_response');
232
+ return { companyName: str(v.companyName), roomName: str(v.roomName), hostName: v.hostName, inCall: v.inCall.map(p => { if (!p || typeof p !== 'object') throw new CallsError('invalid_response'); return { displayName: str(p.displayName) }; }), expiresAt: expires(v.expiresAt), recording: v.recording };
233
+ });
234
+ },
227
235
  dispose() { if (!disposed) { disposed = true; wire.close(); } },
228
236
  };
229
237
  return client;
package/livekit.d.ts CHANGED
@@ -28,7 +28,10 @@ export interface LiveKitAdapterOptions {
28
28
  // `new Worker(new URL('livekit-client/dist/livekit-client.e2ee.worker.mjs', import.meta.url), { type: 'module' })`.
29
29
  // Caller-owned: this adapter never terminates it, so the same instance
30
30
  // carries through every leave()/connect() cycle a reconnect drives.
31
- worker: Worker;
31
+ // Only needed for a call that requires end-to-end keys; a transit-only call
32
+ // connects without it, and connect() on a call with keys throws
33
+ // livekit_adapter_worker_required when it is missing.
34
+ worker?: Worker;
32
35
  capture?: LiveKitCaptureOptions;
33
36
  }
34
37
 
package/livekit.mjs CHANGED
@@ -62,7 +62,6 @@ export function createLiveKitAdapter({ worker, capture = {} } = {}) {
62
62
  // drives across a reconnect. See the Decisions in the shipping report for
63
63
  // why (livekit-client's E2EEManager documents worker reuse across Room
64
64
  // instances; dist/src/e2ee/E2eeManager.d.ts's dispose() comment).
65
- if (!worker) throw new Error('livekit_adapter_worker_required');
66
65
 
67
66
  let room, keyProvider, connectionCount = 0, keyMetadata = [];
68
67
  const errors = [];
@@ -113,19 +112,26 @@ export function createLiveKitAdapter({ worker, capture = {} } = {}) {
113
112
  supported() { return isE2EESupported(); },
114
113
 
115
114
  async connect({ url, token, keys, localIdentity, controlled = true, onUnsafe = () => {}, onMediaChange } = {}) {
116
- if (!isE2EESupported()) throw new Error('e2ee_unavailable');
117
- validateKeys(keys, localIdentity);
115
+ // No keys means a transit-only call: the lease said requiresE2EE false,
116
+ // so there is no key provider, no worker and no isE2EESupported() check.
117
+ const e2ee = keys !== undefined;
118
+ if (e2ee && !isE2EESupported()) throw new Error('e2ee_unavailable');
119
+ if (e2ee && !worker) throw new Error('livekit_adapter_worker_required');
120
+ if (e2ee) validateKeys(keys, localIdentity);
118
121
  onMediaChangeCb = typeof onMediaChange === 'function' ? onMediaChange : () => {};
119
- keyMetadata = keys.map(({ identity, index }) => ({ identity, index }));
120
- keyProvider = new SenderKeyProvider(localIdentity);
121
- // Install the local identity's key last: the same ordering the engine
122
- // itself relies on elsewhere, so a partial install never leaves a peer
123
- // key in place without the local one.
124
- for (const entry of [...keys].sort((a, b) => (a.identity === localIdentity ? 1 : 0) - (b.identity === localIdentity ? 1 : 0))) await keyProvider.setSenderKey(entry.key, entry.identity, entry.index);
122
+ keyMetadata = e2ee ? keys.map(({ identity, index }) => ({ identity, index })) : [];
123
+ keyProvider = undefined;
124
+ if (e2ee) {
125
+ keyProvider = new SenderKeyProvider(localIdentity);
126
+ // Install the local identity's key last: the same ordering the engine
127
+ // itself relies on elsewhere, so a partial install never leaves a peer
128
+ // key in place without the local one.
129
+ for (const entry of [...keys].sort((a, b) => (a.identity === localIdentity ? 1 : 0) - (b.identity === localIdentity ? 1 : 0))) await keyProvider.setSenderKey(entry.key, entry.identity, entry.index);
130
+ }
125
131
  const activeRoom = new Room({
126
132
  adaptiveStream: false, dynacast: false,
127
133
  ...(controlled ? { reconnectPolicy: { nextRetryDelayInMs: () => null } } : {}),
128
- e2ee: { keyProvider, worker },
134
+ ...(e2ee ? { e2ee: { keyProvider, worker } } : {}),
129
135
  publishDefaults: { videoCodec: 'vp8', simulcast: false },
130
136
  ...(preferredDevice.audiooutput ? { audioOutput: { deviceId: preferredDevice.audiooutput } } : {}),
131
137
  });
@@ -166,10 +172,10 @@ export function createLiveKitAdapter({ worker, capture = {} } = {}) {
166
172
  RoomEvent.ParticipantConnected, RoomEvent.ParticipantDisconnected,
167
173
  RoomEvent.MediaDevicesChanged,
168
174
  ]) room.on(event, notify);
169
- await activeRoom.setE2EEEnabled(true);
175
+ if (e2ee) await activeRoom.setE2EEEnabled(true);
170
176
  await activeRoom.connect(url, token, { autoSubscribe: true, maxRetries: 0, peerConnectionTimeout: 15000 });
171
177
  connectionCount++;
172
- return { state: activeRoom.state, encryption: activeRoom.isE2EEEnabled };
178
+ return { state: activeRoom.state, encryption: e2ee && activeRoom.isE2EEEnabled };
173
179
  },
174
180
 
175
181
  async installKeys(entries) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/calls",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Framework-independent SDK for Agora calls: session control (admission, guest links, moderation) and a media-ready browser call handle.",
5
5
  "license": "MIT",
6
6
  "type": "module",