The mesh's one resolver, what every node asks, and a node's hosts file (hq ADR 0194, 0196, 0199)

- dnsmasq holds mesh-dns-resolver: provides wildcard-resolution mesh-wide, forwards every declared
  zone (zones fact), listens on the private address and loopback only, reads no hosts file and no
  operator's files, and no longer writes the container runtime's dns.
- resolv-conf names the mesh's resolver by address, then 1.1.1.1, timeout 1, one attempt; it now
  holds the runtime's live-restore, which dnsmasq held and every node needs.
- resolved-split-dns routes the suffix to the mesh's resolver by address, not 127.0.0.1.
- hosts: new module holding node-hosts-file — the machine's own lines in its block of /etc/hosts,
  the operator's lines kept, changed by entries/add/remove through sudo -n.
This commit is contained in:
2026-10-04 00:38:57 +02:00
parent efff54157b
commit ff697779ab
9 changed files with 393 additions and 25 deletions
+178
View File
@@ -0,0 +1,178 @@
// The hosts file's own code (novox/hq ADR 0199): read /etc/hosts as the machine has it, and change the
// operator's lines — every line outside a `# BEGIN … / # END …` block — leaving every block, the mesh's
// and any other tool's, byte for byte. The mesh writes this module's block; these verbs never touch it.
// Root is the module's concern (ADR 0175 §4): the runtime runs as the operator's account, so the file
// is written through sudo without a prompt where the account is not root, as the packet filter's is.
import { execFile } from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { isIP } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
const execFileP = promisify(execFile);
/** Where the file is. The manifest's resource names the same path; a test holds the two together. */
export const HOSTS_FILE = "/etc/hosts";
/** A command runner, so the writes can be tested without a machine. */
export type Runner = (cmd: string, args: string[]) => Promise<string>;
export function escalated(cmd: string, args: string[], uid: number | undefined = process.getuid?.()): [string, string[]] {
if (uid === 0) return [cmd, args];
return ["sudo", ["-n", cmd, ...args]];
}
const run: Runner = async (cmd, args) => {
const [program, argv] = escalated(cmd, args);
const { stdout } = await execFileP(program, argv);
return stdout;
};
/** One line of the file, as a reader sees it. */
export interface Line {
/** The line exactly as it is in the file. */
text: string;
/** Whose it is: the block's id (`mesh hosts.own`, or another tool's) or "operator". */
owner: string;
/** For an entry: its address and names. Absent for a comment or blank line. */
address?: string;
names?: string[];
}
const BEGIN = /^#\s*BEGIN\s+(.+?)\s*$/;
const END = /^#\s*END\s+(.+?)\s*$/;
/** Every line of a hosts file, each marked whose it is. */
export function parse(text: string): Line[] {
const out: Line[] = [];
let block: string | null = null;
for (const raw of text.split("\n")) {
const begin = raw.match(BEGIN);
if (!block && begin) {
block = begin[1];
out.push({ text: raw, owner: block });
continue;
}
const owner = block ?? "operator";
const entry = raw.replace(/#.*/, "").trim().split(/\s+/).filter(Boolean);
const line: Line = { text: raw, owner };
if (entry.length >= 2 && isIP(entry[0])) {
line.address = entry[0];
line.names = entry.slice(1);
}
out.push(line);
const end = raw.match(END);
if (block && end && end[1] === block) block = null;
}
// A trailing newline splits into one empty last element; it is the file's ending, not a line.
if (out.length > 0 && out[out.length - 1].text === "" && text.endsWith("\n")) out.pop();
return out;
}
const NAME = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*\.?$/;
/** Refused input says why, so a caller is one edit from right. */
function checkAddress(address: string): void {
if (!isIP(address)) throw new Error(`${JSON.stringify(address)} is not an IPv4 or IPv6 address`);
}
function checkName(name: string): void {
if (!NAME.test(name)) throw new Error(`${JSON.stringify(name)} is not a host name`);
}
/** The file with one address and its names added to the operator's lines; unchanged when already there. */
export function withAdded(text: string, address: string, names: string[]): string {
checkAddress(address);
if (names.length === 0) throw new Error("add names at least one name for the address");
names.forEach(checkName);
const lines = parse(text);
const have = new Set(
lines.filter((l) => l.owner === "operator" && l.address === address).flatMap((l) => l.names ?? []),
);
const missing = names.filter((n) => !have.has(n));
if (missing.length === 0) return text;
const body = text.endsWith("\n") || text === "" ? text : text + "\n";
return body + `${address}\t${missing.join(" ")}\n`;
}
/** The file with one name, or every line of one address, taken out of the operator's lines. Blocks are
* never touched: a name only the mesh or another tool writes is refused, naming whose it is. */
export function withRemoved(text: string, what: string): { text: string; removed: number } {
const byAddress = isIP(what) !== 0;
if (!byAddress) checkName(what);
const lines = parse(text);
let removed = 0;
const kept: string[] = [];
for (const l of lines) {
if (l.owner !== "operator" || !l.address) {
kept.push(l.text);
continue;
}
if (byAddress && l.address === what) {
removed++;
continue;
}
if (!byAddress && l.names?.includes(what)) {
removed++;
const rest = l.names.filter((n) => n !== what);
if (rest.length > 0) kept.push(`${l.address}\t${rest.join(" ")}`);
continue;
}
kept.push(l.text);
}
if (removed === 0) {
const elsewhere = lines.find((l) => l.owner !== "operator" && (byAddress ? l.address === what : l.names?.includes(what)));
if (elsewhere) throw new Error(`${what} is written by ${elsewhere.owner}, not the operator; it is not this verb's to remove`);
}
return { text: kept.join("\n") + "\n", removed };
}
export class HostsFile {
private readonly path: string;
private readonly runner: Runner;
constructor(path: string = HOSTS_FILE, runner: Runner = run) {
this.path = path;
this.runner = runner;
}
static onThisMachine(): HostsFile {
return new HostsFile();
}
async read(): Promise<string> {
return readFile(this.path, "utf8");
}
async entries(): Promise<{ path: string; lines: Line[] }> {
return { path: this.path, lines: parse(await this.read()) };
}
async add(address: string, names: string[]): Promise<{ added: boolean; line?: string }> {
const before = await this.read();
const after = withAdded(before, address, names);
if (after === before) return { added: false };
await this.write(after);
return { added: true, line: after.slice(before.length).trim() };
}
async remove(what: string): Promise<{ removed: number }> {
const before = await this.read();
const { text, removed } = withRemoved(before, what);
if (removed > 0) await this.write(text);
return { removed };
}
/** Written whole through a copy beside it, so a reader never sees half a file. */
private async write(content: string): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "hosts-"));
const staged = join(dir, "hosts");
try {
await writeFile(staged, content, { mode: 0o644 });
await this.runner("install", ["-m", "0644", staged, this.path]);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"module": "hosts",
"version": "1",
"claims": [
{
"name": "node-hosts-file",
"scope": "node",
"serves": [
"entries",
"add",
"remove"
]
}
],
"resources": [
{
"id": "own",
"type": "file",
"path": "/etc/hosts",
"mode": "0644",
"into": "block",
"at": "start",
"content": "# The machine's own names (module hosts, novox/hq ADR 0199). Every line outside this block is the\n# operator's: kept across every push, changed through the node-hosts-file verbs add and remove, and\n# given back when this module goes. The mesh's names are not here: the mesh's resolver answers them.\n127.0.0.1\tlocalhost\n::1\tlocalhost\n"
}
],
"build": {
"artifacts": [
{
"name": "tools",
"kind": "bundle",
"language": "typescript",
"entrypoints": [
"tools/index.js"
],
"loads": [
"tools/index.js"
]
}
]
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@novox/module-hosts",
"version": "0.1.0",
"description": "hosts — holds the node-hosts-file seat: writes the machine's own lines into /etc/hosts and serves the verbs entries, add and remove over the operator's lines (novox/hq ADR 0199).",
"type": "module",
"private": true,
"dependencies": {
"@novox/mesh-sdk": "^0.1.1"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.6.0"
},
"scripts": {
"build": "tsc client.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist",
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
}
}
+69
View File
@@ -0,0 +1,69 @@
// The hosts file's verbs over files shaped like the workstation's on 2026-10-03 (novox/hq ADR 0199):
// distribution lines, an operator's development names, the mesh's block and another tool's.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { HOSTS_FILE, escalated, parse, withAdded, withRemoved } from "../client.ts";
const FILE =
"# Static table lookup for hostnames.\n" +
"127.0.0.1\tlocaldev.example.com\n" +
"127.0.0.1 a.example.com b.example.com\n" +
"# BEGIN mesh hosts.own\n" +
"127.0.0.1\tlocalhost\n" +
"::1\tlocalhost\n" +
"# END mesh hosts.own\n" +
"# BEGIN other-tool\n" +
"192.0.2.7\tproject.test\n" +
"# END other-tool\n";
const blocks = (text: string) => parse(text).filter((l) => l.owner !== "operator").map((l) => l.text);
test("every line says whose it is", () => {
const lines = parse(FILE);
assert.equal(lines.length, 10);
assert.deepEqual(lines[1], { text: "127.0.0.1\tlocaldev.example.com", owner: "operator", address: "127.0.0.1", names: ["localdev.example.com"] });
assert.equal(lines[4].owner, "mesh hosts.own");
assert.equal(lines[8].owner, "other-tool");
assert.deepEqual(lines[8].names, ["project.test"]);
});
test("add appends an operator line, and is a no-op when the names are there", () => {
const after = withAdded(FILE, "192.0.2.9", ["lab.test", "www.lab.test"]);
assert.ok(after.endsWith("192.0.2.9\tlab.test www.lab.test\n"));
assert.deepEqual(blocks(after), blocks(FILE));
assert.equal(withAdded(FILE, "127.0.0.1", ["a.example.com"]), FILE);
assert.ok(withAdded(FILE, "127.0.0.1", ["a.example.com", "c.example.com"]).endsWith("127.0.0.1\tc.example.com\n"));
});
test("add refuses what is not an address or a host name", () => {
assert.throws(() => withAdded(FILE, "not-an-ip", ["x.test"]), /not an IPv4 or IPv6 address/);
assert.throws(() => withAdded(FILE, "192.0.2.9", ["bad name\n10.0.0.1 evil"]), /not a host name/);
assert.throws(() => withAdded(FILE, "192.0.2.9", []), /at least one name/);
});
test("remove takes one name or one address from the operator's lines, and blocks stay byte for byte", () => {
const one = withRemoved(FILE, "a.example.com");
assert.equal(one.removed, 1);
assert.ok(one.text.includes("127.0.0.1\tb.example.com\n"));
assert.ok(!one.text.includes("a.example.com"));
assert.deepEqual(blocks(one.text), blocks(FILE));
const all = withRemoved(FILE, "127.0.0.1");
assert.equal(all.removed, 2);
assert.ok(all.text.includes("# BEGIN mesh hosts.own\n127.0.0.1\tlocalhost\n"), "the mesh's own localhost is not the operator's to remove");
});
test("remove refuses a name only a block writes, naming whose", () => {
assert.throws(() => withRemoved(FILE, "project.test"), /written by other-tool/);
assert.equal(withRemoved(FILE, "nowhere.test").removed, 0);
});
test("the file is written as root through sudo where the account is not root", () => {
assert.deepEqual(escalated("install", ["x"], 1000), ["sudo", ["-n", "install", "x"]]);
assert.deepEqual(escalated("install", ["x"], 0), ["install", ["x"]]);
});
test("the path the code writes is the path the manifest's resource declares", () => {
const manifest = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8"));
assert.equal(manifest.resources.find((r: { id: string }) => r.id === "own").path, HOSTS_FILE);
});
+40
View File
@@ -0,0 +1,40 @@
// The hosts file's tools: the node-hosts-file seat's three verbs (novox/hq ADR 0199) — the file's lines
// with whose each is, add an operator's line, remove one. They change the machine's file and nothing
// else; the controller holds none of it.
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
import { HostsFile } from "../client.js";
export function getSeatVerbs(hosts: HostsFile): ToolDefinition[] {
return [
{
name: "entries",
description:
"Every line of this machine's /etc/hosts, each marked whose it is: the operator's, or the block of the module or tool that writes it.",
input: {},
run: async () => hosts.entries(),
},
{
name: "add",
description:
"Add one address and its names to the operator's lines of this machine's /etc/hosts — a name for this machine's own programs, not the mesh's. Nothing changes when they are already there.",
input: {
address: { type: "string", description: "the IPv4 or IPv6 address" },
names: { type: "string", description: "the names for it, separated by spaces" },
},
run: async (args) =>
hosts.add(String(args.address ?? ""), String(args.names ?? "").split(/[\s,]+/).filter(Boolean)),
},
{
name: "remove",
description:
"Remove one name, or every line of one address, from the operator's lines of this machine's /etc/hosts. A line a module writes is refused, naming the module.",
input: { name: { type: "string", description: "a host name, or an address to remove every line of" } },
run: async (args) => hosts.remove(String(args.name ?? "")),
},
];
}
const hosts = HostsFile.onThisMachine();
// The seat's verbs under the seat's name: the runtime serves them as <node>/node-hosts-file.<verb>.
registerModuleTools("node-hosts-file", () => getSeatVerbs(hosts));
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noEmit": true
},
"include": [
"client.ts",
"tools/index.ts"
]
}