@wtfalch/calls 0.2.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), `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
+ 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'
@@ -94,6 +124,11 @@ export interface CallEnded {
94
124
  }
95
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 }
96
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;
97
132
  state(): Promise<CallStats>;
98
133
  // Delivers a snapshot at once, and again whenever the call's own state
99
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
@@ -86,22 +95,37 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
86
95
  // writer of either.
87
96
  const subscribers = new Set();
88
97
  let lastSnapshotKey;
89
- async function httpCall(path, input, bearer, timeout = 3000) {
98
+ async function httpCall(path, input, bearer, timeout = 3000, guest = false) {
90
99
  const epoch = controlEpoch;
91
100
  try {
92
- 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) });
93
- // Carry the service's own code, so a caller can tell a transient refusal
94
- // 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.
95
114
  if (!response.ok) {
96
- const code = await response.json().then(value => value?.error?.code, () => undefined);
97
- 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 });
98
117
  }
99
118
  const value = await response.json();
100
119
  if (epoch !== controlEpoch) throw new Error('stale_control_response');
101
120
  return value;
102
121
  } catch (error) { if (epoch === controlEpoch) await api.pauseMedia(); throw error; }
103
122
  }
104
- 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
+ }
105
129
  async function send(peer, type, content) {
106
130
  const device = await machine.getDevice(new Rust.UserId(peer.userId), new Rust.DeviceId(peer.deviceId));
107
131
  const encrypted = JSON.parse(await device.encryptToDeviceEvent(type, content));
@@ -176,14 +200,14 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
176
200
  return deliverPromise;
177
201
  }
178
202
  async function call(path, body, method = body ? 'POST' : 'GET') {
179
- 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) } : {}) });
180
204
  if (!response.ok) { await media.pause(); gate.stop(); ownKey = undefined; ownKeyPins = undefined; throw new Error(`gateway_refused_${response.status}`); }
181
205
  return response.json();
182
206
  }
183
207
  const api = {
184
208
  async redeem(value) {
185
209
  await this.pause();
186
- const response = await httpCall('/v1/guests/redeem', value);
210
+ const response = await httpCall('/v1/guests/redeem', value, undefined, 3000, true);
187
211
  control = { sessionId: response.sessionId, bearer: `Bearer ${response.credential}`, guest: true };
188
212
  controlExpiresAt = response.expiresAt; controlSpanMs = Math.max(1, response.expiresAt - Date.now());
189
213
  store.save({ control });
@@ -405,8 +429,8 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
405
429
  // already under way never gets these until it is genuinely over, so
406
430
  // they need no expiry wait of their own.
407
431
  const terminal = ['connection_unavailable', 'session_ended', 'participant_removed', 'admission_lapsed'];
408
- if (terminal.includes(error.code) && !endedCause) {
409
- if (error.code !== 'connection_unavailable' || Date.now() >= Math.max(controlExpiresAt, gatewayExpiresAt)) { endedCause = { reason: error.code }; await notify(); }
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(); }
410
434
  }
411
435
  throw error;
412
436
  }
@@ -520,7 +544,15 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
520
544
  // the application asking to leave is why this call is over, so nothing
521
545
  // reported after this point may overwrite it.
522
546
  async leave() { if (!endedCause) endedCause = { reason: 'left' }; clearInterval(credentialTimer); credentialTimer = undefined; await this.pause(); media.resetCapture(); await notify(); },
523
- 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 }; },
524
556
  // Delivers the current snapshot at once, and again whenever notify() finds
525
557
  // one of stats()'s fields changed. No event target: a Set of callbacks is
526
558
  // the whole mechanism, and the returned function just removes one from it.
@@ -569,7 +601,7 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
569
601
  for (;;) {
570
602
  try { await api.bootstrap(sessionId ? { sessionId } : undefined); break; }
571
603
  catch (error) {
572
- if (error.code !== 'connection_unavailable' || Date.now() >= deadline) {
604
+ if (!(error.code === 'conflict' && error.reason === 'connection_unavailable') || Date.now() >= deadline) {
573
605
  // A call that never got established, refused for good: the generic
574
606
  // control_refused bucket, since join() cannot tell 'session_ended'
575
607
  // from 'forbidden' from a connection_unavailable that outlived the
@@ -591,6 +623,13 @@ export function createCallEndpoint({ adapter, store, fetchImpl = (...input) => f
591
623
  // endpoint instead.
592
624
  const subscriptions = new Set();
593
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,
594
633
  state: () => api.stats(),
595
634
  subscribe: fn => {
596
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 {
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; }
@@ -97,8 +95,9 @@ function recordResult(value) {
97
95
  }
98
96
  function failure(response, value) {
99
97
  const error = value && typeof value === 'object' && value.error && typeof value.error === 'object' ? value.error : {};
100
- const code = typeof error.code === 'string' && /^[a-z0-9_:-]{1,80}$/.test(error.code) ? error.code : 'request_failed';
101
- 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);
102
101
  }
103
102
 
104
103
  function transport({ baseUrl, fetch: fetcher = globalThis.fetch, timeoutMs = 30000 }) {
@@ -106,13 +105,16 @@ function transport({ baseUrl, fetch: fetcher = globalThis.fetch, timeoutMs = 300
106
105
  if (typeof fetcher !== 'function') throw new TypeError('fetch is required');
107
106
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) throw new TypeError('invalid timeoutMs');
108
107
  let closed = false;
109
- const call = async (path, body, bearer, epoch, omitCredentials = false) => {
108
+ const call = async (path, body, bearer, epoch, omitCredentials = false, device = undefined) => {
110
109
  if (closed || (epoch !== undefined && epoch !== stateEpoch)) throw new CallsError('disposed');
111
110
  const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
112
111
  try {
113
- 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), {
114
116
  method: 'POST', redirect: 'error', credentials: (bearer || omitCredentials) ? 'omit' : 'same-origin',
115
- 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' }) },
116
118
  body: body === undefined ? undefined : jsonBody(body), signal: controller.signal,
117
119
  });
118
120
  let value; try { value = await response.json(); } catch { throw new CallsError('invalid_response', 'invalid_response', response.status); }
@@ -134,7 +136,13 @@ function sessionPath(sessionId, action) { return `/v1/sessions/${id(sessionId, '
134
136
 
135
137
  export function createCallsClient(options) {
136
138
  const wire = transport(options); let disposed = false;
137
- 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); };
138
146
  const client = {
139
147
  createSession(input) {
140
148
  if (!input || typeof input !== 'object') throw new TypeError('invalid session');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/calls",
3
- "version": "0.2.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
+ }