nixamp 0.8.0 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/library.ts ADDED
@@ -0,0 +1,175 @@
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.ts";
22
+
23
+ export interface Config {
24
+ /** The folder the daemon serves when it is not told which. */
25
+ library?: string;
26
+ }
27
+
28
+ export function configPath(): string {
29
+ return join(stateDir(), "config.json");
30
+ }
31
+
32
+ export function readConfig(): Config {
33
+ try {
34
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8")) as unknown;
35
+ if (typeof parsed !== "object" || parsed === null) return {};
36
+ const record = parsed as Record<string, unknown>;
37
+ return { ...(typeof record["library"] === "string" ? { library: record["library"] } : {}) };
38
+ } catch {
39
+ return {};
40
+ }
41
+ }
42
+
43
+ export function writeConfig(patch: Partial<Config>): void {
44
+ const next = { ...readConfig(), ...patch };
45
+ mkdirSync(stateDir(), { recursive: true });
46
+ writeFileSync(configPath(), `${JSON.stringify(next, null, 2)}\n`);
47
+ }
48
+
49
+ /** The saved library, or "" when nobody has said yet. */
50
+ export function readLibrary(): string {
51
+ return readConfig().library ?? "";
52
+ }
53
+
54
+ export function writeLibrary(path: string): void {
55
+ writeConfig({ library: resolve(path) });
56
+ }
57
+
58
+ /**
59
+ * Why a folder must not be served, or "" when it may be.
60
+ *
61
+ * Judged on the resolved path, so `~/..` and `/home/me/./` do not slip past.
62
+ * A hidden folder inside home is refused because that is where `.ssh`,
63
+ * `.config` and nixamp's own keys are; a hidden folder elsewhere is somebody's
64
+ * deliberate choice.
65
+ */
66
+ export function forbiddenLibrary(path: string, home = homedir()): string {
67
+ const full = resolve(path);
68
+ const house = resolve(home);
69
+ if (full === "/" || /^[A-Za-z]:\\?$/.test(full)) return "the whole filesystem";
70
+ if (full === house) return "your whole home directory";
71
+ if (house.startsWith(`${full}/`)) return "a folder above your home directory";
72
+ if (full.startsWith(`${house}/`)) {
73
+ // Any dotted segment on the way, not only the last: ~/.local/state is
74
+ // where nixamp's own keys are, and its basename says nothing.
75
+ const hidden = full.slice(house.length + 1).split("/").find((segment) => segment.startsWith("."));
76
+ if (hidden) return `a hidden folder (${hidden}), which is where keys and sessions live`;
77
+ }
78
+ return "";
79
+ }
80
+
81
+ /** Folders a person is likely to mean, in the order they are likely to mean them. */
82
+ export function suggestedLibraries(home = homedir()): string[] {
83
+ return ["Music", "Videos", "Movies", "Downloads"]
84
+ .map((name) => join(home, name))
85
+ .filter((path) => {
86
+ try {
87
+ return statSync(path).isDirectory();
88
+ } catch {
89
+ return false;
90
+ }
91
+ });
92
+ }
93
+
94
+ /** One line from the terminal. Split out so the question can be tested. */
95
+ export async function askLine(question: string): Promise<string> {
96
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
97
+ try {
98
+ return (await rl.question(question)).trim();
99
+ } finally {
100
+ rl.close();
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Ask where the media is, refusing the answers that must be refused, and
106
+ * keep the answer. Empty when the person gave up or gave nothing usable
107
+ * three times.
108
+ */
109
+ export async function askLibrary(
110
+ ask: (question: string) => Promise<string> = askLine,
111
+ home = homedir(),
112
+ say: (line: string) => void = (line) => console.log(line),
113
+ ): Promise<string> {
114
+ const suggestions = suggestedLibraries(home);
115
+ say("Where is your media? nixamp serves one folder and nothing outside it.");
116
+ for (const path of suggestions) say(` ${path}`);
117
+ const fallback = suggestions[0] ?? "";
118
+ for (let attempt = 0; attempt < 3; attempt += 1) {
119
+ const typed = await ask(fallback ? `Folder [${fallback}]: ` : "Folder: ");
120
+ const chosen = (typed || fallback).replace(/^~(?=$|\/)/, home);
121
+ if (!chosen) continue;
122
+ const full = resolve(chosen);
123
+ const why = forbiddenLibrary(full, home);
124
+ if (why) {
125
+ say(` nixamp will not serve ${why}. Pick a folder with your media in it.`);
126
+ continue;
127
+ }
128
+ if (!existsSync(full) || !statSync(full).isDirectory()) {
129
+ say(` ${full} is not a folder here.`);
130
+ continue;
131
+ }
132
+ writeLibrary(full);
133
+ say(` Serving ${full}. Change it any time with \`nixamp library <folder>\`.`);
134
+ return full;
135
+ }
136
+ return "";
137
+ }
138
+
139
+ /**
140
+ * The library to use: the saved one, or -- when there is somebody to ask --
141
+ * the one they name now. "" when there is neither.
142
+ */
143
+ export async function chooseLibrary(interactive: boolean, ask?: (question: string) => Promise<string>): Promise<string> {
144
+ const saved = readLibrary();
145
+ if (saved) return saved;
146
+ if (!interactive) return "";
147
+ return askLibrary(ask);
148
+ }
149
+
150
+ /** `nixamp library [folder]`: say where the media is, or set it. */
151
+ export async function libraryCommand(argv: string[]): Promise<number> {
152
+ const [given] = argv;
153
+ if (!given) {
154
+ const saved = readLibrary();
155
+ if (!saved) {
156
+ console.log("nixamp: no library set. `nixamp library ~/Music` sets it, and `nixamp daemon start` serves it.");
157
+ return 1;
158
+ }
159
+ console.log(saved);
160
+ return 0;
161
+ }
162
+ const full = resolve(given.replace(/^~(?=$|\/)/, homedir()));
163
+ const why = forbiddenLibrary(full);
164
+ if (why) {
165
+ console.error(`nixamp: will not serve ${why}. Pick a folder with your media in it.`);
166
+ return 64;
167
+ }
168
+ if (!existsSync(full) || !statSync(full).isDirectory()) {
169
+ console.error(`nixamp: ${full} is not a folder here.`);
170
+ return 66;
171
+ }
172
+ writeLibrary(full);
173
+ console.log(`nixamp will serve ${full}. Start it with \`nixamp daemon start\`.`);
174
+ return 0;
175
+ }
package/src/main.ts CHANGED
@@ -77,6 +77,8 @@ const HELP = `nixamp — it really whips the terminal's ass.
77
77
  nixamp login [--with github] sign in to nixamp.com, in a browser or here
78
78
  nixamp logout / whoami forget it, or check it
79
79
  nixamp token create|list|revoke tokens for a machine that cannot sign in
80
+ nixamp dns [set|rm] names under your handle, for your servers
81
+ nixamp library [folder] where the media is; the daemon serves this and nothing outside it
80
82
  nixamp server list|add|remove the machines you run, kept against your account
81
83
  nixamp opendir list|add|remove folders found on the web, published for everyone
82
84
  nixamp update [version] re-run the installer, keeping your choices
@@ -190,6 +192,18 @@ NIXAMP_TOKEN in the environment is a signed-in nixamp with no login at all.
190
192
  A token is shown once because the server keeps only its hash. Put it in the
191
193
  environment as NIXAMP_TOKEN, or keep it here with \`nixamp login --token\`.
192
194
  Signing out does not touch it: that is what it is for.
195
+ `,
196
+ dns: `nixamp dns — names under your handle, for your servers.
197
+
198
+ nixamp dns every name on your account, and where it points
199
+ nixamp dns set NAME NAME.<handle>.nixamp.com, pointed at this machine
200
+ nixamp dns set NAME --a IP --aaaa IP pointed somewhere you name; "off" clears one
201
+ nixamp dns set NAME --ttl N how long resolvers may keep it (seconds)
202
+ nixamp dns rm NAME take the name away
203
+
204
+ The DNS keys stay on nixamp.com. A signed-in \`nixamp serve\` names itself
205
+ this way on start and picks up the handle's certificate, so a server is
206
+ https://NAME.<handle>.nixamp.com with nothing typed here.
193
207
  `,
194
208
  daemon: `nixamp daemon — a nixamp that outlives the terminal that started it.
195
209
 
@@ -250,9 +264,44 @@ async function runDaemon(argv: string[]): Promise<number> {
250
264
  const [action = "status", ...rest] = argv;
251
265
  const entry = fileURLToPath(new URL("./main.js", import.meta.url));
252
266
 
267
+ // The daemon has to know where the media is. Told a folder, that folder is
268
+ // kept as the library so the next start needs no telling; told nothing, the
269
+ // saved library is used, or asked for when there is somebody to ask.
270
+ const withLibrary = async (args: string[]): Promise<string[] | null> => {
271
+ const { forbiddenLibrary, chooseLibrary, writeLibrary } = await import("./library.ts");
272
+ const { parseServeArgs } = await import("./server.ts");
273
+ const { isRemote } = await import("./sources.ts");
274
+ let given = "";
275
+ try {
276
+ given = parseServeArgs(args).root;
277
+ } catch {
278
+ // A bad flag is the daemon's to report, in its own words.
279
+ return args;
280
+ }
281
+ if (given) {
282
+ if (!isRemote(given)) {
283
+ const why = forbiddenLibrary(given);
284
+ if (why) {
285
+ console.error(`nixamp: will not serve ${why}. Pick a folder with your media in it.`);
286
+ return null;
287
+ }
288
+ writeLibrary(given);
289
+ }
290
+ return args;
291
+ }
292
+ const library = await chooseLibrary(process.stdin.isTTY === true);
293
+ if (!library) {
294
+ console.error("nixamp: which folder? `nixamp library ~/Music` once, then `nixamp daemon start`.");
295
+ return null;
296
+ }
297
+ return [library, ...args];
298
+ };
299
+
253
300
  if (action === "start") {
301
+ const args = await withLibrary(rest);
302
+ if (args === null) return 64;
254
303
  try {
255
- const state = await d.start(rest, entry);
304
+ const state = await d.start(args, entry);
256
305
  for (const line of d.daemonLines(state)) console.log(line);
257
306
  return 0;
258
307
  } catch (error) {
@@ -268,8 +317,12 @@ async function runDaemon(argv: string[]): Promise<number> {
268
317
  }
269
318
 
270
319
  if (action === "restart") {
320
+ // With no arguments the flags it was started with are replayed, library
321
+ // included; with arguments, the library rule applies as for start.
322
+ const args = rest.length === 0 ? rest : await withLibrary(rest);
323
+ if (args === null) return 64;
271
324
  try {
272
- const state = await d.restart(rest, entry);
325
+ const state = await d.restart(args, entry);
273
326
  for (const line of d.daemonLines(state)) console.log(line);
274
327
  return 0;
275
328
  } catch (error) {
@@ -331,7 +384,13 @@ export async function main(): Promise<void> {
331
384
 
332
385
  if (first === "serve") {
333
386
  const { serve } = await import("./server.ts");
334
- await serve(rest, version());
387
+ try {
388
+ await serve(rest, version());
389
+ } catch (error) {
390
+ // A refusal is a sentence, not a stack trace.
391
+ console.error((error as Error).message);
392
+ process.exitCode = 64;
393
+ }
335
394
  return;
336
395
  }
337
396
  if (first === "daemon") {
@@ -346,6 +405,13 @@ export async function main(): Promise<void> {
346
405
  if (first === "login" || first === "signup") {
347
406
  const { login } = await import("./session.ts");
348
407
  process.exitCode = await login(first === "signup" ? [...rest, "--signup"] : rest);
408
+ // Signed in is the moment a machine is about to be a server, so it is
409
+ // the moment to ask where the media is -- once, kept beside the keys.
410
+ if (process.exitCode === 0 && process.stdin.isTTY) {
411
+ const { chooseLibrary } = await import("./library.ts");
412
+ const library = await chooseLibrary(true);
413
+ if (library) console.log(" Start serving it with `nixamp daemon start`.");
414
+ }
349
415
  return;
350
416
  }
351
417
  if (first === "opendir" || first === "opendirs") {
@@ -363,6 +429,16 @@ export async function main(): Promise<void> {
363
429
  process.exitCode = await tokens(rest);
364
430
  return;
365
431
  }
432
+ if (first === "dns") {
433
+ const { dns } = await import("./session.ts");
434
+ process.exitCode = await dns(rest);
435
+ return;
436
+ }
437
+ if (first === "library") {
438
+ const { libraryCommand } = await import("./library.ts");
439
+ process.exitCode = await libraryCommand(rest);
440
+ return;
441
+ }
366
442
  if (first === "logout" || first === "whoami") {
367
443
  const session = await import("./session.ts");
368
444
  process.exitCode = first === "logout" ? session.logout() : await session.whoami();
@@ -377,8 +453,16 @@ export async function main(): Promise<void> {
377
453
 
378
454
  // resolve() would turn https://host/x into /cwd/https:/host/x, so a URL is
379
455
  // left exactly as it was typed.
380
- const asked = first ?? ".";
456
+ // The saved library before the current directory, and never a folder the
457
+ // server would refuse: `d` hands this same folder to a daemon.
458
+ const { forbiddenLibrary, readLibrary } = await import("./library.ts");
459
+ const asked = first ?? (readLibrary() || ".");
381
460
  const target = isRemote(asked) ? asked : resolve(asked);
461
+ const why = isRemote(target) ? "" : forbiddenLibrary(target);
462
+ if (why) {
463
+ console.error(`nixamp: will not play ${why}. Pick a folder with your media in it, or set one: nixamp library ~/Music`);
464
+ process.exit(64);
465
+ }
382
466
  const tools = detectTools();
383
467
  // The noise it makes when it wakes up. Started before the library is walked
384
468
  // so it plays over the wait rather than after it, and never awaited: a
package/src/names.ts ADDED
@@ -0,0 +1,239 @@
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 { isReserved } from "./handles.ts";
16
+ import { isIPv4, isIPv6, type DnsZone } from "./dns.ts";
17
+
18
+ export interface NameRecord {
19
+ label: string;
20
+ host: string;
21
+ a: string;
22
+ aaaa: string;
23
+ ttl: number;
24
+ createdAt: number;
25
+ updatedAt: number;
26
+ }
27
+
28
+ /** An error with the HTTP status it deserves, so a route can pass it straight on. */
29
+ export class NameError extends Error {
30
+ constructor(
31
+ public status: number,
32
+ message: string,
33
+ ) {
34
+ super(message);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Names nobody may give a server, over and above the handles nobody may take:
40
+ * the mail and discovery names a client resolves on its own, anything an
41
+ * underscore marks as a protocol record, and anything punycode-shaped.
42
+ */
43
+ const RESERVED_LABELS = new Set([
44
+ "www", "mail", "mx", "smtp", "imap", "pop", "ns1", "ns2", "ftp",
45
+ "_dmarc", "_acme-challenge", "autoconfig", "autodiscover",
46
+ ]);
47
+
48
+ /**
49
+ * The label a server may have: two to thirty of [a-z0-9-], not starting or
50
+ * ending with a hyphen, lowercased for the caller who typed it in capitals.
51
+ * "" when it is not one, so a route can say so in one sentence.
52
+ */
53
+ export function validLabel(value: unknown): string {
54
+ if (typeof value !== "string") return "";
55
+ const label = value.trim().toLowerCase();
56
+ if (!/^[a-z0-9][a-z0-9-]{0,28}[a-z0-9]$/.test(label)) return "";
57
+ if (label.startsWith("_") || label.startsWith("xn--")) return "";
58
+ if (RESERVED_LABELS.has(label) || isReserved(label)) return "";
59
+ return label;
60
+ }
61
+
62
+ const TABLE = "dns_names";
63
+
64
+ const SCHEMA = `
65
+ CREATE TABLE IF NOT EXISTS ${TABLE} (
66
+ account_id TEXT NOT NULL,
67
+ handle TEXT NOT NULL,
68
+ label TEXT NOT NULL,
69
+ a TEXT NOT NULL DEFAULT '',
70
+ aaaa TEXT NOT NULL DEFAULT '',
71
+ ttl INTEGER NOT NULL DEFAULT 600,
72
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
73
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
74
+ PRIMARY KEY (handle, label)
75
+ );
76
+ CREATE INDEX IF NOT EXISTS ${TABLE}_account ON ${TABLE} (account_id);
77
+ `;
78
+
79
+ export const MIN_TTL = 600;
80
+ export const MAX_TTL = 86_400;
81
+ /** Enough for a rack, not enough for a squatter. */
82
+ export const DEFAULT_PER_ACCOUNT = 20;
83
+
84
+ interface Row {
85
+ account_id: string;
86
+ handle: string;
87
+ label: string;
88
+ a: string;
89
+ aaaa: string;
90
+ ttl: number;
91
+ created_at: unknown;
92
+ updated_at: unknown;
93
+ }
94
+
95
+ function when(value: unknown): number {
96
+ if (value instanceof Date) return value.getTime();
97
+ const parsed = new Date(String(value ?? 0)).getTime();
98
+ return Number.isFinite(parsed) ? parsed : 0;
99
+ }
100
+
101
+ export class Names {
102
+ private ready: Promise<void> | null = null;
103
+
104
+ constructor(
105
+ private readonly db: Queryable,
106
+ private readonly dns: DnsZone,
107
+ private readonly limits: { perAccount?: number } = {},
108
+ ) {}
109
+
110
+ private async ensure(): Promise<void> {
111
+ this.ready ??= this.db.query(SCHEMA).then(() => undefined);
112
+ await this.ready;
113
+ }
114
+
115
+ private host(handle: string, label: string): string {
116
+ return `${label}.${handle}.${this.dns.zone}`;
117
+ }
118
+
119
+ private record(handle: string, row: Row): NameRecord {
120
+ return {
121
+ label: row.label,
122
+ host: this.host(handle, row.label),
123
+ a: row.a ?? "",
124
+ aaaa: row.aaaa ?? "",
125
+ ttl: Number(row.ttl) || MIN_TTL,
126
+ createdAt: when(row.created_at),
127
+ updatedAt: when(row.updated_at),
128
+ };
129
+ }
130
+
131
+ async list(accountId: string, handle: string): Promise<NameRecord[]> {
132
+ await this.ensure();
133
+ const { rows } = await this.db.query(
134
+ `SELECT account_id, handle, label, a, aaaa, ttl, created_at, updated_at
135
+ FROM ${TABLE} WHERE account_id = $1 AND handle = $2 ORDER BY created_at`,
136
+ [accountId, handle],
137
+ );
138
+ return (rows as unknown as Row[]).map((row) => this.record(handle, row));
139
+ }
140
+
141
+ /** The row for one name, whoever owns it. */
142
+ private async find(handle: string, label: string): Promise<Row | null> {
143
+ const { rows } = await this.db.query(
144
+ `SELECT account_id, handle, label, a, aaaa, ttl, created_at, updated_at
145
+ FROM ${TABLE} WHERE handle = $1 AND label = $2`,
146
+ [handle, label],
147
+ );
148
+ return (rows[0] as unknown as Row | undefined) ?? null;
149
+ }
150
+
151
+ /**
152
+ * Make or change a name. `null` for a family takes that record away,
153
+ * `undefined` leaves it as it was, so a server that has only ever had an
154
+ * IPv4 address can be given an IPv6 one without restating the first.
155
+ */
156
+ async set(
157
+ accountId: string,
158
+ handle: string,
159
+ wanted: unknown,
160
+ want: { a?: string | null; aaaa?: string | null; ttl?: number },
161
+ ): Promise<NameRecord> {
162
+ const label = validLabel(wanted);
163
+ if (label === "") throw new NameError(400, "that is not a name a server can have");
164
+ if (want.a !== undefined && want.a !== null && !isIPv4(want.a)) {
165
+ throw new NameError(400, "that is not an IPv4 address");
166
+ }
167
+ if (want.aaaa !== undefined && want.aaaa !== null && !isIPv6(want.aaaa)) {
168
+ throw new NameError(400, "that is not an IPv6 address");
169
+ }
170
+ await this.ensure();
171
+
172
+ const existing = await this.find(handle, label);
173
+ if (existing !== null && existing.account_id !== accountId) {
174
+ throw new NameError(409, "that name belongs to somebody else");
175
+ }
176
+ if (existing === null) {
177
+ const { rows } = await this.db.query(
178
+ `SELECT count(*)::int AS n FROM ${TABLE} WHERE account_id = $1`,
179
+ [accountId],
180
+ );
181
+ const have = Number((rows[0] as { n?: unknown } | undefined)?.n ?? 0);
182
+ const limit = this.limits.perAccount ?? DEFAULT_PER_ACCOUNT;
183
+ if (have >= limit) throw new NameError(422, `an account may have ${limit} names, and this one has ${have}`);
184
+ }
185
+
186
+ // What the name will point at once this is done.
187
+ const a = want.a === undefined ? (existing?.a ?? "") : (want.a ?? "");
188
+ const aaaa = want.aaaa === undefined ? (existing?.aaaa ?? "") : (want.aaaa ?? "");
189
+ if (a === "" && aaaa === "") throw new NameError(400, "give an address");
190
+ const ttl = Math.min(MAX_TTL, Math.max(MIN_TTL, Math.floor(want.ttl ?? existing?.ttl ?? MIN_TTL)));
191
+
192
+ // The zone first. A registrar that says no is the caller's problem to hear
193
+ // about now, not a row that claims a name the world cannot resolve.
194
+ const host = this.host(handle, label);
195
+ try {
196
+ if (a !== "") await this.dns.set(host, "A", a, ttl);
197
+ else if (existing !== null && existing.a !== "") await this.dns.remove(host, "A");
198
+ if (aaaa !== "") await this.dns.set(host, "AAAA", aaaa, ttl);
199
+ else if (existing !== null && existing.aaaa !== "") await this.dns.remove(host, "AAAA");
200
+ } catch (error) {
201
+ throw new NameError(502, `the zone did not take that record: ${(error as Error).message}`);
202
+ }
203
+
204
+ const { rows } = await this.db.query(
205
+ `INSERT INTO ${TABLE} (account_id, handle, label, a, aaaa, ttl)
206
+ VALUES ($1, $2, $3, $4, $5, $6)
207
+ ON CONFLICT (handle, label) DO UPDATE
208
+ SET a = EXCLUDED.a, aaaa = EXCLUDED.aaaa, ttl = EXCLUDED.ttl, updated_at = now()
209
+ RETURNING account_id, handle, label, a, aaaa, ttl, created_at, updated_at`,
210
+ [accountId, handle, label, a, aaaa, ttl],
211
+ );
212
+ const row = rows[0] as unknown as Row | undefined;
213
+ return this.record(handle, row ?? {
214
+ account_id: accountId, handle, label, a, aaaa, ttl,
215
+ created_at: existing?.created_at ?? new Date(), updated_at: new Date(),
216
+ });
217
+ }
218
+
219
+ /** Take a name away. False when it is not this account's to take. */
220
+ async remove(accountId: string, handle: string, wanted: unknown): Promise<boolean> {
221
+ const label = validLabel(wanted);
222
+ if (label === "") return false;
223
+ await this.ensure();
224
+ const existing = await this.find(handle, label);
225
+ if (existing === null || existing.account_id !== accountId) return false;
226
+
227
+ const host = this.host(handle, label);
228
+ try {
229
+ await this.dns.remove(host, "A");
230
+ await this.dns.remove(host, "AAAA");
231
+ } catch (error) {
232
+ throw new NameError(502, `the zone did not let go of that record: ${(error as Error).message}`);
233
+ }
234
+ await this.db.query(`DELETE FROM ${TABLE} WHERE account_id = $1 AND handle = $2 AND label = $3`, [
235
+ accountId, handle, label,
236
+ ]);
237
+ return true;
238
+ }
239
+ }