Freeform TLV Composer

This commit is contained in:
Alicia Sykes committed 2025-10-20 23:46:33 +01:00
1 parent 1277349157
commit fd550ca4f6
5 files changed
+1577

No files matched your search

@@ -0,0 +1,748 @@
<script lang="ts">
import { untrack } from 'svelte';
import Icon from '$lib/components/global/Icon.svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import ExamplesCard from '$lib/components/common/ExamplesCard.svelte';
import { useClipboard } from '$lib/composables';
import {
type TLVOption,
type TLVResult,
type TLVDataType,
buildTLVOption,
getDefaultTLVOption,
validateTLVOption,
createTLVItem,
TLV_EXAMPLES,
} from '$lib/utils/dhcp-freeform-tlv';
let option = $state<TLVOption>({
...getDefaultTLVOption(),
items: [createTLVItem('string')],
});
let result = $state<TLVResult | null>(null);
let validationErrors = $state<string[]>([]);
let selectedExampleIndex = $state<number | null>(null);
const clipboard = useClipboard();
interface TLVExample {
label: string;
option: TLVOption;
description: string;
}
const examples: TLVExample[] = TLV_EXAMPLES.map((ex) => ({
label: ex.optionName,
option: ex,
description: `Option ${ex.optionCode}: ${ex.items.length} item${ex.items.length > 1 ? 's' : ''} - ${ex.items.map((i) => i.dataType).join(', ')}`,
}));
const dataTypeOptions: Array<{ value: TLVDataType; label: string; description: string }> = [
{ value: 'ipv4', label: 'IPv4 Address', description: '4 bytes, e.g., 192.168.1.1' },
{ value: 'ipv6', label: 'IPv6 Address', description: '16 bytes, e.g., 2001:db8::1' },
{ value: 'fqdn', label: 'Domain Name (FQDN)', description: 'DNS wire format with length prefixes' },
{ value: 'string', label: 'String (UTF-8)', description: 'Text encoded as UTF-8 bytes' },
{ value: 'hex', label: 'Raw Hex', description: 'Direct hex bytes' },
{ value: 'uint8', label: 'UInt8', description: '1 byte unsigned integer (0-255)' },
{ value: 'uint16', label: 'UInt16', description: '2 byte unsigned integer (0-65535)' },
{ value: 'uint32', label: 'UInt32', description: '4 byte unsigned integer (0-4294967295)' },
{ value: 'boolean', label: 'Boolean', description: '1 byte (0 or 1)' },
];
function loadExample(example: TLVExample, index: number): void {
// Deep copy the option to avoid reference issues
option = {
...example.option,
items: example.option.items.map((item) => ({ ...item, id: crypto.randomUUID() })),
};
selectedExampleIndex = index;
}
function checkIfExampleStillMatches(): void {
if (selectedExampleIndex === null) return;
const example = examples[selectedExampleIndex];
if (!example) {
selectedExampleIndex = null;
return;
}
const matches =
option.optionCode === example.option.optionCode &&
option.optionName === example.option.optionName &&
option.items.length === example.option.items.length &&
option.items.every(
(item, i) => item.dataType === example.option.items[i].dataType && item.value === example.option.items[i].value,
);
if (!matches) {
selectedExampleIndex = null;
}
}
function addItem(): void {
option.items = [...option.items, createTLVItem('string')];
}
function removeItem(id: string): void {
if (option.items.length > 1) {
option.items = option.items.filter((item) => item.id !== id);
}
}
function getPlaceholder(dataType: TLVDataType): string {
switch (dataType) {
case 'ipv4':
return '192.168.1.1';
case 'ipv6':
return '2001:db8::1';
case 'fqdn':
return 'example.com';
case 'string':
return 'Enter text';
case 'hex':
return 'deadbeef or DE AD BE EF';
case 'uint8':
return '0-255';
case 'uint16':
return '0-65535';
case 'uint32':
return '0-4294967295';
case 'boolean':
return '0, 1, true, or false';
default:
return '';
}
}
$effect(() => {
// Read option properties to trigger effect when they change
const currentOptionCode = option.optionCode;
const currentOptionName = option.optionName;
const _currentItems = option.items.map((item) => ({
dataType: item.dataType,
value: item.value,
}));
// Update validationErrors and result without tracking them (prevents infinite loop)
untrack(() => {
const currentOption: TLVOption = {
optionCode: currentOptionCode,
optionName: currentOptionName,
items: option.items,
};
// Check if form is in initial empty state (1 item with no value)
const isInitialState = currentOption.items.length === 1 && !currentOption.items[0].value.trim();
if (isInitialState) {
validationErrors = [];
result = null;
} else {
validationErrors = validateTLVOption(currentOption);
if (validationErrors.length === 0) {
try {
result = buildTLVOption(currentOption);
} catch (e) {
validationErrors = [e instanceof Error ? e.message : String(e)];
result = null;
}
} else {
result = null;
}
}
checkIfExampleStillMatches();
});
});
</script>
<ToolContentContainer
title="Freeform TLV Composer"
description="Build custom DHCP options using Type-Length-Value encoding. Support for IPv4, IPv6, FQDN, strings, hex data, and numeric types with live hex preview."
>
<ExamplesCard
{examples}
onSelect={loadExample}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
selectedIndex={selectedExampleIndex}
/>
<div class="card input-card">
<div class="card-header">
<h3>Option Configuration</h3>
</div>
<div class="card-content">
<div class="input-row">
<div class="input-group">
<label for="option-code">
<Icon name="hash" size="sm" />
Option Code
<span class="required">*</span>
</label>
<input id="option-code" type="number" bind:value={option.optionCode} min="0" max="255" placeholder="224" />
<span class="help-text">DHCP option number (0-255, recommend 224-254 for custom)</span>
</div>
<div class="input-group">
<label for="option-name">
<Icon name="tag" size="sm" />
Option Name
<span class="required">*</span>
</label>
<input id="option-name" type="text" bind:value={option.optionName} placeholder="e.g., Custom Server Option" />
<span class="help-text">Descriptive name for this option</span>
</div>
</div>
</div>
</div>
<div class="card input-card">
<div class="card-header">
<h3>Data Items</h3>
<p class="help-text">
Add multiple data items to build the option payload. Each item will be encoded sequentially.
</p>
</div>
<div class="card-content items-container">
{#each option.items as item, i (item.id)}
<div class="item-card">
<div class="item-header">
<h4>Item {i + 1}</h4>
<button
type="button"
class="btn-icon btn-remove"
onclick={() => removeItem(item.id)}
disabled={option.items.length === 1}
aria-label="Remove item"
>
<Icon name="x" size="sm" />
</button>
</div>
<div class="input-group">
<label for="datatype-{item.id}">
<Icon name="binary" size="sm" />
Data Type
</label>
<select id="datatype-{item.id}" bind:value={item.dataType}>
{#each dataTypeOptions as typeOption (typeOption.value)}
<option value={typeOption.value}>{typeOption.label}</option>
{/each}
</select>
<span class="help-text">
{dataTypeOptions.find((t) => t.value === item.dataType)?.description}
</span>
</div>
<div class="input-group">
<label for="value-{item.id}">
<Icon name="edit" size="sm" />
Value
</label>
<input
id="value-{item.id}"
type="text"
bind:value={item.value}
placeholder={getPlaceholder(item.dataType)}
/>
</div>
</div>
{/each}
<button type="button" class="btn-add" onclick={addItem}>
<Icon name="plus" size="sm" />
Add Data Item
</button>
</div>
</div>
{#if validationErrors.length > 0}
<div class="card errors-card">
<h3>Validation Errors</h3>
{#each validationErrors as error, i (i)}
<div class="error-message">
<Icon name="alert-triangle" size="sm" />
{error}
</div>
{/each}
</div>
{/if}
{#if result && validationErrors.length === 0}
<div class="card results">
<h3>Encoded Option</h3>
<div class="summary-card">
<div><strong>Option Code:</strong> {result.option.optionCode}</div>
<div><strong>Option Name:</strong> {result.option.optionName}</div>
<div><strong>Data Length:</strong> {result.dataLength} bytes</div>
<div><strong>Items:</strong> {result.option.items.length}</div>
</div>
<div class="output-group">
<div class="output-header">
<h4>Hex-Encoded (Compact)</h4>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied('hex')}
onclick={() => clipboard.copy(result!.hexEncoded, 'hex')}
>
<Icon name={clipboard.isCopied('hex') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('hex') ? 'Copied' : 'Copy'}
</button>
</div>
<pre class="output-value code-block">{result.hexEncoded}</pre>
</div>
<div class="output-group">
<div class="output-header">
<h4>Wire Format (Spaced)</h4>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied('wire')}
onclick={() => clipboard.copy(result!.wireFormat, 'wire')}
>
<Icon name={clipboard.isCopied('wire') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('wire') ? 'Copied' : 'Copy'}
</button>
</div>
<pre class="output-value code-block">{result.wireFormat}</pre>
</div>
{#if result.breakdown.length > 0}
<div class="breakdown-section">
<h4>Byte Breakdown</h4>
{#each result.breakdown as item, i (i)}
<div class="breakdown-item">
<div class="breakdown-label">{item.label}</div>
<div class="breakdown-hex">{item.hex}</div>
<div class="breakdown-desc">{item.description}</div>
</div>
{/each}
</div>
{/if}
</div>
<div class="card results">
<h3>Configuration Examples</h3>
{#if result.examples.iscDhcpd}
<div class="output-group">
<div class="output-header">
<h4>ISC dhcpd Configuration</h4>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied('isc')}
onclick={() => clipboard.copy(result!.examples.iscDhcpd!, 'isc')}
>
<Icon name={clipboard.isCopied('isc') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('isc') ? 'Copied' : 'Copy'}
</button>
</div>
<pre class="output-value code-block">{result.examples.iscDhcpd}</pre>
</div>
{/if}
{#if result.examples.keaDhcp4}
<div class="output-group">
<div class="output-header">
<h4>Kea DHCPv4 Configuration</h4>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied('kea')}
onclick={() => clipboard.copy(result!.examples.keaDhcp4!, 'kea')}
>
<Icon name={clipboard.isCopied('kea') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('kea') ? 'Copied' : 'Copy'}
</button>
</div>
<pre class="output-value code-block">{result.examples.keaDhcp4}</pre>
</div>
{/if}
</div>
<div class="card results info-card">
<h3>About TLV Encoding</h3>
<p>
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.
</p>
<ul>
<li><strong>IPv4/IPv6:</strong> Network addresses encoded as raw bytes</li>
<li><strong>FQDN:</strong> Domain names in DNS wire format (length-prefixed labels)</li>
<li><strong>String:</strong> UTF-8 encoded text</li>
<li><strong>UInt8/16/32:</strong> Unsigned integers of various sizes</li>
<li><strong>Boolean:</strong> Single byte (0x00 or 0x01)</li>
<li><strong>Hex:</strong> Raw hexadecimal bytes for custom data</li>
</ul>
<p>
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.
</p>
</div>
{/if}
</ToolContentContainer>
<style lang="scss">
.card {
background: var(--bg-secondary);
border-radius: var(--radius-lg);
padding: var(--spacing-lg);
border: 1px solid var(--border-primary);
margin-bottom: var(--spacing-lg);
&.input-card {
background: var(--bg-tertiary);
.card-header {
margin-bottom: var(--spacing-sm);
}
}
h3 {
display: flex;
align-items: center;
gap: var(--spacing-sm);
margin: 0 0 var(--spacing-sm);
font-size: 1.25rem;
color: var(--text-primary);
}
h4 {
margin: 0;
font-size: 1rem;
font-weight: 600;
color: var(--text-primary);
}
}
.card-header {
.help-text {
margin: var(--spacing-xs) 0 0;
font-size: 0.875rem;
color: var(--text-secondary);
font-style: italic;
}
}
.card-content {
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.input-group {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
label {
display: flex;
align-items: center;
gap: var(--spacing-xs);
font-weight: 500;
font-size: 0.875rem;
color: var(--text-primary);
}
input,
select {
padding: var(--spacing-sm);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
color: var(--text-primary);
font-family: inherit;
font-size: 0.9375rem;
transition: all 0.2s ease;
&:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary), transparent 90%);
}
}
select {
cursor: pointer;
}
}
.input-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--spacing-md);
@media (max-width: 768px) {
grid-template-columns: 1fr;
}
}
.required {
color: var(--color-error);
}
.help-text {
font-size: 0.75rem;
color: var(--text-tertiary);
font-style: italic;
}
.items-container {
gap: var(--spacing-lg);
}
.item-card {
padding: var(--spacing-md);
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.item-header {
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: var(--spacing-sm);
border-bottom: 1px solid var(--border-secondary);
}
.btn-icon {
display: flex;
align-items: center;
justify-content: center;
padding: var(--spacing-xs);
background: transparent;
border: 1px solid var(--border-secondary);
border-radius: var(--radius-sm);
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s ease;
&:hover:not(:disabled) {
background: var(--surface-hover);
border-color: var(--color-primary);
}
&.btn-remove {
color: var(--color-error);
&:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-error), transparent 90%);
border-color: var(--color-error);
}
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
.btn-add {
display: flex;
align-items: center;
justify-content: center;
gap: var(--spacing-xs);
padding: var(--spacing-sm);
background: transparent;
border: 1px dashed var(--border-secondary);
border-radius: var(--radius-md);
color: var(--text-secondary);
font-size: 0.875rem;
cursor: pointer;
transition: all 0.2s ease;
&:hover {
background: var(--surface-hover);
border-color: var(--color-primary);
color: var(--color-primary);
}
}
.errors-card {
background: color-mix(in srgb, var(--color-error), transparent 95%);
border-color: var(--color-error);
}
.error-message {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-sm);
color: var(--color-error);
font-size: 0.9375rem;
}
.results {
background: var(--bg-tertiary);
animation: slideIn 0.3s ease-out;
&.info-card {
p {
color: var(--text-secondary);
line-height: 1.6;
margin: var(--spacing-sm) 0;
}
ul {
margin: var(--spacing-md) 0;
padding-left: var(--spacing-xl);
color: var(--text-secondary);
line-height: 1.8;
li {
margin: var(--spacing-xs) 0;
strong {
color: var(--text-primary);
}
}
}
}
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.output-group {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
margin-bottom: var(--spacing-lg);
&:last-child {
margin-bottom: 0;
}
}
.output-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.copy-btn {
display: flex;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-xs) var(--spacing-sm);
background: transparent;
border: 1px solid var(--border-secondary);
border-radius: var(--radius-sm);
color: var(--text-secondary);
font-size: 0.875rem;
cursor: pointer;
transition: all 0.2s ease;
&:hover {
background: var(--surface-hover);
border-color: var(--color-primary);
color: var(--color-primary);
}
&.copied {
background: color-mix(in srgb, var(--color-success), transparent 90%);
border-color: var(--color-success);
color: var(--color-success);
}
}
.output-value {
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
font-family: var(--font-mono);
font-size: 0.875rem;
color: var(--color-primary);
overflow-x: auto;
}
.code-block {
white-space: pre;
word-break: normal;
}
.summary-card {
display: flex;
gap: var(--spacing-lg);
flex-wrap: wrap;
padding: var(--spacing-md);
background: color-mix(in srgb, var(--color-info), transparent 95%);
border: 1px solid var(--color-info);
border-radius: var(--radius-md);
margin-bottom: var(--spacing-lg);
font-size: 0.9375rem;
div {
strong {
color: var(--text-primary);
}
}
@media (max-width: 768px) {
flex-direction: column;
gap: var(--spacing-xs);
}
}
.breakdown-section {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
h4 {
margin-bottom: var(--spacing-sm);
}
}
.breakdown-item {
display: grid;
grid-template-columns: auto 1fr;
gap: var(--spacing-sm);
padding: var(--spacing-sm);
background: var(--bg-secondary);
border-radius: var(--radius-sm);
font-size: 0.875rem;
.breakdown-label {
font-weight: 500;
color: var(--text-secondary);
grid-column: 1;
}
.breakdown-hex {
font-family: var(--font-mono);
color: var(--color-primary);
grid-column: 2;
}
.breakdown-desc {
color: var(--text-tertiary);
font-size: 0.8125rem;
grid-column: 1 / -1;
}
}
</style>
+40
View File
@@ -1049,6 +1049,46 @@ export const SUB_NAV: Record<string, (NavItem | NavGroup)[]> = {
'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': [
{
+473
View File
@@ -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' },
],
},
];
@@ -0,0 +1,5 @@
<script lang="ts">
import FreeformTLVBuilder from '$lib/components/tools/FreeformTLVBuilder.svelte';
</script>
<FreeformTLVBuilder />
+311
View File
@@ -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([]);
});
});
});