/** * 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); }