Stop IDs in a request from being turned into other calls to connected systems

The Tailscale device, Proxmox node, Cloudflare zone/record and Azure record/zone IDs
were put into the outgoing request path as typed. An operator could send a crafted ID
("x/../../tailnet/-/keys/k1") and make the app call a different endpoint than the button
meant -- delete an auth key instead of a device, stop every guest on a node, delete a whole
DNS zone -- under the integration's own credential. Gitea and Dockhand encoded their IDs but
still passed "..".

- utils/pathSegment.ts: checks an ID against what a real one looks like, then encodes it
  (encodeURIComponent alone leaves ".." untouched). Used by the Tailscale, Proxmox,
  Cloudflare, Azure, Gitea and Dockhand adapters.
- The routes refuse a bad ID with a 400 before anything is sent, and the DNS routes turn the
  adapters' refusal into a 400. A server's Proxmox node name is validated when saved.
- Azure: a zone ID without "::" is now refused instead of being cut into two bogus pieces.
- Regression tests (npm test --workspace server, Node's built-in runner): the crafted IDs
  are refused for every adapter and route, real IDs still work, viewers are still refused.
  Against the old code 13 of the 22 tests fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-06 21:02:22 +02:00
1 parent fae7089448
commit a641211484
13 files changed
+549 -26

No files matched your search

+20 -5
View File
@@ -10,6 +10,7 @@
*/
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone } from "../types.js";
import { withDiagLogging } from "../../services/diagLog.js";
import { ID_PATTERNS, InvalidIdentifierError, pathSegment } from "../../utils/pathSegment.js";
const ARM_BASE = "https://management.azure.com";
const API_VERSION = "2018-05-01";
@@ -80,8 +81,22 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter {
return `${resourceGroup}::${zoneName}`;
}
// Resource group, zone, record name and type all come from the request (a zone ID, a record ID, a record's name), so each is
// checked before it goes into an ARM path — see utils/pathSegment. "@" (the zone apex) is a legal path character, kept as is.
function zonePath(resourceGroup: string, zoneName: string) {
const group = pathSegment(resourceGroup, "resource group", ID_PATTERNS.azureResourceGroup);
const zone = pathSegment(zoneName, "DNS zone", ID_PATTERNS.azureZone);
return `/subscriptions/${config.subscriptionId}/resourceGroups/${group}/providers/Microsoft.Network/dnsZones/${zone}`;
}
function recordPath(resourceGroup: string, zoneName: string, type: string, relName: string) {
const kind = pathSegment(type, "record type", ID_PATTERNS.azureRecordType);
const name = pathSegment(relName, "record name", ID_PATTERNS.azureRecordSet).replace(/%40/g, "@");
return `${zonePath(resourceGroup, zoneName)}/${kind}/${name}`;
}
function decodeZoneId(zoneId: string) {
const idx = zoneId.indexOf("::");
if (idx < 0) throw new InvalidIdentifierError("zone ID");
return { resourceGroup: zoneId.slice(0, idx), zoneName: zoneId.slice(idx + 2) };
}
@@ -127,7 +142,7 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter {
async function listRecords(zoneId: string): Promise<DnsRecord[]> {
const { resourceGroup, zoneName } = decodeZoneId(zoneId);
const path = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/recordSets`;
const path = `${zonePath(resourceGroup, zoneName)}/recordSets`;
const data = await armFetch(path);
const records: DnsRecord[] = [];
@@ -232,7 +247,7 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter {
if (relName.endsWith(`.${zoneName}`)) relName = relName.slice(0, -(zoneName.length + 1));
if (relName === zoneName) relName = "@";
const path = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${record.type}/${relName}`;
const path = recordPath(resourceGroup, zoneName, record.type, relName);
let existing: any = null;
try {
@@ -268,8 +283,8 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter {
if (newRelName.endsWith(`.${zoneName}`)) newRelName = newRelName.slice(0, -(zoneName.length + 1));
if (newRelName === zoneName) newRelName = "@";
const oldPath = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${type}/${oldRelName}`;
const newPath = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${type}/${newRelName}`;
const oldPath = recordPath(resourceGroup, zoneName, type, oldRelName);
const newPath = recordPath(resourceGroup, zoneName, type, newRelName);
let existing: any = null;
try {
@@ -313,7 +328,7 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter {
const type = parts[1];
const content = parts.slice(2).join("::");
const path = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${type}/${relName}`;
const path = recordPath(resourceGroup, zoneName, type, relName);
const existing = await armFetch(path);
const props = existing.properties;
+9 -4
View File
@@ -4,6 +4,7 @@
*/
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone } from "../types.js";
import { withDiagLogging } from "../../services/diagLog.js";
import { ID_PATTERNS, pathSegment } from "../../utils/pathSegment.js";
const BASE = "https://api.cloudflare.com/client/v4";
@@ -19,6 +20,10 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter {
};
}
// Zone and record IDs come from the request. Cloudflare's are always 32 hex characters (see utils/pathSegment).
const zone = (id: string) => pathSegment(id, "zone ID", ID_PATTERNS.cloudflareId);
const rec = (id: string) => pathSegment(id, "record ID", ID_PATTERNS.cloudflareId);
async function cfFetch(path: string, options: RequestInit = {}) {
const res = await fetch(`${BASE}${path}`, { ...options, headers: headers() });
const data = await res.json();
@@ -45,7 +50,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter {
let page = 1;
let all: any[] = [];
while (true) {
const result = await cfFetch(`/zones/${zoneId}/dns_records?per_page=100&page=${page}`);
const result = await cfFetch(`/zones/${zone(zoneId)}/dns_records?per_page=100&page=${page}`);
all = all.concat(result);
if (result.length < 100) break;
page++;
@@ -75,7 +80,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter {
async function addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord> {
const body = toBody(record);
const result = await cfFetch(`/zones/${zoneId}/dns_records`, {
const result = await cfFetch(`/zones/${zone(zoneId)}/dns_records`, {
method: "POST",
body: JSON.stringify(body),
});
@@ -84,7 +89,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter {
async function updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord> {
const body = toBody(record);
const result = await cfFetch(`/zones/${zoneId}/dns_records/${recordId}`, {
const result = await cfFetch(`/zones/${zone(zoneId)}/dns_records/${rec(recordId)}`, {
method: "PATCH",
body: JSON.stringify(body),
});
@@ -92,7 +97,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter {
}
async function deleteRecord(zoneId: string, recordId: string): Promise<void> {
await cfFetch(`/zones/${zoneId}/dns_records/${recordId}`, { method: "DELETE" });
await cfFetch(`/zones/${zone(zoneId)}/dns_records/${rec(recordId)}`, { method: "DELETE" });
}
return withDiagLogging("cloudflare", { listZones, listRecords, addRecord, updateRecord, deleteRecord });
+4 -3
View File
@@ -10,6 +10,7 @@
* (https://github.com/strausmann/mcp-dockhand/blob/main/docs/dockhand-openapi.json).
*/
import { withDiagLogging } from "../../services/diagLog.js";
import { ID_PATTERNS, numericSegment, pathSegment } from "../../utils/pathSegment.js";
export interface DockhandConfig {
url: string;
@@ -140,15 +141,15 @@ export function createDockhandAdapter(config: DockhandConfig): DockhandAdapter {
}
async function startContainer(environmentId: number, containerId: string): Promise<void> {
await api("POST", `/api/containers/${encodeURIComponent(containerId)}/start?env=${environmentId}`);
await api("POST", `/api/containers/${pathSegment(containerId, "container ID", ID_PATTERNS.container)}/start?env=${numericSegment(environmentId, "environment ID")}`);
}
async function stopContainer(environmentId: number, containerId: string): Promise<void> {
await api("POST", `/api/containers/${encodeURIComponent(containerId)}/stop?env=${environmentId}`);
await api("POST", `/api/containers/${pathSegment(containerId, "container ID", ID_PATTERNS.container)}/stop?env=${numericSegment(environmentId, "environment ID")}`);
}
async function restartContainer(environmentId: number, containerId: string): Promise<void> {
await api("POST", `/api/containers/${encodeURIComponent(containerId)}/restart?env=${environmentId}`);
await api("POST", `/api/containers/${pathSegment(containerId, "container ID", ID_PATTERNS.container)}/restart?env=${numericSegment(environmentId, "environment ID")}`);
}
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
+3 -2
View File
@@ -6,6 +6,7 @@
* Verified against Gitea 1.27.
*/
import { withDiagLogging } from "../../services/diagLog.js";
import { ID_PATTERNS, numericSegment, pathSegment } from "../../utils/pathSegment.js";
export interface GiteaConfig {
url: string;
@@ -112,7 +113,7 @@ export function createGiteaAdapter(config: GiteaConfig): GiteaAdapter {
try {
const data = await api(
"GET",
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/runs?limit=1&page=1`,
`/repos/${pathSegment(owner, "repository owner", ID_PATTERNS.giteaName)}/${pathSegment(repo, "repository name", ID_PATTERNS.giteaName)}/actions/runs?limit=1&page=1`,
);
const run = data?.workflow_runs?.[0];
return run ? mapRun(run) : null;
@@ -137,7 +138,7 @@ export function createGiteaAdapter(config: GiteaConfig): GiteaAdapter {
async function rerunFailedJobs(owner: string, repo: string, runId: number): Promise<void> {
await api(
"POST",
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/runs/${runId}/rerun-failed-jobs`,
`/repos/${pathSegment(owner, "repository owner", ID_PATTERNS.giteaName)}/${pathSegment(repo, "repository name", ID_PATTERNS.giteaName)}/actions/runs/${numericSegment(runId, "run ID")}/rerun-failed-jobs`,
);
}
+18 -9
View File
@@ -23,6 +23,7 @@
*/
import * as https from "node:https";
import { withDiagLogging } from "../../services/diagLog.js";
import { ID_PATTERNS, InvalidIdentifierError, numericSegment, pathSegment } from "../../utils/pathSegment.js";
export interface ProxmoxConfig {
url: string;
@@ -224,6 +225,14 @@ function request(url: string, insecure: boolean, options: { method?: string; hea
export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
const insecure = config.insecure === true;
// Node, guest type and VM number all end up in the request path, and they can come from a request — see utils/pathSegment.
const nodeSeg = (node: string) => pathSegment(node, "node name", ID_PATTERNS.proxmoxNode);
const typeSeg = (type: string) => {
if (type !== "qemu" && type !== "lxc") throw new InvalidIdentifierError("guest type");
return type;
};
const vmidSeg = (vmid: number) => numericSegment(vmid, "VM ID");
function base() {
return config.url.replace(/\/$/, "");
}
@@ -258,7 +267,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
}
async function listGuestsForNode(node: string, type: ProxmoxGuestType): Promise<ProxmoxGuest[]> {
const data = await api("GET", `/nodes/${node}/${type}`);
const data = await api("GET", `/nodes/${nodeSeg(node)}/${typeSeg(type)}`);
return (Array.isArray(data) ? data : []).map((g: any) => ({
vmid: g.vmid,
name: g.name,
@@ -293,8 +302,8 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
async function getGuestDetail(node: string, type: ProxmoxGuestType, vmid: number): Promise<ProxmoxGuestDetail> {
const [config, status] = await Promise.all([
api("GET", `/nodes/${node}/${type}/${vmid}/config`),
api("GET", `/nodes/${node}/${type}/${vmid}/status/current`),
api("GET", `/nodes/${nodeSeg(node)}/${typeSeg(type)}/${vmidSeg(vmid)}/config`),
api("GET", `/nodes/${nodeSeg(node)}/${typeSeg(type)}/${vmidSeg(vmid)}/status/current`),
]);
let cpuCores: number | null = null;
@@ -338,7 +347,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
diskBytes = foundDisk ? totalDisk : null;
try {
const agentData = await api("GET", `/nodes/${node}/qemu/${vmid}/agent/network-get-interfaces`);
const agentData = await api("GET", `/nodes/${nodeSeg(node)}/qemu/${vmidSeg(vmid)}/agent/network-get-interfaces`);
const interfaces = agentData?.result ?? [];
for (const iface of interfaces) {
for (const addr of iface["ip-addresses"] ?? []) {
@@ -358,7 +367,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
// failing, e.g. on an older guest agent version, shouldn't hide IPs
// the other command already got, or vice versa).
try {
const fsData = await api("GET", `/nodes/${node}/qemu/${vmid}/agent/get-fsinfo`);
const fsData = await api("GET", `/nodes/${nodeSeg(node)}/qemu/${vmidSeg(vmid)}/agent/get-fsinfo`);
for (const fs of fsData?.result ?? []) {
// Entries with no backing "disk" (tmpfs, proc, overlay, snap loop
// mounts, ...) aren't real storage — skip them, same convention
@@ -421,8 +430,8 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
// the other, so fetch them independently rather than losing both to
// Promise.all's fail-fast behavior.
const [statusResult, storageResult] = await Promise.allSettled([
api("GET", `/nodes/${node}/status`),
api("GET", `/nodes/${node}/storage`),
api("GET", `/nodes/${nodeSeg(node)}/status`),
api("GET", `/nodes/${nodeSeg(node)}/storage`),
]);
const status = statusResult.status === "fulfilled" ? statusResult.value : null;
@@ -500,7 +509,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
const perNode = await Promise.all(
nodes.map(async (node) => {
try {
const data = await api("GET", `/nodes/${node}/tasks?typefilter=vzdump&limit=${limitPerNode}`);
const data = await api("GET", `/nodes/${nodeSeg(node)}/tasks?typefilter=vzdump&limit=${limitPerNode}`);
return (Array.isArray(data) ? data : []).map((t: any) => ({
node,
upid: t.upid,
@@ -520,7 +529,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter {
}
async function statusAction(node: string, type: ProxmoxGuestType, vmid: number, action: string): Promise<void> {
await api("POST", `/nodes/${node}/${type}/${vmid}/status/${action}`);
await api("POST", `/nodes/${nodeSeg(node)}/${typeSeg(type)}/${vmidSeg(vmid)}/status/${action}`);
}
const startGuest = (node: string, type: ProxmoxGuestType, vmid: number) => statusAction(node, type, vmid, "start");
+3 -2
View File
@@ -17,6 +17,7 @@
* needed.
*/
import { withDiagLogging } from "../../services/diagLog.js";
import { ID_PATTERNS, pathSegment } from "../../utils/pathSegment.js";
const BASE = "https://api.tailscale.com";
@@ -113,11 +114,11 @@ export function createTailscaleAdapter(config: TailscaleConfig): TailscaleAdapte
}
async function deleteDevice(deviceId: string): Promise<void> {
await api("DELETE", `/api/v2/device/${deviceId}`);
await api("DELETE", `/api/v2/device/${pathSegment(deviceId, "device ID", ID_PATTERNS.tailscaleDevice)}`);
}
async function setAuthorized(deviceId: string, authorized: boolean): Promise<void> {
await api("POST", `/api/v2/device/${deviceId}/authorized`, { authorized });
await api("POST", `/api/v2/device/${pathSegment(deviceId, "device ID", ID_PATTERNS.tailscaleDevice)}/authorized`, { authorized });
}
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
+9
View File
@@ -15,6 +15,7 @@ import { createDnsAdapter } from "../dns/registry.js";
import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js";
import { getDnsStats } from "../dns/stats.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { InvalidIdentifierError } from "../utils/pathSegment.js";
import { notifyDnsRecordAdded, notifyDnsRecordUpdated, notifyDnsRecordDeleted } from "../services/notify.js";
async function zoneNameFor(providerId: number, zoneId: string): Promise<string> {
@@ -354,6 +355,8 @@ dnsRouter.post("/providers/:id/zones/:zoneId/sync", requireRole("operator"), asy
res.json({ records, syncedAt: now });
} catch (err) {
// A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent.
if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message });
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
}));
@@ -406,6 +409,8 @@ dnsRouter.post("/providers/:id/zones/:zoneId/records", requireRole("operator"),
res.status(201).json({ record: result });
} catch (err) {
// A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent.
if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message });
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
}));
@@ -459,6 +464,8 @@ dnsRouter.put("/providers/:id/zones/:zoneId/records/:recordId", requireRole("ope
res.json({ record: result });
} catch (err) {
// A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent.
if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message });
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
}));
@@ -510,6 +517,8 @@ dnsRouter.delete("/providers/:id/zones/:zoneId/records/:recordId", requireRole("
res.status(204).end();
} catch (err) {
// A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent.
if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message });
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
}));
+18
View File
@@ -25,6 +25,7 @@ import { createPbsAdapter } from "../integrations/pbs/adapter.js";
import { createOsTicketAdapter } from "../integrations/osticket/adapter.js";
import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../services/uptimeKumaMatch.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js";
export const integrationsRouter = Router();
@@ -315,6 +316,12 @@ integrationsRouter.post("/test", requireRole("admin"), asyncHandler(async (req,
res.json(result);
}));
// IDs taken from the URL end up in the request made to the connected system, under the integration's own credential. They're
// checked here (clear 400, nothing sent) and again inside each adapter (see utils/pathSegment.ts) — either alone would do.
function rejectInvalidId(res: Response, what: string) {
return res.status(400).json({ error: "invalid_id", message: `That isn't a valid ${what}.` });
}
// ─── Tailscale ───────────────────────────────────────────────────────────────
/**
@@ -370,6 +377,8 @@ integrationsRouter.post(
const found = await requireTailscaleAdapter(req, res);
if (!found) return;
if (!isValidId(req.params.deviceId, ID_PATTERNS.tailscaleDevice)) return rejectInvalidId(res, "device ID");
const parsed = authorizeSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
@@ -399,6 +408,8 @@ integrationsRouter.delete(
const found = await requireTailscaleAdapter(req, res);
if (!found) return;
if (!isValidId(req.params.deviceId, ID_PATTERNS.tailscaleDevice)) return rejectInvalidId(res, "device ID");
try {
await found.adapter.deleteDevice(req.params.deviceId);
await recordAudit({
@@ -455,6 +466,9 @@ integrationsRouter.post(
const found = await requireGiteaAdapter(req, res);
if (!found) return;
if (!isValidId(req.params.owner, ID_PATTERNS.giteaName)) return rejectInvalidId(res, "repository owner");
if (!isValidId(req.params.repo, ID_PATTERNS.giteaName)) return rejectInvalidId(res, "repository name");
const runId = Number(req.params.runId);
if (!Number.isInteger(runId)) {
return res.status(400).json({ error: "invalid_run_id" });
@@ -549,6 +563,8 @@ for (const action of dockhandActions) {
const found = await requireDockhandAdapter(req, res);
if (!found) return;
if (!isValidId(req.params.containerId, ID_PATTERNS.container)) return rejectInvalidId(res, "container ID");
const envId = Number(req.params.envId);
if (!Number.isInteger(envId)) {
return res.status(400).json({ error: "invalid_environment_id" });
@@ -716,6 +732,8 @@ for (const action of proxmoxActions) {
const found = await requireProxmoxAdapter(req, res);
if (!found) return;
if (!isValidId(req.params.node, ID_PATTERNS.proxmoxNode)) return rejectInvalidId(res, "node name");
const vmid = Number(req.params.vmid);
if (!Number.isInteger(vmid)) {
return res.status(400).json({ error: "invalid_vmid" });
+2 -1
View File
@@ -7,6 +7,7 @@ import { requireAuth, requireRole } from "../auth/middleware.js";
import { generateApiToken } from "../services/tokens.js";
import { recordAudit } from "../services/audit.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { ID_PATTERNS } from "../utils/pathSegment.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createProxmoxAdapter, type ProxmoxGuestType } from "../integrations/proxmox/adapter.js";
import { serverPortsRouter } from "./serverPorts.js";
@@ -106,7 +107,7 @@ const updateServerSchema = z
hostname: z.string().max(255).optional(),
description: z.string().max(500).optional(),
proxmoxIntegrationId: z.number().int().nullable().optional(),
proxmoxNode: z.string().nullable().optional(),
proxmoxNode: z.string().regex(ID_PATTERNS.proxmoxNode, "Not a valid Proxmox node name.").nullable().optional(),
proxmoxGuestType: z.enum(["qemu", "lxc"]).nullable().optional(),
proxmoxVmid: z.number().int().nullable().optional(),
hideProxmoxLink: z.boolean().optional(),
+53
View File
@@ -0,0 +1,53 @@
/**
* Keeping a value inside the one URL path segment it was meant for.
*
* Several routes take an ID from the request (a Tailscale device, a Proxmox node, a DNS record) and the adapter puts it into
* a call to that system, made with the integration's own credential. Left as it was typed, `x/../../tailnet/-/keys/k1` in a
* "delete device" request turns into a request for a different endpoint — one that button never offered, sent with a key
* that may be allowed to do far more. So every such ID is checked against what a real ID of that kind looks like, and only
* then encoded. Checking matters as much as encoding: encodeURIComponent leaves ".." untouched, and ".." is all it takes.
*/
export class InvalidIdentifierError extends Error {
constructor(public readonly what: string) {
super(`That isn't a valid ${what}.`);
}
}
/**
* What each kind of ID may look like. All of them must start with a letter or digit (or, for Gitea, be anything but "."
* and ".."), so a lone "." or ".." can never match, and none of them allow "/", "?", "#" or "%".
*/
export const ID_PATTERNS = {
/** Tailscale device IDs: "12345" or "nABC123CNTRL". */
tailscaleDevice: /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,
/** Proxmox node names are hostnames. */
proxmoxNode: /^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$/,
/** Gitea user/organisation and repository names. */
giteaName: /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/,
/** Docker container IDs and names. */
container: /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/,
/** Cloudflare zone and record IDs: 32 hex characters. */
cloudflareId: /^[a-f0-9]{32}$/,
/** Azure: resource group, DNS zone, record-set name ("@" is the zone apex, "*" a wildcard) and record type. */
azureResourceGroup: /^[A-Za-z0-9_()-][A-Za-z0-9_.()-]{0,89}$/,
azureZone: /^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/,
azureRecordSet: /^(?:@|[A-Za-z0-9_*][A-Za-z0-9_.*-]{0,253})$/,
azureRecordType: /^[A-Za-z]{1,10}$/,
} as const;
export function isValidId(value: unknown, pattern: RegExp): value is string {
return typeof value === "string" && pattern.test(value);
}
/** The value, encoded for use as one path segment — or an InvalidIdentifierError if it isn't the kind of ID it should be. */
export function pathSegment(value: unknown, what: string, pattern: RegExp): string {
if (!isValidId(value, pattern)) throw new InvalidIdentifierError(what);
return encodeURIComponent(value);
}
/** A whole number, for IDs like a VM number. */
export function numericSegment(value: unknown, what: string): string {
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new InvalidIdentifierError(what);
return String(value);
}