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:
1 parent
082c524125
commit
6f144b4e36
12 files changed
+1110
-10
No files matched your search
@@ -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 });
|
||||
}
|
||||
@@ -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":
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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
@@ -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) });
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user