sigelo-contact 0.1.20 → 0.1.21

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/call.mjs CHANGED
@@ -12,10 +12,12 @@
12
12
  //
13
13
  // The messages (design §2), content {typ, id, …}, id 32 hex, kept apart by the carrier (CALL_LABEL, CALL_SEND: never in
14
14
  // the inbox, the log, MCP; `watch` answers a ring `end unavailable`):
15
- // ring caller {attempt: 1, sdp (the offer), exp (iat + 60 s), text (what an older app shows), pad}
15
+ // ring caller {attempt: 1, sdp (the offer, no address in it: ringSdp), exp (iat + 60 s), text (what an older app shows), pad}
16
16
  // ringing callee {} (only to a contact this side shares presence with: it says "online")
17
17
  // answer callee {attempt, sdp, pad} (attempt 1: the ring accepted; n > 1: a restart answered)
18
- // cands either {attempt, cands: ["candidate:…"]} the candidates gathered after the offer or answer left, once
18
+ // cands either {attempt, cands: ["candidate:…"]} the candidates gathered after the offer or answer left, once; the
19
+ // caller's first ones only after the answer came (the ring carries no address: a callee that never
20
+ // accepts learns none of the caller's, LAN or public)
19
21
  // restart caller {attempt n + 1, sdp (an ICE-restart offer), pad}
20
22
  // end either {reason} hangup declined busy no_answer cancelled lost no_path unavailable
21
23
  // ring, answer and restart are padded to PAD characters of JSON, so their size tells nothing. Every field is checked
@@ -24,7 +26,14 @@
24
26
  //
25
27
  // Timers: the caller gives up at RING_S (end no_answer); a ring past its exp is a "Missed call"; a ring with no page
26
28
  // here that can take it (none polled GET /api/calls?rtc=1 within PAGE_MS) gets `end unavailable`; ICE has ICE_MS after
27
- // the answer, else end no_path ("Could not connect directly from these two networks." No TURN in the free tier);
29
+ // the answer, else end no_path ("Could not connect directly from these two networks.", or with a TURN server offered
30
+ // "Could not connect, not even through the relay host."). TURN (2026-11-26, for everyone): the Line's host asks its relay
31
+ // for a credential (carrier.turnServer, relay/turn.mjs) at each connection (GET /api/calls/turn), again at a restart once
32
+ // within TURN_FRESH_S of its expiry; the policy stays "all" (a direct pair preferred); the screen says "Via relay" while
33
+ // the selected pair has a relayed candidate (getStats). "Always relay my media" (design §6, 2026-11-26: Settings, per
34
+ // profile; SIGELO_ICE_POLICY=relay on a computer): GET /api/calls/turn says policy "relay", the connection is made with
35
+ // iceTransportPolicy "relay" and only relayed candidates leave this page, their related address zeroed (relayOnly):
36
+ // the contact never learns this device's addresses; a relay with no TURN to offer: RELAY_ONLY at once, nothing rung;
28
37
  // roaming (Wi-Fi to mobile data, a new address): disconnected DISCONNECTED_MS (2 s), or failed, or the shell's network
29
38
  // change → the caller restarts ICE with a fresh offer, again every RETRY_MS while it does not connect; both screens say
30
39
  // "Reconnecting…"; LOST_MS (30 s) after the drop → end lost, "Connection lost" on the screen and in the chat. Weak links:
@@ -45,7 +54,7 @@ export const TYPS = Object.freeze(['ring', 'ringing', 'answer', 'cands', 'restar
45
54
  export const REASONS = Object.freeze(['hangup', 'declined', 'busy', 'no_answer', 'cancelled', 'lost', 'no_path', 'unavailable']);
46
55
  /** Seconds: the caller's wait, a ring's life. */
47
56
  export const RING_S = 45, EXP_S = 60;
48
- /** Milliseconds: gathering before the offer goes, before the late candidates go; ICE after the answer; a disconnection
57
+ /** Milliseconds: gathering before an answer or a restart goes (the ring waits for none), before the late candidates go; ICE after the answer; a disconnection
49
58
  * before the restart, then before the call is lost; a page's last poll for a ring to wait for it; an ended call shown. */
50
59
  export const GATHER_MS = 1000, LATE_MS = 5000, ICE_MS = 15000, DISCONNECTED_MS = 2000, RETRY_MS = 8000, LOST_MS = 30000, PAGE_MS = 10000, KEEP_MS = 30000;
51
60
  /** Weak links (2026-11-24): Opus at most MAX_BPS, at least MIN_BPS, stepped by the far end's RTCP every STATS_MS. */
@@ -55,6 +64,13 @@ export const REPLY_MS = 30000;
55
64
  export const PAD = 8192, SDP_MAX = 6144, CANDS_MAX = 16, CAND_MAX = 512, ATTEMPT_MAX = 100, TEXT_MAX = 200;
56
65
  export const OLD_TEXT = 'Calling you on sigelo: update to answer';
57
66
  export const NO_PATH = 'Could not connect directly from these two networks.';
67
+ export const NO_PATH_RELAYED = 'Could not connect, not even through the relay host.';
68
+ /** "Always relay my media" on and the relay gives no TURN: calls and direct transfers fail at once with this sentence. */
69
+ export const RELAY_ONLY = 'Relay only is on and this relay offers no relay path.';
70
+ /** ICE policy from a setting or SIGELO_ICE_POLICY: "relay" when either says so, else "all". */
71
+ export const policyOf = (...v) => (v.some((x) => x === true || x === 'relay') ? 'relay' : 'all');
72
+ /** Seconds: a TURN credential this close to its expiry is fetched again before an ICE restart gathers. */
73
+ export const TURN_FRESH_S = 600;
58
74
  export const STUN_PORT = 3478;
59
75
 
60
76
  const ID = /^[0-9a-f]{32}$/;
@@ -65,10 +81,40 @@ export const newCallId = () => { const b = new Uint8Array(16); globalThis.crypto
65
81
  export const mss = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
66
82
  /** STUN as transfers use it (transfer-engine.mjs stunFor): this side's relay host and the contact's, port 3478. */
67
83
  export const stunOf = (...relays) => [...new Set(relays.filter((r) => typeof r === 'string' && r !== '').map((r) => r.replace(/:\d+$/, '')))].map((h) => `${h}:${STUN_PORT}`);
84
+ /** STUN ['host:port', …] and TURN ({ urls, username, credential } | null) → RTCIceServer[] (as rtc-web.mjs iceServers). */
85
+ export const iceServersOf = (stun, turn = null) => [...(stun.length ? [{ urls: stun.map((s) => `stun:${s}`) }] : []),
86
+ ...(turn ? [{ urls: [...turn.urls], username: turn.username, credential: turn.credential }] : [])];
87
+ /** getStats() → true when the selected candidate pair has a relayed (TURN) candidate on either side, false when it has
88
+ * none, null when no pair is selected yet. */
89
+ export function relayedOf(report) {
90
+ const by = new Map(), pairs = [];
91
+ let selected = null;
92
+ report.forEach((x) => { by.set(x.id, x); if (x.type === 'transport' && x.selectedCandidatePairId) selected = x.selectedCandidatePairId; if (x.type === 'candidate-pair') pairs.push(x); });
93
+ const pair = (selected && by.get(selected)) || pairs.find((x) => x.selected) || pairs.find((x) => x.nominated && x.state === 'succeeded');
94
+ if (!pair) return null;
95
+ return [by.get(pair.localCandidateId), by.get(pair.remoteCandidateId)].some((c) => c?.candidateType === 'relay');
96
+ }
97
+ /** An SDP or candidate lines as they leave under the relay policy: only relayed candidates, their related address
98
+ * (raddr/rport: the mapped public address a TURN allocation reports) zeroed, as a browser hides it. A host or srflx
99
+ * candidate (none is gathered under "relay"; this is the second fence) is dropped. Lines or one string, either form. */
100
+ export function relayOnly(x) {
101
+ const one = (l) => {
102
+ const m = /^(a=)?candidate:/i.test(l) ? / typ (\S+)/.exec(l) : null;
103
+ if (!m) return l;
104
+ return m[1] === 'relay' ? l.replace(/ raddr \S+ rport \d+/, ' raddr 0.0.0.0 rport 0') : null;
105
+ };
106
+ if (Array.isArray(x)) return x.map(one).filter((l) => l !== null);
107
+ return String(x).split(/\r?\n/).map(one).filter((l) => l !== null).join('\r\n');
108
+ }
68
109
  /** A `.local` (multicast DNS) candidate dropped, as rtc-web.mjs does: resolving one would put an mDNS socket on the LAN. */
69
110
  export const noMdns = (sdp) => sdp.split(/\r?\n/).filter((l) => !/^a=candidate:.* [0-9a-f-]+\.local /i.test(l)).join('\r\n');
70
111
  const candsIn = (sdp) => (String(sdp).match(/^a=candidate:.*$/gm) ?? []).map((l) => l.slice(2).trim());
71
112
 
113
+ /** The ring's offer with no address in it: candidate lines gone, the connection and RTCP addresses 0.0.0.0, the port 9
114
+ * (RFC 8840 §4.3.1's values for "none gathered yet"). The caller's candidates follow in `cands` once the answer came. */
115
+ export const ringSdp = (sdp) => String(sdp).split(/\r?\n/).filter((l) => !/^a=(candidate:|end-of-candidates)/i.test(l))
116
+ .map((l) => l.replace(/^c=IN IP[46] \S+/i, 'c=IN IP4 0.0.0.0').replace(/^m=(\S+) \d+/, 'm=$1 9').replace(/^a=rtcp:\d+ IN IP[46] \S+/i, 'a=rtcp:9 IN IP4 0.0.0.0')).join('\r\n');
117
+
72
118
  /** An SDP as a call takes it: ASCII, one audio stream, exactly one sha-256 DTLS fingerprint; else refused. */
73
119
  export function checkSdp(sdp) {
74
120
  if (typeof sdp !== 'string' || sdp.length === 0 || sdp.length > SDP_MAX) bad('sdp', `an SDP of 1 to ${SDP_MAX} characters`);
@@ -134,6 +180,8 @@ export function lineOf(call, nowMs) {
134
180
  * send(did, content) → Promise the carrier's send, label CALL_LABEL, internal CALL_SEND
135
181
  * contact(did) → { did, name, online, … } | null a live contact by its (original) DID
136
182
  * allowed(c) → may that contact ring here ("Can call me"); shares(c) → may it see this side online (presence)
183
+ * person(c) → is that contact a person (design §1: calls are between people; an agent's ring is refused silently,
184
+ * no line, nothing said back, only refused({ did, id, check: 'call_agent' }) for the host's log)
137
185
  * me() → this identity's original DID (glare)
138
186
  * line({ did, dir, text, call: { id, state, secs } }) a chat line kept in the history
139
187
  * alert({ on, id, did, name }) the ring here (the seam above); audio({ on, id, name }) the call's audio mode (the
@@ -142,8 +190,8 @@ export function lineOf(call, nowMs) {
142
190
  */
143
191
  export class Line {
144
192
  #t = new Map(); // id → [timer]
145
- constructor({ send, contact, allowed, shares = () => false, me, line, alert = () => {}, audio = () => {}, changed = () => {}, now = () => Date.now(), timers = globalThis, o = {} }) {
146
- Object.assign(this, { send, contact, allowed, shares, me, line, alert, audio, changed, now, timers });
193
+ constructor({ send, contact, allowed, person = () => true, refused = () => {}, shares = () => false, me, line, alert = () => {}, audio = () => {}, changed = () => {}, now = () => Date.now(), timers = globalThis, o = {} }) {
194
+ Object.assign(this, { send, contact, allowed, person, refused, shares, me, line, alert, audio, changed, now, timers });
147
195
  this.o = { ringS: RING_S, expS: EXP_S, pageMs: PAGE_MS, keepMs: KEEP_MS, ...o };
148
196
  this.calls = new Map();
149
197
  this.live = null;
@@ -194,10 +242,10 @@ export class Line {
194
242
  ...(c.dir === 'in' && c.offer && { offer: c.offer }), signals: c.signals.map((s) => ({ ...s })) };
195
243
  }
196
244
 
197
- /** The caller's Call: the ring goes, padded, with its offer. → the view. */
245
+ /** The caller's Call: the ring goes, padded, with its offer (no address in it, whatever the page gave: ringSdp). → the view. */
198
246
  async start(c, sdp) {
199
247
  if (this.current()) bad('call_busy', 'a call is going on already', 409);
200
- checkSdp(sdp);
248
+ sdp = checkSdp(ringSdp(checkSdp(sdp)));
201
249
  const id = newCallId(), now = this.now();
202
250
  const call = { id, did: c.did, name: c.name, dir: 'out', state: 'calling', at: now, answered: null, connected: null, ended: null, reason: null, by: null, glare: false, attempt: 1, n: 0, signals: [], audio: true };
203
251
  this.calls.set(id, call); this.live = id; this.#seen(id);
@@ -234,6 +282,8 @@ export class Line {
234
282
  async cands(id, attempt, list) {
235
283
  const call = this.#mine(id);
236
284
  if (attempt !== call.attempt) bad('call_state', `attempt ${call.attempt} is the current one`, 409);
285
+ // The caller's addresses go only to a callee that accepted (the ring carried none).
286
+ if (call.dir === 'out' && call.answered === null) bad('call_state', 'the candidates go once the call is answered', 409);
237
287
  await this.#say(call, { typ: 'cands', id, attempt, cands: checkCands(list) });
238
288
  return { sent: list.length };
239
289
  }
@@ -314,6 +364,8 @@ export class Line {
314
364
  if (this.seen.has(x.id)) return; // a repeat of one already taken
315
365
  this.#seen(x.id);
316
366
  const now = this.now(), nowS = Math.floor(now / 1000);
367
+ // An agent rings no human (design §1): no ring, no line, nothing back; the host logs it.
368
+ if (!this.person(c)) { this.dropped++; try { this.refused({ did: c.did, id: x.id, check: 'call_agent' }); } catch {} return; }
317
369
  // Not allowed to ring here (a quiet contact, the switch off) or past its life: a line, nothing said back.
318
370
  if (!this.allowed(c) || x.exp <= nowS || this.gone.has(`${c.did} ${x.id}`)) return this.#missed(c, x.id);
319
371
  let glare = false;
@@ -354,12 +406,13 @@ export class Line {
354
406
 
355
407
  /**
356
408
  * The /api/calls* routes over one Line (UI-API.md "Calls"). contactOf(did) → the contact (refuses an unknown one);
357
- * callable(c) → whether this side may call it now (a person, present); stun(c) → the STUN list; can: { speaker, mic, ring }
409
+ * callable(c) → whether this side may call it now (a person, present); stun(c) → the STUN list; turn() → { urls, username,
410
+ * credential, exp } | null (the relay's TURN credential: carrier.turnServer); can: { speaker, mic, ring }
358
411
  * (ring: the host rings itself, the page plays no tone);
359
412
  * hooks: { speaker(on), mic(), micSettings() } where the host has them (the phone app); allow(c, on) / allowOf(c) the
360
413
  * "Can call me" switch.
361
414
  */
362
- export function callRoutes({ line, contactOf, callable, stun, can = {}, hooks = {}, allow, allowOf }) {
415
+ export function callRoutes({ line, contactOf, callable, stun, turn = async () => null, policy = () => 'all', can = {}, hooks = {}, allow, allowOf }) {
363
416
  const idOf = (b) => (typeof b['id'] === 'string' && ID.test(b['id']) ? b['id'] : bad('body', 'id: a call id (32 hex digits)'));
364
417
  const attemptOf = (b, d) => (b['attempt'] === undefined ? d : isInt(b['attempt']) && b['attempt'] >= 1 && b['attempt'] <= ATTEMPT_MAX ? b['attempt'] : bad('body', 'attempt: a whole number'));
365
418
  return {
@@ -368,6 +421,13 @@ export function callRoutes({ line, contactOf, callable, stun, can = {}, hooks =
368
421
  const peer = c ?? (call ? contactOf(call.did) : null);
369
422
  return { call, stun: stun(peer), can: { speaker: can.speaker === true, mic: can.mic === true, ring: can.ring === true } };
370
423
  },
424
+ // A TURN server for a connection starting now; null: STUN alone. Asked at each connection, never in the poll.
425
+ // policy: "relay" with "Always relay my media" on (the page then refuses to connect without TURN), else "all".
426
+ 'GET /api/calls/turn': async () => {
427
+ let t = null;
428
+ try { t = (await turn()) ?? null; } catch {}
429
+ return { turn: t ? { urls: t.urls, username: t.username, credential: t.credential, exp: t.exp } : null, policy: policyOf(policy()) };
430
+ },
371
431
  'POST /api/calls/start': async (b) => {
372
432
  const c = contactOf(b['to']);
373
433
  const why = callable(c);
@@ -440,13 +500,15 @@ export class Phone {
440
500
  this.o = { gatherMs: GATHER_MS, lateMs: LATE_MS, iceMs: ICE_MS, disconnectedMs: DISCONNECTED_MS, retryMs: RETRY_MS, lostMs: LOST_MS, statsMs: STATS_MS, pollMs: 500, ...o };
441
501
  this.call = null; // the Line's view
442
502
  this.stun = [];
503
+ this.turn = null; // the TURN server of this connection (GET /api/calls/turn), or null
504
+ this.policy = 'all'; // its ICE policy (the same answer): "relay" with "Always relay my media" on
443
505
  this.can = { speaker: false, mic: false };
444
506
  this.#reset();
445
507
  }
446
508
  #reset() {
447
509
  this.pc = null; this.stream = null; this.id = null; this.attempt = 1; this.applied = 0; this.pending = []; this.remote = false;
448
510
  this.ever = false; this.muted = false; this.speakerOn = false; this.phase = null; this.error = null; this.place_ = null;
449
- this.reconnecting = false; this.quality = null; this.bps = MAX_BPS; this.clean = 0; this.prevIn = null; this.loss = null; this.rtt = null;
511
+ this.reconnecting = false; this.quality = null; this.bps = MAX_BPS; this.clean = 0; this.prevIn = null; this.loss = null; this.rtt = null; this.relayed = null; this.turn = null;
450
512
  for (const k of ['ice', 'disc', 'retry', 'lost', 'stats', 'poll']) this.#stop(k);
451
513
  }
452
514
  #tm = {};
@@ -459,7 +521,7 @@ export class Phone {
459
521
  view() {
460
522
  const c = this.call;
461
523
  return { call: c, phase: this.phase, error: this.error, muted: this.muted, speaker: this.speakerOn, can: this.can, reconnecting: this.reconnecting,
462
- quality: this.reconnecting ? 0 : this.quality, bps: this.bps, loss: this.loss, rtt: this.rtt, live: Boolean(c && c.state !== 'ended') || this.phase === 'mic' || this.phase === 'placing' };
524
+ quality: this.reconnecting ? 0 : this.quality, relayed: this.relayed === true, bps: this.bps, loss: this.loss, rtt: this.rtt, live: Boolean(c && c.state !== 'ended') || this.phase === 'mic' || this.phase === 'placing' };
463
525
  }
464
526
  #changed() { try { this.onState(this.view()); } catch {} }
465
527
 
@@ -483,13 +545,32 @@ export class Phone {
483
545
  async #pc() {
484
546
  let certificates;
485
547
  try { if (typeof this.RTC.generateCertificate === 'function') certificates = [await this.RTC.generateCertificate({ name: 'ECDSA', namedCurve: 'P-256' })]; } catch {}
486
- const pc = new this.RTC({ iceServers: this.stun.length ? [{ urls: this.stun.map((s) => `stun:${s}`) }] : [], bundlePolicy: 'max-bundle', rtcpMuxPolicy: 'require', ...(certificates && { certificates }) });
548
+ this.turn = await this.#turnNow();
549
+ // Relay only and no TURN: nothing connects, nothing is gathered (a connection without TURN would gather host candidates).
550
+ if (this.policy === 'relay' && !this.turn) throw Object.assign(new Error(RELAY_ONLY), { check: 'relay_only' });
551
+ const pc = new this.RTC({ iceServers: iceServersOf(this.policy === 'relay' ? [] : this.stun, this.turn), bundlePolicy: 'max-bundle', rtcpMuxPolicy: 'require',
552
+ ...(this.policy === 'relay' && { iceTransportPolicy: 'relay' }), ...(certificates && { certificates }) });
487
553
  for (const t of this.stream.getAudioTracks()) pc.addTrack(t, this.stream);
488
554
  this.prevIn = null;
489
555
  pc.addEventListener('track', (ev) => { try { this.onStream(ev.streams?.[0] ?? null); } catch {} });
490
556
  pc.addEventListener('iceconnectionstatechange', () => void this.#ice(pc));
491
557
  return pc;
492
558
  }
559
+ async #turnNow() {
560
+ try {
561
+ const r = await this.api('GET', '/api/calls/turn');
562
+ this.policy = r?.policy === 'relay' ? 'relay' : 'all';
563
+ return r?.turn && Array.isArray(r.turn.urls) ? r.turn : null;
564
+ } catch { return null; }
565
+ }
566
+ /** Before an ICE restart gathers: a TURN credential near its expiry is replaced (coturn refuses an expired one at a new allocation). */
567
+ async #freshTurn(pc) {
568
+ if (!this.turn || !Number.isSafeInteger(this.turn.exp) || this.turn.exp - TURN_FRESH_S > this.now() / 1000) return;
569
+ const t = await this.#turnNow();
570
+ if (!t || this.pc !== pc) return;
571
+ this.turn = t;
572
+ try { pc.setConfiguration?.({ ...(pc.getConfiguration?.() ?? {}), iceServers: iceServersOf(this.policy === 'relay' ? [] : this.stun, t) }); } catch {}
573
+ }
493
574
  async #mic() {
494
575
  this.phase = 'mic'; this.#changed();
495
576
  if (this.can.mic) await this.api('POST', '/api/calls/mic');
@@ -502,13 +583,32 @@ export class Phone {
502
583
  pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') { this.timers.clearTimeout(t); r(); } });
503
584
  });
504
585
  }
505
- return pc.localDescription.sdp;
586
+ return this.#out(pc.localDescription.sdp);
587
+ }
588
+ /** What leaves this page: under the relay policy, relayed candidates only (relayOnly). */
589
+ #out(sdp) { return this.policy === 'relay' ? relayOnly(sdp) : sdp; }
590
+ /** The caller's candidates once the answer came: all gathered so far at once, then the rest once gathering is done
591
+ * (or lateMs), in batches of CANDS_MAX. */
592
+ async #trickle(pc, attempt) {
593
+ const had = new Set();
594
+ const post = async () => {
595
+ if (this.pc !== pc || this.attempt !== attempt || !this.id) return;
596
+ const more = candsIn(this.#out(pc.localDescription?.sdp ?? '')).filter((c) => !had.has(c));
597
+ for (let i = 0; i < more.length; i += CANDS_MAX) {
598
+ const b = more.slice(i, i + CANDS_MAX);
599
+ for (const c of b) had.add(c);
600
+ await this.api('POST', '/api/calls/cands', { id: this.id, attempt, cands: b }).catch(() => {});
601
+ }
602
+ };
603
+ await post();
604
+ await this.#gathered(pc, this.o.lateMs);
605
+ await post();
506
606
  }
507
607
  /** The candidates found after the SDP left, once (gathering done, or lateMs). */
508
608
  async #late(pc, attempt, sent) {
509
609
  await this.#gathered(pc, this.o.lateMs);
510
610
  if (this.pc !== pc || this.attempt !== attempt || !this.id) return;
511
- const had = new Set(candsIn(sent)), more = candsIn(pc.localDescription?.sdp ?? '').filter((c) => !had.has(c)).slice(0, CANDS_MAX);
611
+ const had = new Set(candsIn(sent)), more = candsIn(this.#out(pc.localDescription?.sdp ?? '')).filter((c) => !had.has(c)).slice(0, CANDS_MAX);
512
612
  if (more.length) await this.api('POST', '/api/calls/cands', { id: this.id, attempt, cands: more }).catch(() => {});
513
613
  }
514
614
  async #remote(pc, type, sdp) {
@@ -523,7 +623,8 @@ export class Phone {
523
623
  }
524
624
  #fail(e) { this.error = { check: e?.check ?? 'call', message: String(e?.message ?? e) }; }
525
625
 
526
- /** Call: the microphone, a fresh connection, the offer after GATHER_MS, the ring. */
626
+ /** Call: the microphone, a fresh connection, the ring at once with an offer that holds no address (ringSdp); the
627
+ * candidates gather meanwhile and go once the answer comes (#trickle). */
527
628
  async place(did) {
528
629
  if (this.view().live) throw Object.assign(new Error('a call is going on already'), { check: 'call_busy' });
529
630
  this.#reset();
@@ -534,10 +635,8 @@ export class Phone {
534
635
  this.phase = 'placing'; this.#changed();
535
636
  const pc = this.pc = await this.#pc();
536
637
  await pc.setLocalDescription(await pc.createOffer());
537
- const sdp = await this.#gathered(pc, this.o.gatherMs);
538
- const r = await this.api('POST', '/api/calls/start', { to: did, sdp });
638
+ const r = await this.api('POST', '/api/calls/start', { to: did, sdp: ringSdp(pc.localDescription.sdp) });
539
639
  this.id = r.call.id; this.call = r.call; this.phase = null;
540
- void this.#late(pc, 1, sdp);
541
640
  this.#changed(); this.#loop();
542
641
  return r.call;
543
642
  } catch (e) {
@@ -566,7 +665,8 @@ export class Phone {
566
665
  this.#changed(); this.#loop();
567
666
  } catch (e) {
568
667
  this.#fail(e); this.phase = 'failed';
569
- await this.api('POST', '/api/calls/end', { id: c.id, reason: 'hangup' }).catch(() => {});
668
+ // Relay only with no TURN here: the caller hears "Could not connect" (no_path), not a hang-up.
669
+ await this.api('POST', '/api/calls/end', { id: c.id, reason: e?.check === 'relay_only' ? 'no_path' : 'hangup' }).catch(() => {});
570
670
  this.#close(); this.#changed();
571
671
  }
572
672
  }
@@ -583,7 +683,7 @@ export class Phone {
583
683
  /** The page leaves the call screen for good (Close on the ended state). */
584
684
  dismiss() { if (!this.view().live) { this.call = null; this.phase = null; this.error = null; this.#changed(); } }
585
685
 
586
- async #noPath() { if (!this.ever && this.id) { this.error = { check: 'no_path', message: NO_PATH }; await this.hangup('no_path'); } }
686
+ async #noPath() { if (!this.ever && this.id) { this.error = { check: 'no_path', message: this.turn ? NO_PATH_RELAYED : NO_PATH }; await this.hangup('no_path'); } }
587
687
  async #ice(pc) {
588
688
  if (this.pc !== pc) return;
589
689
  const s = pc.iceConnectionState;
@@ -592,6 +692,7 @@ export class Phone {
592
692
  if (this.reconnecting) { this.reconnecting = false; this.#changed(); }
593
693
  if (!this.ever) {
594
694
  this.ever = true;
695
+ try { this.relayed = relayedOf(await pc.getStats()); } catch {}
595
696
  await this.#bitrate(pc);
596
697
  this.#start('stats', this.o.statsMs, () => this.#stats(pc));
597
698
  const r = await this.api('POST', '/api/calls/connected', { id: this.id }).catch(() => null);
@@ -623,6 +724,7 @@ export class Phone {
623
724
  // Not connected again within RETRY_MS: another restart (a later network may be up by then).
624
725
  this.#start('retry', this.o.retryMs, () => { if (this.reconnecting && this.pc === pc) { this.#stop('disc'); this.#start('disc', 0, () => this.#restart()); } });
625
726
  try {
727
+ await this.#freshTurn(pc);
626
728
  await pc.setLocalDescription(await pc.createOffer({ iceRestart: true }));
627
729
  this.remote = false;
628
730
  const sdp = await this.#gathered(pc, this.o.gatherMs);
@@ -645,6 +747,7 @@ export class Phone {
645
747
  } else if (x.type === 'inbound-rtp' && (x.kind ?? 'audio') === 'audio') { inLost = x.packetsLost ?? 0; inRecv = x.packetsReceived ?? 0; }
646
748
  else if (x.type === 'candidate-pair' && x.nominated && typeof x.currentRoundTripTime === 'number' && rtt === null) rtt = x.currentRoundTripTime;
647
749
  });
750
+ this.relayed = relayedOf(r);
648
751
  // What reaches this side: the loss since the last read.
649
752
  const p = this.prevIn;
650
753
  if (inLost !== null) {
@@ -698,13 +801,14 @@ export class Phone {
698
801
  try {
699
802
  if (s.typ === 'answer' && call.dir === 'out' && s.attempt === this.attempt) {
700
803
  await this.#remote(pc, 'answer', s.sdp);
701
- if (s.attempt === 1) this.#start('ice', this.o.iceMs, () => this.#noPath());
804
+ if (s.attempt === 1) { this.#start('ice', this.o.iceMs, () => this.#noPath()); void this.#trickle(pc, 1); }
702
805
  // A restart whose path never dropped (the shell's network event came first): ICE stays connected, no event comes.
703
806
  else if (['connected', 'completed'].includes(pc.iceConnectionState)) void this.#ice(pc);
704
807
  } else if (s.typ === 'cands' && s.attempt === this.attempt) {
705
808
  for (const c of s.cands) await this.#add(pc, c);
706
809
  } else if (s.typ === 'restart' && call.dir === 'in') {
707
810
  this.attempt = s.attempt; this.remote = false;
811
+ await this.#freshTurn(pc);
708
812
  await this.#remote(pc, 'offer', s.sdp);
709
813
  await pc.setLocalDescription(await pc.createAnswer());
710
814
  const sdp = await this.#gathered(pc, this.o.gatherMs);