@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.
@@ -0,0 +1,71 @@
1
+ /** Endpoint key scheduling. The loop decides WHEN a key is made, delivered,
2
+ * acknowledged and committed; it never holds key material and never relaxes a
3
+ * check. Every step is an injected endpoint operation that enforces its own
4
+ * authority, so a refused step only costs the loop a backoff.
5
+ */
6
+ export class CallLoop {
7
+ // Timers are wrapped, never passed by reference: a bare setTimeout called
8
+ // as a method throws Illegal invocation in a browser.
9
+ constructor(steps, { intervalMs = 500, retryMs = 1000, maxRetryMs = 8000, setTimer = (fn, ms) => setTimeout(fn, ms), clearTimer = value => clearTimeout(value) } = {}) {
10
+ for (const name of ['status', 'receive', 'distribute', 'commit']) {
11
+ if (typeof steps?.[name] !== 'function') throw new Error('call_loop_steps_required');
12
+ }
13
+ if (![intervalMs, retryMs, maxRetryMs].every(v => Number.isInteger(v) && v > 0) || retryMs > maxRetryMs) throw new Error('call_loop_interval_invalid');
14
+ this.steps = steps; this.intervalMs = intervalMs; this.retryMs = retryMs; this.maxRetryMs = maxRetryMs;
15
+ this.setTimer = setTimer; this.clearTimer = clearTimer;
16
+ this.running = false; this.timer = null; this.backoff = 0; this.epoch = 0; this.failures = 0; this.pass = Promise.resolve();
17
+ }
18
+ start() {
19
+ if (this.running) return;
20
+ this.running = true; this.backoff = 0; this.failures = 0; this.epoch++;
21
+ this.arm(0);
22
+ }
23
+ stop() {
24
+ this.running = false; this.epoch++;
25
+ this.clearTimer(this.timer); this.timer = null;
26
+ }
27
+ arm(delay) {
28
+ const epoch = this.epoch;
29
+ this.clearTimer(this.timer);
30
+ this.timer = this.setTimer(() => { if (this.running && epoch === this.epoch) this.pass = this.run(epoch); }, delay);
31
+ }
32
+ /** Stop and wait for the pass in flight. A credential rotation runs while
33
+ * the loop is quiet, so no gateway request is left holding an old one.
34
+ */
35
+ async quiesce() {
36
+ this.stop();
37
+ try { await this.pass; } catch {}
38
+ }
39
+ async run(epoch) {
40
+ // One pass at a time. A pass that outlives its own interval never overlaps
41
+ // the next, and a stop during a pass discards its result.
42
+ try {
43
+ await this.tick();
44
+ if (!this.running || epoch !== this.epoch) return;
45
+ this.backoff = 0; this.failures = 0;
46
+ this.arm(this.intervalMs);
47
+ } catch {
48
+ if (!this.running || epoch !== this.epoch) return;
49
+ this.failures++;
50
+ this.backoff = Math.min(this.backoff ? this.backoff * 2 : this.retryMs, this.maxRetryMs);
51
+ this.arm(this.backoff);
52
+ }
53
+ }
54
+ async tick() {
55
+ const before = await this.steps.status();
56
+ if (!before?.active) return;
57
+ await this.steps.receive();
58
+ const after = await this.steps.status();
59
+ if (!after?.active) return;
60
+ // A pending rotation is finished before a new one starts, and a new key is
61
+ // made only when this endpoint has none or the pinned roster has changed.
62
+ if (after.pendingRotation) {
63
+ if (after.awaiting === 0) await this.steps.commit();
64
+ return;
65
+ }
66
+ if (!after.hasOwnKey || after.rosterPins !== after.keyPins || after.renewRequested) { await this.steps.distribute(); return; }
67
+ // Media the application asked for comes back by itself once the keys for
68
+ // the current roster are in place. An explicit pause clears that intent.
69
+ if (after.wantsMedia && typeof this.steps.resume === 'function') await this.steps.resume();
70
+ }
71
+ }
@@ -0,0 +1,69 @@
1
+ import * as Rust from '@matrix-org/matrix-sdk-crypto-wasm';
2
+ export { Rust };
3
+ /** Private endpoint prototype. Only this endpoint's Rust crypto machine can
4
+ * produce accepted events. Roster public-key pins come from authenticated Calls
5
+ * control traffic; media-key material is never sent to the Calls service.
6
+ */
7
+ export class GenerationKeys {
8
+ constructor({ now = Date.now } = {}) { this.now = now; this.roster = null; this.keys = new Map(); this.indices = new Map(); this.sessionId = null; this.revision = -1; this.generationId = null; }
9
+ setRoster(roster) {
10
+ if (!roster || !Number.isFinite(roster.expiresAt) || !roster.sessionId || !roster.generationId || !Number.isSafeInteger(roster.revision) || roster.revision < 1) throw new Error('Invalid key roster');
11
+ if ((this.sessionId && this.sessionId !== roster.sessionId) || roster.revision < this.revision || (roster.revision === this.revision && roster.generationId !== this.generationId)) throw new Error('Stale key roster');
12
+ const changed = this.generationId !== roster.generationId || this.sessionId !== roster.sessionId;
13
+ this.sessionId = roster.sessionId; this.revision = roster.revision; this.generationId = roster.generationId;
14
+ if (changed) {
15
+ this.keys.clear(); this.indices.clear();
16
+ }
17
+ for (const user of this.keys.keys()) {
18
+ const previous = this.roster?.peers.find(p => p.userId === user);
19
+ const current = roster.peers.find(p => p.userId === user);
20
+ if (!current || previous?.deviceId !== current.deviceId || previous?.curve25519Key !== current.curve25519Key || previous?.ed25519Key !== current.ed25519Key) this.keys.delete(user);
21
+ }
22
+ this.roster = structuredClone(roster);
23
+ }
24
+ keyFor(userId) {
25
+ if (!this.roster || this.now() >= this.roster.expiresAt) { this.stop(); return null; }
26
+ return this.keys.get(userId) ?? null;
27
+ }
28
+ stop() { this.roster = null; this.keys.clear(); }
29
+ entryFor(userId) {
30
+ const key = this.keyFor(userId);
31
+ return key ? { identity: userId, key, index: this.indices.get(userId) } : null;
32
+ }
33
+ restoreIndices(entries) {
34
+ for (const [userId, index] of entries) {
35
+ if (!this.roster?.peers.some(p => p.userId === userId) || !Number.isSafeInteger(index) || index < 0 || index > 255) throw new Error('Invalid saved key index');
36
+ this.indices.set(userId, Math.max(index, this.indices.get(userId) ?? -1));
37
+ }
38
+ }
39
+ async receive(machine, sync, { onAck = () => {}, onRequest = () => {} } = {}) {
40
+ const roster = this.roster;
41
+ if (!roster || this.now() >= roster.expiresAt) { this.stop(); throw new Error('Key authority unavailable'); }
42
+ const events = await machine.receiveSyncChanges(JSON.stringify(sync.to_device?.events ?? []), new Rust.DeviceLists(), new Map(Object.entries(sync.device_one_time_keys_count ?? {})), new Set(sync.device_unused_fallback_key_types ?? []));
43
+ if (this.roster !== roster || this.now() >= roster.expiresAt) { this.keys.clear(); throw new Error('Key authority changed'); }
44
+ const accepted = [];
45
+ for (const event of events) {
46
+ if (!(event instanceof Rust.DecryptedToDeviceEvent)) continue;
47
+ const raw = JSON.parse(event.rawEvent), info = event.encryptionInfo;
48
+ if (!['io.wtfalch.calls.media_key', 'io.wtfalch.calls.media_key_ack', 'io.wtfalch.calls.media_key_request'].includes(raw.type)) continue;
49
+ const peer = roster.peers.find(p => p.userId === raw.sender && p.deviceId === info.senderDevice?.toString());
50
+ if (!peer || info.sender.toString() !== raw.sender || info.senderCurve25519Key !== peer.curve25519Key) continue;
51
+ const c = raw.content;
52
+ if (!c || typeof c !== 'object' || Array.isArray(c)) continue;
53
+ if (c.session_id !== roster.sessionId || c.generation_id !== roster.generationId || c.sender_device !== peer.deviceId || !Number.isSafeInteger(c.index) || c.index < 0 || c.index > 255) continue;
54
+ if (raw.type === 'io.wtfalch.calls.media_key_request') { onRequest({ userId: peer.userId }); continue; }
55
+ if (raw.type === 'io.wtfalch.calls.media_key_ack') {
56
+ if (typeof c.for_user_id === 'string' && typeof c.rotation_id === 'string') onAck({ userId: peer.userId, forUserId: c.for_user_id, index: c.index, rotationId: c.rotation_id });
57
+ continue;
58
+ }
59
+ // A key already accepted may be delivered again after this endpoint
60
+ // dropped it, but an older index is never accepted back.
61
+ const known = this.indices.get(peer.userId) ?? -1;
62
+ if (c.index < known || (c.index === known && this.keys.has(peer.userId))) continue;
63
+ if (typeof c.key !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(c.key)) continue;
64
+ this.indices.set(peer.userId, c.index); this.keys.set(peer.userId, c.key);
65
+ accepted.push({ userId: peer.userId, generationId: roster.generationId, key: c.key, index: c.index, rotationId: c.rotation_id });
66
+ }
67
+ return accepted;
68
+ }
69
+ }
@@ -0,0 +1,188 @@
1
+ /** Endpoint-only publication gate. It receives key material from the local
2
+ * authenticated key gate, never from the SFU or Calls control service.
3
+ */
4
+ export class MediaLifecycle {
5
+ constructor(adapter, { now = Date.now, onExpire = () => {}, onMediaChange = () => {} } = {}) {
6
+ this.adapter = adapter; this.now = now; this.onExpire = onExpire; this.onMediaChange = onMediaChange; this.epoch = 0; this.state = 'paused';
7
+ this.tail = Promise.resolve(); this.deadline = 0; this.timer = null;
8
+ // Local capture flags, not the room's, and what the application asked
9
+ // for rather than where the transport happens to be. A pause keeps them:
10
+ // the engine pauses and resumes media by itself on every roster and
11
+ // generation change, and a mute that a stranger joining could undo would
12
+ // be worse than no mute at all. Only leave() clears them.
13
+ this.microphoneEnabled = true; this.cameraEnabled = true;
14
+ // Whether a share is live. This one does NOT survive a pause, and that is
15
+ // the opposite of the two above on purpose. A mute is a flag on a track
16
+ // the adapter still holds, so it can be set again on a new connection. A
17
+ // share is a capture the browser only grants to a user gesture, and
18
+ // pause() releases it through stopCapture(). Re-publishing it from an
19
+ // automatic reconnect would either throw, because no gesture is in scope,
20
+ // or open a screen picker the user never asked for -- in the middle of a
21
+ // call, attributed to nothing they did. So a reconnect ends the share and
22
+ // the snapshot says so, and the application offers to share again.
23
+ this.screenSharing = false;
24
+ }
25
+ resetCapture() { this.microphoneEnabled = true; this.cameraEnabled = true; this.screenSharing = false; }
26
+ valid(epoch) { return epoch === this.epoch && this.now() < this.deadline; }
27
+ enqueue(work) { const next = this.tail.then(work); this.tail = next.catch(() => {}); return next; }
28
+ validateKeys(keys, localIdentity) {
29
+ if (!Array.isArray(keys) || !keys.length || typeof localIdentity !== 'string' || !localIdentity) throw new Error('media_authority_unavailable');
30
+ const identities = new Set(); let local = 0;
31
+ for (const entry of keys) {
32
+ if (!entry || typeof entry.identity !== 'string' || !entry.identity || identities.has(entry.identity) || !Number.isInteger(entry.index) || entry.index < 0 || entry.index > 255 || typeof entry.key !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(entry.key)) throw new Error('media_authority_unavailable');
33
+ identities.add(entry.identity); if (entry.identity === localIdentity) local++;
34
+ }
35
+ if (local !== 1) throw new Error('media_authority_unavailable');
36
+ }
37
+ pause() {
38
+ this.epoch++; this.state = 'paused'; this.deadline = 0; clearTimeout(this.timer);
39
+ // stopCapture() below releases the shared display track, so the share is
40
+ // over whether or not anything says so. Recording that here keeps the
41
+ // snapshot honest instead of reporting a share the user can no longer see.
42
+ this.screenSharing = false;
43
+ // Stop capture synchronously, even if connection establishment is awaiting IO.
44
+ this.adapter.stopCapture();
45
+ return this.enqueue(() => this.adapter.leave());
46
+ }
47
+ async activate({ url, token, expiresAt, key, keys, localIdentity }) {
48
+ const draining = this.pause(); const epoch = this.epoch;
49
+ await draining;
50
+ 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);
53
+ this.deadline = expiresAt; this.state = 'connecting';
54
+ // An expiring lease is lost authority, not a pause to recover from.
55
+ this.timer = setTimeout(() => { this.onExpire(); this.pause().catch(() => {}); }, Math.min(2147483647, expiresAt - this.now()));
56
+ return this.enqueue(async () => {
57
+ try {
58
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
59
+ // Harmless from a connection this endpoint has since replaced: pause()
60
+ // and a fresh activate() both bump the epoch before this one's own
61
+ // callback can fire again, so a late report from a superseded
62
+ // connection reaches nothing.
63
+ const result = await this.adapter.connect({ url, token, key, keys, localIdentity, controlled: true, onUnsafe: () => { this.pause().catch(() => {}); }, onMediaChange: () => { if (epoch === this.epoch) this.onMediaChange(); } });
64
+ if (!this.valid(epoch) || !result.encryption) throw new Error('media_authority_unavailable');
65
+ // A fresh connection captures everything by default, so a mute the
66
+ // application set before this reconnect has to be said again. It is
67
+ // said before the state reaches 'ready', so nothing observes a window
68
+ // where the microphone is live against the application's wish.
69
+ if (!this.microphoneEnabled) await this.adapter.setMicrophoneEnabled(false);
70
+ if (!this.cameraEnabled) await this.adapter.setCameraEnabled(false);
71
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
72
+ this.state = 'ready';
73
+ } catch (error) {
74
+ this.adapter.stopCapture(); await this.adapter.leave();
75
+ if (epoch === this.epoch) { this.state = 'paused'; this.deadline = 0; clearTimeout(this.timer); }
76
+ throw error;
77
+ }
78
+ });
79
+ }
80
+ // Renews the pause timer only. Never touches the room, tracks or keys, so
81
+ // it runs synchronously and outside the adapter work queue.
82
+ extend({ expiresAt, epoch }) {
83
+ if (epoch !== this.epoch) throw new Error('stale_media_transition');
84
+ if (this.state !== 'ready' || !Number.isFinite(expiresAt) || expiresAt <= this.deadline) throw new Error('media_authority_unavailable');
85
+ this.deadline = expiresAt;
86
+ clearTimeout(this.timer);
87
+ // An expiring lease is lost authority, not a pause to recover from.
88
+ this.timer = setTimeout(() => { this.onExpire(); this.pause().catch(() => {}); }, Math.min(2147483647, expiresAt - this.now()));
89
+ }
90
+ updateKeys(entries) {
91
+ const epoch = this.epoch;
92
+ return this.enqueue(async () => {
93
+ if (this.state !== 'ready' || !this.valid(epoch) || typeof this.adapter.installKeys !== 'function') throw new Error('media_authority_unavailable');
94
+ try {
95
+ await this.adapter.installKeys(entries);
96
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
97
+ } catch (error) {
98
+ this.adapter.stopCapture(); await this.adapter.leave();
99
+ if (epoch === this.epoch) { this.state = 'paused'; this.deadline = 0; clearTimeout(this.timer); }
100
+ throw error;
101
+ }
102
+ });
103
+ }
104
+ publish(mode) {
105
+ const epoch = this.epoch;
106
+ return this.enqueue(async () => {
107
+ if (this.state !== 'ready' || !this.valid(epoch)) throw new Error('media_authority_unavailable');
108
+ if (!['audio', 'video'].includes(mode)) throw new Error('invalid_media_mode');
109
+ try {
110
+ const authority = { canPublish: () => this.state === 'ready' && this.valid(epoch) };
111
+ await (mode === 'audio' ? this.adapter.publishAudio(authority) : this.adapter.publishVideo(authority));
112
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
113
+ } catch (error) {
114
+ this.adapter.stopCapture(); await this.adapter.leave();
115
+ this.state = 'paused'; this.deadline = 0; clearTimeout(this.timer); throw error;
116
+ }
117
+ });
118
+ }
119
+ // Local capture toggles: mute and camera on/off. Neither touches the room,
120
+ // the key gate or the lease -- the one thing pauseMedia() cannot do without
121
+ // dropping everything else.
122
+ //
123
+ // A failure is answered by which way the toggle was going, because the two
124
+ // directions fail into opposite places. Turning capture off and failing
125
+ // leaves a microphone or camera live that the application asked to stop,
126
+ // so media drops rather than lie about it. Turning capture back on and
127
+ // failing leaves it off, which is already the safe side, so the call
128
+ // carries on and only the caller's promise rejects. Tearing the call down
129
+ // there would cost the reconnection this whole feature exists to avoid.
130
+ capture(kind, enabled) {
131
+ const epoch = this.epoch;
132
+ return this.enqueue(async () => {
133
+ if (this.state !== 'ready' || !this.valid(epoch)) throw new Error('media_authority_unavailable');
134
+ try {
135
+ await (kind === 'microphone' ? this.adapter.setMicrophoneEnabled(enabled) : this.adapter.setCameraEnabled(enabled));
136
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
137
+ if (kind === 'microphone') this.microphoneEnabled = enabled; else this.cameraEnabled = enabled;
138
+ } catch (error) {
139
+ if (enabled) throw error;
140
+ this.adapter.stopCapture(); await this.adapter.leave();
141
+ this.state = 'paused'; this.deadline = 0; clearTimeout(this.timer); throw error;
142
+ }
143
+ });
144
+ }
145
+ setMicrophoneEnabled(enabled) { return this.capture('microphone', enabled); }
146
+ setCameraEnabled(enabled) { return this.capture('camera', enabled); }
147
+ // Screen share is a publication, not a capture toggle: stopping it has to
148
+ // release the capture device, not merely disable a track that would keep
149
+ // recording in the background. The failure direction still reads like
150
+ // capture() above, because the risk is the same shape. A start that fails
151
+ // shared nothing, so it leaves the call alone -- the safe side, same as a
152
+ // failed unmute. A stop that fails leaves the screen still broadcasting,
153
+ // the same leak a failed mute would be, so the call drops rather than lie
154
+ // about it being stopped.
155
+ //
156
+ // onEnded answers the one thing capture() never had to: the browser's own
157
+ // UI can end a share outside this call entirely. It clears the flag so a
158
+ // later reconnect does not silently resume a share the user already ended.
159
+ share(enabled) {
160
+ const epoch = this.epoch;
161
+ return this.enqueue(async () => {
162
+ if (this.state !== 'ready' || !this.valid(epoch)) throw new Error('media_authority_unavailable');
163
+ // Asking for what is already true costs a second screen picker and a
164
+ // second onEnded, either of which could speak for the other's share.
165
+ if (enabled === this.screenSharing) return;
166
+ try {
167
+ // The browser's own stop control ends the share without telling this
168
+ // module, so the adapter reports it here. The epoch is what makes a
169
+ // late report from an old connection harmless: it may only end the
170
+ // share it was registered for, never one started after a reconnect.
171
+ if (enabled) await this.adapter.publishScreen({ canPublish: () => this.state === 'ready' && this.valid(epoch) }, () => { if (epoch === this.epoch) this.screenSharing = false; });
172
+ else await this.adapter.unpublishScreen();
173
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
174
+ this.screenSharing = enabled;
175
+ } catch (error) {
176
+ if (enabled) throw error;
177
+ // A stop that failed leaves a screen the user asked to stop sharing,
178
+ // so media drops. The flag goes with it: pause() below clears it, and
179
+ // nothing may report a share once the capture is gone.
180
+ this.adapter.stopCapture(); await this.adapter.leave();
181
+ this.screenSharing = false;
182
+ this.state = 'paused'; this.deadline = 0; clearTimeout(this.timer); throw error;
183
+ }
184
+ });
185
+ }
186
+ startShare() { return this.share(true); }
187
+ stopShare() { return this.share(false); }
188
+ }
package/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ export class CallsError extends Error { readonly code: string; readonly status: number; }
2
+ export interface CallsClientOptions { baseUrl: string; fetch?: typeof fetch; timeoutMs?: number; }
3
+ export interface OperationResult { operationId: string; enforcement: 'pending' | 'succeeded' | 'blocked'; }
4
+ export function createCallsClient(options: CallsClientOptions): CallsClient;
5
+ export interface CallsClient {
6
+ createSession(input: { sessionId: string; roomId: string; validFrom: number; expiresAt: number; capacity: number; requestId: string }): Promise<OperationResult & { sessionId: string }>;
7
+ roomStatus(roomId: string): Promise<{ live: false } | { live: true; sessionId: string; participantCount: number }>;
8
+ invitation(roomId: string): Promise<{ invited: false } | { invited: true; sessionId: string; roomId: string; startedBy: string | null; members: string[]; decline: { reason: string; declinedAt: number } | null }>;
9
+ joinAdmission(sessionId: string, input: { video: boolean; requestId: string }): Promise<OperationResult & { admissionId: string }>;
10
+ admitGuest(sessionId: string, input: { admissionId: string; video: boolean; requestId: string }): Promise<OperationResult & { admissionId: string }>;
11
+ waiting(sessionId: string): Promise<{ waiting: { admissionId: string; displayName: string | null; waitingSince: number }[] }>;
12
+ record(sessionId: string): Promise<{ sessionId: string; startedAt: number; endedAt: number | null; participants: { admissionId: string; kind: 'member' | 'guest'; actorId?: string; displayName: string | null; admittedAt: number; departedAt: number | null }[] }>;
13
+ removeParticipant(sessionId: string, input: { admissionId: string; requestId: string }): Promise<OperationResult & { admissionId: string }>;
14
+ leave(sessionId: string, input: { requestId: string }): Promise<OperationResult & { admissionId: string }>;
15
+ decline(sessionId: string, input: { reason: string; requestId: string }): Promise<OperationResult & { sessionId: string }>;
16
+ endSession(sessionId: string, input: { requestId: string }): Promise<OperationResult & { sessionId: string }>;
17
+ createGuestLink(sessionId: string, input: { validFrom: number; expiresAt: number; maxRedemptions: number; requestId: string }): Promise<OperationResult & { linkId: string; expiresAt: number; secret: string | null }>;
18
+ revokeGuestLink(sessionId: string, input: { linkId: string; requestId: string }): Promise<OperationResult & { linkId: string }>;
19
+ redeemGuestLink(input: { secret: string; displayName: string }): Promise<GuestHandle>;
20
+ dispose(): void;
21
+ }
22
+ 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 ADDED
@@ -0,0 +1,211 @@
1
+ const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2
+ const REQUEST = /^.{1,128}$/s;
3
+ const STATES = new Set(['pending', 'succeeded', 'blocked']);
4
+ const GUEST_STATES = new Set(['waiting', 'admitted']);
5
+
6
+ export class CallsError extends Error {
7
+ constructor(code, message = code, status = 0) {
8
+ super(message); this.name = 'CallsError'; this.code = code; this.status = status;
9
+ }
10
+ }
11
+
12
+ function origin(value) {
13
+ const base = new URL(value);
14
+ if (base.username || base.password || base.search || base.hash || base.pathname !== '/' ||
15
+ (base.protocol !== 'https:' && !(base.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname)))) {
16
+ throw new TypeError('baseUrl must be an HTTPS origin');
17
+ }
18
+ return base;
19
+ }
20
+ function id(value, name) { if (typeof value !== 'string' || !ID.test(value)) throw new TypeError(`invalid ${name}`); return value; }
21
+ function responseId(value) { if (typeof value !== 'string' || !ID.test(value)) throw new CallsError('invalid_response'); return value; }
22
+ function requestId(value) { if (typeof value !== 'string' || !REQUEST.test(value)) throw new TypeError('invalid requestId'); return value; }
23
+ function jsonBody(input) { return JSON.stringify(input); }
24
+ function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new CallsError('invalid_response'); return value; }
25
+ function expires(value) { if (!Number.isSafeInteger(value)) throw new CallsError('invalid_response'); return value; }
26
+ function enforcement(value) { if (typeof value !== 'string' || !STATES.has(value)) throw new CallsError('invalid_response'); return value; }
27
+ function operationResult(value, fields = []) {
28
+ value = object(value); responseId(value.operationId); enforcement(value.enforcement);
29
+ for (const field of fields) responseId(value[field]);
30
+ return Object.fromEntries(['operationId', ...fields, 'enforcement'].map(k => [k, value[k]]));
31
+ }
32
+ function guestResult(value, expectedSession, expectedAdmission, requireCredential = false, requireState = true) {
33
+ value = object(value); responseId(value.sessionId); responseId(value.admissionId);
34
+ if (expectedSession && value.sessionId !== expectedSession || expectedAdmission && value.admissionId !== expectedAdmission) throw new CallsError('invalid_response');
35
+ expires(value.expiresAt); if (requireState && (typeof value.state !== 'string' || !GUEST_STATES.has(value.state))) throw new CallsError('invalid_response');
36
+ if (requireCredential && (typeof value.credential !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value.credential))) throw new CallsError('invalid_response');
37
+ return { sessionId: value.sessionId, admissionId: value.admissionId, expiresAt: value.expiresAt, ...(requireState ? { state: value.state } : {}), ...(requireCredential ? { credential: value.credential } : {}) };
38
+ }
39
+ function roomStatusResult(value) {
40
+ value = object(value);
41
+ if (typeof value.live !== 'boolean') throw new CallsError('invalid_response');
42
+ if (!value.live) return { live: false };
43
+ responseId(value.sessionId);
44
+ if (!Number.isInteger(value.participantCount) || value.participantCount < 0) throw new CallsError('invalid_response');
45
+ return { live: true, sessionId: value.sessionId, participantCount: value.participantCount };
46
+ }
47
+ function invitationResult(value) {
48
+ value = object(value);
49
+ if (typeof value.invited !== 'boolean') throw new CallsError('invalid_response');
50
+ if (!value.invited) return { invited: false };
51
+ responseId(value.sessionId);
52
+ if (typeof value.roomId !== 'string' || value.roomId.length < 1 || value.roomId.length > 128) throw new CallsError('invalid_response');
53
+ if (value.startedBy !== null && typeof value.startedBy !== 'string') throw new CallsError('invalid_response');
54
+ if (!Array.isArray(value.members) || !value.members.every(m => typeof m === 'string')) throw new CallsError('invalid_response');
55
+ let decline = null;
56
+ if (value.decline !== null) {
57
+ const d = object(value.decline);
58
+ if (typeof d.reason !== 'string' || d.reason.length < 1 || d.reason.length > 500) throw new CallsError('invalid_response');
59
+ decline = { reason: d.reason, declinedAt: expires(d.declinedAt) };
60
+ }
61
+ return { invited: true, sessionId: value.sessionId, roomId: value.roomId, startedBy: value.startedBy, members: value.members, decline };
62
+ }
63
+ function waitingResult(value) {
64
+ value = object(value);
65
+ if (!Array.isArray(value.waiting)) throw new CallsError('invalid_response');
66
+ return { waiting: value.waiting.map(entry => {
67
+ entry = object(entry);
68
+ responseId(entry.admissionId);
69
+ // displayName is guest-declared and bounded only by length server-side
70
+ // (guest-links.mjs redeem()); a host-bridge guest (requestGuest() with
71
+ // no GuestLinks) has none, so null is valid alongside the length bound.
72
+ if (entry.displayName !== null && (typeof entry.displayName !== 'string' || entry.displayName.length < 1 || entry.displayName.length > 80)) throw new CallsError('invalid_response');
73
+ return { admissionId: entry.admissionId, displayName: entry.displayName, waitingSince: expires(entry.waitingSince) };
74
+ }) };
75
+ }
76
+ function recordResult(value) {
77
+ value = object(value);
78
+ responseId(value.sessionId); expires(value.startedAt);
79
+ if (value.endedAt !== null) expires(value.endedAt);
80
+ if (!Array.isArray(value.participants)) throw new CallsError('invalid_response');
81
+ return { sessionId: value.sessionId, startedAt: value.startedAt, endedAt: value.endedAt, participants: value.participants.map(entry => {
82
+ entry = object(entry);
83
+ responseId(entry.admissionId);
84
+ if (entry.kind !== 'member' && entry.kind !== 'guest') throw new CallsError('invalid_response');
85
+ if ('actorId' in entry && typeof entry.actorId !== 'string') throw new CallsError('invalid_response');
86
+ // displayName is guest-declared and bounded only by length server-side
87
+ // (guest-links.mjs redeem()); a member's is always null, same as waiting().
88
+ if (entry.displayName !== null && (typeof entry.displayName !== 'string' || entry.displayName.length < 1 || entry.displayName.length > 80)) throw new CallsError('invalid_response');
89
+ expires(entry.admittedAt); if (entry.departedAt !== null) expires(entry.departedAt);
90
+ return { admissionId: entry.admissionId, kind: entry.kind, ...('actorId' in entry ? { actorId: entry.actorId } : {}), displayName: entry.displayName, admittedAt: entry.admittedAt, departedAt: entry.departedAt };
91
+ }) };
92
+ }
93
+ function failure(response, value) {
94
+ const error = value && typeof value === 'object' && value.error && typeof value.error === 'object' ? value.error : {};
95
+ const code = typeof error.code === 'string' && /^[a-z0-9_:-]{1,80}$/.test(error.code) ? error.code : 'request_failed';
96
+ return new CallsError(code, code, response.status);
97
+ }
98
+
99
+ function transport({ baseUrl, fetch: fetcher = globalThis.fetch, timeoutMs = 30000 }) {
100
+ const base = origin(baseUrl);
101
+ if (typeof fetcher !== 'function') throw new TypeError('fetch is required');
102
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) throw new TypeError('invalid timeoutMs');
103
+ let closed = false;
104
+ const call = async (path, body, bearer, epoch, omitCredentials = false) => {
105
+ if (closed || (epoch !== undefined && epoch !== stateEpoch)) throw new CallsError('disposed');
106
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
107
+ try {
108
+ const response = await fetcher(new URL(path, base), {
109
+ method: 'POST', redirect: 'error', credentials: (bearer || omitCredentials) ? 'omit' : 'same-origin',
110
+ headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
111
+ body: body === undefined ? undefined : jsonBody(body), signal: controller.signal,
112
+ });
113
+ let value; try { value = await response.json(); } catch { throw new CallsError('invalid_response', 'invalid_response', response.status); }
114
+ if (closed || (epoch !== undefined && epoch !== stateEpoch)) throw new CallsError('disposed');
115
+ if (!response.ok) throw failure(response, value);
116
+ if (!value || typeof value !== 'object') throw new CallsError('invalid_response', 'invalid_response', response.status);
117
+ return value;
118
+ } catch (error) {
119
+ if (error instanceof CallsError) throw error;
120
+ if (error?.name === 'AbortError') throw new CallsError('request_timeout');
121
+ throw new CallsError('network_error');
122
+ } finally { clearTimeout(timer); }
123
+ };
124
+ let stateEpoch = 0;
125
+ return { call, close() { closed = true; stateEpoch++; }, epoch() { return stateEpoch; }, base };
126
+ }
127
+
128
+ function sessionPath(sessionId, action) { return `/v1/sessions/${id(sessionId, 'sessionId')}/${action}`; }
129
+
130
+ export function createCallsClient(options) {
131
+ const wire = transport(options); let disposed = false;
132
+ const run = (path, body) => { if (disposed) return Promise.reject(new CallsError('disposed')); const epoch = wire.epoch(); return wire.call(path, body, undefined, epoch); };
133
+ const client = {
134
+ createSession(input) {
135
+ if (!input || typeof input !== 'object') throw new TypeError('invalid session');
136
+ if (typeof input.roomId !== 'string' || input.roomId.length < 1 || input.roomId.length > 128 || !Number.isSafeInteger(input.validFrom) || !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= input.validFrom || !Number.isInteger(input.capacity) || input.capacity < 1 || input.capacity > 1000) throw new TypeError('invalid session');
137
+ const body = { sessionId: id(input.sessionId, 'sessionId'), roomId: input.roomId, validFrom: input.validFrom, expiresAt: input.expiresAt, capacity: input.capacity, requestId: requestId(input.requestId) };
138
+ return run('/v1/sessions', body).then(v => operationResult(v, ['sessionId']));
139
+ },
140
+ roomStatus(roomId) {
141
+ if (typeof roomId !== 'string' || roomId.length < 1 || roomId.length > 128) throw new TypeError('invalid roomId');
142
+ return run('/v1/rooms/session', { roomId }).then(v => roomStatusResult(v));
143
+ },
144
+ invitation(roomId) {
145
+ if (typeof roomId !== 'string' || roomId.length < 1 || roomId.length > 128) throw new TypeError('invalid roomId');
146
+ return run('/v1/rooms/invitation', { roomId }).then(v => invitationResult(v));
147
+ },
148
+ joinAdmission(sessionId, { video = false, requestId: rid } = {}) {
149
+ if (typeof video !== 'boolean') throw new TypeError('invalid video');
150
+ return run(sessionPath(sessionId, 'join'), { video, requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
151
+ },
152
+ admitGuest(sessionId, { admissionId, video = false, requestId: rid } = {}) {
153
+ if (typeof video !== 'boolean') throw new TypeError('invalid video');
154
+ return run(sessionPath(sessionId, 'admit'), { admissionId: id(admissionId, 'admissionId'), video, requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
155
+ },
156
+ waiting(sessionId) {
157
+ return run(sessionPath(sessionId, 'waiting'), {}).then(v => waitingResult(v));
158
+ },
159
+ record(sessionId) {
160
+ return run(sessionPath(sessionId, 'record'), {}).then(v => recordResult(v));
161
+ },
162
+ removeParticipant(sessionId, { admissionId, requestId: rid } = {}) {
163
+ return run(sessionPath(sessionId, 'remove'), { admissionId: id(admissionId, 'admissionId'), requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
164
+ },
165
+ leave(sessionId, { requestId: rid } = {}) {
166
+ return run(sessionPath(sessionId, 'leave'), { requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
167
+ },
168
+ decline(sessionId, { reason, requestId: rid } = {}) {
169
+ if (typeof reason !== 'string' || reason.length < 1 || reason.length > 500) throw new TypeError('invalid reason');
170
+ return run(sessionPath(sessionId, 'decline'), { reason, requestId: requestId(rid) }).then(v => operationResult(v, ['sessionId']));
171
+ },
172
+ endSession(sessionId, { requestId: rid } = {}) {
173
+ return run(sessionPath(sessionId, 'end'), { requestId: requestId(rid) }).then(v => operationResult(v, ['sessionId']));
174
+ },
175
+ createGuestLink(sessionId, input) {
176
+ if (!input || typeof input !== 'object') throw new TypeError('invalid guest link');
177
+ if (!Number.isSafeInteger(input.validFrom) || !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= input.validFrom || !Number.isInteger(input.maxRedemptions) || input.maxRedemptions < 1 || input.maxRedemptions > 1000) throw new TypeError('invalid guest link');
178
+ return run(sessionPath(sessionId, 'links'), { validFrom: input.validFrom, expiresAt: input.expiresAt, maxRedemptions: input.maxRedemptions, requestId: requestId(input.requestId) }).then(v => { const out = operationResult(v, ['linkId']); expires(v.expiresAt); if (!(typeof v.secret === 'string' && /^[A-Za-z0-9_-]{43}$/.test(v.secret)) && v.secret !== null) throw new CallsError('invalid_response'); return { ...out, expiresAt: v.expiresAt, secret: v.secret }; });
179
+ },
180
+ revokeGuestLink(sessionId, { linkId, requestId: rid } = {}) {
181
+ return run(sessionPath(sessionId, 'revoke-link'), { linkId: id(linkId, 'linkId'), requestId: requestId(rid) }).then(v => operationResult(v, ['linkId']));
182
+ },
183
+ redeemGuestLink({ secret, displayName }) {
184
+ if (typeof secret !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(secret) || typeof displayName !== 'string' || !displayName.trim()) throw new TypeError('invalid guest link');
185
+ let credential, epoch = wire.epoch(), queue = Promise.resolve(), handleDisposed = false;
186
+ const operation = (path, body, work = value => value) => {
187
+ const next = queue.then(async () => {
188
+ if (handleDisposed || epoch !== wire.epoch()) throw new CallsError('disposed');
189
+ const value = await wire.call(path, body, credential, epoch);
190
+ if (handleDisposed || epoch !== wire.epoch()) throw new CallsError('disposed');
191
+ return work(value);
192
+ });
193
+ queue = next.catch(() => {});
194
+ return next;
195
+ };
196
+ return wire.call('/v1/guests/redeem', { secret, displayName: displayName.trim() }, undefined, undefined, true).then(value => {
197
+ const guest = guestResult(value, null, null, true); credential = guest.credential;
198
+ const { credential: _credential, ...publicGuest } = guest;
199
+ return {
200
+ ...publicGuest,
201
+ status: () => operation('/v1/guests/status', {}, v => { const next = guestResult(v, guest.sessionId, guest.admissionId); return { sessionId: next.sessionId, admissionId: next.admissionId, state: next.state, expiresAt: next.expiresAt }; }),
202
+ rotate: () => operation('/v1/guests/rotate', {}, v => { const next = guestResult(v, guest.sessionId, guest.admissionId, true, false); if (handleDisposed || epoch !== wire.epoch()) throw new CallsError('disposed'); credential = next.credential; return { sessionId: next.sessionId, admissionId: next.admissionId, expiresAt: next.expiresAt }; }),
203
+ leave: ({ requestId: rid } = {}) => operation(sessionPath(guest.sessionId, 'leave'), { requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId'])),
204
+ dispose() { handleDisposed = true; epoch++; },
205
+ };
206
+ });
207
+ },
208
+ dispose() { if (!disposed) { disposed = true; wire.close(); } },
209
+ };
210
+ return client;
211
+ }
package/livekit.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ // @wtfalch/calls/livekit — a real LiveKit media adapter. It owns
2
+ // livekit-client, devices and tracks; the engine that injects it (via
3
+ // createCallEndpoint({ adapter, ... }), packages/sdk/browser.d.ts) owns
4
+ // authority, keys and lifecycle. Per-sender E2EE keys only -- there is no
5
+ // shared-passphrase mode here.
6
+ import type { CallEndpointAdapter } from './browser.js';
7
+
8
+ export type MediaDeviceKind = 'audioinput' | 'videoinput' | 'audiooutput';
9
+ export interface LiveKitDevice { kind: MediaDeviceKind; deviceId: string; label: string }
10
+ export type ConnectionQuality = 'excellent' | 'good' | 'poor' | 'lost' | 'unknown';
11
+ // microphone/camera: a publication of that source exists and is not muted.
12
+ // screen: a screen-share publication exists and is not muted. A participant
13
+ // with every publication muted, or none at all, still gets an entry -- every
14
+ // flag just reads false; nothing here distinguishes the two.
15
+ export interface ParticipantMedia { microphone: boolean; camera: boolean; screen: boolean; speaking: boolean; quality: ConnectionQuality }
16
+
17
+ export interface LiveKitCaptureOptions {
18
+ // Each returns a track this adapter publishes as-is, in place of calling
19
+ // getUserMedia/getDisplayMedia for that source. For a test that wants
20
+ // synthetic media rather than real devices.
21
+ audio?(): MediaStreamTrack | Promise<MediaStreamTrack>;
22
+ video?(): MediaStreamTrack | Promise<MediaStreamTrack>;
23
+ screen?(): MediaStreamTrack | Promise<MediaStreamTrack>;
24
+ }
25
+
26
+ export interface LiveKitAdapterOptions {
27
+ // livekit-client's E2EE worker, created by the app:
28
+ // `new Worker(new URL('livekit-client/dist/livekit-client.e2ee.worker.mjs', import.meta.url), { type: 'module' })`.
29
+ // Caller-owned: this adapter never terminates it, so the same instance
30
+ // carries through every leave()/connect() cycle a reconnect drives.
31
+ worker: Worker;
32
+ capture?: LiveKitCaptureOptions;
33
+ }
34
+
35
+ // Everything CallEndpointAdapter declares (what the engine calls), plus the
36
+ // adapter-only surface an application calls directly: a live media read, a
37
+ // way to render a participant's video, and device selection. capture and
38
+ // devices/useDevice touch no device unless asked; media() and attach() are
39
+ // synchronous, since both just read the live LiveKit room.
40
+ export interface LiveKitAdapter extends CallEndpointAdapter {
41
+ media(): Record<string, ParticipantMedia>;
42
+ // Draws identity's source into element and returns its detach. The local
43
+ // identity gives a local preview -- camera or screen, same as any peer's.
44
+ // Throws 'track_unavailable' when that source is not published and
45
+ // subscribed yet; call again once media() reports it on.
46
+ attach(identity: string, source: 'camera' | 'screen', element: HTMLVideoElement): () => void;
47
+ // Never asks for permission, so labels are empty until the page holds a
48
+ // microphone or camera.
49
+ devices(): Promise<LiveKitDevice[]>;
50
+ // Switches the live device (room.switchActiveDevice) and remembers it for
51
+ // the next capture (mic/camera) or the next connect() (speaker).
52
+ useDevice(kind: MediaDeviceKind, deviceId: string): Promise<void>;
53
+ }
54
+
55
+ // Return type is CallEndpointAdapter (imported above), extended by
56
+ // LiveKitAdapter with the adapter-only surface above -- so this adapter
57
+ // still is a CallEndpointAdapter, typed to also carry the LiveKit reads and
58
+ // controls an application calls directly.
59
+ export function createLiveKitAdapter(options: LiveKitAdapterOptions): LiveKitAdapter;