nixamp 0.7.41 → 0.9.3

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 (48) hide show
  1. package/dist/catalogs.d.ts +100 -0
  2. package/dist/catalogs.js +0 -0
  3. package/dist/certs.d.ts +112 -0
  4. package/dist/certs.js +217 -0
  5. package/dist/channels.d.ts +17 -0
  6. package/dist/channels.js +45 -0
  7. package/dist/directory.d.ts +10 -0
  8. package/dist/directory.js +6 -0
  9. package/dist/dns.d.ts +63 -0
  10. package/dist/dns.js +171 -0
  11. package/dist/library.d.ts +36 -0
  12. package/dist/library.js +167 -0
  13. package/dist/main.js +92 -4
  14. package/dist/names.d.ts +66 -0
  15. package/dist/names.js +184 -0
  16. package/dist/naming.d.ts +57 -0
  17. package/dist/naming.js +150 -0
  18. package/dist/owner.js +4 -0
  19. package/dist/publish.d.ts +2 -0
  20. package/dist/publish.js +3 -0
  21. package/dist/server.d.ts +37 -0
  22. package/dist/server.js +418 -5
  23. package/dist/session.d.ts +8 -0
  24. package/dist/session.js +103 -0
  25. package/package.json +8 -2
  26. package/src/catalogs.ts +0 -0
  27. package/src/certs.ts +294 -0
  28. package/src/channels.ts +41 -0
  29. package/src/directory.ts +16 -0
  30. package/src/dns.ts +207 -0
  31. package/src/library.ts +175 -0
  32. package/src/main.ts +88 -4
  33. package/src/names.ts +239 -0
  34. package/src/naming.ts +197 -0
  35. package/src/owner.ts +3 -0
  36. package/src/publish.ts +5 -0
  37. package/src/server.ts +446 -5
  38. package/src/session.ts +117 -0
  39. package/web/dist/assets/{hls-3VKVEQE3-70uzupqn.js → hls-3VKVEQE3-C88rYdXy.js} +1 -1
  40. package/web/dist/assets/index-BB3VT0Ks.js +1 -0
  41. package/web/dist/assets/index-DrXbwjOa.css +1 -0
  42. package/web/dist/assets/{mpegts-DQqgM7pi.js → mpegts-BMDK3Ac9.js} +1 -1
  43. package/web/dist/assets/{mpegts-LO6RVLD6-CzrQKX7m.js → mpegts-LO6RVLD6-C06vXzyy.js} +1 -1
  44. package/web/dist/index.html +23 -2
  45. package/web/dist/install.sh +3 -1
  46. package/web/dist/sw.js +6 -6
  47. package/web/dist/assets/index-ComwKkzf.js +0 -1
  48. package/web/dist/assets/index-D3xGDAOd.css +0 -1
package/dist/dns.js ADDED
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The zone: where a server's name is written down.
3
+ *
4
+ * nixamp.com hands every signed-in account's servers a name under
5
+ * `<label>.<handle>.nixamp.com`, and a name is only a name once it resolves.
6
+ * The records live at Porkbun, behind an API key that stays on nixamp.com:
7
+ * a server asks nixamp.com for its name, and nixamp.com is the only thing
8
+ * that ever talks to the registrar. The certificate module needs the same
9
+ * zone for its `_acme-challenge` TXT records, which is why TXT is here too.
10
+ *
11
+ * Behind an interface, because a test wants a zone it can read back without
12
+ * a network, and a nixamp started without keys still wants the rest of the
13
+ * code to run.
14
+ */
15
+ import { isIP } from "node:net";
16
+ /** 2026, not 1998: an address is either family, and both are first class. */
17
+ export function isIPv4(value) {
18
+ return typeof value === "string" && isIP(value) === 4;
19
+ }
20
+ export function isIPv6(value) {
21
+ return typeof value === "string" && isIP(value) === 6;
22
+ }
23
+ /** Porkbun's floor. Anything lower is silently raised, so it is raised here, loudly. */
24
+ export const MIN_TTL = 600;
25
+ function ttlOf(ttl) {
26
+ return Math.max(MIN_TTL, Math.floor(ttl ?? MIN_TTL));
27
+ }
28
+ /**
29
+ * A zone kept in memory. For tests, and for a nixamp started without registrar
30
+ * keys, where a name can be handed out and simply will not resolve -- which the
31
+ * operator is told about elsewhere, rather than crashing here.
32
+ */
33
+ export class MemoryZone {
34
+ zone;
35
+ records = [];
36
+ sequence = 0;
37
+ constructor(zone) {
38
+ this.zone = zone;
39
+ }
40
+ async list(host, type) {
41
+ return this.records.filter((record) => record.host === host && record.type === type);
42
+ }
43
+ async set(host, type, content, ttl) {
44
+ await this.remove(host, type);
45
+ await this.add(host, type, content, ttl);
46
+ }
47
+ async add(host, type, content, ttl) {
48
+ this.records.push({ id: String(++this.sequence), host, type, content, ttl: ttlOf(ttl) });
49
+ }
50
+ async remove(host, type, content) {
51
+ for (let i = this.records.length - 1; i >= 0; i--) {
52
+ const record = this.records[i];
53
+ if (record.host !== host || record.type !== type)
54
+ continue;
55
+ if (content !== undefined && record.content !== content)
56
+ continue;
57
+ this.records.splice(i, 1);
58
+ }
59
+ }
60
+ }
61
+ /** How long to wait on the registrar before deciding it is not answering. */
62
+ const PORKBUN_TIMEOUT_MS = 20_000;
63
+ /**
64
+ * Porkbun's v3 DNS API.
65
+ *
66
+ * Every call is a POST carrying both halves of the key in the body -- the
67
+ * field is `secretapikey`, which the API itself names as the usual mistake --
68
+ * and the subdomain is the host with the zone taken off: "server2.chovy" for
69
+ * "server2.chovy.nixamp.com", and nothing at all for the apex.
70
+ */
71
+ export class Porkbun {
72
+ zone;
73
+ apiKey;
74
+ secretApiKey;
75
+ send;
76
+ base;
77
+ constructor(zone, apiKey, secretApiKey, send = fetch, base = "https://api.porkbun.com/api/json/v3") {
78
+ this.zone = zone;
79
+ this.apiKey = apiKey;
80
+ this.secretApiKey = secretApiKey;
81
+ this.send = send;
82
+ this.base = base;
83
+ }
84
+ /** The part before the zone, or "" for the zone itself. */
85
+ sub(host) {
86
+ const suffix = `.${this.zone}`;
87
+ if (host === this.zone)
88
+ return "";
89
+ if (!host.endsWith(suffix))
90
+ throw new Error(`${host} is not in ${this.zone}`);
91
+ return host.slice(0, -suffix.length);
92
+ }
93
+ async call(path, fields = {}) {
94
+ let answer;
95
+ try {
96
+ answer = await this.send(`${this.base}${path}`, {
97
+ method: "POST",
98
+ headers: { "content-type": "application/json" },
99
+ body: JSON.stringify({ apikey: this.apiKey, secretapikey: this.secretApiKey, ...fields }),
100
+ signal: AbortSignal.timeout(PORKBUN_TIMEOUT_MS),
101
+ });
102
+ }
103
+ catch (error) {
104
+ throw new Error(`Porkbun did not answer: ${error.message}`);
105
+ }
106
+ let body;
107
+ try {
108
+ body = (await answer.json());
109
+ }
110
+ catch {
111
+ throw new Error(`Porkbun answered ${answer.status} with something that is not JSON`);
112
+ }
113
+ if (!answer.ok || body.status !== "SUCCESS") {
114
+ throw new Error(`Porkbun refused: ${body.message ?? `HTTP ${answer.status}`}`);
115
+ }
116
+ return body;
117
+ }
118
+ async list(host, type) {
119
+ // A trailing slash with nothing after it is how the apex is asked for.
120
+ const body = await this.call(`/dns/retrieveByNameType/${this.zone}/${type}/${this.sub(host)}`);
121
+ return (body.records ?? [])
122
+ .filter((record) => (record.type ?? type) === type)
123
+ .map((record) => ({
124
+ id: String(record.id ?? ""),
125
+ host: record.name ?? host,
126
+ type,
127
+ content: record.content ?? "",
128
+ ttl: Number(record.ttl ?? MIN_TTL) || MIN_TTL,
129
+ }));
130
+ }
131
+ async add(host, type, content, ttl) {
132
+ await this.call(`/dns/create/${this.zone}`, {
133
+ name: this.sub(host),
134
+ type,
135
+ content,
136
+ ttl: String(ttlOf(ttl)),
137
+ });
138
+ }
139
+ async set(host, type, content, ttl) {
140
+ const existing = await this.list(host, type);
141
+ const [first, ...extras] = existing;
142
+ if (first === undefined) {
143
+ await this.add(host, type, content, ttl);
144
+ return;
145
+ }
146
+ // Edit rather than delete-and-create: the name never has a moment with no
147
+ // record at all, which for an A record is a moment nobody can connect.
148
+ // Unless nothing would change: Porkbun refuses an edit that edits nothing
149
+ // ("We were unable to edit the DNS record"), and a server announcing the
150
+ // address it already has is the ordinary case, not an error.
151
+ if (first.content !== content || first.ttl !== ttlOf(ttl)) {
152
+ await this.call(`/dns/edit/${this.zone}/${first.id}`, {
153
+ name: this.sub(host),
154
+ type,
155
+ content,
156
+ ttl: String(ttlOf(ttl)),
157
+ });
158
+ }
159
+ for (const extra of extras) {
160
+ await this.call(`/dns/delete/${this.zone}/${extra.id}`);
161
+ }
162
+ }
163
+ async remove(host, type, content) {
164
+ const existing = await this.list(host, type);
165
+ for (const record of existing) {
166
+ if (content !== undefined && record.content !== content)
167
+ continue;
168
+ await this.call(`/dns/delete/${this.zone}/${record.id}`);
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,36 @@
1
+ export interface Config {
2
+ /** The folder the daemon serves when it is not told which. */
3
+ library?: string;
4
+ }
5
+ export declare function configPath(): string;
6
+ export declare function readConfig(): Config;
7
+ export declare function writeConfig(patch: Partial<Config>): void;
8
+ /** The saved library, or "" when nobody has said yet. */
9
+ export declare function readLibrary(): string;
10
+ export declare function writeLibrary(path: string): void;
11
+ /**
12
+ * Why a folder must not be served, or "" when it may be.
13
+ *
14
+ * Judged on the resolved path, so `~/..` and `/home/me/./` do not slip past.
15
+ * A hidden folder inside home is refused because that is where `.ssh`,
16
+ * `.config` and nixamp's own keys are; a hidden folder elsewhere is somebody's
17
+ * deliberate choice.
18
+ */
19
+ export declare function forbiddenLibrary(path: string, home?: string): string;
20
+ /** Folders a person is likely to mean, in the order they are likely to mean them. */
21
+ export declare function suggestedLibraries(home?: string): string[];
22
+ /** One line from the terminal. Split out so the question can be tested. */
23
+ export declare function askLine(question: string): Promise<string>;
24
+ /**
25
+ * Ask where the media is, refusing the answers that must be refused, and
26
+ * keep the answer. Empty when the person gave up or gave nothing usable
27
+ * three times.
28
+ */
29
+ export declare function askLibrary(ask?: (question: string) => Promise<string>, home?: string, say?: (line: string) => void): Promise<string>;
30
+ /**
31
+ * The library to use: the saved one, or -- when there is somebody to ask --
32
+ * the one they name now. "" when there is neither.
33
+ */
34
+ export declare function chooseLibrary(interactive: boolean, ask?: (question: string) => Promise<string>): Promise<string>;
35
+ /** `nixamp library [folder]`: say where the media is, or set it. */
36
+ export declare function libraryCommand(argv: string[]): Promise<number>;
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Where the media is.
3
+ *
4
+ * A server that is not told serves the directory it was started in, and a
5
+ * daemon restarted from a home directory served the home directory: every
6
+ * key, session and download on the machine, listed in a public directory
7
+ * under a link anybody could be handed. That is not a default anyone chose,
8
+ * so it is not a default any more.
9
+ *
10
+ * The library is a setting. It is asked for once -- at sign-in, or the first
11
+ * time the daemon is started without being told -- and kept beside the keys,
12
+ * so `nixamp daemon start` on its own means the same folder every time. And
13
+ * some folders are refused however they are asked for: the whole filesystem,
14
+ * the home directory, anything above it, and the hidden folders where keys
15
+ * and sessions live.
16
+ */
17
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join, resolve } from "node:path";
20
+ import { createInterface } from "node:readline/promises";
21
+ import { stateDir } from "./daemon.js";
22
+ export function configPath() {
23
+ return join(stateDir(), "config.json");
24
+ }
25
+ export function readConfig() {
26
+ try {
27
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
28
+ if (typeof parsed !== "object" || parsed === null)
29
+ return {};
30
+ const record = parsed;
31
+ return { ...(typeof record["library"] === "string" ? { library: record["library"] } : {}) };
32
+ }
33
+ catch {
34
+ return {};
35
+ }
36
+ }
37
+ export function writeConfig(patch) {
38
+ const next = { ...readConfig(), ...patch };
39
+ mkdirSync(stateDir(), { recursive: true });
40
+ writeFileSync(configPath(), `${JSON.stringify(next, null, 2)}\n`);
41
+ }
42
+ /** The saved library, or "" when nobody has said yet. */
43
+ export function readLibrary() {
44
+ return readConfig().library ?? "";
45
+ }
46
+ export function writeLibrary(path) {
47
+ writeConfig({ library: resolve(path) });
48
+ }
49
+ /**
50
+ * Why a folder must not be served, or "" when it may be.
51
+ *
52
+ * Judged on the resolved path, so `~/..` and `/home/me/./` do not slip past.
53
+ * A hidden folder inside home is refused because that is where `.ssh`,
54
+ * `.config` and nixamp's own keys are; a hidden folder elsewhere is somebody's
55
+ * deliberate choice.
56
+ */
57
+ export function forbiddenLibrary(path, home = homedir()) {
58
+ const full = resolve(path);
59
+ const house = resolve(home);
60
+ if (full === "/" || /^[A-Za-z]:\\?$/.test(full))
61
+ return "the whole filesystem";
62
+ if (full === house)
63
+ return "your whole home directory";
64
+ if (house.startsWith(`${full}/`))
65
+ return "a folder above your home directory";
66
+ if (full.startsWith(`${house}/`)) {
67
+ // Any dotted segment on the way, not only the last: ~/.local/state is
68
+ // where nixamp's own keys are, and its basename says nothing.
69
+ const hidden = full.slice(house.length + 1).split("/").find((segment) => segment.startsWith("."));
70
+ if (hidden)
71
+ return `a hidden folder (${hidden}), which is where keys and sessions live`;
72
+ }
73
+ return "";
74
+ }
75
+ /** Folders a person is likely to mean, in the order they are likely to mean them. */
76
+ export function suggestedLibraries(home = homedir()) {
77
+ return ["Music", "Videos", "Movies", "Downloads"]
78
+ .map((name) => join(home, name))
79
+ .filter((path) => {
80
+ try {
81
+ return statSync(path).isDirectory();
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ });
87
+ }
88
+ /** One line from the terminal. Split out so the question can be tested. */
89
+ export async function askLine(question) {
90
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
91
+ try {
92
+ return (await rl.question(question)).trim();
93
+ }
94
+ finally {
95
+ rl.close();
96
+ }
97
+ }
98
+ /**
99
+ * Ask where the media is, refusing the answers that must be refused, and
100
+ * keep the answer. Empty when the person gave up or gave nothing usable
101
+ * three times.
102
+ */
103
+ export async function askLibrary(ask = askLine, home = homedir(), say = (line) => console.log(line)) {
104
+ const suggestions = suggestedLibraries(home);
105
+ say("Where is your media? nixamp serves one folder and nothing outside it.");
106
+ for (const path of suggestions)
107
+ say(` ${path}`);
108
+ const fallback = suggestions[0] ?? "";
109
+ for (let attempt = 0; attempt < 3; attempt += 1) {
110
+ const typed = await ask(fallback ? `Folder [${fallback}]: ` : "Folder: ");
111
+ const chosen = (typed || fallback).replace(/^~(?=$|\/)/, home);
112
+ if (!chosen)
113
+ continue;
114
+ const full = resolve(chosen);
115
+ const why = forbiddenLibrary(full, home);
116
+ if (why) {
117
+ say(` nixamp will not serve ${why}. Pick a folder with your media in it.`);
118
+ continue;
119
+ }
120
+ if (!existsSync(full) || !statSync(full).isDirectory()) {
121
+ say(` ${full} is not a folder here.`);
122
+ continue;
123
+ }
124
+ writeLibrary(full);
125
+ say(` Serving ${full}. Change it any time with \`nixamp library <folder>\`.`);
126
+ return full;
127
+ }
128
+ return "";
129
+ }
130
+ /**
131
+ * The library to use: the saved one, or -- when there is somebody to ask --
132
+ * the one they name now. "" when there is neither.
133
+ */
134
+ export async function chooseLibrary(interactive, ask) {
135
+ const saved = readLibrary();
136
+ if (saved)
137
+ return saved;
138
+ if (!interactive)
139
+ return "";
140
+ return askLibrary(ask);
141
+ }
142
+ /** `nixamp library [folder]`: say where the media is, or set it. */
143
+ export async function libraryCommand(argv) {
144
+ const [given] = argv;
145
+ if (!given) {
146
+ const saved = readLibrary();
147
+ if (!saved) {
148
+ console.log("nixamp: no library set. `nixamp library ~/Music` sets it, and `nixamp daemon start` serves it.");
149
+ return 1;
150
+ }
151
+ console.log(saved);
152
+ return 0;
153
+ }
154
+ const full = resolve(given.replace(/^~(?=$|\/)/, homedir()));
155
+ const why = forbiddenLibrary(full);
156
+ if (why) {
157
+ console.error(`nixamp: will not serve ${why}. Pick a folder with your media in it.`);
158
+ return 64;
159
+ }
160
+ if (!existsSync(full) || !statSync(full).isDirectory()) {
161
+ console.error(`nixamp: ${full} is not a folder here.`);
162
+ return 66;
163
+ }
164
+ writeLibrary(full);
165
+ console.log(`nixamp will serve ${full}. Start it with \`nixamp daemon start\`.`);
166
+ return 0;
167
+ }
package/dist/main.js CHANGED
@@ -53,6 +53,8 @@ const HELP = `nixamp — it really whips the terminal's ass.
53
53
  nixamp login [--with github] sign in to nixamp.com, in a browser or here
54
54
  nixamp logout / whoami forget it, or check it
55
55
  nixamp token create|list|revoke tokens for a machine that cannot sign in
56
+ nixamp dns [set|rm] names under your handle, for your servers
57
+ nixamp library [folder] where the media is; the daemon serves this and nothing outside it
56
58
  nixamp server list|add|remove the machines you run, kept against your account
57
59
  nixamp opendir list|add|remove folders found on the web, published for everyone
58
60
  nixamp update [version] re-run the installer, keeping your choices
@@ -164,6 +166,18 @@ NIXAMP_TOKEN in the environment is a signed-in nixamp with no login at all.
164
166
  A token is shown once because the server keeps only its hash. Put it in the
165
167
  environment as NIXAMP_TOKEN, or keep it here with \`nixamp login --token\`.
166
168
  Signing out does not touch it: that is what it is for.
169
+ `,
170
+ dns: `nixamp dns — names under your handle, for your servers.
171
+
172
+ nixamp dns every name on your account, and where it points
173
+ nixamp dns set NAME NAME.<handle>.nixamp.com, pointed at this machine
174
+ nixamp dns set NAME --a IP --aaaa IP pointed somewhere you name; "off" clears one
175
+ nixamp dns set NAME --ttl N how long resolvers may keep it (seconds)
176
+ nixamp dns rm NAME take the name away
177
+
178
+ The DNS keys stay on nixamp.com. A signed-in \`nixamp serve\` names itself
179
+ this way on start and picks up the handle's certificate, so a server is
180
+ https://NAME.<handle>.nixamp.com with nothing typed here.
167
181
  `,
168
182
  daemon: `nixamp daemon — a nixamp that outlives the terminal that started it.
169
183
 
@@ -221,9 +235,45 @@ async function runDaemon(argv) {
221
235
  const d = await import("./daemon.js");
222
236
  const [action = "status", ...rest] = argv;
223
237
  const entry = fileURLToPath(new URL("./main.js", import.meta.url));
238
+ // The daemon has to know where the media is. Told a folder, that folder is
239
+ // kept as the library so the next start needs no telling; told nothing, the
240
+ // saved library is used, or asked for when there is somebody to ask.
241
+ const withLibrary = async (args) => {
242
+ const { forbiddenLibrary, chooseLibrary, writeLibrary } = await import("./library.js");
243
+ const { parseServeArgs } = await import("./server.js");
244
+ const { isRemote } = await import("./sources.js");
245
+ let given = "";
246
+ try {
247
+ given = parseServeArgs(args).root;
248
+ }
249
+ catch {
250
+ // A bad flag is the daemon's to report, in its own words.
251
+ return args;
252
+ }
253
+ if (given) {
254
+ if (!isRemote(given)) {
255
+ const why = forbiddenLibrary(given);
256
+ if (why) {
257
+ console.error(`nixamp: will not serve ${why}. Pick a folder with your media in it.`);
258
+ return null;
259
+ }
260
+ writeLibrary(given);
261
+ }
262
+ return args;
263
+ }
264
+ const library = await chooseLibrary(process.stdin.isTTY === true);
265
+ if (!library) {
266
+ console.error("nixamp: which folder? `nixamp library ~/Music` once, then `nixamp daemon start`.");
267
+ return null;
268
+ }
269
+ return [library, ...args];
270
+ };
224
271
  if (action === "start") {
272
+ const args = await withLibrary(rest);
273
+ if (args === null)
274
+ return 64;
225
275
  try {
226
- const state = await d.start(rest, entry);
276
+ const state = await d.start(args, entry);
227
277
  for (const line of d.daemonLines(state))
228
278
  console.log(line);
229
279
  return 0;
@@ -239,8 +289,13 @@ async function runDaemon(argv) {
239
289
  return 0;
240
290
  }
241
291
  if (action === "restart") {
292
+ // With no arguments the flags it was started with are replayed, library
293
+ // included; with arguments, the library rule applies as for start.
294
+ const args = rest.length === 0 ? rest : await withLibrary(rest);
295
+ if (args === null)
296
+ return 64;
242
297
  try {
243
- const state = await d.restart(rest, entry);
298
+ const state = await d.restart(args, entry);
244
299
  for (const line of d.daemonLines(state))
245
300
  console.log(line);
246
301
  return 0;
@@ -298,7 +353,14 @@ export async function main() {
298
353
  }
299
354
  if (first === "serve") {
300
355
  const { serve } = await import("./server.js");
301
- await serve(rest, version());
356
+ try {
357
+ await serve(rest, version());
358
+ }
359
+ catch (error) {
360
+ // A refusal is a sentence, not a stack trace.
361
+ console.error(error.message);
362
+ process.exitCode = 64;
363
+ }
302
364
  return;
303
365
  }
304
366
  if (first === "daemon") {
@@ -313,6 +375,14 @@ export async function main() {
313
375
  if (first === "login" || first === "signup") {
314
376
  const { login } = await import("./session.js");
315
377
  process.exitCode = await login(first === "signup" ? [...rest, "--signup"] : rest);
378
+ // Signed in is the moment a machine is about to be a server, so it is
379
+ // the moment to ask where the media is -- once, kept beside the keys.
380
+ if (process.exitCode === 0 && process.stdin.isTTY) {
381
+ const { chooseLibrary } = await import("./library.js");
382
+ const library = await chooseLibrary(true);
383
+ if (library)
384
+ console.log(" Start serving it with `nixamp daemon start`.");
385
+ }
316
386
  return;
317
387
  }
318
388
  if (first === "opendir" || first === "opendirs") {
@@ -330,6 +400,16 @@ export async function main() {
330
400
  process.exitCode = await tokens(rest);
331
401
  return;
332
402
  }
403
+ if (first === "dns") {
404
+ const { dns } = await import("./session.js");
405
+ process.exitCode = await dns(rest);
406
+ return;
407
+ }
408
+ if (first === "library") {
409
+ const { libraryCommand } = await import("./library.js");
410
+ process.exitCode = await libraryCommand(rest);
411
+ return;
412
+ }
333
413
  if (first === "logout" || first === "whoami") {
334
414
  const session = await import("./session.js");
335
415
  process.exitCode = first === "logout" ? session.logout() : await session.whoami();
@@ -346,8 +426,16 @@ export async function main() {
346
426
  }
347
427
  // resolve() would turn https://host/x into /cwd/https:/host/x, so a URL is
348
428
  // left exactly as it was typed.
349
- const asked = first ?? ".";
429
+ // The saved library before the current directory, and never a folder the
430
+ // server would refuse: `d` hands this same folder to a daemon.
431
+ const { forbiddenLibrary, readLibrary } = await import("./library.js");
432
+ const asked = first ?? (readLibrary() || ".");
350
433
  const target = isRemote(asked) ? asked : resolve(asked);
434
+ const why = isRemote(target) ? "" : forbiddenLibrary(target);
435
+ if (why) {
436
+ console.error(`nixamp: will not play ${why}. Pick a folder with your media in it, or set one: nixamp library ~/Music`);
437
+ process.exit(64);
438
+ }
351
439
  const tools = detectTools();
352
440
  // The noise it makes when it wakes up. Started before the library is walked
353
441
  // so it plays over the wait rather than after it, and never awaited: a
@@ -0,0 +1,66 @@
1
+ /**
2
+ * An account's names: the servers it runs, each with a hostname under its handle.
3
+ *
4
+ * `server2.chovy.nixamp.com` used to be a record somebody typed into the
5
+ * registrar by hand, which is why the second machine came up as a bare IP
6
+ * over http. A name is now a row against the account, mirrored into the zone
7
+ * as an A and an AAAA record, and the account may make, change and drop as
8
+ * many as it reasonably needs without anybody holding a registrar key.
9
+ *
10
+ * The database row is the truth and the zone follows it: the zone is written
11
+ * first, so a registrar that refuses is an error to the caller and nothing is
12
+ * stored, rather than a row that claims a name the world cannot resolve.
13
+ */
14
+ import type { Queryable } from "./follows.ts";
15
+ import { type DnsZone } from "./dns.ts";
16
+ export interface NameRecord {
17
+ label: string;
18
+ host: string;
19
+ a: string;
20
+ aaaa: string;
21
+ ttl: number;
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ }
25
+ /** An error with the HTTP status it deserves, so a route can pass it straight on. */
26
+ export declare class NameError extends Error {
27
+ status: number;
28
+ constructor(status: number, message: string);
29
+ }
30
+ /**
31
+ * The label a server may have: two to thirty of [a-z0-9-], not starting or
32
+ * ending with a hyphen, lowercased for the caller who typed it in capitals.
33
+ * "" when it is not one, so a route can say so in one sentence.
34
+ */
35
+ export declare function validLabel(value: unknown): string;
36
+ export declare const MIN_TTL = 600;
37
+ export declare const MAX_TTL = 86400;
38
+ /** Enough for a rack, not enough for a squatter. */
39
+ export declare const DEFAULT_PER_ACCOUNT = 20;
40
+ export declare class Names {
41
+ private readonly db;
42
+ private readonly dns;
43
+ private readonly limits;
44
+ private ready;
45
+ constructor(db: Queryable, dns: DnsZone, limits?: {
46
+ perAccount?: number;
47
+ });
48
+ private ensure;
49
+ private host;
50
+ private record;
51
+ list(accountId: string, handle: string): Promise<NameRecord[]>;
52
+ /** The row for one name, whoever owns it. */
53
+ private find;
54
+ /**
55
+ * Make or change a name. `null` for a family takes that record away,
56
+ * `undefined` leaves it as it was, so a server that has only ever had an
57
+ * IPv4 address can be given an IPv6 one without restating the first.
58
+ */
59
+ set(accountId: string, handle: string, wanted: unknown, want: {
60
+ a?: string | null;
61
+ aaaa?: string | null;
62
+ ttl?: number;
63
+ }): Promise<NameRecord>;
64
+ /** Take a name away. False when it is not this account's to take. */
65
+ remove(accountId: string, handle: string, wanted: unknown): Promise<boolean>;
66
+ }