Developed new DHCP tools

This commit is contained in:
Alicia Sykes committed 2025-10-22 02:04:57 +01:00
1 parent 5061ea54ee
commit b7d4040ad5
29 files changed
+9077

No files matched your search

@@ -0,0 +1,862 @@
<script lang="ts">
import {
parseParameterList,
searchFingerprints,
searchByDevice,
analyzeOptions,
formatParameterListToHex,
formatParameterListDisplay,
exportAsJSON,
exportAsCSV,
DHCP_OPTION_NAMES,
FINGERPRINT_DATABASE,
type FingerprintMatch,
type OptionAnalysis,
} from '$lib/utils/dhcp-fingerprinting';
import { untrack } from 'svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import ExamplesCard from '$lib/components/common/ExamplesCard.svelte';
import { useClipboard } from '$lib/composables/useClipboard.svelte';
const clipboard = useClipboard(1800);
type Tab = 'lookup' | 'reverse';
let activeTab = $state<Tab>('lookup');
let parameterInput = $state<string>('');
let vendorClass = $state<string>('');
let matches = $state<FingerprintMatch[]>([]);
let parsedParams = $state<number[]>([]);
let error = $state<string>('');
let analysis = $state<OptionAnalysis | null>(null);
let reverseQuery = $state<string>('');
let reverseResults = $state<typeof FINGERPRINT_DATABASE>([]);
const examples = [
{
label: 'Windows 10/11',
description: 'Modern Windows desktop',
params: '1,3,6,15,31,33,43,44,46,47,119,121,249,252',
vendor: '',
},
{
label: 'macOS/iOS',
description: 'Apple device',
params: '1,3,6,15,119,252',
vendor: '',
},
{
label: 'Android',
description: 'Android smartphone',
params: '1,3,6,15,26,28,51,58,59,43',
vendor: 'dhcpcd',
},
{
label: 'Linux (dhclient)',
description: 'Linux with ISC dhclient',
params: '1,3,6,15,26,28,42',
vendor: '',
},
{
label: 'Cisco IP Phone',
description: 'Cisco VoIP device',
params: '1,3,6,12,15,28,42,66,67,120,150',
vendor: 'Cisco',
},
{
label: 'Raspberry Pi',
description: 'Raspberry Pi OS (Debian)',
params: '1,3,6,12,15,28,40,41,42',
vendor: '',
},
{
label: 'Samsung Smart TV',
description: 'Smart TV device',
params: '1,3,6,12,15,28,40,41,42,119',
vendor: 'SAMSUNG',
},
];
const navOptions = [
{ value: 'lookup', label: 'Fingerprint Lookup', icon: 'fingerprint' },
{ value: 'reverse', label: 'Device Search', icon: 'monitor' },
];
function loadExample(ex: (typeof examples)[0]) {
activeTab = 'lookup';
parameterInput = ex.params;
vendorClass = ex.vendor;
}
function downloadFile(content: string, filename: string, type: string) {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
function handleExportJSON() {
if (!analysis || matches.length === 0) return;
const json = exportAsJSON(parsedParams, matches, analysis, vendorClass || undefined);
downloadFile(json, 'dhcp-fingerprint.json', 'application/json');
}
function handleExportCSV() {
if (matches.length === 0) return;
const csv = exportAsCSV(matches);
downloadFile(csv, 'dhcp-fingerprint.csv', 'text/csv');
}
// Search effect for fingerprint lookup
$effect(() => {
if (activeTab !== 'lookup') return;
const currentInput = parameterInput;
const currentVendor = vendorClass;
untrack(() => {
if (!currentInput.trim()) {
matches = [];
parsedParams = [];
error = '';
analysis = null;
return;
}
try {
parsedParams = parseParameterList(currentInput);
if (parsedParams.some(isNaN)) {
error = 'Invalid parameter list format';
matches = [];
analysis = null;
return;
}
matches = searchFingerprints(parsedParams, currentVendor || undefined);
analysis = analyzeOptions(parsedParams, matches);
error = '';
} catch (err) {
error = err instanceof Error ? err.message : 'Error parsing input';
matches = [];
parsedParams = [];
analysis = null;
}
});
});
// Search effect for reverse lookup
$effect(() => {
if (activeTab !== 'reverse') return;
const currentQuery = reverseQuery;
untrack(() => {
if (!currentQuery.trim()) {
reverseResults = [];
return;
}
reverseResults = searchByDevice(currentQuery);
});
});
const categoryColors: Record<string, string> = {
desktop: 'var(--color-primary)',
mobile: 'var(--color-info)',
iot: 'var(--color-warning)',
server: 'var(--color-success)',
network: 'var(--color-purple)',
gaming: 'var(--color-primary)',
other: 'var(--text-tertiary)',
};
const confidenceBadges: Record<string, string> = {
high: '🟢',
medium: '🟡',
low: '🔴',
};
</script>
<ToolContentContainer
title="DHCP Fingerprinting Database"
description="Identify devices based on their DHCP fingerprints using Parameter Request List (Option 55) and Vendor Class Identifier (Option 60). Database contains {FINGERPRINT_DATABASE.length} known fingerprints from common devices, operating systems, and IoT equipment."
{navOptions}
bind:selectedNav={activeTab}
>
{#if activeTab === 'lookup'}
<ExamplesCard
{examples}
onSelect={loadExample}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
/>
<div class="card input-card">
<h3>Device Fingerprint Lookup</h3>
<div class="form-group">
<label for="param-list">Parameter Request List (Option 55)</label>
<input
id="param-list"
type="text"
bind:value={parameterInput}
placeholder="e.g., 1,3,6,15 or 0103060f or 1 3 6 15"
class="input"
/>
<span class="hint">Enter as comma-separated, hex, or space-separated numbers</span>
</div>
<div class="form-group">
<label for="vendor-class">Vendor Class Identifier (Option 60) - Optional</label>
<input
id="vendor-class"
type="text"
bind:value={vendorClass}
placeholder="e.g., MSFT, dhcpcd, Cisco"
class="input"
/>
<span class="hint">Helps improve match accuracy</span>
</div>
{#if error}
<div class="error-card">
<strong>Error:</strong>
<p>{error}</p>
</div>
{/if}
</div>
{#if parsedParams.length > 0}
<div class="card result-card">
<h3>Requested DHCP Options</h3>
<div class="result-item">
<span class="label">Parameter List:</span>
<code class="code-value">{formatParameterListDisplay(parsedParams)}</code>
<button
class="btn-copy"
class:copied={clipboard.isCopied('param-list')}
onclick={() => clipboard.copy(formatParameterListDisplay(parsedParams), 'param-list')}
aria-label="Copy"
>
{clipboard.isCopied('param-list') ? 'Copied' : 'Copy'}
</button>
</div>
<div class="result-item">
<span class="label">Hex Encoded:</span>
<code class="code-value">{formatParameterListToHex(parsedParams)}</code>
<button
class="btn-copy"
class:copied={clipboard.isCopied('param-hex')}
onclick={() => clipboard.copy(formatParameterListToHex(parsedParams), 'param-hex')}
aria-label="Copy hex"
>
{clipboard.isCopied('param-hex') ? 'Copied' : 'Copy'}
</button>
</div>
<div class="options-grid">
{#each parsedParams as param, i (i)}
<div class="option-badge">
<span class="option-num">{param}</span>
<span class="option-name">{DHCP_OPTION_NAMES[param] || 'Unknown'}</span>
</div>
{/each}
</div>
{#if analysis && analysis.warnings.length > 0}
<div class="card warning-card">
<h3>Security Warnings</h3>
{#each analysis.warnings as warning, i (i)}
<div class="warning-item">⚠️ {warning}</div>
{/each}
</div>
{/if}
{#if analysis && (analysis.unusual.length > 0 || (analysis.missing.length > 0 && matches.length > 0))}
<div class="card analysis-card">
<h3>Option Analysis</h3>
{#if analysis.unusual.length > 0}
<div class="info-section">
<h4>Unusual Options Detected</h4>
<p>These options may indicate vendor-specific configurations:</p>
<code class="code-value"
>{analysis.unusual.map((o) => `${o} (${DHCP_OPTION_NAMES[o] || 'Unknown'})`).join(', ')}</code
>
</div>
{/if}
{#if analysis.missing.length > 0 && matches.length > 0}
<div class="info-section">
<h4>Missing Options (vs. Best Match)</h4>
<p>Options present in the best match but not in your fingerprint:</p>
<code class="code-value"
>{analysis.missing.map((o) => `${o} (${DHCP_OPTION_NAMES[o] || 'Unknown'})`).join(', ')}</code
>
</div>
{/if}
</div>
{/if}
</div>
{/if}
{#if matches.length > 0}
<div class="card matches-card">
<div class="matches-header">
<h3>Matching Devices ({matches.length})</h3>
<div class="export-buttons">
<button class="btn btn-secondary btn-sm" onclick={handleExportJSON}>Export JSON</button>
<button class="btn btn-secondary btn-sm" onclick={handleExportCSV}>Export CSV</button>
</div>
</div>
<div class="matches-list">
{#each matches as match, i (i)}
<div class="match-item">
<div class="match-header">
<div class="match-title">
<span
class="category-badge"
style="background: {categoryColors[match.fingerprint.category] || categoryColors.other}"
>
{match.fingerprint.category}
</span>
<h4>{match.fingerprint.device}</h4>
<span class="confidence">
{confidenceBadges[match.fingerprint.confidence] || ''}
{match.fingerprint.confidence} confidence
</span>
</div>
<div class="match-score">
<span class="score-value">{match.matchScore.toFixed(0)}%</span>
<span class="score-label">Match</span>
</div>
</div>
<div class="match-details">
<div class="detail-row">
<span class="detail-label">OS:</span>
<span>{match.fingerprint.os}</span>
</div>
<div class="detail-row">
<span class="detail-label">Matched On:</span>
<span>{match.matchedOn.join(', ')}</span>
</div>
{#if match.fingerprint.description}
<div class="detail-row">
<span class="detail-label">Description:</span>
<span>{match.fingerprint.description}</span>
</div>
{/if}
<div class="detail-row">
<span class="detail-label">Known Parameters:</span>
<code class="code-small">{formatParameterListDisplay(match.fingerprint.parameterRequestList)}</code>
</div>
</div>
</div>
{/each}
</div>
</div>
{:else if parsedParams.length > 0 && !error}
<div class="card no-match-card">
<h3>No Matches Found</h3>
<p>The provided fingerprint doesn't match any known devices in the database. This could be:</p>
<ul>
<li>A custom DHCP client configuration</li>
<li>An uncommon device or operating system</li>
<li>A device with a modified DHCP request list</li>
</ul>
<p class="hint">Try adding the Vendor Class Identifier if available.</p>
</div>
{/if}
{:else}
<div class="card input-card">
<h3>Search by Device or OS</h3>
<div class="form-group">
<label for="reverse-query">Search for Device/OS/Vendor</label>
<input
id="reverse-query"
type="text"
bind:value={reverseQuery}
placeholder="e.g., iPhone, Windows, Cisco, Printer..."
class="input"
/>
<span class="hint">Search the database by device name, OS, or vendor</span>
</div>
</div>
{#if reverseResults.length > 0}
<div class="card result-card">
<h3>Found {reverseResults.length} Device{reverseResults.length > 1 ? 's' : ''}</h3>
{#each reverseResults as device, i (i)}
<div class="reverse-item">
<div class="reverse-header">
<span
class="category-badge"
style="background: {categoryColors[device.category] || categoryColors.other}"
>
{device.category}
</span>
<h4>{device.device}</h4>
<span class="confidence">
{confidenceBadges[device.confidence] || ''}
{device.confidence} confidence
</span>
</div>
<div class="reverse-details">
<div class="detail-row">
<span class="detail-label">OS:</span>
<span>{device.os}</span>
</div>
{#if device.description}
<div class="detail-row">
<span class="detail-label">Description:</span>
<span>{device.description}</span>
</div>
{/if}
<div class="detail-row">
<span class="detail-label">Parameter Request List:</span>
<code class="code-small">{formatParameterListDisplay(device.parameterRequestList)}</code>
<button
class="btn-copy"
class:copied={clipboard.isCopied(`reverse-${i}`)}
onclick={() =>
clipboard.copy(formatParameterListDisplay(device.parameterRequestList), `reverse-${i}`)}
aria-label="Copy parameter list"
>
{clipboard.isCopied(`reverse-${i}`) ? 'Copied' : 'Copy'}
</button>
</div>
{#if device.vendorClassPattern}
<div class="detail-row">
<span class="detail-label">Vendor Class Pattern:</span>
<code class="code-small">{device.vendorClassPattern}</code>
</div>
{/if}
</div>
</div>
{/each}
</div>
{:else if reverseQuery.trim()}
<div class="card no-match-card">
<h3>No Devices Found</h3>
<p>No devices matched "{reverseQuery}". Try a different search term.</p>
</div>
{/if}
{/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-md);
&.input-card {
background: var(--bg-tertiary);
}
h3 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-lg);
}
}
.form-group {
margin-bottom: var(--spacing-md);
label {
display: block;
margin-bottom: var(--spacing-xs);
color: var(--text-primary);
font-weight: 500;
}
.hint {
display: block;
margin-top: var(--spacing-xs);
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
.input {
width: 100%;
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: var(--font-mono);
font-size: var(--font-size-sm);
transition: border-color 0.2s;
&:focus {
outline: none;
border-color: var(--color-primary);
}
}
.error-card {
background: color-mix(in srgb, var(--color-error), transparent 90%);
border: 1px solid var(--color-error);
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin-top: var(--spacing-md);
strong {
color: var(--color-error);
display: block;
margin-bottom: var(--spacing-xs);
}
p {
margin: 0;
color: var(--text-primary);
}
}
.result-card {
background: var(--bg-tertiary);
}
.result-item {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-sm);
align-items: center;
padding: var(--spacing-sm);
background: var(--bg-secondary);
border-radius: var(--radius-md);
margin-bottom: var(--spacing-sm);
.label {
font-weight: 500;
color: var(--text-secondary);
min-width: 120px;
}
.code-value {
flex: 1;
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
background: var(--bg-primary);
padding: var(--spacing-xs) var(--spacing-sm);
border-radius: var(--radius-sm);
}
}
.options-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: var(--spacing-xs);
margin: var(--spacing-md) 0;
}
.option-badge {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-sm);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
.option-num {
display: flex;
align-items: center;
justify-content: center;
min-width: 24px;
height: 24px;
padding: var(--spacing-xs);
background: var(--color-primary);
color: var(--bg-primary);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
font-size: var(--font-size-sm);
font-weight: 600;
}
.option-name {
font-size: var(--font-size-sm);
color: var(--text-secondary);
}
}
.matches-card {
background: var(--bg-tertiary);
}
.match-item {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-md);
margin-bottom: var(--spacing-md);
}
.match-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: var(--spacing-md);
margin-bottom: var(--spacing-md);
padding-bottom: var(--spacing-md);
border-bottom: 1px solid var(--border-primary);
}
.match-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-sm);
flex: 1;
h4 {
margin: 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
.confidence {
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
.category-badge {
padding: var(--spacing-xs) var(--spacing-sm);
color: var(--bg-primary);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
font-weight: 600;
text-transform: uppercase;
}
.match-score {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-sm);
background: color-mix(in srgb, var(--color-success), transparent 90%);
border-radius: var(--radius-md);
min-width: 60px;
.score-value {
font-size: var(--font-size-lg);
font-weight: 600;
color: var(--color-success);
}
.score-label {
font-size: var(--font-size-xs);
color: var(--text-secondary);
}
}
.detail-row {
display: flex;
gap: var(--spacing-sm);
font-size: var(--font-size-sm);
margin-bottom: var(--spacing-xs);
.detail-label {
font-weight: 500;
color: var(--text-secondary);
min-width: 140px;
}
.code-small {
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
}
}
.no-match-card {
background: color-mix(in srgb, var(--color-warning), transparent 95%);
border-color: var(--color-warning);
h3 {
color: var(--color-warning);
}
ul {
margin: var(--spacing-sm) 0;
padding-left: var(--spacing-lg);
color: var(--text-primary);
}
p {
margin: var(--spacing-sm) 0;
color: var(--text-primary);
&.hint {
margin-top: var(--spacing-sm);
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
}
.btn-copy {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition:
background 0.2s,
border-color 0.2s,
color 0.2s;
&:hover {
background: var(--bg-secondary);
}
&.copied {
background: var(--color-success);
border-color: var(--color-success);
color: var(--bg-primary);
}
}
.warning-card {
background: color-mix(in srgb, var(--color-warning), transparent 95%);
border-color: var(--color-warning);
h3 {
color: var(--color-warning);
}
}
.warning-item {
padding: var(--spacing-sm);
background: color-mix(in srgb, var(--color-warning), transparent 90%);
border-radius: var(--radius-sm);
color: var(--text-primary);
margin-bottom: var(--spacing-xs);
font-size: var(--font-size-sm);
&:last-child {
margin-bottom: 0;
}
}
.analysis-card {
background: color-mix(in srgb, var(--color-info), transparent 95%);
border-color: var(--color-info);
h3 {
color: var(--color-info);
}
h4 {
margin: var(--spacing-sm) 0 var(--spacing-xs) 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
p {
margin: var(--spacing-xs) 0;
font-size: var(--font-size-sm);
color: var(--text-secondary);
}
.code-value {
display: block;
margin-top: var(--spacing-xs);
}
}
.info-section {
margin-bottom: var(--spacing-md);
}
.matches-header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: var(--spacing-sm);
margin-bottom: var(--spacing-md);
}
.export-buttons {
display: flex;
gap: var(--spacing-xs);
}
.btn {
padding: var(--spacing-sm) var(--spacing-md);
background: var(--color-primary);
color: var(--text-inverse);
border: none;
border-radius: var(--radius-md);
cursor: pointer;
font-weight: 500;
transition: opacity 0.2s;
&:hover {
opacity: 0.9;
}
&.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-primary);
}
&.btn-sm {
padding: var(--spacing-xs) var(--spacing-sm);
font-size: var(--font-size-sm);
}
}
.reverse-item {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-md);
margin-bottom: var(--spacing-md);
}
.reverse-header {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-sm);
margin-bottom: var(--spacing-md);
padding-bottom: var(--spacing-md);
border-bottom: 1px solid var(--border-primary);
h4 {
margin: 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
}
.reverse-details {
.detail-row {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-sm);
align-items: center;
margin-bottom: var(--spacing-xs);
}
}
</style>
+707
View File
@@ -0,0 +1,707 @@
<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 FQDNConfig,
type FQDNResult,
buildFQDNOption,
getDefaultFQDNConfig,
validateFQDNConfig,
FQDN_EXAMPLES,
} from '$lib/utils/dhcpv6-fqdn-rfc4704';
let config = $state<FQDNConfig>(getDefaultFQDNConfig());
let result = $state<FQDNResult | null>(null);
let validationErrors = $state<string[]>([]);
let selectedExampleIndex = $state<number | null>(null);
const clipboard = useClipboard();
function loadExample(example: FQDNConfig & { label: string; description: string }, index: number): void {
config = {
fqdn: example.fqdn,
serverShouldUpdate: example.serverShouldUpdate,
serverOverride: example.serverOverride,
clientShouldUpdate: example.clientShouldUpdate,
};
selectedExampleIndex = index;
}
function checkIfExampleStillMatches(): void {
if (selectedExampleIndex === null) return;
const example = FQDN_EXAMPLES[selectedExampleIndex];
if (!example) {
selectedExampleIndex = null;
return;
}
const matches =
config.fqdn === example.fqdn &&
config.serverShouldUpdate === example.serverShouldUpdate &&
config.serverOverride === example.serverOverride &&
config.clientShouldUpdate === example.clientShouldUpdate;
if (!matches) {
selectedExampleIndex = null;
}
}
$effect(() => {
// Read config properties to trigger effect when they change
const currentFqdn = config.fqdn;
const currentServerUpdate = config.serverShouldUpdate;
const currentServerOverride = config.serverOverride;
const currentClientUpdate = config.clientShouldUpdate;
// Update validationErrors and result without tracking them (prevents infinite loop)
untrack(() => {
const currentConfig: FQDNConfig = {
fqdn: currentFqdn,
serverShouldUpdate: currentServerUpdate,
serverOverride: currentServerOverride,
clientShouldUpdate: currentClientUpdate,
};
// Check if form is in initial empty state
const isInitialState = !currentConfig.fqdn.trim();
if (isInitialState) {
validationErrors = [];
result = null;
} else {
validationErrors = validateFQDNConfig(currentConfig);
if (validationErrors.length === 0) {
try {
result = buildFQDNOption(currentConfig);
} catch (e) {
validationErrors = [e instanceof Error ? e.message : String(e)];
result = null;
}
} else {
result = null;
}
}
checkIfExampleStillMatches();
});
});
</script>
<ToolContentContainer
title="DHCPv6 Client FQDN Option (RFC 4704)"
description="Configure the Client FQDN Option (Option 39) for DHCPv6, enabling dynamic DNS updates and hostname management for IPv6 clients."
>
<ExamplesCard
examples={FQDN_EXAMPLES}
onSelect={loadExample}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
selectedIndex={selectedExampleIndex}
/>
<div class="card input-card">
<div class="card-header">
<h3>FQDN Configuration</h3>
<p class="help-text">Fully Qualified Domain Name for the DHCPv6 client</p>
</div>
<div class="card-content">
<div class="input-group">
<label for="fqdn">
<Icon name="globe" size="sm" />
Fully Qualified Domain Name (FQDN)
</label>
<input id="fqdn" type="text" bind:value={config.fqdn} placeholder="client.example.com" />
</div>
</div>
</div>
<div class="card input-card">
<div class="card-header">
<h3>DNS Update Flags</h3>
<p class="help-text">Control how DNS updates are performed</p>
</div>
<div class="card-content flags-content">
<div class="checkbox-group">
<input id="server-update" type="checkbox" bind:checked={config.serverShouldUpdate} />
<label for="server-update">
<Icon name="server" size="sm" />
<div class="checkbox-text">
<strong>Server Should Update DNS (S Flag)</strong>
<span class="help-text">Server will perform AAAA and PTR record updates</span>
</div>
</label>
</div>
<div class="checkbox-group">
<input id="server-override" type="checkbox" bind:checked={config.serverOverride} />
<label for="server-override">
<Icon name="shield" size="sm" />
<div class="checkbox-text">
<strong>Server Override (O Flag)</strong>
<span class="help-text">Server can override client's preferences</span>
</div>
</label>
</div>
<div class="checkbox-group">
<input id="client-update" type="checkbox" bind:checked={config.clientShouldUpdate} />
<label for="client-update">
<Icon name="user" size="sm" />
<div class="checkbox-text">
<strong>Client Should Update DNS (N Flag = 0)</strong>
<span class="help-text">Client will perform its own DNS updates</span>
</div>
</label>
</div>
</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>Option 39: Client FQDN</h3>
<div class="summary-card">
<div><strong>FQDN:</strong> {result.fqdn}</div>
<div><strong>Total Length:</strong> {result.totalLength} bytes</div>
</div>
<div class="flags-section">
<h4>Flags Breakdown</h4>
<div class="flags-grid">
<div class="flag-item" class:active={result.flags.S}>
<Icon name="server" size="sm" />
<div class="flag-content">
<strong>S Flag</strong>
<span>{result.flags.S ? 'Set' : 'Not Set'}</span>
</div>
</div>
<div class="flag-item" class:active={result.flags.O}>
<Icon name="shield" size="sm" />
<div class="flag-content">
<strong>O Flag</strong>
<span>{result.flags.O ? 'Set' : 'Not Set'}</span>
</div>
</div>
<div class="flag-item" class:active={result.flags.N}>
<Icon name="user" size="sm" />
<div class="flag-content">
<strong>N Flag</strong>
<span>{result.flags.N ? 'Set' : 'Not Set'}</span>
</div>
</div>
</div>
<div class="flag-descriptions">
{#each result.flags.description as desc, i (i)}
<div class="flag-desc-item">
<Icon name="info" size="xs" />
{desc}
</div>
{/each}
</div>
<div class="output-group">
<div class="output-header">
<h4>Flags Byte</h4>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied('flags')}
onclick={() => clipboard.copy(result!.flags.flagsByte, 'flags')}
>
<Icon name={clipboard.isCopied('flags') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('flags') ? 'Copied' : 'Copy'}
</button>
</div>
<pre class="output-value code-block">{result.flags.flagsByte}</pre>
</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>
<div class="breakdown-section">
<h4>Encoding Breakdown</h4>
<div class="breakdown-grid">
<div class="breakdown-item">
<span class="breakdown-label">Flags:</span>
<span class="breakdown-value">{result.breakdown.flags}</span>
</div>
<div class="breakdown-item">
<span class="breakdown-label">FQDN:</span>
<span class="breakdown-value">{result.breakdown.fqdn}</span>
</div>
</div>
</div>
</div>
{#if result.examples.keaDhcp6}
<div class="card results">
<h3>Configuration Example</h3>
<div class="output-group">
<div class="output-header">
<h4>Kea DHCPv6 Configuration</h4>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied('kea')}
onclick={() => clipboard.copy(result!.examples.keaDhcp6!, '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.keaDhcp6}</pre>
</div>
</div>
{/if}
<div class="card results info-card">
<h3>About RFC 4704</h3>
<p>
RFC 4704 defines the Client FQDN Option for DHCPv6, enabling clients and servers to negotiate dynamic DNS
updates for IPv6 addresses.
</p>
<ul>
<li>
<strong>S Flag (Bit 0):</strong> Server should perform DNS updates
</li>
<li>
<strong>O Flag (Bit 1):</strong> Server can override client preferences
</li>
<li>
<strong>N Flag (Bit 2):</strong> Client requests server to perform updates (client will NOT update)
</li>
</ul>
<p>
The FQDN is encoded using DNS wire format with length-prefixed labels, enabling automated hostname registration
in DNS for IPv6 networks.
</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);
&.flags-content {
gap: var(--spacing-lg);
}
}
.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[type='text'] {
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%);
}
}
}
.checkbox-group {
display: flex;
align-items: flex-start;
gap: var(--spacing-sm);
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
transition: all 0.2s ease;
&:has(input:checked) {
background: color-mix(in srgb, var(--color-primary), transparent 95%);
border-color: var(--color-primary);
}
input[type='checkbox'] {
margin-top: 0.25rem;
width: 1.125rem;
height: 1.125rem;
cursor: pointer;
accent-color: var(--color-primary);
}
label {
flex: 1;
display: flex;
align-items: flex-start;
gap: var(--spacing-sm);
cursor: pointer;
font-size: 0.9375rem;
.checkbox-text {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
strong {
color: var(--text-primary);
}
.help-text {
font-size: 0.8125rem;
color: var(--text-secondary);
font-style: italic;
margin: 0;
}
}
}
}
.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);
}
}
.flags-section {
display: flex;
flex-direction: column;
gap: var(--spacing-lg);
margin-bottom: var(--spacing-lg);
h4 {
margin: 0 0 var(--spacing-xs);
}
}
.flags-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: var(--spacing-md);
}
.flag-item {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
font-size: 0.875rem;
transition: all 0.2s ease;
&.active {
background: color-mix(in srgb, var(--color-success), transparent 95%);
border-color: var(--color-success);
.flag-content strong {
color: var(--color-success);
}
}
.flag-content {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
strong {
color: var(--text-primary);
}
span {
color: var(--text-secondary);
font-size: 0.8125rem;
}
}
}
.flag-descriptions {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
}
.flag-desc-item {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-sm);
background: var(--bg-primary);
border-left: 3px solid var(--color-info);
border-radius: var(--radius-sm);
font-size: 0.875rem;
color: var(--text-secondary);
}
.breakdown-section {
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
h4 {
margin-bottom: var(--spacing-md);
}
}
.breakdown-grid {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
}
.breakdown-item {
display: grid;
grid-template-columns: 100px 1fr;
gap: var(--spacing-md);
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);
}
.breakdown-value {
font-family: var(--font-mono);
color: var(--color-primary);
overflow-x: auto;
}
}
</style>
@@ -0,0 +1,642 @@
<script lang="ts">
import {
type DNSConfig,
type DNSResult,
buildDNSOptions,
decodeDNSServersOption,
decodeDomainNameOption,
validateDNSConfig,
DNS_EXAMPLES,
} from '$lib/utils/dhcp-options6-15-dns';
import { untrack } from 'svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import ExamplesCard from '$lib/components/common/ExamplesCard.svelte';
import { useClipboard } from '$lib/composables/useClipboard.svelte';
const clipboard = useClipboard();
type Tab = 'build' | 'decode';
let activeTab = $state<Tab>('build');
// Build mode state
let dnsServers = $state<string[]>(['']);
let domainName = $state<string>('');
let buildResult = $state<DNSResult | null>(null);
let buildErrors = $state<string[]>([]);
// Decode mode state
type DecodeOption = 'option6' | 'option15';
let decodeOption = $state<DecodeOption>('option6');
let hexInput = $state<string>('');
let decodeResult = $state<any>(null);
let decodeError = $state<string>('');
const navOptions = [
{ value: 'build', label: 'Build Options' },
{ value: 'decode', label: 'Decode Options' },
];
function loadExample(example: (typeof DNS_EXAMPLES)[0]) {
activeTab = 'build';
dnsServers = [...example.dnsServers];
domainName = example.domainName;
}
function addDNSServer() {
dnsServers = [...dnsServers, ''];
}
function removeDNSServer(index: number) {
dnsServers = dnsServers.filter((_, i) => i !== index);
if (dnsServers.length === 0) {
dnsServers = [''];
}
}
// Build mode effect
$effect(() => {
if (activeTab !== 'build') return;
const currentServers = dnsServers;
const currentDomain = domainName;
untrack(() => {
const hasInput = currentServers.some((s) => s.trim()) || currentDomain.trim();
if (!hasInput) {
buildResult = null;
buildErrors = [];
return;
}
const config: DNSConfig = {
dnsServers: currentServers,
domainName: currentDomain || undefined,
};
buildErrors = validateDNSConfig(config);
if (buildErrors.length === 0) {
try {
buildResult = buildDNSOptions(config);
} catch (err) {
buildErrors = [err instanceof Error ? err.message : 'Unknown error'];
buildResult = null;
}
} else {
buildResult = null;
}
});
});
// Decode mode effect
$effect(() => {
if (activeTab !== 'decode') return;
const currentHex = hexInput;
const currentOption = decodeOption;
untrack(() => {
if (!currentHex.trim()) {
decodeResult = null;
decodeError = '';
return;
}
try {
if (currentOption === 'option6') {
decodeResult = decodeDNSServersOption(currentHex);
} else {
decodeResult = decodeDomainNameOption(currentHex);
}
decodeError = '';
} catch (err) {
decodeError = err instanceof Error ? err.message : 'Unknown error';
decodeResult = null;
}
});
});
</script>
<ToolContentContainer
title="DHCP Options 6 & 15 - DNS Servers and Domain"
description="Option 6 specifies DNS servers for name resolution, while Option 15 provides the domain name for client hostname resolution. These options work together for complete DNS configuration."
{navOptions}
bind:selectedNav={activeTab}
>
<ExamplesCard
examples={DNS_EXAMPLES}
onSelect={loadExample}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
/>
{#if activeTab === 'build'}
<div class="card input-card">
<h3>DNS Configuration</h3>
<fieldset class="form-group">
<legend>DNS Servers (Option 6)</legend>
{#each dnsServers as _server, i (i)}
<div class="server-row">
<input type="text" bind:value={dnsServers[i]} placeholder="e.g., 8.8.8.8" class="input" />
{#if dnsServers.length > 1}
<button class="btn btn-danger btn-sm" onclick={() => removeDNSServer(i)}>Remove</button>
{/if}
</div>
{/each}
<button class="btn btn-secondary btn-sm" onclick={addDNSServer}>Add DNS Server</button>
</fieldset>
<div class="form-group">
<label for="domain-name">Domain Name (Option 15)</label>
<input id="domain-name" type="text" bind:value={domainName} placeholder="e.g., example.com" class="input" />
<span class="hint">Domain name for client hostname resolution</span>
</div>
{#if buildErrors.length > 0}
<div class="error-card">
<strong>Validation Errors:</strong>
<ul>
{#each buildErrors as error, i (i)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
</div>
{#if buildResult}
<div class="card result-card">
<h3>DHCP DNS Options</h3>
{#if buildResult.option6}
<div class="option-section">
<h4>Option 6 - DNS Servers</h4>
<div class="result-grid">
<div class="result-item">
<span class="label">DNS Servers:</span>
<div class="servers-list">
{#each buildResult.option6.servers as srv, i (i)}
<span class="server-badge">{srv}</span>
{/each}
</div>
</div>
<div class="result-item">
<span class="label">Hex Encoded:</span>
<code class="code-value">{buildResult.option6.hexEncoded}</code>
<button
class="btn-copy"
onclick={() => clipboard.copy(buildResult!.option6!.hexEncoded)}
aria-label="Copy hex"
>
Copy
</button>
</div>
<div class="result-item">
<span class="label">Wire Format:</span>
<code class="code-value">{buildResult.option6.wireFormat}</code>
<button
class="btn-copy"
onclick={() => clipboard.copy(buildResult!.option6!.wireFormat)}
aria-label="Copy wire format"
>
Copy
</button>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{buildResult.option6.totalLength} bytes</span>
</div>
</div>
</div>
{/if}
{#if buildResult.option15}
<div class="option-section">
<h4>Option 15 - Domain Name</h4>
<div class="result-grid">
<div class="result-item">
<span class="label">Domain:</span>
<span class="value">{buildResult.option15.domain}</span>
</div>
<div class="result-item">
<span class="label">Hex Encoded:</span>
<code class="code-value">{buildResult.option15.hexEncoded}</code>
<button
class="btn-copy"
onclick={() => clipboard.copy(buildResult!.option15!.hexEncoded)}
aria-label="Copy hex"
>
Copy
</button>
</div>
<div class="result-item">
<span class="label">Wire Format:</span>
<code class="code-value">{buildResult.option15.wireFormat}</code>
<button
class="btn-copy"
onclick={() => clipboard.copy(buildResult!.option15!.wireFormat)}
aria-label="Copy wire format"
>
Copy
</button>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{buildResult.option15.totalLength} bytes</span>
</div>
</div>
</div>
{/if}
<div class="config-section">
<h4>Configuration Examples</h4>
<div class="config-example">
<h5>ISC DHCPd</h5>
<pre><code>{buildResult.configExamples.iscDhcpd}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.iscDhcpd)}>
Copy
</button>
</div>
<div class="config-example">
<h5>Kea DHCPv4</h5>
<pre><code>{buildResult.configExamples.keaDhcp4}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.keaDhcp4)}>
Copy
</button>
</div>
<div class="config-example">
<h5>dnsmasq</h5>
<pre><code>{buildResult.configExamples.dnsmasq}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.dnsmasq)}> Copy </button>
</div>
</div>
</div>
{/if}
{:else}
<div class="card input-card">
<h3>Decode DNS Options</h3>
<fieldset class="form-group">
<legend>Option to Decode</legend>
<div class="option-select">
<label class="radio-label">
<input type="radio" bind:group={decodeOption} value="option6" />
Option 6 - DNS Servers
</label>
<label class="radio-label">
<input type="radio" bind:group={decodeOption} value="option15" />
Option 15 - Domain Name
</label>
</div>
</fieldset>
<div class="form-group">
<label for="hex-input">Hex String</label>
<textarea
id="hex-input"
bind:value={hexInput}
placeholder={decodeOption === 'option6'
? 'e.g., 08080808 or 08 08 08 08 08 08 04 04'
: 'e.g., 6578616d706c6503636f6d'}
rows="3"
class="input"
></textarea>
<span class="hint">Enter hex bytes (spaces optional)</span>
</div>
{#if decodeError}
<div class="error-card">
<strong>Decode Error:</strong>
<p>{decodeError}</p>
</div>
{/if}
</div>
{#if decodeResult}
<div class="card result-card">
<h3>Decoded {decodeOption === 'option6' ? 'Option 6' : 'Option 15'}</h3>
{#if decodeOption === 'option6'}
<div class="result-grid">
<div class="result-item">
<span class="label">DNS Servers:</span>
<div class="servers-list">
{#each decodeResult.servers as srv, i (i)}
<span class="server-badge">{srv}</span>
{/each}
</div>
</div>
<div class="result-item">
<span class="label">Server Count:</span>
<span class="value">{decodeResult.servers.length}</span>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{decodeResult.totalLength} bytes</span>
</div>
</div>
{:else}
<div class="result-grid">
<div class="result-item">
<span class="label">Domain Name:</span>
<span class="value">{decodeResult.domain}</span>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{decodeResult.totalLength} bytes</span>
</div>
</div>
{/if}
</div>
{/if}
{/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-md);
&.input-card {
background: var(--bg-tertiary);
}
h3 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-lg);
}
h4 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
h5 {
margin: 0 0 var(--spacing-sm) 0;
color: var(--text-secondary);
font-size: var(--font-size-sm);
font-weight: 600;
}
}
.form-group {
margin-bottom: var(--spacing-md);
label {
display: block;
margin-bottom: var(--spacing-xs);
color: var(--text-primary);
font-weight: 500;
}
.hint {
display: block;
margin-top: var(--spacing-xs);
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
fieldset.form-group {
border: none;
padding: 0;
legend {
display: block;
margin-bottom: var(--spacing-xs);
color: var(--text-primary);
font-weight: 500;
}
}
.input {
width: 100%;
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: var(--font-mono);
font-size: var(--font-size-sm);
transition: border-color 0.2s;
&:focus {
outline: none;
border-color: var(--color-primary);
}
}
.server-row {
display: flex;
gap: var(--spacing-sm);
margin-bottom: var(--spacing-sm);
align-items: center;
.input {
flex: 1;
}
}
.option-select {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
}
.radio-label {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-sm);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: var(--bg-secondary);
}
input[type='radio'] {
cursor: pointer;
}
}
.btn {
padding: var(--spacing-sm) var(--spacing-md);
background: var(--color-primary);
color: var(--text-inverse);
border: none;
border-radius: var(--radius-md);
cursor: pointer;
font-weight: 500;
transition: opacity 0.2s;
&:hover {
opacity: 0.9;
}
&.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-primary);
}
&.btn-danger {
background: var(--color-error);
}
&.btn-sm {
padding: var(--spacing-xs) var(--spacing-sm);
font-size: var(--font-size-sm);
}
}
.error-card {
background: color-mix(in srgb, var(--color-error), transparent 90%);
border: 1px solid var(--color-error);
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin-top: var(--spacing-md);
strong {
color: var(--color-error);
display: block;
margin-bottom: var(--spacing-xs);
}
ul {
margin: 0;
padding-left: var(--spacing-lg);
color: var(--text-primary);
}
p {
margin: 0;
color: var(--text-primary);
}
}
.result-card {
h3 {
color: var(--color-success);
}
}
.option-section {
margin-bottom: var(--spacing-lg);
padding-bottom: var(--spacing-lg);
border-bottom: 1px solid var(--border-primary);
&:last-of-type {
border-bottom: none;
padding-bottom: 0;
margin-bottom: 0;
}
}
.result-grid {
display: grid;
gap: var(--spacing-md);
}
.result-item {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-sm);
align-items: center;
padding: var(--spacing-sm);
background: var(--bg-tertiary);
border-radius: var(--radius-md);
.label {
font-weight: 500;
color: var(--text-secondary);
min-width: 120px;
}
.value,
.code-value {
flex: 1;
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
}
}
.servers-list {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-xs);
flex: 1;
}
.server-badge {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--color-primary);
color: var(--text-inverse);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
font-size: var(--font-size-sm);
}
.config-section {
margin-top: var(--spacing-lg);
padding-top: var(--spacing-lg);
border-top: 1px solid var(--border-primary);
}
.config-example {
position: relative;
margin-bottom: var(--spacing-md);
pre {
margin: 0;
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
overflow-x: auto;
code {
font-family: var(--font-mono);
font-size: var(--font-size-sm);
color: var(--text-primary);
}
}
}
.btn-copy {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: var(--bg-secondary);
}
}
</style>
@@ -0,0 +1,543 @@
<script lang="ts">
import {
type GatewayConfig,
type GatewayResult,
buildGatewayOption,
decodeGatewayOption,
validateGatewayConfig,
GATEWAY_EXAMPLES,
} from '$lib/utils/dhcp-option3-gateway';
import { untrack } from 'svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import ExamplesCard from '$lib/components/common/ExamplesCard.svelte';
import { useClipboard } from '$lib/composables/useClipboard.svelte';
const clipboard = useClipboard();
type Tab = 'build' | 'decode';
let activeTab = $state<Tab>('build');
// Build mode state
let gateways = $state<string[]>(['']);
let subnet = $state<string>('');
let buildResult = $state<GatewayResult | null>(null);
let buildErrors = $state<string[]>([]);
// Decode mode state
let hexInput = $state<string>('');
let decodeResult = $state<GatewayResult | null>(null);
let decodeError = $state<string>('');
const navOptions = [
{ value: 'build', label: 'Build Option' },
{ value: 'decode', label: 'Decode Option' },
];
function loadExample(example: (typeof GATEWAY_EXAMPLES)[0]) {
activeTab = 'build';
gateways = [...example.gateways];
subnet = example.subnet || '';
}
function addGateway() {
gateways = [...gateways, ''];
}
function removeGateway(index: number) {
gateways = gateways.filter((_, i) => i !== index);
if (gateways.length === 0) {
gateways = [''];
}
}
// Build mode effect
$effect(() => {
if (activeTab !== 'build') return;
const currentGateways = gateways;
const currentSubnet = subnet;
untrack(() => {
const hasInput = currentGateways.some((g) => g.trim());
if (!hasInput) {
buildResult = null;
buildErrors = [];
return;
}
const config: GatewayConfig = {
gateways: currentGateways,
subnet: currentSubnet || undefined,
};
buildErrors = validateGatewayConfig(config);
if (buildErrors.length === 0) {
try {
buildResult = buildGatewayOption(config);
} catch (err) {
buildErrors = [err instanceof Error ? err.message : 'Unknown error'];
buildResult = null;
}
} else {
buildResult = null;
}
});
});
// Decode mode effect
$effect(() => {
if (activeTab !== 'decode') return;
const currentHex = hexInput;
untrack(() => {
if (!currentHex.trim()) {
decodeResult = null;
decodeError = '';
return;
}
try {
decodeResult = decodeGatewayOption(currentHex);
decodeError = '';
} catch (err) {
decodeError = err instanceof Error ? err.message : 'Unknown error';
decodeResult = null;
}
});
});
</script>
<ToolContentContainer
title="DHCP Option 3 - Router/Default Gateway"
description="Build and decode default gateway configuration. Multiple gateways can be specified for redundancy or load balancing, listed in order of preference."
{navOptions}
bind:selectedNav={activeTab}
>
<ExamplesCard
examples={GATEWAY_EXAMPLES}
onSelect={loadExample}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
/>
{#if activeTab === 'build'}
<div class="card input-card">
<h3>Gateway Configuration</h3>
<div class="form-group">
<label for="subnet">Subnet (Optional - for validation)</label>
<input id="subnet" type="text" bind:value={subnet} placeholder="e.g., 192.168.1.0/24" class="input" />
<span class="hint">If provided, gateways will be validated against this subnet</span>
</div>
<div class="form-group">
<label for="gateway-0">Gateway Addresses (in order of preference)</label>
{#each gateways as _gateway, i (i)}
<div class="gateway-row">
<input
id={i === 0 ? 'gateway-0' : undefined}
type="text"
bind:value={gateways[i]}
placeholder="e.g., 192.168.1.1"
class="input"
aria-label={i > 0 ? `Gateway ${i + 1}` : undefined}
/>
{#if gateways.length > 1}
<button class="btn btn-danger btn-sm" onclick={() => removeGateway(i)}>Remove</button>
{/if}
</div>
{/each}
<button class="btn btn-secondary btn-sm" onclick={addGateway}>Add Gateway</button>
</div>
{#if buildErrors.length > 0}
<div class="error-card">
<strong>Validation Errors:</strong>
<ul>
{#each buildErrors as error, i (i)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
</div>
{#if buildResult}
<div class="card result-card">
<h3>Option 3 - Router</h3>
<div class="result-grid">
<div class="result-item">
<span class="label">Gateways:</span>
<div class="gateway-list">
{#each buildResult.gateways as gw, i (i)}
<span class="gateway-badge">
{i + 1}. {gw}
</span>
{/each}
</div>
</div>
<div class="result-item">
<span class="label">Hex Encoded:</span>
<code class="code-value">{buildResult.hexEncoded}</code>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.hexEncoded)} aria-label="Copy hex">
Copy
</button>
</div>
<div class="result-item">
<span class="label">Wire Format:</span>
<code class="code-value">{buildResult.wireFormat}</code>
<button
class="btn-copy"
onclick={() => clipboard.copy(buildResult!.wireFormat)}
aria-label="Copy wire format"
>
Copy
</button>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{buildResult.totalLength} bytes</span>
</div>
</div>
<div class="config-section">
<h4>Configuration Examples</h4>
<div class="config-example">
<h5>ISC DHCPd</h5>
<pre><code>{buildResult.configExamples.iscDhcpd}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.iscDhcpd)}>
Copy
</button>
</div>
<div class="config-example">
<h5>Kea DHCPv4</h5>
<pre><code>{buildResult.configExamples.keaDhcp4}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.keaDhcp4)}>
Copy
</button>
</div>
<div class="config-example">
<h5>dnsmasq</h5>
<pre><code>{buildResult.configExamples.dnsmasq}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.dnsmasq)}> Copy </button>
</div>
</div>
</div>
{/if}
{:else}
<div class="card input-card">
<h3>Decode Option 3</h3>
<div class="form-group">
<label for="hex-input">Hex String</label>
<textarea
id="hex-input"
bind:value={hexInput}
placeholder="e.g., c0a80101 or c0 a8 01 01"
rows="3"
class="input"
></textarea>
<span class="hint">Enter hex bytes (spaces optional)</span>
</div>
{#if decodeError}
<div class="error-card">
<strong>Decode Error:</strong>
<p>{decodeError}</p>
</div>
{/if}
</div>
{#if decodeResult}
<div class="card result-card">
<h3>Decoded Option 3</h3>
<div class="result-grid">
<div class="result-item">
<span class="label">Gateways:</span>
<div class="gateway-list">
{#each decodeResult.gateways as gw, i (i)}
<span class="gateway-badge">
{i + 1}. {gw}
</span>
{/each}
</div>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{decodeResult.totalLength} bytes</span>
</div>
<div class="result-item">
<span class="label">Gateway Count:</span>
<span class="value">{decodeResult.gateways.length}</span>
</div>
</div>
<div class="config-section">
<h4>Configuration Examples</h4>
<div class="config-example">
<h5>ISC DHCPd</h5>
<pre><code>{decodeResult.configExamples.iscDhcpd}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(decodeResult!.configExamples.iscDhcpd)}>
Copy
</button>
</div>
<div class="config-example">
<h5>Kea DHCPv4</h5>
<pre><code>{decodeResult.configExamples.keaDhcp4}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(decodeResult!.configExamples.keaDhcp4)}>
Copy
</button>
</div>
<div class="config-example">
<h5>dnsmasq</h5>
<pre><code>{decodeResult.configExamples.dnsmasq}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(decodeResult!.configExamples.dnsmasq)}>
Copy
</button>
</div>
</div>
</div>
{/if}
{/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-md);
&.input-card {
background: var(--bg-tertiary);
}
h3 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-lg);
}
h4 {
margin: var(--spacing-lg) 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
h5 {
margin: 0 0 var(--spacing-sm) 0;
color: var(--text-secondary);
font-size: var(--font-size-sm);
font-weight: 600;
}
}
.form-group {
margin-bottom: var(--spacing-md);
label {
display: block;
margin-bottom: var(--spacing-xs);
color: var(--text-primary);
font-weight: 500;
}
.hint {
display: block;
margin-top: var(--spacing-xs);
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
.input {
width: 100%;
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: var(--font-mono);
font-size: var(--font-size-sm);
transition: border-color 0.2s;
&:focus {
outline: none;
border-color: var(--color-primary);
}
}
.gateway-row {
display: flex;
gap: var(--spacing-sm);
margin-bottom: var(--spacing-sm);
align-items: center;
.input {
flex: 1;
}
}
.btn {
padding: var(--spacing-sm) var(--spacing-md);
background: var(--color-primary);
color: var(--text-inverse);
border: none;
border-radius: var(--radius-md);
cursor: pointer;
font-weight: 500;
transition: opacity 0.2s;
&:hover {
opacity: 0.9;
}
&.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-primary);
}
&.btn-danger {
background: var(--color-error);
}
&.btn-sm {
padding: var(--spacing-xs) var(--spacing-sm);
font-size: var(--font-size-sm);
}
}
.error-card {
background: color-mix(in srgb, var(--color-error), transparent 90%);
border: 1px solid var(--color-error);
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin-top: var(--spacing-md);
strong {
color: var(--color-error);
display: block;
margin-bottom: var(--spacing-xs);
}
ul {
margin: 0;
padding-left: var(--spacing-lg);
color: var(--text-primary);
}
p {
margin: 0;
color: var(--text-primary);
}
}
.result-card {
h3 {
color: var(--color-success);
}
}
.result-grid {
display: grid;
gap: var(--spacing-md);
}
.result-item {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-sm);
align-items: center;
padding: var(--spacing-sm);
background: var(--bg-tertiary);
border-radius: var(--radius-md);
.label {
font-weight: 500;
color: var(--text-secondary);
min-width: 120px;
}
.value,
.code-value {
flex: 1;
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
}
}
.gateway-list {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-xs);
flex: 1;
}
.gateway-badge {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--color-primary);
color: var(--text-inverse);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
font-size: var(--font-size-sm);
}
.config-section {
margin-top: var(--spacing-lg);
padding-top: var(--spacing-lg);
border-top: 1px solid var(--border-primary);
}
.config-example {
position: relative;
margin-bottom: var(--spacing-md);
pre {
margin: 0;
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
overflow-x: auto;
code {
font-family: var(--font-mono);
font-size: var(--font-size-sm);
color: var(--text-primary);
}
}
}
.btn-copy {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: var(--bg-secondary);
}
}
</style>
@@ -0,0 +1,559 @@
<script lang="ts">
import {
type LeaseTimeConfig,
type LeaseTimeResult,
validateLeaseTimeConfig,
calculateLeaseTime,
LEASE_TIME_EXAMPLES,
NETWORK_TYPE_DEFAULTS,
CHURN_RATE_HOURS,
formatTime,
} from '$lib/utils/dhcp-lease-calculator';
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';
let poolSize = $state<number | undefined>(100);
let expectedClients = $state<number | undefined>(50);
let churnRate = $state<'low' | 'medium' | 'high' | 'custom'>('medium');
let customChurnHours = $state<number | undefined>(undefined);
let networkType = $state<'corporate' | 'guest' | 'iot' | 'residential' | 'custom'>('corporate');
let validationErrors = $state<string[]>([]);
let result = $state<LeaseTimeResult | null>(null);
let selectedExampleIndex = $state<number | null>(null);
const clipboard = useClipboard();
const examples = LEASE_TIME_EXAMPLES.map((ex) => ({
label: ex.name,
config: ex,
description: ex.description,
}));
function loadExample(example: (typeof examples)[0], index: number): void {
const cfg = example.config;
poolSize = cfg.poolSize;
expectedClients = cfg.expectedClients;
churnRate = cfg.churnRate;
customChurnHours = cfg.customChurnHours;
networkType = cfg.networkType || 'corporate';
selectedExampleIndex = index;
}
function checkIfExampleStillMatches(): void {
if (selectedExampleIndex === null) return;
const example = examples[selectedExampleIndex];
if (!example) {
selectedExampleIndex = null;
return;
}
const cfg = example.config;
const matches =
poolSize === cfg.poolSize &&
expectedClients === cfg.expectedClients &&
churnRate === cfg.churnRate &&
customChurnHours === cfg.customChurnHours &&
networkType === (cfg.networkType || 'corporate');
if (!matches) selectedExampleIndex = null;
}
$effect(() => {
const currentPoolSize = poolSize;
const currentExpectedClients = expectedClients;
const currentChurnRate = churnRate;
const currentCustomChurnHours = customChurnHours;
const currentNetworkType = networkType;
untrack(() => {
const config: LeaseTimeConfig = {
poolSize: currentPoolSize ?? 0,
expectedClients: currentExpectedClients ?? 0,
churnRate: currentChurnRate,
customChurnHours: currentCustomChurnHours,
networkType: currentNetworkType === 'custom' ? undefined : currentNetworkType,
};
const isInitialState = currentPoolSize === undefined || currentExpectedClients === undefined;
if (isInitialState) {
validationErrors = [];
result = null;
} else {
validationErrors = validateLeaseTimeConfig(config);
if (validationErrors.length === 0) {
try {
result = calculateLeaseTime(config);
} catch (e) {
validationErrors = [e instanceof Error ? e.message : String(e)];
result = null;
}
} else {
result = null;
}
}
checkIfExampleStillMatches();
});
});
</script>
<ToolContentContainer
title="DHCP Lease Time Calculator"
description="Calculate optimal DHCP lease times based on network size, client turnover, and utilization. Includes T1/T2 renewal times and configuration examples."
>
<ExamplesCard
{examples}
onSelect={loadExample}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
selectedIndex={selectedExampleIndex}
/>
<div class="card input-card">
<div class="card-header">
<h3>Network Configuration</h3>
<p class="help-text">Enter your network characteristics to calculate optimal lease times</p>
</div>
<div class="card-content">
<div class="input-row">
<div class="input-group">
<label for="pool-size">
<Icon name="layers" size="sm" />
IP Pool Size
</label>
<input id="pool-size" type="number" bind:value={poolSize} placeholder="100" min="1" />
<small>Total available IP addresses in your DHCP pool</small>
</div>
<div class="input-group">
<label for="expected-clients">
<Icon name="users" size="sm" />
Expected Clients
</label>
<input id="expected-clients" type="number" bind:value={expectedClients} placeholder="50" min="0" />
<small>Average number of concurrent clients</small>
</div>
</div>
<div class="input-group">
<label for="network-type">
<Icon name="network" size="sm" />
Network Type
</label>
<select id="network-type" bind:value={networkType}>
{#each Object.entries(NETWORK_TYPE_DEFAULTS) as [key, value] (key)}
<option value={key}>{value.name}</option>
{/each}
<option value="custom">Custom (use churn rate)</option>
</select>
{#if networkType !== 'custom'}
<small>{NETWORK_TYPE_DEFAULTS[networkType].description}</small>
{/if}
</div>
<div class="input-group">
<label for="churn-rate">
<Icon name="refresh" size="sm" />
Client Churn Rate
</label>
<select id="churn-rate" bind:value={churnRate}>
<option value="low">Low - {formatTime(CHURN_RATE_HOURS.low * 3600)}</option>
<option value="medium">Medium - {formatTime(CHURN_RATE_HOURS.medium * 3600)}</option>
<option value="high">High - {formatTime(CHURN_RATE_HOURS.high * 3600)}</option>
<option value="custom">Custom</option>
</select>
<small>How long devices typically stay connected</small>
</div>
{#if churnRate === 'custom'}
<div class="input-group">
<label for="custom-churn">
<Icon name="clock" size="sm" />
Custom Churn Time (hours)
</label>
<input id="custom-churn" type="number" bind:value={customChurnHours} placeholder="24" min="1" />
<small>Average hours a device stays connected</small>
</div>
{/if}
</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>Calculated Lease Times</h3>
<div class="summary-card">
<div><strong>Pool Utilization:</strong> {result.utilizationPercent}%</div>
<div><strong>Recommended Lease:</strong> {result.recommendedLeaseFormatted}</div>
</div>
{#if result.exhaustionTime}
<div class="warning-card">
<Icon name="alert-triangle" size="sm" />
<span><strong>Address Exhaustion:</strong> {result.exhaustionTime}</span>
</div>
{/if}
<div class="lease-times">
{#each [{ label: 'Default Lease Time', value: result.recommendedLeaseFormatted, seconds: result.recommendedLeaseSeconds, key: 'lease' }, { label: 'T1 (Renewal)', value: result.t1RenewalFormatted, seconds: result.t1RenewalSeconds, key: 't1' }, { label: 'T2 (Rebinding)', value: result.t2RebindingFormatted, seconds: result.t2RebindingSeconds, key: 't2' }] as time (time.key)}
<div class="time-item">
<div class="time-header">
<span class="time-label">{time.label}</span>
<button
type="button"
class="copy-btn-small"
onclick={() => clipboard.copy(String(time.seconds), time.key)}
>
<Icon name={clipboard.isCopied(time.key) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="time-value">{time.value}</div>
<div class="time-seconds">{time.seconds} seconds</div>
</div>
{/each}
</div>
{#if result.recommendations.length > 0}
<div class="recommendations">
<h4>Recommendations</h4>
{#each result.recommendations as recommendation, i (i)}
<div class="recommendation-item">
{recommendation}
</div>
{/each}
</div>
{/if}
</div>
{#each [{ title: 'ISC DHCPd Configuration', content: result.configExamples.iscDhcpd, key: 'isc' }, { title: 'Kea DHCPv4 Configuration', content: result.configExamples.keaDhcp4, key: 'kea' }] as config (config.key)}
<div class="card results">
<div class="card-header-with-action">
<h3>{config.title}</h3>
<button
type="button"
class="copy-btn"
class:copied={clipboard.isCopied(config.key)}
onclick={() => clipboard.copy(config.content, config.key)}
>
<Icon name={clipboard.isCopied(config.key) ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied(config.key) ? 'Copied' : 'Copy'}
</button>
</div>
<pre class="output-value code-block">{config.content}</pre>
</div>
{/each}
{/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-md);
}
}
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 0 var(--spacing-sm);
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-header-with-action {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-md);
h3 {
margin: 0;
}
}
.card-content {
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.input-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: var(--spacing-md);
@media (max-width: 768px) {
grid-template-columns: 1fr;
}
}
.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%);
}
}
small {
color: var(--text-secondary);
font-size: 0.85rem;
}
}
.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;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.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);
}
}
.warning-card {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-md);
background: color-mix(in srgb, var(--color-warning), transparent 95%);
border: 1px solid var(--color-warning);
border-radius: var(--radius-md);
margin-bottom: var(--spacing-lg);
color: var(--color-warning);
font-size: 0.9375rem;
}
.lease-times {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: var(--spacing-md);
margin-bottom: var(--spacing-lg);
.time-item {
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
.time-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-sm);
.time-label {
font-weight: 600;
font-size: 0.875rem;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
}
}
.time-value {
font-size: 1.125rem;
font-weight: 600;
color: var(--color-primary);
margin-bottom: var(--spacing-xs);
}
.time-seconds {
font-size: 0.8125rem;
color: var(--text-secondary);
}
}
}
.recommendations {
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
.recommendation-item {
padding: var(--spacing-sm);
margin-bottom: var(--spacing-xs);
font-size: 0.9375rem;
color: var(--text-primary);
line-height: 1.5;
&:last-child {
margin-bottom: 0;
}
}
}
.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);
}
}
.copy-btn-small {
display: flex;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-xs);
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);
}
}
.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;
}
</style>
@@ -0,0 +1,556 @@
<script lang="ts">
import {
type LeaseTimeConfig,
type LeaseTimeResult,
buildLeaseTimeOption,
decodeLeaseTimeOption,
validateLeaseTimeConfig,
formatTime,
LEASE_TIME_PRESETS,
} from '$lib/utils/dhcp-option51-lease-time';
import { untrack } from 'svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import ExamplesCard from '$lib/components/common/ExamplesCard.svelte';
import { useClipboard } from '$lib/composables/useClipboard.svelte';
const clipboard = useClipboard();
type Tab = 'build' | 'decode';
let activeTab = $state<Tab>('build');
// Build mode state
let leaseSeconds = $state<number>(86400);
let infinite = $state<boolean>(false);
let buildResult = $state<LeaseTimeResult | null>(null);
let buildErrors = $state<string[]>([]);
// Decode mode state
let hexInput = $state<string>('');
let decodeResult = $state<LeaseTimeResult | null>(null);
let decodeError = $state<string>('');
const navOptions = [
{ value: 'build', label: 'Build Option' },
{ value: 'decode', label: 'Decode Option' },
];
const examples = LEASE_TIME_PRESETS.map((preset) => ({
...preset,
description: `${preset.description} • ${preset.infinite ? 'Infinite' : formatTime(preset.seconds)}`,
}));
function loadPreset(preset: (typeof LEASE_TIME_PRESETS)[0]) {
activeTab = 'build';
if (preset.infinite) {
infinite = true;
leaseSeconds = 0;
} else {
infinite = false;
leaseSeconds = preset.seconds;
}
}
// Build mode effect
$effect(() => {
if (activeTab !== 'build') return;
const currentSeconds = leaseSeconds;
const currentInfinite = infinite;
untrack(() => {
const config: LeaseTimeConfig = {
leaseSeconds: currentSeconds,
infinite: currentInfinite,
};
buildErrors = validateLeaseTimeConfig(config);
// Build even with warnings
try {
buildResult = buildLeaseTimeOption(config);
} catch (err) {
buildErrors = [err instanceof Error ? err.message : 'Unknown error'];
buildResult = null;
}
});
});
// Decode mode effect
$effect(() => {
if (activeTab !== 'decode') return;
const currentHex = hexInput;
untrack(() => {
if (!currentHex.trim()) {
decodeResult = null;
decodeError = '';
return;
}
try {
decodeResult = decodeLeaseTimeOption(currentHex);
decodeError = '';
} catch (err) {
decodeError = err instanceof Error ? err.message : 'Unknown error';
decodeResult = null;
}
});
});
</script>
<ToolContentContainer
title="DHCP Option 51 - IP Address Lease Time"
description="Option 51 specifies the lease time in seconds for the IP address assignment. T1 (renewal at 50%) and T2 (rebinding at 87.5%) timers are automatically calculated."
{navOptions}
bind:selectedNav={activeTab}
>
<ExamplesCard {examples} onSelect={loadPreset} getLabel={(ex) => ex.label} getDescription={(ex) => ex.description} />
{#if activeTab === 'build'}
<div class="card input-card">
<h3>Lease Time Configuration</h3>
<div class="form-group">
<label class="checkbox-label">
<input type="checkbox" bind:checked={infinite} />
Infinite Lease (0xFFFFFFFF)
</label>
<span class="hint">Permanent IP address assignment (may not be supported by all servers)</span>
</div>
{#if !infinite}
<div class="form-group">
<label for="lease-seconds">Lease Time (seconds)</label>
<input id="lease-seconds" type="number" bind:value={leaseSeconds} min="0" max="4294967294" class="input" />
{#if leaseSeconds > 0}
<span class="hint">= {formatTime(leaseSeconds)}</span>
{/if}
</div>
<div class="quick-values">
<span class="label">Quick Values:</span>
<button class="btn-quick" onclick={() => (leaseSeconds = 3600)}>1h</button>
<button class="btn-quick" onclick={() => (leaseSeconds = 14400)}>4h</button>
<button class="btn-quick" onclick={() => (leaseSeconds = 86400)}>24h</button>
<button class="btn-quick" onclick={() => (leaseSeconds = 259200)}>3d</button>
<button class="btn-quick" onclick={() => (leaseSeconds = 604800)}>7d</button>
</div>
{/if}
{#if buildErrors.length > 0}
<div class="error-card" class:warning={buildErrors.every((e) => e.startsWith('Warning:'))}>
<strong>{buildErrors.some((e) => e.startsWith('Warning:')) ? 'Warnings:' : 'Validation Errors:'}</strong>
<ul>
{#each buildErrors as error, i (i)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
</div>
{#if buildResult}
<div class="card result-card">
<h3>Option 51 - Lease Time</h3>
<div class="result-grid">
<div class="result-item">
<span class="label">Lease Time:</span>
<span class="value highlight">{buildResult.humanReadable}</span>
</div>
<div class="result-item">
<span class="label">Hex Encoded:</span>
<code class="code-value">{buildResult.hexEncoded}</code>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.hexEncoded)} aria-label="Copy hex">
Copy
</button>
</div>
<div class="result-item">
<span class="label">Wire Format:</span>
<code class="code-value">{buildResult.wireFormat}</code>
<button
class="btn-copy"
onclick={() => clipboard.copy(buildResult!.wireFormat)}
aria-label="Copy wire format"
>
Copy
</button>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{buildResult.totalLength} bytes</span>
</div>
{#if !buildResult.isInfinite}
<div class="result-item">
<span class="label">T1 Renewal:</span>
<span class="value">{buildResult.t1RenewalFormatted} (50% of lease)</span>
</div>
<div class="result-item">
<span class="label">T2 Rebinding:</span>
<span class="value">{buildResult.t2RebindingFormatted} (87.5% of lease)</span>
</div>
{/if}
</div>
<div class="config-section">
<h4>Configuration Examples</h4>
<div class="config-example">
<h5>ISC DHCPd</h5>
<pre><code>{buildResult.configExamples.iscDhcpd}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.iscDhcpd)}>
Copy
</button>
</div>
<div class="config-example">
<h5>Kea DHCPv4</h5>
<pre><code>{buildResult.configExamples.keaDhcp4}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.keaDhcp4)}>
Copy
</button>
</div>
<div class="config-example">
<h5>dnsmasq</h5>
<pre><code>{buildResult.configExamples.dnsmasq}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(buildResult!.configExamples.dnsmasq)}> Copy </button>
</div>
</div>
</div>
{/if}
{:else}
<div class="card input-card">
<h3>Decode Option 51</h3>
<div class="form-group">
<label for="hex-input">Hex String</label>
<input
id="hex-input"
type="text"
bind:value={hexInput}
placeholder="e.g., 00015180 or 00 01 51 80"
class="input"
/>
<span class="hint">Enter 8 hex characters (4 bytes, spaces optional)</span>
</div>
{#if decodeError}
<div class="error-card">
<strong>Decode Error:</strong>
<p>{decodeError}</p>
</div>
{/if}
</div>
{#if decodeResult}
<div class="card result-card">
<h3>Decoded Option 51</h3>
<div class="result-grid">
<div class="result-item">
<span class="label">Lease Time:</span>
<span class="value highlight">{decodeResult.humanReadable}</span>
</div>
<div class="result-item">
<span class="label">Seconds:</span>
<span class="value">{decodeResult.leaseSeconds.toLocaleString()}</span>
</div>
{#if decodeResult.isInfinite}
<div class="result-item infinite-badge">
<span class="badge">Infinite Lease</span>
</div>
{/if}
{#if !decodeResult.isInfinite}
<div class="result-item">
<span class="label">T1 Renewal:</span>
<span class="value">{decodeResult.t1RenewalFormatted} (50% of lease)</span>
</div>
<div class="result-item">
<span class="label">T2 Rebinding:</span>
<span class="value">{decodeResult.t2RebindingFormatted} (87.5% of lease)</span>
</div>
{/if}
</div>
<div class="config-section">
<h4>Configuration Examples</h4>
<div class="config-example">
<h5>ISC DHCPd</h5>
<pre><code>{decodeResult.configExamples.iscDhcpd}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(decodeResult!.configExamples.iscDhcpd)}>
Copy
</button>
</div>
<div class="config-example">
<h5>Kea DHCPv4</h5>
<pre><code>{decodeResult.configExamples.keaDhcp4}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(decodeResult!.configExamples.keaDhcp4)}>
Copy
</button>
</div>
<div class="config-example">
<h5>dnsmasq</h5>
<pre><code>{decodeResult.configExamples.dnsmasq}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(decodeResult!.configExamples.dnsmasq)}>
Copy
</button>
</div>
</div>
</div>
{/if}
{/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-md);
&.input-card {
background: var(--bg-tertiary);
}
h3 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-lg);
}
h4 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
h5 {
margin: 0 0 var(--spacing-sm) 0;
color: var(--text-secondary);
font-size: var(--font-size-sm);
font-weight: 600;
}
}
.form-group {
margin-bottom: var(--spacing-md);
label {
display: block;
margin-bottom: var(--spacing-xs);
color: var(--text-primary);
font-weight: 500;
}
.hint {
display: block;
margin-top: var(--spacing-xs);
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
.checkbox-label {
display: flex;
align-items: center;
gap: var(--spacing-sm);
cursor: pointer;
input[type='checkbox'] {
cursor: pointer;
}
}
.input {
width: 100%;
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: var(--font-mono);
font-size: var(--font-size-sm);
transition: border-color 0.2s;
&:focus {
outline: none;
border-color: var(--color-primary);
}
}
.quick-values {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-xs);
align-items: center;
padding: var(--spacing-sm);
background: var(--bg-primary);
border-radius: var(--radius-md);
.label {
color: var(--text-secondary);
font-size: var(--font-size-sm);
margin-right: var(--spacing-xs);
}
}
.btn-quick {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: var(--bg-secondary);
}
}
.error-card {
background: color-mix(in srgb, var(--color-error), transparent 90%);
border: 1px solid var(--color-error);
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin-top: var(--spacing-md);
&.warning {
background: color-mix(in srgb, var(--color-warning), transparent 90%);
border-color: var(--color-warning);
strong {
color: var(--color-warning);
}
}
strong {
color: var(--color-error);
display: block;
margin-bottom: var(--spacing-xs);
}
ul {
margin: 0;
padding-left: var(--spacing-lg);
color: var(--text-primary);
}
p {
margin: 0;
color: var(--text-primary);
}
}
.result-card {
h3 {
color: var(--color-success);
}
}
.result-grid {
display: grid;
gap: var(--spacing-md);
}
.result-item {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-sm);
align-items: center;
padding: var(--spacing-sm);
background: var(--bg-tertiary);
border-radius: var(--radius-md);
.label {
font-weight: 500;
color: var(--text-secondary);
min-width: 120px;
}
.value,
.code-value {
flex: 1;
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
}
.value.highlight {
color: var(--color-primary);
font-weight: 600;
font-size: var(--font-size-md);
}
&.infinite-badge {
justify-content: center;
background: color-mix(in srgb, var(--color-info), transparent 90%);
border: 1px solid var(--color-info);
.badge {
padding: var(--spacing-xs) var(--spacing-md);
background: var(--color-info);
color: var(--text-inverse);
border-radius: var(--radius-sm);
font-weight: 600;
}
}
}
.config-section {
margin-top: var(--spacing-lg);
padding-top: var(--spacing-lg);
border-top: 1px solid var(--border-primary);
}
.config-example {
position: relative;
margin-bottom: var(--spacing-md);
pre {
margin: 0;
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
overflow-x: auto;
code {
font-family: var(--font-mono);
font-size: var(--font-size-sm);
color: var(--text-primary);
}
}
}
.btn-copy {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: var(--bg-secondary);
}
}
</style>
@@ -0,0 +1,554 @@
<script lang="ts">
import {
type PrefixDelegationConfig,
type PrefixConfig,
type PrefixDelegationResult,
buildPrefixDelegation,
validatePrefixDelegationConfig,
PREFIX_DELEGATION_EXAMPLES,
formatTime,
} from '$lib/utils/dhcpv6-prefix-delegation';
import { untrack } from 'svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import ExamplesCard from '$lib/components/common/ExamplesCard.svelte';
import { useClipboard } from '$lib/composables/useClipboard.svelte';
const clipboard = useClipboard();
// State
let iaid = $state<number>(1);
let t1 = $state<number | undefined>(302400);
let t2 = $state<number | undefined>(483840);
let prefixes = $state<PrefixConfig[]>([
{
prefix: '2001:db8::/56',
preferredLifetime: 604800,
validLifetime: 2592000,
},
]);
let result = $state<PrefixDelegationResult | null>(null);
let errors = $state<string[]>([]);
function loadExample(example: (typeof PREFIX_DELEGATION_EXAMPLES)[0]) {
iaid = example.config.iaid;
t1 = example.config.t1;
t2 = example.config.t2;
prefixes = example.config.prefixes.map((p) => ({ ...p }));
}
function addPrefix() {
prefixes = [
...prefixes,
{
prefix: '2001:db8::/56',
preferredLifetime: 604800,
validLifetime: 2592000,
},
];
}
function removePrefix(index: number) {
prefixes = prefixes.filter((_, i) => i !== index);
if (prefixes.length === 0) {
addPrefix();
}
}
// Build effect
$effect(() => {
const currentIaid = iaid;
const currentT1 = t1;
const currentT2 = t2;
const currentPrefixes = prefixes;
untrack(() => {
const config: PrefixDelegationConfig = {
iaid: currentIaid,
t1: currentT1,
t2: currentT2,
prefixes: currentPrefixes,
};
errors = validatePrefixDelegationConfig(config);
if (errors.length === 0) {
try {
result = buildPrefixDelegation(config);
} catch (err) {
errors = [err instanceof Error ? err.message : 'Unknown error'];
result = null;
}
} else {
result = null;
}
});
});
</script>
<ToolContentContainer
title="DHCPv6 Prefix Delegation (IA_PD)"
description="Build DHCPv6 IA_PD options for delegating IPv6 prefixes to requesting routers. Configure Identity Association for Prefix Delegation (Option 25) with IA Prefix options (Option 26) per RFC 8415."
>
<ExamplesCard
examples={PREFIX_DELEGATION_EXAMPLES}
onSelect={(ex) => loadExample(ex)}
getLabel={(ex) => ex.label}
getDescription={(ex) => ex.description}
/>
<div class="card input-card">
<h3>Prefix Delegation Configuration</h3>
<div class="form-row">
<div class="form-group">
<label for="iaid">IAID (Identity Association ID)</label>
<input id="iaid" type="number" bind:value={iaid} min="0" max="4294967295" class="input" />
<span class="hint">Unique identifier for this IA_PD (0-4294967295)</span>
</div>
<div class="form-group">
<label for="t1">T1 Renewal Time (seconds)</label>
<input id="t1" type="number" bind:value={t1} min="0" max="4294967295" placeholder="Optional" class="input" />
{#if t1}
<span class="hint">= {formatTime(t1)}</span>
{/if}
</div>
<div class="form-group">
<label for="t2">T2 Rebinding Time (seconds)</label>
<input id="t2" type="number" bind:value={t2} min="0" max="4294967295" placeholder="Optional" class="input" />
{#if t2}
<span class="hint">= {formatTime(t2)}</span>
{/if}
</div>
</div>
<div class="form-group">
<label for="prefix-0">Delegated Prefixes</label>
{#each prefixes as prefix, i (i)}
<div class="prefix-row">
<div class="prefix-inputs">
<input
id={i === 0 ? 'prefix-0' : undefined}
type="text"
bind:value={prefix.prefix}
placeholder="e.g., 2001:db8::/56"
class="input"
aria-label={i > 0 ? `Prefix ${i + 1}` : undefined}
/>
<input
type="number"
bind:value={prefix.preferredLifetime}
min="0"
max="4294967295"
placeholder="Preferred (s)"
class="input input-sm"
aria-label="Preferred lifetime"
/>
<input
type="number"
bind:value={prefix.validLifetime}
min="0"
max="4294967295"
placeholder="Valid (s)"
class="input input-sm"
aria-label="Valid lifetime"
/>
</div>
{#if prefixes.length > 1}
<button class="btn btn-danger btn-sm" onclick={() => removePrefix(i)}>Remove</button>
{/if}
</div>
{/each}
<button class="btn btn-secondary btn-sm" onclick={addPrefix}>Add Prefix</button>
</div>
{#if errors.length > 0}
<div class="error-card">
<strong>Validation Errors:</strong>
<ul>
{#each errors as error, i (i)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
</div>
{#if result}
<div class="card result-card">
<h3>Option 25 - IA_PD</h3>
<div class="result-grid">
<div class="result-item">
<span class="label">IAID:</span>
<code class="code-value">{result.iaid} (0x{result.iaidHex})</code>
</div>
<div class="result-item">
<span class="label">T1 Renewal:</span>
<span class="value">{result.t1Formatted} ({result.t1}s)</span>
</div>
<div class="result-item">
<span class="label">T2 Rebinding:</span>
<span class="value">{result.t2Formatted} ({result.t2}s)</span>
</div>
<div class="result-item">
<span class="label">Full Hex:</span>
<code class="code-value">{result.fullHex}</code>
<button class="btn-copy" onclick={() => clipboard.copy(result!.fullHex)} aria-label="Copy hex"> Copy </button>
</div>
<div class="result-item">
<span class="label">Wire Format:</span>
<code class="code-value">{result.fullWireFormat}</code>
<button class="btn-copy" onclick={() => clipboard.copy(result!.fullWireFormat)} aria-label="Copy wire format">
Copy
</button>
</div>
<div class="result-item">
<span class="label">Total Length:</span>
<span class="value">{result.totalLength} bytes</span>
</div>
</div>
<div class="prefixes-section">
<h4>Delegated Prefixes (Option 26)</h4>
{#each result.prefixes as prefix, i (i)}
<div class="prefix-card">
<div class="prefix-header">
<span class="prefix-number">{i + 1}</span>
<code class="prefix-value">{prefix.prefix}</code>
</div>
<div class="prefix-details">
<div class="detail-item">
<span class="detail-label">Preferred Lifetime:</span>
<span>{prefix.preferredLifetimeFormatted} ({prefix.preferredLifetime}s)</span>
</div>
<div class="detail-item">
<span class="detail-label">Valid Lifetime:</span>
<span>{prefix.validLifetimeFormatted} ({prefix.validLifetime}s)</span>
</div>
<div class="detail-item">
<span class="detail-label">Wire Format:</span>
<code class="code-small">{prefix.wireFormat}</code>
<button
class="btn-copy btn-copy-sm"
onclick={() => clipboard.copy(prefix.wireFormat.replace(/\s/g, ''))}
aria-label="Copy prefix wire format"
>
Copy
</button>
</div>
</div>
</div>
{/each}
</div>
<div class="config-section">
<h4>Configuration Example</h4>
<div class="config-example">
<h5>Kea DHCPv6</h5>
<pre><code>{result.examples.keaDhcp6}</code></pre>
<button class="btn-copy" onclick={() => clipboard.copy(result!.examples.keaDhcp6!)}> Copy </button>
</div>
</div>
</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-md);
&.input-card {
background: var(--bg-tertiary);
}
h3 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-lg);
}
h4 {
margin: 0 0 var(--spacing-md) 0;
color: var(--text-primary);
font-size: var(--font-size-md);
}
h5 {
margin: 0 0 var(--spacing-sm) 0;
color: var(--text-secondary);
font-size: var(--font-size-sm);
font-weight: 600;
}
}
.form-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: var(--spacing-md);
margin-bottom: var(--spacing-md);
}
.form-group {
margin-bottom: var(--spacing-md);
label {
display: block;
margin-bottom: var(--spacing-xs);
color: var(--text-primary);
font-weight: 500;
}
.hint {
display: block;
margin-top: var(--spacing-xs);
font-size: var(--font-size-sm);
color: var(--text-tertiary);
}
}
.input {
width: 100%;
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: var(--font-mono);
font-size: var(--font-size-sm);
transition: border-color 0.2s;
&:focus {
outline: none;
border-color: var(--color-primary);
}
&.input-sm {
padding: var(--spacing-xs) var(--spacing-sm);
font-size: var(--font-size-xs);
}
}
.prefix-row {
display: flex;
gap: var(--spacing-sm);
margin-bottom: var(--spacing-sm);
align-items: flex-start;
.prefix-inputs {
display: grid;
grid-template-columns: 2fr 1fr 1fr;
gap: var(--spacing-sm);
flex: 1;
}
}
.btn {
padding: var(--spacing-sm) var(--spacing-md);
background: var(--color-primary);
color: var(--text-inverse);
border: none;
border-radius: var(--radius-md);
cursor: pointer;
font-weight: 500;
transition: opacity 0.2s;
&:hover {
opacity: 0.9;
}
&.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-primary);
}
&.btn-danger {
background: var(--color-error);
}
&.btn-sm {
padding: var(--spacing-xs) var(--spacing-sm);
font-size: var(--font-size-sm);
}
}
.error-card {
background: color-mix(in srgb, var(--color-error), transparent 90%);
border: 1px solid var(--color-error);
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin-top: var(--spacing-md);
strong {
color: var(--color-error);
display: block;
margin-bottom: var(--spacing-xs);
}
ul {
margin: 0;
padding-left: var(--spacing-lg);
color: var(--text-primary);
}
}
.result-card {
h3 {
color: var(--color-success);
}
}
.result-grid {
display: grid;
gap: var(--spacing-md);
}
.result-item {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-sm);
align-items: center;
padding: var(--spacing-sm);
background: var(--bg-tertiary);
border-radius: var(--radius-md);
.label {
font-weight: 500;
color: var(--text-secondary);
min-width: 120px;
}
.value,
.code-value {
flex: 1;
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
}
}
.prefixes-section {
margin-top: var(--spacing-lg);
padding-top: var(--spacing-lg);
border-top: 1px solid var(--border-primary);
}
.prefix-card {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin-bottom: var(--spacing-md);
.prefix-header {
display: flex;
align-items: center;
gap: var(--spacing-sm);
margin-bottom: var(--spacing-md);
.prefix-number {
display: flex;
align-items: center;
justify-content: center;
min-width: 28px;
height: 28px;
background: var(--color-primary);
color: var(--text-inverse);
border-radius: var(--radius-sm);
font-weight: 600;
font-size: var(--font-size-sm);
}
.prefix-value {
font-family: var(--font-mono);
font-size: var(--font-size-md);
color: var(--color-primary);
font-weight: 600;
}
}
.prefix-details {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
.detail-item {
display: flex;
align-items: center;
gap: var(--spacing-sm);
font-size: var(--font-size-sm);
.detail-label {
font-weight: 500;
color: var(--text-secondary);
min-width: 140px;
}
.code-small {
font-family: var(--font-mono);
color: var(--text-primary);
word-break: break-all;
flex: 1;
}
}
}
}
.config-section {
margin-top: var(--spacing-lg);
padding-top: var(--spacing-lg);
border-top: 1px solid var(--border-primary);
}
.config-example {
position: relative;
margin-bottom: var(--spacing-md);
pre {
margin: 0;
padding: var(--spacing-md);
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
overflow-x: auto;
code {
font-family: var(--font-mono);
font-size: var(--font-size-sm);
color: var(--text-primary);
}
}
}
.btn-copy {
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: var(--bg-secondary);
}
&.btn-copy-sm {
padding: 2px var(--spacing-xs);
font-size: var(--font-size-xs);
}
}
</style>
+210
View File
@@ -805,6 +805,87 @@ export const SUB_NAV: Record<string, (NavItem | NavGroup)[]> = {
title: 'DHCPv4 Options',
description: 'DHCPv4 option generators and builders',
items: [
{
href: makePath('/dhcp/v4/options/option3-default-gateway'),
label: 'Option 3 - Router/Default Gateway',
description:
'Build and decode DHCP default gateway configuration with support for multiple gateways and subnet validation',
icon: 'router',
keywords: [
'dhcp',
'dhcpv4',
'option',
'option 3',
'router',
'default',
'gateway',
'routing',
'gateways',
'redundancy',
'failover',
'load balancing',
'multiple',
'subnet',
'validation',
'network',
'isc',
'kea',
'dnsmasq',
],
},
{
href: makePath('/dhcp/v4/options/options6-15-dns'),
label: 'Options 6 & 15 - DNS & Domain',
description: 'Build and decode DNS server and domain name options for complete DNS configuration',
icon: 'dns',
keywords: [
'dhcp',
'dhcpv4',
'option',
'option 6',
'option 15',
'dns',
'domain',
'name',
'servers',
'nameservers',
'resolution',
'hostname',
'google',
'cloudflare',
'quad9',
'public dns',
'isc',
'kea',
'dnsmasq',
],
},
{
href: makePath('/dhcp/v4/options/option51-lease-time'),
label: 'Option 51 - IP Address Lease Time',
description: 'Build and decode lease time option with automatic T1/T2 renewal timer calculations',
icon: 'clock',
keywords: [
'dhcp',
'dhcpv4',
'option',
'51',
'lease',
'time',
'duration',
't1',
't2',
'renewal',
'rebinding',
'infinite',
'permanent',
'timer',
'seconds',
'isc',
'kea',
'dnsmasq',
],
},
{
href: makePath('/dhcp/v4/options/option43-vendor-specific'),
label: 'Option 43 - Vendor Specific',
@@ -1143,6 +1224,77 @@ export const SUB_NAV: Record<string, (NavItem | NavGroup)[]> = {
'suffix',
],
},
{
href: makePath('/dhcp/v6/options/option25-prefix-delegation'),
label: 'Options 25/26 - Prefix Delegation',
description:
'Build DHCPv6 IA_PD options for delegating IPv6 prefixes to requesting routers with IA Prefix options per RFC 8415',
icon: 'share',
keywords: [
'dhcpv6',
'dhcp',
'v6',
'ipv6',
'option',
'25',
'26',
'ia_pd',
'prefix',
'delegation',
'pd',
'router',
'isp',
'subnet',
'allocation',
'rfc',
'8415',
'wire',
'format',
'kea',
'isc',
'configuration',
'iaid',
't1',
't2',
'lifetime',
],
},
{
href: makePath('/dhcp/v6/options/option39-fqdn'),
label: 'Option 39 - Client FQDN',
description:
'Configure Client FQDN Option for DHCPv6 dynamic DNS updates with S, O, and N flags per RFC 4704',
icon: 'globe',
keywords: [
'dhcpv6',
'dhcp',
'v6',
'ipv6',
'option',
'39',
'fqdn',
'client',
'fully',
'qualified',
'domain',
'name',
'hostname',
'dns',
'ddns',
'dynamic',
'updates',
'rfc',
'4704',
'flags',
'server',
'override',
'wire',
'format',
'kea',
'isc',
'configuration',
],
},
],
},
{
@@ -1214,6 +1366,64 @@ export const SUB_NAV: Record<string, (NavItem | NavGroup)[]> = {
},
],
},
{
title: 'Calculators & Planning',
description: 'Network planning and optimization tools',
items: [
{
href: makePath('/dhcp/calculators/lease-time'),
label: 'Lease Time Calculator',
description:
'Calculate optimal DHCP lease times based on pool size, client count, and turnover rate with T1/T2 renewal timers',
icon: 'clock',
keywords: [
'dhcp',
'lease',
'time',
'calculator',
'renewal',
't1',
't2',
'rebinding',
'optimization',
'planning',
'pool',
'utilization',
'exhaustion',
'churn',
'turnover',
],
},
{
href: makePath('/dhcp/tools/fingerprinting'),
label: 'DHCP Fingerprinting Database',
description:
'Identify devices by their DHCP fingerprints using Parameter Request List (Option 55) and Vendor Class patterns',
icon: 'fingerprint',
keywords: [
'dhcp',
'fingerprint',
'fingerprinting',
'device',
'identification',
'option',
'55',
'parameter',
'request',
'list',
'vendor',
'class',
'windows',
'macos',
'ios',
'android',
'linux',
'detection',
'analysis',
],
},
],
},
{
title: 'Configuration Generators',
description: 'Server configuration generators and snippets',
+858
View File
@@ -0,0 +1,858 @@
/**
* DHCP Fingerprinting Database
*
* Identifies devices based on DHCP fingerprints, primarily using:
* - Option 55 (Parameter Request List)
* - Option 60 (Vendor Class Identifier)
* - Option 61 (Client Identifier format)
*
* References:
* - fingerbank.org
* - dhcpcd project
* - ISC DHCP fingerprints
*/
export interface DHCPFingerprint {
id: string;
device: string;
os: string;
category: 'desktop' | 'mobile' | 'iot' | 'server' | 'network' | 'gaming' | 'other';
parameterRequestList: number[]; // Option 55
vendorClassPattern?: string; // Option 60 pattern
description?: string;
confidence: 'high' | 'medium' | 'low';
}
export interface FingerprintMatch {
fingerprint: DHCPFingerprint;
matchScore: number;
matchedOn: string[];
}
export interface OptionAnalysis {
unusual: number[];
security: number[];
missing: number[];
warnings: string[];
}
// Security-relevant DHCP options
const SECURITY_OPTIONS = [252, 249, 82, 43, 125];
// Rare/unusual options that might indicate specific vendors
const UNUSUAL_OPTIONS = [
77, 93, 94, 97, 120, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146,
150, 208, 209, 210, 211, 212, 213, 220,
];
/**
* Database of known DHCP fingerprints
*/
export const FINGERPRINT_DATABASE: DHCPFingerprint[] = [
// Windows
{
id: 'win10',
device: 'Windows 10/11',
os: 'Windows',
category: 'desktop',
parameterRequestList: [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252],
confidence: 'high',
description: 'Windows 10/11 desktop or laptop',
},
{
id: 'win7',
device: 'Windows 7',
os: 'Windows',
category: 'desktop',
parameterRequestList: [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 121, 249, 252],
confidence: 'high',
description: 'Windows 7 desktop or laptop',
},
{
id: 'winserver',
device: 'Windows Server',
os: 'Windows Server',
category: 'server',
parameterRequestList: [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252],
vendorClassPattern: 'MSFT',
confidence: 'medium',
description: 'Windows Server 2016/2019/2022',
},
// macOS / iOS
{
id: 'macos',
device: 'macOS',
os: 'macOS',
category: 'desktop',
parameterRequestList: [1, 3, 6, 15, 119, 252],
confidence: 'high',
description: 'Apple macOS device',
},
{
id: 'ios',
device: 'iPhone/iPad',
os: 'iOS',
category: 'mobile',
parameterRequestList: [1, 3, 6, 15, 119, 252],
confidence: 'medium',
description: 'Apple iOS device (iPhone/iPad)',
},
// Android
{
id: 'android',
device: 'Android Device',
os: 'Android',
category: 'mobile',
parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59, 43],
vendorClassPattern: 'dhcpcd',
confidence: 'high',
description: 'Android smartphone or tablet',
},
{
id: 'android-alt',
device: 'Android Device',
os: 'Android',
category: 'mobile',
parameterRequestList: [1, 3, 6, 15, 26, 28],
confidence: 'medium',
description: 'Android device (alternative fingerprint)',
},
// Linux
{
id: 'linux-dhclient',
device: 'Linux (dhclient)',
os: 'Linux',
category: 'desktop',
parameterRequestList: [1, 3, 6, 15, 26, 28, 42],
confidence: 'high',
description: 'Linux system using ISC dhclient',
},
{
id: 'linux-dhcpcd',
device: 'Linux (dhcpcd)',
os: 'Linux',
category: 'desktop',
parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59],
vendorClassPattern: 'dhcpcd',
confidence: 'high',
description: 'Linux system using dhcpcd',
},
{
id: 'ubuntu',
device: 'Ubuntu Linux',
os: 'Linux',
category: 'desktop',
parameterRequestList: [1, 28, 2, 3, 15, 6, 119, 12, 44, 47, 26, 121, 42],
confidence: 'medium',
description: 'Ubuntu desktop or server',
},
// IoT Devices
{
id: 'raspberry-pi',
device: 'Raspberry Pi',
os: 'Linux',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59, 43],
vendorClassPattern: 'dhcpcd',
confidence: 'medium',
description: 'Raspberry Pi (Raspbian/Raspberry Pi OS)',
},
{
id: 'esp32',
device: 'ESP32',
os: 'ESP-IDF/Arduino',
category: 'iot',
parameterRequestList: [1, 3, 6, 15],
confidence: 'low',
description: 'ESP32 microcontroller',
},
{
id: 'arduino',
device: 'Arduino',
os: 'Arduino',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 28, 51, 58, 59],
confidence: 'low',
description: 'Arduino with Ethernet shield',
},
// Network Equipment
{
id: 'cisco-phone',
device: 'Cisco IP Phone',
os: 'Cisco',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 66, 67, 120, 150],
vendorClassPattern: 'Cisco',
confidence: 'high',
description: 'Cisco IP Phone',
},
{
id: 'hp-printer',
device: 'HP Printer',
os: 'Printer OS',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 40, 41, 42],
vendorClassPattern: 'HP',
confidence: 'high',
description: 'HP Network Printer',
},
// Gaming Consoles
{
id: 'ps5',
device: 'PlayStation 5',
os: 'PlayStation OS',
category: 'gaming',
parameterRequestList: [1, 3, 6, 15, 12],
confidence: 'medium',
description: 'Sony PlayStation 5',
},
{
id: 'ps4',
device: 'PlayStation 4',
os: 'PlayStation OS',
category: 'gaming',
parameterRequestList: [1, 3, 6, 15, 12, 28],
confidence: 'medium',
description: 'Sony PlayStation 4',
},
{
id: 'xbox',
device: 'Xbox Series X/S',
os: 'Xbox OS',
category: 'gaming',
parameterRequestList: [1, 3, 6, 15, 44, 46, 47],
vendorClassPattern: 'MSFT',
confidence: 'medium',
description: 'Microsoft Xbox Series X/S',
},
{
id: 'nintendo-switch',
device: 'Nintendo Switch',
os: 'Nintendo OS',
category: 'gaming',
parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59],
confidence: 'low',
description: 'Nintendo Switch',
},
// Chrome OS
{
id: 'chromeos',
device: 'Chrome OS / Chromebook',
os: 'Chrome OS',
category: 'desktop',
parameterRequestList: [1, 3, 6, 15, 26, 28, 42],
confidence: 'medium',
description: 'Google Chrome OS device',
},
// Smart TVs
{
id: 'samsung-tv',
device: 'Samsung Smart TV',
os: 'Tizen',
category: 'iot',
parameterRequestList: [1, 3, 6, 12, 15, 28, 40, 41, 42, 119],
vendorClassPattern: 'SAMSUNG',
confidence: 'high',
description: 'Samsung Smart TV',
},
{
id: 'lg-tv',
device: 'LG Smart TV',
os: 'webOS',
category: 'iot',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42],
vendorClassPattern: 'LGE',
confidence: 'high',
description: 'LG Smart TV',
},
{
id: 'roku',
device: 'Roku Device',
os: 'Roku OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 28, 42],
vendorClassPattern: 'Roku',
confidence: 'high',
description: 'Roku streaming device',
},
{
id: 'firetv',
device: 'Amazon Fire TV',
os: 'Fire OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59],
confidence: 'medium',
description: 'Amazon Fire TV Stick/Cube',
},
{
id: 'appletv',
device: 'Apple TV',
os: 'tvOS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 119, 252],
confidence: 'medium',
description: 'Apple TV streaming device',
},
// More Printers
{
id: 'canon-printer',
device: 'Canon Printer',
os: 'Printer OS',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42],
vendorClassPattern: 'Canon',
confidence: 'high',
description: 'Canon Network Printer',
},
{
id: 'epson-printer',
device: 'Epson Printer',
os: 'Printer OS',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 54],
vendorClassPattern: 'EPSON',
confidence: 'high',
description: 'Epson Network Printer',
},
{
id: 'brother-printer',
device: 'Brother Printer',
os: 'Printer OS',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42],
vendorClassPattern: 'Brother',
confidence: 'high',
description: 'Brother Network Printer',
},
// More Network Equipment
{
id: 'ubiquiti-ap',
device: 'Ubiquiti Access Point',
os: 'UniFi',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 66, 67],
vendorClassPattern: 'ubnt',
confidence: 'high',
description: 'Ubiquiti UniFi Access Point',
},
{
id: 'aruba-ap',
device: 'Aruba Access Point',
os: 'ArubaOS',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 60],
vendorClassPattern: 'ArubaAP',
confidence: 'high',
description: 'Aruba Wireless Access Point',
},
{
id: 'mikrotik',
device: 'MikroTik Router',
os: 'RouterOS',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42],
vendorClassPattern: 'MikroTik',
confidence: 'high',
description: 'MikroTik Router/Switch',
},
// More VoIP Phones
{
id: 'yealink-phone',
device: 'Yealink IP Phone',
os: 'VoIP',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 66, 120],
vendorClassPattern: 'yealink',
confidence: 'high',
description: 'Yealink VoIP Phone',
},
{
id: 'polycom-phone',
device: 'Polycom IP Phone',
os: 'VoIP',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 66, 67, 120, 160],
vendorClassPattern: 'PolycomSoundPointIP',
confidence: 'high',
description: 'Polycom VoIP Phone',
},
{
id: 'grandstream-phone',
device: 'Grandstream IP Phone',
os: 'VoIP',
category: 'network',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 66, 120],
vendorClassPattern: 'Grandstream',
confidence: 'high',
description: 'Grandstream VoIP Phone',
},
// More IoT Devices
{
id: 'nest-thermostat',
device: 'Google Nest Thermostat',
os: 'Nest OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 28, 42],
vendorClassPattern: 'Nest',
confidence: 'medium',
description: 'Google Nest Smart Thermostat',
},
{
id: 'ring-doorbell',
device: 'Ring Doorbell',
os: 'Ring OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 28, 42],
confidence: 'low',
description: 'Ring Video Doorbell',
},
{
id: 'philips-hue',
device: 'Philips Hue Bridge',
os: 'IoT',
category: 'iot',
parameterRequestList: [1, 3, 6, 12, 15, 28],
vendorClassPattern: 'Philips',
confidence: 'medium',
description: 'Philips Hue Smart Light Bridge',
},
{
id: 'alexa-echo',
device: 'Amazon Echo',
os: 'Fire OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59],
confidence: 'low',
description: 'Amazon Alexa Echo Device',
},
{
id: 'google-home',
device: 'Google Home',
os: 'Cast OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 28, 42],
confidence: 'low',
description: 'Google Home/Nest Speaker',
},
{
id: 'sonos',
device: 'Sonos Speaker',
os: 'Sonos OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42],
vendorClassPattern: 'Sonos',
confidence: 'medium',
description: 'Sonos Wireless Speaker',
},
{
id: 'hikvision-camera',
device: 'Hikvision IP Camera',
os: 'Camera OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42],
vendorClassPattern: 'HIKVISION',
confidence: 'high',
description: 'Hikvision Security Camera',
},
{
id: 'axis-camera',
device: 'Axis IP Camera',
os: 'AXIS OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43],
vendorClassPattern: 'AXIS',
confidence: 'high',
description: 'Axis Communications Camera',
},
{
id: 'tesla',
device: 'Tesla Vehicle',
os: 'Tesla OS',
category: 'iot',
parameterRequestList: [1, 3, 6, 15, 28, 42],
confidence: 'low',
description: 'Tesla Electric Vehicle',
},
];
/**
* Parse parameter request list from various formats
*/
export function parseParameterList(input: string): number[] {
// Handle comma-separated (e.g., "1,3,6,15")
if (input.includes(',')) {
return input.split(',').map((s) => parseInt(s.trim(), 10));
}
// Handle space-separated
if (input.includes(' ')) {
const tokens = input.split(/\s+/);
// Check if all tokens are exactly 2 hex chars (hex with spaces like "01 03 06 0f")
const allHexTokens = tokens.every((t) => /^[0-9a-fA-F]{2}$/.test(t));
if (allHexTokens) {
// Parse as hex
return tokens.map((t) => parseInt(t, 16));
}
// Otherwise parse as decimal space-separated (e.g., "1 3 6 15")
return tokens.map((s) => parseInt(s.trim(), 10));
}
// Handle hex format without spaces (e.g., "0103060f")
if (/^[0-9a-fA-F]+$/.test(input) && input.length % 2 === 0) {
const params: number[] = [];
for (let i = 0; i < input.length; i += 2) {
params.push(parseInt(input.substring(i, i + 2), 16));
}
return params;
}
// Single number
return [parseInt(input, 10)];
}
/**
* Calculate match score between two parameter lists with order weighting
*/
function calculateMatchScore(requested: number[], fingerprint: number[]): number {
if (fingerprint.length === 0) return 0;
let score = 0;
const matches = requested.filter((param) => fingerprint.includes(param)).length;
const baseScore = (matches / fingerprint.length) * 100;
// Bonus for matching order of first 5 critical options
let orderBonus = 0;
const criticalCount = Math.min(5, Math.min(requested.length, fingerprint.length));
for (let i = 0; i < criticalCount; i++) {
if (requested[i] === fingerprint[i]) orderBonus += 2;
}
score = Math.min(100, baseScore + orderBonus);
return score;
}
/**
* Check if arrays match exactly
*/
function exactMatch(a: number[], b: number[]): boolean {
if (a.length !== b.length) return false;
return a.every((val, idx) => val === b[idx]);
}
/**
* Analyze DHCP options for unusual patterns and security concerns
*/
export function analyzeOptions(parameterList: number[], matches: FingerprintMatch[]): OptionAnalysis {
const unusual = parameterList.filter((opt) => UNUSUAL_OPTIONS.includes(opt));
const security = parameterList.filter((opt) => SECURITY_OPTIONS.includes(opt));
const warnings: string[] = [];
// Security warnings
if (security.includes(252)) {
warnings.push('Option 252 (WPAD) detected - potential security risk if misconfigured');
}
if (security.includes(82)) {
warnings.push('Option 82 (Relay Agent) - typically inserted by network equipment');
}
// Find missing options from best match
let missing: number[] = [];
if (matches.length > 0) {
const bestMatch = matches[0].fingerprint;
missing = bestMatch.parameterRequestList.filter((opt) => !parameterList.includes(opt));
}
return { unusual, security, missing, warnings };
}
/**
* Search for matching fingerprints with improved algorithm
*/
export function searchFingerprints(parameterList: number[], vendorClass?: string): FingerprintMatch[] {
const matches: FingerprintMatch[] = [];
for (const fingerprint of FINGERPRINT_DATABASE) {
const matchedOn: string[] = [];
let matchScore = 0;
let vendorBonus = 0;
// Check parameter list
const paramScore = calculateMatchScore(parameterList, fingerprint.parameterRequestList);
if (paramScore > 0) {
matchScore = paramScore;
if (exactMatch(parameterList, fingerprint.parameterRequestList)) {
matchedOn.push('Parameter List (Exact)');
matchScore = 100;
} else {
matchedOn.push(`Parameter List (${paramScore.toFixed(0)}%)`);
}
}
// Check vendor class if provided
if (vendorClass && fingerprint.vendorClassPattern) {
const vendorLower = vendorClass.toLowerCase();
const patternLower = fingerprint.vendorClassPattern.toLowerCase();
if (vendorLower.includes(patternLower) || patternLower.includes(vendorLower)) {
matchedOn.push('Vendor Class');
vendorBonus = 30; // Vendor match gives significant boost
matchScore = Math.max(matchScore, 60); // Minimum score with vendor match
}
}
// Apply vendor bonus
matchScore = Math.min(100, matchScore + vendorBonus);
// Only include matches with score > 45% or vendor class match
if (matchScore >= 45 || matchedOn.some((m) => m.includes('Vendor'))) {
matches.push({
fingerprint,
matchScore,
matchedOn,
});
}
}
// Sort by match score (descending), then by confidence
return matches.sort((a, b) => {
if (b.matchScore !== a.matchScore) return b.matchScore - a.matchScore;
const confWeight = { high: 3, medium: 2, low: 1 };
return confWeight[b.fingerprint.confidence] - confWeight[a.fingerprint.confidence];
});
}
/**
* Reverse lookup: find fingerprints by device/OS name
*/
export function searchByDevice(query: string): DHCPFingerprint[] {
const lowerQuery = query.toLowerCase();
return FINGERPRINT_DATABASE.filter(
(fp) =>
fp.device.toLowerCase().includes(lowerQuery) ||
fp.os.toLowerCase().includes(lowerQuery) ||
fp.description?.toLowerCase().includes(lowerQuery),
);
}
/**
* Get DHCP option names (comprehensive list)
*/
export const DHCP_OPTION_NAMES: Record<number, string> = {
1: 'Subnet Mask',
2: 'Time Offset',
3: 'Router',
4: 'Time Server',
5: 'Name Server',
6: 'Domain Name Server',
7: 'Log Server',
8: 'Cookie Server',
9: 'LPR Server',
10: 'Impress Server',
11: 'Resource Location Server',
12: 'Host Name',
13: 'Boot File Size',
14: 'Merit Dump File',
15: 'Domain Name',
16: 'Swap Server',
17: 'Root Path',
18: 'Extensions Path',
19: 'IP Forwarding',
20: 'Non-Local Source Routing',
21: 'Policy Filter',
22: 'Maximum Datagram Reassembly Size',
23: 'Default IP TTL',
24: 'Path MTU Aging Timeout',
25: 'Path MTU Plateau Table',
26: 'Interface MTU',
27: 'All Subnets Local',
28: 'Broadcast Address',
29: 'Perform Mask Discovery',
30: 'Mask Supplier',
31: 'Router Discovery',
32: 'Router Solicitation Address',
33: 'Static Route',
34: 'Trailer Encapsulation',
35: 'ARP Cache Timeout',
36: 'Ethernet Encapsulation',
37: 'TCP Default TTL',
38: 'TCP Keepalive Interval',
39: 'TCP Keepalive Garbage',
40: 'NIS Domain',
41: 'NIS Servers',
42: 'NTP Servers',
43: 'Vendor Specific',
44: 'NetBIOS Name Server',
45: 'NetBIOS Datagram Distribution Server',
46: 'NetBIOS Node Type',
47: 'NetBIOS Scope',
48: 'X Window Font Server',
49: 'X Window Display Manager',
50: 'Requested IP Address',
51: 'IP Address Lease Time',
52: 'Option Overload',
53: 'DHCP Message Type',
54: 'Server Identifier',
55: 'Parameter Request List',
56: 'Message',
57: 'Maximum DHCP Message Size',
58: 'Renewal Time (T1)',
59: 'Rebinding Time (T2)',
60: 'Vendor Class Identifier',
61: 'Client Identifier',
64: 'NIS+ Domain Name',
65: 'NIS+ Servers',
66: 'TFTP Server Name',
67: 'Bootfile Name',
68: 'Mobile IP Home Agent',
69: 'SMTP Server',
70: 'POP3 Server',
71: 'NNTP Server',
72: 'WWW Server',
73: 'Finger Server',
74: 'IRC Server',
75: 'StreetTalk Server',
76: 'STDA Server',
77: 'User Class',
78: 'Directory Agent',
79: 'Service Scope',
80: 'Rapid Commit',
81: 'Client FQDN',
82: 'Relay Agent Information',
83: 'iSNS',
85: 'NDS Servers',
86: 'NDS Tree Name',
87: 'NDS Context',
93: 'Client System Architecture',
94: 'Client Network Interface',
97: 'Client Machine Identifier',
100: 'IEEE 1003.1 TZ String',
101: 'Reference to TZ Database',
108: 'IPv6-Only Preferred',
114: 'Captive Portal',
116: 'Auto-Config',
117: 'Name Service Search',
118: 'Subnet Selection',
119: 'Domain Search',
120: 'SIP Servers',
121: 'Classless Static Route',
122: 'CableLabs Client Configuration',
123: 'GeoConf',
124: 'Vendor Class',
125: 'Vendor-Specific Information',
128: 'TFTP Server IP',
129: 'Call Server IP',
130: 'Discrimination String',
131: 'Remote Statistics Server',
132: 'VLAN ID',
133: 'Layer 2 Priority',
134: 'Diffserv Code Point',
135: 'HTTP Proxy for Phone',
136: 'PANA Authentication Agent',
137: 'LoST Server',
138: 'CAPWAP Access Controller',
139: 'IPv4 Address-MoS',
140: 'IPv4 FQDN-MoS',
141: 'SIP UA Configuration Service',
142: 'IPv4 Address ANDSF',
143: 'IPv6 Address ANDSF',
144: 'GeoLoc',
145: 'FORCERENEW_NONCE_CAPABLE',
146: 'RDNSS Selection',
150: 'TFTP Server Address',
151: 'Status Code',
152: 'Base Time',
153: 'Start Time of State',
154: 'Query Start Time',
155: 'Query End Time',
156: 'DHCP State',
157: 'Data Source',
158: 'PCP Server',
159: 'Port Params',
160: 'Captive Portal (DHCP)',
161: 'MUD URL',
208: 'PXELINUX Magic',
209: 'Configuration File',
210: 'Path Prefix',
211: 'Reboot Time',
212: '6RD',
213: 'V4 Access Domain',
220: 'Subnet Allocation',
249: 'Private/Classless Static Route (MS)',
252: 'Private/WPAD',
};
/**
* Format parameter list to hex
*/
export function formatParameterListToHex(params: number[]): string {
return params.map((p) => p.toString(16).padStart(2, '0')).join('');
}
/**
* Format parameter list for display
*/
export function formatParameterListDisplay(params: number[]): string {
return params.join(', ');
}
/**
* Export fingerprint results as JSON
*/
export function exportAsJSON(
parameterList: number[],
matches: FingerprintMatch[],
analysis: OptionAnalysis,
vendorClass?: string,
): string {
const exportData = {
timestamp: new Date().toISOString(),
input: {
parameterList,
vendorClass: vendorClass || null,
hexEncoded: formatParameterListToHex(parameterList),
},
analysis,
matches: matches.map((m) => ({
device: m.fingerprint.device,
os: m.fingerprint.os,
category: m.fingerprint.category,
confidence: m.fingerprint.confidence,
matchScore: m.matchScore,
matchedOn: m.matchedOn,
})),
};
return JSON.stringify(exportData, null, 2);
}
/**
* Export fingerprint results as CSV
*/
export function exportAsCSV(matches: FingerprintMatch[]): string {
const headers = ['Device', 'OS', 'Category', 'Confidence', 'Match Score', 'Matched On'];
const rows = matches.map((m) => [
m.fingerprint.device,
m.fingerprint.os,
m.fingerprint.category,
m.fingerprint.confidence,
m.matchScore.toFixed(1),
m.matchedOn.join('; '),
]);
return [headers.join(','), ...rows.map((row) => row.map((cell) => `"${cell}"`).join(','))].join('\n');
}
+337
View File
@@ -0,0 +1,337 @@
/**
* DHCP Lease Time Calculator
*
* Calculates optimal lease times based on network characteristics:
* - Pool size and expected client count
* - Client turnover/churn rate
* - Network type (guest, corporate, IoT, etc.)
*
* Also provides T1 (renewal) and T2 (rebinding) times
*/
export interface LeaseTimeConfig {
poolSize: number;
expectedClients: number;
churnRate: 'low' | 'medium' | 'high' | 'custom';
customChurnHours?: number;
networkType?: 'corporate' | 'guest' | 'iot' | 'residential' | 'custom';
}
export interface LeaseTimeResult {
recommendedLeaseSeconds: number;
recommendedLeaseFormatted: string;
t1RenewalSeconds: number;
t1RenewalFormatted: string;
t2RebindingSeconds: number;
t2RebindingFormatted: string;
utilizationPercent: number;
exhaustionTime: string | null;
recommendations: string[];
configExamples: {
iscDhcpd: string;
keaDhcp4: string;
};
}
interface NetworkTypeDefaults {
name: string;
leaseSeconds: number;
description: string;
}
export const NETWORK_TYPE_DEFAULTS: Record<string, NetworkTypeDefaults> = {
corporate: {
name: 'Corporate LAN',
leaseSeconds: 86400, // 24 hours
description: 'Stable network with known devices, daily renewal',
},
guest: {
name: 'Guest WiFi',
leaseSeconds: 3600, // 1 hour
description: 'High turnover, short stays, frequent address recycling',
},
iot: {
name: 'IoT Devices',
leaseSeconds: 604800, // 7 days
description: 'Stable devices, infrequent reboots, long leases preferred',
},
residential: {
name: 'Residential/Home',
leaseSeconds: 86400, // 24 hours
description: 'Mix of stable and mobile devices, moderate turnover',
},
};
export const CHURN_RATE_HOURS: Record<string, number> = {
low: 168, // 7 days - devices stay connected for weeks
medium: 24, // 1 day - typical office environment
high: 4, // 4 hours - guest networks, conferences
};
/**
* Format seconds into human-readable time
*/
export function formatTime(seconds: number): string {
if (seconds < 60) {
return `${seconds} second${seconds !== 1 ? 's' : ''}`;
}
if (seconds < 3600) {
const minutes = Math.floor(seconds / 60);
return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
}
if (seconds < 86400) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (minutes === 0) {
return `${hours} hour${hours !== 1 ? 's' : ''}`;
}
return `${hours} hour${hours !== 1 ? 's' : ''}, ${minutes} minute${minutes !== 1 ? 's' : ''}`;
}
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
if (hours === 0) {
return `${days} day${days !== 1 ? 's' : ''}`;
}
return `${days} day${days !== 1 ? 's' : ''}, ${hours} hour${hours !== 1 ? 's' : ''}`;
}
/**
* Validate lease time configuration
*/
export function validateLeaseTimeConfig(config: LeaseTimeConfig): string[] {
const errors: string[] = [];
if (config.poolSize <= 0) {
errors.push('Pool size must be greater than 0');
}
if (config.expectedClients < 0) {
errors.push('Expected clients cannot be negative');
}
if (config.expectedClients > config.poolSize) {
errors.push('Expected clients exceeds pool size - addresses will be exhausted');
}
if (config.churnRate === 'custom') {
if (config.customChurnHours === undefined || config.customChurnHours <= 0) {
errors.push('Custom churn rate must be greater than 0 hours');
}
}
return errors;
}
/**
* Calculate optimal lease time
*/
export function calculateLeaseTime(config: LeaseTimeConfig): LeaseTimeResult {
const errors = validateLeaseTimeConfig(config);
if (errors.length > 0) {
throw new Error(errors.join('; '));
}
// Determine churn hours
const churnHours = config.churnRate === 'custom' ? config.customChurnHours! : CHURN_RATE_HOURS[config.churnRate];
// Calculate base lease time
let leaseSeconds: number;
if (config.networkType && config.networkType !== 'custom') {
// Use network type default as baseline
leaseSeconds = NETWORK_TYPE_DEFAULTS[config.networkType].leaseSeconds;
} else {
// Calculate based on churn and utilization
const utilizationRatio = config.expectedClients / config.poolSize;
if (utilizationRatio < 0.5) {
// Low utilization - can use longer leases
leaseSeconds = Math.min(churnHours * 3600 * 2, 604800); // Up to 7 days
} else if (utilizationRatio < 0.8) {
// Moderate utilization
leaseSeconds = churnHours * 3600;
} else {
// High utilization - shorter leases for faster recycling
leaseSeconds = Math.max(Math.floor(churnHours * 3600 * 0.5), 600); // At least 10 minutes
}
}
// Calculate T1 (renewal time) - typically 50% of lease
const t1Seconds = Math.floor(leaseSeconds * 0.5);
// Calculate T2 (rebinding time) - typically 87.5% of lease
const t2Seconds = Math.floor(leaseSeconds * 0.875);
// Calculate utilization
const utilizationPercent = Math.round((config.expectedClients / config.poolSize) * 100);
// Estimate time to exhaustion
let exhaustionTime: string | null = null;
if (config.expectedClients > config.poolSize) {
exhaustionTime = 'Immediate - not enough addresses';
} else if (utilizationPercent > 90) {
const timeToExhaustion = ((config.poolSize - config.expectedClients) / config.expectedClients) * leaseSeconds;
exhaustionTime = `~${formatTime(Math.floor(timeToExhaustion))} under current load`;
}
// Generate recommendations
const recommendations: string[] = [];
if (utilizationPercent > 90) {
recommendations.push('⚠️ High utilization - consider expanding pool or shortening lease times');
}
if (utilizationPercent < 30) {
recommendations.push('✓ Low utilization - safe to use longer lease times for stability');
}
if (leaseSeconds < 3600) {
recommendations.push('Short lease times increase DHCP server load - ensure server can handle traffic');
}
if (leaseSeconds > 604800) {
recommendations.push('Very long leases may delay address reclamation - ensure adequate pool size');
}
if (config.networkType === 'guest') {
recommendations.push('Guest networks benefit from short leases (1-4 hours) for rapid address recycling');
}
if (config.networkType === 'iot') {
recommendations.push('IoT devices prefer long leases (7-30 days) to minimize network chatter');
}
// Generate config examples
const configExamples = generateConfigExamples(leaseSeconds, t1Seconds, t2Seconds);
return {
recommendedLeaseSeconds: leaseSeconds,
recommendedLeaseFormatted: formatTime(leaseSeconds),
t1RenewalSeconds: t1Seconds,
t1RenewalFormatted: formatTime(t1Seconds),
t2RebindingSeconds: t2Seconds,
t2RebindingFormatted: formatTime(t2Seconds),
utilizationPercent,
exhaustionTime,
recommendations,
configExamples,
};
}
/**
* Generate configuration examples
*/
function generateConfigExamples(
leaseSeconds: number,
t1Seconds: number,
t2Seconds: number,
): {
iscDhcpd: string;
keaDhcp4: string;
} {
const maxLeaseSeconds = leaseSeconds * 2; // Typical max is 2x default
const iscDhcpd = `# ISC DHCPd Lease Configuration
default-lease-time ${leaseSeconds};
max-lease-time ${maxLeaseSeconds};
# Subnet configuration example
subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200;
option routers 192.168.1.1;
option domain-name-servers 192.168.1.1;
default-lease-time ${leaseSeconds};
max-lease-time ${maxLeaseSeconds};
}`;
const keaDhcp4 = `{
"Dhcp4": {
"valid-lifetime": ${leaseSeconds},
"renew-timer": ${t1Seconds},
"rebind-timer": ${t2Seconds},
"subnet4": [
{
"subnet": "192.168.1.0/24",
"pools": [
{
"pool": "192.168.1.100 - 192.168.1.200"
}
],
"option-data": [
{
"name": "routers",
"data": "192.168.1.1"
},
{
"name": "domain-name-servers",
"data": "192.168.1.1"
}
],
"valid-lifetime": ${leaseSeconds}
}
]
}
}`;
return {
iscDhcpd,
keaDhcp4,
};
}
/**
* Example scenarios
*/
export const LEASE_TIME_EXAMPLES: Array<LeaseTimeConfig & { name: string; description: string }> = [
{
name: 'Small Office',
description: '50 devices, stable network',
poolSize: 100,
expectedClients: 50,
churnRate: 'low',
networkType: 'corporate',
},
{
name: 'Guest WiFi',
description: 'High turnover, 200 capacity',
poolSize: 200,
expectedClients: 150,
churnRate: 'high',
networkType: 'guest',
},
{
name: 'IoT Network',
description: '500 sensors, very stable',
poolSize: 600,
expectedClients: 500,
churnRate: 'low',
networkType: 'iot',
},
{
name: 'Home Network',
description: '10-20 devices, mixed types',
poolSize: 50,
expectedClients: 15,
churnRate: 'medium',
networkType: 'residential',
},
{
name: 'Near Capacity',
description: 'Running close to limit',
poolSize: 100,
expectedClients: 95,
churnRate: 'medium',
networkType: 'corporate',
},
{
name: 'Conference WiFi',
description: 'Very high churn, 500 attendees',
poolSize: 600,
expectedClients: 450,
churnRate: 'high',
networkType: 'guest',
},
];
+277
View File
@@ -0,0 +1,277 @@
/**
* DHCP Option 3 - Router/Default Gateway (RFC 2132)
*
* Specifies a list of IP addresses for routers on the client's subnet.
* Routers are listed in order of preference.
*
* Multiple gateways are used for:
* - Redundancy (failover)
* - Load balancing (some clients)
* - Metric-based routing (Windows)
*/
export interface GatewayConfig {
gateways: string[];
subnet?: string; // Optional for validation
}
export interface GatewayResult {
gateways: string[];
hexEncoded: string;
wireFormat: string;
totalLength: number;
configExamples: {
iscDhcpd: string;
keaDhcp4: string;
dnsmasq: string;
};
}
/**
* Validates an IPv4 address
*/
function validateIPv4(ip: string): boolean {
const parts = ip.split('.');
if (parts.length !== 4) return false;
for (const part of parts) {
const num = parseInt(part, 10);
if (isNaN(num) || num < 0 || num > 255 || part !== num.toString()) {
return false;
}
}
return true;
}
/**
* Checks if IP is within subnet
*/
function isInSubnet(ip: string, subnet: string): boolean {
const [network, prefixStr] = subnet.split('/');
const prefix = parseInt(prefixStr, 10);
if (!validateIPv4(network) || isNaN(prefix) || prefix < 0 || prefix > 32) {
return false;
}
const ipNum = ipToNumber(ip);
const networkNum = ipToNumber(network);
const mask = (0xffffffff << (32 - prefix)) >>> 0;
return (ipNum & mask) === (networkNum & mask);
}
/**
* Converts IP address to number
*/
function ipToNumber(ip: string): number {
const parts = ip.split('.').map((p) => parseInt(p, 10));
return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
}
/**
* Converts IPv4 address to hex bytes
*/
function ipv4ToHex(ip: string): string {
const parts = ip.split('.').map((p) => parseInt(p, 10));
return parts.map((p) => p.toString(16).padStart(2, '0')).join('');
}
/**
* Converts hex bytes to IPv4 address
*/
function hexToIpv4(hex: string): string {
const bytes = hex.match(/.{1,2}/g) || [];
return bytes.map((b) => parseInt(b, 16).toString()).join('.');
}
/**
* Formats hex string as wire format (with spaces)
*/
function formatWireFormat(hex: string): string {
return hex.match(/.{1,2}/g)?.join(' ') || '';
}
/**
* Validates gateway configuration
*/
export function validateGatewayConfig(config: GatewayConfig): string[] {
const errors: string[] = [];
if (!config.gateways || config.gateways.length === 0) {
errors.push('At least one gateway must be specified');
return errors;
}
// Filter out empty entries
const validGateways = config.gateways.filter((g) => g.trim());
if (validGateways.length === 0) {
errors.push('At least one gateway must be specified');
return errors;
}
// Validate each gateway
for (let i = 0; i < config.gateways.length; i++) {
const gateway = config.gateways[i];
if (!gateway.trim()) continue;
if (!validateIPv4(gateway)) {
errors.push(`Gateway ${i + 1}: Invalid IPv4 address`);
continue;
}
// Check if gateway is in subnet (if subnet provided)
if (config.subnet && config.subnet.trim()) {
if (!isInSubnet(gateway, config.subnet)) {
errors.push(`Gateway ${i + 1}: Not within subnet ${config.subnet}`);
}
}
}
// Check for duplicates
const seen = new Set<string>();
for (const gateway of validGateways) {
if (seen.has(gateway)) {
errors.push(`Duplicate gateway: ${gateway}`);
}
seen.add(gateway);
}
return errors;
}
/**
* Builds DHCP Option 3 (Router)
*/
export function buildGatewayOption(config: GatewayConfig): GatewayResult {
const errors = validateGatewayConfig(config);
if (errors.length > 0) {
throw new Error(errors.join('; '));
}
const validGateways = config.gateways.filter((g) => g.trim());
let hexEncoded = '';
for (const gateway of validGateways) {
hexEncoded += ipv4ToHex(gateway);
}
return {
gateways: validGateways,
hexEncoded,
wireFormat: formatWireFormat(hexEncoded),
totalLength: hexEncoded.length / 2,
configExamples: generateConfigExamples(validGateways),
};
}
/**
* Decodes DHCP Option 3 from hex
*/
export function decodeGatewayOption(hex: string): GatewayResult {
// Remove spaces and validate hex
const cleanHex = hex.replace(/\s+/g, '');
if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
throw new Error('Invalid hex string');
}
if (cleanHex.length === 0) {
throw new Error('Hex string cannot be empty');
}
if (cleanHex.length % 8 !== 0) {
throw new Error('Hex string must be multiple of 8 characters (4 bytes per IP)');
}
const gateways: string[] = [];
for (let i = 0; i < cleanHex.length; i += 8) {
const ipHex = cleanHex.substring(i, i + 8);
gateways.push(hexToIpv4(ipHex));
}
return {
gateways,
hexEncoded: cleanHex,
wireFormat: formatWireFormat(cleanHex),
totalLength: cleanHex.length / 2,
configExamples: generateConfigExamples(gateways),
};
}
/**
* Generates configuration examples for various DHCP servers
*/
function generateConfigExamples(gateways: string[]): {
iscDhcpd: string;
keaDhcp4: string;
dnsmasq: string;
} {
const gatewayList = gateways.join(', ');
const iscDhcpd = `subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200;
option routers ${gatewayList};
}`;
const keaDhcp4 = `{
"Dhcp4": {
"subnet4": [
{
"subnet": "192.168.1.0/24",
"pools": [
{
"pool": "192.168.1.100 - 192.168.1.200"
}
],
"option-data": [
{
"name": "routers",
"code": 3,
"data": "${gatewayList}"
}
]
}
]
}
}`;
const dnsmasq =
gateways.length === 1
? `dhcp-option=3,${gateways[0]}`
: `# Multiple gateways (order matters)\n${gateways.map((g) => `dhcp-option=3,${g}`).join('\n')}`;
return {
iscDhcpd,
keaDhcp4,
dnsmasq,
};
}
/**
* Example gateway configurations
*/
export const GATEWAY_EXAMPLES = [
{
label: 'Single Gateway',
description: 'Most common setup with one default gateway',
gateways: ['192.168.1.1'],
},
{
label: 'Dual Gateway (Redundancy)',
description: 'Primary and backup gateway for failover',
gateways: ['192.168.1.1', '192.168.1.2'],
},
{
label: 'Multiple Gateways',
description: 'Multiple gateways for load balancing or complex routing',
gateways: ['10.0.1.1', '10.0.1.2', '10.0.1.3'],
},
{
label: 'Enterprise Network',
description: 'Corporate network with redundant gateways',
gateways: ['172.16.0.1', '172.16.0.2'],
subnet: '172.16.0.0/16',
},
];
+271
View File
@@ -0,0 +1,271 @@
/**
* DHCP Option 51 - IP Address Lease Time (RFC 2132)
*
* Specifies the lease time in seconds for the IP address.
* The value is a 32-bit unsigned integer.
*
* Special values:
* - 0xFFFFFFFF: Infinite lease (permanent assignment)
* - Common values: 3600 (1h), 86400 (24h), 604800 (7d)
*/
export interface LeaseTimeConfig {
leaseSeconds: number;
infinite?: boolean;
}
export interface LeaseTimeResult {
leaseSeconds: number;
hexEncoded: string;
wireFormat: string;
totalLength: number;
humanReadable: string;
isInfinite: boolean;
t1RenewalSeconds?: number;
t1RenewalFormatted?: string;
t2RebindingSeconds?: number;
t2RebindingFormatted?: string;
configExamples: {
iscDhcpd: string;
keaDhcp4: string;
dnsmasq: string;
};
}
/**
* Formats time in human-readable format
*/
export function formatTime(seconds: number): string {
if (seconds === 0xffffffff) return 'Infinite';
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
const parts: string[] = [];
if (days > 0) parts.push(`${days} day${days !== 1 ? 's' : ''}`);
if (hours > 0) parts.push(`${hours} hour${hours !== 1 ? 's' : ''}`);
if (minutes > 0) parts.push(`${minutes} minute${minutes !== 1 ? 's' : ''}`);
if (secs > 0 || parts.length === 0) parts.push(`${secs} second${secs !== 1 ? 's' : ''}`);
return parts.join(', ');
}
/**
* Validates lease time configuration
*/
export function validateLeaseTimeConfig(config: LeaseTimeConfig): string[] {
const errors: string[] = [];
if (config.infinite) {
return errors; // Infinite lease is always valid
}
if (config.leaseSeconds < 0) {
errors.push('Lease time cannot be negative');
}
if (config.leaseSeconds > 0xfffffffe) {
errors.push('Lease time exceeds maximum value (use infinite lease instead)');
}
if (config.leaseSeconds > 0 && config.leaseSeconds < 60) {
errors.push('Warning: Lease time less than 60 seconds is unusually short');
}
if (config.leaseSeconds > 31536000) {
// 1 year
errors.push('Warning: Lease time greater than 1 year is unusually long');
}
return errors;
}
/**
* Converts seconds to 32-bit hex (big-endian)
*/
function secondsToHex(seconds: number): string {
const value = seconds >>> 0; // Ensure unsigned 32-bit
return value.toString(16).padStart(8, '0');
}
/**
* Converts hex to seconds (32-bit big-endian)
*/
function hexToSeconds(hex: string): number {
return parseInt(hex, 16) >>> 0; // Ensure unsigned 32-bit
}
/**
* Formats hex string as wire format (with spaces)
*/
function formatWireFormat(hex: string): string {
return hex.match(/.{1,2}/g)?.join(' ') || '';
}
/**
* Builds DHCP Option 51 (Lease Time)
*/
export function buildLeaseTimeOption(config: LeaseTimeConfig): LeaseTimeResult {
const errors = validateLeaseTimeConfig(config);
// Only throw on actual errors, not warnings
const actualErrors = errors.filter((e) => !e.startsWith('Warning:'));
if (actualErrors.length > 0) {
throw new Error(actualErrors.join('; '));
}
const leaseSeconds = config.infinite ? 0xffffffff : config.leaseSeconds;
const hexEncoded = secondsToHex(leaseSeconds);
const isInfinite = leaseSeconds === 0xffffffff;
const result: LeaseTimeResult = {
leaseSeconds,
hexEncoded,
wireFormat: formatWireFormat(hexEncoded),
totalLength: 4,
humanReadable: formatTime(leaseSeconds),
isInfinite,
configExamples: generateConfigExamples(leaseSeconds, isInfinite),
};
// Calculate T1 and T2 if not infinite
if (!isInfinite) {
result.t1RenewalSeconds = Math.floor(leaseSeconds * 0.5);
result.t1RenewalFormatted = formatTime(result.t1RenewalSeconds);
result.t2RebindingSeconds = Math.floor(leaseSeconds * 0.875);
result.t2RebindingFormatted = formatTime(result.t2RebindingSeconds);
}
return result;
}
/**
* Decodes DHCP Option 51 from hex
*/
export function decodeLeaseTimeOption(hex: string): LeaseTimeResult {
// Remove spaces and validate hex
const cleanHex = hex.replace(/\s+/g, '');
if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
throw new Error('Invalid hex string');
}
if (cleanHex.length === 0) {
throw new Error('Hex string cannot be empty');
}
if (cleanHex.length !== 8) {
throw new Error('Hex string must be exactly 8 characters (4 bytes)');
}
const leaseSeconds = hexToSeconds(cleanHex);
const isInfinite = leaseSeconds === 0xffffffff;
const result: LeaseTimeResult = {
leaseSeconds,
hexEncoded: cleanHex.toLowerCase(),
wireFormat: formatWireFormat(cleanHex.toLowerCase()),
totalLength: 4,
humanReadable: formatTime(leaseSeconds),
isInfinite,
configExamples: generateConfigExamples(leaseSeconds, isInfinite),
};
// Calculate T1 and T2 if not infinite
if (!isInfinite) {
result.t1RenewalSeconds = Math.floor(leaseSeconds * 0.5);
result.t1RenewalFormatted = formatTime(result.t1RenewalSeconds);
result.t2RebindingSeconds = Math.floor(leaseSeconds * 0.875);
result.t2RebindingFormatted = formatTime(result.t2RebindingSeconds);
}
return result;
}
/**
* Generates configuration examples
*/
function generateConfigExamples(
leaseSeconds: number,
isInfinite: boolean,
): {
iscDhcpd: string;
keaDhcp4: string;
dnsmasq: string;
} {
const iscDhcpd = isInfinite
? `subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200;
default-lease-time ${leaseSeconds};
max-lease-time ${leaseSeconds};
# Note: Some DHCP servers may not support infinite leases
}`
: `subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200;
default-lease-time ${leaseSeconds};
max-lease-time ${Math.floor(leaseSeconds * 1.5)};
}`;
const keaDhcp4 = isInfinite
? `{
"Dhcp4": {
"subnet4": [
{
"subnet": "192.168.1.0/24",
"pools": [
{
"pool": "192.168.1.100 - 192.168.1.200"
}
],
"valid-lifetime": ${leaseSeconds},
"comment": "Infinite lease - may not be supported"
}
]
}
}`
: `{
"Dhcp4": {
"subnet4": [
{
"subnet": "192.168.1.0/24",
"pools": [
{
"pool": "192.168.1.100 - 192.168.1.200"
}
],
"valid-lifetime": ${leaseSeconds},
"renew-timer": ${Math.floor(leaseSeconds * 0.5)},
"rebind-timer": ${Math.floor(leaseSeconds * 0.875)}
}
]
}
}`;
const dnsmasq = isInfinite
? `# Infinite lease
dhcp-range=192.168.1.100,192.168.1.200,infinite`
: `# Lease time in seconds or with suffix (m/h/d)
dhcp-range=192.168.1.100,192.168.1.200,${leaseSeconds}s`;
return {
iscDhcpd,
keaDhcp4,
dnsmasq,
};
}
/**
* Common lease time presets
*/
export const LEASE_TIME_PRESETS = [
{ label: '1 Hour', seconds: 3600, description: 'Guest networks, high churn' },
{ label: '4 Hours', seconds: 14400, description: 'Coffee shops, public WiFi' },
{ label: '8 Hours', seconds: 28800, description: 'Office workday' },
{ label: '12 Hours', seconds: 43200, description: 'Half day' },
{ label: '24 Hours', seconds: 86400, description: 'Corporate networks (default)' },
{ label: '3 Days', seconds: 259200, description: 'Small offices' },
{ label: '7 Days', seconds: 604800, description: 'IoT devices, stable networks' },
{ label: '30 Days', seconds: 2592000, description: 'Very stable environments' },
{ label: 'Infinite', seconds: 0xffffffff, description: 'Permanent assignment', infinite: true },
];
+389
View File
@@ -0,0 +1,389 @@
/**
* DHCP Options 6 & 15 - DNS Servers and Domain Name (RFC 2132)
*
* Option 6: Domain Name Server - List of DNS servers available to client
* Option 15: Domain Name - Domain name for client resolution
*
* These options work together to provide complete DNS configuration.
*/
export interface DNSConfig {
dnsServers: string[];
domainName?: string;
}
export interface DNSResult {
option6?: {
servers: string[];
hexEncoded: string;
wireFormat: string;
totalLength: number;
};
option15?: {
domain: string;
hexEncoded: string;
wireFormat: string;
totalLength: number;
};
configExamples: {
iscDhcpd: string;
keaDhcp4: string;
dnsmasq: string;
};
}
/**
* Validates an IPv4 address
*/
function validateIPv4(ip: string): boolean {
const parts = ip.split('.');
if (parts.length !== 4) return false;
for (const part of parts) {
const num = parseInt(part, 10);
if (isNaN(num) || num < 0 || num > 255 || part !== num.toString()) {
return false;
}
}
return true;
}
/**
* Validates a domain name (FQDN or hostname)
*/
function validateDomainName(domain: string): boolean {
// Basic domain validation - RFC 1035
if (domain.length === 0 || domain.length > 253) return false;
// Allow FQDN with or without trailing dot
const normalized = domain.endsWith('.') ? domain.slice(0, -1) : domain;
// Check each label
const labels = normalized.split('.');
if (labels.length === 0) return false;
for (const label of labels) {
// Label must be 1-63 characters
if (label.length === 0 || label.length > 63) return false;
// Must start and end with alphanumeric
if (!/^[a-zA-Z0-9]/.test(label) || !/[a-zA-Z0-9]$/.test(label)) return false;
// Can contain alphanumeric and hyphens
if (!/^[a-zA-Z0-9-]+$/.test(label)) return false;
}
return true;
}
/**
* Converts IPv4 address to hex bytes
*/
function ipv4ToHex(ip: string): string {
const parts = ip.split('.').map((p) => parseInt(p, 10));
return parts.map((p) => p.toString(16).padStart(2, '0')).join('');
}
/**
* Converts hex bytes to IPv4 address
*/
function hexToIpv4(hex: string): string {
const bytes = hex.match(/.{1,2}/g) || [];
return bytes.map((b) => parseInt(b, 16).toString()).join('.');
}
/**
* Converts domain name to ASCII hex bytes
*/
function domainToHex(domain: string): string {
// Remove trailing dot if present
const normalized = domain.endsWith('.') ? domain.slice(0, -1) : domain;
// Convert to ASCII hex
return normalized
.split('')
.map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');
}
/**
* Converts hex bytes to domain name
*/
function hexToDomain(hex: string): string {
const bytes = hex.match(/.{1,2}/g) || [];
return bytes.map((b) => String.fromCharCode(parseInt(b, 16))).join('');
}
/**
* Formats hex string as wire format (with spaces)
*/
function formatWireFormat(hex: string): string {
return hex.match(/.{1,2}/g)?.join(' ') || '';
}
/**
* Validates DNS configuration
*/
export function validateDNSConfig(config: DNSConfig): string[] {
const errors: string[] = [];
// Check that at least one option is configured
const hasDNSServers = config.dnsServers && config.dnsServers.some((s) => s.trim());
const hasDomainName = config.domainName && config.domainName.trim();
if (!hasDNSServers && !hasDomainName) {
errors.push('At least one DNS server or domain name must be configured');
}
// Validate DNS servers (Option 6)
if (config.dnsServers) {
for (let i = 0; i < config.dnsServers.length; i++) {
const server = config.dnsServers[i];
if (!server.trim()) continue;
if (!validateIPv4(server)) {
errors.push(`DNS Server ${i + 1}: Invalid IPv4 address`);
}
}
// Check for duplicates
const validServers = config.dnsServers.filter((s) => s.trim());
const seen = new Set<string>();
for (const server of validServers) {
if (seen.has(server)) {
errors.push(`Duplicate DNS server: ${server}`);
}
seen.add(server);
}
}
// Validate domain name (Option 15)
if (config.domainName && config.domainName.trim()) {
if (!validateDomainName(config.domainName.trim())) {
errors.push('Domain Name: Invalid domain name format');
}
}
return errors;
}
/**
* Builds DHCP Options 6 and/or 15
*/
export function buildDNSOptions(config: DNSConfig): DNSResult {
const errors = validateDNSConfig(config);
if (errors.length > 0) {
throw new Error(errors.join('; '));
}
const result: Partial<DNSResult> = {};
// Build Option 6: DNS Servers
if (config.dnsServers && config.dnsServers.length > 0) {
const validServers = config.dnsServers.filter((s) => s.trim());
if (validServers.length > 0) {
let serversHex = '';
for (const server of validServers) {
serversHex += ipv4ToHex(server);
}
result.option6 = {
servers: validServers,
hexEncoded: serversHex,
wireFormat: formatWireFormat(serversHex),
totalLength: serversHex.length / 2,
};
}
}
// Build Option 15: Domain Name
if (config.domainName && config.domainName.trim()) {
const domainInput = config.domainName.trim();
// Remove trailing dot for consistency
const domain = domainInput.endsWith('.') ? domainInput.slice(0, -1) : domainInput;
const domainHex = domainToHex(domain);
result.option15 = {
domain,
hexEncoded: domainHex,
wireFormat: formatWireFormat(domainHex),
totalLength: domainHex.length / 2,
};
}
result.configExamples = generateConfigExamples(result.option6?.servers || [], result.option15?.domain);
return result as DNSResult;
}
/**
* Decodes DHCP Option 6 (DNS Servers) from hex
*/
export function decodeDNSServersOption(hex: string): DNSResult['option6'] {
// Remove spaces and validate hex
const cleanHex = hex.replace(/\s+/g, '');
if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
throw new Error('Invalid hex string');
}
if (cleanHex.length === 0) {
throw new Error('Hex string cannot be empty');
}
if (cleanHex.length % 8 !== 0) {
throw new Error('Hex string must be multiple of 8 characters (4 bytes per IP)');
}
const servers: string[] = [];
for (let i = 0; i < cleanHex.length; i += 8) {
const ipHex = cleanHex.substring(i, i + 8);
servers.push(hexToIpv4(ipHex));
}
return {
servers,
hexEncoded: cleanHex,
wireFormat: formatWireFormat(cleanHex),
totalLength: cleanHex.length / 2,
};
}
/**
* Decodes DHCP Option 15 (Domain Name) from hex
*/
export function decodeDomainNameOption(hex: string): DNSResult['option15'] {
// Remove spaces and validate hex
const cleanHex = hex.replace(/\s+/g, '');
if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
throw new Error('Invalid hex string');
}
if (cleanHex.length === 0) {
throw new Error('Hex string cannot be empty');
}
const domain = hexToDomain(cleanHex);
// Validate decoded domain
if (!validateDomainName(domain)) {
throw new Error('Decoded domain name is invalid');
}
return {
domain,
hexEncoded: cleanHex,
wireFormat: formatWireFormat(cleanHex),
totalLength: cleanHex.length / 2,
};
}
/**
* Generates configuration examples
*/
function generateConfigExamples(
servers: string[],
domain?: string,
): {
iscDhcpd: string;
keaDhcp4: string;
dnsmasq: string;
} {
const hasServers = servers.length > 0;
const hasDomain = domain && domain.trim();
let iscDhcpd = 'subnet 192.168.1.0 netmask 255.255.255.0 {\n range 192.168.1.100 192.168.1.200;\n';
if (hasServers) {
iscDhcpd += ` option domain-name-servers ${servers.join(', ')};\n`;
}
if (hasDomain) {
iscDhcpd += ` option domain-name "${domain}";\n`;
}
iscDhcpd += '}';
const optionData: string[] = [];
if (hasServers) {
optionData.push(` {
"name": "domain-name-servers",
"code": 6,
"data": "${servers.join(', ')}"
}`);
}
if (hasDomain) {
optionData.push(` {
"name": "domain-name",
"code": 15,
"data": "${domain}"
}`);
}
const keaDhcp4 = `{
"Dhcp4": {
"subnet4": [
{
"subnet": "192.168.1.0/24",
"pools": [
{
"pool": "192.168.1.100 - 192.168.1.200"
}
],
"option-data": [
${optionData.join(',\n')}
]
}
]
}
}`;
let dnsmasq = '';
if (hasServers) {
dnsmasq += `dhcp-option=6,${servers.join(',')}\n`;
}
if (hasDomain) {
dnsmasq += `dhcp-option=15,${domain}`;
}
return {
iscDhcpd,
keaDhcp4,
dnsmasq: dnsmasq.trim(),
};
}
/**
* Example DNS configurations
*/
export const DNS_EXAMPLES = [
{
label: 'Google DNS',
description: 'Public DNS servers from Google',
dnsServers: ['8.8.8.8', '8.8.4.4'],
domainName: 'example.com',
},
{
label: 'Cloudflare DNS',
description: 'Fast public DNS from Cloudflare',
dnsServers: ['1.1.1.1', '1.0.0.1'],
domainName: 'example.org',
},
{
label: 'Quad9 DNS',
description: 'Security-focused public DNS',
dnsServers: ['9.9.9.9', '149.112.112.112'],
domainName: 'example.net',
},
{
label: 'Corporate Network',
description: 'Internal DNS servers with company domain',
dnsServers: ['10.0.1.10', '10.0.1.11'],
domainName: 'corp.example.com',
},
{
label: 'Single DNS Server',
description: 'Simple configuration with one DNS server',
dnsServers: ['192.168.1.1'],
domainName: 'home.local',
},
];
+276
View File
@@ -0,0 +1,276 @@
/**
* DHCPv6 Client FQDN Option (RFC 4704)
*
* Option 39: Client FQDN
*
* Allows DHCPv6 clients to exchange FQDN information with servers,
* enabling dynamic DNS updates.
*/
export interface FQDNConfig {
fqdn: string;
serverShouldUpdate: boolean;
serverOverride: boolean;
clientShouldUpdate: boolean;
}
export interface FQDNResult {
flags: {
S: boolean; // Server should update DNS
O: boolean; // Server override
N: boolean; // Client should not update
flagsByte: string;
description: string[];
};
fqdn: string;
hexEncoded: string;
wireFormat: string;
totalLength: number;
breakdown: {
flags: string;
fqdn: string;
};
examples: {
keaDhcp6?: string;
};
}
/**
* Validates FQDN format
*/
function validateFQDN(fqdn: string): boolean {
// Basic FQDN validation - must be valid domain name
// Allow labels with alphanumeric chars and hyphens (not at start/end)
const labelRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
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])?$/;
// Check overall format and length
if (!fqdnRegex.test(fqdn) || fqdn.length > 253) {
return false;
}
// Check each label individually
const labels = fqdn.split('.');
for (const label of labels) {
if (!labelRegex.test(label) || label.length > 63) {
return false;
}
}
return true;
}
/**
* Validates FQDN configuration
*/
export function validateFQDNConfig(config: FQDNConfig): string[] {
const errors: string[] = [];
// Validate FQDN
if (!config.fqdn || !config.fqdn.trim()) {
errors.push('FQDN is required');
} else if (!validateFQDN(config.fqdn)) {
errors.push('Invalid FQDN format');
}
// Validate flags logic
if (config.clientShouldUpdate && config.serverShouldUpdate) {
errors.push('Both client and server cannot be set to update DNS simultaneously');
}
return errors;
}
/**
* 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('');
}
/**
* 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;
}
/**
* Formats hex string as wire format (with spaces)
*/
function formatWireFormat(hex: string): string {
return hex.match(/.{1,2}/g)?.join(' ') || '';
}
/**
* Builds DHCPv6 FQDN option
*/
export function buildFQDNOption(config: FQDNConfig): FQDNResult {
const errors = validateFQDNConfig(config);
if (errors.length > 0) {
throw new Error(errors.join('; '));
}
// Build flags byte
// Bit 0: S (Server should update)
// Bit 1: O (Server override)
// Bit 2: N (Client should NOT update)
let flagsByte = 0;
if (config.serverShouldUpdate) {
flagsByte |= 0b00000001; // Set S bit
}
if (config.serverOverride) {
flagsByte |= 0b00000010; // Set O bit
}
if (!config.clientShouldUpdate) {
flagsByte |= 0b00000100; // Set N bit
}
const flagsHex = flagsByte.toString(16).padStart(2, '0');
// Build FQDN in wire format
const fqdnHex = fqdnToHex(config.fqdn);
// Combine flags + FQDN
const fullHex = flagsHex + fqdnHex;
const flagDescriptions: string[] = [];
if (config.serverShouldUpdate) {
flagDescriptions.push('S=1: Server should perform DNS updates');
} else {
flagDescriptions.push('S=0: Server should not perform DNS updates');
}
if (config.serverOverride) {
flagDescriptions.push('O=1: Server can override client preferences');
} else {
flagDescriptions.push('O=0: Server should honor client preferences');
}
if (!config.clientShouldUpdate) {
flagDescriptions.push('N=1: Client requests server to perform updates');
} else {
flagDescriptions.push('N=0: Client will perform its own updates');
}
const result: FQDNResult = {
flags: {
S: config.serverShouldUpdate,
O: config.serverOverride,
N: !config.clientShouldUpdate,
flagsByte: flagsHex,
description: flagDescriptions,
},
fqdn: config.fqdn,
hexEncoded: fullHex,
wireFormat: formatWireFormat(fullHex),
totalLength: fullHex.length / 2,
breakdown: {
flags: formatWireFormat(flagsHex),
fqdn: formatWireFormat(fqdnHex),
},
examples: generateConfigExamples(config),
};
return result;
}
/**
* Generates Kea DHCPv6 configuration examples
*/
function generateConfigExamples(config: FQDNConfig): {
keaDhcp6?: string;
} {
const keaDhcp6 = `{
"Dhcp6": {
"ddns-send-updates": ${config.serverShouldUpdate},
"ddns-override-no-update": ${config.serverOverride},
"ddns-override-client-update": ${config.serverOverride},
"ddns-replace-client-name": "${config.serverShouldUpdate ? 'always' : 'never'}",
"ddns-qualifying-suffix": "${config.fqdn.split('.').slice(1).join('.')}",
"subnet6": [
{
"subnet": "2001:db8::/64",
"pools": [
{
"pool": "2001:db8::100 - 2001:db8::200"
}
]
}
]
}
}`;
return {
keaDhcp6,
};
}
/**
* Returns a default FQDN configuration
*/
export function getDefaultFQDNConfig(): FQDNConfig {
return {
fqdn: '',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
}
/**
* Example FQDN configurations
*/
export const FQDN_EXAMPLES: Array<FQDNConfig & { label: string; description: string }> = [
{
label: 'Server Updates DNS',
description: 'Server performs all DNS updates',
fqdn: 'client.example.com',
serverShouldUpdate: true,
serverOverride: true,
clientShouldUpdate: false,
},
{
label: 'Client Updates DNS',
description: 'Client performs its own DNS updates',
fqdn: 'workstation.corp.example.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: true,
},
{
label: 'Server with Override',
description: 'Server updates and can override client',
fqdn: 'managed-device.internal.example.com',
serverShouldUpdate: true,
serverOverride: true,
clientShouldUpdate: false,
},
{
label: 'No Updates',
description: 'Neither client nor server updates DNS',
fqdn: 'static.example.org',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
},
];
+416
View File
@@ -0,0 +1,416 @@
/**
* DHCPv6 Prefix Delegation (RFC 8415)
*
* Option 25: Identity Association for Prefix Delegation (IA_PD)
* Option 26: IA Prefix Option
*
* Used for delegating IPv6 prefixes to requesting routers/clients.
*/
export interface PrefixDelegationConfig {
iaid: number; // IA_PD IAID (4 bytes)
t1?: number; // T1 renewal time (seconds)
t2?: number; // T2 rebinding time (seconds)
prefixes: PrefixConfig[];
}
export interface PrefixConfig {
prefix: string; // IPv6 prefix (e.g., "2001:db8::/48")
preferredLifetime?: number; // Preferred lifetime (seconds, 0xFFFFFFFF = infinite)
validLifetime?: number; // Valid lifetime (seconds, 0xFFFFFFFF = infinite)
}
export interface PrefixDelegationResult {
iaid: number;
iaidHex: string;
t1: number;
t1Hex: string;
t1Formatted: string;
t2: number;
t2Hex: string;
t2Formatted: string;
prefixes: Array<{
prefix: string;
prefixLength: number;
preferredLifetime: number;
preferredLifetimeHex: string;
preferredLifetimeFormatted: string;
validLifetime: number;
validLifetimeHex: string;
validLifetimeFormatted: string;
prefixHex: string;
wireFormat: string;
optionLength: number;
}>;
fullHex: string;
fullWireFormat: string;
totalLength: number;
examples: {
keaDhcp6?: string;
};
}
/**
* Validates an IPv6 prefix
*/
function validateIPv6Prefix(prefix: string): boolean {
const parts = prefix.split('/');
if (parts.length !== 2) return false;
const [addr, len] = parts;
const prefixLen = parseInt(len, 10);
if (isNaN(prefixLen) || prefixLen < 0 || prefixLen > 128) return false;
// Basic IPv6 address validation
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 ipv6FullCompressedRegex = /^::$/;
return ipv6Regex.test(addr) || ipv6CompressedRegex.test(addr) || ipv6FullCompressedRegex.test(addr);
}
/**
* Expands IPv6 address to full form
*/
function expandIPv6(ip: string): string {
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'));
return segments.join(':');
}
/**
* Converts IPv6 address to hex bytes (16 bytes)
*/
function ipv6ToHex(ip: string): string {
const expanded = expandIPv6(ip);
return expanded.split(':').join('');
}
/**
* Converts 32-bit number to hex (4 bytes)
*/
function uint32ToHex(value: number): string {
return value.toString(16).padStart(8, '0');
}
/**
* Formats time value to human-readable string
*/
export function formatTime(seconds: number): string {
if (seconds === 0xffffffff) return 'Infinite';
if (seconds === 0) return '0 seconds';
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
const parts: string[] = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (mins > 0) parts.push(`${mins}m`);
if (secs > 0) parts.push(`${secs}s`);
return parts.join(' ') || '0s';
}
/**
* Formats hex string with spaces every 2 characters
*/
function formatWireFormat(hex: string): string {
return hex.match(/.{1,2}/g)?.join(' ') || '';
}
/**
* Validates prefix delegation configuration
*/
export function validatePrefixDelegationConfig(config: PrefixDelegationConfig): string[] {
const errors: string[] = [];
// Validate IAID
if (config.iaid < 0 || config.iaid > 0xffffffff) {
errors.push('IAID must be between 0 and 4294967295');
}
// Validate T1/T2
if (config.t1 !== undefined && (config.t1 < 0 || config.t1 > 0xffffffff)) {
errors.push('T1 must be between 0 and 4294967295');
}
if (config.t2 !== undefined && (config.t2 < 0 || config.t2 > 0xffffffff)) {
errors.push('T2 must be between 0 and 4294967295');
}
if (
config.t1 !== undefined &&
config.t2 !== undefined &&
config.t1 !== 0 &&
config.t2 !== 0 &&
config.t1 > config.t2
) {
errors.push('T1 must be less than or equal to T2');
}
// Validate prefixes
if (!config.prefixes || config.prefixes.length === 0) {
errors.push('At least one prefix must be configured');
} else {
config.prefixes.forEach((prefix, i) => {
if (!validateIPv6Prefix(prefix.prefix)) {
errors.push(`Prefix ${i + 1}: Invalid IPv6 prefix format`);
}
if (
prefix.preferredLifetime !== undefined &&
(prefix.preferredLifetime < 0 || prefix.preferredLifetime > 0xffffffff)
) {
errors.push(`Prefix ${i + 1}: Preferred lifetime must be between 0 and 4294967295`);
}
if (prefix.validLifetime !== undefined && (prefix.validLifetime < 0 || prefix.validLifetime > 0xffffffff)) {
errors.push(`Prefix ${i + 1}: Valid lifetime must be between 0 and 4294967295`);
}
if (
prefix.preferredLifetime !== undefined &&
prefix.validLifetime !== undefined &&
prefix.preferredLifetime !== 0xffffffff &&
prefix.validLifetime !== 0xffffffff &&
prefix.preferredLifetime > prefix.validLifetime
) {
errors.push(`Prefix ${i + 1}: Preferred lifetime must be <= valid lifetime`);
}
});
}
return errors;
}
/**
* Builds DHCPv6 IA_PD option
*/
export function buildPrefixDelegation(config: PrefixDelegationConfig): PrefixDelegationResult {
const errors = validatePrefixDelegationConfig(config);
if (errors.length > 0) {
throw new Error(errors.join('; '));
}
const t1 = config.t1 ?? 0;
const t2 = config.t2 ?? 0;
const iaidHex = uint32ToHex(config.iaid);
const t1Hex = uint32ToHex(t1);
const t2Hex = uint32ToHex(t2);
const prefixes: PrefixDelegationResult['prefixes'] = [];
let prefixesHex = '';
for (const prefix of config.prefixes) {
const [addr, len] = prefix.prefix.split('/');
const prefixLength = parseInt(len, 10);
const preferredLifetime = prefix.preferredLifetime ?? 604800; // 7 days default
const validLifetime = prefix.validLifetime ?? 2592000; // 30 days default
const preferredLifetimeHex = uint32ToHex(preferredLifetime);
const validLifetimeHex = uint32ToHex(validLifetime);
const prefixHex = ipv6ToHex(addr);
// Option 26 format: option-code (2) + option-len (2) + preferred-lifetime (4) + valid-lifetime (4) + prefix-length (1) + prefix (16)
const optionData = preferredLifetimeHex + validLifetimeHex + prefixLength.toString(16).padStart(2, '0') + prefixHex;
const optionLen = (optionData.length / 2).toString(16).padStart(4, '0');
const optionCode = '001a'; // 0x001a = 26
const fullOptionHex = optionCode + optionLen + optionData;
prefixesHex += fullOptionHex;
prefixes.push({
prefix: prefix.prefix,
prefixLength,
preferredLifetime,
preferredLifetimeHex,
preferredLifetimeFormatted: formatTime(preferredLifetime),
validLifetime,
validLifetimeHex,
validLifetimeFormatted: formatTime(validLifetime),
prefixHex,
wireFormat: formatWireFormat(fullOptionHex),
optionLength: fullOptionHex.length / 2,
});
}
// Full IA_PD option: option-code (2) + option-len (2) + IAID (4) + T1 (4) + T2 (4) + IA_PD-options
const iaPdData = iaidHex + t1Hex + t2Hex + prefixesHex;
const iaPdLen = (iaPdData.length / 2).toString(16).padStart(4, '0');
const iaPdCode = '0019'; // 0x0019 = 25
const fullHex = iaPdCode + iaPdLen + iaPdData;
return {
iaid: config.iaid,
iaidHex,
t1,
t1Hex,
t1Formatted: formatTime(t1),
t2,
t2Hex,
t2Formatted: formatTime(t2),
prefixes,
fullHex,
fullWireFormat: formatWireFormat(fullHex),
totalLength: fullHex.length / 2,
examples: generateConfigExamples(config, prefixes),
};
}
/**
* Generates Kea DHCPv6 configuration examples
*/
function generateConfigExamples(
config: PrefixDelegationConfig,
prefixes: PrefixDelegationResult['prefixes'],
): { keaDhcp6?: string } {
const _prefixConfigs = prefixes
.map(
(p) => ` {
"prefix": "${p.prefix.split('/')[0]}",
"prefix-len": ${p.prefixLength},
"delegated-len": ${p.prefixLength},
"preferred-lifetime": ${p.preferredLifetime === 0xffffffff ? 4294967295 : p.preferredLifetime},
"valid-lifetime": ${p.validLifetime === 0xffffffff ? 4294967295 : p.validLifetime}
}`,
)
.join(',\n');
const keaDhcp6 = `{
"Dhcp6": {
"subnet6": [
{
"subnet": "2001:db8::/32",
"pd-pools": [
{
"prefix": "${prefixes[0].prefix.split('/')[0]}",
"prefix-len": ${prefixes[0].prefixLength},
"delegated-len": ${prefixes[0].prefixLength}
}
]${
config.t1 !== undefined || config.t2 !== undefined
? `,
"renew-timer": ${config.t1 ?? 0},
"rebind-timer": ${config.t2 ?? 0}`
: ''
}
}
]
}
}`;
return { keaDhcp6 };
}
/**
* Example configurations
*/
export const PREFIX_DELEGATION_EXAMPLES: Array<{
label: string;
description: string;
config: PrefixDelegationConfig;
}> = [
{
label: 'Home Router /56',
description: 'Typical home router prefix delegation',
config: {
iaid: 1,
t1: 302400, // 3.5 days
t2: 483840, // 5.6 days
prefixes: [
{
prefix: '2001:db8:1000::/56',
preferredLifetime: 604800, // 7 days
validLifetime: 2592000, // 30 days
},
],
},
},
{
label: 'Small Business /48',
description: 'Small business with larger prefix',
config: {
iaid: 100,
t1: 1209600, // 14 days
t2: 1814400, // 21 days
prefixes: [
{
prefix: '2001:db8::/48',
preferredLifetime: 2592000, // 30 days
validLifetime: 7776000, // 90 days
},
],
},
},
{
label: 'ISP Customer /60',
description: 'ISP delegating /60 to customer',
config: {
iaid: 42,
t1: 86400, // 1 day
t2: 138240, // 1.6 days
prefixes: [
{
prefix: '2001:db8:abcd::/60',
preferredLifetime: 172800, // 2 days
validLifetime: 604800, // 7 days
},
],
},
},
{
label: 'Multiple Prefixes',
description: 'Router with multiple delegated prefixes',
config: {
iaid: 1,
prefixes: [
{
prefix: '2001:db8:1::/56',
preferredLifetime: 604800,
validLifetime: 2592000,
},
{
prefix: '2001:db8:2::/56',
preferredLifetime: 604800,
validLifetime: 2592000,
},
],
},
},
];
/**
* Returns default configuration
*/
export function getDefaultPrefixDelegationConfig(): PrefixDelegationConfig {
return {
iaid: 1,
t1: 302400, // 3.5 days
t2: 483840, // 5.6 days
prefixes: [
{
prefix: '2001:db8::/56',
preferredLifetime: 604800, // 7 days
validLifetime: 2592000, // 30 days
},
],
};
}
@@ -0,0 +1,5 @@
<script lang="ts">
import LeaseTimeCalculator from '$lib/components/tools/LeaseTimeCalculator.svelte';
</script>
<LeaseTimeCalculator />
@@ -0,0 +1,17 @@
<script lang="ts">
import DHCPFingerprinting from '$lib/components/tools/DHCPFingerprinting.svelte';
</script>
<svelte:head>
<title>DHCP Fingerprinting Database | IP Calc</title>
<meta
name="description"
content="Identify devices based on their DHCP fingerprints using Parameter Request List (Option 55) and Vendor Class Identifier (Option 60). Search through a comprehensive database of known device signatures."
/>
<meta
name="keywords"
content="dhcp, fingerprinting, device identification, parameter request list, option 55, option 60, vendor class, network discovery, device detection"
/>
</svelte:head>
<DHCPFingerprinting />
@@ -0,0 +1,5 @@
<script lang="ts">
import GatewayOption3 from '$lib/components/tools/GatewayOption3.svelte';
</script>
<GatewayOption3 />
@@ -0,0 +1,5 @@
<script lang="ts">
import LeaseTimeOption51 from '$lib/components/tools/LeaseTimeOption51.svelte';
</script>
<LeaseTimeOption51 />
@@ -0,0 +1,5 @@
<script lang="ts">
import DNSOptions6And15 from '$lib/components/tools/DNSOptions6And15.svelte';
</script>
<DNSOptions6And15 />
@@ -0,0 +1,17 @@
<script lang="ts">
import PrefixDelegation from '$lib/components/tools/PrefixDelegation.svelte';
</script>
<svelte:head>
<title>DHCPv6 Prefix Delegation (IA_PD) - Options 25/26 | IP Calc</title>
<meta
name="description"
content="Build DHCPv6 IA_PD options for delegating IPv6 prefixes to requesting routers. Configure Identity Association for Prefix Delegation (Option 25) with IA Prefix options (Option 26) per RFC 8415."
/>
<meta
name="keywords"
content="dhcpv6, prefix delegation, ia_pd, option 25, option 26, ipv6, rfc 8415, router, prefix, subnet delegation, isp, kea, isc"
/>
</svelte:head>
<PrefixDelegation />
@@ -0,0 +1,17 @@
<script lang="ts">
import DHCPv6FQDN from '$lib/components/tools/DHCPv6FQDN.svelte';
</script>
<svelte:head>
<title>DHCPv6 Client FQDN Option (Option 39) - RFC 4704 | IP Calc</title>
<meta
name="description"
content="Configure DHCPv6 Client FQDN Option (Option 39) for dynamic DNS updates. Build fully qualified domain name options with S, O, and N flags per RFC 4704."
/>
<meta
name="keywords"
content="dhcpv6, fqdn, option 39, client fqdn, dynamic dns, ddns, ipv6, rfc 4704, dns updates, hostname, wire format, kea, isc, flags"
/>
</svelte:head>
<DHCPv6FQDN />
@@ -0,0 +1,171 @@
import { describe, it, expect } from 'vitest';
import {
parseParameterList,
searchFingerprints,
formatParameterListToHex,
formatParameterListDisplay,
} from '$lib/utils/dhcp-fingerprinting';
describe('dhcp-fingerprinting', () => {
describe('parseParameterList', () => {
it('should parse hex format', () => {
const result = parseParameterList('0103060f');
expect(result).toEqual([1, 3, 6, 15]);
});
it('should parse hex with spaces', () => {
const result = parseParameterList('01 03 06 0f');
expect(result).toEqual([1, 3, 6, 15]);
});
it('should parse comma-separated', () => {
const result = parseParameterList('1,3,6,15');
expect(result).toEqual([1, 3, 6, 15]);
});
it('should parse space-separated', () => {
const result = parseParameterList('1 3 6 15');
expect(result).toEqual([1, 3, 6, 15]);
});
it('should parse single number', () => {
const result = parseParameterList('1');
expect(result).toEqual([1]);
});
it('should handle leading zeros in hex', () => {
const result = parseParameterList('010306');
expect(result).toEqual([1, 3, 6]);
});
});
describe('formatParameterListToHex', () => {
it('should format to hex', () => {
const result = formatParameterListToHex([1, 3, 6, 15]);
expect(result).toBe('0103060f');
});
it('should pad single digit hex', () => {
const result = formatParameterListToHex([1, 255]);
expect(result).toBe('01ff');
});
it('should handle empty array', () => {
const result = formatParameterListToHex([]);
expect(result).toBe('');
});
});
describe('formatParameterListDisplay', () => {
it('should format with commas', () => {
const result = formatParameterListDisplay([1, 3, 6, 15]);
expect(result).toBe('1, 3, 6, 15');
});
it('should handle single value', () => {
const result = formatParameterListDisplay([1]);
expect(result).toBe('1');
});
it('should handle empty array', () => {
const result = formatParameterListDisplay([]);
expect(result).toBe('');
});
});
describe('searchFingerprints', () => {
it('should find Windows 10/11 exact match', () => {
const params = [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252];
const matches = searchFingerprints(params);
expect(matches.length).toBeGreaterThan(0);
const win10Match = matches.find((m) => m.fingerprint.id === 'win10');
expect(win10Match).toBeDefined();
expect(win10Match!.matchScore).toBe(100);
});
it('should find macOS match', () => {
const params = [1, 3, 6, 15, 119, 252];
const matches = searchFingerprints(params);
expect(matches.length).toBeGreaterThan(0);
const macMatch = matches.find((m) => m.fingerprint.id === 'macos');
expect(macMatch).toBeDefined();
expect(macMatch!.matchScore).toBe(100);
});
it('should find Android match with vendor class', () => {
const params = [1, 3, 6, 15, 26, 28, 51, 58, 59, 43];
const matches = searchFingerprints(params, 'dhcpcd');
expect(matches.length).toBeGreaterThan(0);
const androidMatch = matches.find((m) => m.fingerprint.id === 'android');
expect(androidMatch).toBeDefined();
expect(androidMatch!.matchedOn).toContain('Vendor Class');
});
it('should find partial match', () => {
const params = [1, 3, 6, 15]; // Subset of many fingerprints
const matches = searchFingerprints(params);
expect(matches.length).toBeGreaterThan(0);
// Should have at least some matches
expect(matches.some((m) => m.matchScore >= 50)).toBe(true);
});
it('should sort by match score', () => {
const params = [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252];
const matches = searchFingerprints(params);
// Verify descending order
for (let i = 1; i < matches.length; i++) {
expect(matches[i - 1].matchScore).toBeGreaterThanOrEqual(matches[i].matchScore);
}
});
it('should not match with very low score', () => {
const params = [99, 98, 97]; // Random options unlikely to match
const matches = searchFingerprints(params);
// Should have very few or no matches
expect(matches.length).toBeLessThan(3);
});
it('should identify Linux dhclient', () => {
const params = [1, 3, 6, 15, 26, 28, 42];
const matches = searchFingerprints(params);
const linuxMatch = matches.find((m) => m.fingerprint.id === 'linux-dhclient');
expect(linuxMatch).toBeDefined();
expect(linuxMatch!.matchScore).toBe(100);
});
it('should handle empty parameter list', () => {
const matches = searchFingerprints([]);
expect(matches).toEqual([]);
});
it('should boost score for vendor class match', () => {
const params = [1, 3, 6]; // Partial match
const matchesWithoutVendor = searchFingerprints(params);
const matchesWithVendor = searchFingerprints(params, 'Cisco');
// Cisco matches should have higher scores when vendor is provided
const ciscoWithVendor = matchesWithVendor.find((m) => m.fingerprint.id === 'cisco-phone');
const ciscoWithoutVendor = matchesWithoutVendor.find((m) => m.fingerprint.id === 'cisco-phone');
if (ciscoWithVendor && ciscoWithoutVendor) {
expect(ciscoWithVendor.matchScore).toBeGreaterThan(ciscoWithoutVendor.matchScore);
}
});
it('should indicate exact match in matchedOn', () => {
const params = [1, 3, 6, 15, 119, 252];
const matches = searchFingerprints(params);
const macMatch = matches.find((m) => m.fingerprint.id === 'macos');
expect(macMatch).toBeDefined();
expect(macMatch!.matchedOn.some((m) => m.includes('Exact'))).toBe(true);
});
});
});
@@ -0,0 +1,223 @@
import { describe, it, expect } from 'vitest';
import {
validateLeaseTimeConfig,
calculateLeaseTime,
formatTime,
type LeaseTimeConfig,
} from '$lib/utils/dhcp-lease-calculator';
describe('dhcp-lease-calculator', () => {
describe('formatTime', () => {
it('should format seconds correctly', () => {
expect(formatTime(30)).toBe('30 seconds');
expect(formatTime(1)).toBe('1 second');
});
it('should format minutes correctly', () => {
expect(formatTime(60)).toBe('1 minute');
expect(formatTime(120)).toBe('2 minutes');
expect(formatTime(90)).toBe('1 minute');
});
it('should format hours correctly', () => {
expect(formatTime(3600)).toBe('1 hour');
expect(formatTime(7200)).toBe('2 hours');
expect(formatTime(3660)).toBe('1 hour, 1 minute');
});
it('should format days correctly', () => {
expect(formatTime(86400)).toBe('1 day');
expect(formatTime(172800)).toBe('2 days');
expect(formatTime(90000)).toBe('1 day, 1 hour');
});
});
describe('validateLeaseTimeConfig', () => {
it('should accept valid configuration', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 50,
churnRate: 'medium',
networkType: 'corporate',
};
expect(validateLeaseTimeConfig(config)).toEqual([]);
});
it('should reject pool size <= 0', () => {
const config: LeaseTimeConfig = {
poolSize: 0,
expectedClients: 50,
churnRate: 'medium',
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Pool size must be greater than 0');
});
it('should reject negative expected clients', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: -10,
churnRate: 'medium',
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Expected clients cannot be negative');
});
it('should warn when expected clients exceeds pool size', () => {
const config: LeaseTimeConfig = {
poolSize: 50,
expectedClients: 100,
churnRate: 'medium',
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('exceeds pool size');
});
it('should require custom churn hours when churn rate is custom', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 50,
churnRate: 'custom',
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Custom churn rate');
});
it('should accept custom churn hours', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 50,
churnRate: 'custom',
customChurnHours: 12,
};
expect(validateLeaseTimeConfig(config)).toEqual([]);
});
});
describe('calculateLeaseTime', () => {
it('should calculate lease time for corporate network', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 50,
churnRate: 'medium',
networkType: 'corporate',
};
const result = calculateLeaseTime(config);
expect(result.recommendedLeaseSeconds).toBe(86400); // 24 hours
expect(result.utilizationPercent).toBe(50);
expect(result.t1RenewalSeconds).toBe(43200); // 50% of lease
expect(result.t2RebindingSeconds).toBe(75600); // 87.5% of lease
});
it('should calculate lease time for guest network', () => {
const config: LeaseTimeConfig = {
poolSize: 200,
expectedClients: 150,
churnRate: 'high',
networkType: 'guest',
};
const result = calculateLeaseTime(config);
expect(result.recommendedLeaseSeconds).toBe(3600); // 1 hour
expect(result.utilizationPercent).toBe(75);
expect(result.t1RenewalSeconds).toBe(1800); // 50% of lease
expect(result.t2RebindingSeconds).toBe(3150); // 87.5% of lease
});
it('should calculate lease time for IoT network', () => {
const config: LeaseTimeConfig = {
poolSize: 600,
expectedClients: 500,
churnRate: 'low',
networkType: 'iot',
};
const result = calculateLeaseTime(config);
expect(result.recommendedLeaseSeconds).toBe(604800); // 7 days
expect(result.utilizationPercent).toBe(83);
});
it('should use custom churn rate when specified', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 50,
churnRate: 'custom',
customChurnHours: 6,
networkType: 'custom',
};
const result = calculateLeaseTime(config);
// Low utilization (50%), should be 2x churn time but capped
expect(result.recommendedLeaseSeconds).toBeGreaterThan(0);
expect(result.utilizationPercent).toBe(50);
});
it('should provide exhaustion warning for high utilization', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 95,
churnRate: 'medium',
networkType: 'corporate',
};
const result = calculateLeaseTime(config);
expect(result.utilizationPercent).toBe(95);
expect(result.exhaustionTime).not.toBeNull();
expect(result.exhaustionTime).toContain('under current load');
});
it('should provide recommendations for high utilization', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 92,
churnRate: 'medium',
networkType: 'corporate',
};
const result = calculateLeaseTime(config);
expect(result.recommendations.length).toBeGreaterThan(0);
expect(result.recommendations.some((r) => r.includes('High utilization'))).toBe(true);
});
it('should provide recommendations for low utilization', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 20,
churnRate: 'medium',
networkType: 'corporate',
};
const result = calculateLeaseTime(config);
expect(result.recommendations.length).toBeGreaterThan(0);
expect(result.recommendations.some((r) => r.includes('Low utilization'))).toBe(true);
});
it('should include config examples', () => {
const config: LeaseTimeConfig = {
poolSize: 100,
expectedClients: 50,
churnRate: 'medium',
networkType: 'corporate',
};
const result = calculateLeaseTime(config);
expect(result.configExamples).toBeDefined();
expect(result.configExamples.iscDhcpd).toContain('default-lease-time');
expect(result.configExamples.keaDhcp4).toContain('valid-lifetime');
});
it('should throw error for invalid configuration', () => {
const config: LeaseTimeConfig = {
poolSize: 0,
expectedClients: 50,
churnRate: 'medium',
};
expect(() => calculateLeaseTime(config)).toThrow();
});
});
});
@@ -0,0 +1,197 @@
import { describe, it, expect } from 'vitest';
import {
validateGatewayConfig,
buildGatewayOption,
decodeGatewayOption,
type GatewayConfig,
} from '$lib/utils/dhcp-option3-gateway';
describe('dhcp-option3-gateway', () => {
describe('validateGatewayConfig', () => {
it('should require at least one gateway', () => {
const config: GatewayConfig = {
gateways: [],
};
const errors = validateGatewayConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('At least one gateway');
});
it('should reject empty gateway entries', () => {
const config: GatewayConfig = {
gateways: ['', ' '],
};
const errors = validateGatewayConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('At least one gateway');
});
it('should validate IPv4 addresses', () => {
const config: GatewayConfig = {
gateways: ['not-an-ip'],
};
const errors = validateGatewayConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Invalid IPv4 address');
});
it('should accept valid IPv4 addresses', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1'],
};
const errors = validateGatewayConfig(config);
expect(errors).toEqual([]);
});
it('should validate gateway is within subnet', () => {
const config: GatewayConfig = {
gateways: ['192.168.2.1'],
subnet: '192.168.1.0/24',
};
const errors = validateGatewayConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Not within subnet');
});
it('should accept gateway within subnet', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1'],
subnet: '192.168.1.0/24',
};
const errors = validateGatewayConfig(config);
expect(errors).toEqual([]);
});
it('should detect duplicate gateways', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1', '192.168.1.1'],
};
const errors = validateGatewayConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Duplicate gateway');
});
it('should skip empty entries during validation', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1', '', '192.168.1.2'],
};
const errors = validateGatewayConfig(config);
expect(errors).toEqual([]);
});
it('should validate multiple gateways', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1', '192.168.1.2', '192.168.1.3'],
};
const errors = validateGatewayConfig(config);
expect(errors).toEqual([]);
});
});
describe('buildGatewayOption', () => {
it('should build option for single gateway', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1'],
};
const result = buildGatewayOption(config);
expect(result.gateways).toEqual(['192.168.1.1']);
expect(result.hexEncoded).toBe('c0a80101');
expect(result.totalLength).toBe(4);
});
it('should build option for multiple gateways', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1', '192.168.1.2'],
};
const result = buildGatewayOption(config);
expect(result.gateways).toEqual(['192.168.1.1', '192.168.1.2']);
expect(result.hexEncoded).toBe('c0a80101c0a80102');
expect(result.totalLength).toBe(8);
});
it('should encode IP addresses correctly', () => {
const config: GatewayConfig = {
gateways: ['10.0.0.1'],
};
const result = buildGatewayOption(config);
expect(result.hexEncoded).toBe('0a000001');
});
it('should format wire format with spaces', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1'],
};
const result = buildGatewayOption(config);
expect(result.wireFormat).toBe('c0 a8 01 01');
});
it('should skip empty gateway entries', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1', '', '192.168.1.2'],
};
const result = buildGatewayOption(config);
expect(result.gateways).toEqual(['192.168.1.1', '192.168.1.2']);
expect(result.totalLength).toBe(8);
});
it('should generate config examples', () => {
const config: GatewayConfig = {
gateways: ['192.168.1.1'],
};
const result = buildGatewayOption(config);
expect(result.configExamples.iscDhcpd).toContain('option routers 192.168.1.1');
expect(result.configExamples.keaDhcp4).toContain('"name": "routers"');
expect(result.configExamples.dnsmasq).toContain('dhcp-option=3,192.168.1.1');
});
it('should throw error for invalid configuration', () => {
const config: GatewayConfig = {
gateways: ['invalid-ip'],
};
expect(() => buildGatewayOption(config)).toThrow();
});
});
describe('decodeGatewayOption', () => {
it('should decode single gateway', () => {
const result = decodeGatewayOption('c0a80101');
expect(result.gateways).toEqual(['192.168.1.1']);
expect(result.totalLength).toBe(4);
});
it('should decode multiple gateways', () => {
const result = decodeGatewayOption('c0a80101c0a80102');
expect(result.gateways).toEqual(['192.168.1.1', '192.168.1.2']);
expect(result.totalLength).toBe(8);
});
it('should handle hex with spaces', () => {
const result = decodeGatewayOption('c0 a8 01 01');
expect(result.gateways).toEqual(['192.168.1.1']);
});
it('should handle uppercase hex', () => {
const result = decodeGatewayOption('C0A80101');
expect(result.gateways).toEqual(['192.168.1.1']);
});
it('should throw error for empty hex', () => {
expect(() => decodeGatewayOption('')).toThrow('empty');
});
it('should throw error for invalid hex characters', () => {
expect(() => decodeGatewayOption('zzzzz')).toThrow('Invalid hex');
});
it('should throw error for incorrect length', () => {
expect(() => decodeGatewayOption('c0a801')).toThrow('multiple of 8');
});
it('should decode and provide config examples', () => {
const result = decodeGatewayOption('c0a80101');
expect(result.configExamples.iscDhcpd).toBeDefined();
expect(result.configExamples.keaDhcp4).toBeDefined();
expect(result.configExamples.dnsmasq).toBeDefined();
});
});
});
@@ -0,0 +1,239 @@
import { describe, it, expect } from 'vitest';
import {
validateLeaseTimeConfig,
buildLeaseTimeOption,
decodeLeaseTimeOption,
formatTime,
type LeaseTimeConfig,
} from '$lib/utils/dhcp-option51-lease-time';
describe('dhcp-option51-lease-time', () => {
describe('formatTime', () => {
it('should format infinite lease', () => {
expect(formatTime(0xffffffff)).toBe('Infinite');
});
it('should format seconds', () => {
expect(formatTime(30)).toBe('30 seconds');
expect(formatTime(1)).toBe('1 second');
});
it('should format minutes', () => {
expect(formatTime(60)).toBe('1 minute');
expect(formatTime(120)).toBe('2 minutes');
});
it('should format hours', () => {
expect(formatTime(3600)).toBe('1 hour');
expect(formatTime(7200)).toBe('2 hours');
});
it('should format days', () => {
expect(formatTime(86400)).toBe('1 day');
expect(formatTime(172800)).toBe('2 days');
});
it('should format combined time', () => {
expect(formatTime(90061)).toBe('1 day, 1 hour, 1 minute, 1 second');
});
});
describe('validateLeaseTimeConfig', () => {
it('should accept infinite lease', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 0,
infinite: true,
};
const errors = validateLeaseTimeConfig(config);
expect(errors).toEqual([]);
});
it('should accept valid lease time', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 86400,
};
const errors = validateLeaseTimeConfig(config);
expect(errors).toEqual([]);
});
it('should reject negative lease time', () => {
const config: LeaseTimeConfig = {
leaseSeconds: -100,
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('cannot be negative');
});
it('should reject lease time exceeding max', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 0xffffffff,
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('exceeds maximum');
});
it('should warn about very short lease', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 30,
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Warning:');
});
it('should warn about very long lease', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 40000000,
};
const errors = validateLeaseTimeConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Warning:');
});
});
describe('buildLeaseTimeOption', () => {
it('should build infinite lease', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 0,
infinite: true,
};
const result = buildLeaseTimeOption(config);
expect(result.leaseSeconds).toBe(0xffffffff);
expect(result.hexEncoded).toBe('ffffffff');
expect(result.isInfinite).toBe(true);
expect(result.humanReadable).toBe('Infinite');
});
it('should build 24 hour lease', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 86400,
};
const result = buildLeaseTimeOption(config);
expect(result.leaseSeconds).toBe(86400);
expect(result.hexEncoded).toBe('00015180');
expect(result.isInfinite).toBe(false);
expect(result.totalLength).toBe(4);
});
it('should calculate T1 renewal time', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 86400,
};
const result = buildLeaseTimeOption(config);
expect(result.t1RenewalSeconds).toBe(43200); // 50%
});
it('should calculate T2 rebinding time', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 86400,
};
const result = buildLeaseTimeOption(config);
expect(result.t2RebindingSeconds).toBe(75600); // 87.5%
});
it('should not calculate T1/T2 for infinite lease', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 0,
infinite: true,
};
const result = buildLeaseTimeOption(config);
expect(result.t1RenewalSeconds).toBeUndefined();
expect(result.t2RebindingSeconds).toBeUndefined();
});
it('should format wire format with spaces', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 3600,
};
const result = buildLeaseTimeOption(config);
expect(result.wireFormat).toBe('00 00 0e 10');
});
it('should generate config examples', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 86400,
};
const result = buildLeaseTimeOption(config);
expect(result.configExamples.iscDhcpd).toContain('default-lease-time');
expect(result.configExamples.keaDhcp4).toContain('valid-lifetime');
expect(result.configExamples.dnsmasq).toContain('dhcp-range');
});
it('should build with warnings but not throw', () => {
const config: LeaseTimeConfig = {
leaseSeconds: 30,
};
expect(() => buildLeaseTimeOption(config)).not.toThrow();
});
it('should throw for invalid config', () => {
const config: LeaseTimeConfig = {
leaseSeconds: -100,
};
expect(() => buildLeaseTimeOption(config)).toThrow();
});
});
describe('decodeLeaseTimeOption', () => {
it('should decode infinite lease', () => {
const result = decodeLeaseTimeOption('ffffffff');
expect(result.leaseSeconds).toBe(0xffffffff);
expect(result.isInfinite).toBe(true);
expect(result.humanReadable).toBe('Infinite');
});
it('should decode 24 hour lease', () => {
const result = decodeLeaseTimeOption('00015180');
expect(result.leaseSeconds).toBe(86400);
expect(result.isInfinite).toBe(false);
});
it('should decode 1 hour lease', () => {
const result = decodeLeaseTimeOption('00000e10');
expect(result.leaseSeconds).toBe(3600);
});
it('should handle hex with spaces', () => {
const result = decodeLeaseTimeOption('00 01 51 80');
expect(result.leaseSeconds).toBe(86400);
});
it('should handle uppercase hex', () => {
const result = decodeLeaseTimeOption('00015180');
expect(result.leaseSeconds).toBe(86400);
});
it('should calculate T1 and T2 for decoded lease', () => {
const result = decodeLeaseTimeOption('00015180');
expect(result.t1RenewalSeconds).toBe(43200);
expect(result.t2RebindingSeconds).toBe(75600);
});
it('should not calculate T1/T2 for infinite lease', () => {
const result = decodeLeaseTimeOption('ffffffff');
expect(result.t1RenewalSeconds).toBeUndefined();
expect(result.t2RebindingSeconds).toBeUndefined();
});
it('should throw error for empty hex', () => {
expect(() => decodeLeaseTimeOption('')).toThrow('empty');
});
it('should throw error for invalid hex', () => {
expect(() => decodeLeaseTimeOption('zzzz')).toThrow('Invalid hex');
});
it('should throw error for incorrect length', () => {
expect(() => decodeLeaseTimeOption('0001')).toThrow('exactly 8 characters');
});
it('should generate config examples for decoded value', () => {
const result = decodeLeaseTimeOption('00015180');
expect(result.configExamples.iscDhcpd).toBeDefined();
expect(result.configExamples.keaDhcp4).toBeDefined();
expect(result.configExamples.dnsmasq).toBeDefined();
});
});
});
@@ -0,0 +1,240 @@
import { describe, it, expect } from 'vitest';
import {
validateDNSConfig,
buildDNSOptions,
decodeDNSServersOption,
decodeDomainNameOption,
type DNSConfig,
} from '$lib/utils/dhcp-options6-15-dns';
describe('dhcp-options6-15-dns', () => {
describe('validateDNSConfig', () => {
it('should require at least one DNS server or domain', () => {
const config: DNSConfig = {
dnsServers: [],
};
const errors = validateDNSConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('At least one DNS server or domain name');
});
it('should validate IPv4 DNS servers', () => {
const config: DNSConfig = {
dnsServers: ['invalid-ip'],
};
const errors = validateDNSConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Invalid IPv4 address');
});
it('should accept valid DNS servers', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8', '8.8.4.4'],
};
const errors = validateDNSConfig(config);
expect(errors).toEqual([]);
});
it('should validate domain name format', () => {
const config: DNSConfig = {
dnsServers: [],
domainName: '-invalid-.com',
};
const errors = validateDNSConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Invalid domain name');
});
it('should accept valid domain names', () => {
const config: DNSConfig = {
dnsServers: [],
domainName: 'example.com',
};
const errors = validateDNSConfig(config);
expect(errors).toEqual([]);
});
it('should accept domain with trailing dot', () => {
const config: DNSConfig = {
dnsServers: [],
domainName: 'example.com.',
};
const errors = validateDNSConfig(config);
expect(errors).toEqual([]);
});
it('should detect duplicate DNS servers', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8', '8.8.8.8'],
};
const errors = validateDNSConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Duplicate');
});
it('should skip empty entries', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8', ''],
domainName: 'example.com',
};
const errors = validateDNSConfig(config);
expect(errors).toEqual([]);
});
});
describe('buildDNSOptions', () => {
it('should build Option 6 for DNS servers', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8'],
};
const result = buildDNSOptions(config);
expect(result.option6).toBeDefined();
expect(result.option6!.servers).toEqual(['8.8.8.8']);
expect(result.option6!.hexEncoded).toBe('08080808');
expect(result.option6!.totalLength).toBe(4);
});
it('should build Option 6 for multiple DNS servers', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8', '8.8.4.4'],
};
const result = buildDNSOptions(config);
expect(result.option6!.servers).toEqual(['8.8.8.8', '8.8.4.4']);
expect(result.option6!.hexEncoded).toBe('0808080808080404');
expect(result.option6!.totalLength).toBe(8);
});
it('should build Option 15 for domain name', () => {
const config: DNSConfig = {
dnsServers: [],
domainName: 'example.com',
};
const result = buildDNSOptions(config);
expect(result.option15).toBeDefined();
expect(result.option15!.domain).toBe('example.com');
expect(result.option15!.hexEncoded).toBe('6578616d706c652e636f6d');
});
it('should build both options when provided', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8'],
domainName: 'example.com',
};
const result = buildDNSOptions(config);
expect(result.option6).toBeDefined();
expect(result.option15).toBeDefined();
});
it('should format wire format with spaces', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8'],
};
const result = buildDNSOptions(config);
expect(result.option6!.wireFormat).toBe('08 08 08 08');
});
it('should skip empty DNS servers', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8', '', '8.8.4.4'],
};
const result = buildDNSOptions(config);
expect(result.option6!.servers).toEqual(['8.8.8.8', '8.8.4.4']);
});
it('should handle domain with trailing dot', () => {
const config: DNSConfig = {
dnsServers: [],
domainName: 'example.com.',
};
const result = buildDNSOptions(config);
expect(result.option15!.domain).toBe('example.com');
});
it('should generate config examples', () => {
const config: DNSConfig = {
dnsServers: ['8.8.8.8'],
domainName: 'example.com',
};
const result = buildDNSOptions(config);
expect(result.configExamples.iscDhcpd).toContain('domain-name-servers');
expect(result.configExamples.iscDhcpd).toContain('domain-name');
expect(result.configExamples.keaDhcp4).toContain('"code": 6');
expect(result.configExamples.keaDhcp4).toContain('"code": 15');
expect(result.configExamples.dnsmasq).toContain('dhcp-option=6');
expect(result.configExamples.dnsmasq).toContain('dhcp-option=15');
});
it('should throw error for invalid config', () => {
const config: DNSConfig = {
dnsServers: ['invalid-ip'],
};
expect(() => buildDNSOptions(config)).toThrow();
});
});
describe('decodeDNSServersOption', () => {
it('should decode single DNS server', () => {
const result = decodeDNSServersOption('08080808');
expect(result!.servers).toEqual(['8.8.8.8']);
expect(result!.totalLength).toBe(4);
});
it('should decode multiple DNS servers', () => {
const result = decodeDNSServersOption('0808080808080404');
expect(result!.servers).toEqual(['8.8.8.8', '8.8.4.4']);
expect(result!.totalLength).toBe(8);
});
it('should handle hex with spaces', () => {
const result = decodeDNSServersOption('08 08 08 08');
expect(result!.servers).toEqual(['8.8.8.8']);
});
it('should handle uppercase hex', () => {
const result = decodeDNSServersOption('08080808');
expect(result!.servers).toEqual(['8.8.8.8']);
});
it('should throw error for empty hex', () => {
expect(() => decodeDNSServersOption('')).toThrow('empty');
});
it('should throw error for invalid hex', () => {
expect(() => decodeDNSServersOption('zzzz')).toThrow('Invalid hex');
});
it('should throw error for incorrect length', () => {
expect(() => decodeDNSServersOption('080808')).toThrow('multiple of 8');
});
});
describe('decodeDomainNameOption', () => {
it('should decode domain name', () => {
const result = decodeDomainNameOption('6578616d706c652e636f6d');
expect(result!.domain).toBe('example.com');
});
it('should handle hex with spaces', () => {
const result = decodeDomainNameOption('65 78 61 6d 70 6c 65 2e 63 6f 6d');
expect(result!.domain).toBe('example.com');
});
it('should handle uppercase hex', () => {
const result = decodeDomainNameOption('6578616D706C652E636F6D');
expect(result!.domain).toBe('example.com');
});
it('should throw error for empty hex', () => {
expect(() => decodeDomainNameOption('')).toThrow('empty');
});
it('should throw error for invalid hex', () => {
expect(() => decodeDomainNameOption('zzzz')).toThrow('Invalid hex');
});
it('should throw error for invalid domain', () => {
// Invalid domain characters
expect(() => decodeDomainNameOption('2d2d2d')).toThrow('invalid');
});
});
});
@@ -0,0 +1,265 @@
import { describe, it, expect } from 'vitest';
import {
validateFQDNConfig,
buildFQDNOption,
getDefaultFQDNConfig,
type FQDNConfig,
} from '$lib/utils/dhcpv6-fqdn-rfc4704';
describe('dhcpv6-fqdn-rfc4704', () => {
describe('validateFQDNConfig', () => {
it('should require FQDN', () => {
const emptyConfig: FQDNConfig = {
fqdn: '',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const errors = validateFQDNConfig(emptyConfig);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('FQDN is required');
});
it('should validate FQDN format', () => {
const invalidConfig: FQDNConfig = {
fqdn: '-invalid-.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const errors = validateFQDNConfig(invalidConfig);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Invalid FQDN format');
});
it('should accept valid FQDNs', () => {
const validConfig: FQDNConfig = {
fqdn: 'client.example.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const errors = validateFQDNConfig(validConfig);
expect(errors).toEqual([]);
});
it('should reject when both client and server should update', () => {
const invalidConfig: FQDNConfig = {
fqdn: 'client.example.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: true,
};
const errors = validateFQDNConfig(invalidConfig);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('Both client and server cannot be set to update');
});
it('should accept single-label domains', () => {
const validConfig: FQDNConfig = {
fqdn: 'localhost',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const errors = validateFQDNConfig(validConfig);
expect(errors).toEqual([]);
});
it('should accept multi-level subdomains', () => {
const validConfig: FQDNConfig = {
fqdn: 'workstation.corp.internal.example.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const errors = validateFQDNConfig(validConfig);
expect(errors).toEqual([]);
});
});
describe('buildFQDNOption', () => {
it('should build FQDN option with server update flag', () => {
const config: FQDNConfig = {
fqdn: 'client.example.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.fqdn).toBe('client.example.com');
expect(result.flags.S).toBe(true);
expect(result.flags.O).toBe(false);
expect(result.flags.N).toBe(true); // N=1 means client should NOT update
});
it('should encode FQDN in DNS wire format', () => {
const config: FQDNConfig = {
fqdn: 'example.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
// Should be: flags(1 byte) + 07(example length) + example + 03(com length) + com + 00(null)
expect(result.hexEncoded).toContain('076578616d706c6503636f6d00');
});
it('should set S flag correctly', () => {
const config: FQDNConfig = {
fqdn: 'test.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.flags.S).toBe(true);
expect(result.flags.flagsByte).toBe('05'); // S=1, N=1 (0b00000101)
});
it('should set O flag correctly', () => {
const config: FQDNConfig = {
fqdn: 'test.com',
serverShouldUpdate: true,
serverOverride: true,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.flags.O).toBe(true);
expect(result.flags.flagsByte).toBe('07'); // S=1, O=1, N=1 (0b00000111)
});
it('should set N flag correctly when client should update', () => {
const config: FQDNConfig = {
fqdn: 'test.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: true,
};
const result = buildFQDNOption(config);
expect(result.flags.N).toBe(false); // N=0 means client WILL update
expect(result.flags.flagsByte).toBe('00'); // All flags = 0
});
it('should generate wire format with spaces', () => {
const config: FQDNConfig = {
fqdn: 'test.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.wireFormat).toContain(' ');
expect(result.wireFormat.split(' ').length).toBeGreaterThan(1);
});
it('should calculate total length correctly', () => {
const config: FQDNConfig = {
fqdn: 'example.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
// 1 byte (flags) + 1 byte (len) + 7 bytes (example) + 1 byte (len) + 3 bytes (com) + 1 byte (null) = 14
expect(result.totalLength).toBe(14);
});
it('should generate Kea configuration example', () => {
const config: FQDNConfig = {
fqdn: 'client.example.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.examples.keaDhcp6).toBeDefined();
expect(result.examples.keaDhcp6).toContain('ddns-send-updates');
expect(result.examples.keaDhcp6).toContain('true');
});
it('should generate Kea config with client updates', () => {
const config: FQDNConfig = {
fqdn: 'client.example.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: true,
};
const result = buildFQDNOption(config);
expect(result.examples.keaDhcp6).toBeDefined();
expect(result.examples.keaDhcp6).toContain('ddns-send-updates');
expect(result.examples.keaDhcp6).toContain('false');
});
it('should provide flag descriptions', () => {
const config: FQDNConfig = {
fqdn: 'test.com',
serverShouldUpdate: true,
serverOverride: true,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.flags.description.length).toBe(3);
expect(result.flags.description[0]).toContain('S=1');
expect(result.flags.description[1]).toContain('O=1');
expect(result.flags.description[2]).toContain('N=1');
});
it('should provide encoding breakdown', () => {
const config: FQDNConfig = {
fqdn: 'test.com',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.breakdown.flags).toBeDefined();
expect(result.breakdown.fqdn).toBeDefined();
});
it('should throw error for invalid configuration', () => {
const invalidConfig: FQDNConfig = {
fqdn: '',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
expect(() => buildFQDNOption(invalidConfig)).toThrow();
});
it('should handle subdomain FQDN correctly', () => {
const config: FQDNConfig = {
fqdn: 'workstation.corp.example.com',
serverShouldUpdate: true,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.fqdn).toBe('workstation.corp.example.com');
expect(result.totalLength).toBeGreaterThan(0);
});
it('should handle single-label domain', () => {
const config: FQDNConfig = {
fqdn: 'localhost',
serverShouldUpdate: false,
serverOverride: false,
clientShouldUpdate: false,
};
const result = buildFQDNOption(config);
expect(result.fqdn).toBe('localhost');
// 1 byte (flags) + 1 byte (len) + 9 bytes (localhost) + 1 byte (null) = 12
expect(result.totalLength).toBe(12);
});
});
describe('getDefaultFQDNConfig', () => {
it('should return default configuration', () => {
const defaultConfig = getDefaultFQDNConfig();
expect(defaultConfig.fqdn).toBe('');
expect(defaultConfig.serverShouldUpdate).toBe(true);
expect(defaultConfig.serverOverride).toBe(false);
expect(defaultConfig.clientShouldUpdate).toBe(false);
});
});
});
@@ -0,0 +1,214 @@
import { describe, it, expect } from 'vitest';
import {
validatePrefixDelegationConfig,
buildPrefixDelegation,
formatTime,
type PrefixDelegationConfig,
} from '$lib/utils/dhcpv6-prefix-delegation';
describe('dhcpv6-prefix-delegation', () => {
describe('validatePrefixDelegationConfig', () => {
it('should validate IAID range', () => {
const config: PrefixDelegationConfig = {
iaid: -1,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const errors = validatePrefixDelegationConfig(config);
expect(errors.length).toBeGreaterThan(0);
expect(errors[0]).toContain('IAID must be between');
});
it('should validate T1/T2 relationship', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
t1: 1000,
t2: 500,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const errors = validatePrefixDelegationConfig(config);
expect(errors.some((e) => e.includes('T1 must be less than'))).toBe(true);
});
it('should require at least one prefix', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [],
};
const errors = validatePrefixDelegationConfig(config);
expect(errors.some((e) => e.includes('At least one prefix'))).toBe(true);
});
it('should validate IPv6 prefix format', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [{ prefix: 'invalid' }],
};
const errors = validatePrefixDelegationConfig(config);
expect(errors.some((e) => e.includes('Invalid IPv6 prefix'))).toBe(true);
});
it('should validate lifetime relationship', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [
{
prefix: '2001:db8::/56',
preferredLifetime: 1000,
validLifetime: 500,
},
],
};
const errors = validatePrefixDelegationConfig(config);
expect(errors.some((e) => e.includes('Preferred lifetime must be'))).toBe(true);
});
it('should accept valid configuration', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
t1: 300,
t2: 500,
prefixes: [
{
prefix: '2001:db8::/56',
preferredLifetime: 600,
validLifetime: 1000,
},
],
};
const errors = validatePrefixDelegationConfig(config);
expect(errors).toEqual([]);
});
});
describe('buildPrefixDelegation', () => {
it('should build basic IA_PD option', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const result = buildPrefixDelegation(config);
expect(result).toBeDefined();
expect(result.iaid).toBe(1);
expect(result.iaidHex).toBe('00000001');
});
it('should handle multiple prefixes', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [{ prefix: '2001:db8:1::/56' }, { prefix: '2001:db8:2::/56' }],
};
const result = buildPrefixDelegation(config);
expect(result.prefixes.length).toBe(2);
});
it('should encode prefix correctly', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [
{
prefix: '2001:db8::/56',
preferredLifetime: 604800,
validLifetime: 2592000,
},
],
};
const result = buildPrefixDelegation(config);
expect(result.prefixes[0].prefixLength).toBe(56);
expect(result.prefixes[0].preferredLifetimeHex).toBe('00093a80');
expect(result.prefixes[0].validLifetimeHex).toBe('00278d00');
});
it('should format T1/T2 correctly', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
t1: 86400,
t2: 138240,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const result = buildPrefixDelegation(config);
expect(result.t1).toBe(86400);
expect(result.t2).toBe(138240);
expect(result.t1Hex).toBe('00015180');
expect(result.t2Hex).toBe('00021c00');
});
it('should generate wire format', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const result = buildPrefixDelegation(config);
expect(result.fullWireFormat).toContain(' ');
expect(result.totalLength).toBeGreaterThan(0);
});
it('should generate Kea config example', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const result = buildPrefixDelegation(config);
expect(result.examples.keaDhcp6).toBeDefined();
expect(result.examples.keaDhcp6).toContain('pd-pools');
});
it('should handle compressed IPv6 addresses', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
prefixes: [{ prefix: '2001:db8::1/64' }],
};
const result = buildPrefixDelegation(config);
expect(result.prefixes[0].prefixLength).toBe(64);
});
it('should handle zero T1/T2', () => {
const config: PrefixDelegationConfig = {
iaid: 1,
t1: 0,
t2: 0,
prefixes: [{ prefix: '2001:db8::/56' }],
};
const result = buildPrefixDelegation(config);
expect(result.t1).toBe(0);
expect(result.t2).toBe(0);
});
it('should throw on invalid config', () => {
const config: PrefixDelegationConfig = {
iaid: -1,
prefixes: [{ prefix: 'invalid' }],
};
expect(() => buildPrefixDelegation(config)).toThrow();
});
});
describe('formatTime', () => {
it('should format infinite time', () => {
expect(formatTime(0xffffffff)).toBe('Infinite');
});
it('should format zero', () => {
expect(formatTime(0)).toBe('0 seconds');
});
it('should format days', () => {
expect(formatTime(86400)).toBe('1d');
});
it('should format complex durations', () => {
const result = formatTime(90061); // 1d 1h 1m 1s
expect(result).toContain('1d');
expect(result).toContain('1h');
expect(result).toContain('1m');
expect(result).toContain('1s');
});
it('should format hours and minutes', () => {
expect(formatTime(3661)).toBe('1h 1m 1s');
});
it('should format only seconds', () => {
expect(formatTime(42)).toBe('42s');
});
});
});