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/src/paywall.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Paying to listen, once a stream is busy.
3
+ *
4
+ * A nixamp serving a handful of friends should cost nothing and ask nothing.
5
+ * Past that it is bandwidth someone is paying for, so the gate opens: over the
6
+ * free listener count, a new listener is answered 402 with an x402 offer and a
7
+ * dollar buys a day.
8
+ *
9
+ * Three things are deliberate. The count is of *live* listeners, so a stream
10
+ * quietens back to free on its own. Only the audio is gated, because a 402 on
11
+ * /api/state would break the page that has to render the offer. And nobody is
12
+ * ever cut off mid-track: the gate is asked once, when a request arrives, and
13
+ * a listener who got in stays in.
14
+ */
15
+ import { createGateway } from "@profullstack/x402-gateway";
16
+ import type { IncomingMessage, ServerResponse } from "node:http";
17
+
18
+ /** Listeners who get in for nothing. The sixth is the one who pays. */
19
+ export const FREE_LISTENERS = 5;
20
+
21
+ export interface PaywallConfig {
22
+ enabled: boolean;
23
+ /** EVM address that receives the USDC. Without one there is nothing to pay to. */
24
+ payTo: string;
25
+ /** A scoped CoinPay key with payments:create. */
26
+ coinpayKey: string;
27
+ priceCents: number;
28
+ /** What one price buys. 1440 is a day. */
29
+ passMinutes: number;
30
+ }
31
+
32
+ export const DEFAULT_PAYWALL: PaywallConfig = {
33
+ enabled: false,
34
+ payTo: "",
35
+ coinpayKey: "",
36
+ priceCents: 100,
37
+ passMinutes: 1440,
38
+ };
39
+
40
+ /** Only the audio is behind the gate. */
41
+ export const GATED = ["/api/stream/", "/api/media/", "/api/live"];
42
+
43
+ export function isGated(path: string): boolean {
44
+ return GATED.some((prefix) => path.startsWith(prefix));
45
+ }
46
+
47
+ /**
48
+ * Whether this request should be charged at all. Configuration first, because
49
+ * a disabled paywall must never answer 402; then the path, then how busy the
50
+ * stream is.
51
+ */
52
+ export function shouldCharge(config: PaywallConfig, path: string, liveListeners: number): boolean {
53
+ if (!config.enabled || !config.payTo) return false;
54
+ if (!isGated(path)) return false;
55
+ return liveListeners > FREE_LISTENERS;
56
+ }
57
+
58
+ export interface PaywallOptions {
59
+ config: () => PaywallConfig;
60
+ /** How many listeners are on the audio routes right now. */
61
+ liveListeners: () => number;
62
+ /**
63
+ * The origin a payer is quoted, which has to be one they can reach. A
64
+ * function because the port is not known until the socket is bound.
65
+ */
66
+ siteUrl: () => string;
67
+ /** True for the operator's own browser, which never pays to hear its own music. */
68
+ exempt: (request: IncomingMessage) => boolean;
69
+ }
70
+
71
+ /**
72
+ * A node http shim over the gateway's Fetch-API handler. Returns true when it
73
+ * answered the request, so the server's own routing can stop.
74
+ */
75
+ export function createPaywall(options: PaywallOptions) {
76
+ let built: { key: string; handle: (request: Request) => Promise<Response | null> } | null = null;
77
+
78
+ /** Rebuilt when the configuration changes, because it can change at runtime. */
79
+ const gateway = (config: PaywallConfig, siteUrl: string) => {
80
+ const key = `${siteUrl} ${JSON.stringify(config)}`;
81
+ if (built?.key === key) return built.handle;
82
+ const gate = createGateway({
83
+ siteUrl,
84
+ siteName: "nixamp",
85
+ payTo: config.payTo,
86
+ priceCents: config.priceCents,
87
+ passMinutes: config.passMinutes,
88
+ coinpay: { apiKey: config.coinpayKey },
89
+ header: "x-nixamp-pass",
90
+ path: "/listen/pay",
91
+ // Whether to charge is about how busy this stream is, not about who is
92
+ // asking, so the agent lists play no part.
93
+ isPaidAgent: () => true,
94
+ benefits: ["Listen to this stream for a day, as many tracks as you like."],
95
+ });
96
+ built = { key, handle: (request) => gate.handle(request) };
97
+ return built.handle;
98
+ };
99
+
100
+ return async function paywall(
101
+ request: IncomingMessage,
102
+ response: ServerResponse,
103
+ path: string,
104
+ ): Promise<boolean> {
105
+ const config = options.config();
106
+ // The sales page answers whenever the paywall is configured, so a listener
107
+ // can buy a pass before the stream is busy enough to need one.
108
+ const selling = config.enabled && config.payTo !== "" && path.startsWith("/listen/pay");
109
+ if (!selling && !shouldCharge(config, path, options.liveListeners())) return false;
110
+ if (options.exempt(request)) return false;
111
+
112
+ const siteUrl = options.siteUrl();
113
+ const answer = await gateway(config, siteUrl)(toRequest(request, siteUrl));
114
+ if (answer === null) return false;
115
+
116
+ const body = await rewrite(answer, siteUrl);
117
+ response.writeHead(answer.status, {
118
+ ...Object.fromEntries(answer.headers),
119
+ "content-length": String(body.byteLength),
120
+ });
121
+ response.end(body);
122
+ return true;
123
+ };
124
+ }
125
+
126
+ /**
127
+ * The gateway sells crawl access, and says so: its 402 tells the caller that
128
+ * "payment is required for training crawlers". Someone trying to hear a song
129
+ * is not a crawler, so the sentence is replaced on the way out. The offer
130
+ * itself is untouched -- only the words are ours.
131
+ */
132
+ export async function rewrite(answer: Response, siteUrl: string): Promise<Buffer> {
133
+ const raw = Buffer.from(await answer.arrayBuffer());
134
+ if (answer.status !== 402 || !(answer.headers.get("content-type") ?? "").includes("json")) return raw;
135
+
136
+ try {
137
+ const parsed = JSON.parse(raw.toString("utf8")) as Record<string, unknown>;
138
+ parsed["error"] =
139
+ `This stream has more than ${FREE_LISTENERS} people listening. ` +
140
+ `A pass is ${(parsed as { pass?: { price?: string } }).pass?.price ?? "$1"} for a day: ${siteUrl}/listen/pay`;
141
+ return Buffer.from(JSON.stringify(parsed));
142
+ } catch {
143
+ // Not JSON after all: send exactly what the gateway produced.
144
+ return raw;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Enough of a Fetch Request for the gateway: it reads the URL, the method and
150
+ * headers. A body would need streaming, and nothing it gates has one.
151
+ */
152
+ export function toRequest(request: IncomingMessage, siteUrl: string): Request {
153
+ const headers = new Headers();
154
+ for (const [name, value] of Object.entries(request.headers)) {
155
+ if (value === undefined) continue;
156
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
157
+ }
158
+ return new Request(new URL(request.url ?? "/", siteUrl), {
159
+ method: request.method ?? "GET",
160
+ headers,
161
+ });
162
+ }
163
+
164
+ /** Read a paywall out of the environment, for an operator who runs one by hand. */
165
+ export function paywallFromEnv(env: NodeJS.ProcessEnv = process.env): PaywallConfig {
166
+ const price = Number(env["NIXAMP_PRICE_CENTS"]);
167
+ const minutes = Number(env["NIXAMP_PASS_MINUTES"]);
168
+ return {
169
+ enabled: env["NIXAMP_X402"] === "1",
170
+ payTo: env["NIXAMP_PAY_TO"] ?? "",
171
+ coinpayKey: env["COINPAY_X402_KEY"] ?? "",
172
+ priceCents: Number.isFinite(price) && price > 0 ? Math.floor(price) : DEFAULT_PAYWALL.priceCents,
173
+ passMinutes:
174
+ Number.isFinite(minutes) && minutes > 0 ? Math.floor(minutes) : DEFAULT_PAYWALL.passMinutes,
175
+ };
176
+ }
177
+
178
+ /**
179
+ * The directory's answer may carry a configuration, which is how a server is
180
+ * turned on and off from nixamp.com. Anything missing keeps what it had, and
181
+ * a payTo the operator did not set is never invented here.
182
+ */
183
+ export function applyRemoteConfig(current: PaywallConfig, remote: unknown): PaywallConfig {
184
+ if (typeof remote !== "object" || remote === null) return current;
185
+ const record = remote as Record<string, unknown>;
186
+ const price = Number(record["priceCents"]);
187
+ const minutes = Number(record["passMinutes"]);
188
+ return {
189
+ enabled: typeof record["enabled"] === "boolean" ? record["enabled"] : current.enabled,
190
+ payTo: typeof record["payTo"] === "string" && record["payTo"] ? record["payTo"] : current.payTo,
191
+ coinpayKey:
192
+ typeof record["coinpayKey"] === "string" && record["coinpayKey"]
193
+ ? record["coinpayKey"]
194
+ : current.coinpayKey,
195
+ priceCents: Number.isFinite(price) && price > 0 ? Math.floor(price) : current.priceCents,
196
+ passMinutes: Number.isFinite(minutes) && minutes > 0 ? Math.floor(minutes) : current.passMinutes,
197
+ };
198
+ }
package/src/playlist.ts CHANGED
@@ -15,6 +15,11 @@ import {
15
15
  export const AUDIO_EXTENSIONS = new Set([
16
16
  ".mp3", ".flac", ".ogg", ".oga", ".opus", ".m4a", ".aac",
17
17
  ".wav", ".wma", ".aiff", ".aif", ".alac", ".mp4", ".webm",
18
+ // Video containers, for their audio. Everything on the way out of here is
19
+ // already decoded by ffmpeg and re-encoded to MP3 with -vn, so a film is a
20
+ // long track with a picture nobody asked for -- and a library of them was
21
+ // invisible to nixamp for want of the extension being on this list.
22
+ ".mkv", ".avi", ".mov", ".m4v", ".mpg", ".mpeg", ".wmv", ".flv",
18
23
  ]);
19
24
 
20
25
  export function isAudio(path: string): boolean {
package/src/publish.ts ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Publishing to the directory, and asking first.
3
+ *
4
+ * Listing a stream tells the world an address it can reach you on, so it is
5
+ * never done silently. The prompt defaults to yes; a terminal that cannot ask
6
+ * defaults to no, because "there was nobody to ask" is not consent.
7
+ */
8
+ import { createInterface } from "node:readline/promises";
9
+ import { DEFAULT_DIRECTORY, HEARTBEAT_MS, type Listing } from "./directory.ts";
10
+
11
+ export interface PublishTarget {
12
+ directory: string;
13
+ name: string;
14
+ /** The listen link: what a stranger opens. Never the control key. */
15
+ url: string;
16
+ /**
17
+ * The same stream as bytes, for a listener that cannot hold a cookie.
18
+ *
19
+ * The phone line plays this address into a call. The listen link cannot be
20
+ * played: it is a redirect that sets a cookie, and Telnyx fetching it once
21
+ * gets a 401 in JSON, which is a caller hearing nothing.
22
+ */
23
+ audio?: string;
24
+ tracks: number;
25
+ nowPlaying: () => string;
26
+ /**
27
+ * The account this stream belongs to, from `nixamp login`.
28
+ *
29
+ * The directory used to take anybody's word for a listing. It cannot any
30
+ * more: a listing now carries a phone code people dial and minutes somebody
31
+ * pays for, so it has to be attributable. Reading the directory is still
32
+ * open to everyone -- it is announcing that needs a name behind it.
33
+ */
34
+ token?: string;
35
+ /**
36
+ * Called with whatever configuration the directory sent back. This is how
37
+ * nixamp.com turns x402 on and off for a server without it restarting.
38
+ */
39
+ onConfig?: (config: unknown) => void;
40
+ /** Called when the directory refused us for want of an account. */
41
+ onRefused?: () => void;
42
+ }
43
+
44
+ /**
45
+ * Ask, with yes as the default. Returns false without asking when there is no
46
+ * terminal on the other end, which is the case for the daemon and for CI.
47
+ */
48
+ export async function confirm(question: string, tty = process.stdin.isTTY === true): Promise<boolean> {
49
+ if (!tty) return false;
50
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
51
+ try {
52
+ const answer = (await rl.question(`${question} [Y/n] `)).trim().toLowerCase();
53
+ return answer === "" || answer === "y" || answer === "yes";
54
+ } finally {
55
+ rl.close();
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Announce, then keep announcing. The directory forgets an entry that stops
61
+ * renewing, so stopping the heartbeat is how a stream leaves the list even if
62
+ * the process dies without saying goodbye.
63
+ */
64
+ export class Publisher {
65
+ private id: string | null = null;
66
+ private timer: ReturnType<typeof setInterval> | null = null;
67
+ /** Whether we have already said that the directory wants an account. */
68
+ private refused = false;
69
+
70
+ constructor(
71
+ private readonly target: PublishTarget,
72
+ private readonly fetcher: typeof fetch = fetch,
73
+ ) {}
74
+
75
+ async start(): Promise<Listing | null> {
76
+ const first = await this.announce();
77
+ this.timer = setInterval(() => void this.announce(), HEARTBEAT_MS);
78
+ this.timer.unref?.();
79
+ return first;
80
+ }
81
+
82
+ async announce(): Promise<Listing | null> {
83
+ try {
84
+ const response = await this.fetcher(`${this.target.directory}/api/directory`, {
85
+ method: "POST",
86
+ headers: {
87
+ "content-type": "application/json",
88
+ ...(this.target.token ? { authorization: `Bearer ${this.target.token}` } : {}),
89
+ },
90
+ body: JSON.stringify({
91
+ ...(this.id ? { id: this.id } : {}),
92
+ name: this.target.name,
93
+ url: this.target.url,
94
+ ...(this.target.audio ? { audio: this.target.audio } : {}),
95
+ tracks: this.target.tracks,
96
+ nowPlaying: this.target.nowPlaying(),
97
+ }),
98
+ });
99
+ if (!response.ok) {
100
+ // Worth telling the operator about exactly once. A heartbeat that is
101
+ // refused every 90 seconds should not print every 90 seconds, and
102
+ // "could not reach the directory" would be the wrong thing to say
103
+ // about a directory that answered perfectly clearly.
104
+ if (response.status === 401 && !this.refused) {
105
+ this.refused = true;
106
+ this.target.onRefused?.();
107
+ }
108
+ return null;
109
+ }
110
+ const listing = (await response.json()) as Listing & { config?: unknown };
111
+ this.id = listing.id;
112
+ if (listing.config !== undefined) this.target.onConfig?.(listing.config);
113
+ return listing;
114
+ } catch {
115
+ // The directory being down is not a reason for a player to stop playing.
116
+ return null;
117
+ }
118
+ }
119
+
120
+ /** Leave the list now rather than waiting to be forgotten. */
121
+ async stop(): Promise<void> {
122
+ if (this.timer) clearInterval(this.timer);
123
+ this.timer = null;
124
+ if (this.id === null) return;
125
+ try {
126
+ await this.fetcher(`${this.target.directory}/api/directory?id=${encodeURIComponent(this.id)}`, {
127
+ method: "DELETE",
128
+ ...(this.target.token ? { headers: { authorization: `Bearer ${this.target.token}` } } : {}),
129
+ });
130
+ } catch {
131
+ // It expires on its own within the TTL, which is the point of the TTL.
132
+ }
133
+ this.id = null;
134
+ }
135
+ }
136
+
137
+ export { DEFAULT_DIRECTORY };
package/src/rtmp-in.ts ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * RTMP publishers, several at once.
3
+ *
4
+ * ffmpeg's RTMP listener serves one connection and exits, so N simultaneous
5
+ * publishers means N listeners on N ports. That is the honest cost of using
6
+ * ffmpeg as the RTMP server rather than implementing the protocol, and it buys
7
+ * a broadcaster that every phone and desktop app already speaks.
8
+ *
9
+ * Each listener decodes to MP3 itself, so its channel fans those bytes out
10
+ * without decoding them a second time.
11
+ */
12
+ import { spawn, type ChildProcess } from "node:child_process";
13
+ import type { Channels } from "./channels.ts";
14
+
15
+ export interface RtmpSlot {
16
+ port: number;
17
+ /** The channel a publisher on this port lands on. */
18
+ id: string;
19
+ }
20
+
21
+ /**
22
+ * Arm a listener per slot, and arm it again after each publisher leaves --
23
+ * otherwise a broadcaster who reconnects finds nothing listening.
24
+ */
25
+ export class RtmpListeners {
26
+ private readonly running = new Map<number, ChildProcess>();
27
+ private stopped = false;
28
+
29
+ constructor(
30
+ private readonly channels: Channels,
31
+ private readonly ffmpeg: string[],
32
+ private readonly key: string,
33
+ ) {}
34
+
35
+ listen(slots: RtmpSlot[]): void {
36
+ for (const slot of slots) this.arm(slot);
37
+ }
38
+
39
+ private arm(slot: RtmpSlot): void {
40
+ if (this.stopped || this.running.has(slot.port)) return;
41
+
42
+ const [command, ...prefix] = this.ffmpeg as [string, ...string[]];
43
+ const child = spawn(
44
+ command,
45
+ [
46
+ ...prefix,
47
+ "-hide_banner",
48
+ "-loglevel", "error",
49
+ "-rtmp_listen", "1",
50
+ // Wait indefinitely: a stream that starts tomorrow is still the stream.
51
+ "-timeout", "-1",
52
+ "-f", "flv",
53
+ "-i", `rtmp://0.0.0.0:${slot.port}/live/${this.key}`,
54
+ "-vn",
55
+ "-c:a", "libmp3lame",
56
+ "-b:a", "192k",
57
+ "-y",
58
+ "-f", "mp3",
59
+ "pipe:1",
60
+ ],
61
+ { stdio: ["ignore", "pipe", "pipe"] },
62
+ );
63
+ this.running.set(slot.port, child);
64
+
65
+ // The first bytes are the only honest signal that a publisher turned up:
66
+ // ffmpeg does not announce a connect, and a healthy stream says nothing at
67
+ // -loglevel error.
68
+ let channel: ReturnType<Channels["attach"]> = null;
69
+ child.stdout?.on("data", (chunk: Buffer) => {
70
+ channel ??= this.channels.attach(slot.id, "an RTMP publisher", "flv", "rtmp");
71
+ channel?.feed(chunk);
72
+ });
73
+ child.stdout?.on("error", () => child.kill("SIGKILL"));
74
+ child.on("error", () => this.done(slot, child, channel));
75
+ child.on("close", () => this.done(slot, child, channel));
76
+ }
77
+
78
+ private done(slot: RtmpSlot, child: ChildProcess, channel: { close(): void } | null): void {
79
+ if (this.running.get(slot.port) !== child) return;
80
+ this.running.delete(slot.port);
81
+ channel?.close();
82
+ if (!this.stopped) this.arm(slot);
83
+ }
84
+
85
+ stop(): void {
86
+ this.stopped = true;
87
+ for (const child of this.running.values()) child.kill("SIGKILL");
88
+ this.running.clear();
89
+ }
90
+ }