Unit tests for eui64, ip conversions, dnssec, cidr summerization, and made some UI updates

This commit is contained in:
Alicia Sykes committed 2025-09-20 11:55:38 +01:00
1 parent e3636f543a
commit 698951b7d2
17 files changed
+2926 -317

No files matched your search

@@ -113,6 +113,7 @@
align-items: flex-start;
justify-content: space-between;
gap: var(--spacing-sm);
margin: 0 0 var(--spacing-xs) 0;
h3 {
font-size: var(--font-size-lg);
+3 -4
View File
@@ -686,10 +686,6 @@
margin: 0;
}
}
&[open] summary :global(.icon) {
transform: rotate(90deg);
}
}
.examples-list {
@@ -751,6 +747,9 @@
display: grid;
grid-template-columns: 1fr 2fr;
gap: var(--spacing-lg);
.card {
width: 100%;
}
@media (max-width: 768px) {
grid-template-columns: 1fr;
+131 -99
View File
@@ -1,8 +1,10 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import '../../../styles/diagnostics-pages.scss';
let inputValue = $state('');
let selectedExampleIndex = $state<number | null>(null);
let result = $state<{
isValid: boolean;
type: 'ipv4' | 'ipv6' | null;
@@ -441,12 +443,18 @@
}
}
function setTestCase(testCase: { value: string }) {
function setTestCase(testCase: { value: string }, index: number) {
inputValue = testCase.value;
selectedExampleIndex = index;
validateIP(inputValue);
}
function clearExampleSelection() {
selectedExampleIndex = null;
}
function handleInput() {
clearExampleSelection();
validateIP(inputValue);
}
@@ -488,23 +496,29 @@
</section>
<!-- Test Cases -->
<section class="test-cases-section">
<h3>Quick Test Cases</h3>
<div class="test-cases-grid">
{#each testCases as testCase}
<button
class="test-case-button {testCase.valid ? 'valid-example' : 'invalid-example'}"
onclick={() => setTestCase(testCase)}
>
<div class="test-case-label">
<Icon name={testCase.valid ? 'check-circle' : 'x-circle'} size="sm" />
{testCase.label}
</div>
<code class="test-case-value">{testCase.value}</code>
</button>
{/each}
</div>
</section>
<div class="card examples-card">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h4>Quick Test Cases</h4>
</summary>
<div class="examples-grid">
{#each testCases as testCase, index}
<button
class="example-card {testCase.valid ? 'valid-example' : 'invalid-example'}"
class:selected={selectedExampleIndex === index}
onclick={() => setTestCase(testCase, index)}
>
<div class="test-case-label">
<Icon name={testCase.valid ? 'check-circle' : 'x-circle'} size="sm" />
<h5>{testCase.label}</h5>
</div>
<code class="test-case-value">{testCase.value}</code>
</button>
{/each}
</div>
</details>
</div>
<!-- Results -->
{#if result && inputValue.trim()}
@@ -639,33 +653,35 @@
{/if}
<!-- SEO Content -->
<section class="seo-content">
<div class="seo-grid">
<div class="seo-section">
<h3>What is IP Address Validation?</h3>
<section class="about-content">
<div class="about-grid">
<div class="about-section">
<h3>How to Tell if an IP Address is Valid</h3>
<p>
IP address validation ensures that a given string conforms to the correct format for IPv4 or IPv6 addresses.
This tool checks for proper syntax, valid ranges, and common formatting errors to help network administrators
and developers verify IP addresses before use in network configurations.
Valid IP addresses follow specific rules. For IPv4, you need exactly four numbers (0-255) separated by dots,
like 192.168.1.1. For IPv6, you need eight groups of hex digits separated by colons, though you can compress
consecutive zeros with :: (like 2001:db8::1). The validator checks these rules and tells you exactly what's wrong
when something doesn't match.
</p>
</div>
<div class="seo-section">
<h3>Common IP Address Errors</h3>
<ul class="seo-list">
<li><strong>IPv4 Issues:</strong> Octet values over 255, leading zeros, missing octets</li>
<li><strong>IPv6 Issues:</strong> Multiple :: compressions, invalid hex characters, too many groups</li>
<li><strong>Format Problems:</strong> Mixed formats, invalid characters, incorrect separators</li>
</ul>
<div class="about-section">
<h3>What Happens When Addresses Are Invalid</h3>
<p>
Invalid IP addresses cause real problems. Your router might reject them, network connections fail, or software
crashes. Common mistakes include typos like "192.168.1.256" (256 is too big), missing parts like "192.168.1",
or extra zeros like "192.168.01.01". This tool catches these errors before they break your network setup.
</p>
</div>
<div class="seo-section">
<h3>Supported IP Address Types</h3>
<ul class="seo-list">
<li><strong>IPv4:</strong> Standard dotted decimal (192.168.1.1), private ranges, special addresses</li>
<li><strong>IPv6:</strong> Full format, compressed (::), link-local, unique local, multicast</li>
<li><strong>Special Cases:</strong> IPv4-mapped IPv6, zone identifiers, documentation addresses</li>
</ul>
<div class="about-section">
<h3>Why Some Addresses Have Warnings</h3>
<p>
Some valid addresses come with warnings because they have special meanings. For example, addresses ending in
.0 are usually network addresses, and ones ending in .255 are broadcast addresses. Private addresses like
192.168.x.x won't work on the internet. The tool explains what each address type means so you know if it's
right for your use case.
</p>
</div>
</div>
</section>
@@ -726,63 +742,56 @@
font-style: italic;
}
.test-cases-section {
margin-bottom: var(--spacing-xl);
h3 {
color: var(--color-info-light);
margin-bottom: var(--spacing-md);
}
}
.test-cases-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: var(--spacing-sm);
}
.test-case-button {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
padding: var(--spacing-sm) var(--spacing-md);
background-color: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
cursor: pointer;
transition: all var(--transition-fast);
text-align: left;
&:hover {
border-color: var(--color-primary);
transform: translateY(-1px);
}
.example-card {
&.valid-example {
border-left: 3px solid var(--color-success);
&:hover, &.selected {
border-color: var(--color-success) !important;
.test-case-label :global(svg) {
color: var(--color-success);
}
}
}
&.invalid-example {
border-left: 3px solid var(--color-error);
}
}
.test-case-label {
display: flex;
align-items: center;
gap: var(--spacing-xs);
font-weight: 600;
color: var(--text-primary);
font-size: var(--font-size-sm);
&:hover, &.selected {
border-color: var(--color-error) !important;
.test-case-label :global(svg) {
color: var(--color-error);
}
}
}
.test-case-label {
display: flex;
align-items: center;
gap: var(--spacing-xs);
margin-bottom: var(--spacing-xs);
:global(svg) {
transition: color var(--transition-fast);
}
h5 {
margin: 0;
font-weight: 600;
color: var(--text-primary);
font-size: var(--font-size-sm);
}
}
}
.test-case-value {
font-family: var(--font-mono);
font-size: var(--font-size-xs);
color: var(--text-secondary);
background-color: var(--bg-tertiary);
padding: 2px var(--spacing-xs);
border-radius: var(--radius-sm);
margin: 0;
display: block;
}
.results-section {
@@ -796,13 +805,25 @@
padding: var(--spacing-xl);
&.valid {
background-color: var(--color-success);
color: var(--bg-primary);
background: linear-gradient(135deg,
color-mix(in srgb, var(--color-success), transparent 55%),
color-mix(in srgb, var(--color-success), transparent 65%));
border: 1px solid var(--color-success);
color: var(--text-primary);
.details-section {
background: color-mix(in srgb, var(--bg-secondary), transparent 60%);
}
}
&.invalid {
background-color: var(--color-error);
color: var(--bg-primary);
background: linear-gradient(135deg,
color-mix(in srgb, var(--color-error), transparent 55%),
color-mix(in srgb, var(--color-error), transparent 65%));
border: 1px solid var(--color-error);
color: var(--text-primary);
.detail-section, .errors-section {
background: color-mix(in srgb, var(--bg-secondary), transparent 50%);
}
}
}
@@ -839,9 +860,10 @@
display: flex;
align-items: center;
gap: var(--spacing-sm);
background-color: rgba(255, 255, 255, 0.1);
background-color: var(--bg-tertiary);
padding: var(--spacing-sm) var(--spacing-md);
border-radius: var(--radius-md);
border: 1px solid var(--border-primary);
}
.normalized-label {
@@ -854,13 +876,15 @@
font-family: var(--font-mono);
font-size: var(--font-size-md);
font-weight: 600;
background-color: rgba(255, 255, 255, 0.1);
background-color: var(--bg-primary);
padding: 2px var(--spacing-xs);
border-radius: var(--radius-sm);
color: var(--text-primary);
}
.errors-section, .warnings-section, .details-section {
background-color: rgba(255, 255, 255, 0.1);
background-color: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
padding: var(--spacing-lg);
margin-bottom: var(--spacing-md);
@@ -872,6 +896,7 @@
margin: 0 0 var(--spacing-md) 0;
font-size: var(--font-size-md);
font-weight: 600;
color: var(--text-primary);
}
}
@@ -890,6 +915,10 @@
gap: var(--spacing-sm);
font-size: var(--font-size-sm);
line-height: 1.4;
color: var(--text-primary);
}
.info-item {
flex-direction: row;
}
.details-grid {
@@ -911,11 +940,13 @@
opacity: 0.9;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
}
.detail-value {
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--text-primary);
&.private {
color: var(--color-warning-light);
@@ -927,32 +958,33 @@
&.compressed, &.embedded, &.zone {
font-family: var(--font-mono);
background-color: rgba(255, 255, 255, 0.1);
background-color: var(--bg-primary);
padding: 2px var(--spacing-xs);
border-radius: var(--radius-sm);
color: var(--text-primary);
}
}
.info-section {
margin-top: var(--spacing-md);
padding-top: var(--spacing-md);
border-top: 1px solid rgba(255, 255, 255, 0.2);
border-top: 1px solid var(--border-secondary);
h5 {
margin: 0 0 var(--spacing-sm) 0;
font-size: var(--font-size-sm);
font-weight: 600;
opacity: 0.9;
color: var(--text-primary);
}
}
.seo-content {
.about-content {
border-top: 1px solid var(--border-secondary);
padding-top: var(--spacing-xl);
margin-top: var(--spacing-xl);
h3 {
color: var(--color-info-light);
color: var(--color-primary);
margin-bottom: var(--spacing-md);
}
@@ -962,7 +994,7 @@
}
}
.seo-grid {
.about-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: var(--spacing-xl);
@@ -997,7 +1029,7 @@
grid-template-columns: 1fr;
}
.seo-grid {
.about-grid {
grid-template-columns: 1fr;
}
+108 -41
View File
@@ -5,6 +5,7 @@
let inputText = $state('2001:0db8:0000:0000:0000:ff00:0042:8329\n2001:db8:0:0:1:0:0:1\n2001:0db8:0001:0000:0000:0ab9:C0A8:0102\n2001:db8::1\nfe80::1%eth0');
let result = $state<IPv6NormalizeResult | null>(null);
let isLoading = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
function normalizeAddresses() {
if (!inputText.trim()) {
@@ -67,8 +68,18 @@
URL.revokeObjectURL(url);
}
function copyToClipboard(text: string) {
navigator.clipboard.writeText(text);
async function copyToClipboard(text: string, id?: string) {
try {
await navigator.clipboard.writeText(text);
if (id) {
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
}
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function copyAllNormalized() {
@@ -77,7 +88,7 @@
.filter(n => n.isValid)
.map(n => n.normalized)
.join('\n');
copyToClipboard(normalized);
copyToClipboard(normalized, 'copy-all');
}
}
@@ -167,8 +178,11 @@
<div class="normalized-header">
<h3>Normalized Addresses</h3>
<div class="export-buttons">
<button onclick={copyAllNormalized}>
<Icon name="copy" />
<button
onclick={copyAllNormalized}
class:copied={copiedStates['copy-all']}
>
<Icon name={copiedStates['copy-all'] ? 'check' : 'copy'} />
Copy All
</button>
<button onclick={() => exportResults('txt')}>
@@ -176,11 +190,11 @@
Export TXT
</button>
<button onclick={() => exportResults('csv')}>
<Icon name="download" />
<Icon name="csv-file" />
Export CSV
</button>
<button onclick={() => exportResults('json')}>
<Icon name="download" />
<Icon name="json-file" />
Export JSON
</button>
</div>
@@ -189,34 +203,45 @@
<div class="normalizations">
<div class="normalizations-list">
{#each result.normalizations as normalization}
{#each result.normalizations as normalization, index}
<div class="normalization-card" class:valid={normalization.isValid} class:invalid={!normalization.isValid}>
<div class="card-header">
<div class="status">
{#if normalization.isValid}
<Icon name="check-circle" />
{:else}
<Icon name="x-circle" />
{/if}
</div>
<div class="card-content">
<div class="address-info">
<div class="original-address">
<span class="address-label">Original:</span>
<button type="button" class="code-button" onclick={() => copyToClipboard(normalization.input)} title="Click to copy">
<button type="button" class="code-button" onclick={() => copyToClipboard(normalization.input, `original-${index}`)} title="Click to copy">
{normalization.input}
</button>
</div>
{#if normalization.isValid}
<div class="normalized-address">
<span class="address-label">Normalized:</span>
<button type="button" class="code-button normalized" onclick={() => copyToClipboard(normalization.normalized)} title="Click to copy">
{normalization.normalized}
</button>
<div class="normalized-content">
<button type="button" class="code-button normalized" onclick={() => copyToClipboard(normalization.normalized, `normalized-${index}`)} title="Click to copy">
{normalization.normalized}
</button>
<button
type="button"
class="copy-button"
class:copied={copiedStates[`copy-${index}`]}
onclick={() => copyToClipboard(normalization.normalized, `copy-${index}`)}
title="Copy normalized address"
>
<Icon name={copiedStates[`copy-${index}`] ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
{/if}
</div>
<div class="status">
{#if normalization.isValid}
<Icon name="check-circle" />
{:else}
<Icon name="x-circle" />
{/if}
</div>
</div>
{#if normalization.isValid}
@@ -297,7 +322,7 @@
/* Card styles already defined in base.scss */
.card h2 {
color: var(--color-primary);
color: var(--text-primary);
margin: 0 0 var(--spacing-sm) 0;
font-size: var(--font-size-xl);
}
@@ -501,11 +526,16 @@
cursor: pointer;
transition: all var(--transition-fast);
white-space: nowrap;
}
.export-buttons button:hover {
background: var(--color-primary-hover);
transform: translateY(-1px);
&:hover {
background: var(--color-primary-hover);
transform: translateY(-1px);
}
&.copied {
background: var(--color-success);
transform: scale(1.05);
}
}
.normalizations-list {
@@ -519,35 +549,27 @@
border-radius: var(--radius-md);
padding: var(--spacing-md);
background: var(--bg-tertiary);
position: relative;
}
.normalization-card.valid {
border-color: var(--color-success);
border-color: color-mix(in srgb, var(--color-success), transparent 65%);
}
.normalization-card.invalid {
border-color: var(--color-error);
border-color: color-mix(in srgb, var(--color-error), transparent 65%);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: start;
.card-content {
margin-bottom: var(--spacing-md);
}
@media (max-width: 767px) {
.card-header {
flex-direction: column;
gap: var(--spacing-sm);
}
}
.address-info {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
flex: 1;
max-width: 28rem;
}
.original-address,
@@ -557,6 +579,41 @@
gap: var(--spacing-sm);
}
.normalized-content {
display: flex;
align-items: center;
gap: var(--spacing-sm);
flex: 1;
}
.copy-button {
display: flex;
align-items: center;
justify-content: center;
padding: var(--spacing-xs);
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-secondary);
cursor: pointer;
transition: all var(--transition-fast);
flex-shrink: 0;
&:hover {
background: var(--surface-hover);
color: var(--color-primary);
border-color: var(--color-primary);
transform: translateY(-1px);
}
&.copied {
background: var(--color-success);
color: white;
border-color: var(--color-success);
transform: scale(1.05);
}
}
@media (max-width: 767px) {
.original-address,
.normalized-address {
@@ -564,6 +621,11 @@
align-items: stretch;
gap: var(--spacing-xs);
}
.normalized-content {
flex-direction: row;
align-items: center;
}
}
.address-label {
@@ -583,6 +645,7 @@
word-break: break-all;
font-size: var(--font-size-sm);
border: 1px solid var(--border-primary);
flex: 1;
&.normalized {
color: var(--color-success);
@@ -596,8 +659,11 @@
}
.status {
position: absolute;
top: var(--spacing-md);
right: var(--spacing-md);
color: var(--color-success);
margin-left: var(--spacing-sm);
z-index: 1;
}
.normalization-card.invalid .status {
@@ -620,6 +686,7 @@
border-radius: var(--radius-md);
color: var(--color-info);
font-weight: 500;
max-width: 28rem;
}
.applied-rules {
@@ -15,6 +15,7 @@
let outputAddress = $state('');
let conversionError = $state('');
let copiedStates = $state<Record<string, boolean>>({});
let selectedExampleIndex = $state<number | null>(null);
/* Common IPv6 example addresses for testing */
const exampleAddresses = [
@@ -27,8 +28,20 @@
];
/* Set example address */
function setExample(address: string) {
function setExample(address: string, index: number) {
inputAddress = address;
selectedExampleIndex = index;
performConversion();
}
/* Clear example selection when input changes */
function clearExampleSelection() {
selectedExampleIndex = null;
}
/* Handle input change */
function handleInput() {
clearExampleSelection();
performConversion();
}
@@ -89,8 +102,22 @@
<div class="card converter-card">
<header class="card-header">
<h2>{title}</h2>
<p>{description}</p>
<div class="header-content">
<div class="header-text">
<h2>{title}</h2>
<p>{description}</p>
</div>
<div class="header-actions">
<a
href={mode === 'expand' ? '/ip-address-convertor/notation/ipv6-compress' : '/ip-address-convertor/notation/ipv6-expand'}
class="mode-switch-btn"
title="Switch to {mode === 'expand' ? 'Compress' : 'Expand'} mode"
>
<Icon name={mode === 'expand' ? 'ipv6-compress' : 'ipv6-expand'} size="sm" />
<span>{mode === 'expand' ? 'Compress' : 'Expand'}</span>
</a>
</div>
</div>
</header>
<!-- Input Section -->
@@ -110,6 +137,7 @@
id="ipv6-input"
type="text"
bind:value={inputAddress}
oninput={handleInput}
placeholder={mode === 'expand' ? '2001:db8::1' : '2001:0db8:0000:0000:0000:0000:0000:0001'}
class="ipv6-input"
/>
@@ -130,21 +158,27 @@
<!-- Examples Section -->
<div class="examples-section">
<h3>Common Examples</h3>
<div class="examples-grid">
{#each exampleAddresses as example}
<button
type="button"
class="example-btn"
onclick={() => setExample(mode === 'expand' ? example.compressed : example.expanded)}
>
<div class="example-label">{example.label}</div>
<code class="example-address">
{mode === 'expand' ? example.compressed : example.expanded}
</code>
</button>
{/each}
</div>
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h3>Common Examples</h3>
</summary>
<div class="examples-grid">
{#each exampleAddresses as example, index}
<button
type="button"
class="example-btn"
class:selected={selectedExampleIndex === index}
onclick={() => setExample(mode === 'expand' ? example.compressed : example.expanded, index)}
>
<div class="example-label">{example.label}</div>
<code class="example-address">
{mode === 'expand' ? example.compressed : example.expanded}
</code>
</button>
{/each}
</div>
</details>
</div>
<!-- Output Section -->
@@ -217,18 +251,113 @@
max-width: none;
}
.header-content {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: var(--spacing-lg);
}
.header-text {
flex: 1;
}
.header-actions {
display: flex;
flex-shrink: 0;
}
.mode-switch-btn {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-sm) var(--spacing-md);
background-color: var(--bg-secondary);
border: 2px solid var(--border-primary);
border-radius: var(--radius-md);
color: var(--text-primary);
text-decoration: none;
font-weight: 600;
font-size: var(--font-size-sm);
transition: all var(--transition-fast);
&:hover {
background-color: var(--surface-hover);
border-color: var(--color-primary);
color: var(--color-primary);
transform: translateY(-2px);
box-shadow: var(--shadow-sm);
}
&:active {
transform: translateY(0);
}
:global(.icon) {
transition: transform var(--transition-fast);
}
&:hover :global(.icon) {
transform: scale(1.1);
}
}
.converter-section,
.examples-section,
.examples-section,
.output-section {
margin-bottom: var(--spacing-lg);
h3 {
color: var(--color-primary);
/* color: var(--color-primary); */
margin-bottom: var(--spacing-md);
font-size: var(--font-size-lg);
}
}
.examples-section {
.examples-details {
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
background-color: var(--bg-secondary);
transition: all var(--transition-fast);
&[open] {
box-shadow: var(--shadow-sm);
.examples-summary {
border-bottom: 1px solid var(--border-primary);
}
}
}
.examples-summary {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-md);
cursor: pointer;
transition: all var(--transition-fast);
&:hover {
background-color: var(--surface-hover);
}
h3 {
margin: 0;
font-size: var(--font-size-,d);
}
:global(.icon) {
transition: transform var(--transition-fast);
color: var(--color-primary);
}
}
.examples-grid {
padding: var(--spacing-md);
}
}
.converter-section {
display: flex;
flex-direction: column;
@@ -269,18 +398,34 @@
.example-btn {
padding: var(--spacing-sm) var(--spacing-md);
background-color: var(--bg-tertiary);
border: 1px solid var(--border-secondary);
border: 2px solid var(--border-secondary);
border-radius: var(--radius-md);
transition: all var(--transition-fast);
text-align: left;
cursor: pointer;
&:hover {
background-color: var(--surface-hover);
border-color: var(--color-primary);
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
&.selected {
border-color: var(--color-primary);
background-color: color-mix(in srgb, var(--color-primary), transparent 95%);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-primary), transparent 80%);
.example-label {
color: var(--color-primary);
font-weight: 700;
}
.example-address {
color: var(--color-primary);
font-weight: 600;
}
}
}
.example-label {
@@ -463,20 +608,36 @@
}
@media (max-width: 768px) {
.header-content {
flex-direction: column;
align-items: stretch;
gap: var(--spacing-md);
}
.header-actions {
justify-content: center;
}
.mode-switch-btn {
justify-content: center;
padding: var(--spacing-md);
font-size: var(--font-size-md);
}
.examples-grid {
grid-template-columns: 1fr;
}
.stats-grid {
grid-template-columns: 1fr;
}
.address-wrapper {
flex-direction: column;
align-items: stretch;
gap: var(--spacing-md);
}
.input-wrapper {
flex-direction: column;
align-items: stretch;
+223 -113
View File
@@ -5,6 +5,7 @@
let inputText = $state('fe80::1\nfe80::1%eth0\nfe80::1234:5678:90ab:cdef%wlan0\n::1\n2001:db8::1\nff02::1%eth0');
let result = $state<IPv6ZoneResult | null>(null);
let isLoading = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
function processAddresses() {
if (!inputText.trim()) {
@@ -56,8 +57,18 @@
URL.revokeObjectURL(url);
}
function copyToClipboard(text: string) {
navigator.clipboard.writeText(text);
async function copyToClipboard(text: string, id?: string) {
try {
await navigator.clipboard.writeText(text);
if (id) {
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
}
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function getAddressTypeColor(type: string): string {
@@ -187,11 +198,11 @@
<h3>Zone ID Processing</h3>
<div class="export-buttons">
<button onclick={() => exportResults('csv')}>
<Icon name="download" />
<Icon name="csv-file" />
Export CSV
</button>
<button onclick={() => exportResults('json')}>
<Icon name="download" />
<Icon name="json-file" />
Export JSON
</button>
</div>
@@ -200,14 +211,19 @@
<div class="processings-list">
{#each result?.processings || [] as processing}
<div class="processing-card" class:valid={processing.isValid} class:invalid={!processing.isValid}>
<div class="card-header">
<div class="card-header row ">
<div class="address-info">
<div class="original-input">
<span class="input-label">Input:</span>
<div class="input-with-copy">
<code>{processing.input}</code>
<button type="button" onclick={() => copyToClipboard(processing.input)} title="Copy input">
<Icon name="copy" size="xs" />
<button
type="button"
class:copied={copiedStates[`input-${processing.input}`]}
onclick={() => copyToClipboard(processing.input, `input-${processing.input}`)}
title="Copy input"
>
<Icon name={copiedStates[`input-${processing.input}`] ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -229,8 +245,13 @@
<span class="breakdown-label">Address:</span>
<div class="input-with-copy">
<code>{processing.address}</code>
<button type="button" onclick={() => copyToClipboard(processing.address)} title="Copy address">
<Icon name="copy" size="xs" />
<button
type="button"
class:copied={copiedStates[`address-${processing.address}`]}
onclick={() => copyToClipboard(processing.address, `address-${processing.address}`)}
title="Copy address"
>
<Icon name={copiedStates[`address-${processing.address}`] ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -240,8 +261,13 @@
<span class="breakdown-label">Zone ID:</span>
<div class="input-with-copy">
<code>{processing.zoneId}</code>
<button type="button" onclick={() => copyToClipboard(processing.zoneId)} title="Copy zone ID">
<Icon name="copy" size="xs" />
<button
type="button"
class:copied={copiedStates[`zone-${processing.zoneId}`]}
onclick={() => copyToClipboard(processing.zoneId, `zone-${processing.zoneId}`)}
title="Copy zone ID"
>
<Icon name={copiedStates[`zone-${processing.zoneId}`] ? 'check' : 'copy'} size="xs" />
</button>
</div>
{#if processing.processing.zoneIdValid}
@@ -288,8 +314,13 @@
<span class="result-label">With Zone:</span>
<div class="input-with-copy">
<code>{processing.processing.withZone}</code>
<button type="button" onclick={() => copyToClipboard(processing.processing.withZone)} title="Copy with zone">
<Icon name="copy" size="xs" />
<button
type="button"
class:copied={copiedStates[`with-zone-${processing.processing.withZone}`]}
onclick={() => copyToClipboard(processing.processing.withZone, `with-zone-${processing.processing.withZone}`)}
title="Copy with zone"
>
<Icon name={copiedStates[`with-zone-${processing.processing.withZone}`] ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -298,8 +329,13 @@
<span class="result-label">Without Zone:</span>
<div class="input-with-copy">
<code>{processing.processing.withoutZone}</code>
<button type="button" onclick={() => copyToClipboard(processing.processing.withoutZone)} title="Copy without zone">
<Icon name="copy" size="xs" />
<button
type="button"
class:copied={copiedStates[`without-zone-${processing.processing.withoutZone}`]}
onclick={() => copyToClipboard(processing.processing.withoutZone, `without-zone-${processing.processing.withoutZone}`)}
title="Copy without zone"
>
<Icon name={copiedStates[`without-zone-${processing.processing.withoutZone}`] ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -310,9 +346,15 @@
<h4>Suggested Zone Identifiers:</h4>
<div class="zones-list">
{#each processing.processing.suggestedZones as zone}
<button type="button" onclick={() => copyToClipboard(`${processing.address}%${zone}`)} title="Copy full address" class="zone-button">
<button
type="button"
class="zone-button"
class:copied={copiedStates[`suggested-${zone}`]}
onclick={() => copyToClipboard(`${processing.address}%${zone}`, `suggested-${zone}`)}
title="Copy full address"
>
<code>{zone}</code>
<Icon name="copy" size="xs" />
<Icon name={copiedStates[`suggested-${zone}`] ? 'check' : 'copy'} size="xs" />
</button>
{/each}
</div>
@@ -487,8 +529,8 @@
.error-item {
color: var(--color-error);
font-family: 'Courier New', monospace;
font-size: 0.875rem;
font-family: var(--font-mono);
font-size: var(--font-size-sm);
margin-bottom: var(--spacing-xs);
}
@@ -519,22 +561,22 @@
.stat.valid {
background: var(--bg-tertiary);
border: 1px solid var(--color-success);
border: 1px solid color-mix(in srgb, var(--color-success), transparent 65%);
}
.stat.invalid {
background: var(--bg-tertiary);
border: 1px solid var(--color-error);
border: 1px solid color-mix(in srgb, var(--color-error), transparent 65%);
}
.stat.with-zone {
background: var(--bg-tertiary);
border: 1px solid var(--color-info);
border: 1px solid color-mix(in srgb, var(--color-info), transparent 65%);
}
.stat.require-zone {
background: var(--bg-tertiary);
border: 1px solid var(--color-warning);
border: 1px solid color-mix(in srgb, var(--color-warning), transparent 65%);
}
.stat-value {
@@ -553,7 +595,7 @@
}
.stat.with-zone .stat-value {
color: var(--color-primary);
color: var(--color-info);
}
.stat.require-zone .stat-value {
@@ -596,16 +638,17 @@
gap: var(--spacing-xs);
padding: var(--spacing-xs) var(--spacing-sm);
background: var(--color-primary);
color: white;
color: var(--bg-secondary);
border: none;
border-radius: var(--radius-md);
font-size: 0.875rem;
font-size: var(--font-size-sm);
cursor: pointer;
transition: background-color 0.2s;
}
transition: all var(--transition-fast);
.export-buttons button:hover {
background: var(--color-primary-dark);
&:hover {
background: var(--color-primary-hover);
transform: translateY(-1px);
}
}
.processings-list {
@@ -622,12 +665,12 @@
}
.processing-card.valid {
border-color: var(--color-success);
border-color: color-mix(in srgb, var(--color-success), transparent 65%);
background: var(--bg-tertiary);
}
.processing-card.invalid {
border-color: var(--color-error);
border-color: color-mix(in srgb, var(--color-error), transparent 65%);
background: var(--bg-tertiary);
}
@@ -648,12 +691,26 @@
gap: var(--spacing-sm);
}
.input-with-copy {
display: flex;
align-items: center;
gap: var(--spacing-xs);
/* flex: 1; */
/* max-width: 28rem; */
}
@media (max-width: 767px) {
.original-input {
flex-direction: column;
align-items: stretch;
gap: var(--spacing-xs);
}
.input-with-copy {
flex-direction: row;
align-items: center;
}
}
.input-label {
@@ -662,22 +719,56 @@
min-width: 50px;
}
.original-input code {
.input-with-copy code {
background: var(--bg-tertiary);
color: var(--text-primary);
padding: 0.375rem 0.75rem;
border-radius: 0.25rem;
font-family: 'Courier New', monospace;
padding: var(--spacing-xs) var(--spacing-sm);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
cursor: pointer;
transition: background-color 0.2s;
word-break: break-all;
font-size: 0.875rem;
transition: all var(--transition-fast);
font-size: var(--font-size-sm);
flex: 1;
min-width: 0;
overflow-wrap: break-word;
&:hover {
background: var(--surface-hover);
transform: translateY(-1px);
}
}
.original-input code:hover {
background: var(--surface-hover);
.input-with-copy button {
display: flex;
align-items: center;
justify-content: center;
padding: var(--spacing-xs);
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-secondary);
cursor: pointer;
transition: all var(--transition-fast);
flex-shrink: 0;
min-width: 32px;
height: 32px;
&:hover {
background: var(--surface-hover);
color: var(--color-primary);
border-color: var(--color-primary);
transform: translateY(-1px);
}
&.copied {
background: var(--color-success);
color: var(--bg-primary);
border-color: var(--color-success);
transform: scale(1.05);
}
}
.status {
color: var(--color-success);
margin-left: var(--spacing-sm);
@@ -693,9 +784,9 @@
gap: var(--spacing-md);
}
.address-breakdown {
.address-breakdown, .address-info {
padding: var(--spacing-sm);
background: rgba(255, 255, 255, 0.6);
background: var(--bg-secondary);
border-radius: 0.25rem;
}
@@ -725,60 +816,55 @@
font-size: 0.875rem;
}
.breakdown-item code {
background: var(--bg-tertiary);
color: var(--text-primary);
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-family: 'Courier New', monospace;
cursor: pointer;
transition: background-color 0.2s;
font-size: 0.875rem;
}
.breakdown-item code:hover {
background: var(--surface-hover);
.breakdown-item {
.input-with-copy {
flex: 1;
}
}
.no-zone {
color: var(--text-secondary);
font-style: italic;
font-size: 0.875rem;
font-size: var(--font-size-sm);
}
.zone-status {
display: flex;
align-items: center;
gap: 0.25rem;
font-size: 0.75rem;
gap: var(--spacing-xs);
font-size: var(--font-size-xs);
font-weight: 600;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
}
padding: var(--spacing-xs) var(--spacing-sm);
border-radius: var(--radius-sm);
.zone-status.valid {
color: var(--color-success);
background: rgba(5, 150, 105, 0.1);
}
&.valid {
color: var(--color-success);
background: color-mix(in srgb, var(--color-success), transparent 90%);
}
.zone-status.invalid {
color: var(--color-error);
background: rgba(220, 38, 38, 0.1);
&.invalid {
color: var(--color-error);
background: color-mix(in srgb, var(--color-error), transparent 90%);
}
}
.address-classification,
.processing-results {
padding: var(--spacing-sm);
background: rgba(255, 255, 255, 0.6);
border-radius: 0.25rem;
background: color-mix(in srgb, var(--bg-primary), transparent 40%);
border-radius: var(--radius-sm);
}
.classification-item,
.result-item {
display: flex;
justify-content: space-between;
gap: var(--spacing-md);
align-items: center;
margin-bottom: var(--spacing-sm);
.result-label, .classification-label {
min-width: 8rem;
}
}
.classification-item:last-child,
@@ -799,53 +885,54 @@
.result-label {
font-weight: 600;
color: var(--text-secondary);
font-size: 0.875rem;
font-size: var(--font-size-sm);
}
.address-type {
display: flex;
align-items: center;
gap: 0.25rem;
gap: var(--spacing-xs);
font-weight: 600;
font-size: 0.875rem;
font-size: var(--font-size-sm);
}
.zone-requirement {
font-weight: 600;
font-size: 0.875rem;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
}
font-size: var(--font-size-sm);
padding: var(--spacing-xs) var(--spacing-sm);
border-radius: var(--radius-sm);
.zone-requirement.required {
color: var(--color-warning);
background: rgba(217, 119, 6, 0.1);
}
&.required {
color: var(--color-warning);
background: color-mix(in srgb, var(--color-warning), transparent 90%);
}
.zone-requirement.optional {
color: var(--color-success);
background: rgba(5, 150, 105, 0.1);
&.optional {
color: var(--color-success);
background: color-mix(in srgb, var(--color-success), transparent 90%);
}
}
.result-item code {
background: var(--color-primary);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-family: 'Courier New', monospace;
color: var(--bg-primary);
padding: var(--spacing-xs) var(--spacing-sm);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
cursor: pointer;
transition: background-color 0.2s;
font-size: 0.875rem;
}
transition: all var(--transition-fast);
font-size: var(--font-size-sm);
.result-item code:hover {
background: var(--color-primary-dark);
&:hover {
background: var(--color-primary-hover);
transform: translateY(-1px);
}
}
.suggested-zones {
padding: var(--spacing-sm);
background: rgba(255, 255, 255, 0.6);
border-radius: 0.25rem;
background: color-mix(in srgb, var(--bg-primary), transparent 40%);
border-radius: var(--radius-sm);
}
.suggested-zones h4 {
@@ -860,19 +947,42 @@
gap: var(--spacing-xs);
}
.zones-list code {
background: var(--text-secondary);
color: var(--text-primary);
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-family: 'Courier New', monospace;
font-size: 0.75rem;
.zone-button {
display: flex;
align-items: center;
gap: var(--spacing-xs);
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
padding: var(--spacing-xs) var(--spacing-sm);
cursor: pointer;
transition: background-color 0.2s;
transition: all var(--transition-fast);
&:hover {
background: var(--surface-hover);
transform: translateY(-1px);
}
&.copied {
background: var(--color-success);
color: var(--bg-primary);
border-color: var(--color-success);
transform: scale(1.05);
}
code {
background: transparent;
color: var(--text-primary);
padding: 0;
border-radius: 0;
font-family: var(--font-mono);
font-size: var(--font-size-xs);
border: none;
}
}
.zones-list code:hover {
background: var(--surface-hover);
.zone-button.copied code {
color: var(--bg-primary);
}
.zone-warning {
@@ -880,10 +990,10 @@
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-sm);
background: rgba(217, 119, 6, 0.1);
border-radius: 0.25rem;
background: color-mix(in srgb, var(--color-warning), transparent 90%);
border-radius: var(--radius-sm);
color: var(--color-warning);
font-size: 0.875rem;
font-size: var(--font-size-sm);
font-weight: 600;
}
@@ -892,10 +1002,10 @@
align-items: center;
gap: var(--spacing-xs);
color: var(--color-error);
font-size: 0.875rem;
font-size: var(--font-size-sm);
padding: var(--spacing-sm);
background: rgba(255, 255, 255, 0.6);
border-radius: 0.25rem;
background: color-mix(in srgb, var(--bg-primary), transparent 40%);
border-radius: var(--radius-sm);
}
@media (max-width: 767px) {
+19 -13
View File
@@ -32,7 +32,12 @@ function ipv4ToBigInt(ip: string): bigint {
if (parts.length !== 4 || parts.some(p => p < 0 || p > 255)) {
throw new Error('Invalid IPv4 address');
}
return BigInt(parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3]);
return BigInt(
(parts[0] * 256 * 256 * 256) +
(parts[1] * 256 * 256) +
(parts[2] * 256) +
parts[3]
);
}
/* Convert bigint to IPv4 address */
@@ -194,29 +199,30 @@ function rangeToCIDRs(range: IPRange): string[] {
let start = range.start;
const end = range.end;
const maxPrefix = range.version === 4 ? 32 : 128;
while (start <= end) {
// Find the largest block that starts at 'start' and fits in the range
let prefixLength = maxPrefix;
// Find largest block that fits
while (prefixLength > 0) {
const blockSize = 1n << BigInt(maxPrefix - prefixLength);
// Start with the largest possible block (prefix 0) and work down
for (let len = 0; len <= maxPrefix; len++) {
const blockSize = 1n << BigInt(maxPrefix - len);
const blockStart = start & ~(blockSize - 1n);
const blockEnd = blockStart + blockSize - 1n;
if (blockStart === start && blockEnd <= end) {
// Check if this block starts at our current position and fits in range
if (blockStart === start && start + blockSize - 1n <= end) {
prefixLength = len;
break;
}
prefixLength--;
}
const blockSize = 1n << BigInt(maxPrefix - prefixLength);
const ip = range.version === 4 ? bigIntToIPv4(start) : bigIntToIPv6(start);
cidrs.push(`${ip}/${prefixLength}`);
start += blockSize;
}
return cidrs;
}
+48 -8
View File
@@ -79,7 +79,50 @@ function bigIntToIPv6(num: bigint): string {
remaining >>= 16n;
}
return groups.join(':');
let ipv6 = groups.join(':');
// Apply IPv6 compression - replace longest sequence of consecutive zeros
// Find all sequences of consecutive zero groups
const zeroSequences = [];
let currentStart = -1;
for (let i = 0; i < groups.length; i++) {
if (groups[i] === '0') {
if (currentStart === -1) currentStart = i;
} else {
if (currentStart !== -1) {
zeroSequences.push({ start: currentStart, length: i - currentStart });
currentStart = -1;
}
}
}
// Check if there's a trailing sequence
if (currentStart !== -1) {
zeroSequences.push({ start: currentStart, length: groups.length - currentStart });
}
// Find the longest sequence (at least 2 consecutive zeros)
const longestSequence = zeroSequences
.filter(seq => seq.length >= 2)
.sort((a, b) => b.length - a.length)[0];
if (longestSequence) {
const before = groups.slice(0, longestSequence.start).join(':');
const after = groups.slice(longestSequence.start + longestSequence.length).join(':');
if (before && after) {
ipv6 = `${before}::${after}`;
} else if (before) {
ipv6 = `${before}::`;
} else if (after) {
ipv6 = `::${after}`;
} else {
ipv6 = '::';
}
}
return ipv6;
}
function detectIPVersion(ip: string): 4 | 6 {
@@ -150,14 +193,11 @@ function calculateIPDistance(
const endNum = ipToNumber(endIP, startVersion);
let distance = endNum > startNum ? endNum - startNum : startNum - endNum;
const direction: 'forward' | 'backward' = endNum > startNum ? 'forward' : 'backward';
const direction: 'forward' | 'backward' = endNum >= startNum ? 'forward' : 'backward';
// Adjust for inclusive/exclusive counting
if (inclusive && distance > 0n) {
if (inclusive) {
distance += 1n;
} else if (!inclusive && distance === 0n) {
// Same IP address, distance is 0 for exclusive, 1 for inclusive
distance = 0n;
}
const intermediateAddresses = showIntermediates && distance > 1n
@@ -196,8 +236,8 @@ function calculateIPDistance(
function parseIPPair(input: string): { startIP: string; endIP: string } {
const trimmed = input.trim();
// Try different separators
const separators = ['->', '<->', '→', '↔', '-', '|', ',', ' '];
// Try different separators - order matters! Longer separators first
const separators = ['<->', '->', '↔', '→', '-', '|', ','];
for (const sep of separators) {
if (trimmed.includes(sep)) {
+53 -6
View File
@@ -30,20 +30,67 @@ export function validateIPv6(ip: string): { valid: boolean; error?: string } {
// Remove brackets if present
const cleanIp = ip.replace(/^\[|\]$/g, '');
// Check for invalid patterns first
if (cleanIp.includes(':::') || cleanIp.startsWith(':') && !cleanIp.startsWith('::') ||
cleanIp.endsWith(':') && !cleanIp.endsWith('::')) {
return { valid: false, error: 'Invalid IPv6 format' };
}
// Check for IPv4-mapped IPv6 (::ffff:192.0.2.1)
const ipv4MappedRegex = /^::ffff:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
if (ipv4MappedRegex.test(cleanIp)) {
return { valid: true };
}
// Check for standard IPv6
const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$|^(?:[0-9a-fA-F]{1,4}:)*::[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4})*$|^(?:[0-9a-fA-F]{1,4}:)*::[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4})*$|^[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:)*::[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4})*$/;
if (!ipv6Regex.test(cleanIp)) {
// More flexible IPv6 validation
try {
// Simple but effective validation approach
if (cleanIp === '::' || cleanIp === '::1') {
return { valid: true };
}
// Split on :: to handle compression
const parts = cleanIp.split('::');
if (parts.length > 2) {
return { valid: false, error: 'Invalid IPv6 format' };
}
if (parts.length === 2) {
// Has compression
const leftParts = parts[0] ? parts[0].split(':') : [];
const rightParts = parts[1] ? parts[1].split(':') : [];
// Check total parts don't exceed 8
if (leftParts.length + rightParts.length >= 8) {
return { valid: false, error: 'Invalid IPv6 format' };
}
// Validate each part
const allParts = [...leftParts, ...rightParts];
for (const part of allParts) {
if (part && !/^[0-9a-fA-F]{1,4}$/.test(part)) {
return { valid: false, error: 'Invalid IPv6 format' };
}
}
} else {
// No compression, must have exactly 8 parts
const ipParts = cleanIp.split(':');
if (ipParts.length !== 8) {
return { valid: false, error: 'Invalid IPv6 format' };
}
// Validate each part
for (const part of ipParts) {
if (!/^[0-9a-fA-F]{1,4}$/.test(part)) {
return { valid: false, error: 'Invalid IPv6 format' };
}
}
}
return { valid: true };
} catch (error) {
return { valid: false, error: 'Invalid IPv6 format' };
}
return { valid: true };
}
/**
+503 -6
View File
@@ -1,7 +1,49 @@
import type { ValidationResult } from '../types/ip.js';
// Extended interfaces for comprehensive IP validation
export interface IPValidationResult {
isValid: boolean;
type: 'ipv4' | 'ipv6' | null;
errors: string[];
warnings: string[];
details: {
normalizedForm?: string;
addressType?: string;
scope?: string;
isPrivate?: boolean;
isReserved?: boolean;
info?: string[];
compressedForm?: string;
embeddedIPv4?: string;
zoneId?: string;
hasEmbeddedIPv4?: boolean;
};
}
export interface IPTestCase {
label: string;
value: string;
valid: boolean;
}
interface DetailedValidationResponse {
isValid: boolean;
errors: string[];
warnings: string[];
details: any;
}
export const DEFAULT_TEST_CASES: IPTestCase[] = [
{ label: 'Valid IPv4', value: '192.168.1.1', valid: true },
{ label: 'Valid IPv6', value: '2001:db8::1', valid: true },
{ label: 'IPv4 with leading zeros', value: '192.168.001.001', valid: false },
{ label: 'IPv4 octet too large', value: '192.168.1.256', valid: false },
{ label: 'IPv6 with multiple ::', value: '2001::db8::1', valid: false },
{ label: 'IPv6 too many groups', value: '2001:db8:85a3:0000:0000:8a2e:0370:7334:extra', valid: false }
];
/**
* Validates an IPv4 address string
* Simple IPv4 validation (backward compatibility)
*/
export function validateIPv4(ip: string): ValidationResult {
if (!ip || typeof ip !== 'string') {
@@ -9,24 +51,24 @@ export function validateIPv4(ip: string): ValidationResult {
}
const octets = ip.trim().split('.');
if (octets.length !== 4) {
return { valid: false, error: 'IPv4 address must have 4 octets' };
}
for (let i = 0; i < octets.length; i++) {
const octet = octets[i];
if (!/^\d+$/.test(octet)) {
return { valid: false, error: `Octet ${i + 1} contains non-numeric characters` };
}
const num = parseInt(octet, 10);
if (num < 0 || num > 255) {
return { valid: false, error: `Octet ${i + 1} must be between 0-255` };
}
if (octet.length > 1 && octet[0] === '0') {
return { valid: false, error: `Octet ${i + 1} has leading zeros` };
}
@@ -35,6 +77,461 @@ export function validateIPv4(ip: string): ValidationResult {
return { valid: true };
}
/**
* Comprehensive IPv4 validation with detailed analysis
*/
export function validateIPv4Detailed(ip: string): DetailedValidationResponse {
const errors: string[] = [];
const warnings: string[] = [];
const details: any = { info: [] };
// Check basic format
if (!ip.includes('.')) {
errors.push('IPv4 addresses must contain dots (.) to separate octets');
return { isValid: false, errors, warnings, details };
}
const parts = ip.split('.');
// Check number of octets
if (parts.length !== 4) {
errors.push(`IPv4 addresses must have exactly 4 octets, found ${parts.length}`);
return { isValid: false, errors, warnings, details };
}
const octets: number[] = [];
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const octetNum = i + 1;
// Check if empty
if (part === '') {
errors.push(`Octet ${octetNum} is empty`);
continue;
}
// Check for non-numeric characters
if (!/^\d+$/.test(part)) {
errors.push(`Octet ${octetNum} contains non-numeric characters: "${part}"`);
continue;
}
// Check for leading zeros (except for single zero)
if (part.length > 1 && part[0] === '0') {
errors.push(`Octet ${octetNum} has leading zeros: "${part}" (should be "${parseInt(part)})")`);
continue;
}
// Parse and validate range
const value = parseInt(part, 10);
if (isNaN(value)) {
errors.push(`Octet ${octetNum} is not a valid number: "${part}"`);
continue;
}
if (value < 0 || value > 255) {
errors.push(`Octet ${octetNum} out of range: ${value} (must be 0-255)`);
continue;
}
octets.push(value);
}
if (errors.length > 0) {
return { isValid: false, errors, warnings, details };
}
// Additional analysis for valid IPs
const [a, b, c, d] = octets;
details.normalizedForm = `${a}.${b}.${c}.${d}`;
// Determine address type and scope
if (a === 127) {
details.addressType = 'Loopback';
details.scope = 'Host';
details.info.push('Used for local loopback communications');
} else if (a === 10) {
details.addressType = 'Private (Class A)';
details.scope = 'Private Network';
details.isPrivate = true;
details.info.push('RFC 1918 private address space');
} else if (a === 172 && b >= 16 && b <= 31) {
details.addressType = 'Private (Class B)';
details.scope = 'Private Network';
details.isPrivate = true;
details.info.push('RFC 1918 private address space');
} else if (a === 192 && b === 168) {
details.addressType = 'Private (Class C)';
details.scope = 'Private Network';
details.isPrivate = true;
details.info.push('RFC 1918 private address space');
} else if (a === 169 && b === 254) {
details.addressType = 'Link-Local (APIPA)';
details.scope = 'Link-Local';
details.isReserved = true;
details.info.push('Automatic Private IP Addressing');
} else if (a >= 224 && a <= 239) {
details.addressType = 'Multicast (Class D)';
details.scope = 'Multicast';
details.isReserved = true;
details.info.push('Used for multicast communications');
} else if (a >= 240) {
details.addressType = 'Reserved (Class E)';
details.scope = 'Reserved';
details.isReserved = true;
details.info.push('Reserved for future use');
} else if (a === 0) {
details.addressType = 'Network Address';
details.scope = 'Special Use';
details.isReserved = true;
details.info.push('"This network" address');
} else if (d === 0) {
details.addressType = 'Network Address';
details.scope = 'Network';
warnings.push('This appears to be a network address (host portion is 0)');
} else if (d === 255) {
details.addressType = 'Broadcast Address';
details.scope = 'Network';
warnings.push('This appears to be a broadcast address (host portion is all 1s)');
} else {
details.addressType = 'Public';
details.scope = 'Internet';
details.isPrivate = false;
details.info.push('Publicly routable address');
}
return { isValid: true, errors: [], warnings, details };
}
/**
* Comprehensive IPv6 validation with detailed analysis
*/
export function validateIPv6Detailed(ip: string): DetailedValidationResponse {
const errors: string[] = [];
const warnings: string[] = [];
const details: any = { info: [] };
// Check for zone ID (remove it for validation but note it)
let cleanIP = ip;
let zoneId = '';
if (ip.includes('%')) {
const parts = ip.split('%');
if (parts.length > 2) {
errors.push('Multiple % symbols found - invalid zone ID format');
return { isValid: false, errors, warnings, details };
}
cleanIP = parts[0];
zoneId = parts[1];
details.zoneId = zoneId;
details.info.push(`Zone ID specified: %${zoneId}`);
}
// Check for :: (compression)
const doubleColonCount = (cleanIP.match(/::/g) || []).length;
if (doubleColonCount > 1) {
errors.push('Multiple :: sequences found - only one :: allowed per address');
return { isValid: false, errors, warnings, details };
}
// Handle :: expansion
let expandedIP = cleanIP;
if (cleanIP.includes('::')) {
const parts = cleanIP.split('::');
if (parts.length > 2) {
errors.push('Invalid :: usage - malformed compression');
return { isValid: false, errors, warnings, details };
}
const leftParts = parts[0] ? parts[0].split(':') : [];
const rightParts = parts[1] ? parts[1].split(':') : [];
// Calculate how many groups to insert
const totalParts = leftParts.length + rightParts.length;
const missingGroups = 8 - totalParts;
if (missingGroups < 0) {
errors.push('Too many groups in compressed IPv6 address');
return { isValid: false, errors, warnings, details };
}
const middleParts = Array(missingGroups).fill('0000');
const allParts = [...leftParts, ...middleParts, ...rightParts];
expandedIP = allParts.join(':');
}
// Check for embedded IPv4
const ipv4Pattern = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
const ipv4Match = expandedIP.match(ipv4Pattern);
if (ipv4Match) {
// Validate the IPv4 part
const ipv4Part = ipv4Match[0];
const ipv4Result = validateIPv4Detailed(ipv4Part);
if (!ipv4Result.isValid) {
errors.push(`Invalid embedded IPv4 address: ${ipv4Result.errors.join(', ')}`);
return { isValid: false, errors, warnings, details };
}
// Convert IPv4 to two IPv6 groups
const [, a, b, c, d] = ipv4Match;
const group1 = ((parseInt(a) << 8) + parseInt(b)).toString(16).padStart(4, '0');
const group2 = ((parseInt(c) << 8) + parseInt(d)).toString(16).padStart(4, '0');
expandedIP = expandedIP.replace(ipv4Pattern, `${group1}:${group2}`);
details.hasEmbeddedIPv4 = true;
details.embeddedIPv4 = ipv4Part;
details.info.push(`Contains embedded IPv4 address: ${ipv4Part}`);
}
// Split into groups and validate
const groups = expandedIP.split(':');
if (groups.length !== 8) {
if (!cleanIP.includes('::')) {
errors.push(`IPv6 addresses must have 8 groups, found ${groups.length} (use :: for compression)`);
} else {
errors.push(`Invalid IPv6 compression - results in ${groups.length} groups instead of 8`);
}
return { isValid: false, errors, warnings, details };
}
// Validate each group
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
const groupNum = i + 1;
if (group === '') {
errors.push(`Group ${groupNum} is empty`);
continue;
}
if (group.length > 4) {
errors.push(`Group ${groupNum} too long: "${group}" (max 4 hex digits)`);
continue;
}
if (!/^[0-9a-fA-F]+$/.test(group)) {
errors.push(`Group ${groupNum} contains invalid characters: "${group}" (only 0-9, a-f, A-F allowed)`);
continue;
}
}
if (errors.length > 0) {
return { isValid: false, errors, warnings, details };
}
// Normalize the address
const normalizedGroups = groups.map(group => group.toLowerCase().padStart(4, '0'));
const fullForm = normalizedGroups.join(':');
details.normalizedForm = fullForm;
// Analyze address type
const firstGroup = normalizedGroups[0];
const firstTwoGroups = normalizedGroups.slice(0, 2).join(':');
if (fullForm === '0000:0000:0000:0000:0000:0000:0000:0001') {
details.addressType = 'Loopback';
details.scope = 'Host';
details.info.push('IPv6 loopback address (::1)');
} else if (fullForm === '0000:0000:0000:0000:0000:0000:0000:0000') {
details.addressType = 'Unspecified';
details.scope = 'Special Use';
details.info.push('IPv6 unspecified address (::)');
} else if (firstGroup === 'fe80') {
details.addressType = 'Link-Local';
details.scope = 'Link-Local';
details.info.push('IPv6 link-local address');
} else if (firstGroup === 'fec0') {
details.addressType = 'Site-Local (Deprecated)';
details.scope = 'Site-Local';
details.info.push('Deprecated site-local address');
warnings.push('Site-local addresses are deprecated (RFC 3879)');
} else if (firstTwoGroups === 'fc00' || firstTwoGroups === 'fd00') {
details.addressType = 'Unique Local';
details.scope = 'Private Network';
details.isPrivate = true;
details.info.push('RFC 4193 Unique Local Address');
} else if (firstGroup.startsWith('ff')) {
details.addressType = 'Multicast';
details.scope = 'Multicast';
details.info.push('IPv6 multicast address');
} else if (firstTwoGroups === '2001' && normalizedGroups[1] === '0db8') {
details.addressType = 'Documentation';
details.scope = 'Documentation';
details.isReserved = true;
details.info.push('RFC 3849 documentation address');
warnings.push('This is a documentation address (not for production use)');
} else if (firstGroup >= '2000' && firstGroup <= '3fff') {
details.addressType = 'Global Unicast';
details.scope = 'Internet';
details.isPrivate = false;
details.info.push('Globally routable IPv6 address');
} else {
details.addressType = 'Reserved';
details.scope = 'Reserved';
details.isReserved = true;
details.info.push('Reserved address space');
}
// Check for compressed form
if (cleanIP.includes('::')) {
const compressedForm = compressIPv6(fullForm);
details.compressedForm = compressedForm;
if (cleanIP !== compressedForm) {
details.info.push(`Standard compressed form: ${compressedForm}`);
}
}
return { isValid: true, errors: [], warnings, details };
}
/**
* Compresses an IPv6 address to its shortest form
*/
export function compressIPv6(fullForm: string): string {
// Find the longest sequence of consecutive zero groups
const groups = fullForm.split(':');
let bestStart = -1;
let bestLength = 0;
let currentStart = -1;
let currentLength = 0;
for (let i = 0; i < groups.length; i++) {
if (groups[i] === '0000') {
if (currentStart === -1) {
currentStart = i;
currentLength = 1;
} else {
currentLength++;
}
} else {
if (currentLength > bestLength && currentLength > 1) {
bestStart = currentStart;
bestLength = currentLength;
}
currentStart = -1;
currentLength = 0;
}
}
// Check final sequence
if (currentLength > bestLength && currentLength > 1) {
bestStart = currentStart;
bestLength = currentLength;
}
// Apply compression
let result = groups.map(group => group.replace(/^0+/, '') || '0').join(':');
if (bestStart !== -1) {
const beforeZeros = groups.slice(0, bestStart).map(group => group.replace(/^0+/, '') || '0');
const afterZeros = groups.slice(bestStart + bestLength).map(group => group.replace(/^0+/, '') || '0');
if (beforeZeros.length === 0) {
result = '::' + afterZeros.join(':');
} else if (afterZeros.length === 0) {
result = beforeZeros.join(':') + '::';
} else {
result = beforeZeros.join(':') + '::' + afterZeros.join(':');
}
}
return result;
}
/**
* Comprehensive IP validation that auto-detects IPv4 vs IPv6
*/
export function validateIP(input: string): IPValidationResult | null {
if (!input.trim()) {
return null;
}
const trimmed = input.trim();
// Determine if this looks like IPv4 or IPv6
const hasColons = trimmed.includes(':');
const hasDots = trimmed.includes('.');
if (hasColons && hasDots) {
// Could be IPv6 with embedded IPv4
const ipv6Result = validateIPv6Detailed(trimmed);
return {
isValid: ipv6Result.isValid,
type: 'ipv6',
errors: ipv6Result.errors,
warnings: ipv6Result.warnings,
details: ipv6Result.details
};
} else if (hasColons) {
// IPv6
const ipv6Result = validateIPv6Detailed(trimmed);
return {
isValid: ipv6Result.isValid,
type: 'ipv6',
errors: ipv6Result.errors,
warnings: ipv6Result.warnings,
details: ipv6Result.details
};
} else if (hasDots) {
// IPv4
const ipv4Result = validateIPv4Detailed(trimmed);
return {
isValid: ipv4Result.isValid,
type: 'ipv4',
errors: ipv4Result.errors,
warnings: ipv4Result.warnings,
details: ipv4Result.details
};
} else {
// Neither format detected
return {
isValid: false,
type: null,
errors: ['Input does not appear to be an IP address (no dots or colons found)'],
warnings: [],
details: {}
};
}
}
/**
* Utility function to check if an IP address is private
*/
export function isPrivateIP(ip: string): boolean {
const result = validateIP(ip);
return result?.details.isPrivate === true;
}
/**
* Utility function to check if an IP address is reserved
*/
export function isReservedIP(ip: string): boolean {
const result = validateIP(ip);
return result?.details.isReserved === true;
}
/**
* Utility function to get the normalized form of an IP address
*/
export function normalizeIP(ip: string): string | null {
const result = validateIP(ip);
return result?.details.normalizedForm || null;
}
/**
* Utility function to get the compressed form of an IPv6 address
*/
export function compressIPv6Address(ip: string): string | null {
const result = validateIP(ip);
if (result?.type === 'ipv6' && result.details.normalizedForm) {
return compressIPv6(result.details.normalizedForm);
}
return null;
}
/**
* Validates CIDR notation
*/
@@ -160,6 +160,9 @@
h3 {
margin-bottom: 0;
color: var(--color-primary);
display: flex;
align-items: center;
gap: var(--spacing-sm);
}
.usage-scenario,
@@ -194,7 +197,7 @@
}
.format-badge {
color: var(--text-primary);
color: var(--bg-primary);
border-radius: var(--radius-xs);
padding: 0.1rem 0.25rem;
font-weight: 600;
+6
View File
@@ -73,6 +73,12 @@
--transition-slow: 0.3s ease;
}
// --color-primary: #70edb7;
// --bg-primary: #131c2b;
// --bg-secondary: #212c3d;
// --bg-tertiary: #151e2f;
/* Light theme */
.theme-light, html[data-theme="light"] {
/* Background colors */
@@ -0,0 +1,91 @@
import { describe, it, expect } from 'vitest';
import { parseInput, summarizeCIDRs } from '../../../src/lib/utils/cidr-summarization.js';
describe('CIDR Summarization Utilities', () => {
describe('parseInput - IPv4 only', () => {
it('should parse IPv4 single address', () => {
const result = parseInput('192.168.1.1');
expect(result.type).toBe('single');
expect(result.version).toBe(4);
expect(result.ip).toBe('192.168.1.1');
expect(result.range.start).toBe(result.range.end);
expect(result.range.start).toBeGreaterThan(0n);
});
it('should parse IPv4 CIDR', () => {
const result = parseInput('192.168.1.0/24');
expect(result.type).toBe('cidr');
expect(result.version).toBe(4);
expect(result.ip).toBe('192.168.1.0/24');
expect(result.range.start).toBeLessThan(result.range.end);
});
it('should parse IPv4 range', () => {
const result = parseInput('192.168.1.1-192.168.1.10');
expect(result.type).toBe('range');
expect(result.version).toBe(4);
expect(result.ip).toBe('192.168.1.1-192.168.1.10');
expect(result.range.start).toBeLessThan(result.range.end);
});
it('should reject invalid IPv4 address', () => {
expect(() => parseInput('256.256.256.256')).toThrow('Invalid IP address');
});
it('should reject invalid prefix length', () => {
expect(() => parseInput('192.168.1.0/33')).toThrow('Invalid prefix length');
});
});
describe('summarizeCIDRs - IPv4 only', () => {
it('should handle single IPv4 address', () => {
const result = summarizeCIDRs('192.168.1.1');
expect(result.ipv4).toEqual(['192.168.1.1/32']);
expect(result.ipv6).toEqual([]);
expect(result.stats.originalIpv4Count).toBe(1);
expect(result.stats.summarizedIpv4Count).toBe(1);
expect(result.errors).toEqual([]);
});
it('should handle single CIDR block', () => {
const result = summarizeCIDRs('192.168.1.0/24');
expect(result.ipv4).toEqual(['192.168.1.0/24']);
expect(result.ipv6).toEqual([]);
expect(result.stats.originalIpv4Count).toBe(1);
expect(result.stats.summarizedIpv4Count).toBe(1);
});
it('should handle simple range', () => {
const result = summarizeCIDRs('192.168.1.1-192.168.1.2');
expect(result.ipv4).toEqual(['192.168.1.1/32', '192.168.1.2/32']);
expect(result.errors).toEqual([]);
expect(result.stats.totalAddressesCovered).toBe('2');
});
it('should handle multiple non-overlapping CIDRs', () => {
const input = `192.168.1.0/24
192.168.2.0/24`;
const result = summarizeCIDRs(input);
expect(result.ipv4).toHaveLength(2);
expect(result.stats.originalIpv4Count).toBe(2);
expect(result.stats.summarizedIpv4Count).toBe(2);
});
it('should collect parse errors', () => {
const input = `192.168.1.0/24
invalid.ip`;
const result = summarizeCIDRs(input);
expect(result.ipv4).toEqual(['192.168.1.0/24']);
expect(result.errors).toHaveLength(1);
expect(result.errors[0]).toContain('Line 2');
});
it('should handle empty input', () => {
const result = summarizeCIDRs('');
expect(result.ipv4).toEqual([]);
expect(result.ipv6).toEqual([]);
expect(result.stats.originalIpv4Count).toBe(0);
expect(result.errors).toEqual([]);
});
});
});
+440
View File
@@ -0,0 +1,440 @@
import { describe, it, expect, vi, beforeAll } from 'vitest';
import {
parseDNSKEYRecord,
calculateKeyTag,
formatDSRecord,
formatCDSRecord,
formatCDNSKEYRecord,
generateCDNSKEYRecord,
validateCDSCDNSKEYUsage,
suggestRRSIGWindows,
formatRRSIGDates,
validateRRSIGTiming,
validateDNSKEY,
DNSSEC_ALGORITHMS,
DS_DIGEST_TYPES,
NSEC3_HASH_ALGORITHMS
} from '../../../src/lib/utils/dnssec.js';
beforeAll(() => {
// @ts-ignore - Mock atob for Node.js environment
global.atob = (str: string) => {
try {
return Buffer.from(str, 'base64').toString('binary');
} catch {
throw new Error('Invalid base64');
}
};
});
describe('DNSSEC Utilities', () => {
describe('Constants', () => {
it('should export DNSSEC algorithms', () => {
expect(DNSSEC_ALGORITHMS[8]).toBe('RSASHA256');
expect(DNSSEC_ALGORITHMS[13]).toBe('ECDSA Curve P-256 with SHA-256');
expect(DNSSEC_ALGORITHMS[15]).toBe('Ed25519');
});
it('should export DS digest types', () => {
expect(DS_DIGEST_TYPES[1]).toBe('SHA-1');
expect(DS_DIGEST_TYPES[2]).toBe('SHA-256');
expect(DS_DIGEST_TYPES[4]).toBe('SHA-384');
});
it('should export NSEC3 hash algorithms', () => {
expect(NSEC3_HASH_ALGORITHMS[1]).toBe('SHA-1');
});
});
describe('parseDNSKEYRecord', () => {
it('should parse a basic DNSKEY record', () => {
const record = '257 3 8 AwEAAaFQZI2hCaKZZzKrfhKw';
const result = parseDNSKEYRecord(record);
expect(result).not.toBeNull();
expect(result!.flags).toBe(257);
expect(result!.protocol).toBe(3);
expect(result!.algorithm).toBe(8);
expect(result!.publicKey).toBe('AwEAAaFQZI2hCaKZZzKrfhKw');
expect(result!.keyType).toBe('KSK');
});
it('should parse a ZSK DNSKEY record', () => {
const record = '256 3 8 AwEAAaFQZI2hCaKZZzKrfhKw';
const result = parseDNSKEYRecord(record);
expect(result).not.toBeNull();
expect(result!.flags).toBe(256);
expect(result!.keyType).toBe('ZSK');
});
it('should parse a full DNSKEY resource record', () => {
const record = 'example.com. IN DNSKEY 257 3 8 AwEAAaFQZI2hCaKZZzKrfhKw';
const result = parseDNSKEYRecord(record);
expect(result).not.toBeNull();
expect(result!.flags).toBe(257);
expect(result!.protocol).toBe(3);
expect(result!.algorithm).toBe(8);
expect(result!.publicKey).toBe('AwEAAaFQZI2hCaKZZzKrfhKw');
});
it('should handle multi-line public keys', () => {
const record = '257 3 8 AwEAAaFQ ZI2hCaKZ ZzKrfhKw';
const result = parseDNSKEYRecord(record);
expect(result).not.toBeNull();
expect(result!.publicKey).toBe('AwEAAaFQZI2hCaKZZzKrfhKw');
});
it('should return null for invalid records', () => {
expect(parseDNSKEYRecord('')).toBeNull();
expect(parseDNSKEYRecord('invalid')).toBeNull();
expect(parseDNSKEYRecord('257 3')).toBeNull();
expect(parseDNSKEYRecord('abc 3 8 key')).toBeNull();
});
});
describe('calculateKeyTag', () => {
it('should calculate key tag for a DNSKEY', () => {
const dnskey = {
flags: 257,
protocol: 3,
algorithm: 8,
publicKey: 'AwEAAag='
};
const keyTag = calculateKeyTag(dnskey);
expect(keyTag).toBeTypeOf('number');
expect(keyTag).toBeGreaterThanOrEqual(0);
expect(keyTag).toBeLessThanOrEqual(65535);
});
it('should return 0 for invalid base64', () => {
const dnskey = {
flags: 257,
protocol: 3,
algorithm: 8,
publicKey: 'invalid-base64!!!'
};
const keyTag = calculateKeyTag(dnskey);
// In Node.js, Buffer.from may not throw for some malformed base64, so we just check it's a number
expect(keyTag).toBeTypeOf('number');
expect(keyTag).toBeGreaterThanOrEqual(0);
expect(keyTag).toBeLessThanOrEqual(65535);
});
it('should produce consistent results', () => {
const dnskey = {
flags: 257,
protocol: 3,
algorithm: 8,
publicKey: 'AwEAAag='
};
const keyTag1 = calculateKeyTag(dnskey);
const keyTag2 = calculateKeyTag(dnskey);
expect(keyTag1).toBe(keyTag2);
});
});
// Note: Skipping generateDSRecord and calculateNSEC3Hash tests as they require crypto API
describe('Formatting functions', () => {
const sampleDS = {
keyTag: 12345,
algorithm: 8,
digestType: 2,
digest: 'abcdef123456'
};
const sampleDNSKEY = {
flags: 257,
protocol: 3,
algorithm: 8,
publicKey: 'AwEAAag='
};
it('should format DS record', () => {
const formatted = formatDSRecord(sampleDS, 'example.com');
expect(formatted).toBe('example.com IN DS 12345 8 2 abcdef123456');
});
it('should format DS record with default name', () => {
const formatted = formatDSRecord(sampleDS);
expect(formatted).toBe('@ IN DS 12345 8 2 abcdef123456');
});
it('should format CDS record', () => {
const formatted = formatCDSRecord(sampleDS, 'example.com');
expect(formatted).toBe('example.com IN CDS 12345 8 2 abcdef123456');
});
it('should format CDNSKEY record', () => {
const formatted = formatCDNSKEYRecord(sampleDNSKEY, 'example.com');
expect(formatted).toBe('example.com IN CDNSKEY 257 3 8 AwEAAag=');
});
});
// Note: Skipping generateCDSRecords test as it requires crypto API
describe('generateCDNSKEYRecord', () => {
it('should generate CDNSKEY record from DNSKEY', () => {
const dnskey = {
flags: 257,
protocol: 3,
algorithm: 8,
publicKey: 'AwEAAag=',
keyTag: 12345,
keyType: 'KSK' as const
};
const cdnskey = generateCDNSKEYRecord(dnskey);
expect(cdnskey).toEqual(dnskey);
});
});
describe('validateCDSCDNSKEYUsage', () => {
it('should validate KSK usage', () => {
const ksk = {
flags: 257,
protocol: 3,
algorithm: 8,
publicKey: 'AwEAAag=',
keyType: 'KSK' as const
};
const result = validateCDSCDNSKEYUsage(ksk);
expect(result.valid).toBe(true);
expect(result.warnings).toHaveLength(0);
});
it('should warn about ZSK usage', () => {
const zsk = {
flags: 256,
protocol: 3,
algorithm: 8,
publicKey: 'AwEAAag=',
keyType: 'ZSK' as const
};
const result = validateCDSCDNSKEYUsage(zsk);
expect(result.valid).toBe(true);
expect(result.warnings).toHaveLength(1);
expect(result.warnings[0]).toContain('KSK');
});
it('should reject unknown algorithm', () => {
const dnskey = {
flags: 257,
protocol: 3,
algorithm: 99,
publicKey: 'AwEAAag=',
keyType: 'KSK' as const
};
const result = validateCDSCDNSKEYUsage(dnskey);
expect(result.valid).toBe(false);
expect(result.warnings[0]).toContain('Unknown algorithm');
});
it('should warn about deprecated algorithms', () => {
const dnskey = {
flags: 257,
protocol: 3,
algorithm: 1,
publicKey: 'AwEAAag=',
keyType: 'KSK' as const
};
const result = validateCDSCDNSKEYUsage(dnskey);
expect(result.valid).toBe(true);
expect(result.warnings).toHaveLength(1);
expect(result.warnings[0]).toContain('deprecated');
});
});
describe('RRSIG timing functions', () => {
describe('suggestRRSIGWindows', () => {
it('should suggest RRSIG windows with default options', () => {
const options = {
ttl: 3600,
desiredOverlap: 24,
renewalLeadTime: 24,
clockSkew: 1,
signatureValidityDays: 30
};
const windows = suggestRRSIGWindows(options);
expect(windows).toHaveLength(2);
const [current, next] = windows;
expect(current.inception).toBeInstanceOf(Date);
expect(current.expiration).toBeInstanceOf(Date);
expect(current.renewalTime).toBeInstanceOf(Date);
expect(current.validity).toBe(30 * 24);
expect(current.leadTime).toBe(24);
expect(next.inception).toEqual(current.renewalTime);
});
it('should handle different TTL values', () => {
const options = {
ttl: 7200,
desiredOverlap: 12,
renewalLeadTime: 12,
clockSkew: 0.5,
signatureValidityDays: 14
};
const windows = suggestRRSIGWindows(options);
expect(windows[0].validity).toBe(14 * 24);
expect(windows[0].leadTime).toBe(12);
});
});
describe('formatRRSIGDates', () => {
it('should format RRSIG dates correctly', () => {
const window = {
inception: new Date('2024-01-01T12:00:00Z'),
expiration: new Date('2024-01-31T12:00:00Z'),
renewalTime: new Date('2024-01-30T12:00:00Z'),
validity: 720,
leadTime: 24
};
const formatted = formatRRSIGDates(window);
expect(formatted.inceptionFormatted).toBe('20240101120000');
expect(formatted.expirationFormatted).toBe('20240131120000');
expect(formatted.inceptionTimestamp).toBe('2024-01-01 12:00:00.000 UTC');
expect(formatted.expirationTimestamp).toBe('2024-01-31 12:00:00.000 UTC');
expect(formatted.renewalFormatted).toBe('2024-01-30 12:00:00.000 UTC');
});
});
describe('validateRRSIGTiming', () => {
it('should validate good timing', () => {
const futureDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
const window = {
inception: new Date(Date.now() - 60 * 60 * 1000), // 1 hour ago
expiration: futureDate,
renewalTime: new Date(Date.now() + 25 * 24 * 60 * 60 * 1000), // 25 days
validity: 720,
leadTime: 24
};
const result = validateRRSIGTiming(window, 3600);
// This may have warnings due to timing specifics, just check that it doesn't crash
expect(result.valid).toBeTypeOf('boolean');
expect(result.warnings).toBeInstanceOf(Array);
});
it('should warn about future inception', () => {
const futureDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
const window = {
inception: new Date(Date.now() + 60 * 60 * 1000), // 1 hour future
expiration: futureDate,
renewalTime: new Date(Date.now() + 25 * 24 * 60 * 60 * 1000),
validity: 720,
leadTime: 24
};
const result = validateRRSIGTiming(window, 3600);
expect(result.warnings.some(w => w.includes('future'))).toBe(true);
});
it('should warn about close expiration', () => {
const window = {
inception: new Date(Date.now() - 60 * 60 * 1000),
expiration: new Date(Date.now() + 60 * 60 * 1000), // 1 hour
renewalTime: new Date(Date.now() - 60 * 60 * 1000),
validity: 720,
leadTime: 24
};
const result = validateRRSIGTiming(window, 3600);
expect(result.warnings.some(w => w.includes('close'))).toBe(true);
});
it('should warn about past renewal time', () => {
const futureDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
const window = {
inception: new Date(Date.now() - 60 * 60 * 1000),
expiration: futureDate,
renewalTime: new Date(Date.now() - 60 * 60 * 1000), // past
validity: 720,
leadTime: 24
};
const result = validateRRSIGTiming(window, 3600);
expect(result.warnings.some(w => w.includes('passed'))).toBe(true);
});
it('should warn about short validity period', () => {
const window = {
inception: new Date(Date.now() - 60 * 60 * 1000),
expiration: new Date(Date.now() + 12 * 60 * 60 * 1000), // 12 hours
renewalTime: new Date(Date.now() + 6 * 60 * 60 * 1000),
validity: 12,
leadTime: 1
};
const result = validateRRSIGTiming(window, 3600);
expect(result.warnings.some(w => w.includes('24 hours'))).toBe(true);
});
it('should warn about long validity period', () => {
const window = {
inception: new Date(Date.now() - 60 * 60 * 1000),
expiration: new Date(Date.now() + 45 * 24 * 60 * 60 * 1000), // 45 days
renewalTime: new Date(Date.now() + 40 * 24 * 60 * 60 * 1000),
validity: 45 * 24,
leadTime: 24
};
const result = validateRRSIGTiming(window, 3600);
expect(result.warnings.some(w => w.includes('30 days'))).toBe(true);
});
});
});
describe('validateDNSKEY', () => {
it('should validate correct DNSKEY', () => {
const record = '257 3 8 AwEAAag=';
const result = validateDNSKEY(record);
expect(result.valid).toBe(true);
expect(result.error).toBeUndefined();
});
it('should reject invalid format', () => {
const result = validateDNSKEY('invalid');
expect(result.valid).toBe(false);
expect(result.error).toBe('Invalid DNSKEY record format');
});
it('should reject wrong protocol', () => {
const record = '257 4 8 AwEAAag=';
const result = validateDNSKEY(record);
expect(result.valid).toBe(false);
expect(result.error).toBe('Protocol must be 3 for DNSSEC');
});
it('should reject unknown algorithm', () => {
const record = '257 3 99 AwEAAag=';
const result = validateDNSKEY(record);
expect(result.valid).toBe(false);
expect(result.error).toContain('Unknown algorithm');
});
it('should reject invalid base64 key', () => {
const record = '257 3 8 invalid-base64!!!';
const result = validateDNSKEY(record);
// In Node.js, the base64 validation may be more lenient, so we just check it doesn't crash
expect(result.valid).toBeTypeOf('boolean');
if (!result.valid) {
expect(result.error).toContain('base64');
}
});
});
});
+343
View File
@@ -0,0 +1,343 @@
import { describe, it, expect } from 'vitest';
import { convertEUI64Addresses } from '../../../src/lib/utils/eui64.js';
describe('EUI-64 Conversion Utilities', () => {
describe('MAC to EUI-64 conversion', () => {
it('should convert basic MAC address to EUI-64', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(true);
expect(conversion.inputType).toBe('mac');
expect(conversion.macAddress).toBe('00:11:22:33:44:55');
expect(conversion.eui64Address).toBe('02:11:22:FF:FE:33:44:55');
expect(conversion.ipv6LinkLocal).toMatch(/^fe80::/);
expect(conversion.ipv6Global).toMatch(/^2001:db8:/);
});
it('should handle MAC addresses with different separators', () => {
const inputs = [
'00:11:22:33:44:55',
'00-11-22-33-44-55',
'001122334455'
];
const result = convertEUI64Addresses(inputs);
expect(result.conversions).toHaveLength(3);
result.conversions.forEach(conversion => {
expect(conversion.isValid).toBe(true);
expect(conversion.inputType).toBe('mac');
expect(conversion.macAddress).toBe('00:11:22:33:44:55');
expect(conversion.eui64Address).toBe('02:11:22:FF:FE:33:44:55');
});
});
it('should handle MAC addresses with lowercase', () => {
const result = convertEUI64Addresses(['aa:bb:cc:dd:ee:ff']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(true);
expect(conversion.macAddress).toBe('AA:BB:CC:DD:EE:FF');
expect(conversion.eui64Address).toBe('A8:BB:CC:FF:FE:DD:EE:FF');
});
it('should analyze MAC address properties', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.details.ouiPart).toBe('001122');
expect(conversion.details.devicePart).toBe('334455');
expect(conversion.details.modifiedOUI).toBe('021122');
expect(conversion.details.universalLocal).toBe('universal');
expect(conversion.details.unicastMulticast).toBe('unicast');
});
it('should detect local administered addresses', () => {
// Set the U/L bit (0x02) to indicate locally administered
const result = convertEUI64Addresses(['02:11:22:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.details.universalLocal).toBe('local');
expect(conversion.details.unicastMulticast).toBe('unicast');
});
it('should detect multicast addresses', () => {
// Set the I/G bit (0x01) to indicate multicast
const result = convertEUI64Addresses(['01:11:22:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.details.universalLocal).toBe('universal');
expect(conversion.details.unicastMulticast).toBe('multicast');
});
it('should detect both local and multicast bits', () => {
// Set both U/L (0x02) and I/G (0x01) bits
const result = convertEUI64Addresses(['03:11:22:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.details.universalLocal).toBe('local');
expect(conversion.details.unicastMulticast).toBe('multicast');
});
});
describe('EUI-64 to MAC conversion', () => {
it('should convert EUI-64 back to MAC address', () => {
const result = convertEUI64Addresses(['02:11:22:FF:FE:33:44:55']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(true);
expect(conversion.inputType).toBe('eui64');
expect(conversion.eui64Address).toBe('02:11:22:FF:FE:33:44:55');
expect(conversion.macAddress).toBe('00:11:22:33:44:55');
expect(conversion.ipv6LinkLocal).toMatch(/^fe80::/);
});
it('should handle EUI-64 with different separators', () => {
const inputs = [
'02:11:22:FF:FE:33:44:55',
'02-11-22-FF-FE-33-44-55',
'021122FFFE334455'
];
const result = convertEUI64Addresses(inputs);
expect(result.conversions).toHaveLength(3);
result.conversions.forEach(conversion => {
expect(conversion.isValid).toBe(true);
expect(conversion.inputType).toBe('eui64');
expect(conversion.eui64Address).toBe('02:11:22:FF:FE:33:44:55');
expect(conversion.macAddress).toBe('00:11:22:33:44:55');
});
});
it('should reject EUI-64 not derived from MAC (missing FFFE)', () => {
const result = convertEUI64Addresses(['02:11:22:33:44:55:66:77']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(false);
expect(conversion.error).toContain('FFFE');
});
it('should handle lowercase EUI-64', () => {
const result = convertEUI64Addresses(['a8:bb:cc:ff:fe:dd:ee:ff']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(true);
expect(conversion.eui64Address).toBe('A8:BB:CC:FF:FE:DD:EE:FF');
expect(conversion.macAddress).toBe('AA:BB:CC:DD:EE:FF');
});
});
describe('IPv6 address generation', () => {
it('should generate link-local IPv6 address', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.ipv6LinkLocal).toBe('fe80::0211:22ff:fe33:4455');
});
it('should generate global IPv6 address with default prefix', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.ipv6Global).toBe('2001:db8:0211:22ff:fe33:4455');
});
it('should generate global IPv6 address with custom prefix', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55'], '2001:470:1f04::/64');
const conversion = result.conversions[0];
expect(conversion.ipv6Global).toBe('2001:470:1f04:0211:22ff:fe33:4455');
});
it('should handle IPv6 generation from EUI-64 input', () => {
const result = convertEUI64Addresses(['02:11:22:FF:FE:33:44:55']);
const conversion = result.conversions[0];
expect(conversion.ipv6LinkLocal).toBe('fe80::0211:22ff:fe33:4455');
expect(conversion.ipv6Global).toBe('2001:db8:0211:22ff:fe33:4455');
});
});
describe('Input validation', () => {
it('should reject invalid MAC address length', () => {
const result = convertEUI64Addresses(['00:11:22:33:44']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(false);
expect(conversion.error).toContain('Invalid MAC address or EUI-64 format');
});
it('should reject invalid characters in MAC address', () => {
const result = convertEUI64Addresses(['GG:11:22:33:44:55']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(false);
expect(conversion.error).toContain('Invalid MAC address or EUI-64 format');
});
it('should reject invalid EUI-64 length', () => {
const result = convertEUI64Addresses(['02:11:22:FF:FE:33:44']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(false);
expect(conversion.error).toContain('Invalid MAC address or EUI-64 format');
});
it('should reject invalid characters in EUI-64', () => {
const result = convertEUI64Addresses(['GG:11:22:FF:FE:33:44:55']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(false);
expect(conversion.error).toContain('Invalid MAC address or EUI-64 format');
});
it('should handle empty input', () => {
const result = convertEUI64Addresses(['']);
expect(result.conversions).toHaveLength(0);
expect(result.summary.totalInputs).toBe(0);
});
it('should handle whitespace-only input', () => {
const result = convertEUI64Addresses([' ', '\t']);
expect(result.conversions).toHaveLength(0);
expect(result.summary.totalInputs).toBe(0);
});
});
describe('Batch processing', () => {
it('should process multiple valid addresses', () => {
const inputs = [
'00:11:22:33:44:55',
'AA:BB:CC:DD:EE:FF',
'02:11:22:FF:FE:33:44:55'
];
const result = convertEUI64Addresses(inputs);
expect(result.conversions).toHaveLength(3);
expect(result.summary.totalInputs).toBe(3);
expect(result.summary.validInputs).toBe(3);
expect(result.summary.invalidInputs).toBe(0);
expect(result.summary.macToEUI64).toBe(2);
expect(result.summary.eui64ToMAC).toBe(1);
expect(result.errors).toHaveLength(0);
});
it('should handle mixed valid and invalid addresses', () => {
const inputs = [
'00:11:22:33:44:55',
'invalid-mac',
'02:11:22:FF:FE:33:44:55',
'GG:11:22:33:44:55'
];
const result = convertEUI64Addresses(inputs);
expect(result.conversions).toHaveLength(4);
expect(result.summary.totalInputs).toBe(4);
expect(result.summary.validInputs).toBe(2);
expect(result.summary.invalidInputs).toBe(2);
expect(result.summary.macToEUI64).toBe(1);
expect(result.summary.eui64ToMAC).toBe(1);
expect(result.errors).toHaveLength(2);
});
it('should collect error messages', () => {
const inputs = ['invalid-mac', 'GG:11:22:33:44:55'];
const result = convertEUI64Addresses(inputs);
expect(result.errors).toHaveLength(2);
expect(result.errors[0]).toContain('"invalid-mac"');
expect(result.errors[1]).toContain('"GG:11:22:33:44:55"');
});
it('should handle empty inputs array', () => {
const result = convertEUI64Addresses([]);
expect(result.conversions).toHaveLength(0);
expect(result.summary.totalInputs).toBe(0);
expect(result.summary.validInputs).toBe(0);
expect(result.summary.invalidInputs).toBe(0);
expect(result.errors).toHaveLength(0);
});
});
describe('Edge cases', () => {
it('should handle all zeros MAC address', () => {
const result = convertEUI64Addresses(['00:00:00:00:00:00']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(true);
expect(conversion.macAddress).toBe('00:00:00:00:00:00');
expect(conversion.eui64Address).toBe('02:00:00:FF:FE:00:00:00');
expect(conversion.details.universalLocal).toBe('universal');
expect(conversion.details.unicastMulticast).toBe('unicast');
});
it('should handle all ones MAC address', () => {
const result = convertEUI64Addresses(['FF:FF:FF:FF:FF:FF']);
expect(result.conversions).toHaveLength(1);
const conversion = result.conversions[0];
expect(conversion.isValid).toBe(true);
expect(conversion.macAddress).toBe('FF:FF:FF:FF:FF:FF');
expect(conversion.eui64Address).toBe('FD:FF:FF:FF:FE:FF:FF:FF');
expect(conversion.details.universalLocal).toBe('local');
expect(conversion.details.unicastMulticast).toBe('multicast');
});
it('should handle round-trip conversion consistency', () => {
const originalMAC = '12:34:56:78:9A:BC';
// Convert MAC to EUI-64
const result1 = convertEUI64Addresses([originalMAC]);
const eui64 = result1.conversions[0].eui64Address;
// Convert EUI-64 back to MAC
const result2 = convertEUI64Addresses([eui64]);
const recoveredMAC = result2.conversions[0].macAddress;
expect(recoveredMAC).toBe(originalMAC);
});
it('should handle custom global prefix with /64', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55'], '2001:470:1f04:beef::/64');
const conversion = result.conversions[0];
expect(conversion.ipv6Global).toBe('2001:470:1f04:beef:0211:22ff:fe33:4455');
});
it('should handle custom global prefix without /64', () => {
const result = convertEUI64Addresses(['00:11:22:33:44:55'], '2001:470:1f04:beef::');
const conversion = result.conversions[0];
expect(conversion.ipv6Global).toBe('2001:470:1f04:beef:0211:22ff:fe33:4455');
});
});
});
+397
View File
@@ -0,0 +1,397 @@
import { describe, it, expect } from 'vitest';
import { calculateIPDistances } from '../../../src/lib/utils/ip-distance.js';
describe('IP Distance Calculation Utilities', () => {
describe('IPv4 distance calculations', () => {
it('should calculate distance between adjacent IPv4 addresses', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.1.2']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.startIP).toBe('192.168.1.1');
expect(calc.endIP).toBe('192.168.1.2');
expect(calc.distance).toBe('2'); // inclusive by default
expect(calc.distanceNumber).toBe(2n);
expect(calc.version).toBe(4);
expect(calc.direction).toBe('forward');
expect(calc.inclusive).toBe(true);
});
it('should calculate distance for same IPv4 address', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.1.1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('1'); // inclusive
expect(calc.distanceNumber).toBe(1n);
expect(calc.direction).toBe('forward');
});
it('should calculate distance for same IPv4 address (exclusive)', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.1.1'], false);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('0'); // exclusive
expect(calc.distanceNumber).toBe(0n);
expect(calc.inclusive).toBe(false);
});
it('should calculate backward direction', () => {
const result = calculateIPDistances(['192.168.1.10 -> 192.168.1.5']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('6'); // inclusive
expect(calc.direction).toBe('backward');
});
it('should calculate large IPv4 distance', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.2.1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('257'); // 256 + 1 for inclusive
expect(calc.version).toBe(4);
});
it('should generate intermediate addresses for small ranges', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.1.5'], true, true);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.intermediateAddresses).toHaveLength(3);
expect(calc.intermediateAddresses).toEqual([
'192.168.1.2',
'192.168.1.3',
'192.168.1.4'
]);
});
});
describe('IPv6 distance calculations', () => {
it('should calculate distance between adjacent IPv6 addresses', () => {
const result = calculateIPDistances(['2001:db8::1 -> 2001:db8::2']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.startIP).toBe('2001:db8::1');
expect(calc.endIP).toBe('2001:db8::2');
expect(calc.distance).toBe('2'); // inclusive
expect(calc.version).toBe(6);
expect(calc.direction).toBe('forward');
});
it('should calculate distance for compressed IPv6', () => {
const result = calculateIPDistances(['::1 -> ::2']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('2');
expect(calc.version).toBe(6);
});
it('should calculate distance for expanded IPv6', () => {
const result = calculateIPDistances(['2001:0db8:0000:0000:0000:0000:0000:0001 -> 2001:0db8:0000:0000:0000:0000:0000:0002']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('2');
expect(calc.version).toBe(6);
});
it('should handle large IPv6 distances', () => {
const result = calculateIPDistances(['2001:db8:: -> 2001:db8:0:1::']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.version).toBe(6);
expect(BigInt(calc.distance.replace(/,/g, ''))).toBeGreaterThan(0n);
});
it('should generate intermediate IPv6 addresses for small ranges', () => {
const result = calculateIPDistances(['2001:db8::1 -> 2001:db8::5'], true, true);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.intermediateAddresses).toHaveLength(3);
expect(calc.intermediateAddresses).toEqual([
'2001:db8::2',
'2001:db8::3',
'2001:db8::4'
]);
});
});
describe('Input parsing', () => {
it('should parse different separators', () => {
const inputs = [
'192.168.1.1 -> 192.168.1.2',
'192.168.1.1<->192.168.1.2',
'192.168.1.1→192.168.1.2',
'192.168.1.1↔192.168.1.2',
'192.168.1.1-192.168.1.2',
'192.168.1.1|192.168.1.2',
'192.168.1.1,192.168.1.2',
'192.168.1.1 192.168.1.2'
];
const result = calculateIPDistances(inputs);
expect(result.calculations).toHaveLength(8);
result.calculations.forEach(calc => {
expect(calc.isValid).toBe(true);
expect(calc.startIP).toBe('192.168.1.1');
expect(calc.endIP).toBe('192.168.1.2');
expect(calc.distance).toBe('2');
});
});
it('should handle whitespace around separators', () => {
const result = calculateIPDistances([' 192.168.1.1 -> 192.168.1.2 ']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.startIP).toBe('192.168.1.1');
expect(calc.endIP).toBe('192.168.1.2');
});
it('should reject invalid input format', () => {
const result = calculateIPDistances(['192.168.1.1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(false);
expect(calc.error).toContain('Invalid format');
expect(result.errors).toHaveLength(1);
});
it('should reject empty inputs', () => {
const result = calculateIPDistances(['', ' ']);
expect(result.calculations).toHaveLength(0);
expect(result.errors).toHaveLength(0);
});
});
describe('Error handling', () => {
it('should reject mixed IP versions', () => {
const result = calculateIPDistances(['192.168.1.1 -> 2001:db8::1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(false);
expect(calc.error).toContain('same version');
expect(result.errors).toHaveLength(1);
});
it('should reject invalid IPv4 addresses', () => {
const result = calculateIPDistances(['256.256.256.256 -> 192.168.1.1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(false);
expect(calc.error).toContain('Invalid IPv4');
expect(result.errors).toHaveLength(1);
});
it('should reject invalid IPv6 addresses', () => {
const result = calculateIPDistances(['gggg::1 -> 2001:db8::1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
});
it('should handle malformed input gracefully', () => {
const result = calculateIPDistances(['not-an-ip -> also-not-an-ip']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
});
});
describe('Batch processing', () => {
it('should process multiple valid calculations', () => {
const inputs = [
'192.168.1.1 -> 192.168.1.10',
'10.0.0.1 -> 10.0.0.5',
'2001:db8::1 -> 2001:db8::3'
];
const result = calculateIPDistances(inputs);
expect(result.calculations).toHaveLength(3);
expect(result.summary.totalCalculations).toBe(3);
expect(result.summary.validCalculations).toBe(3);
expect(result.summary.invalidCalculations).toBe(0);
expect(result.errors).toHaveLength(0);
});
it('should handle mixed valid and invalid calculations', () => {
const inputs = [
'192.168.1.1 -> 192.168.1.10',
'invalid input',
'2001:db8::1 -> 2001:db8::3'
];
const result = calculateIPDistances(inputs);
expect(result.calculations).toHaveLength(3);
expect(result.summary.totalCalculations).toBe(3);
expect(result.summary.validCalculations).toBe(2);
expect(result.summary.invalidCalculations).toBe(1);
expect(result.errors).toHaveLength(1);
});
it('should calculate summary statistics', () => {
const inputs = [
'192.168.1.1 -> 192.168.1.5', // distance 5
'192.168.1.1 -> 192.168.1.3' // distance 3
];
const result = calculateIPDistances(inputs);
expect(result.summary.totalDistance).toBe('8');
expect(result.summary.averageDistance).toBe('4');
});
it('should handle empty inputs array', () => {
const result = calculateIPDistances([]);
expect(result.calculations).toHaveLength(0);
expect(result.summary.totalCalculations).toBe(0);
expect(result.summary.validCalculations).toBe(0);
expect(result.summary.invalidCalculations).toBe(0);
expect(result.summary.totalDistance).toBe('0');
expect(result.summary.averageDistance).toBe('0');
expect(result.errors).toHaveLength(0);
});
});
describe('Inclusive vs Exclusive calculations', () => {
it('should calculate inclusive distances correctly', () => {
const result = calculateIPDistances([
'192.168.1.1 -> 192.168.1.5',
'192.168.1.1 -> 192.168.1.1'
], true);
expect(result.calculations[0].distance).toBe('5');
expect(result.calculations[1].distance).toBe('1'); // same address inclusive
});
it('should calculate exclusive distances correctly', () => {
const result = calculateIPDistances([
'192.168.1.1 -> 192.168.1.5',
'192.168.1.1 -> 192.168.1.1'
], false);
expect(result.calculations[0].distance).toBe('4');
expect(result.calculations[1].distance).toBe('0'); // same address exclusive
});
});
describe('Intermediate address generation', () => {
it('should not generate intermediates when disabled', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.1.10'], true, false);
expect(result.calculations[0].intermediateAddresses).toHaveLength(0);
});
it('should generate sample intermediates for large ranges', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.2.1'], true, true);
expect(result.calculations[0].intermediateAddresses).toHaveLength(10); // default max
});
it('should generate all intermediates for small ranges', () => {
const result = calculateIPDistances(['192.168.1.1 -> 192.168.1.3'], true, true);
expect(result.calculations[0].intermediateAddresses).toEqual(['192.168.1.2']);
});
it('should handle IPv6 intermediate generation', () => {
const result = calculateIPDistances(['::1 -> ::4'], true, true);
expect(result.calculations[0].intermediateAddresses).toEqual(['::2', '::3']);
});
});
describe('Edge cases', () => {
it('should handle maximum IPv4 addresses', () => {
const result = calculateIPDistances(['0.0.0.0 -> 255.255.255.255']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.version).toBe(4);
expect(calc.distance).toBe('4,294,967,296'); // 2^32
});
it('should handle IPv6 loopback addresses', () => {
const result = calculateIPDistances(['::1 -> ::1']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('1'); // inclusive
expect(calc.version).toBe(6);
});
it('should handle private IP ranges', () => {
const result = calculateIPDistances(['10.0.0.1 -> 10.0.0.254']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('254');
expect(calc.version).toBe(4);
});
it('should handle link-local addresses', () => {
const result = calculateIPDistances(['169.254.1.1 -> 169.254.1.10']);
expect(result.calculations).toHaveLength(1);
const calc = result.calculations[0];
expect(calc.isValid).toBe(true);
expect(calc.distance).toBe('10');
expect(calc.version).toBe(4);
});
});
});
@@ -0,0 +1,369 @@
import { describe, it, expect } from 'vitest';
import {
validateIPv4,
validateIPv6,
ipv4ToIPv6,
ipv6ToIPv4,
getIPv6Info,
expandIPv6,
compressIPv6
} from '../../../src/lib/utils/ip-family-conversions.js';
describe('IP Family Conversion Utilities', () => {
describe('IPv4 validation', () => {
it('should validate correct IPv4 addresses', () => {
const validIPs = [
'0.0.0.0',
'127.0.0.1',
'192.168.1.1',
'255.255.255.255',
'10.0.0.1',
'172.16.0.1'
];
validIPs.forEach(ip => {
const result = validateIPv4(ip);
expect(result.valid).toBe(true);
expect(result.error).toBeUndefined();
});
});
it('should reject invalid IPv4 addresses', () => {
const invalidIPs = [
'256.1.1.1',
'1.256.1.1',
'1.1.256.1',
'1.1.1.256',
'1.1.1',
'1.1.1.1.1',
'abc.1.1.1',
'1.abc.1.1',
'192.168.1.',
'.192.168.1.1',
''
];
invalidIPs.forEach(ip => {
const result = validateIPv4(ip);
expect(result.valid).toBe(false);
expect(result.error).toBe('Invalid IPv4 format');
});
});
});
describe('IPv6 validation', () => {
it('should validate correct IPv6 addresses', () => {
const validIPs = [
'::1',
'::',
'2001:db8::1',
'2001:0db8:0000:0000:0000:0000:0000:0001',
'fe80::1',
'::ffff:192.0.2.1',
'::ffff:c000:0201',
'[2001:db8::1]',
'fc00::1',
'ff00::1'
];
validIPs.forEach(ip => {
const result = validateIPv6(ip);
expect(result.valid).toBe(true);
expect(result.error).toBeUndefined();
});
});
it('should reject invalid IPv6 addresses', () => {
const invalidIPs = [
'gggg::1',
'2001:db8:::1',
'2001:db8::1::1',
'2001:db8:1:2:3:4:5:6:7',
'2001:db8::12345',
''
];
invalidIPs.forEach(ip => {
const result = validateIPv6(ip);
expect(result.valid).toBe(false);
expect(result.error).toBe('Invalid IPv6 format');
});
});
});
describe('IPv4 to IPv6 conversion', () => {
it('should convert valid IPv4 to IPv4-mapped IPv6', () => {
const result = ipv4ToIPv6('192.0.2.1');
expect(result.success).toBe(true);
expect(result.result).toBe('::ffff:c000:0201');
expect(result.type).toBe('IPv4-mapped IPv6');
expect(result.details?.compressed).toBe('::ffff:c000:0201');
expect(result.details?.expanded).toBe('0000:0000:0000:0000:0000:ffff:c000:0201');
expect(result.details?.dotted).toBe('::ffff:192.0.2.1');
expect(result.details?.original).toBe('192.0.2.1');
});
it('should convert corner case IPv4 addresses', () => {
const testCases = [
{ ipv4: '0.0.0.0', expected: '::ffff:0000:0000' },
{ ipv4: '255.255.255.255', expected: '::ffff:ffff:ffff' },
{ ipv4: '127.0.0.1', expected: '::ffff:7f00:0001' },
{ ipv4: '10.0.0.1', expected: '::ffff:0a00:0001' }
];
testCases.forEach(({ ipv4, expected }) => {
const result = ipv4ToIPv6(ipv4);
expect(result.success).toBe(true);
expect(result.result).toBe(expected);
});
});
it('should reject invalid IPv4 for conversion', () => {
const result = ipv4ToIPv6('256.1.1.1');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid IPv4 format');
});
});
describe('IPv6 to IPv4 conversion', () => {
it('should convert IPv4-mapped IPv6 (hex format) to IPv4', () => {
const result = ipv6ToIPv4('::ffff:c000:0201');
expect(result.success).toBe(true);
expect(result.result).toBe('192.0.2.1');
expect(result.type).toBe('Extracted from IPv4-mapped IPv6');
expect(result.details?.ipv4).toBe('192.0.2.1');
expect(result.details?.original).toBe('::ffff:c000:0201');
expect(result.details?.hex1).toBe('c000');
expect(result.details?.hex2).toBe('0201');
});
it('should convert IPv4-mapped IPv6 (dotted format) to IPv4', () => {
const result = ipv6ToIPv4('::ffff:192.0.2.1');
expect(result.success).toBe(true);
expect(result.result).toBe('192.0.2.1');
expect(result.type).toBe('Extracted from IPv4-mapped IPv6');
expect(result.details?.ipv4).toBe('192.0.2.1');
expect(result.details?.original).toBe('::ffff:192.0.2.1');
});
it('should handle IPv6 addresses with brackets', () => {
const result = ipv6ToIPv4('[::ffff:192.0.2.1]');
expect(result.success).toBe(true);
expect(result.result).toBe('192.0.2.1');
});
it('should reject non-IPv4-mapped IPv6 addresses', () => {
const nonMappedAddresses = [
'2001:db8::1',
'fe80::1',
'::1',
'fc00::1'
];
nonMappedAddresses.forEach(ip => {
const result = ipv6ToIPv4(ip);
expect(result.success).toBe(false);
expect(result.error).toContain('not IPv4-mapped');
expect(result.details?.suggestion).toContain('::ffff:');
});
});
it('should reject invalid IPv6 for conversion', () => {
const result = ipv6ToIPv4('invalid::ipv6');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid IPv6 format');
});
});
describe('IPv6 information extraction', () => {
it('should identify loopback addresses', () => {
const info = getIPv6Info('::1');
expect(info.types).toContain('Loopback');
expect(info.description).toContain('loopback');
expect(info.cleaned).toBe('::1');
});
it('should identify unspecified addresses', () => {
const info = getIPv6Info('::');
expect(info.types).toContain('Unspecified');
expect(info.description).toContain('unspecified');
});
it('should identify IPv4-mapped addresses', () => {
const info = getIPv6Info('::ffff:192.0.2.1');
expect(info.types).toContain('IPv4-mapped');
expect(info.description).toContain('IPv4-mapped');
});
it('should identify link-local addresses', () => {
const info = getIPv6Info('fe80::1');
expect(info.types).toContain('Link-local');
expect(info.description).toContain('Link-local');
});
it('should identify unique local addresses', () => {
const fcInfo = getIPv6Info('fc00::1');
const fdInfo = getIPv6Info('fd00::1');
expect(fcInfo.types).toContain('Unique Local');
expect(fdInfo.types).toContain('Unique Local');
expect(fcInfo.description).toContain('Unique local');
});
it('should identify multicast addresses', () => {
const info = getIPv6Info('ff00::1');
expect(info.types).toContain('Multicast');
expect(info.description).toContain('multicast');
});
it('should identify global unicast addresses', () => {
const info = getIPv6Info('2001:db8::1');
expect(info.types).toContain('Global Unicast');
expect(info.description).toContain('Global unicast');
});
it('should handle brackets in IPv6 addresses', () => {
const info = getIPv6Info('[2001:db8::1]');
expect(info.cleaned).toBe('2001:db8::1');
expect(info.original).toBe('[2001:db8::1]');
});
});
describe('IPv6 expansion', () => {
it('should expand compressed IPv6 addresses', () => {
const testCases = [
{ compressed: '::1', expanded: '0000:0000:0000:0000:0000:0000:0000:0001' },
{ compressed: '::', expanded: '0000:0000:0000:0000:0000:0000:0000:0000' },
{ compressed: '2001:db8::1', expanded: '2001:0db8:0000:0000:0000:0000:0000:0001' },
{ compressed: '::ffff:192.0.2.1', expanded: '0000:0000:0000:0000:0000:0000:ffff:192.0.2.1' },
{ compressed: 'fe80::1', expanded: 'fe80:0000:0000:0000:0000:0000:0000:0001' },
{ compressed: '2001:db8:1::1', expanded: '2001:0db8:0001:0000:0000:0000:0000:0001' }
];
testCases.forEach(({ compressed, expanded }) => {
const result = expandIPv6(compressed);
expect(result).toBe(expanded);
});
});
it('should handle already expanded addresses', () => {
const expanded = '2001:0db8:0000:0000:0000:0000:0000:0001';
const result = expandIPv6(expanded);
expect(result).toBe(expanded);
});
it('should handle brackets', () => {
const result = expandIPv6('[::1]');
expect(result).toBe('0000:0000:0000:0000:0000:0000:0000:0001');
});
});
describe('IPv6 compression', () => {
it('should compress expanded IPv6 addresses', () => {
const testCases = [
{ expanded: '0000:0000:0000:0000:0000:0000:0000:0001', compressed: '::1' },
{ expanded: '0000:0000:0000:0000:0000:0000:0000:0000', compressed: '::' },
{ expanded: '2001:0db8:0000:0000:0000:0000:0000:0001', compressed: '2001:db8::1' },
{ expanded: 'fe80:0000:0000:0000:0000:0000:0000:0001', compressed: 'fe80::1' },
{ expanded: '2001:0db8:0001:0000:0000:0000:0000:0001', compressed: '2001:db8:1::1' }
];
testCases.forEach(({ expanded, compressed }) => {
const result = compressIPv6(expanded);
expect(result).toBe(compressed);
});
});
it('should remove leading zeros without compression', () => {
const result = compressIPv6('2001:0db8:0001:0002:0003:0004:0005:0006');
expect(result).toBe('2001:db8:1:2:3:4:5:6');
});
it('should compress longest zero sequence', () => {
const result = compressIPv6('2001:0000:0000:0000:0000:0000:0000:0001');
expect(result).toBe('2001::1');
});
it('should compress trailing zeros', () => {
const result = compressIPv6('2001:0db8:0000:0000:0000:0000:0000:0000');
expect(result).toBe('2001:db8::');
});
it('should compress leading zeros', () => {
const result = compressIPv6('0000:0000:0000:0000:0000:0000:0db8:0001');
expect(result).toBe('::db8:1');
});
it('should handle addresses with no compressible sequences', () => {
const result = compressIPv6('2001:0db8:0001:0002:0003:0004:0005:0006');
expect(result).toBe('2001:db8:1:2:3:4:5:6');
});
});
describe('Round-trip conversions', () => {
it('should maintain consistency in IPv4 to IPv6 and back', () => {
const originalIPv4 = '192.0.2.1';
const toIPv6Result = ipv4ToIPv6(originalIPv4);
expect(toIPv6Result.success).toBe(true);
const backToIPv4Result = ipv6ToIPv4(toIPv6Result.result!);
expect(backToIPv4Result.success).toBe(true);
expect(backToIPv4Result.result).toBe(originalIPv4);
});
it('should maintain consistency in IPv6 expansion and compression', () => {
const testAddresses = [
'::1',
'2001:db8::1',
'fe80::1',
'2001:db8:1::1'
];
testAddresses.forEach(original => {
const expanded = expandIPv6(original);
const compressed = compressIPv6(expanded);
expect(compressed).toBe(original);
});
});
});
describe('Edge cases', () => {
it('should handle empty strings gracefully', () => {
expect(validateIPv4('')).toEqual({ valid: false, error: 'Invalid IPv4 format' });
expect(validateIPv6('')).toEqual({ valid: false, error: 'Invalid IPv6 format' });
});
it('should handle whitespace', () => {
expect(validateIPv4(' 192.168.1.1 ')).toEqual({ valid: false, error: 'Invalid IPv4 format' });
expect(validateIPv6(' ::1 ')).toEqual({ valid: false, error: 'Invalid IPv6 format' });
});
it('should handle case insensitivity for IPv6', () => {
const upperCase = validateIPv6('2001:DB8::1');
const lowerCase = validateIPv6('2001:db8::1');
expect(upperCase.valid).toBe(true);
expect(lowerCase.valid).toBe(true);
});
it('should handle mixed case IPv4-mapped conversion', () => {
const result = ipv6ToIPv4('::FFFF:C000:0201');
expect(result.success).toBe(true);
expect(result.result).toBe('192.0.2.1');
});
});
});