import { randomBytes } from "@/worker/auth/bytes"; import { HOST_WORDS } from "@/worker/auth/host-wordlist"; const wordSet = new Set(HOST_WORDS); const hostLabelRe = /^[a-z]+(-[a-z]+){4}$/; function randomWordIndex(): number { const length = HOST_WORDS.length; const max = 65_536 - (65_536 % length); while (true) { const bytes = randomBytes(2); const value = (bytes[0] << 8) | bytes[1]; if (value < max) return value % length; } } export function isValidHostLabel(label: string): boolean { if (label.length > 63 || !hostLabelRe.test(label)) return false; return label.split("-").every((word) => wordSet.has(word)); } export function generateHostLabel(): string { for (let attempt = 0; attempt < 100; attempt += 1) { const words = Array.from({ length: 5 }, () => HOST_WORDS[randomWordIndex()]); const label = words.join("-"); if (label.length <= 63) return label; } throw new Error("Unable to generate a host label under 64 characters"); }