From fd550ca4f6d45371b940c65cee66bead01211463 Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sun, 19 Oct 2025 23:45:00 +0100 Subject: [PATCH] Freeform TLV Composer --- .../tools/FreeformTLVBuilder.svelte | 748 ++++++++++++++++++ src/lib/constants/nav.ts | 40 + src/lib/utils/dhcp-freeform-tlv.ts | 473 +++++++++++ .../dhcp/options/freeform-tlv/+page.svelte | 5 + tests/unit/utils/dhcp-freeform-tlv.test.ts | 311 ++++++++ 5 files changed, 1577 insertions(+) create mode 100644 src/lib/components/tools/FreeformTLVBuilder.svelte create mode 100644 src/lib/utils/dhcp-freeform-tlv.ts create mode 100644 src/routes/dhcp/options/freeform-tlv/+page.svelte create mode 100644 tests/unit/utils/dhcp-freeform-tlv.test.ts diff --git a/src/lib/components/tools/FreeformTLVBuilder.svelte b/src/lib/components/tools/FreeformTLVBuilder.svelte new file mode 100644 index 0000000..38a18c3 --- /dev/null +++ b/src/lib/components/tools/FreeformTLVBuilder.svelte @@ -0,0 +1,748 @@ + + + + ex.label} + getDescription={(ex) => ex.description} + selectedIndex={selectedExampleIndex} + /> + +
+
+

Option Configuration

+
+
+
+
+ + + DHCP option number (0-255, recommend 224-254 for custom) +
+ +
+ + + Descriptive name for this option +
+
+
+
+ +
+
+

Data Items

+

+ Add multiple data items to build the option payload. Each item will be encoded sequentially. +

+
+
+ {#each option.items as item, i (item.id)} +
+
+

Item {i + 1}

+ +
+ +
+ + + + {dataTypeOptions.find((t) => t.value === item.dataType)?.description} + +
+ +
+ + +
+
+ {/each} + + +
+
+ + {#if validationErrors.length > 0} +
+

Validation Errors

+ {#each validationErrors as error, i (i)} +
+ + {error} +
+ {/each} +
+ {/if} + + {#if result && validationErrors.length === 0} +
+

Encoded Option

+ +
+
Option Code: {result.option.optionCode}
+
Option Name: {result.option.optionName}
+
Data Length: {result.dataLength} bytes
+
Items: {result.option.items.length}
+
+ +
+
+

Hex-Encoded (Compact)

+ +
+
{result.hexEncoded}
+
+ +
+
+

Wire Format (Spaced)

+ +
+
{result.wireFormat}
+
+ + {#if result.breakdown.length > 0} +
+

Byte Breakdown

+ {#each result.breakdown as item, i (i)} +
+
{item.label}
+
{item.hex}
+
{item.description}
+
+ {/each} +
+ {/if} +
+ +
+

Configuration Examples

+ + {#if result.examples.iscDhcpd} +
+
+

ISC dhcpd Configuration

+ +
+
{result.examples.iscDhcpd}
+
+ {/if} + + {#if result.examples.keaDhcp4} +
+
+

Kea DHCPv4 Configuration

+ +
+
{result.examples.keaDhcp4}
+
+ {/if} +
+ +
+

About TLV Encoding

+

+ Type-Length-Value (TLV) is a common encoding scheme used in DHCP options. This tool allows you to compose custom + DHCP options by combining multiple data items of different types. +

+
    +
  • IPv4/IPv6: Network addresses encoded as raw bytes
  • +
  • FQDN: Domain names in DNS wire format (length-prefixed labels)
  • +
  • String: UTF-8 encoded text
  • +
  • UInt8/16/32: Unsigned integers of various sizes
  • +
  • Boolean: Single byte (0x00 or 0x01)
  • +
  • Hex: Raw hexadecimal bytes for custom data
  • +
+

+ The generated hex output represents the option data only. DHCP servers will automatically add the option code + and length fields when sending the option to clients. +

+
+ {/if} +
+ + diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index 584ce3e..24d7d07 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -1049,6 +1049,46 @@ export const SUB_NAV: Record = { 'firmware', ], }, + { + href: makePath('/dhcp/options/freeform-tlv'), + label: 'Freeform TLV Composer', + description: + 'Build custom DHCP options using Type-Length-Value encoding with support for IPv4, IPv6, FQDN, strings, hex data, and numeric types', + icon: 'tools', + keywords: [ + 'dhcp', + 'tlv', + 'type', + 'length', + 'value', + 'custom', + 'option', + 'freeform', + 'composer', + 'builder', + 'ipv4', + 'ipv6', + 'fqdn', + 'string', + 'hex', + 'uint8', + 'uint16', + 'uint32', + 'boolean', + 'encoder', + 'generator', + 'isc', + 'dhcpd', + 'kea', + 'configuration', + 'wire', + 'format', + 'vendor', + 'specific', + 'site', + 'local', + ], + }, ], '/dns': [ { diff --git a/src/lib/utils/dhcp-freeform-tlv.ts b/src/lib/utils/dhcp-freeform-tlv.ts new file mode 100644 index 0000000..26bd6e4 --- /dev/null +++ b/src/lib/utils/dhcp-freeform-tlv.ts @@ -0,0 +1,473 @@ +/** + * DHCP Freeform TLV (Type-Length-Value) Composer + * + * Allows creation of custom DHCP options with various data types. + * Supports IPv4, IPv6, FQDN, hex, string, uint8, uint16, uint32, and boolean values. + */ + +export type TLVDataType = 'ipv4' | 'ipv6' | 'fqdn' | 'hex' | 'string' | 'uint8' | 'uint16' | 'uint32' | 'boolean'; + +export interface TLVItem { + id: string; + dataType: TLVDataType; + value: string; +} + +export interface TLVOption { + optionCode: number; + optionName: string; + items: TLVItem[]; +} + +export interface TLVResult { + option: TLVOption; + hexEncoded: string; + wireFormat: string; + totalLength: number; + dataLength: number; + breakdown: Array<{ + label: string; + hex: string; + description: string; + }>; + examples: { + iscDhcpd?: string; + keaDhcp4?: string; + }; +} + +/** + * Validates an IPv4 address + */ +function validateIPv4(ip: string): boolean { + const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; + if (!ipv4Regex.test(ip)) return false; + + const octets = ip.split('.').map((o) => parseInt(o, 10)); + return octets.every((o) => o >= 0 && o <= 255); +} + +/** + * Validates an IPv6 address (simplified validation) + */ +function validateIPv6(ip: string): boolean { + // Simplified IPv6 validation - accepts standard and compressed formats + const ipv6Regex = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/; + const ipv6CompressedRegex = /^::([0-9a-fA-F]{0,4}:){0,6}[0-9a-fA-F]{0,4}$/; + const ipv6MixedRegex = /^([0-9a-fA-F]{0,4}:){6}\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + + return ipv6Regex.test(ip) || ipv6CompressedRegex.test(ip) || ipv6MixedRegex.test(ip); +} + +/** + * Converts IPv4 address to hex bytes + */ +function ipv4ToHex(ip: string): string { + const octets = ip.split('.').map((o) => parseInt(o, 10)); + return octets.map((o) => o.toString(16).padStart(2, '0')).join(''); +} + +/** + * Converts IPv6 address to hex bytes + */ +function ipv6ToHex(ip: string): string { + // Expand compressed IPv6 addresses + let expanded = ip; + + // Handle :: compression + if (ip.includes('::')) { + const parts = ip.split('::'); + const leftParts = parts[0] ? parts[0].split(':') : []; + const rightParts = parts[1] ? parts[1].split(':') : []; + const missingParts = 8 - leftParts.length - rightParts.length; + const middleParts = Array(missingParts).fill('0000'); + expanded = [...leftParts, ...middleParts, ...rightParts].join(':'); + } + + // Pad each segment to 4 hex digits + const segments = expanded.split(':').map((seg) => seg.padStart(4, '0')); + + // Convert to hex bytes + return segments.join(''); +} + +/** + * Converts a string to hex bytes (UTF-8 encoding) + */ +function stringToHex(str: string): string { + const encoder = new TextEncoder(); + const bytes = encoder.encode(str); + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); +} + +/** + * Validates hex string + */ +function validateHex(hex: string): boolean { + return /^[0-9a-fA-F]*$/.test(hex.replace(/[\s:]/g, '')); +} + +/** + * Normalizes hex string (removes spaces and colons) + */ +function normalizeHex(hex: string): string { + return hex.replace(/[\s:]/g, '').toLowerCase(); +} + +/** + * Validates FQDN (Fully Qualified Domain Name) + */ +function validateFQDN(fqdn: string): boolean { + // Basic FQDN validation + const fqdnRegex = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/; + return fqdnRegex.test(fqdn) && fqdn.length <= 253; +} + +/** + * Converts FQDN to DNS wire format (length-prefixed labels) + */ +function fqdnToHex(fqdn: string): string { + const labels = fqdn.split('.'); + let hex = ''; + + for (const label of labels) { + const labelLength = label.length; + hex += labelLength.toString(16).padStart(2, '0'); + hex += stringToHex(label); + } + + // Add null terminator + hex += '00'; + + return hex; +} + +/** + * Validates a TLV item based on its data type + */ +export function validateTLVItem(item: TLVItem): string | null { + if (!item.value.trim()) { + return `${item.dataType.toUpperCase()}: Value is required`; + } + + switch (item.dataType) { + case 'ipv4': + if (!validateIPv4(item.value)) { + return `IPv4: Invalid address format`; + } + break; + + case 'ipv6': + if (!validateIPv6(item.value)) { + return `IPv6: Invalid address format`; + } + break; + + case 'fqdn': + if (!validateFQDN(item.value)) { + return `FQDN: Invalid domain name format`; + } + break; + + case 'hex': + if (!validateHex(item.value)) { + return `Hex: Only hexadecimal characters allowed`; + } + if (normalizeHex(item.value).length % 2 !== 0) { + return `Hex: Must have an even number of hex digits`; + } + break; + + case 'string': + if (item.value.length > 255) { + return `String: Maximum length is 255 characters`; + } + break; + + case 'uint8': { + const val = parseInt(item.value, 10); + if (isNaN(val) || val < 0 || val > 255) { + return `UInt8: Must be a number between 0 and 255`; + } + break; + } + + case 'uint16': { + const val = parseInt(item.value, 10); + if (isNaN(val) || val < 0 || val > 65535) { + return `UInt16: Must be a number between 0 and 65535`; + } + break; + } + + case 'uint32': { + const val = parseInt(item.value, 10); + if (isNaN(val) || val < 0 || val > 4294967295) { + return `UInt32: Must be a number between 0 and 4294967295`; + } + break; + } + + case 'boolean': + if (item.value !== '0' && item.value !== '1' && item.value !== 'true' && item.value !== 'false') { + return `Boolean: Must be 0, 1, true, or false`; + } + break; + } + + return null; +} + +/** + * Validates a TLV option + */ +export function validateTLVOption(option: TLVOption): string[] { + const errors: string[] = []; + + // Validate option code + if (option.optionCode < 0 || option.optionCode > 255) { + errors.push('Option code must be between 0 and 255'); + } + + // Validate option name + if (!option.optionName.trim()) { + errors.push('Option name is required'); + } + + // Validate items + if (option.items.length === 0) { + errors.push('At least one data item is required'); + } + + // Validate each item + for (let i = 0; i < option.items.length; i++) { + const itemError = validateTLVItem(option.items[i]); + if (itemError) { + errors.push(`Item ${i + 1}: ${itemError}`); + } + } + + return errors; +} + +/** + * Encodes a TLV item to hex bytes + */ +function encodeTLVItem(item: TLVItem): string { + switch (item.dataType) { + case 'ipv4': + return ipv4ToHex(item.value); + + case 'ipv6': + return ipv6ToHex(item.value); + + case 'fqdn': + return fqdnToHex(item.value); + + case 'hex': + return normalizeHex(item.value); + + case 'string': + return stringToHex(item.value); + + case 'uint8': { + const val = parseInt(item.value, 10); + return val.toString(16).padStart(2, '0'); + } + + case 'uint16': { + const val = parseInt(item.value, 10); + return val.toString(16).padStart(4, '0'); + } + + case 'uint32': { + const val = parseInt(item.value, 10); + return val.toString(16).padStart(8, '0'); + } + + case 'boolean': { + const val = item.value === '1' || item.value === 'true' ? 1 : 0; + return val.toString(16).padStart(2, '0'); + } + + default: + return ''; + } +} + +/** + * Formats hex string as wire format (with spaces) + */ +function formatWireFormat(hex: string): string { + return hex.match(/.{1,2}/g)?.join(' ') || ''; +} + +/** + * Generates DHCP configuration examples + */ +function generateConfigExamples(result: TLVResult): { + iscDhcpd?: string; + keaDhcp4?: string; +} { + const { option, hexEncoded } = result; + const wireFormat = formatWireFormat(hexEncoded); + + // ISC dhcpd configuration + const iscDhcpd = `# ${option.optionName} (Option ${option.optionCode}) +option space custom-options; +option custom-options.${option.optionName.toLowerCase().replace(/\s+/g, '-')} code ${option.optionCode} = string; + +subnet 192.168.1.0 netmask 255.255.255.0 { + range 192.168.1.100 192.168.1.200; + option custom-options.${option.optionName.toLowerCase().replace(/\s+/g, '-')} ${wireFormat}; +}`; + + // Kea DHCPv4 configuration + const keaDhcp4 = `{ + "Dhcp4": { + "subnet4": [ + { + "subnet": "192.168.1.0/24", + "pools": [ + { + "pool": "192.168.1.100 - 192.168.1.200" + } + ], + "option-data": [ + { + "name": "${option.optionName}", + "code": ${option.optionCode}, + "data": "${hexEncoded}", + "csv-format": false + } + ] + } + ] + } +}`; + + return { + iscDhcpd, + keaDhcp4, + }; +} + +/** + * Builds a DHCP TLV option + */ +export function buildTLVOption(option: TLVOption): TLVResult { + const errors = validateTLVOption(option); + if (errors.length > 0) { + throw new Error(errors.join('; ')); + } + + // Encode all items + let dataHex = ''; + const breakdown: Array<{ label: string; hex: string; description: string }> = []; + + for (let i = 0; i < option.items.length; i++) { + const item = option.items[i]; + const itemHex = encodeTLVItem(item); + dataHex += itemHex; + + breakdown.push({ + label: `Item ${i + 1} (${item.dataType})`, + hex: formatWireFormat(itemHex), + description: `${item.value} encoded as ${item.dataType.toUpperCase()}`, + }); + } + + const dataLength = dataHex.length / 2; // Convert hex chars to bytes + const totalLength = dataLength; // For DHCP options, total length = data length + + const result: TLVResult = { + option, + hexEncoded: dataHex, + wireFormat: formatWireFormat(dataHex), + totalLength, + dataLength, + breakdown, + examples: {}, + }; + + result.examples = generateConfigExamples(result); + + return result; +} + +/** + * Returns a default TLV option + */ +export function getDefaultTLVOption(): TLVOption { + return { + optionCode: 224, // Start of site-specific options range + optionName: 'Custom Option', + items: [], + }; +} + +/** + * Creates a new TLV item with a unique ID + */ +export function createTLVItem(dataType: TLVDataType = 'string'): TLVItem { + return { + id: crypto.randomUUID(), + dataType, + value: '', + }; +} + +/** + * Example TLV options for quick start + */ +export const TLV_EXAMPLES: TLVOption[] = [ + { + optionCode: 224, + optionName: 'Custom Server List', + items: [ + { id: '1', dataType: 'ipv4', value: '192.168.1.10' }, + { id: '2', dataType: 'ipv4', value: '192.168.1.11' }, + ], + }, + { + optionCode: 225, + optionName: 'Custom Config Server', + items: [{ id: '1', dataType: 'fqdn', value: 'config.example.com' }], + }, + { + optionCode: 226, + optionName: 'Custom Flags', + items: [ + { id: '1', dataType: 'boolean', value: 'true' }, + { id: '2', dataType: 'uint8', value: '5' }, + { id: '3', dataType: 'uint16', value: '8080' }, + ], + }, + { + optionCode: 227, + optionName: 'Custom Hex Data', + items: [{ id: '1', dataType: 'hex', value: 'deadbeef' }], + }, + { + optionCode: 228, + optionName: 'VoIP Configuration', + items: [ + { id: '1', dataType: 'ipv4', value: '10.0.0.50' }, + { id: '2', dataType: 'uint16', value: '5060' }, + { id: '3', dataType: 'fqdn', value: 'sip.voip.local' }, + { id: '4', dataType: 'string', value: 'domain=internal' }, + ], + }, + { + optionCode: 229, + optionName: 'IoT Device Profile', + items: [ + { id: '1', dataType: 'uint32', value: '3600' }, + { id: '2', dataType: 'ipv6', value: '2001:db8::1' }, + { id: '3', dataType: 'uint8', value: '10' }, + { id: '4', dataType: 'boolean', value: 'false' }, + ], + }, +]; diff --git a/src/routes/dhcp/options/freeform-tlv/+page.svelte b/src/routes/dhcp/options/freeform-tlv/+page.svelte new file mode 100644 index 0000000..15679c9 --- /dev/null +++ b/src/routes/dhcp/options/freeform-tlv/+page.svelte @@ -0,0 +1,5 @@ + + + diff --git a/tests/unit/utils/dhcp-freeform-tlv.test.ts b/tests/unit/utils/dhcp-freeform-tlv.test.ts new file mode 100644 index 0000000..623b907 --- /dev/null +++ b/tests/unit/utils/dhcp-freeform-tlv.test.ts @@ -0,0 +1,311 @@ +import { describe, it, expect } from 'vitest'; +import { + validateTLVItem, + validateTLVOption, + buildTLVOption, + createTLVItem, + getDefaultTLVOption, + type TLVItem, + type TLVOption, +} from '$lib/utils/dhcp-freeform-tlv'; + +describe('dhcp-freeform-tlv', () => { + describe('validateTLVItem', () => { + it('should validate IPv4 addresses correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'ipv4', value: '192.168.1.1' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const invalidItem: TLVItem = { id: '1', dataType: 'ipv4', value: '256.1.1.1' }; + expect(validateTLVItem(invalidItem)).toContain('Invalid address format'); + }); + + it('should validate IPv6 addresses correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'ipv6', value: '2001:db8::1' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const invalidItem: TLVItem = { id: '1', dataType: 'ipv6', value: 'invalid' }; + expect(validateTLVItem(invalidItem)).toContain('Invalid address format'); + }); + + it('should validate FQDN correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'fqdn', value: 'example.com' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const invalidItem: TLVItem = { id: '1', dataType: 'fqdn', value: '-invalid-.com' }; + expect(validateTLVItem(invalidItem)).toContain('Invalid domain name format'); + }); + + it('should validate hex strings correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'hex', value: 'deadbeef' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const invalidOddLength: TLVItem = { id: '1', dataType: 'hex', value: 'abc' }; + expect(validateTLVItem(invalidOddLength)).toContain('even number of hex digits'); + + const invalidChars: TLVItem = { id: '1', dataType: 'hex', value: 'xyz' }; + expect(validateTLVItem(invalidChars)).toContain('hexadecimal characters'); + }); + + it('should validate uint8 correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'uint8', value: '255' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const outOfRange: TLVItem = { id: '1', dataType: 'uint8', value: '256' }; + expect(validateTLVItem(outOfRange)).toContain('0 and 255'); + }); + + it('should validate uint16 correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'uint16', value: '65535' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const outOfRange: TLVItem = { id: '1', dataType: 'uint16', value: '65536' }; + expect(validateTLVItem(outOfRange)).toContain('0 and 65535'); + }); + + it('should validate uint32 correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'uint32', value: '4294967295' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const outOfRange: TLVItem = { id: '1', dataType: 'uint32', value: '4294967296' }; + expect(validateTLVItem(outOfRange)).toContain('0 and 4294967295'); + }); + + it('should validate boolean correctly', () => { + const validTrue: TLVItem = { id: '1', dataType: 'boolean', value: 'true' }; + expect(validateTLVItem(validTrue)).toBeNull(); + + const validOne: TLVItem = { id: '1', dataType: 'boolean', value: '1' }; + expect(validateTLVItem(validOne)).toBeNull(); + + const invalid: TLVItem = { id: '1', dataType: 'boolean', value: 'yes' }; + expect(validateTLVItem(invalid)).toContain('0, 1, true, or false'); + }); + + it('should validate string length correctly', () => { + const validItem: TLVItem = { id: '1', dataType: 'string', value: 'Hello World' }; + expect(validateTLVItem(validItem)).toBeNull(); + + const tooLong: TLVItem = { id: '1', dataType: 'string', value: 'a'.repeat(256) }; + expect(validateTLVItem(tooLong)).toContain('Maximum length is 255'); + }); + + it('should reject empty values', () => { + const emptyItem: TLVItem = { id: '1', dataType: 'string', value: '' }; + expect(validateTLVItem(emptyItem)).toContain('Value is required'); + }); + }); + + describe('validateTLVOption', () => { + it('should validate option code range', () => { + const invalidLow: TLVOption = { + optionCode: -1, + optionName: 'Test', + items: [{ id: '1', dataType: 'string', value: 'test' }], + }; + expect(validateTLVOption(invalidLow)).toContain('Option code must be between 0 and 255'); + + const invalidHigh: TLVOption = { + optionCode: 256, + optionName: 'Test', + items: [{ id: '1', dataType: 'string', value: 'test' }], + }; + expect(validateTLVOption(invalidHigh)).toContain('Option code must be between 0 and 255'); + }); + + it('should require option name', () => { + const noName: TLVOption = { + optionCode: 224, + optionName: '', + items: [{ id: '1', dataType: 'string', value: 'test' }], + }; + expect(validateTLVOption(noName)).toContain('Option name is required'); + }); + + it('should require at least one item', () => { + const noItems: TLVOption = { + optionCode: 224, + optionName: 'Test', + items: [], + }; + expect(validateTLVOption(noItems)).toContain('At least one data item is required'); + }); + + it('should validate all items and return all errors', () => { + const multipleErrors: TLVOption = { + optionCode: 224, + optionName: 'Test', + items: [ + { id: '1', dataType: 'ipv4', value: '999.999.999.999' }, + { id: '2', dataType: 'uint8', value: '300' }, + ], + }; + const errors = validateTLVOption(multipleErrors); + expect(errors.length).toBeGreaterThan(1); + }); + }); + + describe('buildTLVOption', () => { + it('should encode IPv4 addresses correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test IPv4', + items: [{ id: '1', dataType: 'ipv4', value: '192.168.1.1' }], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('c0a80101'); + expect(result.wireFormat).toBe('c0 a8 01 01'); + expect(result.dataLength).toBe(4); + }); + + it('should encode hex data correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test Hex', + items: [{ id: '1', dataType: 'hex', value: 'DE AD BE EF' }], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('deadbeef'); + expect(result.dataLength).toBe(4); + }); + + it('should encode strings correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test String', + items: [{ id: '1', dataType: 'string', value: 'hello' }], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('68656c6c6f'); + expect(result.dataLength).toBe(5); + }); + + it('should encode uint8 correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test UInt8', + items: [{ id: '1', dataType: 'uint8', value: '255' }], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('ff'); + expect(result.dataLength).toBe(1); + }); + + it('should encode uint16 correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test UInt16', + items: [{ id: '1', dataType: 'uint16', value: '8080' }], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('1f90'); + expect(result.dataLength).toBe(2); + }); + + it('should encode uint32 correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test UInt32', + items: [{ id: '1', dataType: 'uint32', value: '3600' }], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('00000e10'); + expect(result.dataLength).toBe(4); + }); + + it('should encode boolean correctly', () => { + const optionTrue: TLVOption = { + optionCode: 224, + optionName: 'Test Boolean', + items: [{ id: '1', dataType: 'boolean', value: 'true' }], + }; + const resultTrue = buildTLVOption(optionTrue); + expect(resultTrue.hexEncoded).toBe('01'); + + const optionFalse: TLVOption = { + optionCode: 224, + optionName: 'Test Boolean', + items: [{ id: '1', dataType: 'boolean', value: '0' }], + }; + const resultFalse = buildTLVOption(optionFalse); + expect(resultFalse.hexEncoded).toBe('00'); + }); + + it('should encode FQDN with DNS wire format', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test FQDN', + items: [{ id: '1', dataType: 'fqdn', value: 'example.com' }], + }; + const result = buildTLVOption(option); + // 07 (length) + example + 03 (length) + com + 00 (null terminator) + expect(result.hexEncoded).toBe('076578616d706c6503636f6d00'); + }); + + it('should encode multiple items correctly', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Test Multiple', + items: [ + { id: '1', dataType: 'uint8', value: '5' }, + { id: '2', dataType: 'uint16', value: '8080' }, + ], + }; + const result = buildTLVOption(option); + expect(result.hexEncoded).toBe('051f90'); + expect(result.dataLength).toBe(3); + expect(result.breakdown.length).toBe(2); + }); + + it('should generate configuration examples', () => { + const option: TLVOption = { + optionCode: 224, + optionName: 'Custom Option', + items: [{ id: '1', dataType: 'string', value: 'test' }], + }; + const result = buildTLVOption(option); + expect(result.examples.iscDhcpd).toBeDefined(); + expect(result.examples.keaDhcp4).toBeDefined(); + expect(result.examples.iscDhcpd).toContain('option space custom-options'); + expect(result.examples.keaDhcp4).toContain('"code": 224'); + }); + + it('should throw error for invalid option', () => { + const invalidOption: TLVOption = { + optionCode: 300, + optionName: '', + items: [], + }; + expect(() => buildTLVOption(invalidOption)).toThrow(); + }); + }); + + describe('createTLVItem', () => { + it('should create item with default dataType', () => { + const item = createTLVItem(); + expect(item.dataType).toBe('string'); + expect(item.value).toBe(''); + expect(item.id).toBeDefined(); + }); + + it('should create item with specified dataType', () => { + const item = createTLVItem('ipv4'); + expect(item.dataType).toBe('ipv4'); + expect(item.value).toBe(''); + }); + + it('should generate unique IDs', () => { + const item1 = createTLVItem(); + const item2 = createTLVItem(); + expect(item1.id).not.toBe(item2.id); + }); + }); + + describe('getDefaultTLVOption', () => { + it('should return default option with option code 224', () => { + const defaultOption = getDefaultTLVOption(); + expect(defaultOption.optionCode).toBe(224); + expect(defaultOption.optionName).toBe('Custom Option'); + expect(defaultOption.items).toEqual([]); + }); + }); +});