Edit Technitium zones: switch off and on, and their options

An Edit zone panel on the open zone of a Technitium provider switches the zone
off and on (its records stay) and edits who may ask it (query access), who may
copy it (zone transfer, with the TSIG keys the server has) and who is told when
it changes (notify). Only the groups that apply to the kind of zone are shown,
a mode that goes by a list needs it, and entries must be addresses or networks;
only groups that differ are sent, each whole, and the zone is read again
afterwards so anything else that moved is named on the page and in the audit
log. The server's own zones are not touched. Administrators only, audited.
Zones in the list show when they are off and what kind they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 23:20:19 +01:00
1 parent 082c524125
commit 6f144b4e36
12 files changed
+1110 -10

No files matched your search

+5 -1
View File
@@ -598,8 +598,12 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
- **Config fields:** Technitium URL, API Token
- **Auth:** Bearer token
- **Actions used:** list zones, **make a zone**, **delete a zone**, read zone records, add/delete records (an "update" is implemented as delete + add)
- **Actions used:** list zones, **make a zone**, **edit a zone** (switch it off and on, its options), **delete a zone**, read zone records, add/delete records (an "update" is implemented as delete + add)
- **Making a zone** (DNS page → pick the provider → **New zone**, administrators only — it makes the server an authority for a name; it is the one DNS provider that can): a **Primary** zone (a domain name such as `home.lan`, or an address or network such as `192.168.1.0/24`, which Technitium turns into the reverse `…in-addr.arpa` zone), a **Secondary** zone (the servers that hold it, comma-separated) or a **Forwarder** zone (the DNS server to pass questions to — an address, a name, a URL or `this-server` — the protocol, UDP unless told, and whether to check DNSSEC, off unless told). It is `POST /api/zones/create` with the name and the type (and, for a Secondary, `primaryNameServerAddresses`; for a Forwarder, `initializeForwarder`, `forwarder`, `protocol` and `dnssecValidation`). The name is written lower case without a trailing dot and must be ASCII (a name with other letters in its `xn--` form); anything else is refused before Technitium is asked, and what Technitium says when it refuses (a zone that is there already) is shown as it was said. The new zone opens when it is made; a Primary zone has the records Technitium makes for it and the rest are added as usual. It is written in the audit log (who made which zone, of which kind).
- **Editing a zone** (DNS page → open the zone → **Edit zone**, administrators only; the server's own internal zones are never touched):
- **Switch off / on** — `POST /api/zones/disable` and `/api/zones/enable`. Off, the server stops answering for the zone; its records stay, and on brings it all back. A switched-off zone is marked *off* in the zone list, and the Technitium integration does not judge it.
- **Who may ask the zone** (`queryAccess`: everyone, nobody, only private networks, only the zone's name servers, only the networks listed, or the name servers and the networks listed), **who may copy it** (`zoneTransfer`, the same without the private-network choice, and the TSIG keys the server has that a transfer may be limited to) and **who is told when it changes** (`notify`: nobody, the zone's name servers, only the servers listed, or both). A choice that goes by a list needs it: networks are addresses or CIDR networks, one to a line and in order, with `!` in front to refuse one; servers are addresses. It is `GET /api/zones/options/get` (with the TSIG key names) and `POST /api/zones/options/set`.
- **What a kind of zone has:** a Primary or Secondary zone has all three; a Forwarder or Stub or Catalog zone only who may ask it, and a secondary catalog none; anything else is refused with the reason, before Technitium is asked. What is not changed is not sent: only the groups that differ go, each whole (its mode and the list it uses), because the documentation does not say what Technitium does with a setting that is left out of the call. **So afterwards the zone is read again, and anything else it says about the zone that moved (dynamic updates, its catalog …) is named on the page and in the audit log** — a warning, not an undo. Written in the audit log: who switched which zone off or on, and which groups of options were changed (never the lists). The options call needs the token's user to have **Zones: Modify** (and, as the documentation words it, **Zone: Delete** on that zone). **Not verified against a live install.**
- **Deleting a zone** (DNS page → open the zone → **Delete zone**, administrators only): the zone **and every record in it** go, for good — `POST /api/zones/delete` with the zone's name. The zone's name has to be typed, and the server checks it again: it must be the name the zone has now and the provider must list the zone, so a page that is minutes old, a wrong id, or one of the server's own internal zones (which are not listed) cannot be deleted by mistake; an id that is not a zone name as written (lower case, no trailing dot) is refused. What this app has cached of the zone and its records is dropped with it (the registration of the domain on the *Domain names* tab is not touched). What Technitium says when it refuses — a token that may not delete zones — is shown, and then nothing is changed here. It is written in the audit log (who deleted which zone, and how many of its records were cached). **Not verified against a live install**: the calls are as Technitium's API documentation has them.
- **Required access:** A token tied to a Technitium user account with **Zones: View + Modify** permission — view-only will fail on record changes (updates are add/delete calls under the hood) and on making a zone. **Deleting a zone** needs **Zones: Delete**, which is a permission of its own.
- **This is the DNS provider** (zones and records, on the DNS page). How the *server* is doing — queries, blocking, zone health, a real DNS test, alerts — is a separate integration with its own token: see [Technitium DNS](#technitium-dns) under the integrations above.
+1 -1
View File
@@ -80,7 +80,7 @@ All modules from the original plan are built:
DNS, cPanel, and Technitium; providers are configured in-app (not via env
vars) and their credentials are encrypted at rest. On a Technitium provider an
administrator can also **make a zone** (Primary, Secondary or Forwarder — a name, or a
network for a reverse zone) and **delete** one (its name typed to confirm; every record in it goes), and
network for a reverse zone) **edit** one (switch it off and on; who may ask it, copy it, and be told when it changes) and **delete** one (its name typed to confirm; every record in it goes), and
Technitium's own refusal (a zone that exists, a token that may not delete) is shown as it was said
- **Servers** — cron/systemd tracking across Debian/Raspbian servers via a
lightweight push agent (`agent/linux/`), Windows scheduled-task tracking
+1 -1
View File
@@ -108,7 +108,7 @@ even further, to admin only:
- **Integrations & DNS providers**: any operator can use an integration
once it's configured (start/stop a guest, run a template, sync DNS
records, etc.), but adding, editing, testing, or deleting an
integration or DNS provider is admin-only. So is **making or deleting a zone** on a DNS provider that can (Technitium): making one makes the server an authority for a name, and deleting one takes every record in it, so neither is an operator's job like adding a record.
integration or DNS provider is admin-only. So is **making, editing or deleting a zone** on a DNS provider that can (Technitium): making one makes the server an authority for a name, deleting one takes every record in it, and editing one switches it off or changes who may ask or copy it, so none is an operator's job like adding a record.
- **Servers**: registering a new server, rotating its agent token, and
editing/deleting a server are admin-only; tagging a server and
linking/unlinking it to a Proxmox guest just need operator.
+57 -3
View File
@@ -7,9 +7,12 @@
*
* Making a zone is `/api/zones/create` (permission "Zones: Modify"): the name and the type, and for a Secondary zone its primary servers, for a Forwarder zone the address to pass questions to, the
* protocol to use and whether to validate DNSSEC. It answers with the name of the zone it made (`response.domain` — for a reverse zone the …arpa name). Deleting one is `/api/zones/delete` with the
* zone's name (permission "Zones: Delete", which is not the one for changing records): the zone and every record in it go. Neither is checked against a live server.
* zone's name (permission "Zones: Delete", which is not the one for changing records): the zone and every record in it go. A zone is switched off and on with `/api/zones/disable` and
* `/api/zones/enable`, and its options are read with `/api/zones/options/get` and changed with `/api/zones/options/set` — query access, zone transfer and notify here. None of them is
* checked against a live server.
*/
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone, NewDnsZone } from "../types.js";
import type { DnsZoneOptions, ZoneOptionsChange } from "../zoneOptions.js";
import { withDiagLogging } from "../../services/diagLog.js";
export interface TechnitiumConfig {
@@ -118,10 +121,61 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
await apiPost("/api/zones/delete", { zone: zoneId });
}
const list = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);
const text = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
/** What the options call says that this app does not edit, by name, as JSON — so that an edit can be seen not to have changed it. What changes by itself (failed notifications) is left out. */
const NOT_COMPARED = new Set(["name", "type", "internal", "disabled", "queryAccess", "queryAccessNetworkACL", "zoneTransfer", "zoneTransferNetworkACL", "zoneTransferTsigKeyNames", "notify", "notifyNameServers", "availableTsigKeyNames", "availableCatalogZoneNames", "notifyFailed", "notifyFailedFor"]);
async function getZoneOptions(zoneId: string): Promise<DnsZoneOptions> {
const r = await apiGet("/api/zones/options/get", { zone: zoneId, includeAvailableTsigKeyNames: "true", includeAvailableCatalogZoneNames: "false" });
if (r === null || typeof r !== "object" || typeof r.name !== "string") throw new Error("Technitium did not say how that zone is set");
const other: Record<string, string> = {};
for (const [k, v] of Object.entries(r)) if (!NOT_COMPARED.has(k)) other[k] = JSON.stringify(v) ?? "null";
return {
name: r.name,
type: text(r.type) ?? "",
internal: r.internal === true,
disabled: r.disabled === true,
queryAccess: text(r.queryAccess),
queryAccessNetworkACL: list(r.queryAccessNetworkACL),
zoneTransfer: text(r.zoneTransfer),
zoneTransferNetworkACL: list(r.zoneTransferNetworkACL),
zoneTransferTsigKeyNames: list(r.zoneTransferTsigKeyNames),
notify: text(r.notify),
notifyNameServers: list(r.notifyNameServers),
availableTsigKeyNames: list(r.availableTsigKeyNames),
other,
};
}
async function setZoneEnabled(zoneId: string, enabled: boolean): Promise<void> {
await apiPost(enabled ? "/api/zones/enable" : "/api/zones/disable", { zone: zoneId });
}
async function setZoneOptions(zoneId: string, c: ZoneOptionsChange): Promise<void> {
const params: Record<string, string> = { zone: zoneId };
if (c.queryAccess !== undefined) {
params.queryAccess = c.queryAccess;
if (c.queryAccessNetworkACL) params.queryAccessNetworkACL = c.queryAccessNetworkACL.join(",");
}
if (c.zoneTransfer !== undefined) {
params.zoneTransfer = c.zoneTransfer;
if (c.zoneTransferNetworkACL) params.zoneTransferNetworkACL = c.zoneTransferNetworkACL.join(",");
}
// Technitium clears a list with the word false.
if (c.zoneTransferTsigKeyNames !== undefined) params.zoneTransferTsigKeyNames = c.zoneTransferTsigKeyNames.length > 0 ? c.zoneTransferTsigKeyNames.join(",") : "false";
if (c.notify !== undefined) {
params.notify = c.notify;
if (c.notifyNameServers) params.notifyNameServers = c.notifyNameServers.join(",");
}
await apiPost("/api/zones/options/set", params);
}
async function listZones(): Promise<DnsZone[]> {
const resp = await apiGet("/api/zones/list");
const zones = resp?.zones ?? [];
return zones.filter((z: any) => !z.internal).map((z: any) => ({ id: z.name, name: z.name }));
return zones.filter((z: any) => !z.internal).map((z: any) => ({ id: z.name, name: z.name, type: typeof z.type === "string" ? z.type : undefined, disabled: z.disabled === true }));
}
async function listRecords(zone: string): Promise<DnsRecord[]> {
@@ -171,5 +225,5 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
await apiPost("/api/zones/records/delete", { domain: name, zone, type, ...typeParams });
}
return withDiagLogging("technitium", { listZones, createZone, deleteZone, listRecords, addRecord, updateRecord, deleteRecord });
return withDiagLogging("technitium", { listZones, createZone, deleteZone, getZoneOptions, setZoneEnabled, setZoneOptions, listRecords, addRecord, updateRecord, deleteRecord });
}
+3
View File
@@ -13,6 +13,9 @@ export const ZONE_CREATING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<Dns
/** The kinds of provider whose adapter can delete a zone: the page offers "Delete zone" for these, and the route refuses it for the others. */
export const ZONE_DELETING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<DnsProviderType>(["technitium"]);
/** The kinds of provider whose zones can be switched off and on and have their options edited. */
export const ZONE_EDITING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<DnsProviderType>(["technitium"]);
export function createDnsAdapter(providerType: DnsProviderType, config: DnsProviderConfig): DnsAdapter {
switch (providerType) {
case "cloudflare":
+12
View File
@@ -1,6 +1,12 @@
import type { DnsZoneOptions, ZoneOptionsChange } from "./zoneOptions.js";
export interface DnsZone {
id: string;
name: string;
/** What kind of zone it is (Technitium: Primary, Secondary, Forwarder …), when the provider says. */
type?: string;
/** Switched off, when the provider says. */
disabled?: boolean;
}
export interface DnsRecord {
@@ -34,6 +40,12 @@ export interface DnsAdapter {
createZone?(zone: NewDnsZone): Promise<DnsZone>;
/** Only for a provider that can delete a zone (ZONE_DELETING_PROVIDERS in registry.ts): the zone and every record in it are gone. */
deleteZone?(zoneId: string): Promise<void>;
/** Only for a provider whose zones can be edited (ZONE_EDITING_PROVIDERS in registry.ts): how the zone is set now. */
getZoneOptions?(zoneId: string): Promise<DnsZoneOptions>;
/** Switches a zone on or off; its records stay. */
setZoneEnabled?(zoneId: string, enabled: boolean): Promise<void>;
/** Changes the options named (each group whole — see zoneOptions.ts). */
setZoneOptions?(zoneId: string, change: ZoneOptionsChange): Promise<void>;
listRecords(zoneId: string): Promise<DnsRecord[]>;
addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord>;
updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord>;
+152
View File
@@ -0,0 +1,152 @@
/**
* A zone's options as far as this app edits them — who may ask the zone (query access), who may copy it (zone transfer) and who is told when it changes (notify) — and how an edit of them is
* checked and planned. Pure: nothing here talks to a provider. The values are Technitium's own words for them; the plan is only what has to be sent for what differs from the zone now.
*
* A group of options is sent whole (its mode and what the mode uses — the network list, the servers) or not at all, because what Technitium does with a parameter that is left out of a call is
* not documented: what is not changed is not mentioned.
*/
import * as net from "node:net";
export const QUERY_ACCESS = ["Deny", "Allow", "AllowOnlyPrivateNetworks", "AllowOnlyZoneNameServers", "UseSpecifiedNetworkACL", "AllowZoneNameServersAndUseSpecifiedNetworkACL"] as const;
export type QueryAccess = (typeof QUERY_ACCESS)[number];
export const ZONE_TRANSFER = ["Deny", "Allow", "AllowOnlyZoneNameServers", "UseSpecifiedNetworkACL", "AllowZoneNameServersAndUseSpecifiedNetworkACL"] as const;
export type ZoneTransfer = (typeof ZONE_TRANSFER)[number];
export const NOTIFY_MODES = ["None", "ZoneNameServers", "SpecifiedNameServers", "BothZoneAndSpecifiedNameServers"] as const;
export type NotifyMode = (typeof NOTIFY_MODES)[number];
/** Whether a mode goes by a list of networks, which then has to be given. */
export const usesAcl = (mode: string): boolean => mode === "UseSpecifiedNetworkACL" || mode === "AllowZoneNameServersAndUseSpecifiedNetworkACL";
/** Whether a notify mode goes by a list of servers, which then has to be given. */
export const usesNameServers = (mode: string): boolean => mode === "SpecifiedNameServers" || mode === "BothZoneAndSpecifiedNameServers";
/** What an edit asks for. Anything left out is not asked to change. */
export interface ZoneOptionsChange {
queryAccess?: QueryAccess;
queryAccessNetworkACL?: string[];
zoneTransfer?: ZoneTransfer;
zoneTransferNetworkACL?: string[];
zoneTransferTsigKeyNames?: string[];
notify?: NotifyMode;
notifyNameServers?: string[];
}
/** A zone's options as the provider has them now. `other` is everything else it says about the zone (as JSON text, by name), kept only to see that an edit did not change what it did not mean to. */
export interface DnsZoneOptions {
name: string;
type: string;
/** One of the server's own zones: not edited from here. */
internal: boolean;
disabled: boolean;
queryAccess: string | null;
queryAccessNetworkACL: string[];
zoneTransfer: string | null;
zoneTransferNetworkACL: string[];
zoneTransferTsigKeyNames: string[];
notify: string | null;
notifyNameServers: string[];
/** The TSIG keys the server has, which a zone transfer may be limited to. */
availableTsigKeyNames: string[];
other: Record<string, string>;
}
/** A network list entry — an address or a network in CIDR form, with a `!` in front to deny it — as it is to be sent; null when it is not one. */
export function aclEntry(input: string): string | null {
const s = input.trim();
const deny = s.startsWith("!");
const m = /^([0-9a-fA-F.:]+)(?:\/(\d{1,3}))?$/.exec(deny ? s.slice(1).trim() : s);
if (!m) return null;
const v4 = net.isIPv4(m[1]);
if (!v4 && !net.isIPv6(m[1])) return null;
if (m[2] !== undefined && Number(m[2]) > (v4 ? 32 : 128)) return null;
return `${deny ? "!" : ""}${m[1].toLowerCase()}${m[2] !== undefined ? `/${m[2]}` : ""}`;
}
const sameInOrder = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
const sameAsSet = (a: string[], b: string[]) => sameInOrder([...a].sort(), [...b].sort());
export type OptionsPlan = { send: ZoneOptionsChange; changed: ("queryAccess" | "zoneTransfer" | "notify")[] } | { error: string };
/**
* What has to be sent to make a zone of this type have what was asked, from what it has now: only the groups that differ, each whole. An error says what is wrong with the ask: an option the
* kind of zone does not have, a mode that needs a list and has none, an entry that is not an address or network, a key the server does not have. No change is not an error: `changed` is empty.
*/
export function planOptionsChange(type: string, current: DnsZoneOptions, wanted: ZoneOptionsChange): OptionsPlan {
const send: ZoneOptionsChange = {};
const changed: ("queryAccess" | "zoneTransfer" | "notify")[] = [];
const takesQuery = type !== "SecondaryCatalog";
const takesTransferAndNotify = type === "Primary" || type === "Secondary";
const acl = (list: string[] | undefined, fallback: string[], what: string): string[] | string => {
const out: string[] = [];
for (const raw of list ?? fallback) {
const e = aclEntry(raw);
if (e === null) return `"${raw}" is not an address or a network (for example 192.168.1.0/24, or !10.0.0.5 to refuse one).`;
out.push(e);
}
return out.length > 0 ? out : `${what} goes by a list of networks, and the list is empty.`;
};
if (wanted.queryAccess !== undefined || wanted.queryAccessNetworkACL !== undefined) {
if (!takesQuery) return { error: `A ${type} zone has no query access to set.` };
const mode = wanted.queryAccess ?? current.queryAccess;
if (mode === null) return { error: "The zone's query access is not known, so it is not changed from here." };
let list: string[] = [];
if (usesAcl(mode)) {
const r = acl(wanted.queryAccessNetworkACL, current.queryAccessNetworkACL, "Query access");
if (typeof r === "string") return { error: r };
list = r;
}
if (mode !== current.queryAccess || (usesAcl(mode) && !sameInOrder(list, current.queryAccessNetworkACL))) {
send.queryAccess = mode as QueryAccess;
if (usesAcl(mode)) send.queryAccessNetworkACL = list;
changed.push("queryAccess");
}
}
if (wanted.zoneTransfer !== undefined || wanted.zoneTransferNetworkACL !== undefined || wanted.zoneTransferTsigKeyNames !== undefined) {
if (!takesTransferAndNotify) return { error: `A ${type} zone has no zone transfer to set.` };
const mode = wanted.zoneTransfer ?? current.zoneTransfer;
if (mode === null) return { error: "The zone's transfer setting is not known, so it is not changed from here." };
let list: string[] = [];
if (usesAcl(mode)) {
const r = acl(wanted.zoneTransferNetworkACL, current.zoneTransferNetworkACL, "Zone transfer");
if (typeof r === "string") return { error: r };
list = r;
}
const keys = wanted.zoneTransferTsigKeyNames ?? current.zoneTransferTsigKeyNames;
const unknown = keys.find((k) => !current.availableTsigKeyNames.includes(k));
if (unknown !== undefined) return { error: `The server has no TSIG key called "${unknown}".` };
if (mode !== current.zoneTransfer || (usesAcl(mode) && !sameInOrder(list, current.zoneTransferNetworkACL)) || !sameAsSet(keys, current.zoneTransferTsigKeyNames)) {
send.zoneTransfer = mode as ZoneTransfer;
if (usesAcl(mode)) send.zoneTransferNetworkACL = list;
send.zoneTransferTsigKeyNames = keys;
changed.push("zoneTransfer");
}
}
if (wanted.notify !== undefined || wanted.notifyNameServers !== undefined) {
if (!takesTransferAndNotify) return { error: `A ${type} zone has no notify setting to set here.` };
const mode = wanted.notify ?? current.notify;
if (mode === null) return { error: "The zone's notify setting is not known, so it is not changed from here." };
let servers: string[] = [];
if (usesNameServers(mode)) {
servers = (wanted.notifyNameServers ?? current.notifyNameServers).map((s) => s.trim());
if (servers.length === 0) return { error: "Notify goes to named servers, and none is named." };
const bad = servers.find((s) => net.isIP(s) === 0);
if (bad !== undefined) return { error: `"${bad}" is not an address of a server to notify.` };
}
if (mode !== current.notify || (usesNameServers(mode) && !sameAsSet(servers, current.notifyNameServers))) {
send.notify = mode as NotifyMode;
if (usesNameServers(mode)) send.notifyNameServers = servers;
changed.push("notify");
}
}
return { send, changed };
}
/** The things the zone says that an edit did not mean to change but did — by comparing what it said (`other`) before and after. Empty when nothing else moved. */
export function unexpectedChanges(before: DnsZoneOptions, after: DnsZoneOptions): string[] {
const names = new Set([...Object.keys(before.other), ...Object.keys(after.other)]);
return [...names].filter((n) => before.other[n] !== after.other[n]).sort();
}
+111 -3
View File
@@ -1,4 +1,4 @@
import { Router } from "express";
import { Router, type Request, type Response } from "express";
import { eq, and } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
@@ -11,7 +11,8 @@ import {
splitProviderConfig,
validateProviderConfig,
} from "../dns/providerSchemas.js";
import { createDnsAdapter, ZONE_CREATING_PROVIDERS, ZONE_DELETING_PROVIDERS } from "../dns/registry.js";
import { createDnsAdapter, ZONE_CREATING_PROVIDERS, ZONE_DELETING_PROVIDERS, ZONE_EDITING_PROVIDERS } from "../dns/registry.js";
import { NOTIFY_MODES, planOptionsChange, QUERY_ACCESS, unexpectedChanges, ZONE_TRANSFER, type DnsZoneOptions } from "../dns/zoneOptions.js";
import { normaliseZoneName } from "../dns/zoneNames.js";
import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js";
import { getDnsStats } from "../dns/stats.js";
@@ -56,7 +57,7 @@ dnsRouter.get("/providers", asyncHandler(async (_req, res) => {
createdAt: dnsProviders.createdAt,
})
.from(dnsProviders);
res.json({ providers: rows.map((r) => ({ ...r, canCreateZones: ZONE_CREATING_PROVIDERS.has(r.providerType), canDeleteZones: ZONE_DELETING_PROVIDERS.has(r.providerType) })) });
res.json({ providers: rows.map((r) => ({ ...r, canCreateZones: ZONE_CREATING_PROVIDERS.has(r.providerType), canDeleteZones: ZONE_DELETING_PROVIDERS.has(r.providerType), canEditZones: ZONE_EDITING_PROVIDERS.has(r.providerType) })) });
}));
const configValueSchema = z.union([z.string(), z.boolean()]);
@@ -331,6 +332,113 @@ dnsRouter.post("/providers/:id/zones", requireRole("admin"), asyncHandler(async
}
}));
/** The provider and the zone an edit is about, or the answer to send when it cannot be: an id that is no zone name, a provider that is not there, is switched off or cannot edit zones. */
async function loadEditableZone(req: Request, res: Response) {
const providerId = /^\d+$/.test(req.params.id) ? Number(req.params.id) : Number.NaN;
const zoneId = req.params.zoneId;
if (!Number.isInteger(providerId) || normaliseZoneName(zoneId) !== zoneId) {
res.status(400).json({ error: "invalid_id" });
return null;
}
const found = await getDnsAdapterForProvider(providerId);
if (!found) {
res.status(404).json({ error: "not_found" });
return null;
}
if (!found.provider.enabled) {
res.status(400).json({ error: "provider_disabled", message: "This provider is switched off." });
return null;
}
const { adapter } = found;
if (!ZONE_EDITING_PROVIDERS.has(found.provider.providerType) || !adapter.getZoneOptions || !adapter.setZoneEnabled || !adapter.setZoneOptions) {
res.status(400).json({ error: "not_supported", message: "Zones can't be edited from here on this kind of provider." });
return null;
}
return { providerId, zoneId, adapter: adapter as typeof adapter & Required<Pick<typeof adapter, "getZoneOptions" | "setZoneEnabled" | "setZoneOptions">> };
}
/** What the page is told of a zone's options: not what is only kept to see that an edit changed nothing else. */
const publicOptions = ({ other: _other, ...options }: DnsZoneOptions) => options;
const providerFailure = (res: Response, err: unknown) => res.status(502).json({ error: "dns_provider_error", message: err instanceof Error ? err.message : String(err) });
/** How a zone is set now — query access, zone transfer and notify, and whether it is switched off — and which TSIG keys the server has. An administrator's: the lists name networks. */
dnsRouter.get("/providers/:id/zones/:zoneId/options", requireRole("admin"), asyncHandler(async (req, res) => {
const ctx = await loadEditableZone(req, res);
if (!ctx) return;
try {
res.json({ options: publicOptions(await ctx.adapter.getZoneOptions(ctx.zoneId)) });
} catch (err) {
providerFailure(res, err);
}
}));
const enabledSchema = z.object({ enabled: z.boolean() });
/** Switches a zone off or on again. Off, the server no longer answers for the zone; its records stay, and on brings it all back. One of the server's own zones is not touched. */
dnsRouter.post("/providers/:id/zones/:zoneId/enabled", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = enabledSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say whether the zone is to be on or off." });
const ctx = await loadEditableZone(req, res);
if (!ctx) return;
try {
const options = await ctx.adapter.getZoneOptions(ctx.zoneId);
if (options.internal) return res.status(409).json({ error: "refused", message: "That is one of the server's own zones." });
if (options.disabled === !parsed.data.enabled) return res.json({ enabled: parsed.data.enabled, changed: false });
await ctx.adapter.setZoneEnabled(ctx.zoneId, parsed.data.enabled);
} catch (err) {
return providerFailure(res, err);
}
await recordAudit({ actor: req.currentUser!, category: "dns", action: parsed.data.enabled ? "enable_zone" : "disable_zone", targetType: "dns_zone", targetId: ctx.zoneId, detail: { providerId: ctx.providerId, name: ctx.zoneId } });
res.json({ enabled: parsed.data.enabled, changed: true });
}));
const aclList = z.array(z.string().trim().min(1).max(80)).max(100);
const optionsChangeSchema = z
.object({
queryAccess: z.enum(QUERY_ACCESS).optional(),
queryAccessNetworkACL: aclList.optional(),
zoneTransfer: z.enum(ZONE_TRANSFER).optional(),
zoneTransferNetworkACL: aclList.optional(),
zoneTransferTsigKeyNames: z.array(z.string().trim().min(1).max(255)).max(50).optional(),
notify: z.enum(NOTIFY_MODES).optional(),
notifyNameServers: z.array(z.string().trim().min(1).max(80)).max(20).optional(),
})
.strict();
/**
* Changes who may ask a zone, who may copy it and who is told when it changes. What is asked is checked against the kind of zone it is and what it has now (see dns/zoneOptions.ts); only the
* groups that differ are sent, each whole. Technitium does not say what it does with a setting that is not mentioned, so afterwards the zone is read again and anything else that moved is said.
* One of the server's own zones is not touched.
*/
dnsRouter.patch("/providers/:id/zones/:zoneId/options", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = optionsChangeSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "That is not a change of a zone's options.", details: parsed.error.flatten() });
const ctx = await loadEditableZone(req, res);
if (!ctx) return;
let before: DnsZoneOptions;
let plan: ReturnType<typeof planOptionsChange>;
try {
before = await ctx.adapter.getZoneOptions(ctx.zoneId);
if (before.internal) return res.status(409).json({ error: "refused", message: "That is one of the server's own zones." });
plan = planOptionsChange(before.type, before, parsed.data);
if ("error" in plan) return res.status(400).json({ error: "invalid_options", message: plan.error });
if (plan.changed.length === 0) return res.json({ changed: [], unexpected: [], options: publicOptions(before) });
await ctx.adapter.setZoneOptions(ctx.zoneId, plan.send);
} catch (err) {
return providerFailure(res, err);
}
let after: DnsZoneOptions | null = null;
try {
after = await ctx.adapter.getZoneOptions(ctx.zoneId);
} catch {
// The change was made; only the read-back failed.
}
const unexpected = after ? unexpectedChanges(before, after) : [];
await recordAudit({ actor: req.currentUser!, category: "dns", action: "update_zone_options", targetType: "dns_zone", targetId: ctx.zoneId, detail: { providerId: ctx.providerId, name: ctx.zoneId, changed: plan.changed, ...(unexpected.length > 0 ? { unexpected } : {}) } });
res.json({ changed: plan.changed, unexpected, options: after ? publicOptions(after) : null });
}));
const deleteZoneSchema = z.object({ name: z.string().min(1).max(300) });
/**
+464
View File
@@ -0,0 +1,464 @@
/**
* Editing a Technitium zone: switching it off and on, and its options (who may ask it, who may copy it, who is told when it changes) — how an edit is checked and planned against the kind of zone
* and what it has now, what is sent to Technitium, what is said when something else moved, who may, what is refused and what is written in the audit log.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer as createHttpServer, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-tn-zopts-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, dnsProviders, integrationCredentials, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js");
const zo = await import("../src/dns/zoneOptions.js");
const { createTechnitiumAdapter } = await import("../src/dns/adapters/technitium.js");
const { dnsRouter } = await import("../src/routes/dns.js");
await runMigrations();
const opts = (over: Partial<import("../src/dns/zoneOptions.js").DnsZoneOptions> = {}): import("../src/dns/zoneOptions.js").DnsZoneOptions => ({
name: "home.lan",
type: "Primary",
internal: false,
disabled: false,
queryAccess: "Allow",
queryAccessNetworkACL: [],
zoneTransfer: "Deny",
zoneTransferNetworkACL: [],
zoneTransferTsigKeyNames: [],
notify: "ZoneNameServers",
notifyNameServers: [],
availableTsigKeyNames: ["key.lan", "catalog"],
other: {},
...over,
});
const plan = (type: string, current: ReturnType<typeof opts>, wanted: import("../src/dns/zoneOptions.js").ZoneOptionsChange) => zo.planOptionsChange(type, current, wanted);
const ok = (p: ReturnType<typeof plan>) => {
assert.ok(!("error" in p), "error" in p ? p.error : "");
return p;
};
const failure = (p: ReturnType<typeof plan>) => {
assert.ok("error" in p, "expected an error");
return (p as { error: string }).error;
};
describe("a network list entry", () => {
test("an address or a network, with ! to refuse it, in the form it is sent", () => {
assert.equal(zo.aclEntry("192.168.1.0/24"), "192.168.1.0/24");
assert.equal(zo.aclEntry(" !10.0.0.5 "), "!10.0.0.5");
assert.equal(zo.aclEntry("FD00::/8"), "fd00::/8");
assert.equal(zo.aclEntry("::1"), "::1");
});
test("anything else is not: text, a network too big for its kind, an empty refusal", () => {
for (const bad of ["", "!", "lan", "192.168.1.0/33", "fd00::/129", "300.1.1.1", "10.0.0.1/", "10.0.0.1,10.0.0.2", "a b"]) assert.equal(zo.aclEntry(bad), null, JSON.stringify(bad));
});
});
describe("what an edit comes to", () => {
test("what is already so is no change, and nothing is sent", () => {
const p = ok(plan("Primary", opts(), { queryAccess: "Allow", zoneTransfer: "Deny", notify: "ZoneNameServers" }));
assert.deepEqual([p.changed, "send" in p ? p.send : null], [[], {}]);
});
test("only the group that differs is sent; a mode that does not go by a list sends none", () => {
const p = ok(plan("Primary", opts({ queryAccessNetworkACL: ["10.0.0.0/8"] }), { queryAccess: "AllowOnlyPrivateNetworks", zoneTransfer: "Deny" }));
assert.deepEqual("send" in p ? p.send : null, { queryAccess: "AllowOnlyPrivateNetworks" });
assert.deepEqual(p.changed, ["queryAccess"]);
});
test("a mode that goes by a list needs the list, written as addresses and networks", () => {
assert.match(failure(plan("Primary", opts(), { queryAccess: "UseSpecifiedNetworkACL" })), /list of networks, and the list is empty/);
assert.match(failure(plan("Primary", opts(), { queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["home"] })), /"home" is not an address or a network/);
const p = ok(plan("Primary", opts(), { queryAccess: "AllowZoneNameServersAndUseSpecifiedNetworkACL", queryAccessNetworkACL: ["192.168.1.0/24", " !192.168.1.66"] }));
assert.deepEqual("send" in p ? p.send : null, { queryAccess: "AllowZoneNameServersAndUseSpecifiedNetworkACL", queryAccessNetworkACL: ["192.168.1.0/24", "!192.168.1.66"] });
});
test("a list changed under the same mode is a change — in its order, which matters — and the mode is sent with it", () => {
const cur = opts({ queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["10.0.0.0/8", "!10.0.0.5"] });
assert.deepEqual(ok(plan("Primary", cur, { queryAccessNetworkACL: ["10.0.0.0/8", "!10.0.0.5"] })).changed, []);
const swapped = ok(plan("Primary", cur, { queryAccessNetworkACL: ["!10.0.0.5", "10.0.0.0/8"] }));
assert.deepEqual(["send" in swapped ? swapped.send : null, swapped.changed], [{ queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["!10.0.0.5", "10.0.0.0/8"] }, ["queryAccess"]]);
});
test("zone transfer: the keys it is limited to must be ones the server has; they are sent with the mode, and none is a change to none", () => {
assert.match(failure(plan("Primary", opts(), { zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["nope.lan"] })), /no TSIG key called "nope\.lan"/);
const p = ok(plan("Primary", opts(), { zoneTransfer: "AllowOnlyZoneNameServers", zoneTransferTsigKeyNames: ["key.lan"] }));
assert.deepEqual("send" in p ? p.send : null, { zoneTransfer: "AllowOnlyZoneNameServers", zoneTransferTsigKeyNames: ["key.lan"] });
const cleared = ok(plan("Primary", opts({ zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["key.lan", "catalog"] }), { zoneTransferTsigKeyNames: [] }));
assert.deepEqual("send" in cleared ? cleared.send : null, { zoneTransfer: "Allow", zoneTransferTsigKeyNames: [] });
assert.deepEqual(ok(plan("Primary", opts({ zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["key.lan", "catalog"] }), { zoneTransferTsigKeyNames: ["catalog", "key.lan"] })).changed, [], "the order of keys is not a change");
});
test("notify: named servers need addresses; a mode that names none sends none", () => {
assert.match(failure(plan("Primary", opts(), { notify: "SpecifiedNameServers" })), /none is named/);
assert.match(failure(plan("Primary", opts(), { notify: "SpecifiedNameServers", notifyNameServers: ["ns1.lan"] })), /"ns1\.lan" is not an address/);
const p = ok(plan("Primary", opts(), { notify: "BothZoneAndSpecifiedNameServers", notifyNameServers: ["10.0.0.2", "fd00::2"] }));
assert.deepEqual("send" in p ? p.send : null, { notify: "BothZoneAndSpecifiedNameServers", notifyNameServers: ["10.0.0.2", "fd00::2"] });
const none = ok(plan("Primary", opts({ notify: "SpecifiedNameServers", notifyNameServers: ["10.0.0.2"] }), { notify: "None" }));
assert.deepEqual("send" in none ? none.send : null, { notify: "None" });
});
test("what a kind of zone does not have is refused: a Forwarder neither transfers nor notifies here, a secondary catalog has no query access", () => {
assert.match(failure(plan("Forwarder", opts({ type: "Forwarder" }), { zoneTransfer: "Allow" })), /Forwarder zone has no zone transfer/);
assert.match(failure(plan("Forwarder", opts({ type: "Forwarder" }), { notify: "None" })), /Forwarder zone has no notify/);
assert.match(failure(plan("SecondaryCatalog", opts({ type: "SecondaryCatalog" }), { queryAccess: "Deny" })), /no query access/);
assert.deepEqual(ok(plan("Forwarder", opts({ type: "Forwarder" }), { queryAccess: "Deny" })).changed, ["queryAccess"]);
});
test("a zone whose mode the provider did not say is not changed blindly", () => {
assert.match(failure(plan("Primary", opts({ queryAccess: null }), { queryAccessNetworkACL: ["10.0.0.0/8"] })), /not known/);
assert.match(failure(plan("Primary", opts({ notify: null }), { notifyNameServers: ["10.0.0.2"] })), /not known/);
});
test("what else the zone says that moved is named; what did not is not", () => {
const before = opts({ other: { update: '"Deny"', catalog: '"c1"', dnssecStatus: '"Unsigned"' } });
assert.deepEqual(zo.unexpectedChanges(before, opts({ other: { update: '"Deny"', catalog: '"c1"', dnssecStatus: '"Unsigned"' } })), []);
assert.deepEqual(zo.unexpectedChanges(before, opts({ other: { update: '"Allow"', dnssecStatus: '"Unsigned"' } })), ["catalog", "update"]);
});
});
/** A Technitium with a few zones that keeps the options it is given, and can be told to forget something it was not asked to change. */
interface ZoneState {
name: string;
type: string;
internal: boolean;
disabled: boolean;
queryAccess: string;
queryAccessNetworkACL: string[];
zoneTransfer: string;
zoneTransferNetworkACL: string[];
zoneTransferTsigKeyNames: string[];
notify: string;
notifyNameServers: string[];
update: string;
updateNetworkACL: string[];
catalog: string;
notifyFailed: boolean;
}
const fresh = (): Map<string, ZoneState> =>
new Map(
[
["home.lan", "Primary"],
["mirror.lan", "Secondary"],
["corp.example", "Forwarder"],
["localhost", "Primary"],
].map(([name, type]) => [
name,
{ name, type, internal: name === "localhost", disabled: false, queryAccess: "Allow", queryAccessNetworkACL: [], zoneTransfer: "Deny", zoneTransferNetworkACL: [], zoneTransferTsigKeyNames: [], notify: "ZoneNameServers", notifyNameServers: [], update: "UseSpecifiedNetworkACL", updateNetworkACL: ["192.168.180.0/24"], catalog: "catalog1", notifyFailed: false },
]),
);
let zones = fresh();
let forgetUpdates = false;
let refuse: string | null = null;
const seen: { path: string; auth: string; form: Record<string, string> }[] = [];
let fake: Server;
let fakeUrl = "";
before(async () => {
fake = createHttpServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
const u = new URL(req.url ?? "", "http://x");
const form = Object.fromEntries(new URLSearchParams(body));
const query = Object.fromEntries(u.searchParams);
seen.push({ path: u.pathname, auth: String(req.headers.authorization ?? ""), form: { ...query, ...form } });
const send = (json: unknown) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(json));
};
const params = { ...query, ...form };
const zone = zones.get(params.zone ?? "");
if (u.pathname === "/api/zones/list") return send({ status: "ok", response: { zones: [...zones.values()].map((z) => ({ name: z.name, type: z.type, internal: z.internal, disabled: z.disabled })) } });
if (refuse !== null && u.pathname !== "/api/zones/options/get") return send({ status: "error", errorMessage: refuse });
if (!zone) return send({ status: "error", errorMessage: `No such zone was found: ${params.zone}` });
if (u.pathname === "/api/zones/options/get") {
const { name, type, internal, disabled, queryAccess, queryAccessNetworkACL, zoneTransfer, zoneTransferNetworkACL, zoneTransferTsigKeyNames, notify, notifyNameServers, update, updateNetworkACL, catalog, notifyFailed } = zone;
return send({ status: "ok", response: { name, type, internal, disabled, dnssecStatus: "Unsigned", notifyFailed, notifyFailedFor: [], catalog, queryAccess, queryAccessNetworkACL, zoneTransfer, zoneTransferNetworkACL, zoneTransferTsigKeyNames, notify, notifyNameServers, update, updateNetworkACL, availableTsigKeyNames: ["key.lan", "catalog"] } });
}
if (u.pathname === "/api/zones/enable" || u.pathname === "/api/zones/disable") {
zone.disabled = u.pathname.endsWith("/disable");
return send({ status: "ok" });
}
if (u.pathname === "/api/zones/options/set") {
const list = (v: string) => (v === "false" ? [] : v.split(","));
if (params.queryAccess !== undefined) zone.queryAccess = params.queryAccess;
if (params.queryAccessNetworkACL !== undefined) zone.queryAccessNetworkACL = list(params.queryAccessNetworkACL);
if (params.zoneTransfer !== undefined) zone.zoneTransfer = params.zoneTransfer;
if (params.zoneTransferNetworkACL !== undefined) zone.zoneTransferNetworkACL = list(params.zoneTransferNetworkACL);
if (params.zoneTransferTsigKeyNames !== undefined) zone.zoneTransferTsigKeyNames = list(params.zoneTransferTsigKeyNames);
if (params.notify !== undefined) zone.notify = params.notify;
if (params.notifyNameServers !== undefined) zone.notifyNameServers = list(params.notifyNameServers);
// A server that sets what it is not told to back to its default.
if (forgetUpdates) {
zone.update = "Deny";
zone.updateNetworkACL = [];
}
return send({ status: "ok" });
}
res.writeHead(404);
res.end("{}");
});
});
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
});
after(() => {
fake.close();
});
const reset = () => {
zones = fresh();
forgetUpdates = false;
refuse = null;
seen.length = 0;
};
describe("what is sent to Technitium", () => {
const adapter = () => createTechnitiumAdapter({ url: `${fakeUrl}/`, token: "tok-1" });
test("the options are read with the token in the header, asking which TSIG keys there are; what the server says that is not edited is kept aside", async () => {
reset();
const o = await adapter().getZoneOptions!("home.lan");
assert.deepEqual(seen[0].path, "/api/zones/options/get");
assert.deepEqual([seen[0].auth, seen[0].form], ["Bearer tok-1", { zone: "home.lan", includeAvailableTsigKeyNames: "true", includeAvailableCatalogZoneNames: "false" }]);
assert.deepEqual([o.name, o.type, o.internal, o.disabled, o.queryAccess, o.zoneTransfer, o.notify, o.availableTsigKeyNames], ["home.lan", "Primary", false, false, "Allow", "Deny", "ZoneNameServers", ["key.lan", "catalog"]]);
assert.deepEqual(Object.keys(o.other).sort(), ["catalog", "dnssecStatus", "update", "updateNetworkACL"]);
assert.equal(o.other.updateNetworkACL, '["192.168.180.0/24"]');
});
test("a zone is switched off and on with its own two calls", async () => {
reset();
await adapter().setZoneEnabled!("home.lan", false);
assert.deepEqual([seen[0].path, seen[0].form], ["/api/zones/disable", { zone: "home.lan" }]);
assert.equal(zones.get("home.lan")!.disabled, true);
await adapter().setZoneEnabled!("home.lan", true);
assert.equal(seen[1].path, "/api/zones/enable");
assert.equal(zones.get("home.lan")!.disabled, false);
});
test("the options go as the parameters Technitium names, lists comma-separated; a list of none is the word false", async () => {
reset();
await adapter().setZoneOptions!("home.lan", {
queryAccess: "UseSpecifiedNetworkACL",
queryAccessNetworkACL: ["10.0.0.0/8", "!10.0.0.5"],
zoneTransfer: "Allow",
zoneTransferTsigKeyNames: [],
notify: "SpecifiedNameServers",
notifyNameServers: ["10.0.0.2", "10.0.0.3"],
});
assert.deepEqual(seen[0].form, {
zone: "home.lan",
queryAccess: "UseSpecifiedNetworkACL",
queryAccessNetworkACL: "10.0.0.0/8,!10.0.0.5",
zoneTransfer: "Allow",
zoneTransferTsigKeyNames: "false",
notify: "SpecifiedNameServers",
notifyNameServers: "10.0.0.2,10.0.0.3",
});
});
test("the zone list says which are switched off and what kind they are", async () => {
reset();
zones.get("mirror.lan")!.disabled = true;
const list = await adapter().listZones();
assert.deepEqual(list.map((z) => [z.id, z.type, z.disabled]), [["home.lan", "Primary", false], ["mirror.lan", "Secondary", true], ["corp.example", "Forwarder", false]]);
});
test("what Technitium says when it refuses is the error", async () => {
reset();
refuse = "Access was denied to use Zones: Modify";
await assert.rejects(() => adapter().setZoneOptions!("home.lan", { queryAccess: "Deny" }), /Access was denied/);
await assert.rejects(() => adapter().setZoneEnabled!("home.lan", false), /Access was denied/);
});
});
describe("the routes", () => {
let app: Server;
let base = "";
let technitium = 0;
let disabled = 0;
let cloudflare = 0;
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
const getOptions = (id: number, zone: string, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}/options`, { headers: as(sub) });
const patch = (id: number, zone: string, body: unknown, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}/options`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
const enable = (id: number, zone: string, enabled: unknown, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}/enabled`, { method: "POST", headers: as(sub), body: JSON.stringify({ enabled }) });
const writes = () => seen.filter((s) => /\/(set|enable|disable)$/.test(s.path));
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Alma", role: "admin" },
{ oidcSub: "operator", name: "Olle", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
const cred = (await db.insert(integrationCredentials).values({ name: "dns:technitium", encryptedSecret: encryptSecret(JSON.stringify({ token: "tok-route" })) }).returning({ id: integrationCredentials.id }))[0];
const config = JSON.stringify({ url: fakeUrl });
technitium = (await db.insert(dnsProviders).values({ providerType: "technitium", name: "Home DNS", credentialId: cred.id, config }).returning({ id: dnsProviders.id }))[0].id;
disabled = (await db.insert(dnsProviders).values({ providerType: "technitium", name: "Old DNS", credentialId: cred.id, config, enabled: false }).returning({ id: dnsProviders.id }))[0].id;
cloudflare = (await db.insert(dnsProviders).values({ providerType: "cloudflare", name: "Cloudflare", config: "{}" }).returning({ id: dnsProviders.id }))[0].id;
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
next();
});
a.use("/api/dns", dnsRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/dns`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("the providers say which can edit zones", async () => {
const body = (await (await fetch(`${base}/providers`, { headers: as("viewer") })).json()) as { providers: { id: number; canEditZones: boolean }[] };
const can = Object.fromEntries(body.providers.map((p) => [p.id, p.canEditZones]));
assert.deepEqual([can[technitium], can[disabled], can[cloudflare]], [true, true, false]);
});
test("only an administrator reads or changes a zone's options or switches it; nothing reaches Technitium for anyone else", async () => {
reset();
for (const sub of ["viewer", "operator"]) {
assert.equal((await getOptions(technitium, "home.lan", sub)).status, 403, sub);
assert.equal((await patch(technitium, "home.lan", { queryAccess: "Deny" }, sub)).status, 403, sub);
assert.equal((await enable(technitium, "home.lan", false, sub)).status, 403, sub);
}
assert.deepEqual(seen, []);
});
test("the options a zone has now, without what is only kept aside", async () => {
reset();
const res = await getOptions(technitium, "home.lan");
assert.equal(res.status, 200);
const { options } = (await res.json()) as { options: Record<string, unknown> };
assert.deepEqual([options.name, options.type, options.queryAccess, options.availableTsigKeyNames], ["home.lan", "Primary", "Allow", ["key.lan", "catalog"]]);
assert.equal("other" in options, false);
});
test("switching a zone off and on: Technitium is asked, the audit log says who, and what is already so asks nothing", async () => {
reset();
const off = await enable(technitium, "home.lan", false);
assert.deepEqual(await off.json(), { enabled: false, changed: true });
assert.equal(zones.get("home.lan")!.disabled, true);
assert.deepEqual(writes().map((s) => s.path), ["/api/zones/disable"]);
const again = await enable(technitium, "home.lan", false);
assert.deepEqual(await again.json(), { enabled: false, changed: false });
assert.equal(writes().length, 1);
assert.deepEqual(await (await enable(technitium, "home.lan", true)).json(), { enabled: true, changed: true });
const entries = await audit("disable_zone");
assert.deepEqual([entries.length, entries[0].category, entries[0].targetType, entries[0].targetId], [1, "dns", "dns_zone", "home.lan"]);
assert.equal((await audit("enable_zone")).length, 1);
});
test("the server's own zones, a zone that is not there and a body that does not say on or off are not switched", async () => {
reset();
assert.equal((await enable(technitium, "localhost", false)).status, 409);
assert.equal((await enable(technitium, "nothere.lan", false)).status, 502, "Technitium's own words for it");
assert.equal((await enable(technitium, "home.lan", "yes")).status, 400);
assert.deepEqual(writes(), []);
});
test("an edit sends the group that differs, whole, and answers with the zone as it is now; the audit log names what changed", async () => {
reset();
const res = await patch(technitium, "home.lan", { queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["10.0.0.0/8", " !10.0.0.5"], zoneTransfer: "Deny" });
assert.equal(res.status, 200);
const body = (await res.json()) as { changed: string[]; unexpected: string[]; options: { queryAccess: string; queryAccessNetworkACL: string[] } };
assert.deepEqual([body.changed, body.unexpected, body.options.queryAccess, body.options.queryAccessNetworkACL], [["queryAccess"], [], "UseSpecifiedNetworkACL", ["10.0.0.0/8", "!10.0.0.5"]]);
assert.deepEqual(writes().map((s) => s.form), [{ zone: "home.lan", queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: "10.0.0.0/8,!10.0.0.5" }]);
const [entry] = await audit("update_zone_options");
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { providerId: technitium, name: "home.lan", changed: ["queryAccess"] });
});
test("an edit that changes nothing sends nothing and writes nothing", async () => {
reset();
const before = (await audit("update_zone_options")).length;
const res = await patch(technitium, "home.lan", { queryAccess: "Allow", notify: "ZoneNameServers" });
assert.deepEqual(((await res.json()) as { changed: string[] }).changed, []);
assert.deepEqual(writes(), []);
assert.equal((await audit("update_zone_options")).length, before);
});
test("if the server also changed something that was not asked, the answer and the audit log say so", async () => {
reset();
forgetUpdates = true;
const res = await patch(technitium, "home.lan", { notify: "None" });
assert.equal(res.status, 200);
const body = (await res.json()) as { changed: string[]; unexpected: string[] };
assert.deepEqual([body.changed, body.unexpected], [["notify"], ["update", "updateNetworkACL"]]);
const entries = await audit("update_zone_options");
assert.deepEqual(JSON.parse(entries.at(-1)!.detail ?? "{}").unexpected, ["update", "updateNetworkACL"]);
});
test("what is wrong with an edit is said before anything is sent: a kind of zone, a missing list, a key or a field that does not exist, a value that is no mode", async () => {
reset();
const bad: [string, unknown][] = [
["corp.example", { zoneTransfer: "Allow" }],
["corp.example", { notify: "None" }],
["home.lan", { queryAccess: "UseSpecifiedNetworkACL" }],
["home.lan", { queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["lan"] }],
["home.lan", { zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["nope"] }],
["home.lan", { notify: "SpecifiedNameServers", notifyNameServers: [] }],
["home.lan", { queryAccess: "Everyone" }],
["home.lan", { notify: "SeparateNameServersForCatalogAndMemberZones" }],
["home.lan", { disabled: true }],
["home.lan", { queryAccessNetworkACL: "10.0.0.0/8" }],
];
for (const [zone, body] of bad) {
const res = await patch(technitium, zone, body);
assert.equal(res.status, 400, JSON.stringify([zone, body]));
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
}
assert.deepEqual(writes(), []);
});
test("a Forwarder's query access can be changed; a zone name that is not written as one, and the server's own zones, are refused", async () => {
reset();
assert.equal((await patch(technitium, "corp.example", { queryAccess: "Deny" })).status, 200);
assert.equal(zones.get("corp.example")!.queryAccess, "Deny");
for (const bad of ["Home.LAN", "home.lan.", "a b", "a/b"]) assert.equal((await patch(technitium, bad, { queryAccess: "Deny" })).status, 400, bad);
assert.equal((await patch(technitium, "localhost", { queryAccess: "Deny" })).status, 409);
assert.equal(zones.get("localhost")!.queryAccess, "Allow");
});
test("what Technitium says when it refuses is passed on, and nothing is written in the audit log", async () => {
reset();
const before = (await audit("update_zone_options")).length;
refuse = "Access was denied to use Zones: Modify";
const res = await patch(technitium, "home.lan", { queryAccess: "Deny" });
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /Access was denied/);
assert.equal((await audit("update_zone_options")).length, before);
});
test("a provider that cannot edit zones, a switched-off one, an unknown one and an id that is no id are not asked", async () => {
reset();
const unsupported = await patch(cloudflare, "home.lan", { queryAccess: "Deny" });
assert.equal(((await unsupported.json()) as { error: string }).error, "not_supported");
assert.equal(((await (await patch(disabled, "home.lan", { queryAccess: "Deny" })).json()) as { error: string }).error, "provider_disabled");
assert.equal((await patch(999999, "home.lan", { queryAccess: "Deny" })).status, 404);
assert.equal((await fetch(`${base}/providers/abc/zones/home.lan/options`, { headers: as("admin") })).status, 400);
assert.deepEqual(seen, []);
});
});
+37
View File
@@ -679,6 +679,8 @@ export interface DnsProviderSummary {
canCreateZones: boolean;
/** Whether zones can be deleted on it from here (Technitium). */
canDeleteZones: boolean;
/** Whether zones can be switched off and on and their options edited from here (Technitium). */
canEditZones: boolean;
}
/** A zone to be made: a Primary one, a Secondary one from the servers that hold it, or a Forwarder one that passes questions on. */
@@ -692,6 +694,37 @@ export interface DnsZone {
name: string;
syncedAt: string | null;
recordCount: number;
/** Primary, Secondary, Forwarder … when the provider says. */
type?: string;
/** Switched off, when the provider says. */
disabled?: boolean;
}
/** How a zone is set now (Technitium): whether it is on, who may ask it, who may copy it, who is told when it changes. */
export interface DnsZoneOptionsInfo {
name: string;
type: string;
internal: boolean;
disabled: boolean;
queryAccess: string | null;
queryAccessNetworkACL: string[];
zoneTransfer: string | null;
zoneTransferNetworkACL: string[];
zoneTransferTsigKeyNames: string[];
notify: string | null;
notifyNameServers: string[];
availableTsigKeyNames: string[];
}
/** What an edit of a zone's options asks for; what is left out is not asked to change. */
export interface DnsZoneOptionsChange {
queryAccess?: string;
queryAccessNetworkACL?: string[];
zoneTransfer?: string;
zoneTransferNetworkACL?: string[];
zoneTransferTsigKeyNames?: string[];
notify?: string;
notifyNameServers?: string[];
}
export interface DnsRecord {
@@ -3927,6 +3960,10 @@ export const api = {
},
zones: {
list: (providerId: number) => request<{ zones: DnsZone[] }>(`/api/dns/providers/${providerId}/zones`),
options: (providerId: number, zoneId: string) => request<{ options: DnsZoneOptionsInfo }>(`/api/dns/providers/${providerId}/zones/${encodeURIComponent(zoneId)}/options`),
updateOptions: (providerId: number, zoneId: string, change: DnsZoneOptionsChange) =>
request<{ changed: string[]; unexpected: string[]; options: DnsZoneOptionsInfo | null }>(`/api/dns/providers/${providerId}/zones/${encodeURIComponent(zoneId)}/options`, { method: "PATCH", body: JSON.stringify(change) }),
setEnabled: (providerId: number, zoneId: string, enabled: boolean) => request<{ enabled: boolean; changed: boolean }>(`/api/dns/providers/${providerId}/zones/${encodeURIComponent(zoneId)}/enabled`, { method: "POST", body: JSON.stringify({ enabled }) }),
remove: (providerId: number, zoneId: string, name: string) => request<void>(`/api/dns/providers/${providerId}/zones/${encodeURIComponent(zoneId)}`, { method: "DELETE", body: JSON.stringify({ name }) }),
create: (providerId: number, body: NewDnsZoneInput) => request<{ zone: { id: string; name: string } }>(`/api/dns/providers/${providerId}/zones`, { method: "POST", body: JSON.stringify(body) }),
},
+239
View File
@@ -0,0 +1,239 @@
import { useEffect, useState, type FormEvent } from "react";
import { api, type DnsZone, type DnsZoneOptionsChange, type DnsZoneOptionsInfo } from "../api/client";
import { ErrorNotice } from "./Notice";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const QUERY_ACCESS: [string, string][] = [
["Allow", "Everyone"],
["Deny", "Nobody"],
["AllowOnlyPrivateNetworks", "Only private networks"],
["AllowOnlyZoneNameServers", "Only the zone's name servers"],
["UseSpecifiedNetworkACL", "Only the networks listed"],
["AllowZoneNameServersAndUseSpecifiedNetworkACL", "The zone's name servers and the networks listed"],
];
const ZONE_TRANSFER: [string, string][] = [
["Deny", "Nobody"],
["Allow", "Everyone"],
["AllowOnlyZoneNameServers", "Only the zone's name servers"],
["UseSpecifiedNetworkACL", "Only the networks listed"],
["AllowZoneNameServersAndUseSpecifiedNetworkACL", "The zone's name servers and the networks listed"],
];
const NOTIFY: [string, string][] = [
["None", "Nobody"],
["ZoneNameServers", "The zone's name servers"],
["SpecifiedNameServers", "Only the servers listed"],
["BothZoneAndSpecifiedNameServers", "The zone's name servers and the servers listed"],
];
const usesAcl = (mode: string) => mode === "UseSpecifiedNetworkACL" || mode === "AllowZoneNameServersAndUseSpecifiedNetworkACL";
const usesServers = (mode: string) => mode === "SpecifiedNameServers" || mode === "BothZoneAndSpecifiedNameServers";
/** What was typed as a list: one to a line, or separated by commas or spaces. */
const listOf = (text: string) => text.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
const NAMES: Record<string, string> = { queryAccess: "who may ask", zoneTransfer: "who may copy it", notify: "who is told" };
function Choice({ id, label, value, options, onChange }: { id: string; label: string; value: string; options: [string, string][]; onChange: (v: string) => void }) {
return (
<div className="mb-2">
<label className="form-label" htmlFor={id}>
{label}
</label>
<select id={id} className="form-select form-select-sm" value={value} onChange={(e) => onChange(e.target.value)}>
{options.map(([v, text]) => (
<option key={v} value={v}>
{text}
</option>
))}
</select>
</div>
);
}
/**
* Editing one zone of a provider that can (Technitium): switching it off and on, and who may ask it, who may copy it and who is told when it changes. It reads the zone's options when it opens;
* what Save sends is checked against the kind of zone, and if the server also changed something that was not asked, this says so. Only the groups that apply to the kind of zone are shown.
*/
export default function DnsZoneEditor({ providerId, zone, onChanged, onClose }: { providerId: number; zone: DnsZone; onChanged: () => void; onClose: () => void }) {
const [options, setOptions] = useState<DnsZoneOptionsInfo | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [unexpected, setUnexpected] = useState<string[]>([]);
const [queryAccess, setQueryAccess] = useState("Allow");
const [queryAcl, setQueryAcl] = useState("");
const [transfer, setTransfer] = useState("Deny");
const [transferAcl, setTransferAcl] = useState("");
const [keys, setKeys] = useState<string[]>([]);
const [notify, setNotify] = useState("None");
const [notifyServers, setNotifyServers] = useState("");
const fill = (o: DnsZoneOptionsInfo) => {
setOptions(o);
setQueryAccess(o.queryAccess ?? "Allow");
setQueryAcl(o.queryAccessNetworkACL.join("\n"));
setTransfer(o.zoneTransfer ?? "Deny");
setTransferAcl(o.zoneTransferNetworkACL.join("\n"));
setKeys(o.zoneTransferTsigKeyNames);
setNotify(o.notify ?? "None");
setNotifyServers(o.notifyNameServers.join("\n"));
};
useEffect(() => {
setOptions(null);
setError(null);
setUnexpected([]);
api.dns.zones
.options(providerId, zone.id)
.then((r) => fill(r.options))
.catch((err) => setError(readableError(err)));
}, [providerId, zone.id]);
const type = options?.type ?? zone.type ?? "";
const hasQuery = type !== "SecondaryCatalog";
const hasTransferAndNotify = type === "Primary" || type === "Secondary";
async function switchTo(on: boolean) {
if (!options) return;
if (!on && !(await confirmDialog({ title: "Switch off zone", message: `Switch off "${zone.name}"? The server stops answering for it. Its records stay, and switching it on again brings it all back.`, confirmLabel: "Switch off", danger: true }))) return;
setBusy(true);
setError(null);
try {
await api.dns.zones.setEnabled(providerId, zone.id, on);
toast.success(`${zone.name} is ${on ? "on" : "off"}.`);
setOptions({ ...options, disabled: !on });
onChanged();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function save(e: FormEvent) {
e.preventDefault();
if (!options || busy) return;
const change: DnsZoneOptionsChange = {};
if (hasQuery) {
change.queryAccess = queryAccess;
if (usesAcl(queryAccess)) change.queryAccessNetworkACL = listOf(queryAcl);
}
if (hasTransferAndNotify) {
change.zoneTransfer = transfer;
if (usesAcl(transfer)) change.zoneTransferNetworkACL = listOf(transferAcl);
change.zoneTransferTsigKeyNames = keys;
change.notify = notify;
if (usesServers(notify)) change.notifyNameServers = listOf(notifyServers);
}
setBusy(true);
setError(null);
setUnexpected([]);
try {
const r = await api.dns.zones.updateOptions(providerId, zone.id, change);
if (r.options) fill(r.options);
setUnexpected(r.unexpected);
toast.success(r.changed.length === 0 ? "Nothing was different." : `Saved: ${r.changed.map((c) => NAMES[c] ?? c).join(", ")}.`);
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
return (
<div className="card-body border-bottom">
<div className="d-flex align-items-center mb-2">
<h4 className="mb-0">Edit {zone.name}</h4>
<button type="button" className="btn btn-sm btn-link text-secondary ms-auto" onClick={onClose}>
Close
</button>
</div>
<ErrorNotice error={error} />
{!options && !error && <div className="text-secondary small">Reading how the zone is set…</div>}
{options && (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
<span>
{type ? `${type} zone — ` : ""}
{options.disabled ? <span className="text-yellow">switched off: the server does not answer for it.</span> : "on."}
</span>
<button type="button" className={`btn btn-sm ${options.disabled ? "btn-primary" : "btn-outline-secondary"}`} disabled={busy} onClick={() => void switchTo(options.disabled)}>
{options.disabled ? "Switch on" : "Switch off"}
</button>
</div>
{!hasQuery && !hasTransferAndNotify ? (
<div className="text-secondary small">There are no options to edit on this kind of zone from here.</div>
) : (
<form onSubmit={save}>
{hasQuery && (
<fieldset className="mb-3">
<legend className="fs-5">Who may ask this zone</legend>
<Choice id="zopt-query" label="Questions about it are answered for" value={queryAccess} options={QUERY_ACCESS} onChange={setQueryAccess} />
{usesAcl(queryAccess) && (
<div className="mb-2">
<label className="form-label" htmlFor="zopt-query-acl">
Networks
</label>
<textarea id="zopt-query-acl" className="form-control form-control-sm" rows={3} placeholder={"192.168.1.0/24\n!192.168.1.66"} value={queryAcl} onChange={(e) => setQueryAcl(e.target.value)} />
<div className="text-secondary small">One to a line, in order: an address or a network, with ! in front to refuse it. Anyone not listed is refused.</div>
</div>
)}
</fieldset>
)}
{hasTransferAndNotify && (
<>
<fieldset className="mb-3">
<legend className="fs-5">Who may copy this zone</legend>
<Choice id="zopt-transfer" label="A zone transfer is given to" value={transfer} options={ZONE_TRANSFER} onChange={setTransfer} />
{usesAcl(transfer) && (
<div className="mb-2">
<label className="form-label" htmlFor="zopt-transfer-acl">
Networks
</label>
<textarea id="zopt-transfer-acl" className="form-control form-control-sm" rows={3} value={transferAcl} onChange={(e) => setTransferAcl(e.target.value)} />
</div>
)}
<div className="mb-1">
<div className="form-label">Only with one of these TSIG keys</div>
{options.availableTsigKeyNames.length === 0 ? (
<div className="text-secondary small">The server has no TSIG keys, so a transfer is not limited by one.</div>
) : (
options.availableTsigKeyNames.map((k) => (
<label key={k} className="form-check form-check-inline">
<input type="checkbox" className="form-check-input" checked={keys.includes(k)} onChange={() => setKeys((cur) => (cur.includes(k) ? cur.filter((x) => x !== k) : [...cur, k]))} />
<span className="form-check-label">{k}</span>
</label>
))
)}
</div>
</fieldset>
<fieldset className="mb-3">
<legend className="fs-5">Who is told when it changes</legend>
<Choice id="zopt-notify" label="A notification goes to" value={notify} options={NOTIFY} onChange={setNotify} />
{usesServers(notify) && (
<div className="mb-2">
<label className="form-label" htmlFor="zopt-notify-servers">
Servers
</label>
<textarea id="zopt-notify-servers" className="form-control form-control-sm" rows={2} placeholder="10.0.0.2" value={notifyServers} onChange={(e) => setNotifyServers(e.target.value)} />
<div className="text-secondary small">Addresses, one to a line.</div>
</div>
)}
</fieldset>
</>
)}
{unexpected.length > 0 && (
<div className="alert alert-warning small">
Saved, but Technitium also changed something that was not asked: <strong>{unexpected.join(", ")}</strong>. Look at the zone in its own console.
</div>
)}
<button type="submit" className="btn btn-sm btn-primary" disabled={busy}>
{busy ? "Saving…" : "Save"}
</button>
</form>
)}
</>
)}
</div>
);
}
+28 -1
View File
@@ -14,6 +14,7 @@ import {
} from "../api/client";
import DnsProviderForm from "../components/DnsProviderForm";
import DnsNewZone from "../components/DnsNewZone";
import DnsZoneEditor from "../components/DnsZoneEditor";
import { formatDateTime } from "../utils/date";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
@@ -89,6 +90,7 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
const [zonesError, setZonesError] = useState<string | null>(null);
const [selectedZone, setSelectedZone] = useState<DnsZone | null>(null);
const [creatingZone, setCreatingZone] = useState(false);
const [editingZone, setEditingZone] = useState(false);
const [records, setRecords] = useState<DnsRecord[] | null>(null);
const [syncedAt, setSyncedAt] = useState<string | null>(null);
@@ -137,6 +139,17 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
if (selectedProviderId && !managingProviders) loadZones(selectedProviderId);
}, [selectedProviderId, managingProviders]);
/** Reads the zones again without closing anything: the open zone is kept, with what the provider now says of it (switched off, say). */
function refreshZones(providerId: number) {
api.dns.zones
.list(providerId)
.then((res) => {
setZones(res.zones);
setSelectedZone((current) => (current ? (res.zones.find((z) => z.id === current.id) ?? current) : current));
})
.catch(() => {});
}
function loadRecords(providerId: number, zone: DnsZone) {
api.dns.records
.list(providerId, zone.id)
@@ -160,6 +173,7 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
function selectZone(zone: DnsZone) {
setSelectedZone(zone);
setEditingZone(false);
setRecordForm(null);
setEditingRecordId(null);
if (selectedProviderId) loadRecords(selectedProviderId, zone);
@@ -516,7 +530,11 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
className={selectedZone?.id === z.id ? "table-active" : ""}
onClick={() => selectZone(z)}
>
<td>{z.name}</td>
<td>
{z.name}
{z.disabled && <span className="badge bg-yellow-lt text-yellow ms-2">off</span>}
{z.type && z.type !== "Primary" && <span className="badge bg-secondary-lt text-secondary ms-1">{z.type}</span>}
</td>
<td>{z.recordCount}</td>
<td className="text-secondary">
{z.syncedAt ? <TimeAgo value={z.syncedAt} /> : "never"}
@@ -556,6 +574,11 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
Add record
</button>
)}
{isAdmin && selectedProvider?.canEditZones && selectedProvider.enabled && (
<button className="btn btn-sm btn-outline-secondary ms-2" onClick={() => setEditingZone((v) => !v)} aria-expanded={editingZone}>
Edit zone
</button>
)}
{isAdmin && selectedProvider?.canDeleteZones && selectedProvider.enabled && (
<button className="btn btn-sm btn-outline-danger ms-2" onClick={() => void deleteZone()}>
Delete zone
@@ -564,6 +587,10 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
</div>
</div>
{editingZone && selectedProviderId && (
<DnsZoneEditor providerId={selectedProviderId} zone={selectedZone} onChanged={() => refreshZones(selectedProviderId)} onClose={() => setEditingZone(false)} />
)}
{recordForm && (
<form onSubmit={submitRecord}>
<div className="card-body row g-2">