@wtfalch/calls 0.1.0 → 0.3.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,10 +12,11 @@ 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. 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. 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
 
19
+ - `callId` and `roomId` — the session and the room it belongs to, stable for this handle's whole lifetime, including after `leave()`. `callId` is the same `sessionId` `join()`/`redeem()`/`awaitAdmission()` already use; `roomId` names the room a caller like a task tracker can point back to.
19
20
  - `state()` and `subscribe()` — a snapshot now and again on every change. It carries `participants`, the roster as `{ participantId, self, displayName, actorId?, media? }`, so a changing roster needs no polling. `media` is `{ microphone, camera, screen, speaking, quality }`, present when the adapter reports it, and a subscriber hears it change.
20
21
  - `publish('audio' | 'video' | 'screen')` and `stopShare()`.
21
22
  - `setMicrophoneEnabled()` and `setMode()` — mute and camera without leaving the call.
@@ -23,7 +24,7 @@ Member requests use same-origin cookies and exact-origin requests. Guest link re
23
24
  - `devices()` and `useDevice(kind, deviceId)` — list and switch microphone, camera and speaker.
24
25
  - `ready()` and `leave()`.
25
26
 
26
- When the call ends, the last snapshot a subscriber hears has `ended: { reason }`: `left` (you called `leave()`), `admission_expired` (a guest was never let in), `control_refused` (joining failed) or `connection_unavailable` (the service stopped serving the call). The service does not yet say whether the host ended it, you were removed or your credential lapsed, so all three arrive as `connection_unavailable`.
27
+ When the call ends, the last snapshot a subscriber hears has `ended: { callId, roomId, reason }`. `callId` and `roomId` read the same way `CallHandle`'s own do, except `roomId` is `null` for `control_refused` and, rarely, `admission_expired`, where the call never reached a room the service could name; `callId` is `null` only when no session was ever named to begin with. `reason` is one of: `left` (you called `leave()`), `admission_expired` (a guest was never let in), `control_refused` (joining failed), `session_ended` (the host ended it, or its window closed), `participant_removed` (a moderator removed you) or `admission_lapsed` (your own admission or credential expired, or lost eligibility). `connection_unavailable` remains for the cases the service still cannot tell apart: a race with a sweep that has not run yet, or a still-admitted row whose binding/media credential alone lapsed.
27
28
 
28
29
  The handle renders nothing itself. You inject the media adapter; `@wtfalch/calls/livekit` below is the shipped one. With an adapter that lacks `attach`, `devices` or `useDevice`, those methods throw an error with code `media_unsupported`.
29
30
 
package/browser.d.ts CHANGED
@@ -52,7 +52,25 @@ export interface CallEndpointStore {
52
52
  save(value: Record<string, any>): void;
53
53
  open(rust: unknown, identity: EndpointIdentity): Promise<{ machine: unknown; deviceKeys: unknown; upload?: { id: string; type: unknown; body: unknown }; close(): void }>;
54
54
  }
55
- export interface CallEndpointOptions { adapter: CallEndpointAdapter; store: CallEndpointStore; fetchImpl?: typeof fetch; wasmUrl?: string }
55
+ export interface CallEndpointOptions {
56
+ adapter: CallEndpointAdapter;
57
+ store: CallEndpointStore;
58
+ fetchImpl?: typeof fetch;
59
+ // Not prefixed by baseUrl: the host serves this file and passes its own URL.
60
+ wasmUrl?: string;
61
+ // Where the Calls service is reached, with the same rules as the control
62
+ // client's baseUrl: HTTPS (HTTP for loopback), an optional path prefix, no
63
+ // credentials, query or fragment. Every `/v1/...` and gateway request goes
64
+ // under it. Unset, requests use relative paths on the page's own origin.
65
+ baseUrl?: string;
66
+ // A bearer token for member requests, in place of the same-origin cookie.
67
+ // A function is called again on every request. It is never sent on guest or
68
+ // gateway requests, which carry their own credentials.
69
+ token?: string | (() => string | Promise<string>);
70
+ // A stable id for this browser, sent as `x-calls-device` on member requests.
71
+ // 8 to 128 characters of A-Z a-z 0-9 _ -.
72
+ deviceId?: string;
73
+ }
56
74
  // A stable identity per participant, not the userId, deviceId or key pins
57
75
  // roster.peers carries for key delivery -- those are not what draws a tile.
58
76
  // self marks the local endpoint's own entry. actorId is present on every
@@ -68,6 +86,18 @@ export interface CallEndpointOptions { adapter: CallEndpointAdapter; store: Call
68
86
  export interface Participant { participantId: string; self: boolean; displayName: string | null; actorId?: string; media?: ParticipantMedia }
69
87
  // Why this endpoint's call is over. null while it is not.
70
88
  export interface CallEnded {
89
+ // The call this was (join/redeem/awaitAdmission's own sessionId) and the
90
+ // room it belonged to (calls_sessions.room_id, via the service's own state
91
+ // response -- packages/service/src/control.mjs). Both are read from
92
+ // whatever this endpoint already learned and are never cleared, so they
93
+ // stay the same answer after the call has ended. roomId is null only when
94
+ // no call was ever established well enough for the service to have named
95
+ // one -- 'control_refused' and, rarely, 'admission_expired', when this
96
+ // endpoint's very first bootstrap never got that far. callId is null only
97
+ // when no session was ever named at all: no guest redemption, no stored
98
+ // control, and no sessionId given to join().
99
+ callId: string | null;
100
+ roomId: string | null;
71
101
  reason:
72
102
  // The application called leave().
73
103
  | 'left'
@@ -78,15 +108,27 @@ export interface CallEnded {
78
108
  // established -- any refusal join() does not retry, including one that
79
109
  // outlived its provisioning wait.
80
110
  | 'control_refused'
81
- // That same refusal reaching an endpoint whose call was already running:
82
- // the service's one code for "this endpoint's binding no longer holds,"
83
- // covering the host ending the session, this participant being removed,
84
- // and an admission or credential expiring or being revoked alike, since
85
- // the service reports none of those more specifically.
86
- | 'connection_unavailable';
111
+ // That same refusal reaching an endpoint whose call was already running,
112
+ // where the service cannot say more -- a race with a sweep that has not
113
+ // yet run, a still-admitted row whose binding/media credential alone
114
+ // lapsed, or a mismatch that was never really this caller's call.
115
+ | 'connection_unavailable'
116
+ // The host ended the session, or its own validity window simply closed.
117
+ | 'session_ended'
118
+ // A moderator removed this participant specifically, with remove().
119
+ | 'participant_removed'
120
+ // This participant's own admission or credential expired, or it lost
121
+ // eligibility (a revoked grant, a suspended namespace, a logged-out
122
+ // source session), without the wider session ending.
123
+ | 'admission_lapsed';
87
124
  }
88
125
  export interface CallStats { lifecycle: 'paused' | 'connecting' | 'ready'; microphoneEnabled: boolean; cameraEnabled: boolean; screenSharing: boolean; senderIndex?: number; peers: number; keyedPeers: number; participants: Participant[]; gatewayExpiresAt: number; controlExpiresAt: number; awaitingKeys: number | null; ended: CallEnded | null }
89
126
  export interface CallHandle {
127
+ // The call this handle is for, and the room it belongs to. Both are
128
+ // captured once join() resolves and stay this handle's own stable answer
129
+ // for its whole lifetime, including after leave().
130
+ callId: string;
131
+ roomId: string;
90
132
  state(): Promise<CallStats>;
91
133
  // Delivers a snapshot at once, and again whenever the call's own state
92
134
  // moves: lifecycle, roster, keys, local capture, share, credential expiry
package/browser.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Rust, GenerationKeys } from './engine/generation-keys.mjs';
2
2
  import { MediaLifecycle } from './engine/media-lifecycle.mjs';
3
3
  import { CallLoop } from './engine/call-loop.mjs';
4
+ import { ID, origin, deviceHeader, tokenResolver } from './shared.mjs';
4
5
 
5
6
  /** What this module itself needs from the engine it runs in. Capture and
6
7
  * storage are injected, so their requirements are theirs to declare: an
@@ -30,9 +31,17 @@ export function environmentSupport(scope = globalThis) {
30
31
  * wants. Media capture and endpoint storage are injected, so this module
31
32
  * touches no device and picks no storage of its own.
32
33
  */
33
- export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => fetch(...input), wasmUrl = '/crypto.wasm' }) {
34
+ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => fetch(...input), wasmUrl = '/crypto.wasm', baseUrl, token, deviceId }) {
34
35
  for (const [name, value] of [['adapter', adapter], ['store', store]]) if (!value || typeof value !== 'object') throw new Error(`call_endpoint_${name}_required`);
35
36
  for (const name of ['read', 'save', 'open']) if (typeof store[name] !== 'function') throw new Error('call_endpoint_store_required');
37
+ // Options are checked before anything else is built. With a baseUrl every
38
+ // request goes under it. With a baseUrl or a token, requests omit ambient
39
+ // cookies and refuse redirects, so a bearer cannot follow one to another
40
+ // origin; only a member request without a token still uses the cookie.
41
+ const base = baseUrl === undefined ? undefined : origin(baseUrl), device = deviceHeader(deviceId);
42
+ const resolveToken = tokenResolver(token, () => Object.assign(new Error('invalid_token'), { code: 'invalid_token' }));
43
+ const configured = base !== undefined || token !== undefined;
44
+ const url = path => base ? new URL(path.replace(/^\/+/, ''), base).href : path;
36
45
  const missing = environmentSupport();
37
46
  if (missing.length) throw Object.assign(new Error(`call_endpoint_unsupported_environment: ${missing.join(', ')}`), { code: 'call_endpoint_unsupported_environment', missing });
38
47
  // The adapter owns capture and transforms, so only it can say whether this
@@ -70,34 +79,53 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
70
79
  // calling leave(). 'admission_expired' is a guest whose wait for admission
71
80
  // never resolved. 'control_refused' is a terminal control-plane refusal
72
81
  // 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.
82
+ // is that same refusal reaching an endpoint whose call was already running,
83
+ // and control.mjs cannot say more -- a race with a sweep that has not yet
84
+ // run, a still-admitted row whose binding/media credential alone lapsed, or
85
+ // a mismatch that is not really this caller's call to begin with.
86
+ // 'session_ended', 'participant_removed' and 'admission_lapsed' are that
87
+ // same refusal where the service could say which: the host ending the
88
+ // session, this participant being removed, or this participant's own
89
+ // admission or credential expiring or losing eligibility (Sessions.endReason,
90
+ // packages/service/src/sessions.mjs). join() clears it at the start of
91
+ // every attempt.
79
92
  let endedCause = null;
80
93
  // Every subscriber the application has registered, and the fingerprint of
81
94
  // the last snapshot they were told about. notify() below is the only
82
95
  // writer of either.
83
96
  const subscribers = new Set();
84
97
  let lastSnapshotKey;
85
- async function httpCall(path, input, bearer, timeout = 3000) {
98
+ async function httpCall(path, input, bearer, timeout = 3000, guest = false) {
86
99
  const epoch = controlEpoch;
87
100
  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.
101
+ // A request with no guest credential is a member's, except the guest's
102
+ // own redeem, which has none yet. Only a member request carries the
103
+ // member token and the device id.
104
+ const member = !bearer && !guest, memberToken = member ? await resolveToken() : undefined;
105
+ const response = await fetchImpl(url(path), {
106
+ method: 'POST', credentials: (member ? token !== undefined : configured) ? 'omit' : 'same-origin', ...(configured ? { redirect: 'error' } : {}),
107
+ headers: { ...(bearer ? { authorization: bearer } : {}), ...(memberToken ? { authorization: `Bearer ${memberToken}` } : {}), ...(member && device ? { 'x-calls-device': device } : {}), 'content-type': 'application/json' },
108
+ body: JSON.stringify(input), signal: AbortSignal.timeout(timeout),
109
+ });
110
+ // Carry the service's own code and reason, so a caller can tell a
111
+ // transient refusal from a terminal one. Both are the same status; the
112
+ // wire code is the estate's shared nine-code set (@wtfalch/contracts),
113
+ // and which conflict or refusal this is rides `reason` instead.
91
114
  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 });
115
+ const error = await response.json().then(value => value?.error, () => undefined);
116
+ throw Object.assign(new Error(`control_refused_${response.status}`), { code: error?.code, reason: error?.reason });
94
117
  }
95
118
  const value = await response.json();
96
119
  if (epoch !== controlEpoch) throw new Error('stale_control_response');
97
120
  return value;
98
121
  } catch (error) { if (epoch === controlEpoch) await api.pauseMedia(); throw error; }
99
122
  }
100
- function controlCall(action, input) { return httpCall(`/v1/sessions/${control.sessionId}/${action}`, input, control.bearer, action === 'bootstrap-finish' ? 30000 : 3000); }
123
+ // The session id comes from the server, the caller or the store, and goes into a
124
+ // path: anything but a UUID could step outside the control prefix.
125
+ function controlCall(action, input) {
126
+ if (typeof control.sessionId !== 'string' || !ID.test(control.sessionId)) throw Object.assign(new Error('invalid sessionId'), { code: 'invalid_request' });
127
+ return httpCall(`/v1/sessions/${control.sessionId}/${action}`, input, control.bearer, action === 'bootstrap-finish' ? 30000 : 3000);
128
+ }
101
129
  async function send(peer, type, content) {
102
130
  const device = await machine.getDevice(new Rust.UserId(peer.userId), new Rust.DeviceId(peer.deviceId));
103
131
  const encrypted = JSON.parse(await device.encryptToDeviceEvent(type, content));
@@ -172,14 +200,14 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
172
200
  return deliverPromise;
173
201
  }
174
202
  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) } : {}) });
203
+ const response = await fetchImpl(url(`/_matrix/client/v3/${path}`), { method, ...(configured ? { credentials: 'omit', redirect: 'error' } : {}), headers: { authorization: `Bearer ${credential}`, 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
176
204
  if (!response.ok) { await media.pause(); gate.stop(); ownKey = undefined; ownKeyPins = undefined; throw new Error(`gateway_refused_${response.status}`); }
177
205
  return response.json();
178
206
  }
179
207
  const api = {
180
208
  async redeem(value) {
181
209
  await this.pause();
182
- const response = await httpCall('/v1/guests/redeem', value);
210
+ const response = await httpCall('/v1/guests/redeem', value, undefined, 3000, true);
183
211
  control = { sessionId: response.sessionId, bearer: `Bearer ${response.credential}`, guest: true };
184
212
  controlExpiresAt = response.expiresAt; controlSpanMs = Math.max(1, response.expiresAt - Date.now());
185
213
  store.save({ control });
@@ -395,8 +423,15 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
395
423
  // this endpoint holds has passed its expiry is it permanent: each has
396
424
  // had its own renewal window (rotateCredentials) and none came back.
397
425
  // 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(); }
426
+ // credential's is the one that counts for it. session_ended,
427
+ // participant_removed and admission_lapsed are the same terminal
428
+ // refusal as connection_unavailable, with a cause attached; a call
429
+ // already under way never gets these until it is genuinely over, so
430
+ // they need no expiry wait of their own.
431
+ const terminal = ['connection_unavailable', 'session_ended', 'participant_removed', 'admission_lapsed'];
432
+ if (error.code === 'conflict' && terminal.includes(error.reason) && !endedCause) {
433
+ if (error.reason !== 'connection_unavailable' || Date.now() >= Math.max(controlExpiresAt, gatewayExpiresAt)) { endedCause = { reason: error.reason }; await notify(); }
434
+ }
400
435
  throw error;
401
436
  }
402
437
  try {
@@ -509,7 +544,15 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
509
544
  // the application asking to leave is why this call is over, so nothing
510
545
  // reported after this point may overwrite it.
511
546
  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 }; },
547
+ // endedCause itself never carries callId/roomId -- both are read fresh
548
+ // from control/roster here, the same source join()'s own handle reads at
549
+ // return time. control.sessionId is set from the moment redeem() or
550
+ // bootstrap() first names a session, before a roster or a room is ever
551
+ // known; roster.roomId only arrives once /state has answered at least
552
+ // once (configure()), which 'admission_expired' and 'control_refused'
553
+ // never reach. Neither is cleared once set, so both keep answering after
554
+ // 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 }; },
513
556
  // Delivers the current snapshot at once, and again whenever notify() finds
514
557
  // one of stats()'s fields changed. No event target: a Set of callbacks is
515
558
  // the whole mechanism, and the returned function just removes one from it.
@@ -558,7 +601,7 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
558
601
  for (;;) {
559
602
  try { await api.bootstrap(sessionId ? { sessionId } : undefined); break; }
560
603
  catch (error) {
561
- if (error.code !== 'connection_unavailable' || Date.now() >= deadline) {
604
+ if (!(error.code === 'conflict' && error.reason === 'connection_unavailable') || Date.now() >= deadline) {
562
605
  // A call that never got established, refused for good: the generic
563
606
  // control_refused bucket, since join() cannot tell 'session_ended'
564
607
  // from 'forbidden' from a connection_unavailable that outlived the
@@ -580,6 +623,13 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
580
623
  // endpoint instead.
581
624
  const subscriptions = new Set();
582
625
  return {
626
+ // roster is populated by the configure() call above, so both are
627
+ // already known by the time join() resolves. They are captured here,
628
+ // not read live off roster, so they stay this handle's own stable
629
+ // answer even though the endpoint's roster keeps moving underneath it
630
+ // -- including after this handle's own leave().
631
+ callId: roster.sessionId,
632
+ roomId: roster.roomId,
583
633
  state: () => api.stats(),
584
634
  subscribe: fn => {
585
635
  const off = api.subscribe(fn);
@@ -61,7 +61,16 @@ export class MediaLifecycle {
61
61
  // callback can fire again, so a late report from a superseded
62
62
  // connection reaches nothing.
63
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');
64
+ // Two different facts used to share one code here (issue #36): the
65
+ // epoch moving during connect() -- a pause, a fresh activate(), or
66
+ // this lease's own expiry timer, all harmless supersessions of this
67
+ // connection -- is not the same as a connection that came back
68
+ // without encryption, which is this adapter's own authority failing.
69
+ // The likeliest mover during a slow connect is the call loop's own
70
+ // refresh(), which pauses on a new roster revision
71
+ // (packages/sdk/browser.mjs refresh()); the loop then retries.
72
+ if (!this.valid(epoch)) throw new Error('stale_media_transition');
73
+ if (!result.encryption) throw new Error('media_authority_unavailable');
65
74
  // A fresh connection captures everything by default, so a mute the
66
75
  // application set before this reconnect has to be said again. It is
67
76
  // said before the state reaches 'ready', so nothing observes a window
package/index.d.ts CHANGED
@@ -1,5 +1,28 @@
1
- export class CallsError extends Error { readonly code: string; readonly status: number; }
2
- export interface CallsClientOptions { baseUrl: string; fetch?: typeof fetch; timeoutMs?: number; }
1
+ // The estate's shared nine-code set (@wtfalch/contracts SERVICE_ERROR_CODES):
2
+ // every wire failure narrows to one of these. A local SDK-only failure that
3
+ // never reached the wire (disposed, a malformed response, a timed-out or
4
+ // network-failed request) uses one of the five local codes instead.
5
+ export type CallsWireErrorCode = 'invalid_request' | 'unauthorized' | 'forbidden' | 'not_found' | 'conflict' | 'over_budget' | 'not_configured' | 'rate_limited' | 'unavailable';
6
+ export type CallsLocalErrorCode = 'disposed' | 'invalid_response' | 'request_timeout' | 'network_error' | 'invalid_token';
7
+ export type CallsErrorCode = CallsWireErrorCode | CallsLocalErrorCode;
8
+ // The calls-specific detail behind a wire `code`, read from the response's
9
+ // `error.reason` -- for example `capacity_reached` alongside `conflict`, so a
10
+ // caller that needs to branch on *which* conflict still can. Unset when the
11
+ // service sent none, or when the failure never reached the wire.
12
+ export type CallsErrorReason = 'unauthenticated' | 'not_delegable' | 'invalid_window' | 'invalid_device_keys' | 'provisioning_unavailable' | 'connection_unavailable' | 'idempotency_conflict' | 'session_exists' | 'admission_exists' | 'admission_expired' | 'room_not_open' | 'session_ended' | 'capacity_reached' | 'participant_removed' | 'admission_lapsed';
13
+ export class CallsError extends Error { readonly code: CallsErrorCode; readonly status: number; readonly reason?: CallsErrorReason; }
14
+ export interface CallsClientOptions {
15
+ baseUrl: string;
16
+ fetch?: typeof fetch;
17
+ timeoutMs?: number;
18
+ // A bearer token for a member request forwarded by a trusted host proxy,
19
+ // in place of the same-origin namespace cookie. A function is called
20
+ // again on every request, so it can hand back a fresh token.
21
+ token?: string | (() => string | Promise<string>);
22
+ // A stable id for this browser, sent as `x-calls-device` on member requests
23
+ // (not on guest-handle requests). 8 to 128 characters of A-Z a-z 0-9 _ -.
24
+ deviceId?: string;
25
+ }
3
26
  export interface OperationResult { operationId: string; enforcement: 'pending' | 'succeeded' | 'blocked'; }
4
27
  export function createCallsClient(options: CallsClientOptions): CallsClient;
5
28
  export interface CallsClient {
@@ -11,6 +34,12 @@ export interface CallsClient {
11
34
  waiting(sessionId: string): Promise<{ waiting: { admissionId: string; displayName: string | null; waitingSince: number }[] }>;
12
35
  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
36
  removeParticipant(sessionId: string, input: { admissionId: string; requestId: string }): Promise<OperationResult & { admissionId: string }>;
37
+ // A one-shot server mute of that participant's microphone publication; they
38
+ // can unmute themselves again afterward, and there is no server unmute.
39
+ muteParticipant(sessionId: string, input: { admissionId: string; requestId: string }): Promise<OperationResult & { admissionId: string }>;
40
+ // Mutes every other currently-published microphone, excluding the caller's
41
+ // own admission if it has one. admissionIds lists who was actually muted.
42
+ muteAllParticipants(sessionId: string, input: { requestId: string }): Promise<OperationResult & { admissionIds: string[] }>;
14
43
  leave(sessionId: string, input: { requestId: string }): Promise<OperationResult & { admissionId: string }>;
15
44
  decline(sessionId: string, input: { reason: string; requestId: string }): Promise<OperationResult & { sessionId: string }>;
16
45
  endSession(sessionId: string, input: { requestId: string }): Promise<OperationResult & { sessionId: string }>;
package/index.mjs CHANGED
@@ -1,22 +1,20 @@
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;
1
+ import { ID, origin, deviceHeader, tokenResolver } from './shared.mjs';
2
2
  const REQUEST = /^.{1,128}$/s;
3
3
  const STATES = new Set(['pending', 'succeeded', 'blocked']);
4
4
  const GUEST_STATES = new Set(['waiting', 'admitted']);
5
5
 
6
+ // The estate's shared nine-code set (@wtfalch/contracts SERVICE_ERROR_CODES).
7
+ // A wire code outside this set is an old or unmigrated service, folded to
8
+ // 'unavailable' the same way an unparseable body is.
9
+ const WIRE_CODES = new Set(['invalid_request', 'unauthorized', 'forbidden', 'not_found', 'conflict', 'over_budget', 'not_configured', 'rate_limited', 'unavailable']);
10
+ const REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
11
+
6
12
  export class CallsError extends Error {
7
- constructor(code, message = code, status = 0) {
8
- super(message); this.name = 'CallsError'; this.code = code; this.status = status;
13
+ constructor(code, message = code, status = 0, reason = undefined) {
14
+ super(message); this.name = 'CallsError'; this.code = code; this.status = status; this.reason = reason;
9
15
  }
10
16
  }
11
17
 
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
18
  function id(value, name) { if (typeof value !== 'string' || !ID.test(value)) throw new TypeError(`invalid ${name}`); return value; }
21
19
  function responseId(value) { if (typeof value !== 'string' || !ID.test(value)) throw new CallsError('invalid_response'); return value; }
22
20
  function requestId(value) { if (typeof value !== 'string' || !REQUEST.test(value)) throw new TypeError('invalid requestId'); return value; }
@@ -36,6 +34,11 @@ function guestResult(value, expectedSession, expectedAdmission, requireCredentia
36
34
  if (requireCredential && (typeof value.credential !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value.credential))) throw new CallsError('invalid_response');
37
35
  return { sessionId: value.sessionId, admissionId: value.admissionId, expiresAt: value.expiresAt, ...(requireState ? { state: value.state } : {}), ...(requireCredential ? { credential: value.credential } : {}) };
38
36
  }
37
+ function muteAllResult(value) {
38
+ value = object(value); responseId(value.operationId); enforcement(value.enforcement);
39
+ if (!Array.isArray(value.admissionIds) || !value.admissionIds.every(a => typeof a === 'string' && ID.test(a))) throw new CallsError('invalid_response');
40
+ return { operationId: value.operationId, admissionIds: value.admissionIds, enforcement: value.enforcement };
41
+ }
39
42
  function roomStatusResult(value) {
40
43
  value = object(value);
41
44
  if (typeof value.live !== 'boolean') throw new CallsError('invalid_response');
@@ -92,8 +95,9 @@ function recordResult(value) {
92
95
  }
93
96
  function failure(response, value) {
94
97
  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);
98
+ const code = typeof error.code === 'string' && WIRE_CODES.has(error.code) ? error.code : 'unavailable';
99
+ const reason = typeof error.reason === 'string' && REASON_PATTERN.test(error.reason) ? error.reason : undefined;
100
+ return new CallsError(code, code, response.status, reason);
97
101
  }
98
102
 
99
103
  function transport({ baseUrl, fetch: fetcher = globalThis.fetch, timeoutMs = 30000 }) {
@@ -101,13 +105,16 @@ function transport({ baseUrl, fetch: fetcher = globalThis.fetch, timeoutMs = 300
101
105
  if (typeof fetcher !== 'function') throw new TypeError('fetch is required');
102
106
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) throw new TypeError('invalid timeoutMs');
103
107
  let closed = false;
104
- const call = async (path, body, bearer, epoch, omitCredentials = false) => {
108
+ const call = async (path, body, bearer, epoch, omitCredentials = false, device = undefined) => {
105
109
  if (closed || (epoch !== undefined && epoch !== stateEpoch)) throw new CallsError('disposed');
106
110
  const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
107
111
  try {
108
- const response = await fetcher(new URL(path, base), {
112
+ // base's pathname always ends in '/' (origin() above); stripping a
113
+ // leading slash from path joins it under any prefix instead of
114
+ // replacing the prefix the way an absolute path would.
115
+ const response = await fetcher(new URL(path.replace(/^\/+/, ''), base), {
109
116
  method: 'POST', redirect: 'error', credentials: (bearer || omitCredentials) ? 'omit' : 'same-origin',
110
- headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
117
+ headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(device ? { 'x-calls-device': device } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
111
118
  body: body === undefined ? undefined : jsonBody(body), signal: controller.signal,
112
119
  });
113
120
  let value; try { value = await response.json(); } catch { throw new CallsError('invalid_response', 'invalid_response', response.status); }
@@ -129,7 +136,13 @@ function sessionPath(sessionId, action) { return `/v1/sessions/${id(sessionId, '
129
136
 
130
137
  export function createCallsClient(options) {
131
138
  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); };
139
+ // A host proxy forwards a bearer token for a member request instead of the
140
+ // same-origin cookie; resolved per call so a function-shaped token can
141
+ // hand back a fresh one. Passing it to wire.call also switches that call's
142
+ // credentials to 'omit', the same as the guest credential below.
143
+ const resolveToken = tokenResolver(options.token, () => new CallsError('invalid_token'));
144
+ const device = deviceHeader(options.deviceId);
145
+ const run = async (path, body) => { if (disposed) return Promise.reject(new CallsError('disposed')); const epoch = wire.epoch(); const bearer = await resolveToken(); return wire.call(path, body, bearer, epoch, false, device); };
133
146
  const client = {
134
147
  createSession(input) {
135
148
  if (!input || typeof input !== 'object') throw new TypeError('invalid session');
@@ -162,6 +175,12 @@ export function createCallsClient(options) {
162
175
  removeParticipant(sessionId, { admissionId, requestId: rid } = {}) {
163
176
  return run(sessionPath(sessionId, 'remove'), { admissionId: id(admissionId, 'admissionId'), requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
164
177
  },
178
+ muteParticipant(sessionId, { admissionId, requestId: rid } = {}) {
179
+ return run(sessionPath(sessionId, 'mute'), { admissionId: id(admissionId, 'admissionId'), requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
180
+ },
181
+ muteAllParticipants(sessionId, { requestId: rid } = {}) {
182
+ return run(sessionPath(sessionId, 'mute-all'), { requestId: requestId(rid) }).then(v => muteAllResult(v));
183
+ },
165
184
  leave(sessionId, { requestId: rid } = {}) {
166
185
  return run(sessionPath(sessionId, 'leave'), { requestId: requestId(rid) }).then(v => operationResult(v, ['admissionId']));
167
186
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/calls",
3
- "version": "0.1.0",
3
+ "version": "0.3.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",
@@ -37,6 +37,7 @@
37
37
  "browser.d.ts",
38
38
  "livekit.mjs",
39
39
  "livekit.d.ts",
40
+ "shared.mjs",
40
41
  "engine",
41
42
  "LICENSE",
42
43
  "README.md"
package/shared.mjs ADDED
@@ -0,0 +1,40 @@
1
+ // The shape of every session, admission and link id the service issues.
2
+ export 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;
3
+
4
+ export function origin(value) {
5
+ const base = new URL(value);
6
+ // A path prefix is allowed (a host proxying Calls under its own origin,
7
+ // e.g. `https://agora.example/api/calls`), everything else about the
8
+ // origin stays as strict as a bare origin: no credentials, no query or
9
+ // fragment, and HTTPS except for loopback development.
10
+ if (base.username || base.password || base.search || base.hash ||
11
+ (base.protocol !== 'https:' && !(base.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname)))) {
12
+ throw new TypeError('baseUrl must be an HTTPS origin, optionally with a path prefix');
13
+ }
14
+ if (!base.pathname.endsWith('/')) base.pathname += '/';
15
+ return base;
16
+ }
17
+
18
+ // A member request names its browser with this header. Anything outside the
19
+ // shape the service accepts is refused here, at construction.
20
+ export function deviceHeader(value) {
21
+ if (value !== undefined && (typeof value !== 'string' || !/^[A-Za-z0-9_-]{8,128}$/.test(value))) throw new TypeError('invalid deviceId');
22
+ return value;
23
+ }
24
+
25
+ // Returns an async function that resolves the member bearer on every call.
26
+ // `fail` builds the error for a token that cannot be used, so each entry
27
+ // refuses in its own error type.
28
+ export function tokenResolver(source, fail) {
29
+ if (source !== undefined && typeof source !== 'string' && typeof source !== 'function') throw new TypeError('invalid token');
30
+ return async () => {
31
+ if (source === undefined) return undefined;
32
+ let value;
33
+ try { value = typeof source === 'function' ? await source() : source; }
34
+ catch { throw fail(); }
35
+ // The server accepts `Bearer <1-8192 non-space chars>`; refuse anything
36
+ // else here so no request goes out without the bearer the caller asked for.
37
+ if (typeof value !== 'string' || !/^[\x21-\x7e]{1,8192}$/.test(value)) throw fail();
38
+ return value;
39
+ };
40
+ }