nixamp 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,742 @@
1
+ /**
2
+ * The party line.
3
+ *
4
+ * A phone number, a six-digit code, and everybody who keyed the same code
5
+ * talking to each other. You call 888-ROOM-818, key 482917, and you are on the
6
+ * line with whoever else keyed 482917.
7
+ *
8
+ * Six digits, and digits rather than letters, for one reason: the code is a
9
+ * thing you say to somebody. The generated ids this replaces were long enough
10
+ * that nobody could read one down a phone line, and letters would have brought
11
+ * case and spelling with them -- was that a capital B, was it "blue" or "blu".
12
+ * A keypad has one way to type a 4 and nobody disagrees about how to say it.
13
+ *
14
+ * The rooms are not configured anywhere. Keying a code nobody is using opens
15
+ * it, and the last person to hang up closes it -- the same shape as a channel,
16
+ * where a name is just where a stream happens to be rather than a record
17
+ * somebody created first. The code is a rendezvous, not a credential: two
18
+ * people who agree on 482917 beforehand both dial in, and neither had to
19
+ * create it first.
20
+ *
21
+ * The audio mixing is Telnyx's. A conference is a name on their side too, so
22
+ * this module never touches a byte of audio: it answers a call, asks a
23
+ * question, and puts the leg into a conference. What we keep is the part
24
+ * Telnyx does not -- which spoken words mean which conference, and how many
25
+ * people a room is holding.
26
+ *
27
+ * Two things about conferences are worth knowing before reading the state
28
+ * machine. They expire after four hours whether or not anyone is still on
29
+ * them, so a long-lived room's conference id goes stale underneath us and has
30
+ * to be remade on the next join. And the id is only knowable after the first
31
+ * caller creates it, so the first caller and the tenth take different paths
32
+ * through the same function.
33
+ */
34
+ import { createPublicKey, verify as verifySignature, timingSafeEqual } from "node:crypto";
35
+
36
+ /** Where Telnyx's REST API lives. Injectable so a test never leaves the process. */
37
+ const TELNYX_API = "https://api.telnyx.com/v2";
38
+
39
+ /**
40
+ * Telnyx's own voice, so a room prompt costs nothing beyond the call. A
41
+ * Polly or ElevenLabs voice reads better and bills separately; the name is
42
+ * configuration rather than a constant for exactly that reason.
43
+ */
44
+ const DEFAULT_VOICE = "Telnyx.KokoroTTS.af";
45
+
46
+ /** How long a signed webhook stays acceptable. Telnyx's own SDKs use five minutes. */
47
+ const SIGNATURE_TOLERANCE_MS = 5 * 60 * 1000;
48
+
49
+ /** A conference Telnyx will discard on its own, so we stop trusting ours first. */
50
+ const CONFERENCE_TTL_MS = 4 * 60 * 60 * 1000;
51
+
52
+ export interface RoomInfo {
53
+ /** The six-digit code, which is the room's whole identity. */
54
+ code: string;
55
+ /** Telnyx's id for the conference, once a first caller has made one. */
56
+ conferenceId: string | null;
57
+ /** How many legs we have put in, less the ones we have seen leave. */
58
+ callers: number;
59
+ startedAt: number;
60
+ }
61
+
62
+ interface Room extends RoomInfo {
63
+ /** Legs currently in the room, so a caller is never counted twice. */
64
+ legs: Set<string>;
65
+ }
66
+
67
+ /**
68
+ * What the party line needs to know about a stream.
69
+ *
70
+ * A narrow view of the Directory rather than the Directory itself, so this
71
+ * module stays a function of its inputs and a test can describe a stream
72
+ * without standing one up.
73
+ */
74
+ export interface StreamLookup {
75
+ liveByCode(
76
+ code: string,
77
+ ): { name: string; url: string; audio: string; nowPlaying: string; startedAt: number } | undefined;
78
+ endedByCode(code: string): { name: string; nowPlaying: string; startedAt: number; endedAt: number } | undefined;
79
+ }
80
+
81
+ /** Sending a text. Injected because the number that sends is not this one. */
82
+ export interface Sms {
83
+ send(to: string, text: string): Promise<boolean>;
84
+ }
85
+
86
+ export interface PartyLineOptions {
87
+ /** A Telnyx API key with call-control rights. */
88
+ apiKey: string;
89
+ /** The directory, on the instance that hosts one. */
90
+ streams?: StreamLookup;
91
+ /**
92
+ * How to text somebody when a stream comes back.
93
+ *
94
+ * Not from the toll-free number the call arrived on: toll-free A2P messaging
95
+ * is filtered by carriers until the number is verified, and ours is not. A
96
+ * long code that already has a messaging profile sends today, so reminders
97
+ * go out from there and the verification can land whenever it lands.
98
+ */
99
+ sms?: Sms;
100
+ /**
101
+ * The account's ed25519 public key, base64, from the portal. Without it
102
+ * every webhook is refused: an unauthenticated call-control webhook lets a
103
+ * stranger drive calls we are paying for.
104
+ */
105
+ publicKey: string;
106
+ /** What the caller hears before being asked for a room. */
107
+ greeting?: string;
108
+ voice?: string;
109
+ /** A ceiling per room, so one room cannot spend the whole balance. */
110
+ maxParticipants?: number;
111
+ /** The number to tell people to call back on. Injected, not hardcoded. */
112
+ callIn?: string;
113
+ /** Injected for tests. */
114
+ now?: () => number;
115
+ fetch?: typeof globalThis.fetch;
116
+ onEvent?: (message: string) => void;
117
+ }
118
+
119
+ /**
120
+ * How long a room code is.
121
+ *
122
+ * Six digits, because the code has to survive being read down a phone line and
123
+ * typed into a URL. The generated ids this replaces were long enough that
124
+ * nobody could say one out loud, which is the whole failure being fixed: a
125
+ * room code is something you tell somebody, so it has to be short enough to
126
+ * hold in your head between hearing it and dialling it.
127
+ */
128
+ export const CODE_LENGTH = 6;
129
+
130
+ /**
131
+ * A room code, from whatever the caller keyed.
132
+ *
133
+ * Digits only, and exactly six of them. Five is not a near miss to be
134
+ * charitable about -- it is a different room, and guessing which one they
135
+ * meant would drop somebody into a stranger's conversation.
136
+ *
137
+ * Nothing here is case-sensitive because nothing here has a case. That is the
138
+ * point of digits over letters: a phone keypad has one way to type a 4, and no
139
+ * two people disagree about how to say it.
140
+ */
141
+ export function roomCodeFrom(entered: unknown): string {
142
+ if (typeof entered !== "string" && typeof entered !== "number") return "";
143
+ const digits = String(entered).replace(/\D/g, "");
144
+ return digits.length === CODE_LENGTH ? digits : "";
145
+ }
146
+
147
+ /**
148
+ * A time as a caller should hear it.
149
+ *
150
+ * Pacific, spelled out, because that is the clock the streams are announced on
151
+ * and a bare "9:27" down a phone line is a time in somebody's head rather than
152
+ * a time. Built with Intl rather than arithmetic: the offset changes twice a
153
+ * year and hand-rolled zone maths is how you end up an hour out for three
154
+ * weeks every spring.
155
+ */
156
+ export function pacificTime(at: number): string {
157
+ const clock = new Intl.DateTimeFormat("en-US", {
158
+ hour: "numeric",
159
+ minute: "2-digit",
160
+ timeZone: "America/Los_Angeles",
161
+ }).format(new Date(at));
162
+ return `${clock} Pacific`;
163
+ }
164
+
165
+ /** How a code is read back: one digit at a time, because 482917 is not a number. */
166
+ export function spokenCode(code: string): string {
167
+ return code.split("").join(", ");
168
+ }
169
+
170
+ /**
171
+ * Telnyx signs `${timestamp}|${body}` with ed25519 and sends both back in
172
+ * headers. Node will not take a bare 32-byte key, so it is wrapped in the
173
+ * fixed SPKI prefix that says "this is ed25519" and handed over as DER.
174
+ */
175
+ const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
176
+
177
+ function ed25519KeyFrom(base64Key: string): ReturnType<typeof createPublicKey> | null {
178
+ let raw: Buffer;
179
+ try {
180
+ raw = Buffer.from(base64Key, "base64");
181
+ } catch {
182
+ return null;
183
+ }
184
+ if (raw.length !== 32) return null;
185
+ try {
186
+ return createPublicKey({
187
+ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]),
188
+ format: "der",
189
+ type: "spki",
190
+ });
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+
196
+ export interface TelnyxEvent {
197
+ event_type?: string;
198
+ payload?: Record<string, unknown>;
199
+ }
200
+
201
+ /**
202
+ * The party line, as a thing that answers webhooks.
203
+ *
204
+ * It owns no socket and no timer. The server hands it a verified event and it
205
+ * issues whatever call-control commands that event calls for, which makes the
206
+ * whole state machine testable with a fetch that records what it was asked.
207
+ */
208
+ export class PartyLine {
209
+ private readonly rooms = new Map<string, Room>();
210
+ /** Which room a leg is heading for, between asking and being answered. */
211
+ private readonly legRoom = new Map<string, string>();
212
+ /** The number each caller is calling from, for a reminder they ask for. */
213
+ private readonly legFrom = new Map<string, string>();
214
+ /** Legs that heard "press 1", and which stream they would be reminded about. */
215
+ private readonly pendingReminder = new Map<string, string>();
216
+ /** Who to text when a stream returns, by stream code. */
217
+ private readonly reminders = new Map<string, Set<string>>();
218
+ /**
219
+ * The same list, somewhere that survives a deploy.
220
+ *
221
+ * A caller who pressed 1 was told they would be texted. Keeping that promise
222
+ * only in a Map meant a restart broke it silently, which is the worst way to
223
+ * break a promise made to somebody on a telephone.
224
+ */
225
+ private reminderStore: {
226
+ add: (code: string, phone: string) => void;
227
+ take: (code: string) => Promise<string[]>;
228
+ } | null = null;
229
+
230
+ /** Start echoing reminders somewhere durable, and put back what was there. */
231
+ persistRemindersTo(
232
+ store: { add: (code: string, phone: string) => void; take: (code: string) => Promise<string[]> },
233
+ waiting: ReadonlyMap<string, ReadonlySet<string>> = new Map(),
234
+ ): void {
235
+ this.reminderStore = store;
236
+ for (const [code, phones] of waiting) {
237
+ const set = this.reminders.get(code) ?? new Set<string>();
238
+ for (const phone of phones) set.add(phone);
239
+ this.reminders.set(code, set);
240
+ }
241
+ }
242
+ /**
243
+ * Legs listening to a stream, by its code.
244
+ *
245
+ * Separate from the rooms because a stream listener is not in a conference:
246
+ * they are a leg with an MP3 playing into it. Nothing else was counting
247
+ * them, so the directory had no way to say how many people were on the
248
+ * phone for a broadcast.
249
+ */
250
+ private readonly streamLegs = new Map<string, Set<string>>();
251
+ private readonly key: ReturnType<typeof createPublicKey> | null;
252
+ private readonly fetch: typeof globalThis.fetch;
253
+ private readonly now: () => number;
254
+
255
+ constructor(private readonly options: PartyLineOptions) {
256
+ this.key = options.publicKey ? ed25519KeyFrom(options.publicKey) : null;
257
+ this.fetch = options.fetch ?? globalThis.fetch;
258
+ this.now = options.now ?? Date.now;
259
+ }
260
+
261
+ /** True when this instance can actually check a signature. */
262
+ get armed(): boolean {
263
+ return this.key !== null && this.options.apiKey.length > 0;
264
+ }
265
+
266
+ /**
267
+ * Whether a webhook really came from Telnyx.
268
+ *
269
+ * The body has to be the bytes that arrived. Parsing and reserialising JSON
270
+ * changes key order and whitespace, and the signature is over the original.
271
+ */
272
+ verify(rawBody: string, signature: string | undefined, timestamp: string | undefined): boolean {
273
+ if (this.key === null || !signature || !timestamp) return false;
274
+
275
+ const sent = Number(timestamp) * 1000;
276
+ if (!Number.isFinite(sent)) return false;
277
+ // Both directions: a replayed webhook is old, and a clock-skewed forgery
278
+ // from the future is no more trustworthy for being ahead.
279
+ if (Math.abs(this.now() - sent) > SIGNATURE_TOLERANCE_MS) return false;
280
+
281
+ let sig: Buffer;
282
+ try {
283
+ sig = Buffer.from(signature, "base64");
284
+ } catch {
285
+ return false;
286
+ }
287
+ if (sig.length !== 64) return false;
288
+
289
+ try {
290
+ return verifySignature(
291
+ null,
292
+ Buffer.from(`${timestamp}|${rawBody}`, "utf8"),
293
+ this.key,
294
+ sig,
295
+ );
296
+ } catch {
297
+ return false;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * The rooms with someone in them, busiest first, with their codes.
303
+ *
304
+ * The code is published on purpose. An earlier version withheld it on the
305
+ * reasoning that a code is the only thing between a stranger and a
306
+ * conversation -- true of a private room, and wrong here: this is a public
307
+ * call-in line, and a listing you cannot dial is a listing of nothing. The
308
+ * code is how you join, so it is what the list is for.
309
+ */
310
+ list(): { code: string; callers: number; startedAt: number }[] {
311
+ return [...this.rooms.values()]
312
+ .filter((room) => room.callers > 0)
313
+ .map(({ code, callers, startedAt }) => ({ code, callers, startedAt }))
314
+ .sort((a, b) => b.callers - a.callers || a.startedAt - b.startedAt);
315
+ }
316
+
317
+ /**
318
+ * Drive one call-control event.
319
+ *
320
+ * Every branch returns rather than falling through, because an event we do
321
+ * not handle is the normal case -- Telnyx sends a dozen kinds per call and
322
+ * this cares about four.
323
+ */
324
+ async handle(event: TelnyxEvent): Promise<void> {
325
+ const type = event.event_type ?? "";
326
+ const payload = event.payload ?? {};
327
+ const leg = typeof payload["call_control_id"] === "string" ? payload["call_control_id"] : "";
328
+ if (!leg) return;
329
+
330
+ if (type === "call.initiated") {
331
+ // Only inbound. An outbound leg we dialled is not somebody calling in,
332
+ // and answering it would be answering ourselves.
333
+ if (payload["direction"] !== "incoming") return;
334
+ // Kept now because a reminder needs it later, and by the time the caller
335
+ // presses 1 the only thing we have is the leg.
336
+ if (typeof payload["from"] === "string") this.legFrom.set(leg, payload["from"]);
337
+ await this.command(leg, "answer", {});
338
+ return;
339
+ }
340
+
341
+ if (type === "call.answered") {
342
+ await this.ask(leg);
343
+ return;
344
+ }
345
+
346
+ if (type === "call.gather.ended") {
347
+ const digits = typeof payload["digits"] === "string" ? payload["digits"] : "";
348
+
349
+ // A leg that was just offered a reminder is answering that, not keying a
350
+ // room code -- the same event carries both, so the question we asked is
351
+ // what decides how to read it.
352
+ const offered = this.pendingReminder.get(leg);
353
+ if (offered !== undefined) {
354
+ this.pendingReminder.delete(leg);
355
+ await this.reminder(leg, offered, digits);
356
+ return;
357
+ }
358
+
359
+ const code = roomCodeFrom(digits);
360
+ if (!code) {
361
+ // Re-ask rather than guess. Anything that is not six digits is not a
362
+ // room, and picking the nearest one would be picking a stranger's.
363
+ await this.ask(leg, "That is not a six digit code. ");
364
+ return;
365
+ }
366
+ // A code that belongs to a stream is answered as a stream. Anything else
367
+ // is an ordinary room, which is what this line was before.
368
+ if (await this.stream(leg, code)) return;
369
+ await this.join(leg, code);
370
+ return;
371
+ }
372
+
373
+ if (type === "conference.participant.left" || type === "call.hangup") {
374
+ this.release(leg);
375
+ this.legFrom.delete(leg);
376
+ this.pendingReminder.delete(leg);
377
+ return;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Ask for a room code, on the keypad.
383
+ *
384
+ * Not by voice, which is the one thing here that changed its mind. Speech
385
+ * suited a room *name* -- "blue" misheard is still recognisably a word, and
386
+ * a person can say it differently the second time. A six-digit code has no
387
+ * such slack: one digit misheard is a different room that also exists, and
388
+ * the caller lands in a stranger's conversation with nothing to tell them
389
+ * they went wrong. A keypad cannot mishear a 4.
390
+ *
391
+ * Six digits terminates the gather on its own, so the caller does not have
392
+ * to press anything after; # is there for the ones who do it anyway.
393
+ */
394
+ private async ask(leg: string, prefix = ""): Promise<void> {
395
+ const greeting =
396
+ this.options.greeting ??
397
+ "Welcome to the party line. Enter a six digit room code. Anyone who enters the same code will be on the line with you.";
398
+
399
+ await this.command(leg, "gather_using_speak", {
400
+ payload: `${prefix}${greeting}`,
401
+ voice: this.voice,
402
+ valid_digits: "0123456789",
403
+ minimum_digits: CODE_LENGTH,
404
+ maximum_digits: CODE_LENGTH,
405
+ terminating_digit: "#",
406
+ timeout_millis: 20000,
407
+ });
408
+ }
409
+
410
+ /**
411
+ * Answer a code that belongs to a stream, rather than a room.
412
+ *
413
+ * Returns false when the code is nobody's stream, which is how an ordinary
414
+ * room code still works: this line was a party line before it was a way into
415
+ * a broadcast, and a code that means nothing to the directory should still
416
+ * mean a room.
417
+ */
418
+ private async stream(leg: string, code: string): Promise<boolean> {
419
+ const streams = this.options.streams;
420
+ if (streams === undefined) return false;
421
+
422
+ const live = streams.liveByCode(code);
423
+ if (live !== undefined) {
424
+ const what = live.nowPlaying ? ` of ${live.nowPlaying}` : "";
425
+
426
+ // The share link is not playable. It answers 302 with a cookie and sends
427
+ // a browser to the player page; Telnyx fetches once with no cookie jar
428
+ // and gets a 401 in JSON. Playing it means a caller who is told "here it
429
+ // is" and then hears nothing at all, which is how this was found. Say
430
+ // what is true instead, and hang up rather than bill for silence.
431
+ if (!live.audio) {
432
+ await this.command(leg, "speak", {
433
+ payload:
434
+ `${live.name} is live right now${what}, but this stream cannot be played over the phone. ` +
435
+ "You can listen to it at nixamp dot com slash directory. Goodbye.",
436
+ voice: this.voice,
437
+ });
438
+ await this.command(leg, "hangup", {});
439
+ this.options.onEvent?.(` ${code} is live but announced no audio address; nothing to play.`);
440
+ return true;
441
+ }
442
+
443
+ await this.command(leg, "speak", {
444
+ payload: `Welcome to ${live.name}'s live stream${what}. It started at ${pacificTime(live.startedAt)}. Here it is.`,
445
+ voice: this.voice,
446
+ });
447
+ // A nixamp stream is an MP3 over HTTP and Telnyx will play a URL into a
448
+ // call, so listening by phone costs no audio handling here at all.
449
+ const playing = await this.command(leg, "playback_start", {
450
+ audio_url: live.audio,
451
+ loop: "infinity",
452
+ });
453
+ // Counted only once the audio is actually going. A leg we failed to
454
+ // start is not somebody listening, and the directory would be saying so.
455
+ if (playing) {
456
+ const legs = this.streamLegs.get(code) ?? new Set<string>();
457
+ legs.add(leg);
458
+ this.streamLegs.set(code, legs);
459
+ this.options.onEvent?.(` a caller is listening to ${code} (${legs.size} on the phone).`);
460
+ }
461
+ return true;
462
+ }
463
+
464
+ const ended = streams.endedByCode(code);
465
+ if (ended === undefined) return false;
466
+
467
+ const what = ended.nowPlaying ? ` of ${ended.nowPlaying}` : "";
468
+ // Set before the prompt, not after: the answer can arrive while we are
469
+ // still awaiting the command that asked for it.
470
+ this.pendingReminder.set(leg, code);
471
+ await this.command(leg, "gather_using_speak", {
472
+ payload:
473
+ `Welcome to ${ended.name}'s live stream${what}. ` +
474
+ `The live stream ended at ${pacificTime(ended.endedAt)}. ` +
475
+ "Call back later when they stream again. " +
476
+ "Press 1 to get a text message when they do.",
477
+ voice: this.voice,
478
+ valid_digits: "1",
479
+ minimum_digits: 1,
480
+ maximum_digits: 1,
481
+ timeout_millis: 12000,
482
+ });
483
+ return true;
484
+ }
485
+
486
+ /** Whether the caller took the reminder that was offered. */
487
+ private async reminder(leg: string, code: string, digits: string): Promise<void> {
488
+ const from = this.legFrom.get(leg) ?? "";
489
+ if (!digits.includes("1") || !from) {
490
+ // Not pressing 1 is an answer. So is a call with no caller id, which we
491
+ // cannot text however willing the caller was.
492
+ await this.command(leg, "speak", { payload: "Goodbye.", voice: this.voice });
493
+ await this.command(leg, "hangup", {});
494
+ return;
495
+ }
496
+
497
+ const waiting = this.reminders.get(code) ?? new Set<string>();
498
+ waiting.add(from);
499
+ this.reminders.set(code, waiting);
500
+ this.reminderStore?.add(code, from);
501
+ this.options.onEvent?.(` a caller asked to be told when ${code} is live again.`);
502
+
503
+ await this.command(leg, "speak", {
504
+ payload: "Got it. We will text you when they are live again. Goodbye.",
505
+ voice: this.voice,
506
+ });
507
+ await this.command(leg, "hangup", {});
508
+ }
509
+
510
+ /**
511
+ * A stream came back: text whoever asked to be told.
512
+ *
513
+ * The list is cleared as it is sent. A reminder is a thing somebody asked
514
+ * for once, and texting them every time that stream starts for the rest of
515
+ * the week is how a useful message becomes the reason they block the number.
516
+ */
517
+ async wentLive(stream: { code: string; name: string; nowPlaying: string }): Promise<number> {
518
+ const sms = this.options.sms;
519
+ // Taken from the store first, and that take is what clears it: a number
520
+ // put there by a process that has since been replaced is still owed a
521
+ // text, and this one never heard the call that promised it.
522
+ const stored = this.reminderStore ? await this.reminderStore.take(stream.code) : [];
523
+ const waiting = new Set([...(this.reminders.get(stream.code) ?? []), ...stored]);
524
+ if (waiting.size === 0 || sms === undefined) return 0;
525
+ this.reminders.delete(stream.code);
526
+
527
+ const what = stream.nowPlaying ? ` of ${stream.nowPlaying}` : "";
528
+ // STOP is not decoration: an automated text to a US number has to say how
529
+ // to make it stop, and the carriers check.
530
+ const text =
531
+ `${stream.name} is live now${what} on nixamp. ` +
532
+ `Call ${this.options.callIn ?? "408-357-2326"} and key ${stream.code} to listen. ` +
533
+ "Reply STOP to opt out.";
534
+
535
+ let sent = 0;
536
+ for (const to of waiting) if (await sms.send(to, text)) sent += 1;
537
+ this.options.onEvent?.(` texted ${sent} of ${waiting.size} waiting on ${stream.code}.`);
538
+ return sent;
539
+ }
540
+
541
+ /** How many numbers are waiting to hear that a code is live. */
542
+ waitingOn(code: string): number {
543
+ return this.reminders.get(code)?.size ?? 0;
544
+ }
545
+
546
+ /** Put a leg into a room, making the conference if it is the first one there. */
547
+ private async join(leg: string, code: string): Promise<void> {
548
+ const room = this.room(code);
549
+
550
+ if (room.callers >= this.maxParticipants) {
551
+ await this.command(leg, "speak", {
552
+ payload: "That room is full. Goodbye.",
553
+ voice: this.voice,
554
+ });
555
+ await this.command(leg, "hangup", {});
556
+ return;
557
+ }
558
+
559
+ this.legRoom.set(leg, code);
560
+
561
+ // A conference we made more than four hours ago is gone on Telnyx's side
562
+ // whatever our map says, so it is remade rather than joined.
563
+ const stale = this.now() - room.startedAt > CONFERENCE_TTL_MS;
564
+ if (room.conferenceId !== null && !stale) {
565
+ const joined = await this.request(
566
+ `/conferences/${encodeURIComponent(room.conferenceId)}/actions/join`,
567
+ { call_control_id: leg, start_conference_on_enter: true },
568
+ );
569
+ if (joined !== null) {
570
+ this.enter(room, leg);
571
+ return;
572
+ }
573
+ // The id was stale in a way the clock did not predict -- an operator
574
+ // ended it, or Telnyx did. Fall through and make a new one.
575
+ room.conferenceId = null;
576
+ }
577
+
578
+ const created = await this.request("/conferences", {
579
+ name: `partyline-${this.now()}-${room.legs.size}`,
580
+ call_control_id: leg,
581
+ start_conference_on_create: true,
582
+ max_participants: this.maxParticipants,
583
+ });
584
+
585
+ const id = created && typeof created === "object"
586
+ ? ((created as Record<string, unknown>)["data"] as Record<string, unknown> | undefined)?.["id"]
587
+ : undefined;
588
+
589
+ if (typeof id !== "string") {
590
+ await this.command(leg, "speak", {
591
+ payload: "Sorry, that room could not be opened. Goodbye.",
592
+ voice: this.voice,
593
+ });
594
+ await this.command(leg, "hangup", {});
595
+ this.legRoom.delete(leg);
596
+ return;
597
+ }
598
+
599
+ room.conferenceId = id;
600
+ room.startedAt = this.now();
601
+ this.enter(room, leg);
602
+ }
603
+
604
+ private enter(room: Room, leg: string): void {
605
+ if (room.legs.has(leg)) return;
606
+ room.legs.add(leg);
607
+ room.callers = room.legs.size;
608
+ this.options.onEvent?.(` a caller joined a room (${room.callers} on the line).`);
609
+ }
610
+
611
+ /** How many people are listening to a stream by phone. */
612
+ listenersOn(code: string): number {
613
+ return this.streamLegs.get(code)?.size ?? 0;
614
+ }
615
+
616
+ /** A leg that hung up or was dropped, wherever it was. */
617
+ private release(leg: string): void {
618
+ for (const [code, legs] of this.streamLegs) {
619
+ if (legs.delete(leg) && legs.size === 0) this.streamLegs.delete(code);
620
+ }
621
+ const code = this.legRoom.get(leg);
622
+ this.legRoom.delete(leg);
623
+ if (code === undefined) return;
624
+ const room = this.rooms.get(code);
625
+ if (room === undefined) return;
626
+ room.legs.delete(leg);
627
+ room.callers = room.legs.size;
628
+ if (room.callers === 0) {
629
+ // Telnyx ends an empty conference itself; keeping the code would only
630
+ // mean handing the next caller a dead id.
631
+ this.rooms.delete(code);
632
+ this.options.onEvent?.(" a room is empty.");
633
+ }
634
+ }
635
+
636
+ /**
637
+ * The room on this code, made if nobody is using it.
638
+ *
639
+ * Entering a code nobody is in opens that room rather than failing. The code
640
+ * is a rendezvous, not a credential: two people who agree on 482917
641
+ * beforehand should both be able to dial in, and neither of them should have
642
+ * had to create it first.
643
+ */
644
+ private room(code: string): Room {
645
+ const existing = this.rooms.get(code);
646
+ if (existing !== undefined) return existing;
647
+ const room: Room = {
648
+ code,
649
+ conferenceId: null,
650
+ callers: 0,
651
+ startedAt: this.now(),
652
+ legs: new Set<string>(),
653
+ };
654
+ this.rooms.set(code, room);
655
+ return room;
656
+ }
657
+
658
+ private get voice(): string {
659
+ return this.options.voice ?? DEFAULT_VOICE;
660
+ }
661
+
662
+ private get maxParticipants(): number {
663
+ return this.options.maxParticipants ?? 50;
664
+ }
665
+
666
+ /** One call-control command. True when Telnyx accepted it. */
667
+ private async command(leg: string, action: string, body: unknown): Promise<boolean> {
668
+ const path = `/calls/${encodeURIComponent(leg)}/actions/${action}`;
669
+ return (await this.request(path, body)) !== null;
670
+ }
671
+
672
+ /** A POST to Telnyx, or null if it did not work. */
673
+ private async request(path: string, body: unknown): Promise<unknown | null> {
674
+ try {
675
+ const response = await this.fetch(`${TELNYX_API}${path}`, {
676
+ method: "POST",
677
+ headers: {
678
+ authorization: `Bearer ${this.options.apiKey}`,
679
+ "content-type": "application/json",
680
+ },
681
+ body: JSON.stringify(body),
682
+ });
683
+ if (!response.ok) {
684
+ // A command against a leg that already hung up is a 422 and is not
685
+ // worth a stack trace; it is the ordinary end of a race.
686
+ this.options.onEvent?.(` telnyx ${path} -> ${response.status}`);
687
+ return null;
688
+ }
689
+ const text = await response.text();
690
+ return text ? (JSON.parse(text) as unknown) : {};
691
+ } catch (error) {
692
+ this.options.onEvent?.(` telnyx ${path} failed: ${(error as Error).message}`);
693
+ return null;
694
+ }
695
+ }
696
+ }
697
+
698
+ /**
699
+ * Texting, over Telnyx.
700
+ *
701
+ * A separate `from` because it is a different number: the call arrives on the
702
+ * toll-free line, but toll-free A2P messaging is filtered by carriers until
703
+ * that number is verified and ours is not yet. The long code already carries a
704
+ * messaging profile, so it can send today -- and when verification lands, this
705
+ * becomes a one-line change rather than a redesign.
706
+ */
707
+ export function telnyxSms(
708
+ { apiKey, from, fetch = globalThis.fetch, onEvent }: {
709
+ apiKey: string;
710
+ from: string;
711
+ fetch?: typeof globalThis.fetch;
712
+ onEvent?: (message: string) => void;
713
+ },
714
+ ): Sms {
715
+ return {
716
+ async send(to: string, text: string): Promise<boolean> {
717
+ try {
718
+ const response = await fetch(`${TELNYX_API}/messages`, {
719
+ method: "POST",
720
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
721
+ body: JSON.stringify({ from, to, text }),
722
+ });
723
+ if (!response.ok) {
724
+ onEvent?.(` sms to ${to} -> ${response.status}`);
725
+ return false;
726
+ }
727
+ return true;
728
+ } catch (error) {
729
+ onEvent?.(` sms to ${to} failed: ${(error as Error).message}`);
730
+ return false;
731
+ }
732
+ },
733
+ };
734
+ }
735
+
736
+ /** Constant-time compare, for the places a token is checked rather than signed. */
737
+ export function sameSecret(a: string, b: string): boolean {
738
+ const left = Buffer.from(a, "utf8");
739
+ const right = Buffer.from(b, "utf8");
740
+ if (left.length !== right.length) return false;
741
+ return timingSafeEqual(left, right);
742
+ }