diff --git a/src/lib/components/page-specific/about/BuildingSection.svelte b/src/lib/components/page-specific/about/BuildingSection.svelte index a30bc34..54a3e25 100644 --- a/src/lib/components/page-specific/about/BuildingSection.svelte +++ b/src/lib/components/page-specific/about/BuildingSection.svelte @@ -41,7 +41,7 @@
  • Option #3 - Docker:
    Build the Docker image, with docker build -t networking-toolbox . - then run docker run -p 8080:300080 networking-toolbox + then run docker run -p 8080:3000 networking-toolbox
  • --> diff --git a/src/lib/components/page-specific/about/DeployingSection.svelte b/src/lib/components/page-specific/about/DeployingSection.svelte index ade2c06..e7739e4 100644 --- a/src/lib/components/page-specific/about/DeployingSection.svelte +++ b/src/lib/components/page-specific/about/DeployingSection.svelte @@ -13,7 +13,7 @@

    Option #1 - Docker

    With Docker installed, just run the following command:

    - docker run -p 8080:300080 lissy93/networking-toolbox + docker run -p 8080:3000 lissy93/networking-toolbox

    You can also checkout our diff --git a/src/lib/components/page-specific/about/SelfHostingSection.svelte b/src/lib/components/page-specific/about/SelfHostingSection.svelte index 0073547..db24b70 100644 --- a/src/lib/components/page-specific/about/SelfHostingSection.svelte +++ b/src/lib/components/page-specific/about/SelfHostingSection.svelte @@ -8,7 +8,7 @@ {site.title} can be easily deployed to your own server. Just run the following command:

    - docker run -p 8080:300080 lissy93/networking-toolbox + docker run -p 8080:3000 lissy93/networking-toolbox

    You can also checkout our + import Icon from '$lib/components/global/Icon.svelte'; + import { useClipboard } from '$lib/composables'; + import { + generateSnippets, + getDefaultSnippetConfig, + type SnippetConfig, + type SnippetResult, + type DhcpTarget, + type PoolRange, + } from '$lib/utils/dhcp-snippets.js'; + + let config = $state(getDefaultSnippetConfig()); + let result = $state(null); + + const clipboard = useClipboard(); + + const targetOptions: Array<{ value: DhcpTarget; label: string }> = [ + { value: 'isc-dhcpd', label: 'ISC dhcpd' }, + { value: 'kea-dhcp4', label: 'Kea DHCPv4' }, + { value: 'kea-dhcp6', label: 'Kea DHCPv6' }, + ]; + + // Reactive generation + $effect(() => { + generate(); + }); + + function generate() { + result = generateSnippets(config); + } + + function addPool() { + const lastPool = config.pools[config.pools.length - 1]; + const newPool: PoolRange = { start: lastPool.end, end: lastPool.end }; + config.pools = [...config.pools, newPool]; + } + + function removePool(index: number) { + if (config.pools.length > 1) { + config.pools = config.pools.filter((_, i) => i !== index); + } + } + + function toggleTarget(target: DhcpTarget) { + if (config.targets.includes(target)) { + config.targets = config.targets.filter((t) => t !== target); + } else { + config.targets = [...config.targets, target]; + } + } + + +

    +
    +

    Configuration

    +
    +
    + +
    + +
    + {#each targetOptions as option (option.value)} + + {/each} +
    +
    + + +
    + + +
    + + +
    + + +
    + + +
    + + {#each config.pools as pool, i (i)} +
    + + - + + {#if config.pools.length > 1} + + {/if} +
    + {/each} + +
    + + +
    + + +
    + + +
    + + (config.dnsServers = e.currentTarget.value.split(',').map((s) => s.trim()))} + placeholder="8.8.8.8, 8.8.4.4" + /> +
    + + +
    + + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    + + +
    +
    +
    + +{#if result} + {#if result.validations.length > 0} +
    +

    Validation Errors

    + {#each result.validations as error (error.field)} +
    + + {error.field}: + {error.message} +
    + {/each} +
    + {:else} +
    + +

    {result.summary}

    +
    + +
    +

    Generated Snippets

    + + {#if result.iscDhcpdSnippet} +
    +
    +

    ISC dhcpd.conf

    + +
    +
    {result.iscDhcpdSnippet}
    +
    + {/if} + + {#if result.keaDhcp4Snippet} +
    +
    +

    Kea DHCPv4 JSON

    + +
    +
    {result.keaDhcp4Snippet}
    +
    + {/if} + + {#if result.keaDhcp6Snippet} +
    +
    +

    Kea DHCPv6 JSON

    + +
    +
    {result.keaDhcp6Snippet}
    +
    + {/if} +
    + {/if} +{/if} + + diff --git a/src/lib/constants/icon-map.ts b/src/lib/constants/icon-map.ts index 3043660..7845e86 100644 --- a/src/lib/constants/icon-map.ts +++ b/src/lib/constants/icon-map.ts @@ -309,6 +309,7 @@ export const iconMap: Record = { dhcp: ``, router: ``, tools: ``, + 'code-file': ``, // 'mail-check': ``, // 'eye': ``, // 'star': ``, diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index 9506167..c7f800e 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -862,6 +862,32 @@ export const SUB_NAV: Record = { 'scopes', ], }, + { + href: makePath('/dhcp/kea-isc-snippets'), + label: 'Kea/ISC Snippets Generator', + description: + 'Generate complete subnet configurations for ISC dhcpd and Kea DHCP servers with pools, options, and reservations', + icon: 'code-file', + keywords: [ + 'dhcp', + 'isc', + 'kea', + 'snippets', + 'generator', + 'subnet', + 'configuration', + 'dhcpd.conf', + 'pools', + 'options', + 'reservations', + 'static', + 'lease', + 'classes', + 'json', + 'dhcp4', + 'dhcp6', + ], + }, ], '/dns': [ { diff --git a/src/lib/utils/dhcp-snippets.ts b/src/lib/utils/dhcp-snippets.ts new file mode 100644 index 0000000..0fdee89 --- /dev/null +++ b/src/lib/utils/dhcp-snippets.ts @@ -0,0 +1,449 @@ +/** + * DHCP Kea/ISC Snippets Generator + * Generates complete subnet configurations for ISC dhcpd and Kea DHCP servers + */ + +export type DhcpTarget = 'isc-dhcpd' | 'kea-dhcp4' | 'kea-dhcp6'; +export type DhcpMode = 'dhcp4' | 'dhcp6'; +export type Option43Container = 'tlv' | 'ascii' | 'rawhex'; +export type VendorPreset43 = 'cisco-capwap' | 'aruba' | 'ruckus' | 'generic-tlv' | 'custom'; +export type RenderLocation = 'global' | 'class-match' | 'pool-only'; + +export interface PoolRange { + start: string; + end: string; +} + +export interface ClientClass { + name: string; + matchRule: string; // ISC expression + keaTest?: string; // Kea client-class test expression + options?: { + option43?: string; + dns?: string[]; + leaseTime?: number; + }; + pools?: PoolRange[]; +} + +export interface StaticReservation { + identifier: string; // MAC/DUID/client-id + ipAddress: string; + hostname?: string; + clientClasses?: string[]; +} + +export interface VendorDiscovery { + preset: VendorPreset43; + option60?: string; + option43Container: Option43Container; + suboption?: number; + controllerAddresses: string[]; + renderLocation: RenderLocation; +} + +export interface SnippetConfig { + targets: DhcpTarget[]; + mode: DhcpMode; + subnet: string; // CIDR + pools: PoolRange[]; + gateway?: string; + dnsServers?: string[]; + domainName?: string; + defaultLeaseTime?: number; + maxLeaseTime?: number; + preferredLifetime?: number; // v6 + validLifetime?: number; // v6 + vendorDiscovery?: VendorDiscovery; + classes?: ClientClass[]; + reservations?: StaticReservation[]; + emitOptionNames?: boolean; + prettyJson?: boolean; +} + +export interface ValidationError { + field: string; + message: string; +} + +export interface SnippetResult { + iscDhcpdSnippet?: string; + keaDhcp4Snippet?: string; + keaDhcp6Snippet?: string; + summary: string; + validations: ValidationError[]; +} + +const VENDOR_PRESETS_43: Record = { + 'cisco-capwap': { name: 'Cisco CAPWAP', defaultSuboption: 241, defaultOption60: 'Cisco AP' }, + aruba: { name: 'Aruba APs', defaultSuboption: 1, defaultOption60: 'ArubaAP' }, + ruckus: { name: 'Ruckus APs', defaultSuboption: 3, defaultOption60: 'Ruckus CPE' }, + 'generic-tlv': { name: 'Generic TLV', defaultSuboption: 1, defaultOption60: '' }, + custom: { name: 'Custom', defaultSuboption: 1, defaultOption60: '' }, +}; + +/** + * Parse CIDR into network and netmask + */ +function parseCIDR(cidr: string): { network: string; netmask: string; prefix: number } { + const [network, prefixStr] = cidr.split('/'); + const prefix = parseInt(prefixStr, 10); + + if (cidr.includes(':')) { + // IPv6 - return prefix as-is + return { network, netmask: '', prefix }; + } + + // IPv4 - convert to dotted netmask + const mask = (0xffffffff << (32 - prefix)) >>> 0; + const netmask = [(mask >>> 24) & 0xff, (mask >>> 16) & 0xff, (mask >>> 8) & 0xff, mask & 0xff].join('.'); + + return { network, netmask, prefix }; +} + +/** + * Check if IP is within subnet + */ +function isIPInSubnet(ip: string, subnet: string): boolean { + const { network, prefix } = parseCIDR(subnet); + + if (ip.includes(':') || network.includes(':')) { + // IPv6 - simplified check + return ip.startsWith(network.split('::')[0]); + } + + // IPv4 + const ipNum = ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0; + const netNum = network.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0; + const maskNum = (0xffffffff << (32 - prefix)) >>> 0; + + return (ipNum & maskNum) === (netNum & maskNum); +} + +/** + * Validate configuration + */ +export function validateConfig(config: SnippetConfig): ValidationError[] { + const errors: ValidationError[] = []; + + // Validate CIDR + if (!config.subnet.match(/^[\da-f:.]+\/\d+$/i)) { + errors.push({ field: 'subnet', message: 'Invalid CIDR notation' }); + return errors; + } + + const isV6 = config.subnet.includes(':'); + const expectedMode = isV6 ? 'dhcp6' : 'dhcp4'; + + if (config.mode !== expectedMode) { + errors.push({ + field: 'mode', + message: `Mode mismatch: ${isV6 ? 'IPv6' : 'IPv4'} subnet requires ${expectedMode}`, + }); + } + + // Validate pools are within subnet + config.pools.forEach((pool, i) => { + if (!isIPInSubnet(pool.start, config.subnet)) { + errors.push({ field: `pools[${i}].start`, message: 'Pool start IP outside subnet' }); + } + if (!isIPInSubnet(pool.end, config.subnet)) { + errors.push({ field: `pools[${i}].end`, message: 'Pool end IP outside subnet' }); + } + }); + + // Validate gateway is within subnet + if (config.gateway && !isIPInSubnet(config.gateway, config.subnet)) { + errors.push({ field: 'gateway', message: 'Gateway IP outside subnet' }); + } + + // Validate reservations + config.reservations?.forEach((res, i) => { + if (!isIPInSubnet(res.ipAddress, config.subnet)) { + errors.push({ + field: `reservations[${i}].ipAddress`, + message: 'Reservation IP outside subnet', + }); + } + }); + + return errors; +} + +/** + * Encode Option 43 data + */ +function encodeOption43(addresses: string[], container: Option43Container, suboption: number): string { + if (container === 'ascii') { + // ASCII: comma-separated list + return addresses.join(','); + } + + if (container === 'rawhex') { + // Raw hex - user provides it + return addresses[0] || ''; + } + + // TLV encoding: suboption code (1 byte) + length (1 byte) + data + const parts: string[] = []; + addresses.forEach((addr) => { + const octets = addr.split('.').map((o) => parseInt(o, 10)); + const dataHex = octets.map((o) => o.toString(16).padStart(2, '0')).join(':'); + const length = octets.length; + const suboptHex = suboption.toString(16).padStart(2, '0'); + const lengthHex = length.toString(16).padStart(2, '0'); + parts.push(`${suboptHex}:${lengthHex}:${dataHex}`); + }); + + return parts.join(':'); +} + +/** + * Generate ISC dhcpd.conf snippet + */ +function generateISCSnippet(config: SnippetConfig): string { + const { network, netmask } = parseCIDR(config.subnet); + const lines: string[] = []; + + lines.push(`# Subnet: ${config.subnet}`); + lines.push(`subnet ${network} netmask ${netmask} {`); + + // Options + if (config.gateway) { + lines.push(` option routers ${config.gateway};`); + } + if (config.dnsServers && config.dnsServers.length > 0) { + lines.push(` option domain-name-servers ${config.dnsServers.join(', ')};`); + } + if (config.domainName) { + lines.push(` option domain-name "${config.domainName}";`); + } + + // Lease times + if (config.defaultLeaseTime) { + lines.push(` default-lease-time ${config.defaultLeaseTime};`); + } + if (config.maxLeaseTime) { + lines.push(` max-lease-time ${config.maxLeaseTime};`); + } + + lines.push(''); + + // Vendor discovery (global) + if ( + config.vendorDiscovery && + config.vendorDiscovery.renderLocation === 'global' && + config.vendorDiscovery.controllerAddresses.length > 0 + ) { + const vd = config.vendorDiscovery; + const option43 = encodeOption43(vd.controllerAddresses, vd.option43Container, vd.suboption || 1); + + lines.push(` # Vendor discovery - ${VENDOR_PRESETS_43[vd.preset].name}`); + if (vd.option60) { + lines.push(` option vendor-class-identifier "${vd.option60}";`); + } + if (vd.option43Container === 'ascii') { + lines.push(` option vendor-encapsulated-options "${option43}";`); + } else { + lines.push(` option vendor-encapsulated-options ${option43};`); + } + lines.push(` # Controllers: ${vd.controllerAddresses.join(', ')}`); + lines.push(''); + } + + // Pools + config.pools.forEach((pool, i) => { + lines.push(` # Pool ${i + 1}`); + lines.push(` pool {`); + lines.push(` range ${pool.start} ${pool.end};`); + lines.push(` }`); + lines.push(''); + }); + + lines.push(`}`); + lines.push(''); + + // Client classes + if (config.classes && config.classes.length > 0) { + lines.push(`# Client classes`); + config.classes.forEach((cls) => { + lines.push(`class "${cls.name}" {`); + lines.push(` match if ${cls.matchRule};`); + if (cls.options?.option43) { + lines.push(` option vendor-encapsulated-options ${cls.options.option43};`); + } + if (cls.options?.dns) { + lines.push(` option domain-name-servers ${cls.options.dns.join(', ')};`); + } + lines.push(`}`); + lines.push(''); + }); + } + + // Host reservations + if (config.reservations && config.reservations.length > 0) { + lines.push(`# Static reservations`); + config.reservations.forEach((res) => { + const hostname = res.hostname || `host-${res.ipAddress.replace(/[.:]/g, '-')}`; + lines.push(`host ${hostname} {`); + lines.push(` hardware ethernet ${res.identifier};`); + lines.push(` fixed-address ${res.ipAddress};`); + if (res.hostname) { + lines.push(` option host-name "${res.hostname}";`); + } + lines.push(`}`); + lines.push(''); + }); + } + + return lines.join('\n'); +} + +/** + * Generate Kea DHCP snippet (JSON) + */ +function generateKeaSnippet(config: SnippetConfig, isV6: boolean): string { + const obj: any = { + subnet: config.subnet, + pools: config.pools.map((p) => ({ pool: `${p.start} - ${p.end}` })), + }; + + // Options + const optionData: any[] = []; + + if (config.gateway) { + optionData.push({ + name: isV6 ? 'unicast' : 'routers', + data: config.gateway, + }); + } + + if (config.dnsServers && config.dnsServers.length > 0) { + optionData.push({ + name: 'dns-servers', + data: config.dnsServers.join(', '), + }); + } + + if (config.domainName) { + optionData.push({ + name: 'domain-name', + data: config.domainName, + }); + } + + if (optionData.length > 0) { + obj['option-data'] = optionData; + } + + // Lease times + if (!isV6) { + if (config.defaultLeaseTime) obj['valid-lifetime'] = config.defaultLeaseTime; + if (config.maxLeaseTime) obj['max-valid-lifetime'] = config.maxLeaseTime; + } else { + if (config.preferredLifetime) obj['preferred-lifetime'] = config.preferredLifetime; + if (config.validLifetime) obj['valid-lifetime'] = config.validLifetime; + } + + // Client classes + if (config.classes && config.classes.length > 0) { + obj['client-classes'] = config.classes.map((cls) => ({ + name: cls.name, + test: cls.keaTest || cls.matchRule, + })); + } + + // Reservations + if (config.reservations && config.reservations.length > 0) { + obj.reservations = config.reservations.map((res) => ({ + [isV6 ? 'duid' : 'hw-address']: res.identifier, + 'ip-address': res.ipAddress, + hostname: res.hostname, + })); + } + + return JSON.stringify(obj, null, config.prettyJson ? 2 : 0); +} + +/** + * Generate summary text + */ +function generateSummary(config: SnippetConfig): string { + const parts: string[] = []; + + parts.push(`Subnet: ${config.subnet}`); + parts.push(`Pools: ${config.pools.length} range(s)`); + + if (config.gateway) parts.push(`Gateway: ${config.gateway}`); + if (config.dnsServers && config.dnsServers.length > 0) { + parts.push(`DNS: ${config.dnsServers.join(', ')}`); + } + + if (config.vendorDiscovery && config.vendorDiscovery.controllerAddresses.length > 0) { + const vd = config.vendorDiscovery; + parts.push( + `Vendor discovery: ${VENDOR_PRESETS_43[vd.preset].name} (${vd.controllerAddresses.length} controller(s))`, + ); + } + + if (config.classes && config.classes.length > 0) { + parts.push(`Client classes: ${config.classes.length}`); + } + + if (config.reservations && config.reservations.length > 0) { + parts.push(`Static reservations: ${config.reservations.length}`); + } + + return parts.join(' • '); +} + +/** + * Main generator function + */ +export function generateSnippets(config: SnippetConfig): SnippetResult { + const validations = validateConfig(config); + const result: SnippetResult = { + validations, + summary: generateSummary(config), + }; + + if (validations.length > 0) { + return result; + } + + const isV6 = config.mode === 'dhcp6'; + + if (config.targets.includes('isc-dhcpd')) { + result.iscDhcpdSnippet = generateISCSnippet(config); + } + + if (config.targets.includes('kea-dhcp4') && !isV6) { + result.keaDhcp4Snippet = generateKeaSnippet(config, false); + } + + if (config.targets.includes('kea-dhcp6') && isV6) { + result.keaDhcp6Snippet = generateKeaSnippet(config, true); + } + + return result; +} + +/** + * Get default configuration + */ +export function getDefaultSnippetConfig(): SnippetConfig { + return { + targets: ['isc-dhcpd', 'kea-dhcp4'], + mode: 'dhcp4', + subnet: '192.168.1.0/24', + pools: [{ start: '192.168.1.100', end: '192.168.1.200' }], + gateway: '192.168.1.1', + dnsServers: ['8.8.8.8', '8.8.4.4'], + defaultLeaseTime: 86400, + maxLeaseTime: 604800, + emitOptionNames: true, + prettyJson: true, + }; +} + +export { VENDOR_PRESETS_43 }; diff --git a/src/routes/dhcp/kea-isc-snippets/+page.svelte b/src/routes/dhcp/kea-isc-snippets/+page.svelte new file mode 100644 index 0000000..2a1d01a --- /dev/null +++ b/src/routes/dhcp/kea-isc-snippets/+page.svelte @@ -0,0 +1,11 @@ + + + + + diff --git a/tests/unit/utils/dhcp-snippets.test.ts b/tests/unit/utils/dhcp-snippets.test.ts new file mode 100644 index 0000000..0ecc400 --- /dev/null +++ b/tests/unit/utils/dhcp-snippets.test.ts @@ -0,0 +1,452 @@ +import { describe, it, expect } from 'vitest'; +import { + generateSnippets, + validateConfig, + getDefaultSnippetConfig, + type SnippetConfig, + type ValidationError, +} from '$lib/utils/dhcp-snippets.js'; + +describe('DHCP Snippets Generator', () => { + describe('getDefaultSnippetConfig', () => { + it('should return valid default configuration', () => { + const config = getDefaultSnippetConfig(); + + expect(config.targets).toEqual(['isc-dhcpd', 'kea-dhcp4']); + expect(config.mode).toBe('dhcp4'); + expect(config.subnet).toBe('192.168.1.0/24'); + expect(config.pools).toHaveLength(1); + expect(config.pools[0].start).toBe('192.168.1.100'); + expect(config.pools[0].end).toBe('192.168.1.200'); + expect(config.gateway).toBe('192.168.1.1'); + expect(config.dnsServers).toEqual(['8.8.8.8', '8.8.4.4']); + expect(config.defaultLeaseTime).toBe(86400); + expect(config.maxLeaseTime).toBe(604800); + }); + }); + + describe('validateConfig', () => { + it('should validate correct IPv4 configuration', () => { + const config = getDefaultSnippetConfig(); + const errors = validateConfig(config); + + expect(errors).toHaveLength(0); + }); + + it('should detect invalid CIDR notation', () => { + const config = getDefaultSnippetConfig(); + config.subnet = 'invalid'; + + const errors = validateConfig(config); + + expect(errors).toHaveLength(1); + expect(errors[0].field).toBe('subnet'); + expect(errors[0].message).toContain('Invalid CIDR notation'); + }); + + it('should detect mode mismatch for IPv4', () => { + const config = getDefaultSnippetConfig(); + config.mode = 'dhcp6'; // IPv6 mode with IPv4 subnet + + const errors = validateConfig(config); + + expect(errors.some((e) => e.field === 'mode')).toBe(true); + }); + + it('should detect mode mismatch for IPv6', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '2001:db8::/64'; + config.mode = 'dhcp4'; // IPv4 mode with IPv6 subnet + + const errors = validateConfig(config); + + expect(errors.some((e) => e.field === 'mode')).toBe(true); + }); + + it('should detect pool start IP outside subnet', () => { + const config = getDefaultSnippetConfig(); + config.pools[0].start = '10.0.0.1'; // Outside 192.168.1.0/24 + + const errors = validateConfig(config); + + expect(errors.some((e) => e.field === 'pools[0].start')).toBe(true); + }); + + it('should detect pool end IP outside subnet', () => { + const config = getDefaultSnippetConfig(); + config.pools[0].end = '10.0.0.254'; // Outside 192.168.1.0/24 + + const errors = validateConfig(config); + + expect(errors.some((e) => e.field === 'pools[0].end')).toBe(true); + }); + + it('should detect gateway outside subnet', () => { + const config = getDefaultSnippetConfig(); + config.gateway = '10.0.0.1'; // Outside 192.168.1.0/24 + + const errors = validateConfig(config); + + expect(errors.some((e) => e.field === 'gateway')).toBe(true); + }); + + it('should validate IPv6 configuration', () => { + const config = getDefaultSnippetConfig(); + config.mode = 'dhcp6'; + config.subnet = '2001:db8::/64'; + config.pools = [{ start: '2001:db8::100', end: '2001:db8::200' }]; + config.gateway = '2001:db8::1'; + + const errors = validateConfig(config); + + expect(errors).toHaveLength(0); + }); + + it('should validate multiple pools', () => { + const config = getDefaultSnippetConfig(); + config.pools = [ + { start: '192.168.1.10', end: '192.168.1.50' }, + { start: '192.168.1.100', end: '192.168.1.200' }, + ]; + + const errors = validateConfig(config); + + expect(errors).toHaveLength(0); + }); + + it('should detect multiple validation errors', () => { + const config = getDefaultSnippetConfig(); + config.pools[0].start = '10.0.0.1'; + config.pools[0].end = '10.0.0.254'; + config.gateway = '172.16.0.1'; + + const errors = validateConfig(config); + + expect(errors.length).toBeGreaterThan(1); + }); + }); + + describe('generateSnippets', () => { + it('should generate ISC dhcpd snippet', () => { + const config = getDefaultSnippetConfig(); + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toBeDefined(); + expect(result.iscDhcpdSnippet).toContain('subnet 192.168.1.0 netmask 255.255.255.0'); + expect(result.iscDhcpdSnippet).toContain('option routers 192.168.1.1'); + expect(result.iscDhcpdSnippet).toContain('option domain-name-servers 8.8.8.8, 8.8.4.4'); + expect(result.iscDhcpdSnippet).toContain('range 192.168.1.100 192.168.1.200'); + expect(result.iscDhcpdSnippet).toContain('default-lease-time 86400'); + expect(result.iscDhcpdSnippet).toContain('max-lease-time 604800'); + }); + + it('should generate Kea DHCPv4 snippet', () => { + const config = getDefaultSnippetConfig(); + const result = generateSnippets(config); + + expect(result.keaDhcp4Snippet).toBeDefined(); + + const keaConfig = JSON.parse(result.keaDhcp4Snippet!); + expect(keaConfig.subnet).toBe('192.168.1.0/24'); + expect(keaConfig.pools).toHaveLength(1); + expect(keaConfig.pools[0].pool).toBe('192.168.1.100 - 192.168.1.200'); + expect(keaConfig['option-data']).toBeDefined(); + expect(keaConfig['valid-lifetime']).toBe(86400); + }); + + it('should generate Kea DHCPv6 snippet', () => { + const config = getDefaultSnippetConfig(); + config.mode = 'dhcp6'; + config.subnet = '2001:db8::/64'; + config.pools = [{ start: '2001:db8::100', end: '2001:db8::200' }]; + config.gateway = '2001:db8::1'; + config.targets = ['kea-dhcp6']; + config.preferredLifetime = 3600; + config.validLifetime = 7200; + + const result = generateSnippets(config); + + expect(result.keaDhcp6Snippet).toBeDefined(); + + const keaConfig = JSON.parse(result.keaDhcp6Snippet!); + expect(keaConfig.subnet).toBe('2001:db8::/64'); + expect(keaConfig['preferred-lifetime']).toBe(3600); + expect(keaConfig['valid-lifetime']).toBe(7200); + }); + + it('should generate summary', () => { + const config = getDefaultSnippetConfig(); + const result = generateSnippets(config); + + expect(result.summary).toContain('Subnet: 192.168.1.0/24'); + expect(result.summary).toContain('Pools: 1 range(s)'); + expect(result.summary).toContain('Gateway: 192.168.1.1'); + expect(result.summary).toContain('DNS: 8.8.8.8, 8.8.4.4'); + }); + + it('should not generate snippets when validation fails', () => { + const config = getDefaultSnippetConfig(); + config.subnet = 'invalid'; + + const result = generateSnippets(config); + + expect(result.validations).toHaveLength(1); + expect(result.iscDhcpdSnippet).toBeUndefined(); + expect(result.keaDhcp4Snippet).toBeUndefined(); + }); + + it('should handle multiple pools in ISC snippet', () => { + const config = getDefaultSnippetConfig(); + config.pools = [ + { start: '192.168.1.10', end: '192.168.1.50' }, + { start: '192.168.1.100', end: '192.168.1.200' }, + ]; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('# Pool 1'); + expect(result.iscDhcpdSnippet).toContain('# Pool 2'); + expect(result.iscDhcpdSnippet).toContain('range 192.168.1.10 192.168.1.50'); + expect(result.iscDhcpdSnippet).toContain('range 192.168.1.100 192.168.1.200'); + }); + + it('should include domain name when provided', () => { + const config = getDefaultSnippetConfig(); + config.domainName = 'example.com'; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('option domain-name "example.com"'); + }); + + it('should generate only selected target snippets', () => { + const config = getDefaultSnippetConfig(); + config.targets = ['isc-dhcpd']; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toBeDefined(); + expect(result.keaDhcp4Snippet).toBeUndefined(); + }); + + it('should handle pretty JSON formatting', () => { + const config = getDefaultSnippetConfig(); + config.prettyJson = true; + + const result = generateSnippets(config); + + expect(result.keaDhcp4Snippet).toContain('\n'); + expect(result.keaDhcp4Snippet).toContain(' '); + }); + + it('should handle compact JSON formatting', () => { + const config = getDefaultSnippetConfig(); + config.prettyJson = false; + + const result = generateSnippets(config); + + expect(result.keaDhcp4Snippet).not.toContain('\n '); + }); + }); + + describe('ISC DHCP specific features', () => { + it('should correctly convert /24 to netmask', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '192.168.1.0/24'; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('netmask 255.255.255.0'); + }); + + it('should correctly convert /16 to netmask', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '172.16.0.0/16'; + config.pools = [{ start: '172.16.1.1', end: '172.16.1.254' }]; + config.gateway = '172.16.0.1'; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('netmask 255.255.0.0'); + }); + + it('should correctly convert /8 to netmask', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '10.0.0.0/8'; + config.pools = [{ start: '10.0.1.1', end: '10.0.1.254' }]; + config.gateway = '10.0.0.1'; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('netmask 255.0.0.0'); + }); + + it('should handle non-standard subnet masks', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '192.168.1.0/25'; + config.pools = [{ start: '192.168.1.1', end: '192.168.1.126' }]; + config.gateway = '192.168.1.127'; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('netmask 255.255.255.128'); + }); + }); + + describe('Kea DHCP specific features', () => { + it('should use correct option names for IPv4', () => { + const config = getDefaultSnippetConfig(); + const result = generateSnippets(config); + + const keaConfig = JSON.parse(result.keaDhcp4Snippet!); + const routerOption = keaConfig['option-data'].find((opt: any) => opt.name === 'routers'); + + expect(routerOption).toBeDefined(); + expect(routerOption.data).toBe('192.168.1.1'); + }); + + it('should include DNS servers in option-data', () => { + const config = getDefaultSnippetConfig(); + const result = generateSnippets(config); + + const keaConfig = JSON.parse(result.keaDhcp4Snippet!); + const dnsOption = keaConfig['option-data'].find((opt: any) => opt.name === 'dns-servers'); + + expect(dnsOption).toBeDefined(); + expect(dnsOption.data).toBe('8.8.8.8, 8.8.4.4'); + }); + + it('should not generate IPv4 snippet when mode is IPv6', () => { + const config = getDefaultSnippetConfig(); + config.mode = 'dhcp6'; + config.subnet = '2001:db8::/64'; + config.pools = [{ start: '2001:db8::100', end: '2001:db8::200' }]; + + const result = generateSnippets(config); + + expect(result.keaDhcp4Snippet).toBeUndefined(); + }); + + it('should not generate IPv6 snippet when mode is IPv4', () => { + const config = getDefaultSnippetConfig(); + config.targets = ['kea-dhcp6']; + + const result = generateSnippets(config); + + expect(result.keaDhcp6Snippet).toBeUndefined(); + }); + }); + + describe('Edge cases', () => { + it('should handle empty DNS servers', () => { + const config = getDefaultSnippetConfig(); + config.dnsServers = []; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).not.toContain('option domain-name-servers'); + }); + + it('should handle missing gateway', () => { + const config = getDefaultSnippetConfig(); + config.gateway = undefined; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).not.toContain('option routers'); + }); + + it('should handle missing domain name', () => { + const config = getDefaultSnippetConfig(); + config.domainName = undefined; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).not.toContain('option domain-name "'); + }); + + it('should handle /32 subnet', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '192.168.1.1/32'; + config.pools = [{ start: '192.168.1.1', end: '192.168.1.1' }]; + config.gateway = '192.168.1.1'; + + const result = generateSnippets(config); + + expect(result.iscDhcpdSnippet).toContain('netmask 255.255.255.255'); + }); + + it('should handle large subnet (/8)', () => { + const config = getDefaultSnippetConfig(); + config.subnet = '10.0.0.0/8'; + config.pools = [{ start: '10.1.1.1', end: '10.1.1.254' }]; + config.gateway = '10.0.0.1'; + + const errors = validateConfig(config); + + expect(errors).toHaveLength(0); + }); + }); + + describe('Summary generation', () => { + it('should include all configured options in summary', () => { + const config = getDefaultSnippetConfig(); + config.domainName = 'test.local'; + + const result = generateSnippets(config); + + expect(result.summary).toContain('Subnet'); + expect(result.summary).toContain('Pools'); + expect(result.summary).toContain('Gateway'); + expect(result.summary).toContain('DNS'); + }); + + it('should handle summary with multiple pools', () => { + const config = getDefaultSnippetConfig(); + config.pools = [ + { start: '192.168.1.10', end: '192.168.1.50' }, + { start: '192.168.1.100', end: '192.168.1.200' }, + { start: '192.168.1.210', end: '192.168.1.250' }, + ]; + + const result = generateSnippets(config); + + expect(result.summary).toContain('Pools: 3 range(s)'); + }); + }); + + describe('Validation error messages', () => { + it('should provide clear error for pool outside subnet', () => { + const config = getDefaultSnippetConfig(); + config.pools[0].start = '10.0.0.1'; + + const errors = validateConfig(config); + const poolError = errors.find((e) => e.field === 'pools[0].start'); + + expect(poolError).toBeDefined(); + expect(poolError?.message).toBe('Pool start IP outside subnet'); + }); + + it('should provide clear error for gateway outside subnet', () => { + const config = getDefaultSnippetConfig(); + config.gateway = '10.0.0.1'; + + const errors = validateConfig(config); + const gatewayError = errors.find((e) => e.field === 'gateway'); + + expect(gatewayError).toBeDefined(); + expect(gatewayError?.message).toBe('Gateway IP outside subnet'); + }); + + it('should provide clear error for mode mismatch', () => { + const config = getDefaultSnippetConfig(); + config.mode = 'dhcp6'; + + const errors = validateConfig(config); + const modeError = errors.find((e) => e.field === 'mode'); + + expect(modeError).toBeDefined(); + expect(modeError?.message).toContain('Mode mismatch'); + }); + }); +});