nixamp 0.2.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.
Files changed (69) hide show
  1. package/README.md +171 -0
  2. package/dist/accounts.d.ts +54 -0
  3. package/dist/accounts.js +160 -0
  4. package/dist/broadcast.d.ts +96 -0
  5. package/dist/broadcast.js +193 -0
  6. package/dist/channels.d.ts +94 -0
  7. package/dist/channels.js +235 -0
  8. package/dist/connections.d.ts +6 -0
  9. package/dist/connections.js +13 -0
  10. package/dist/directory.d.ts +186 -0
  11. package/dist/directory.js +275 -0
  12. package/dist/durable.d.ts +70 -0
  13. package/dist/durable.js +156 -0
  14. package/dist/follows.d.ts +92 -0
  15. package/dist/follows.js +248 -0
  16. package/dist/ingest.d.ts +80 -0
  17. package/dist/ingest.js +252 -0
  18. package/dist/main.js +21 -0
  19. package/dist/manage.js +2 -1
  20. package/dist/notify.d.ts +83 -0
  21. package/dist/notify.js +126 -0
  22. package/dist/optin.d.ts +37 -0
  23. package/dist/optin.js +122 -0
  24. package/dist/owner.d.ts +53 -0
  25. package/dist/owner.js +96 -0
  26. package/dist/partyline.d.ts +259 -0
  27. package/dist/partyline.js +616 -0
  28. package/dist/paywall.d.ts +60 -0
  29. package/dist/paywall.js +162 -0
  30. package/dist/playlist.js +5 -0
  31. package/dist/publish.d.ts +57 -0
  32. package/dist/publish.js +106 -0
  33. package/dist/rtmp-in.d.ts +22 -0
  34. package/dist/rtmp-in.js +79 -0
  35. package/dist/server.d.ts +94 -0
  36. package/dist/server.js +1158 -12
  37. package/dist/session.d.ts +29 -0
  38. package/dist/session.js +184 -0
  39. package/dist/share.d.ts +26 -0
  40. package/dist/share.js +31 -0
  41. package/package.json +8 -2
  42. package/src/accounts.ts +193 -0
  43. package/src/broadcast.ts +264 -0
  44. package/src/channels.ts +281 -0
  45. package/src/connections.ts +13 -0
  46. package/src/directory.ts +362 -0
  47. package/src/durable.ts +215 -0
  48. package/src/follows.ts +307 -0
  49. package/src/ingest.ts +297 -0
  50. package/src/main.ts +21 -0
  51. package/src/manage.ts +2 -1
  52. package/src/notify.ts +217 -0
  53. package/src/optin.ts +128 -0
  54. package/src/owner.ts +113 -0
  55. package/src/partyline.ts +742 -0
  56. package/src/paywall.ts +198 -0
  57. package/src/playlist.ts +5 -0
  58. package/src/publish.ts +137 -0
  59. package/src/rtmp-in.ts +90 -0
  60. package/src/server.ts +1304 -12
  61. package/src/session.ts +209 -0
  62. package/src/share.ts +40 -0
  63. package/src/types/auth-system.d.ts +77 -0
  64. package/web/dist/assets/{index-BGKWWaIx.css → index-DSIDSSPF.css} +1 -1
  65. package/web/dist/assets/index-qRguFskX.js +1 -0
  66. package/web/dist/index.html +62 -6
  67. package/web/dist/install.sh +82 -0
  68. package/web/dist/sw.js +45 -3
  69. package/web/dist/assets/index-Dhja5wxB.js +0 -1
package/dist/server.js CHANGED
@@ -11,12 +11,30 @@
11
11
  */
12
12
  import { createReadStream, statSync } from "node:fs";
13
13
  import { createServer as createHttpServer } from "node:http";
14
+ import { hostname } from "node:os";
14
15
  import { spawn, spawnSync } from "node:child_process";
15
16
  import { readFileSync } from "node:fs";
16
17
  import { Connections } from "./connections.js";
17
- import { isRemote } from "./sources.js";
18
- import { elevate, firewallInUse, keyCookie, keyFrom, keysMatch, newKey, portCommands, reachableAddresses, shareLink, } from "./share.js";
18
+ import { Broadcaster, DEFAULT_ENCODER, PRESETS, redact, } from "./broadcast.js";
19
+ import { Ingest, normaliseFormat } from "./ingest.js";
20
+ import { Channels, cleanId } from "./channels.js";
21
+ import { RtmpListeners } from "./rtmp-in.js";
22
+ import { Accounts, clearedCookie, sessionCookie, tokenFrom } from "./accounts.js";
23
+ import { needsAdmin, Owner } from "./owner.js";
24
+ import { readSession } from "./session.js";
25
+ import { Directory, ENDED_TTL_MS, parseAnnouncement } from "./directory.js";
26
+ import { PartyLine, telnyxSms } from "./partyline.js";
27
+ import { CALL_IN_NUMBER, OPT_IN_PATH, optInPage } from "./optin.js";
28
+ import pg from "pg";
29
+ import { Follows, phoneFrom } from "./follows.js";
30
+ import { Durable } from "./durable.js";
31
+ import { notifyAll, resendEmail, webPush } from "./notify.js";
32
+ import { confirm, DEFAULT_DIRECTORY, Publisher } from "./publish.js";
33
+ import { applyRemoteConfig, createPaywall, FREE_LISTENERS, paywallFromEnv, } from "./paywall.js";
34
+ import { isRemote, playsInBrowser } from "./sources.js";
35
+ import { allowedForListening, elevate, firewallInUse, keyCookie, keyFrom, newKey, portCommands, reachableAddresses, scopeOf, shareLink, audioLink, } from "./share.js";
19
36
  import { extname, join, normalize, resolve, sep } from "node:path";
37
+ import { fileURLToPath } from "node:url";
20
38
  import { detectTools, peaks, RATE, Stream, toMono, } from "./audio.js";
21
39
  import { Analyser, bandEdges, bands, decay } from "./fft.js";
22
40
  import { loadSource } from "./playlist.js";
@@ -43,6 +61,15 @@ export function parseServeArgs(argv) {
43
61
  key: true,
44
62
  openPort: false,
45
63
  announce: false,
64
+ directory: false,
65
+ publish: "ask",
66
+ name: "",
67
+ x402: false,
68
+ owner: "",
69
+ ingest: false,
70
+ rtmpIn: 0,
71
+ rtmpStreams: 3,
72
+ rtmp: [],
46
73
  };
47
74
  let sawRoot = false;
48
75
  for (let i = 0; i < argv.length; i++) {
@@ -79,6 +106,49 @@ export function parseServeArgs(argv) {
79
106
  else if (arg === "--announce") {
80
107
  options.announce = true;
81
108
  }
109
+ else if (arg === "--directory") {
110
+ options.directory = true;
111
+ }
112
+ else if (arg === "--publish") {
113
+ options.publish = "yes";
114
+ }
115
+ else if (arg === "--no-publish") {
116
+ options.publish = "no";
117
+ }
118
+ else if (arg === "--name") {
119
+ options.name = value();
120
+ }
121
+ else if (arg === "--owner") {
122
+ options.owner = value();
123
+ }
124
+ else if (arg === "--ingest") {
125
+ options.ingest = true;
126
+ }
127
+ else if (arg === "--rtmp-streams") {
128
+ const count = Number(value());
129
+ if (!Number.isInteger(count) || count < 1 || count > 16) {
130
+ throw new Error("nixamp serve: --rtmp-streams must be between 1 and 16");
131
+ }
132
+ options.rtmpStreams = count;
133
+ }
134
+ else if (arg === "--rtmp-in") {
135
+ const port = Number(value());
136
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
137
+ throw new Error("nixamp serve: --rtmp-in must be a port number");
138
+ }
139
+ options.rtmpIn = port;
140
+ // Listening for RTMP is accepting a live stream, so it implies --ingest.
141
+ options.ingest = true;
142
+ }
143
+ else if (arg === "--rtmp") {
144
+ options.rtmp.push(value());
145
+ }
146
+ else if (arg === "--x402") {
147
+ options.x402 = true;
148
+ }
149
+ else if (arg === "--no-x402") {
150
+ options.x402 = false;
151
+ }
82
152
  else if (arg.startsWith("-")) {
83
153
  throw new Error(`nixamp serve: unknown option ${arg}`);
84
154
  }
@@ -449,38 +519,609 @@ export function createHandler(engine, options) {
449
519
  const url = new URL(request.url ?? "/", "http://localhost");
450
520
  const path = url.pathname;
451
521
  const key = options.key ?? null;
522
+ const listenKey = options.listenKey ?? null;
452
523
  if (request.method === "OPTIONS") {
453
524
  response.writeHead(204, CORS);
454
525
  response.end();
455
526
  return;
456
527
  }
457
- // Opening the share link is what hands a browser its key. It comes back as
458
- // a cookie, so every later fetch, EventSource and <audio src> carries it
459
- // without the page knowing anything about keys.
528
+ // Opening a share link is what hands a browser its key. It comes back as a
529
+ // cookie, so every later fetch, EventSource and <audio src> carries it
530
+ // without the page knowing anything about keys. Either key works here, and
531
+ // which one was used decides what the browser can then do.
460
532
  if (key !== null && path.startsWith("/s/")) {
461
533
  const offered = decodeURIComponent(path.slice("/s/".length));
462
- if (!keysMatch(offered, key)) {
534
+ if (scopeOf(offered, key, listenKey) === null) {
463
535
  json(response, 404, { error: "not found" });
464
536
  return;
465
537
  }
466
- response.writeHead(302, { ...CORS, "set-cookie": keyCookie(key), location: "/" });
538
+ response.writeHead(302, { ...CORS, "set-cookie": keyCookie(offered), location: "/" });
467
539
  response.end();
468
540
  return;
469
541
  }
542
+ // The page explaining the reminder texts. Public for the same reason the
543
+ // webhook is: the reader is a carrier reviewing the number, or somebody
544
+ // who just got a message and wants it to stop. Neither has a share link.
545
+ if (path === OPT_IN_PATH && options.partyLine) {
546
+ const body = optInPage();
547
+ response.writeHead(200, {
548
+ ...CORS,
549
+ "content-type": "text/html; charset=utf-8",
550
+ "content-length": Buffer.byteLength(body),
551
+ });
552
+ response.end(request.method === "HEAD" ? undefined : body);
553
+ return;
554
+ }
555
+ // --- following a broadcaster ------------------------------------------
556
+ //
557
+ // Behind the sign-in rather than the share key: a follow belongs to an
558
+ // account, and an account is the only thing that makes "notify me on my
559
+ // other device" mean anything.
560
+ if (path.startsWith("/api/v1/follows") && options.follows && options.accounts) {
561
+ const me = await options.accounts.whoIs(tokenFrom(request.headers));
562
+ if (me === null) {
563
+ json(response, 401, { error: "sign in to follow" });
564
+ return;
565
+ }
566
+ const follows = options.follows;
567
+ if (path === "/api/v1/follows" && request.method === "GET") {
568
+ const ids = await follows.following(me.id);
569
+ // An id is not a name. The directory is the only thing that knows what
570
+ // an account calls itself, from the last stream it announced -- which
571
+ // is empty for somebody who has never streamed, and the caller decides
572
+ // what to show for that rather than being handed a blank.
573
+ json(response, 200, {
574
+ following: ids.map((id) => ({
575
+ id,
576
+ name: options.directory?.nameOf(id) ?? "",
577
+ live: options.directory?.isLive(id) ?? false,
578
+ })),
579
+ });
580
+ return;
581
+ }
582
+ const streamer = path.slice("/api/v1/follows/".length);
583
+ if (!path.startsWith("/api/v1/follows/") || !streamer) {
584
+ json(response, 404, { error: "no such endpoint" });
585
+ return;
586
+ }
587
+ if (request.method === "PUT" || request.method === "POST") {
588
+ const added = await follows.follow(me.id, decodeURIComponent(streamer));
589
+ // Following yourself is refused rather than silently stored: you do
590
+ // not need telling that you went live.
591
+ json(response, added ? 200 : 422, added
592
+ ? { following: true, followers: await follows.followerCount(decodeURIComponent(streamer)) }
593
+ : { error: "you cannot follow yourself" });
594
+ return;
595
+ }
596
+ if (request.method === "DELETE") {
597
+ await follows.unfollow(me.id, decodeURIComponent(streamer));
598
+ json(response, 200, { following: false });
599
+ return;
600
+ }
601
+ if (request.method === "GET") {
602
+ json(response, 200, { following: await follows.isFollowing(me.id, decodeURIComponent(streamer)) });
603
+ return;
604
+ }
605
+ json(response, 405, { error: "PUT, DELETE or GET" });
606
+ return;
607
+ }
608
+ // --- where to reach a follower ----------------------------------------
609
+ if (path.startsWith("/api/v1/notify") && options.follows && options.accounts) {
610
+ // The key is public by design: it is what a browser needs before it can
611
+ // ask permission, and it is useless without the private half.
612
+ if (path === "/api/v1/notify/key" && request.method === "GET") {
613
+ json(response, 200, { publicKey: options.vapidPublicKey ?? "" });
614
+ return;
615
+ }
616
+ const me = await options.accounts.whoIs(tokenFrom(request.headers));
617
+ if (me === null) {
618
+ json(response, 401, { error: "sign in first" });
619
+ return;
620
+ }
621
+ const follows = options.follows;
622
+ if (path === "/api/v1/notify/prefs") {
623
+ if (request.method === "GET") {
624
+ json(response, 200, await follows.prefs(me.id));
625
+ return;
626
+ }
627
+ if (request.method !== "PUT" && request.method !== "POST") {
628
+ json(response, 405, { error: "GET or PUT" });
629
+ return;
630
+ }
631
+ let body;
632
+ try {
633
+ body = JSON.parse(await readBody(request));
634
+ }
635
+ catch {
636
+ json(response, 400, { error: "bad JSON" });
637
+ return;
638
+ }
639
+ // A number we cannot dial is worse than no number: it is a text that
640
+ // silently goes nowhere for as long as nobody checks.
641
+ if (body["phone"] !== undefined && body["phone"] !== "" && !phoneFrom(body["phone"])) {
642
+ json(response, 422, { error: "that does not look like a phone number" });
643
+ return;
644
+ }
645
+ await follows.setPrefs(me.id, {
646
+ ...(body["phone"] === undefined ? {} : { phone: String(body["phone"]) }),
647
+ ...(typeof body["wantsEmail"] === "boolean" ? { wantsEmail: body["wantsEmail"] } : {}),
648
+ ...(typeof body["wantsSms"] === "boolean" ? { wantsSms: body["wantsSms"] } : {}),
649
+ ...(typeof body["wantsWeb"] === "boolean" ? { wantsWeb: body["wantsWeb"] } : {}),
650
+ });
651
+ json(response, 200, await follows.prefs(me.id));
652
+ return;
653
+ }
654
+ if (path === "/api/v1/notify/subscribe") {
655
+ if (request.method === "DELETE") {
656
+ const endpoint = url.searchParams.get("endpoint") ?? "";
657
+ await follows.removePush(endpoint);
658
+ json(response, 200, { ok: true });
659
+ return;
660
+ }
661
+ if (request.method !== "POST" && request.method !== "PUT") {
662
+ json(response, 405, { error: "POST or DELETE" });
663
+ return;
664
+ }
665
+ let body;
666
+ try {
667
+ body = JSON.parse(await readBody(request));
668
+ }
669
+ catch {
670
+ json(response, 400, { error: "bad JSON" });
671
+ return;
672
+ }
673
+ const endpoint = typeof body.endpoint === "string" ? body.endpoint : "";
674
+ const p256dh = typeof body.keys?.p256dh === "string" ? body.keys.p256dh : "";
675
+ const auth = typeof body.keys?.auth === "string" ? body.keys.auth : "";
676
+ if (!endpoint || !p256dh || !auth) {
677
+ json(response, 422, { error: "a subscription needs an endpoint and both keys" });
678
+ return;
679
+ }
680
+ await follows.addPush(me.id, { endpoint, p256dh, auth });
681
+ json(response, 200, { ok: true });
682
+ return;
683
+ }
684
+ json(response, 404, { error: "no such endpoint" });
685
+ return;
686
+ }
687
+ // --- the party line ---------------------------------------------------
688
+ //
689
+ // Ahead of the share-key check because the caller is a telephone. Telnyx
690
+ // has no cookie and no link; what it has is an ed25519 signature over the
691
+ // body, which is a stronger claim than a key in a URL anyway.
692
+ if (path.startsWith("/api/v1/partyline/") && options.partyLine) {
693
+ const partyLine = options.partyLine;
694
+ if (path === "/api/v1/partyline/rooms") {
695
+ json(response, 200, { rooms: partyLine.list() });
696
+ return;
697
+ }
698
+ if (path !== "/api/v1/partyline/webhook") {
699
+ json(response, 404, { error: "no such endpoint" });
700
+ return;
701
+ }
702
+ if (request.method !== "POST") {
703
+ json(response, 405, { error: "POST only" });
704
+ return;
705
+ }
706
+ // The bytes as they arrived. Parsing first and reserialising would
707
+ // change the whitespace the signature was computed over.
708
+ let raw;
709
+ try {
710
+ raw = await readBody(request);
711
+ }
712
+ catch {
713
+ json(response, 413, { error: "body too large" });
714
+ return;
715
+ }
716
+ const signature = request.headers["telnyx-signature-ed25519"];
717
+ const timestamp = request.headers["telnyx-timestamp"];
718
+ const ok = partyLine.verify(raw, typeof signature === "string" ? signature : undefined, typeof timestamp === "string" ? timestamp : undefined);
719
+ if (!ok) {
720
+ json(response, 401, { error: "bad signature" });
721
+ return;
722
+ }
723
+ let event;
724
+ try {
725
+ event = JSON.parse(raw);
726
+ }
727
+ catch {
728
+ json(response, 400, { error: "bad JSON" });
729
+ return;
730
+ }
731
+ // Answer first, act second. Telnyx retries anything it does not hear
732
+ // back about quickly, and a retried call.answered would ask the caller
733
+ // which room they wanted twice.
734
+ json(response, 200, { ok: true });
735
+ void partyLine.handle(event.data ?? {}).catch(() => { });
736
+ return;
737
+ }
470
738
  // /api/health answers unauthenticated on purpose: it is how you check the
471
739
  // port is open from another device before wondering whether the link is
472
740
  // wrong, and it says nothing about the library.
473
- if (key !== null && path !== "/api/health") {
474
- const offered = keyFrom(request, url);
475
- if (offered === null || !keysMatch(offered, key)) {
741
+ if (key !== null &&
742
+ path !== "/api/health" &&
743
+ path !== "/api/directory" &&
744
+ !path.startsWith("/api/v1/auth/")) {
745
+ const scope = scopeOf(keyFrom(request, url), key, listenKey);
746
+ if (scope === null) {
476
747
  json(response, 401, { error: "this nixamp needs the key from its share link" });
477
748
  return;
478
749
  }
750
+ if (scope === "listen" && !allowedForListening(path)) {
751
+ json(response, 403, { error: "this link can listen, not drive" });
752
+ return;
753
+ }
479
754
  }
480
755
  if (path === "/api/health") {
481
756
  json(response, 200, { name: "nixamp", version: options.version, media: options.media });
482
757
  return;
483
758
  }
759
+ // --- accounts ---------------------------------------------------------
760
+ //
761
+ // Before the share-key check, because signing in is how somebody without a
762
+ // key becomes somebody with one. The API is versioned and namespaced the
763
+ // way the rest of the fleet's is.
764
+ if (path.startsWith("/api/v1/auth/") && options.accounts) {
765
+ const accounts = options.accounts;
766
+ const secure = options.secureCookies ?? false;
767
+ if (path === "/api/v1/auth/me") {
768
+ const who = await accounts.whoIs(tokenFrom(request.headers));
769
+ if (who === null) {
770
+ json(response, 401, { error: "not signed in" });
771
+ return;
772
+ }
773
+ json(response, 200, { account: who });
774
+ return;
775
+ }
776
+ if (path === "/api/v1/auth/logout") {
777
+ response.writeHead(200, {
778
+ ...CORS,
779
+ "content-type": "application/json; charset=utf-8",
780
+ "set-cookie": clearedCookie(),
781
+ });
782
+ response.end(JSON.stringify({ ok: true }));
783
+ return;
784
+ }
785
+ const signingUp = path === "/api/v1/auth/signup";
786
+ if (!signingUp && path !== "/api/v1/auth/login") {
787
+ json(response, 404, { error: "no such endpoint" });
788
+ return;
789
+ }
790
+ if (request.method !== "POST") {
791
+ json(response, 405, { error: "POST only" });
792
+ return;
793
+ }
794
+ let body;
795
+ try {
796
+ body = JSON.parse(await readBody(request));
797
+ }
798
+ catch {
799
+ json(response, 400, { error: "bad JSON" });
800
+ return;
801
+ }
802
+ const result = signingUp
803
+ ? await accounts.signUp(body.email, body.password)
804
+ : await accounts.signIn(body.email, body.password);
805
+ if (!result.ok) {
806
+ // 409 for an address that is taken, 401 for credentials that are not.
807
+ json(response, signingUp ? 409 : 401, { error: result.error });
808
+ return;
809
+ }
810
+ // The token goes back in the body for the CLI and the desktop app, and
811
+ // as a cookie for the browser, which then needs to know nothing about it.
812
+ response.writeHead(200, {
813
+ ...CORS,
814
+ "content-type": "application/json; charset=utf-8",
815
+ "set-cookie": sessionCookie(result.token, secure),
816
+ });
817
+ response.end(JSON.stringify({ account: result.account, token: result.token }));
818
+ return;
819
+ }
820
+ // The directory is public to read and answered before the key check,
821
+ // because a visitor to nixamp.com has no key and is exactly who it is for.
822
+ //
823
+ // Announcing is not public any more. A listing now carries a phone number
824
+ // people dial and minutes we pay for, so it has to be attributable to
825
+ // somebody: broadcasters register, and a caller just dials. Reading stays
826
+ // open to everyone -- the whole point is a directory a stranger can browse.
827
+ if (path === "/api/directory" && options.directory) {
828
+ if (request.method === "GET") {
829
+ // Each stream carries its call-in code and how many people are on the
830
+ // phone for it. The code is published on purpose: it is a public
831
+ // call-in line, and a listing you cannot dial is a listing of nothing.
832
+ const onThePhone = options.partyLine;
833
+ const streams = options.directory.list().map((stream) => ({
834
+ ...stream,
835
+ callers: onThePhone ? onThePhone.listenersOn(stream.code) : 0,
836
+ }));
837
+ // Recently ended too, because following exists to hear about
838
+ // broadcasts you would otherwise miss -- and a list of only what is on
839
+ // can only be used to follow somebody during a broadcast you did not
840
+ // miss. No url and no code: there is nothing to listen to.
841
+ const recent = options.directory.recentlyEnded().map((stream) => ({
842
+ name: stream.name,
843
+ ownerId: stream.ownerId,
844
+ nowPlaying: stream.nowPlaying,
845
+ endedAt: stream.endedAt,
846
+ }));
847
+ json(response, 200, { streams, recent, callIn: CALL_IN_NUMBER, now: Date.now() });
848
+ return;
849
+ }
850
+ if (request.method === "POST") {
851
+ // Only where there are accounts to check against. An instance with no
852
+ // Accounts is somebody's laptop, which has no registration to demand.
853
+ let ownerId = "";
854
+ if (options.accounts) {
855
+ const who = await options.accounts.whoIs(tokenFrom(request.headers));
856
+ if (who === null) {
857
+ json(response, 401, {
858
+ error: "sign in to list a stream: nixamp login, then nixamp serve --directory",
859
+ });
860
+ return;
861
+ }
862
+ // From the token, never the body. A stream that could name its own
863
+ // owner could name somebody else's, and their followers would be
864
+ // told about a broadcast that person is not making.
865
+ ownerId = who.id;
866
+ }
867
+ let announcement;
868
+ try {
869
+ announcement = parseAnnouncement(JSON.parse(await readBody(request)));
870
+ }
871
+ catch {
872
+ json(response, 400, { error: "bad JSON" });
873
+ return;
874
+ }
875
+ if (announcement === null) {
876
+ json(response, 422, { error: "a listing needs a name and a URL a browser can reach" });
877
+ return;
878
+ }
879
+ const listing = options.directory.announce(announcement, ownerId);
880
+ // A stream reappearing is the event somebody asked to be told about.
881
+ // Answered first and texted after, because the publisher's heartbeat
882
+ // should not wait on an SMS gateway.
883
+ json(response, 200, listing);
884
+ if (options.partyLine) {
885
+ void options.partyLine
886
+ .wentLive({ code: listing.code, name: listing.name, nowPlaying: listing.nowPlaying })
887
+ .catch(() => { });
888
+ }
889
+ return;
890
+ }
891
+ if (request.method === "DELETE") {
892
+ const id = url.searchParams.get("id");
893
+ if (id)
894
+ options.directory.withdraw(id);
895
+ json(response, 200, { ok: true });
896
+ return;
897
+ }
898
+ json(response, 405, { error: "GET, POST or DELETE" });
899
+ return;
900
+ }
901
+ // Administering is a different question from listening, and it is asked
902
+ // after the share key: the control key answers both, but a listen key or a
903
+ // nixamp.com session answers only one of them.
904
+ if (options.owner && needsAdmin(path, request.method ?? "GET")) {
905
+ // A server started with --no-key has said that anyone who can reach the
906
+ // port may drive it, and prints exactly that. Locking administration to
907
+ // nobody would contradict it and leave such a server unadministrable.
908
+ const holdsControl = key === null || scopeOf(keyFrom(request, url), key, null) === "control";
909
+ const check = await options.owner.check(holdsControl, tokenFrom(request.headers));
910
+ if (path === "/api/admin") {
911
+ // Always answered, and honestly: the page has to know whether to draw
912
+ // an admin panel at all, and "no" is a real answer rather than a 403.
913
+ json(response, 200, { allowed: check.allowed, as: check.as, claimed: options.owner.claimed });
914
+ return;
915
+ }
916
+ if (!check.allowed) {
917
+ json(response, 403, {
918
+ error: options.owner.claimed
919
+ ? "sign in to nixamp.com as this server's owner, or use its control link"
920
+ : "this server has no owner signed in; use its control link",
921
+ });
922
+ return;
923
+ }
924
+ }
925
+ // After the key check: a paying listener still needs the link, and a 402
926
+ // is a worse answer than a 401 to someone who has neither.
927
+ if (options.paywall && (await options.paywall(request, response, path)))
928
+ return;
929
+ // --- several streams at once ------------------------------------------
930
+ //
931
+ // A channel is one publisher and everybody listening to them. Two or three
932
+ // devices can publish at once, each to their own channel, and a listener
933
+ // picks which to hear.
934
+ if (path === "/api/channels" && options.channels) {
935
+ json(response, 200, { channels: options.channels.list(), listeners: options.channels.listeners });
936
+ return;
937
+ }
938
+ // Publishing. Anyone with the control link may; listening to the result is
939
+ // open to whoever has the share link, like the rest of the audio.
940
+ if (path.startsWith("/api/channels/") && options.channels) {
941
+ const channels = options.channels;
942
+ const rest = path.slice("/api/channels/".length);
943
+ const [rawId, action] = rest.split("/");
944
+ const id = cleanId(rawId);
945
+ if (action === undefined && request.method === "GET") {
946
+ // Listening. The response is the fan-out target: whatever ffmpeg
947
+ // produces for this channel is written to it until one end goes away.
948
+ const detach = channels.listen(id, response);
949
+ if (detach === null) {
950
+ json(response, 404, { error: "nothing is playing on that channel" });
951
+ return;
952
+ }
953
+ watch(request, response, "stream", id);
954
+ response.writeHead(200, {
955
+ ...CORS,
956
+ "content-type": "audio/mpeg",
957
+ "cache-control": "no-store",
958
+ });
959
+ const leave = () => detach();
960
+ request.on("close", leave);
961
+ response.on("close", leave);
962
+ return;
963
+ }
964
+ if (action === undefined && request.method === "DELETE") {
965
+ // Asked once: the second call would answer false, having just stopped
966
+ // the thing it was asking about.
967
+ const stopped = channels.stop(id);
968
+ json(response, stopped ? 200 : 404, { ok: stopped });
969
+ return;
970
+ }
971
+ if (request.method !== "POST") {
972
+ json(response, 405, { error: "GET, POST or DELETE" });
973
+ return;
974
+ }
975
+ const format = normaliseFormat(url.searchParams.get("format") ?? request.headers["content-type"]);
976
+ if (format === null) {
977
+ json(response, 415, { error: "give a container ffmpeg knows: webm, ogg, mp4, mp3, wav" });
978
+ return;
979
+ }
980
+ const name = url.searchParams.get("name") ?? "";
981
+ // A chunked publisher sends many requests to one channel, so the first
982
+ // claims it and the rest feed what is already there.
983
+ if (action === "chunk") {
984
+ if (!channels.has(id) && channels.publish(id, name, format, "http") === null) {
985
+ json(response, 409, { error: "that channel is already being published to" });
986
+ return;
987
+ }
988
+ const chunks = [];
989
+ for await (const chunk of request)
990
+ chunks.push(chunk);
991
+ channels.writeTo(id, Buffer.concat(chunks));
992
+ json(response, 200, { ok: true });
993
+ return;
994
+ }
995
+ const claimed = channels.publish(id, name, format, "http");
996
+ if (claimed === null) {
997
+ json(response, 409, { error: "that channel is already being published to" });
998
+ return;
999
+ }
1000
+ try {
1001
+ await claimed.pump(request);
1002
+ }
1003
+ catch {
1004
+ // A publisher that hung up is not an error worth a 500.
1005
+ }
1006
+ claimed.close();
1007
+ json(response, 200, { ok: true, bytes: claimed.info.bytes });
1008
+ return;
1009
+ }
1010
+ // --- streaming in ---------------------------------------------------
1011
+ //
1012
+ // Both shapes write into the same ffmpeg, so everything downstream cannot
1013
+ // tell which one a sender used.
1014
+ if (path === "/api/ingest" && options.ingest) {
1015
+ if (request.method === "GET") {
1016
+ json(response, 200, options.ingest.status());
1017
+ return;
1018
+ }
1019
+ if (request.method === "DELETE") {
1020
+ options.ingest.close();
1021
+ json(response, 200, { ok: true });
1022
+ return;
1023
+ }
1024
+ if (request.method !== "POST") {
1025
+ json(response, 405, { error: "GET, POST or DELETE" });
1026
+ return;
1027
+ }
1028
+ const format = normaliseFormat(url.searchParams.get("format") ?? request.headers["content-type"]);
1029
+ if (format === null) {
1030
+ json(response, 415, { error: "give a container ffmpeg knows: webm, ogg, mp4, mp3, wav" });
1031
+ return;
1032
+ }
1033
+ const session = options.ingest.open(url.searchParams.get("name") ?? "", format);
1034
+ if (session === null) {
1035
+ // Somebody else is already broadcasting, which is a different problem
1036
+ // from the request being wrong.
1037
+ json(response, 409, { error: "something is already streaming in" });
1038
+ return;
1039
+ }
1040
+ try {
1041
+ await options.ingest.pump(request);
1042
+ }
1043
+ catch {
1044
+ // A sender that hung up is not an error worth a 500.
1045
+ }
1046
+ options.ingest.close();
1047
+ json(response, 200, { ok: true, bytes: session.bytes });
1048
+ return;
1049
+ }
1050
+ // A browser cannot stream a request body over plain HTTP/1.1, so a phone
1051
+ // sends its recording a chunk at a time instead.
1052
+ if (path === "/api/ingest/chunk" && options.ingest) {
1053
+ if (request.method !== "POST") {
1054
+ json(response, 405, { error: "POST only" });
1055
+ return;
1056
+ }
1057
+ if (!options.ingest.live) {
1058
+ const format = normaliseFormat(url.searchParams.get("format") ?? request.headers["content-type"]);
1059
+ if (format === null) {
1060
+ json(response, 415, { error: "give a container ffmpeg knows: webm, ogg, mp4, mp3, wav" });
1061
+ return;
1062
+ }
1063
+ if (options.ingest.open(url.searchParams.get("name") ?? "", format) === null) {
1064
+ json(response, 409, { error: "something is already streaming in" });
1065
+ return;
1066
+ }
1067
+ }
1068
+ const chunks = [];
1069
+ for await (const chunk of request)
1070
+ chunks.push(chunk);
1071
+ options.ingest.write(Buffer.concat(chunks));
1072
+ json(response, 200, options.ingest.status());
1073
+ return;
1074
+ }
1075
+ // --- broadcasting out -------------------------------------------------
1076
+ if (path === "/api/broadcast" && options.broadcaster) {
1077
+ if (request.method === "GET") {
1078
+ json(response, 200, options.broadcaster.status());
1079
+ return;
1080
+ }
1081
+ if (request.method === "DELETE") {
1082
+ options.broadcaster.stop();
1083
+ json(response, 200, options.broadcaster.status());
1084
+ return;
1085
+ }
1086
+ if (request.method !== "POST") {
1087
+ json(response, 405, { error: "GET, POST or DELETE" });
1088
+ return;
1089
+ }
1090
+ let source = "";
1091
+ try {
1092
+ source = String(JSON.parse(await readBody(request)).source ?? "");
1093
+ }
1094
+ catch {
1095
+ json(response, 400, { error: "bad JSON" });
1096
+ return;
1097
+ }
1098
+ const current = engine.snapshot();
1099
+ const chosen = source || engine.trackPath(current.index) || "";
1100
+ if (!chosen) {
1101
+ json(response, 422, { error: "nothing to broadcast" });
1102
+ return;
1103
+ }
1104
+ const plan = options.broadcast?.() ?? { destinations: [], settings: DEFAULT_ENCODER };
1105
+ const started = options.broadcaster.start({
1106
+ source: chosen,
1107
+ destinations: plan.destinations,
1108
+ settings: plan.settings,
1109
+ webAudio: false,
1110
+ // Music has no picture, and RTMP platforms insist on a video track.
1111
+ needsVideo: true,
1112
+ });
1113
+ if (!started.ok) {
1114
+ json(response, 422, { error: started.error });
1115
+ return;
1116
+ }
1117
+ json(response, 200, options.broadcaster.status());
1118
+ return;
1119
+ }
1120
+ // Names and URLs, never a key.
1121
+ if (path === "/api/broadcast/destinations" && options.broadcast) {
1122
+ json(response, 200, { destinations: options.broadcast().destinations.map(redact) });
1123
+ return;
1124
+ }
484
1125
  if (path === "/api/state") {
485
1126
  json(response, 200, engine.snapshot());
486
1127
  return;
@@ -588,13 +1229,36 @@ export function createHandler(engine, options) {
588
1229
  return;
589
1230
  }
590
1231
  watch(request, response, "media", engine.snapshot().tracks[index]?.title ?? file);
591
- sendFile(request, response, file);
1232
+ // A browser asks for every track here, and a matroska or an avi handed
1233
+ // to it raw is bytes it cannot play. Seeking is what this route is for
1234
+ // and transcoding gives it up, but an unseekable film beats a silent
1235
+ // one -- and the seekable formats are untouched.
1236
+ if (playsInBrowser(file))
1237
+ sendFile(request, response, file);
1238
+ else
1239
+ transcode(request, response, file, options.ffmpeg ?? ["ffmpeg"]);
592
1240
  return;
593
1241
  }
594
1242
  // Whatever the source is, this comes back as MP3 a browser will play:
595
1243
  // a flac, a wma, a URL, an HLS stream. ffmpeg reads them all and we hand
596
1244
  // the bytes on as they arrive, so a live stream starts immediately rather
597
1245
  // than after it ends, which for a live stream is never.
1246
+ // One address that keeps playing, for a listener that cannot ask for the
1247
+ // next track: the phone line hands exactly this to Telnyx.
1248
+ if (path === "/api/live") {
1249
+ if (!options.media) {
1250
+ json(response, 403, { error: "media streaming is off" });
1251
+ return;
1252
+ }
1253
+ const current = engine.snapshot();
1254
+ if (current.tracks.length === 0) {
1255
+ json(response, 404, { error: "nothing is playing" });
1256
+ return;
1257
+ }
1258
+ watch(request, response, "stream", current.tracks[current.index]?.title ?? "live");
1259
+ liveAudio(request, response, engine, options.ffmpeg ?? ["ffmpeg"]);
1260
+ return;
1261
+ }
598
1262
  if (path.startsWith("/api/stream/")) {
599
1263
  const index = Number(path.slice("/api/stream/".length));
600
1264
  const source = Number.isInteger(index) ? engine.trackPath(index) : undefined;
@@ -645,6 +1309,127 @@ function readIfPossible(path) {
645
1309
  return null;
646
1310
  }
647
1311
  }
1312
+ /** How long to wait before looking again when the player has not moved on. */
1313
+ const LIVE_GAP_MS = 500;
1314
+ /** How long to wait when there is nothing to play at all yet. */
1315
+ const LIVE_IDLE_MS = 2000;
1316
+ /**
1317
+ * Whatever is playing, as one endless MP3.
1318
+ *
1319
+ * /api/stream/N is one track: it needs an index, and it stops at the end of
1320
+ * the song. That is right for a browser, which knows what is playing and can
1321
+ * ask for the next one. It is wrong for everything that cannot -- a telephone
1322
+ * call, `curl | mpv`, anything handed a single address and expected to keep
1323
+ * hearing sound. Those need one URL that never ends and never needs asking
1324
+ * again, which is what a listener means by "the stream".
1325
+ *
1326
+ * So this follows the player rather than an index: transcode what is playing,
1327
+ * and when that track ends look at what is playing now and keep writing into
1328
+ * the same response. The listener sees one continuous audio/mpeg body.
1329
+ *
1330
+ * Read at native rate (-re), unlike /api/stream/N which is free to run ahead
1331
+ * into a browser's buffer. Here running ahead would finish the song in two
1332
+ * seconds and then sit waiting for the player to catch up, so the thing that
1333
+ * decides what plays next would be minutes behind what the listener hears.
1334
+ */
1335
+ function liveAudio(request, response, engine, ffmpeg) {
1336
+ const [command, ...prefix] = ffmpeg;
1337
+ let child = null;
1338
+ let waiting = null;
1339
+ let closed = false;
1340
+ let started = false;
1341
+ let playing = -1;
1342
+ // Held back until the first byte, for the reason transcode() holds it back:
1343
+ // a 200 with nothing behind it is indistinguishable from silence.
1344
+ const begin = () => {
1345
+ if (started || closed)
1346
+ return;
1347
+ started = true;
1348
+ response.writeHead(200, {
1349
+ ...CORS,
1350
+ "content-type": "audio/mpeg",
1351
+ "cache-control": "no-store",
1352
+ "transfer-encoding": "chunked",
1353
+ });
1354
+ };
1355
+ const later = (ms, run) => {
1356
+ if (waiting)
1357
+ clearTimeout(waiting);
1358
+ waiting = setTimeout(run, ms);
1359
+ waiting.unref?.();
1360
+ };
1361
+ const stop = () => {
1362
+ if (closed)
1363
+ return;
1364
+ closed = true;
1365
+ if (waiting)
1366
+ clearTimeout(waiting);
1367
+ waiting = null;
1368
+ unsubscribe();
1369
+ child?.kill("SIGKILL");
1370
+ child = null;
1371
+ if (!response.writableEnded)
1372
+ response.end();
1373
+ };
1374
+ const next = () => {
1375
+ if (closed || child !== null)
1376
+ return;
1377
+ if (waiting) {
1378
+ clearTimeout(waiting);
1379
+ waiting = null;
1380
+ }
1381
+ const snapshot = engine.snapshot();
1382
+ const source = engine.trackPath(snapshot.index);
1383
+ if (source === undefined) {
1384
+ // A playlist that was replaced out from under us, or one that is empty
1385
+ // for the moment. Keep the connection and keep looking.
1386
+ later(LIVE_IDLE_MS, next);
1387
+ return;
1388
+ }
1389
+ playing = snapshot.index;
1390
+ const spawned = spawn(command, [
1391
+ ...prefix,
1392
+ "-hide_banner",
1393
+ "-loglevel", "error",
1394
+ ...(isRemote(source) ? ["-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5"] : []),
1395
+ "-re",
1396
+ "-i", source,
1397
+ "-vn",
1398
+ "-f", "mp3",
1399
+ "-b:a", "192k",
1400
+ "-",
1401
+ ], { stdio: ["ignore", "pipe", "pipe"] });
1402
+ child = spawned;
1403
+ spawned.stdout.once("data", begin);
1404
+ spawned.stdout.on("error", () => spawned.kill("SIGKILL"));
1405
+ // end: false, because the response outlives this track. Ending it here is
1406
+ // exactly the bug this endpoint exists to avoid.
1407
+ spawned.stdout.pipe(response, { end: false });
1408
+ spawned.stderr.resume();
1409
+ spawned.on("error", stop);
1410
+ spawned.on("close", () => {
1411
+ if (child !== spawned)
1412
+ return;
1413
+ child = null;
1414
+ if (closed)
1415
+ return;
1416
+ // Follow the player if it has already moved on. If it has not, look
1417
+ // again shortly -- which is also what makes a single-track library
1418
+ // repeat rather than fall silent.
1419
+ later(engine.snapshot().index === playing ? LIVE_GAP_MS : 0, next);
1420
+ });
1421
+ };
1422
+ // A track change that lands while we are between songs is the signal to go
1423
+ // now rather than wait out the poll.
1424
+ const unsubscribe = engine.subscribe(() => {
1425
+ if (child === null && !closed && engine.snapshot().index !== playing)
1426
+ next();
1427
+ });
1428
+ response.on("close", stop);
1429
+ response.on("error", stop);
1430
+ request.on("close", stop);
1431
+ next();
1432
+ }
648
1433
  /**
649
1434
  * Decode anything and hand back MP3, as it is produced.
650
1435
  *
@@ -789,13 +1574,219 @@ export async function serve(argv, version = "0.1.0") {
789
1574
  : new EmptyEngine(`No audio files under ${root}.`);
790
1575
  const web = options.web !== null ? resolve(options.web) : defaultWebDir();
791
1576
  const key = options.key ? newKey() : null;
1577
+ // Minted whether or not it is published, so `nixamp admin` and the operator
1578
+ // both have a link they can hand out without handing over the controls.
1579
+ const listenKey = key === null ? null : newKey();
1580
+ // Configuration can arrive from the directory later, so it is a box the
1581
+ // paywall reads rather than a value it was handed once.
1582
+ let paywallConfig = { ...paywallFromEnv(), enabled: options.x402 || paywallFromEnv().enabled };
1583
+ const connections = new Connections();
1584
+ const paywall = createPaywall({
1585
+ config: () => paywallConfig,
1586
+ liveListeners: () => connections.listening,
1587
+ // The address a payer can actually reach: the public one where there is
1588
+ // one, since a quote pointing at 192.168.1.5 is one they cannot pay from.
1589
+ siteUrl: () => {
1590
+ const bound = server.address();
1591
+ const live = typeof bound === "object" && bound !== null ? bound.port : options.port;
1592
+ const reachable = reachableAddresses(options.host, live);
1593
+ return (reachable.find((a) => a.label === "on the internet") ?? reachable[0])?.url
1594
+ ?? `http://127.0.0.1:${live}`;
1595
+ },
1596
+ // The operator drives with the control key, and is not a customer.
1597
+ exempt: (request) => key !== null && scopeOf(keyFrom(request, new URL(request.url ?? "/", "http://localhost")), key, null) === "control",
1598
+ });
1599
+ const channels = new Channels({
1600
+ ffmpeg: tools.ffmpeg,
1601
+ onStart: (info) => console.log(` ${info.name} is publishing to "${info.id}" (${info.format} over ${info.via}).`),
1602
+ onEnd: (info) => console.log(` "${info.id}" stopped.`),
1603
+ });
1604
+ const destinations = parseDestinations(options.rtmp);
1605
+ const broadcaster = new Broadcaster(tools.ffmpeg);
1606
+ const ingest = options.ingest
1607
+ ? new Ingest({
1608
+ ffmpeg: tools.ffmpeg,
1609
+ sink: "pipe:1",
1610
+ onStart: (session) => console.log(` ${session.name} started streaming in (${session.format}).`),
1611
+ onEnd: (session, error) => console.log(` ${session.name} stopped streaming in${error ? `: ${error}` : ""}.`),
1612
+ })
1613
+ : undefined;
1614
+ // The account signed in on this machine owns the server it starts. That is
1615
+ // the whole claim: `nixamp login` then `nixamp serve`, and the phone in your
1616
+ // pocket can administer it from anywhere by signing in as the same person.
1617
+ // Following outlives every stream, so unlike the rest of this it wants a
1618
+ // database. Only where there is one: a nixamp on a laptop has no followers.
1619
+ const pool = options.directory && process.env["DATABASE_URL"]
1620
+ ? new pg.Pool({ connectionString: process.env["DATABASE_URL"] })
1621
+ : undefined;
1622
+ const follows = pool ? new Follows(pool) : undefined;
1623
+ // The two things that were promises kept only in memory: a caller who was
1624
+ // told they would be texted, and the ended stream a code still points at.
1625
+ const durable = pool ? new Durable(pool, (message) => console.log(message)) : undefined;
1626
+ const vapidPublicKey = process.env["VAPID_PUBLIC_KEY"] ?? "";
1627
+ const vapidPrivateKey = process.env["VAPID_PRIVATE_KEY"] ?? "";
1628
+ /**
1629
+ * Tell a broadcaster's followers, on whatever they asked to be told on.
1630
+ *
1631
+ * Fired from the directory on the transition to live rather than on every
1632
+ * heartbeat, and awaited by nobody: a publisher's heartbeat should not sit
1633
+ * waiting on a push service.
1634
+ */
1635
+ const tellFollowers = (listing) => {
1636
+ if (follows === undefined || !listing.ownerId)
1637
+ return;
1638
+ const what = listing.nowPlaying ? ` Playing ${listing.nowPlaying}.` : "";
1639
+ const note = {
1640
+ title: `${listing.name} is live`,
1641
+ body: `${what} Listen at ${DEFAULT_DIRECTORY}/directory, or call ${CALL_IN_NUMBER} and key ${listing.code}.`.trim(),
1642
+ url: listing.url,
1643
+ };
1644
+ void follows
1645
+ .audience(listing.ownerId)
1646
+ .then((audience) => notifyAll(audience, note, {
1647
+ ...(process.env["RESEND_API_KEY"]
1648
+ ? {
1649
+ email: resendEmail({
1650
+ apiKey: process.env["RESEND_API_KEY"],
1651
+ from: process.env["NIXAMP_MAIL_FROM"] ?? "nixamp <notifications@nixamp.com>",
1652
+ onEvent: (message) => console.log(message),
1653
+ }),
1654
+ }
1655
+ : {}),
1656
+ ...(process.env["TELNYX_API_KEY"] && process.env["PARTYLINE_SMS_FROM"]
1657
+ ? {
1658
+ sms: telnyxSms({
1659
+ apiKey: process.env["TELNYX_API_KEY"],
1660
+ from: process.env["PARTYLINE_SMS_FROM"],
1661
+ onEvent: (message) => console.log(message),
1662
+ }),
1663
+ }
1664
+ : {}),
1665
+ ...(vapidPublicKey && vapidPrivateKey
1666
+ ? {
1667
+ push: webPush({
1668
+ publicKey: vapidPublicKey,
1669
+ privateKey: vapidPrivateKey,
1670
+ subject: process.env["NIXAMP_SITE"] ?? DEFAULT_DIRECTORY,
1671
+ onEvent: (message) => console.log(message),
1672
+ }),
1673
+ }
1674
+ : {}),
1675
+ // A subscription the vendor has retired is a row to delete, not a
1676
+ // failure to retry.
1677
+ onGone: (endpoint) => follows.removePush(endpoint),
1678
+ onEvent: (message) => console.log(message),
1679
+ }))
1680
+ .catch(() => { });
1681
+ };
1682
+ // Hoisted rather than built inline, because the party line needs the same
1683
+ // instance: a second Directory would be a second set of stream codes, and
1684
+ // the one the phone looked in would never be the one the publishers reach.
1685
+ const directory = options.directory
1686
+ ? new Directory(undefined, undefined, undefined, tellFollowers)
1687
+ : undefined;
1688
+ if (directory && durable) {
1689
+ // Echoed rather than awaited: the directory answers from memory, so a
1690
+ // database that is briefly unreachable should cost the durability and not
1691
+ // the request.
1692
+ directory.persistTo({
1693
+ save: (item) => void durable.saveEnded(item),
1694
+ drop: (id) => void durable.dropEnded(id),
1695
+ });
1696
+ // And put back what the last process knew, without holding up the listen.
1697
+ void durable
1698
+ .loadEnded(Date.now() - ENDED_TTL_MS)
1699
+ .then((items) => {
1700
+ if (items.length > 0)
1701
+ console.log(` remembered ${items.length} stream(s) that had ended.`);
1702
+ directory.seedEnded(items);
1703
+ })
1704
+ .catch(() => { });
1705
+ void durable.sweep(Date.now() - ENDED_TTL_MS, new Date(Date.now() - 30 * 24 * 60 * 60 * 1000));
1706
+ }
1707
+ const session = readSession();
1708
+ const owner = new Owner({
1709
+ ownerId: options.owner || (session?.token ? await ownerIdOf(session) : ""),
1710
+ site: session?.site ?? DEFAULT_DIRECTORY,
1711
+ });
1712
+ // The party line answers a phone number, and there is only one number. Both
1713
+ // keys or neither: without the public key every webhook would be refused,
1714
+ // which is a worse failure than not offering the endpoint.
1715
+ const partyLine = options.directory && process.env["TELNYX_API_KEY"] && process.env["TELNYX_PUBLIC_KEY"]
1716
+ ? new PartyLine({
1717
+ apiKey: process.env["TELNYX_API_KEY"],
1718
+ publicKey: process.env["TELNYX_PUBLIC_KEY"],
1719
+ streams: directory,
1720
+ callIn: CALL_IN_NUMBER,
1721
+ // Only when a sending number is configured. Without one the line
1722
+ // still answers and still says when the stream ended; it just does
1723
+ // not offer a text it could not send.
1724
+ ...(process.env["PARTYLINE_SMS_FROM"]
1725
+ ? {
1726
+ sms: telnyxSms({
1727
+ apiKey: process.env["TELNYX_API_KEY"],
1728
+ from: process.env["PARTYLINE_SMS_FROM"],
1729
+ onEvent: (message) => console.log(message),
1730
+ }),
1731
+ }
1732
+ : {}),
1733
+ ...(process.env["PARTYLINE_GREETING"] ? { greeting: process.env["PARTYLINE_GREETING"] } : {}),
1734
+ ...(process.env["PARTYLINE_VOICE"] ? { voice: process.env["PARTYLINE_VOICE"] } : {}),
1735
+ onEvent: (message) => console.log(message),
1736
+ })
1737
+ : undefined;
1738
+ if (partyLine && durable) {
1739
+ // Put back everybody a previous process promised to text, then keep
1740
+ // echoing. Seeding first means a stream that goes live during startup
1741
+ // still finds them.
1742
+ void durable
1743
+ .loadReminders()
1744
+ .then((waiting) => {
1745
+ const owed = [...waiting.values()].reduce((n, set) => n + set.size, 0);
1746
+ if (owed > 0)
1747
+ console.log(` ${owed} caller(s) are still owed a text.`);
1748
+ partyLine.persistRemindersTo({
1749
+ add: (code, phone) => void durable.addReminder(code, phone),
1750
+ take: (code) => durable.takeReminders(code),
1751
+ }, waiting);
1752
+ })
1753
+ .catch(() => {
1754
+ // Still worth echoing new ones even if the old list could not be read.
1755
+ partyLine.persistRemindersTo({
1756
+ add: (code, phone) => void durable.addReminder(code, phone),
1757
+ take: (code) => durable.takeReminders(code),
1758
+ });
1759
+ });
1760
+ }
792
1761
  const server = createServer(engine, {
793
1762
  web,
794
1763
  media: options.media,
1764
+ owner,
1765
+ channels,
1766
+ ...(ingest ? { ingest } : {}),
1767
+ broadcaster,
1768
+ broadcast: () => ({ destinations, settings: DEFAULT_ENCODER }),
795
1769
  version,
796
1770
  key,
1771
+ listenKey,
1772
+ connections,
1773
+ paywall,
797
1774
  ffmpeg: tools.ffmpeg,
798
1775
  load: (next) => loadSource(tools, next),
1776
+ ...(directory ? { directory } : {}),
1777
+ ...(follows ? { follows, vapidPublicKey } : {}),
1778
+ ...(partyLine ? { partyLine } : {}),
1779
+ // Accounts live where the directory lives, and only there: a nixamp on a
1780
+ // laptop has nobody to be an account of.
1781
+ ...(options.directory && process.env["DATABASE_URL"]
1782
+ ? {
1783
+ accounts: new Accounts({
1784
+ connectionString: process.env["DATABASE_URL"],
1785
+ secret: process.env["NIXAMP_JWT_SECRET"] ?? "",
1786
+ }),
1787
+ secureCookies: (process.env["NIXAMP_SITE"] ?? "").startsWith("https://"),
1788
+ }
1789
+ : {}),
799
1790
  });
800
1791
  // A port already in use is the most ordinary failure there is, and it
801
1792
  // arrives as an unhandled 'error' event that takes the process down with a
@@ -838,6 +1829,15 @@ export async function serve(argv, version = "0.1.0") {
838
1829
  else {
839
1830
  console.log(" Open that link once on a phone or a laptop and it stays signed in.");
840
1831
  console.log(` Anything without the key gets a 401. Key: ${key}`);
1832
+ if (listenKey !== null) {
1833
+ console.log("");
1834
+ console.log(" A listen-only link, for someone you want to hear it but not drive it:");
1835
+ for (const { label, url } of addresses) {
1836
+ if (label === "here")
1837
+ continue;
1838
+ console.log(` ${shareLink(url, listenKey)}`);
1839
+ }
1840
+ }
841
1841
  }
842
1842
  if (addresses.some((a) => a.label === "on the internet")) {
843
1843
  console.log("");
@@ -847,6 +1847,31 @@ export async function serve(argv, version = "0.1.0") {
847
1847
  }
848
1848
  if (!options.media)
849
1849
  console.log(" Audio stays on this machine: --no-media is set.");
1850
+ if (owner.claimed) {
1851
+ console.log(` ${session?.email} can administer this from anywhere, signed in at ${session?.site}.`);
1852
+ }
1853
+ if (options.ingest)
1854
+ console.log(" Accepting a live stream in at POST /api/ingest.");
1855
+ let rtmp = null;
1856
+ if (options.rtmpIn > 0) {
1857
+ const publish = addresses.find((a) => a.label !== "here") ?? addresses[0];
1858
+ const host = publish ? new URL(publish.url).hostname : "127.0.0.1";
1859
+ // One listener per stream, because ffmpeg's RTMP listener serves a single
1860
+ // connection per process. Three devices going live at once is three ports.
1861
+ const slots = Array.from({ length: options.rtmpStreams }, (_, i) => ({
1862
+ port: options.rtmpIn + i,
1863
+ id: i === 0 ? "live" : `live-${i + 1}`,
1864
+ }));
1865
+ rtmp = new RtmpListeners(channels, tools.ffmpeg, listenKey ?? "live");
1866
+ rtmp.listen(slots);
1867
+ console.log(" Or publish from OBS, Larix or ffmpeg, one per URL:");
1868
+ for (const slot of slots) {
1869
+ console.log(` rtmp://${host}:${slot.port}/live/${listenKey ?? "live"} -> "${slot.id}"`);
1870
+ }
1871
+ }
1872
+ if (destinations.length > 0) {
1873
+ console.log(` Ready to broadcast to ${destinations.map((d) => d.name).join(", ")}.`);
1874
+ }
850
1875
  if (web === null)
851
1876
  console.log(" No built PWA found, so / has nothing to serve: run `bun run web:build`.");
852
1877
  // Listening on every interface proves the socket is open here and nothing
@@ -889,7 +1914,68 @@ export async function serve(argv, version = "0.1.0") {
889
1914
  }
890
1915
  }
891
1916
  }
1917
+ // The listing carries the listen link, and only ever a public address: an
1918
+ // entry pointing at 192.168.1.5 is one nobody outside that house can open.
1919
+ const publishable_ = addresses.find((a) => a.label === "on the internet")
1920
+ ?? addresses.find((a) => a.label === "on tailscale");
1921
+ let publisher = null;
1922
+ if (options.publish !== "no" && publishable_) {
1923
+ const listen = shareLink(publishable_.url, listenKey);
1924
+ // Announced next to the listen link, not instead of it: one is for a person
1925
+ // with a browser, the other for the phone line and anything else that is
1926
+ // handed one address and expected to play it.
1927
+ const audio = audioLink(publishable_.url, listenKey);
1928
+ const wanted = options.publish === "yes"
1929
+ ? true
1930
+ : await confirm(`\n List this stream at ${DEFAULT_DIRECTORY}/directory so anyone can find it?\n It publishes ${listen} — listen only, not the controls.`);
1931
+ if (wanted) {
1932
+ publisher = new Publisher({
1933
+ directory: DEFAULT_DIRECTORY,
1934
+ name: options.name || hostname(),
1935
+ url: listen,
1936
+ audio,
1937
+ tracks: tracks.length,
1938
+ // From `nixamp login`. The directory will not list a stream it cannot
1939
+ // attribute to somebody, because a listing is now a phone code that
1940
+ // costs money to answer.
1941
+ ...(session?.token ? { token: session.token } : {}),
1942
+ onRefused: () => {
1943
+ console.log("");
1944
+ console.log(" nixamp.com would not list this stream: it needs an account.");
1945
+ console.log(" Run `nixamp login` (or `nixamp signup`) and start again.");
1946
+ },
1947
+ nowPlaying: () => {
1948
+ const snapshot = engine.snapshot();
1949
+ return snapshot.tracks[snapshot.index]?.title ?? "";
1950
+ },
1951
+ onConfig: (remote) => {
1952
+ const next = applyRemoteConfig(paywallConfig, remote?.x402);
1953
+ if (JSON.stringify(next) === JSON.stringify(paywallConfig))
1954
+ return;
1955
+ paywallConfig = next;
1956
+ console.log(next.enabled
1957
+ ? ` nixamp.com turned paid listening on: $${(next.priceCents / 100).toFixed(2)} for ${next.passMinutes} minutes, over ${FREE_LISTENERS} listeners.`
1958
+ : " nixamp.com turned paid listening off.");
1959
+ },
1960
+ });
1961
+ const listing = await publisher.start();
1962
+ console.log("");
1963
+ console.log(listing
1964
+ ? ` Listed at ${DEFAULT_DIRECTORY}/directory as "${listing.name}". It leaves the list when this stops.`
1965
+ : ` Could not reach ${DEFAULT_DIRECTORY}; not listed.`);
1966
+ }
1967
+ }
1968
+ else if (options.publish === "yes" && !publishable_) {
1969
+ console.log("");
1970
+ console.log(" --publish needs an address the world can reach. This machine has none.");
1971
+ }
892
1972
  const shutdown = () => {
1973
+ rtmp?.stop();
1974
+ channels.stopAll();
1975
+ ingest?.stopRtmp();
1976
+ ingest?.close();
1977
+ broadcaster.stop();
1978
+ void publisher?.stop();
893
1979
  closePort?.();
894
1980
  engine.stop();
895
1981
  server.close(() => process.exit(0));
@@ -899,12 +1985,72 @@ export async function serve(argv, version = "0.1.0") {
899
1985
  process.on("SIGINT", shutdown);
900
1986
  process.on("SIGTERM", shutdown);
901
1987
  }
1988
+ /**
1989
+ * `--rtmp youtube=<key>` or `--rtmp name=rtmp://host/app/key`.
1990
+ *
1991
+ * A key is a password, so it is taken from the command line or the environment
1992
+ * and never from a request: a client that could name its own destination could
1993
+ * point your broadcast at itself.
1994
+ */
1995
+ export function parseDestinations(specs) {
1996
+ const out = [];
1997
+ for (const [index, spec] of specs.entries()) {
1998
+ const at = spec.indexOf("=");
1999
+ if (at <= 0)
2000
+ continue;
2001
+ const name = spec.slice(0, at).trim();
2002
+ const rest = spec.slice(at + 1).trim();
2003
+ if (!name || !rest)
2004
+ continue;
2005
+ const preset = PRESETS[name.toLowerCase()];
2006
+ if (preset && !/^rtmps?:\/\//i.test(rest)) {
2007
+ out.push({ id: String(index + 1), name, url: preset, key: rest, enabled: true });
2008
+ continue;
2009
+ }
2010
+ if (!/^rtmps?:\/\//i.test(rest))
2011
+ continue;
2012
+ // A full URL: the last path segment is the key.
2013
+ const cut = rest.lastIndexOf("/");
2014
+ if (cut <= "rtmp://".length)
2015
+ continue;
2016
+ out.push({
2017
+ id: String(index + 1),
2018
+ name,
2019
+ url: rest.slice(0, cut),
2020
+ key: rest.slice(cut + 1),
2021
+ enabled: true,
2022
+ });
2023
+ }
2024
+ return out;
2025
+ }
2026
+ /**
2027
+ * Which account the signed-in session belongs to. Asked once at startup rather
2028
+ * than trusted from the file: a token that nixamp.com no longer accepts should
2029
+ * not confer ownership of anything.
2030
+ */
2031
+ async function ownerIdOf(session) {
2032
+ try {
2033
+ const answer = await fetch(`${session.site}/api/v1/auth/me`, {
2034
+ headers: { authorization: `Bearer ${session.token}` },
2035
+ });
2036
+ if (!answer.ok)
2037
+ return "";
2038
+ const body = (await answer.json());
2039
+ return typeof body.account?.id === "string" ? body.account.id : "";
2040
+ }
2041
+ catch {
2042
+ // Offline at startup means no remote administration until a restart, and
2043
+ // the control key still works. Better than claiming an owner we cannot
2044
+ // check.
2045
+ return "";
2046
+ }
2047
+ }
902
2048
  /** The built PWA, when it is sitting next to us in the same install. */
903
2049
  function defaultWebDir() {
904
2050
  const fromEnv = process.env.NIXAMP_WEB_DIR;
905
2051
  if (fromEnv && isFile(join(fromEnv, "index.html")))
906
2052
  return fromEnv;
907
- const here = new URL(".", import.meta.url).pathname;
2053
+ const here = fileURLToPath(new URL(".", import.meta.url));
908
2054
  for (const guess of [
909
2055
  join(here, "..", "web", "dist"),
910
2056
  join(here, "..", "..", "web", "dist"),