Built MAC Address Converter & OUI Lookup

This commit is contained in:
Alicia Sykes committed 2025-10-10 23:15:29 +01:00
1 parent f259a510d1
commit 937c83898e
12 files changed
+4336 -1

No files matched your search

+2
View File
@@ -259,6 +259,8 @@ export const iconMap: Record<string, string> = {
map: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d="M112 191.2L112 490.2L208 445L208 146L112 191.2zM234.6 91.1C237.8 91.6 240.9 92.4 244 93.4L416.5 152.1L418.1 151.3L240 92C238.2 91.4 236.4 91.1 234.6 91.2zM256 148.2L256 449.3L384 492L384 191.7L256 148.2zM432 198L432 494L528 448.8L528 150.6L432 198z"/><path d="M576 112C576 103.7 571.7 96 564.7 91.6C557.7 87.2 548.8 86.8 541.4 90.5L416.5 152.1L244 93.4C230.3 88.7 215.3 89.6 202.1 95.7L77.8 154.3C69.4 158.2 64 166.7 64 176L64 528C64 536.2 68.2 543.9 75.1 548.3C82 552.7 90.7 553.2 98.2 549.7L225.5 489.8L396.2 546.7C409.9 551.3 424.7 550.4 437.8 544.2L562.2 485.7C570.6 481.7 576 473.3 576 464L576 112zM208 146.1L208 445.1L112 490.3L112 191.3L208 146.1zM256 449.4L256 148.3L384 191.8L384 492.1L256 449.4zM432 198L528 150.6L528 448.8L432 494L432 198z"/></svg>`,
signpost: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d="M144.4 192L144.4 288C144.4 296.8 151.6 304 160.4 304L458.3 304L513.2 240L458.3 176L160.4 176C151.6 176 144.4 183.2 144.4 192z"/><path d="M296.4 88C296.4 74.7 307.1 64 320.4 64C333.7 64 344.4 74.7 344.4 88L344.4 128L465.7 128C475 128 483.9 132.1 490 139.2L567.5 229.6C572.6 235.6 572.6 244.4 567.5 250.4L490 340.8C483.9 347.9 475 352 465.7 352L344.4 352L344.4 552C344.4 565.3 333.7 576 320.4 576C307.1 576 296.4 565.3 296.4 552L296.4 352L160.4 352C125.1 352 96.4 323.3 96.4 288L96.4 192C96.4 156.7 125.1 128 160.4 128L296.4 128L296.4 88zM296.4 304L458.3 304L513.2 240L458.3 176L160.4 176C151.6 176 144.4 183.2 144.4 192L144.4 288C144.4 296.8 151.6 304 160.4 304L296.4 304z"/></svg>`,
wifi: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d=""/><path d="M72.9 245.4C136.4 182.7 223.7 144 320.1 144C416.5 144 503.7 182.7 567.3 245.4C576.7 254.7 591.9 254.6 601.2 245.2C610.5 235.8 610.4 220.6 601 211.3C528.8 140 429.5 96 320.1 96C210.7 96 111.3 140 39.1 211.3C29.7 220.6 29.6 235.8 38.9 245.2C48.2 254.6 63.4 254.7 72.8 245.4zM320.1 320C373.7 320 421.7 343.9 454 381.7C462.6 391.8 477.8 393 487.8 384.4C497.8 375.8 499.1 360.6 490.5 350.6C449.5 302.6 388.3 272 320.1 272C251.9 272 190.8 302.5 149.7 350.6C141.1 360.7 142.3 375.8 152.4 384.4C162.5 393 177.6 391.8 186.2 381.7C218.5 343.9 266.5 320 320.1 320zM368.1 496C368.1 469.5 346.6 448 320.1 448C293.6 448 272.1 469.5 272.1 496C272.1 522.5 293.6 544 320.1 544C346.6 544 368.1 522.5 368.1 496z"/></svg>`,
sliders: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d="M112 432C112 449.7 126.3 464 144 464C161.7 464 176 449.7 176 432C176 414.3 161.7 400 144 400C126.3 400 112 414.3 112 432zM464 208C464 225.7 478.3 240 496 240C513.7 240 528 225.7 528 208C528 190.3 513.7 176 496 176C478.3 176 464 190.3 464 208z"/><path d="M144 464C126.3 464 112 449.7 112 432C112 414.3 126.3 400 144 400C161.7 400 176 414.3 176 432C176 449.7 161.7 464 144 464zM220.3 408C210.1 375.5 179.8 352 144 352C99.8 352 64 387.8 64 432C64 476.2 99.8 512 144 512C179.8 512 210.1 488.5 220.3 456L552 456C565.3 456 576 445.3 576 432C576 418.7 565.3 408 552 408L220.3 408zM528 208C528 225.7 513.7 240 496 240C478.3 240 464 225.7 464 208C464 190.3 478.3 176 496 176C513.7 176 528 190.3 528 208zM419.7 184L88 184C74.7 184 64 194.7 64 208C64 221.3 74.7 232 88 232L419.7 232C429.9 264.5 460.2 288 496 288C540.2 288 576 252.2 576 208C576 163.8 540.2 128 496 128C460.2 128 429.9 151.5 419.7 184z"/></svg>`,
'mac-lookup': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d="M48 160L48 480C48 488.8 55.2 496 64 496L384 496C392.8 496 400 488.8 400 480L400 160C400 151.2 392.8 144 384 144L64 144C55.2 144 48 151.2 48 160zM96 216C96 202.7 106.7 192 120 192C133.3 192 144 202.7 144 216L144 296C144 309.3 133.3 320 120 320C106.7 320 96 309.3 96 296L96 216zM192 216C192 202.7 202.7 192 216 192C229.3 192 240 202.7 240 216L240 296C240 309.3 229.3 320 216 320C202.7 320 192 309.3 192 296L192 216z"/><path d="M384 144C392.8 144 400 151.2 400 160L400 480C400 488.8 392.8 496 384 496L64 496C55.2 496 48 488.8 48 480L48 160C48 151.2 55.2 144 64 144L384 144zM64 96C28.7 96 0 124.7 0 160L0 480C0 515.3 28.7 544 64 544L384 544C419.3 544 448 515.3 448 480L448 160C448 124.7 419.3 96 384 96L64 96zM120 192C106.7 192 96 202.7 96 216L96 296C96 309.3 106.7 320 120 320C133.3 320 144 309.3 144 296L144 216C144 202.7 133.3 192 120 192zM216 192C202.7 192 192 202.7 192 216L192 296C192 309.3 202.7 320 216 320C229.3 320 240 309.3 240 296L240 216C240 202.7 229.3 192 216 192zM597.3 172C608.3 164.6 611.3 149.7 604 138.7C596.7 127.7 581.7 124.7 570.7 132L522.7 164C511.7 171.4 508.7 186.3 516 197.3C523.3 208.3 538.3 211.3 549.3 204L597.3 172zM536 296C522.7 296 512 306.7 512 320C512 333.3 522.7 344 536 344L616 344C629.3 344 640 333.3 640 320C640 306.7 629.3 296 616 296L536 296zM549.3 436C538.3 428.6 523.4 431.6 516 442.7C508.6 453.8 511.6 468.6 522.7 476L570.7 508C581.7 515.4 596.6 512.4 604 501.3C611.4 490.2 608.4 475.4 597.3 468L549.3 436z"/></svg>`,
// '': ``,
asterisk: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d=""/><path d="M320 64C333.3 64 344 74.7 344 88L344 278.3L508 183.2C519.5 176.5 534.2 180.5 540.8 191.9C547.4 203.3 543.5 218.1 532.1 224.7L367.8 320L532 415.2C543.5 421.8 547.4 436.5 540.7 448C534 459.5 519.4 463.4 507.9 456.7L344 361.7L344 552C344 565.3 333.3 576 320 576C306.7 576 296 565.3 296 552L296 361.7L132 456.8C120.5 463.5 105.8 459.5 99.2 448.1C92.6 436.7 96.5 421.9 108 415.2L272.2 320L108 224.8C96.5 218.1 92.6 203.4 99.2 192C105.8 180.6 120.5 176.6 132 183.3L296 278.3L296 88C296 74.7 306.7 64 320 64z"/></svg>`,
certificate: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><!--!Font Awesome Pro v7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2025 Fonticons, Inc.--><path opacity=".4" d="M208 128C208 119.2 215.2 112 224 112L336 112L336 200C336 239.8 368.2 272 408 272L496 272L496 512C496 520.8 488.8 528 480 528L288 528L288 504.8C317.8 473.3 336 430.8 336 384C336 303.4 281.9 235.5 208 214.6L208 128z"/><path d="M224 112L336 112L336 200C336 239.8 368.2 272 408 272L496 272L496 512C496 520.8 488.8 528 480 528L288 528L288 576L480 576C515.3 576 544 547.3 544 512L544 250.5C544 233.5 537.3 217.2 525.3 205.2L402.7 82.7C390.7 70.7 374.5 64 357.5 64L224 64C188.7 64 160 92.7 160 128L160 208C176.6 208 192.7 210.3 208 214.6L208 128C208 119.2 215.2 112 224 112zM384 131.9L476.1 224L408 224C394.7 224 384 213.3 384 200L384 131.9zM288 384C288 313.3 230.7 256 160 256C89.3 256 32 313.3 32 384C32 424.4 50.7 460.5 80 483.9L80 589C80 599.5 88.5 608 99 608C102.3 608 105.5 607.1 108.4 605.5L160 576L211.6 605.5C214.5 607.1 217.7 608 221 608C231.5 608 240 599.5 240 589L240 483.9C269.3 460.4 288 424.4 288 384zM160 336C186.5 336 208 357.5 208 384C208 410.5 186.5 432 160 432C133.5 432 112 410.5 112 384C112 357.5 133.5 336 160 336z"/></svg>`,
+31
View File
@@ -274,6 +274,13 @@ export const SUB_NAV: Record<string, (NavItem | NavGroup)[]> = {
},
],
},
{
href: makePath('/cidr/range-to-cidr'),
label: 'IP Range to CIDR',
description: 'Convert IP address ranges (start-end) into minimal CIDR blocks',
icon: 'sliders',
keywords: ['range', 'cidr', 'convert', 'converter', 'ip', 'start', 'end', 'blocks', 'firewall', 'acl'],
},
{
href: makePath('/cidr/summarize'),
label: 'CIDR Summarizer',
@@ -721,6 +728,30 @@ export const SUB_NAV: Record<string, (NavItem | NavGroup)[]> = {
'ipv6',
],
},
{
href: makePath('/ip-address-convertor/mac-address'),
label: 'MAC Address Converter',
description: 'Convert MAC addresses between formats and identify manufacturer from OUI database',
icon: 'mac-lookup',
keywords: [
'mac',
'address',
'converter',
'format',
'oui',
'manufacturer',
'vendor',
'colon',
'hyphen',
'cisco',
'dot',
'notation',
'ethernet',
'hardware',
'layer2',
'ieee',
],
},
],
},
],
+192
View File
@@ -0,0 +1,192 @@
export const macAddressContent = {
title: 'MAC Address Converter & OUI Lookup',
description: 'Convert MAC addresses between formats and identify manufacturers',
sections: {
whatIsMAC: {
title: 'What is a MAC Address?',
content:
'A MAC (Media Access Control) address is a unique 48-bit (6-byte) identifier assigned to network interface controllers (NICs) for communications on the physical network segment. It operates at Layer 2 (Data Link Layer) of the OSI model and is typically displayed as six groups of two hexadecimal digits (e.g., 00:1A:2B:3C:4D:5E).',
},
structure: {
title: 'MAC Address Structure',
components: [
{
component: 'OUI (Organizationally Unique Identifier)',
description:
'First 24 bits (3 bytes) assigned by IEEE to manufacturers. Identifies who made the network interface.',
},
{
component: 'NIC Specific (Device ID)',
description: 'Last 24 bits (3 bytes) assigned by the manufacturer to uniquely identify the specific device.',
},
{
component: 'I/G bit (Individual/Group)',
description:
'Bit 0 of first octet: 0 = Unicast (single destination), 1 = Multicast/Broadcast (multiple destinations).',
},
{
component: 'U/L bit (Universal/Local)',
description:
'Bit 1 of first octet: 0 = Universally administered (manufacturer-assigned), 1 = Locally administered (software-assigned).',
},
],
example: {
address: '3C:22:FB:A1:B2:C3',
breakdown: [
'OUI: 3C:22:FB (Apple, Inc.)',
'Device ID: A1:B2:C3',
'First octet binary: 00111100 (I/G=0, U/L=0) → Universal Unicast',
],
},
},
addressTypes: {
title: 'MAC Address Types',
types: [
{
type: 'Universal Unicast',
description: 'Standard manufacturer-assigned addresses. Most common type for physical network cards.',
},
{
type: 'Locally Administered Unicast',
description:
'Software-assigned addresses used in virtual machines, VPNs, and software-defined networking. Second hex digit is 2, 3, 6, 7, A, B, E, or F.',
},
{
type: 'Multicast',
description:
'Used for one-to-many communication. First octet has LSB set to 1 (e.g., 01:00:5E:xx:xx:xx for IPv4 multicast).',
},
{
type: 'Broadcast',
description: 'FF:FF:FF:FF:FF:FF - Reaches all devices on the local network segment.',
},
],
},
formats: {
title: 'Common MAC Address Formats',
formats: [
{
format: 'Colon notation',
example: '00:1A:2B:3C:4D:5E',
usage: 'Standard on Linux, BSD, macOS',
},
{
format: 'Hyphen notation',
example: '00-1A-2B-3C-4D-5E',
usage: 'Common on Windows systems',
},
{
format: 'Cisco/Dot notation',
example: '001A.2B3C.4D5E',
usage: 'Used in Cisco IOS and NX-OS',
},
{
format: 'Bare format',
example: '001A2B3C4D5E',
usage: 'Common in databases and APIs',
},
{
format: 'EUI-64',
example: '02:1A:2B:FF:FE:3C:4D:5E',
usage: 'Extended format used for IPv6 interface IDs (inserts FFFE and flips U/L bit)',
},
],
},
ouiLookup: {
title: 'OUI Lookup and Block Types',
content: 'The IEEE Registration Authority manages OUI assignments. There are different block sizes:',
blockTypes: [
{
type: 'MA-L (Large)',
description: '24-bit prefix, provides 16,777,216 addresses. Standard OUI assignment for large manufacturers.',
},
{
type: 'MA-M (Medium)',
description: '28-bit prefix, provides 1,048,576 addresses. For medium-sized organizations.',
},
{
type: 'MA-S (Small)',
description: '36-bit prefix, provides 4,096 addresses. For smaller organizations or specific products.',
},
{
type: 'CID (Company ID)',
description: 'Special identifier for company-specific uses.',
},
],
lookupInfo:
'OUI lookups query the IEEE database to identify the manufacturer and registration details associated with a given MAC address prefix.',
},
specialAddresses: {
title: 'Special and Reserved MAC Addresses',
addresses: [
{
address: 'FF:FF:FF:FF:FF:FF',
type: 'Broadcast',
description: 'All devices on local segment',
},
{
address: '01:00:5E:xx:xx:xx',
type: 'IPv4 Multicast',
description: 'Maps to IPv4 multicast addresses (224.0.0.0/4)',
},
{
address: '33:33:xx:xx:xx:xx',
type: 'IPv6 Multicast',
description: 'Maps to IPv6 multicast addresses (FF00::/8)',
},
{
address: '00:00:5E:xx:xx:xx',
type: 'IANA Reserved',
description: 'IANA-managed reserved addresses',
},
{
address: 'Various',
type: 'Link-local',
description: 'Vendor-specific link-local addresses for protocols like LLDP, STP, VRRP',
},
{
address: 'xx:x2-F:xx:xx:xx:xx',
type: 'Privacy MAC',
description: 'Randomized addresses (U/L bit set) used by modern devices to prevent tracking',
},
],
},
useCases: {
title: 'Common Use Cases',
cases: [
{
useCase: 'Network Troubleshooting',
description: 'Identify devices on the network, track down rogue devices, or diagnose connectivity issues',
},
{
useCase: 'Security and Access Control',
description: 'MAC filtering for wireless networks, port security on switches, device whitelisting',
},
{
useCase: 'Asset Management',
description: 'Inventory network devices by manufacturer, track hardware deployments',
},
{
useCase: 'Virtualization',
description: 'Assign locally administered MACs to virtual machines and containers',
},
{
useCase: 'Format Conversion',
description: 'Convert between different notations for different systems and tools',
},
{
useCase: 'Privacy Analysis',
description: 'Identify if devices are using randomized MACs for privacy protection',
},
],
},
},
quickTips: [
'MAC addresses are only unique within a local network segment; routing between networks uses IP addresses',
'The second character of a MAC address reveals important info: Even = Universal, Odd = Multicast, 2/3/6/7/A/B/E/F = Locally administered',
'Virtual machines and modern smartphones often use locally administered (randomized) MACs for privacy',
'Not all 48-bit combinations are valid - some ranges are reserved for special purposes',
"MAC spoofing can change a device's MAC address in software, but doesn't change the hardware address",
'For IPv6 SLAAC, MAC addresses are converted to EUI-64 by inserting FFFE in the middle and flipping the U/L bit',
],
};
+250
View File
@@ -0,0 +1,250 @@
// MAC Address formatting and OUI lookup utilities
export interface MACFormat {
colon: string; // 00:1A:2B:3C:4D:5E
hyphen: string; // 00-1A-2B-3C-4D-5E
cisco: string; // 001A.2B3C.4D5E
bare: string; // 001A2B3C4D5E
bareUppercase: string; // 001A2B3C4D5E
bareLowercase: string; // 001a2b3c4d5e
eui64: string; // 00:1A:2B:FF:FE:3C:4D:5E
ipv6Style: string; // 001A:2B3C:4D5E
spaceSeparated: string; // 00 1A 2B 3C 4D 5E
decimalOctets: string; // 0.26.43.60.77.94
reverse: string; // 5E:4D:3C:2B:1A:00
prefixedMac: string; // MAC=00:1A:2B:3C:4D:5E
prefixedHwaddr: string; // HWaddr 00:1A:2B:3C:4D:5E
slashSeparated: string; // 00/1A/2B/3C/4D/5E
prefixedBare: string; // MAC001A2B3C4D5E
prefixedAddr: string; // addr001A2B3C4D5E
}
export interface OUIInfo {
oui: string;
manufacturer: string | null;
found: boolean;
country?: string;
address?: string;
blockType?: string; // MA-L, MA-M, MA-S, CID
blockStart?: string;
blockEnd?: string;
blockSize?: number;
isPrivate?: boolean;
isRand?: boolean;
updated?: string;
}
export interface MACConversionResult {
input: string;
isValid: boolean;
normalized: string; // Uppercase, no separators
formats: MACFormat;
oui: OUIInfo;
details: {
isUniversal: boolean; // U/L bit
isUnicast: boolean; // I/G bit
binary: string;
};
error?: string;
}
/**
* Parse MAC address from various formats
*/
function parseMACAddress(input: string): string | null {
// Remove all separators and whitespace
const cleaned = input.replace(/[:\-.\s]/g, '').toUpperCase();
// Must be exactly 12 hex characters
if (!/^[0-9A-F]{12}$/.test(cleaned)) {
return null;
}
return cleaned;
}
/**
* Format MAC address in different styles
*/
function formatMAC(normalized: string): MACFormat {
const upper = normalized.toUpperCase();
const lower = normalized.toLowerCase();
const octets = upper.match(/.{1,2}/g)!;
// EUI-64: Insert FFFE in the middle and flip U/L bit (bit 1 of first octet)
const firstOctet = parseInt(octets[0], 16);
const flippedFirstOctet = (firstOctet ^ 0x02).toString(16).padStart(2, '0').toUpperCase();
const eui64 = `${flippedFirstOctet}:${octets[1]}:${octets[2]}:FF:FE:${octets[3]}:${octets[4]}:${octets[5]}`;
return {
colon: octets.join(':'),
hyphen: octets.join('-'),
cisco: `${upper.slice(0, 4)}.${upper.slice(4, 8)}.${upper.slice(8, 12)}`,
bare: upper,
bareUppercase: upper,
bareLowercase: lower,
eui64,
ipv6Style: `${upper.slice(0, 4)}:${upper.slice(4, 8)}:${upper.slice(8, 12)}`,
spaceSeparated: octets.join(' '),
decimalOctets: octets.map((o) => parseInt(o, 16)).join('.'),
reverse: [...octets].reverse().join(':'),
prefixedMac: `MAC=${octets.join(':')}`,
prefixedHwaddr: `HWaddr ${octets.join(':')}`,
slashSeparated: octets.join('/'),
prefixedBare: `MAC${upper}`,
prefixedAddr: `addr${upper}`,
};
}
/**
* Extract OUI (first 3 octets) and look up manufacturer
*/
async function lookupOUI(normalized: string): Promise<OUIInfo> {
const oui = normalized.slice(0, 6).toUpperCase();
const ouiFormatted = oui.match(/.{1,2}/g)!.join(':');
try {
const response = await fetch(`/api/internal/mac-lookup?oui=${encodeURIComponent(ouiFormatted)}`);
if (!response.ok) {
return {
oui: ouiFormatted,
manufacturer: null,
found: false,
};
}
const data = await response.json();
if (!data.found) {
return {
oui: ouiFormatted,
manufacturer: null,
found: false,
};
}
return {
oui: ouiFormatted,
manufacturer: data.manufacturer,
found: true,
country: data.country,
address: data.address,
blockType: data.blockType,
blockStart: data.blockStart,
blockEnd: data.blockEnd,
blockSize: data.blockSize,
isPrivate: data.isPrivate,
isRand: data.isRand,
updated: data.updated,
};
} catch {
return {
oui: ouiFormatted,
manufacturer: null,
found: false,
};
}
}
/**
* Get MAC address details (U/L bit, I/G bit)
*/
function getMACDetails(normalized: string): {
isUniversal: boolean;
isUnicast: boolean;
binary: string;
} {
const bytes = normalized.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16));
const binary = bytes.map((b) => b.toString(2).padStart(8, '0')).join('');
// U/L bit: bit 1 of first octet (0 = universal, 1 = local)
const ulBit = (bytes[0] & 0x02) !== 0;
const isUniversal = !ulBit;
// I/G bit: bit 0 of first octet (0 = unicast, 1 = multicast)
const igBit = (bytes[0] & 0x01) !== 0;
const isUnicast = !igBit;
return {
isUniversal,
isUnicast,
binary,
};
}
/**
* Convert a MAC address to all formats with OUI lookup
*/
export async function convertMACAddress(input: string): Promise<MACConversionResult> {
const normalized = parseMACAddress(input);
if (!normalized) {
return {
input,
isValid: false,
normalized: '',
formats: {
colon: '',
hyphen: '',
cisco: '',
bare: '',
bareUppercase: '',
bareLowercase: '',
eui64: '',
ipv6Style: '',
spaceSeparated: '',
decimalOctets: '',
reverse: '',
prefixedMac: '',
prefixedHwaddr: '',
slashSeparated: '',
prefixedBare: '',
prefixedAddr: '',
},
oui: { oui: '', manufacturer: null, found: false },
details: {
isUniversal: false,
isUnicast: false,
binary: '',
},
error: 'Invalid MAC address format. Expected 12 hexadecimal characters (e.g., 00:1A:2B:3C:4D:5E)',
};
}
const oui = await lookupOUI(normalized);
return {
input,
isValid: true,
normalized,
formats: formatMAC(normalized),
oui,
details: getMACDetails(normalized),
};
}
/**
* Convert multiple MAC addresses
*/
export async function convertMACAddresses(inputs: string[]): Promise<{
conversions: MACConversionResult[];
summary: {
total: number;
valid: number;
invalid: number;
withOUI: number;
};
}> {
const conversions = await Promise.all(inputs.map(convertMACAddress));
return {
conversions,
summary: {
total: conversions.length,
valid: conversions.filter((c) => c.isValid).length,
invalid: conversions.filter((c) => !c.isValid).length,
withOUI: conversions.filter((c) => c.isValid && c.oui.found).length,
},
};
}
+355
View File
@@ -0,0 +1,355 @@
// IP Range to CIDR conversion utilities
import { validateIPv4Detailed, validateIPv6Detailed } from './ip-validation.js';
export interface CIDRBlock {
cidr: string;
network: string;
prefix: number;
firstIP: string;
lastIP: string;
totalIPs: string;
}
export interface RangeConversionResult {
startIP: string;
endIP: string;
isValid: boolean;
ipVersion: 4 | 6 | null;
cidrs: CIDRBlock[];
totalBlocks: number;
totalAddresses: string;
error?: string;
}
/**
* Convert IPv4 address to BigInt
*/
function ipv4ToBigInt(ip: string): bigint {
const octets = ip.split('.').map(Number);
return (BigInt(octets[0]) << 24n) | (BigInt(octets[1]) << 16n) | (BigInt(octets[2]) << 8n) | BigInt(octets[3]);
}
/**
* Convert BigInt to IPv4 address string
*/
function bigIntToIPv4(num: bigint): string {
return [
Number((num >> 24n) & 0xffn),
Number((num >> 16n) & 0xffn),
Number((num >> 8n) & 0xffn),
Number(num & 0xffn),
].join('.');
}
/**
* Convert IPv6 address to BigInt
*/
function ipv6ToBigInt(ip: string): bigint {
// First expand to full form
const result = validateIPv6Detailed(ip);
if (!result.isValid || !result.details.normalizedForm) {
throw new Error('Invalid IPv6 address');
}
const fullForm = result.details.normalizedForm;
const groups = fullForm.split(':');
let num = 0n;
for (const group of groups) {
num = (num << 16n) | BigInt(parseInt(group, 16));
}
return num;
}
/**
* Convert BigInt to IPv6 address string
*/
function bigIntToIPv6(num: bigint): string {
const groups: string[] = [];
for (let i = 0; i < 8; i++) {
const shift = BigInt(112 - i * 16);
const group = Number((num >> shift) & 0xffffn);
groups.push(group.toString(16).padStart(4, '0'));
}
return groups.join(':');
}
/**
* Compress IPv6 address to canonical form
*/
function compressIPv6(ip: string): string {
const groups = ip.split(':');
// Find longest sequence of zero groups
let bestStart = -1;
let bestLength = 0;
let currentStart = -1;
let currentLength = 0;
for (let i = 0; i < groups.length; i++) {
if (groups[i] === '0000' || groups[i] === '0') {
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;
}
// Remove leading zeros from groups
let result = groups.map((g) => g.replace(/^0+/, '') || '0').join(':');
// Apply :: compression if found
if (bestStart !== -1) {
const beforeZeros = groups.slice(0, bestStart).map((g) => g.replace(/^0+/, '') || '0');
const afterZeros = groups.slice(bestStart + bestLength).map((g) => g.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;
}
/**
* Convert IP range to minimal set of CIDR blocks (IPv4)
*/
function rangeToCIDRv4(startIP: string, endIP: string): CIDRBlock[] {
let startNum = ipv4ToBigInt(startIP);
const endNum = ipv4ToBigInt(endIP);
const cidrs: CIDRBlock[] = [];
while (startNum <= endNum) {
// Find the largest prefix that fits
let prefix = 32;
// Find trailing zeros in startNum (alignment)
let trailingZeros = 0;
for (let i = 0; i < 32; i++) {
if ((startNum & (1n << BigInt(i))) !== 0n) {
break;
}
trailingZeros++;
}
// Maximum prefix based on alignment
const maxPrefixFromAlignment = 32 - trailingZeros;
// Find maximum prefix that doesn't exceed endNum
let maxPrefixFromRange = 32;
for (let p = 0; p <= 32; p++) {
const blockSize = 2n ** BigInt(32 - p);
const blockEnd = startNum + blockSize - 1n;
if (blockEnd <= endNum) {
maxPrefixFromRange = p;
break;
}
}
prefix = Math.max(maxPrefixFromAlignment, maxPrefixFromRange);
const blockSize = 2n ** BigInt(32 - prefix);
const blockEnd = startNum + blockSize - 1n;
const networkAddr = bigIntToIPv4(startNum);
const lastAddr = bigIntToIPv4(blockEnd);
cidrs.push({
cidr: `${networkAddr}/${prefix}`,
network: networkAddr,
prefix,
firstIP: networkAddr,
lastIP: lastAddr,
totalIPs: blockSize.toString(),
});
startNum = blockEnd + 1n;
}
return cidrs;
}
/**
* Convert IP range to minimal set of CIDR blocks (IPv6)
*/
function rangeToCIDRv6(startIP: string, endIP: string): CIDRBlock[] {
let startNum = ipv6ToBigInt(startIP);
const endNum = ipv6ToBigInt(endIP);
const cidrs: CIDRBlock[] = [];
while (startNum <= endNum) {
// Find the largest prefix that fits
let prefix = 128;
// Find trailing zeros in startNum (alignment)
let trailingZeros = 0;
for (let i = 0; i < 128; i++) {
if ((startNum & (1n << BigInt(i))) !== 0n) {
break;
}
trailingZeros++;
}
// Maximum prefix based on alignment
const maxPrefixFromAlignment = 128 - trailingZeros;
// Find maximum prefix that doesn't exceed endNum
let maxPrefixFromRange = 128;
for (let p = 0; p <= 128; p++) {
const blockSize = 2n ** BigInt(128 - p);
const blockEnd = startNum + blockSize - 1n;
if (blockEnd <= endNum) {
maxPrefixFromRange = p;
break;
}
}
prefix = Math.max(maxPrefixFromAlignment, maxPrefixFromRange);
const blockSize = 2n ** BigInt(128 - prefix);
const blockEnd = startNum + blockSize - 1n;
const networkAddr = bigIntToIPv6(startNum);
const lastAddr = bigIntToIPv6(blockEnd);
const compressedNetwork = compressIPv6(networkAddr);
const compressedLast = compressIPv6(lastAddr);
cidrs.push({
cidr: `${compressedNetwork}/${prefix}`,
network: compressedNetwork,
prefix,
firstIP: compressedNetwork,
lastIP: compressedLast,
totalIPs: blockSize.toString(),
});
startNum = blockEnd + 1n;
}
return cidrs;
}
/**
* Convert an IP range (start IP - end IP) to minimal CIDR blocks
*/
export function convertRangeToCIDR(startIP: string, endIP: string): RangeConversionResult {
// Validate start IP
const startResult = validateIPv4Detailed(startIP.trim());
const startResult6 = validateIPv6Detailed(startIP.trim());
let startVersion: 4 | 6 | null = null;
let normalizedStart = '';
if (startResult.isValid) {
startVersion = 4;
normalizedStart = startResult.details.normalizedForm || startIP;
} else if (startResult6.isValid) {
startVersion = 6;
normalizedStart = startResult6.details.normalizedForm || startIP;
} else {
return {
startIP,
endIP,
isValid: false,
ipVersion: null,
cidrs: [],
totalBlocks: 0,
totalAddresses: '0',
error: `Invalid start IP address: ${startIP}`,
};
}
// Validate end IP
const endResult = validateIPv4Detailed(endIP.trim());
const endResult6 = validateIPv6Detailed(endIP.trim());
let endVersion: 4 | 6 | null = null;
let normalizedEnd = '';
if (endResult.isValid) {
endVersion = 4;
normalizedEnd = endResult.details.normalizedForm || endIP;
} else if (endResult6.isValid) {
endVersion = 6;
normalizedEnd = endResult6.details.normalizedForm || endIP;
} else {
return {
startIP,
endIP,
isValid: false,
ipVersion: null,
cidrs: [],
totalBlocks: 0,
totalAddresses: '0',
error: `Invalid end IP address: ${endIP}`,
};
}
// Check version match
if (startVersion !== endVersion) {
return {
startIP,
endIP,
isValid: false,
ipVersion: null,
cidrs: [],
totalBlocks: 0,
totalAddresses: '0',
error: 'Start and end IP addresses must be the same version (both IPv4 or both IPv6)',
};
}
// Check order
const startNum = startVersion === 4 ? ipv4ToBigInt(normalizedStart) : ipv6ToBigInt(normalizedStart);
const endNum = endVersion === 4 ? ipv4ToBigInt(normalizedEnd) : ipv6ToBigInt(normalizedEnd);
if (startNum > endNum) {
return {
startIP,
endIP,
isValid: false,
ipVersion: startVersion,
cidrs: [],
totalBlocks: 0,
totalAddresses: '0',
error: 'Start IP must be less than or equal to end IP',
};
}
// Convert to CIDR blocks
const cidrs =
startVersion === 4 ? rangeToCIDRv4(normalizedStart, normalizedEnd) : rangeToCIDRv6(normalizedStart, normalizedEnd);
const totalAddresses = (endNum - startNum + 1n).toString();
return {
startIP: startVersion === 4 ? normalizedStart : compressIPv6(normalizedStart),
endIP: endVersion === 4 ? normalizedEnd : compressIPv6(normalizedEnd),
isValid: true,
ipVersion: startVersion,
cidrs,
totalBlocks: cidrs.length,
totalAddresses,
};
}
@@ -0,0 +1,50 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url }) => {
const oui = url.searchParams.get('oui');
if (!oui) {
return json({ error: 'OUI parameter is required' }, { status: 400 });
}
try {
// Use maclookup.app API for detailed information
const cleanOui = oui.replace(/[:-]/g, '');
const response = await fetch(`https://api.maclookup.app/v2/macs/${cleanOui}`, {
headers: {
'User-Agent': 'IP-Calc/1.0',
},
});
if (!response.ok) {
if (response.status === 404) {
return json({ found: false, manufacturer: null }, { status: 200 });
}
return json({ error: 'Failed to fetch OUI data' }, { status: response.status });
}
const data = await response.json();
if (!data.success || !data.found) {
return json({ found: false, manufacturer: null }, { status: 200 });
}
return json({
found: true,
manufacturer: data.company,
country: data.country,
address: data.address,
blockType: data.blockType, // MA-L, MA-M, MA-S, CID
blockStart: data.blockStart,
blockEnd: data.blockEnd,
blockSize: data.blockSize,
isPrivate: data.isPrivate,
isRand: data.isRand,
updated: data.updated,
});
} catch (error) {
console.error('MAC lookup error:', error);
return json({ error: 'Failed to fetch OUI data', found: false }, { status: 500 });
}
};
+759
View File
@@ -0,0 +1,759 @@
<script lang="ts">
import { convertRangeToCIDR, type RangeConversionResult } from '$lib/utils/range-to-cidr.js';
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
let startIP = $state('192.168.1.10');
let endIP = $state('192.168.1.50');
let result = $state<RangeConversionResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
let selectedExampleIndex = $state<number | null>(null);
const examples = [
{ start: '192.168.1.10', end: '192.168.1.50', description: 'Small IPv4 range' },
{ start: '10.0.0.0', end: '10.0.0.255', description: 'IPv4 /24 network' },
{ start: '172.16.0.0', end: '172.16.3.255', description: 'IPv4 /22 equivalent' },
{ start: '2001:db8::', end: '2001:db8::ff', description: 'Small IPv6 range' },
];
function convertRange() {
if (!startIP.trim() || !endIP.trim()) {
result = null;
return;
}
result = convertRangeToCIDR(startIP, endIP);
}
async function copyToClipboard(text: string, id: string = text) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
function copyAllCIDRs() {
if (!result || !result.isValid) return;
const allCIDRs = result.cidrs.map((c) => c.cidr).join('\n');
copyToClipboard(allCIDRs, 'all-cidrs');
}
function loadExample(example: (typeof examples)[0], index: number) {
startIP = example.start;
endIP = example.end;
selectedExampleIndex = index;
convertRange();
}
function clearExampleSelection() {
selectedExampleIndex = null;
}
function exportResults(format: 'csv' | 'json' | 'txt') {
if (!result || !result.isValid) return;
const timestamp = new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-');
let content = '';
let filename = '';
if (format === 'csv') {
const headers = 'CIDR,Network,Prefix,First IP,Last IP,Total IPs';
const rows = result.cidrs.map(
(cidr) =>
`"${cidr.cidr}","${cidr.network}","${cidr.prefix}","${cidr.firstIP}","${cidr.lastIP}","${cidr.totalIPs}"`,
);
content = [headers, ...rows].join('\n');
filename = `range-to-cidr-${timestamp}.csv`;
} else if (format === 'json') {
content = JSON.stringify(result, null, 2);
filename = `range-to-cidr-${timestamp}.json`;
} else {
content = result.cidrs.map((c) => c.cidr).join('\n');
filename = `range-to-cidr-${timestamp}.txt`;
}
const blob = new Blob([content], {
type: format === 'csv' ? 'text/csv' : format === 'json' ? 'application/json' : 'text/plain',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// Auto-convert when inputs change
$effect(() => {
if (startIP.trim() && endIP.trim()) {
const timeoutId = setTimeout(convertRange, 300);
return () => clearTimeout(timeoutId);
}
});
</script>
<div class="card">
<header class="card-header">
<h2>IP Range to CIDR Converter</h2>
<p>Convert an IP address range (start IP → end IP) into the minimal set of CIDR blocks that cover the range</p>
</header>
<!-- Quick Examples -->
<div class="card examples-card">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h4>Quick Examples</h4>
</summary>
<div class="examples-grid">
{#each examples as example, i (i)}
<button
class="example-card"
class:selected={selectedExampleIndex === i}
onclick={() => loadExample(example, i)}
use:tooltip={`Convert ${example.start} - ${example.end}`}
>
<div class="example-range">
<code>{example.start}</code>
<Icon name="arrow-right" size="xs" />
<code>{example.end}</code>
</div>
<p>{example.description}</p>
</button>
{/each}
</div>
</details>
</div>
<!-- Input Form -->
<div class="card input-card">
<div class="card-content">
<div class="input-form">
<div class="input-row">
<div class="input-group">
<label for="start-ip" use:tooltip={{ text: 'Starting IP address of the range', position: 'top' }}>
Start IP Address
</label>
<input
id="start-ip"
type="text"
bind:value={startIP}
placeholder="192.168.1.10"
onchange={clearExampleSelection}
/>
</div>
<div class="range-arrow">
<Icon name="arrow-right" />
</div>
<div class="input-group">
<label for="end-ip" use:tooltip={{ text: 'Ending IP address of the range', position: 'top' }}>
End IP Address
</label>
<input
id="end-ip"
type="text"
bind:value={endIP}
placeholder="192.168.1.50"
onchange={clearExampleSelection}
/>
</div>
<button class="convert-btn" onclick={convertRange}>
<Icon name="zap" size="sm" />
Convert
</button>
</div>
</div>
</div>
</div>
{#if result}
<div class="results">
{#if result.error}
<div class="error-box">
<Icon name="alert-triangle" />
<div>
<h3>Error</h3>
<p>{result.error}</p>
</div>
</div>
{:else if result.isValid}
<div class="summary">
<h3>Conversion Result</h3>
<div class="summary-grid">
<div class="summary-item">
<span class="summary-label">IP Version</span>
<span class="summary-value">IPv{result.ipVersion}</span>
</div>
<div class="summary-item">
<span class="summary-label">Start IP</span>
<code class="summary-value">{result.startIP}</code>
</div>
<div class="summary-item">
<span class="summary-label">End IP</span>
<code class="summary-value">{result.endIP}</code>
</div>
<div class="summary-item">
<span class="summary-label">Total Addresses</span>
<span class="summary-value">{result.totalAddresses.toLocaleString()}</span>
</div>
<div class="summary-item highlight">
<span class="summary-label">CIDR Blocks</span>
<span class="summary-value">{result.totalBlocks}</span>
</div>
</div>
</div>
<div class="cidr-results">
<div class="cidr-header">
<h3>CIDR Blocks ({result.totalBlocks})</h3>
<div class="action-buttons">
<button onclick={copyAllCIDRs} class="action-btn">
<Icon name={copiedStates['all-cidrs'] ? 'check' : 'copy'} />
{copiedStates['all-cidrs'] ? 'Copied!' : 'Copy All'}
</button>
<button onclick={() => exportResults('txt')} class="action-btn">
<Icon name="download" />
Export TXT
</button>
<button onclick={() => exportResults('csv')} class="action-btn">
<Icon name="download" />
Export CSV
</button>
<button onclick={() => exportResults('json')} class="action-btn">
<Icon name="download" />
Export JSON
</button>
</div>
</div>
<div class="cidr-list">
{#each result.cidrs as cidr, index (cidr.cidr)}
<div class="cidr-block">
<div class="cidr-main">
<span class="cidr-index">{index + 1}</span>
<code class="cidr-notation">{cidr.cidr}</code>
<button
class="copy-btn"
onclick={() => copyToClipboard(cidr.cidr, `cidr-${index}`)}
use:tooltip={{ text: 'Copy CIDR', position: 'top' }}
>
<Icon name={copiedStates[`cidr-${index}`] ? 'check' : 'copy'} />
</button>
</div>
<div class="cidr-details">
<div class="detail">
<span class="detail-label">Network:</span>
<code>{cidr.network}</code>
</div>
<div class="detail">
<span class="detail-label">Prefix:</span>
<code>/{cidr.prefix}</code>
</div>
<div class="detail">
<span class="detail-label">Range:</span>
<code>{cidr.firstIP} - {cidr.lastIP}</code>
</div>
<div class="detail">
<span class="detail-label">Addresses:</span>
<span>{BigInt(cidr.totalIPs).toLocaleString()}</span>
</div>
</div>
</div>
{/each}
</div>
</div>
{/if}
</div>
{/if}
<!-- About section moved to bottom -->
<div class="info-section">
<h3>About Range to CIDR</h3>
<div class="info-content">
<p>This tool converts arbitrary IP ranges into CIDR notation blocks:</p>
<ul>
<li><strong>Minimal set</strong>: Finds the smallest number of CIDR blocks</li>
<li><strong>Aligned blocks</strong>: CIDRs respect network boundaries</li>
<li><strong>IPv4 & IPv6</strong>: Supports both address families</li>
<li><strong>Exact coverage</strong>: All addresses in range are included</li>
</ul>
<p>Useful for converting firewall rules, ACLs, or vendor-provided IP ranges to CIDR format.</p>
</div>
</div>
</div>
<style lang="scss">
.card {
max-width: 90rem;
margin: 0 auto;
padding: var(--spacing-xl);
background: var(--bg-secondary);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-md);
}
.card-header {
margin-bottom: var(--spacing-xl);
h2 {
font-size: var(--font-size-2xl);
font-weight: 700;
color: var(--text-primary);
margin-bottom: var(--spacing-sm);
}
p {
font-size: var(--font-size-md);
color: var(--text-secondary);
line-height: 1.6;
}
}
// Examples card (matches diagnostics pages style)
.examples-card {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
margin-bottom: var(--spacing-lg);
box-shadow: var(--shadow-sm);
overflow: hidden;
.examples-details {
border: none;
background: none;
summary {
list-style: none;
cursor: pointer;
user-select: none;
&::-webkit-details-marker {
display: none;
}
}
.examples-summary {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-md);
cursor: pointer;
:global(svg) {
transition: transform var(--transition-fast);
color: var(--text-secondary);
}
h4 {
font-size: var(--font-size-md);
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
}
&[open] .examples-summary :global(svg) {
transform: rotate(90deg);
}
.examples-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: var(--spacing-sm);
padding: 0 var(--spacing-md) var(--spacing-md);
.example-card {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
padding: var(--spacing-md);
background: 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,
&.selected {
border-color: var(--color-primary);
background: var(--bg-primary);
}
.example-range {
display: flex;
align-items: center;
gap: var(--spacing-xs);
font-size: var(--font-size-sm);
code {
font-family: var(--font-mono);
color: var(--text-primary);
font-size: var(--font-size-xs);
}
}
p {
font-size: var(--font-size-xs);
color: var(--text-secondary);
margin: 0;
}
}
}
}
}
// Input card
.input-card {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
margin-bottom: var(--spacing-lg);
box-shadow: var(--shadow-sm);
padding: var(--spacing-sm);
.card-content {
padding: var(--spacing-md);
}
.input-form {
.input-row {
display: flex;
align-items: flex-end;
gap: var(--spacing-md);
@media (max-width: 768px) {
flex-direction: column;
align-items: stretch;
.range-arrow {
transform: rotate(90deg);
}
.convert-btn {
width: 100%;
}
}
.input-group {
flex: 1;
label {
display: block;
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--text-primary);
margin-bottom: var(--spacing-xs);
}
input {
width: 100%;
padding: var(--spacing-sm) var(--spacing-md);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
background: var(--bg-primary);
color: var(--text-primary);
font-family: var(--font-mono);
font-size: var(--font-size-md);
transition: border-color var(--transition-fast);
&:focus {
outline: none;
border-color: var(--color-primary);
}
}
}
.range-arrow {
display: flex;
align-items: center;
padding-bottom: var(--spacing-sm);
color: var(--text-secondary);
}
.convert-btn {
display: flex;
align-items: center;
justify-content: center;
gap: var(--spacing-xs);
padding: var(--spacing-sm) var(--spacing-lg);
background: var(--color-primary);
color: var(--bg-primary);
border: none;
border-radius: var(--radius-md);
font-size: var(--font-size-sm);
font-weight: 600;
cursor: pointer;
transition: all var(--transition-fast);
white-space: nowrap;
height: fit-content;
margin-bottom: 1px;
&:hover {
opacity: 0.9;
transform: translateY(-1px);
}
}
}
}
}
.results {
margin-top: var(--spacing-xl);
}
.error-box {
display: flex;
align-items: flex-start;
gap: var(--spacing-md);
padding: var(--spacing-md);
background: color-mix(in srgb, var(--color-error), transparent 90%);
border-left: 4px solid var(--color-error);
border-radius: var(--radius-md);
color: var(--color-error);
h3 {
font-size: var(--font-size-md);
font-weight: 600;
margin-bottom: var(--spacing-xs);
}
p {
font-size: var(--font-size-sm);
}
}
.summary {
margin-bottom: var(--spacing-xl);
h3 {
font-size: var(--font-size-lg);
font-weight: 600;
color: var(--text-primary);
margin-bottom: var(--spacing-md);
}
.summary-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: var(--spacing-md);
.summary-item {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
padding: var(--spacing-md);
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
&.highlight {
background: linear-gradient(
135deg,
color-mix(in srgb, var(--color-primary), transparent 95%),
color-mix(in srgb, var(--color-primary), transparent 98%)
);
border-color: var(--color-primary);
}
.summary-label {
font-size: var(--font-size-xs);
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.summary-value {
font-size: var(--font-size-lg);
font-weight: 700;
color: var(--text-primary);
&:is(code) {
font-family: var(--font-mono);
}
}
}
}
}
.cidr-results {
.cidr-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: var(--spacing-md);
flex-wrap: wrap;
gap: var(--spacing-md);
h3 {
font-size: var(--font-size-lg);
font-weight: 600;
color: var(--text-primary);
}
.action-buttons {
display: flex;
gap: var(--spacing-sm);
flex-wrap: wrap;
.action-btn {
display: flex;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-sm) var(--spacing-md);
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
color: var(--text-primary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: all var(--transition-fast);
&:hover {
background: var(--bg-primary);
border-color: var(--color-primary);
}
}
}
}
.cidr-list {
display: flex;
flex-direction: column;
gap: var(--spacing-md);
.cidr-block {
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
padding: var(--spacing-md);
border: 1px solid var(--border-primary);
transition: all var(--transition-fast);
.cidr-main {
display: flex;
align-items: center;
gap: var(--spacing-md);
margin-bottom: var(--spacing-sm);
.cidr-index {
display: flex;
align-items: center;
justify-content: center;
min-width: 2rem;
height: 2rem;
background: var(--color-primary);
border-radius: var(--radius-sm);
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--bg-primary);
}
.cidr-notation {
flex: 1;
font-family: var(--font-mono);
font-size: var(--font-size-lg);
font-weight: 600;
color: var(--text-primary);
}
.copy-btn {
padding: var(--spacing-sm);
background: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
display: flex;
align-items: center;
transition: color var(--transition-fast);
&:hover {
color: var(--color-primary);
}
}
}
.cidr-details {
padding-left: calc(2rem + var(--spacing-md));
display: flex;
gap: var(--spacing-lg);
flex-wrap: wrap;
@media (max-width: 640px) {
padding-left: 0;
grid-template-columns: 1fr;
}
.detail {
display: flex;
align-items: baseline;
gap: var(--spacing-xs);
font-size: var(--font-size-sm);
.detail-label {
color: var(--text-secondary);
font-weight: 500;
}
code {
font-family: var(--font-mono);
color: var(--text-primary);
background: var(--bg-primary);
}
span {
color: var(--text-primary);
}
}
}
}
}
}
// Info section at bottom
.info-section {
margin-top: var(--spacing-xl);
background: linear-gradient(
135deg,
color-mix(in srgb, var(--color-info), transparent 95%),
color-mix(in srgb, var(--color-info), transparent 98%)
);
border: 1px solid color-mix(in srgb, var(--color-info), transparent 80%);
border-radius: var(--radius-md);
padding: var(--spacing-lg);
h3 {
font-size: var(--font-size-lg);
font-weight: 600;
color: var(--text-primary);
margin-bottom: var(--spacing-md);
}
.info-content {
font-size: var(--font-size-sm);
color: var(--text-secondary);
line-height: 1.6;
p {
margin-bottom: var(--spacing-sm);
}
ul {
margin-left: var(--spacing-md);
margin-bottom: var(--spacing-sm);
li {
margin-bottom: var(--spacing-xs);
}
}
strong {
color: var(--text-primary);
}
}
}
</style>
File diff suppressed because it is too large. Load diff
+348
View File
@@ -0,0 +1,348 @@
import { describe, it, expect } from 'vitest';
import { macAddressContent } from '../../../src/lib/content/mac-address.js';
describe('MAC Address Content', () => {
it('should have title and description', () => {
expect(macAddressContent.title).toBeDefined();
expect(macAddressContent.title).toContain('MAC Address');
expect(macAddressContent.description).toBeDefined();
});
describe('What is MAC section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.whatIsMAC).toBeDefined();
expect(macAddressContent.sections.whatIsMAC.title).toBeDefined();
expect(macAddressContent.sections.whatIsMAC.content).toBeDefined();
});
it('should explain MAC addresses', () => {
expect(macAddressContent.sections.whatIsMAC.content).toContain('Media Access Control');
expect(macAddressContent.sections.whatIsMAC.content).toContain('48-bit');
});
});
describe('Structure section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.structure).toBeDefined();
expect(macAddressContent.sections.structure.title).toBeDefined();
expect(macAddressContent.sections.structure.components).toBeDefined();
expect(macAddressContent.sections.structure.example).toBeDefined();
});
it('should have at least 4 components', () => {
expect(macAddressContent.sections.structure.components.length).toBeGreaterThanOrEqual(4);
});
it('should include OUI component', () => {
const ouiComponent = macAddressContent.sections.structure.components.find(
(c) => c.component.includes('OUI')
);
expect(ouiComponent).toBeDefined();
expect(ouiComponent?.description).toContain('24 bits');
});
it('should include I/G bit component', () => {
const igComponent = macAddressContent.sections.structure.components.find(
(c) => c.component.includes('I/G')
);
expect(igComponent).toBeDefined();
expect(igComponent?.description).toContain('Bit 0');
});
it('should include U/L bit component', () => {
const ulComponent = macAddressContent.sections.structure.components.find(
(c) => c.component.includes('U/L')
);
expect(ulComponent).toBeDefined();
expect(ulComponent?.description).toContain('Bit 1');
});
it('should have valid example', () => {
expect(macAddressContent.sections.structure.example.address).toMatch(
/^[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}$/
);
expect(macAddressContent.sections.structure.example.breakdown).toBeInstanceOf(Array);
expect(macAddressContent.sections.structure.example.breakdown.length).toBeGreaterThan(0);
});
});
describe('Address Types section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.addressTypes).toBeDefined();
expect(macAddressContent.sections.addressTypes.title).toBeDefined();
expect(macAddressContent.sections.addressTypes.types).toBeDefined();
});
it('should have at least 4 address types', () => {
expect(macAddressContent.sections.addressTypes.types.length).toBeGreaterThanOrEqual(4);
});
it('should include Universal Unicast type', () => {
const universalUnicast = macAddressContent.sections.addressTypes.types.find(
(t) => t.type.includes('Universal Unicast')
);
expect(universalUnicast).toBeDefined();
});
it('should include Locally Administered type', () => {
const locallyAdmin = macAddressContent.sections.addressTypes.types.find(
(t) => t.type.includes('Locally Administered')
);
expect(locallyAdmin).toBeDefined();
});
it('should include Multicast type', () => {
const multicast = macAddressContent.sections.addressTypes.types.find(
(t) => t.type === 'Multicast'
);
expect(multicast).toBeDefined();
});
it('should include Broadcast type', () => {
const broadcast = macAddressContent.sections.addressTypes.types.find(
(t) => t.type === 'Broadcast'
);
expect(broadcast).toBeDefined();
expect(broadcast?.description).toContain('FF:FF:FF:FF:FF:FF');
});
});
describe('Formats section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.formats).toBeDefined();
expect(macAddressContent.sections.formats.title).toBeDefined();
expect(macAddressContent.sections.formats.formats).toBeDefined();
});
it('should have at least 5 format types', () => {
expect(macAddressContent.sections.formats.formats.length).toBeGreaterThanOrEqual(5);
});
it('should include colon notation', () => {
const colonFormat = macAddressContent.sections.formats.formats.find(
(f) => f.format.toLowerCase().includes('colon')
);
expect(colonFormat).toBeDefined();
expect(colonFormat?.example).toContain(':');
});
it('should include hyphen notation', () => {
const hyphenFormat = macAddressContent.sections.formats.formats.find(
(f) => f.format.toLowerCase().includes('hyphen')
);
expect(hyphenFormat).toBeDefined();
expect(hyphenFormat?.example).toContain('-');
});
it('should include Cisco/Dot notation', () => {
const ciscoFormat = macAddressContent.sections.formats.formats.find(
(f) => f.format.toLowerCase().includes('cisco') || f.format.toLowerCase().includes('dot')
);
expect(ciscoFormat).toBeDefined();
expect(ciscoFormat?.example).toContain('.');
});
it('should include bare format', () => {
const bareFormat = macAddressContent.sections.formats.formats.find(
(f) => f.format.toLowerCase().includes('bare')
);
expect(bareFormat).toBeDefined();
expect(bareFormat?.example).not.toContain(':');
expect(bareFormat?.example).not.toContain('-');
expect(bareFormat?.example).not.toContain('.');
});
it('should include EUI-64 format', () => {
const eui64Format = macAddressContent.sections.formats.formats.find(
(f) => f.format.includes('EUI-64')
);
expect(eui64Format).toBeDefined();
expect(eui64Format?.example).toContain('FF:FE');
});
});
describe('OUI Lookup section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.ouiLookup).toBeDefined();
expect(macAddressContent.sections.ouiLookup.title).toBeDefined();
expect(macAddressContent.sections.ouiLookup.content).toBeDefined();
expect(macAddressContent.sections.ouiLookup.blockTypes).toBeDefined();
expect(macAddressContent.sections.ouiLookup.lookupInfo).toBeDefined();
});
it('should have block types', () => {
expect(macAddressContent.sections.ouiLookup.blockTypes.length).toBeGreaterThanOrEqual(3);
});
it('should include MA-L block type', () => {
const maL = macAddressContent.sections.ouiLookup.blockTypes.find(
(b) => b.type.includes('MA-L')
);
expect(maL).toBeDefined();
expect(maL?.description).toContain('24-bit');
});
it('should include MA-M block type', () => {
const maM = macAddressContent.sections.ouiLookup.blockTypes.find(
(b) => b.type.includes('MA-M')
);
expect(maM).toBeDefined();
expect(maM?.description).toContain('28-bit');
});
it('should include MA-S block type', () => {
const maS = macAddressContent.sections.ouiLookup.blockTypes.find(
(b) => b.type.includes('MA-S')
);
expect(maS).toBeDefined();
expect(maS?.description).toContain('36-bit');
});
});
describe('Special Addresses section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.specialAddresses).toBeDefined();
expect(macAddressContent.sections.specialAddresses.title).toBeDefined();
expect(macAddressContent.sections.specialAddresses.addresses).toBeDefined();
});
it('should have at least 4 special addresses', () => {
expect(macAddressContent.sections.specialAddresses.addresses.length).toBeGreaterThanOrEqual(4);
});
it('should include broadcast address', () => {
const broadcast = macAddressContent.sections.specialAddresses.addresses.find(
(a) => a.type === 'Broadcast'
);
expect(broadcast).toBeDefined();
expect(broadcast?.address).toBe('FF:FF:FF:FF:FF:FF');
});
it('should include IPv4 multicast', () => {
const ipv4Multicast = macAddressContent.sections.specialAddresses.addresses.find(
(a) => a.type.includes('IPv4') && a.type.includes('Multicast')
);
expect(ipv4Multicast).toBeDefined();
expect(ipv4Multicast?.address).toContain('01:00:5E');
});
it('should include IPv6 multicast', () => {
const ipv6Multicast = macAddressContent.sections.specialAddresses.addresses.find(
(a) => a.type.includes('IPv6') && a.type.includes('Multicast')
);
expect(ipv6Multicast).toBeDefined();
expect(ipv6Multicast?.address).toContain('33:33');
});
});
describe('Use Cases section', () => {
it('should exist and have required fields', () => {
expect(macAddressContent.sections.useCases).toBeDefined();
expect(macAddressContent.sections.useCases.title).toBeDefined();
expect(macAddressContent.sections.useCases.cases).toBeDefined();
});
it('should have at least 4 use cases', () => {
expect(macAddressContent.sections.useCases.cases.length).toBeGreaterThanOrEqual(4);
});
it('should include network troubleshooting', () => {
const troubleshooting = macAddressContent.sections.useCases.cases.find(
(c) => c.useCase.toLowerCase().includes('troubleshooting')
);
expect(troubleshooting).toBeDefined();
});
it('should include security use case', () => {
const security = macAddressContent.sections.useCases.cases.find(
(c) => c.useCase.toLowerCase().includes('security')
);
expect(security).toBeDefined();
});
it('all use cases should have useCase and description', () => {
macAddressContent.sections.useCases.cases.forEach((useCase) => {
expect(useCase.useCase).toBeDefined();
expect(useCase.useCase.length).toBeGreaterThan(0);
expect(useCase.description).toBeDefined();
expect(useCase.description.length).toBeGreaterThan(0);
});
});
});
describe('Quick Tips', () => {
it('should exist and be an array', () => {
expect(macAddressContent.quickTips).toBeDefined();
expect(macAddressContent.quickTips).toBeInstanceOf(Array);
});
it('should have at least 3 tips', () => {
expect(macAddressContent.quickTips.length).toBeGreaterThanOrEqual(3);
});
it('all tips should be non-empty strings', () => {
macAddressContent.quickTips.forEach((tip) => {
expect(typeof tip).toBe('string');
expect(tip.length).toBeGreaterThan(0);
});
});
it('should include information about local network scope', () => {
const localScopeTip = macAddressContent.quickTips.find(
(tip) => tip.toLowerCase().includes('local network') || tip.toLowerCase().includes('routing')
);
expect(localScopeTip).toBeDefined();
});
});
describe('Data structure integrity', () => {
it('all components should have component and description fields', () => {
macAddressContent.sections.structure.components.forEach((comp) => {
expect(comp.component).toBeDefined();
expect(comp.component.length).toBeGreaterThan(0);
expect(comp.description).toBeDefined();
expect(comp.description.length).toBeGreaterThan(0);
});
});
it('all address types should have type and description fields', () => {
macAddressContent.sections.addressTypes.types.forEach((type) => {
expect(type.type).toBeDefined();
expect(type.type.length).toBeGreaterThan(0);
expect(type.description).toBeDefined();
expect(type.description.length).toBeGreaterThan(0);
});
});
it('all formats should have format, example, and usage fields', () => {
macAddressContent.sections.formats.formats.forEach((fmt) => {
expect(fmt.format).toBeDefined();
expect(fmt.format.length).toBeGreaterThan(0);
expect(fmt.example).toBeDefined();
expect(fmt.example.length).toBeGreaterThan(0);
expect(fmt.usage).toBeDefined();
expect(fmt.usage.length).toBeGreaterThan(0);
});
});
it('all block types should have type and description fields', () => {
macAddressContent.sections.ouiLookup.blockTypes.forEach((block) => {
expect(block.type).toBeDefined();
expect(block.type.length).toBeGreaterThan(0);
expect(block.description).toBeDefined();
expect(block.description.length).toBeGreaterThan(0);
});
});
it('all special addresses should have address, type, and description fields', () => {
macAddressContent.sections.specialAddresses.addresses.forEach((addr) => {
expect(addr.address).toBeDefined();
expect(addr.address.length).toBeGreaterThan(0);
expect(addr.type).toBeDefined();
expect(addr.type.length).toBeGreaterThan(0);
expect(addr.description).toBeDefined();
expect(addr.description.length).toBeGreaterThan(0);
});
});
});
});
@@ -0,0 +1,374 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GET } from '../../../../../../src/routes/api/internal/mac-lookup/+server.js';
describe('MAC Lookup API Endpoint', () => {
beforeEach(() => {
vi.clearAllMocks();
globalThis.fetch = vi.fn();
});
describe('Parameter validation', () => {
it('should return 400 if OUI parameter is missing', async () => {
const url = new URL('http://localhost/api/internal/mac-lookup');
const response = await GET({ url } as any);
expect(response.status).toBe(400);
const data = await response.json();
expect(data.error).toContain('OUI parameter is required');
});
it('should accept OUI parameter', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
});
});
describe('External API interaction', () => {
it('should call maclookup.app API with cleaned OUI', async () => {
const mockResponse = {
ok: false,
status: 404,
};
const mockFetch = vi.fn().mockResolvedValueOnce(mockResponse);
globalThis.fetch = mockFetch;
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
await GET({ url } as any);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('3C22FB'),
expect.objectContaining({
headers: expect.objectContaining({
'User-Agent': 'IP-Calc/1.0',
}),
})
);
});
it('should handle colons in OUI input', async () => {
const mockResponse = {
ok: false,
status: 404,
};
const mockFetch = vi.fn().mockResolvedValueOnce(mockResponse);
globalThis.fetch = mockFetch;
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
await GET({ url } as any);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('3C22FB'),
expect.any(Object)
);
});
it('should handle hyphens in OUI input', async () => {
const mockResponse = {
ok: false,
status: 404,
};
const mockFetch = vi.fn().mockResolvedValueOnce(mockResponse);
globalThis.fetch = mockFetch;
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C-22-FB');
await GET({ url } as any);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('3C22FB'),
expect.any(Object)
);
});
});
describe('Successful OUI lookup', () => {
it('should return OUI information when found', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
success: true,
found: true,
company: 'Apple, Inc.',
country: 'US',
address: '1 Apple Park Way, Cupertino CA 95014',
blockType: 'MA-L',
blockStart: '3C:22:FB:00:00:00',
blockEnd: '3C:22:FB:FF:FF:FF',
blockSize: 16777216,
isPrivate: false,
isRand: false,
updated: '2023-01-15',
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
const data = await response.json();
expect(data.found).toBe(true);
expect(data.manufacturer).toBe('Apple, Inc.');
expect(data.country).toBe('US');
expect(data.blockType).toBe('MA-L');
expect(data.blockSize).toBe(16777216);
});
it('should include all relevant fields', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
success: true,
found: true,
company: 'Test Company',
country: 'CA',
address: '123 Test St',
blockType: 'MA-M',
blockStart: '00:11:22:00:00:00',
blockEnd: '00:11:22:0F:FF:FF',
blockSize: 1048576,
isPrivate: true,
isRand: false,
updated: '2024-01-01',
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:11:22');
const response = await GET({ url } as any);
const data = await response.json();
expect(data).toMatchObject({
found: true,
manufacturer: 'Test Company',
country: 'CA',
address: '123 Test St',
blockType: 'MA-M',
blockStart: '00:11:22:00:00:00',
blockEnd: '00:11:22:0F:FF:FF',
blockSize: 1048576,
isPrivate: true,
isRand: false,
updated: '2024-01-01',
});
});
});
describe('OUI not found scenarios', () => {
it('should return not found when API returns 404', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:00:00');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
const data = await response.json();
expect(data.found).toBe(false);
expect(data.manufacturer).toBe(null);
});
it('should return not found when API returns success=false', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
success: false,
found: false,
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:00:00');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
const data = await response.json();
expect(data.found).toBe(false);
expect(data.manufacturer).toBe(null);
});
it('should return not found when API returns found=false', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
success: true,
found: false,
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:00:00');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
const data = await response.json();
expect(data.found).toBe(false);
expect(data.manufacturer).toBe(null);
});
});
describe('Error handling', () => {
it('should handle external API errors gracefully', async () => {
const mockResponse = {
ok: false,
status: 500,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
const response = await GET({ url } as any);
expect(response.status).toBe(500);
const data = await response.json();
expect(data.error).toBeDefined();
});
it('should handle network errors', async () => {
globalThis.fetch = vi.fn().mockRejectedValueOnce(new Error('Network error'));
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
const response = await GET({ url } as any);
expect(response.status).toBe(500);
const data = await response.json();
expect(data.error).toContain('Failed to fetch OUI data');
expect(data.found).toBe(false);
});
it('should handle JSON parsing errors', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockRejectedValue(new Error('JSON parse error')),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB');
const response = await GET({ url } as any);
expect(response.status).toBe(500);
const data = await response.json();
expect(data.error).toBeDefined();
});
});
describe('Edge cases', () => {
it('should handle empty OUI parameter', async () => {
const url = new URL('http://localhost/api/internal/mac-lookup?oui=');
const response = await GET({ url } as any);
expect(response.status).toBe(400);
const data = await response.json();
expect(data.error).toContain('OUI parameter is required');
});
it('should handle full MAC address as OUI', async () => {
const mockResponse = {
ok: false,
status: 404,
};
const mockFetch = vi.fn().mockResolvedValueOnce(mockResponse);
globalThis.fetch = mockFetch;
const url = new URL('http://localhost/api/internal/mac-lookup?oui=3C:22:FB:A1:B2:C3');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('3C22FBA1B2C3'),
expect.any(Object)
);
});
it('should handle lowercase OUI', async () => {
const mockResponse = {
ok: false,
status: 404,
};
const mockFetch = vi.fn().mockResolvedValueOnce(mockResponse);
globalThis.fetch = mockFetch;
const url = new URL('http://localhost/api/internal/mac-lookup?oui=aa:bb:cc');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
expect(mockFetch).toHaveBeenCalled();
});
it('should handle OUI with spaces', async () => {
const mockResponse = {
ok: false,
status: 404,
};
const mockFetch = vi.fn().mockResolvedValueOnce(mockResponse);
globalThis.fetch = mockFetch;
const url = new URL('http://localhost/api/internal/mac-lookup?oui=AA BB CC');
const response = await GET({ url } as any);
expect(response.status).toBe(200);
// Spaces should be removed or handled
expect(mockFetch).toHaveBeenCalled();
});
});
describe('API response consistency', () => {
it('should always return found field', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:00:00');
const response = await GET({ url } as any);
const data = await response.json();
expect(data).toHaveProperty('found');
expect(typeof data.found).toBe('boolean');
});
it('should always return manufacturer field when found is true', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
success: true,
found: true,
company: 'Test Vendor',
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:11:22');
const response = await GET({ url } as any);
const data = await response.json();
expect(data).toHaveProperty('manufacturer');
expect(data.manufacturer).toBe('Test Vendor');
});
it('should return null manufacturer when not found', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const url = new URL('http://localhost/api/internal/mac-lookup?oui=00:00:00');
const response = await GET({ url } as any);
const data = await response.json();
expect(data).toHaveProperty('manufacturer');
expect(data.manufacturer).toBe(null);
});
});
});
+585
View File
@@ -0,0 +1,585 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { convertMACAddress, convertMACAddresses } from '../../../src/lib/utils/mac-address.js';
describe('MAC Address Conversion Utilities', () => {
beforeEach(() => {
vi.clearAllMocks();
globalThis.fetch = vi.fn();
});
describe('MAC address parsing', () => {
it('should parse colon-separated MAC address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('001A2B3C4D5E');
});
it('should parse hyphen-separated MAC address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00-1A-2B-3C-4D-5E');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('001A2B3C4D5E');
});
it('should parse Cisco dot-separated MAC address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('001A.2B3C.4D5E');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('001A2B3C4D5E');
});
it('should parse bare MAC address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('001A2B3C4D5E');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('001A2B3C4D5E');
});
it('should handle lowercase MAC address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('aa:bb:cc:dd:ee:ff');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('AABBCCDDEEFF');
});
it('should reject invalid MAC address length', async () => {
const result = await convertMACAddress('00:1A:2B:3C:4D');
expect(result.isValid).toBe(false);
expect(result.error).toContain('Invalid MAC address format');
});
it('should reject invalid characters', async () => {
const result = await convertMACAddress('GG:1A:2B:3C:4D:5E');
expect(result.isValid).toBe(false);
expect(result.error).toContain('Invalid MAC address format');
});
it('should reject empty input', async () => {
const result = await convertMACAddress('');
expect(result.isValid).toBe(false);
expect(result.error).toContain('Invalid MAC address format');
});
});
describe('MAC address formatting', () => {
it('should format to all common formats', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.colon).toBe('00:1A:2B:3C:4D:5E');
expect(result.formats.hyphen).toBe('00-1A-2B-3C-4D-5E');
expect(result.formats.cisco).toBe('001A.2B3C.4D5E');
expect(result.formats.bare).toBe('001A2B3C4D5E');
expect(result.formats.bareUppercase).toBe('001A2B3C4D5E');
expect(result.formats.bareLowercase).toBe('001a2b3c4d5e');
});
it('should format to EUI-64', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.eui64).toBe('02:1A:2B:FF:FE:3C:4D:5E');
});
it('should format to various prefixed formats', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.prefixedMac).toBe('MAC=00:1A:2B:3C:4D:5E');
expect(result.formats.prefixedHwaddr).toBe('HWaddr 00:1A:2B:3C:4D:5E');
expect(result.formats.slashSeparated).toBe('00/1A/2B/3C/4D/5E');
expect(result.formats.prefixedBare).toBe('MAC001A2B3C4D5E');
expect(result.formats.prefixedAddr).toBe('addr001A2B3C4D5E');
});
it('should format to decimal octets', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.decimalOctets).toBe('0.26.43.60.77.94');
});
it('should format to reversed order', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.reverse).toBe('5E:4D:3C:2B:1A:00');
});
it('should format to IPv6 style', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.ipv6Style).toBe('001A:2B3C:4D5E');
});
it('should format to space-separated', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.spaceSeparated).toBe('00 1A 2B 3C 4D 5E');
});
});
describe('MAC address details', () => {
it('should identify universal unicast address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.details.isUniversal).toBe(true);
expect(result.details.isUnicast).toBe(true);
});
it('should identify locally administered address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// Second hex digit 2 means U/L bit is set
const result = await convertMACAddress('02:1A:2B:3C:4D:5E');
expect(result.details.isUniversal).toBe(false);
expect(result.details.isUnicast).toBe(true);
});
it('should identify multicast address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// First hex digit odd means I/G bit is set
const result = await convertMACAddress('01:1A:2B:3C:4D:5E');
expect(result.details.isUniversal).toBe(true);
expect(result.details.isUnicast).toBe(false);
});
it('should identify locally administered multicast address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// Both bits set: 03 = 0000 0011
const result = await convertMACAddress('03:1A:2B:3C:4D:5E');
expect(result.details.isUniversal).toBe(false);
expect(result.details.isUnicast).toBe(false);
});
it('should include binary representation', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('FF:FF:FF:FF:FF:FF');
expect(result.details.binary).toBe(
'111111111111111111111111111111111111111111111111'
);
});
});
describe('OUI lookup', () => {
it('should lookup OUI information successfully', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
found: true,
manufacturer: 'Apple, Inc.',
country: 'US',
address: '1 Apple Park Way, Cupertino CA 95014',
blockType: 'MA-L',
blockStart: '3C:22:FB:00:00:00',
blockEnd: 'FF:FF:FF:FF:FF:FF',
blockSize: 16777216,
isPrivate: false,
isRand: false,
updated: '2023-01-15',
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('3C:22:FB:A1:B2:C3');
expect(result.oui.found).toBe(true);
expect(result.oui.manufacturer).toBe('Apple, Inc.');
expect(result.oui.country).toBe('US');
expect(result.oui.blockType).toBe('MA-L');
expect(result.oui.blockSize).toBe(16777216);
});
it('should handle OUI not found', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:00:00:00:00:00');
expect(result.oui.found).toBe(false);
expect(result.oui.manufacturer).toBe(null);
});
it('should handle OUI lookup API error', async () => {
globalThis.fetch = vi.fn().mockRejectedValueOnce(new Error('Network error'));
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.oui.found).toBe(false);
expect(result.oui.manufacturer).toBe(null);
});
it('should handle API returning not found in JSON', async () => {
const mockResponse = {
ok: true,
json: vi.fn().mockResolvedValue({
found: false,
manufacturer: null,
}),
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.oui.found).toBe(false);
expect(result.oui.manufacturer).toBe(null);
});
});
describe('EUI-64 conversion', () => {
it('should flip U/L bit in EUI-64', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// Universal address (0x00) should become local (0x02) in EUI-64
const result = await convertMACAddress('00:1A:2B:3C:4D:5E');
expect(result.formats.eui64).toBe('02:1A:2B:FF:FE:3C:4D:5E');
});
it('should flip U/L bit for local address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// Local address (0x02) should become universal (0x00) in EUI-64
const result = await convertMACAddress('02:1A:2B:3C:4D:5E');
expect(result.formats.eui64).toBe('00:1A:2B:FF:FE:3C:4D:5E');
});
it('should insert FFFE in the middle', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('AA:BB:CC:DD:EE:FF');
// A8 because 0xAA XOR 0x02 = 0xA8
expect(result.formats.eui64).toBe('A8:BB:CC:FF:FE:DD:EE:FF');
});
});
describe('Batch conversion', () => {
it('should convert multiple valid MAC addresses', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
const inputs = [
'00:1A:2B:3C:4D:5E',
'AA:BB:CC:DD:EE:FF',
'3C:22:FB:A1:B2:C3',
];
const result = await convertMACAddresses(inputs);
expect(result.conversions).toHaveLength(3);
expect(result.summary.total).toBe(3);
expect(result.summary.valid).toBe(3);
expect(result.summary.invalid).toBe(0);
expect(result.summary.withOUI).toBe(0);
});
it('should handle mixed valid and invalid addresses', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
const inputs = ['00:1A:2B:3C:4D:5E', 'invalid-mac', 'GG:HH:II:JJ:KK:LL'];
const result = await convertMACAddresses(inputs);
expect(result.conversions).toHaveLength(3);
expect(result.summary.total).toBe(3);
expect(result.summary.valid).toBe(1);
expect(result.summary.invalid).toBe(2);
});
it('should count addresses with OUI information', async () => {
const mockResponse1 = {
ok: true,
json: vi.fn().mockResolvedValue({
found: true,
company: 'Apple, Inc.',
}),
};
const mockResponse2 = {
ok: false,
status: 404,
};
globalThis.fetch = vi
.fn()
.mockResolvedValueOnce(mockResponse1)
.mockResolvedValueOnce(mockResponse2);
const inputs = ['3C:22:FB:A1:B2:C3', '00:00:00:00:00:00'];
const result = await convertMACAddresses(inputs);
expect(result.summary.total).toBe(2);
expect(result.summary.valid).toBe(2);
expect(result.summary.withOUI).toBe(1);
});
it('should handle empty inputs array', async () => {
const result = await convertMACAddresses([]);
expect(result.conversions).toHaveLength(0);
expect(result.summary.total).toBe(0);
expect(result.summary.valid).toBe(0);
expect(result.summary.invalid).toBe(0);
});
it('should process all inputs including empty strings', async () => {
const inputs = ['00:1A:2B:3C:4D:5E', '', ' ', '\t'];
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
const result = await convertMACAddresses(inputs);
expect(result.conversions).toHaveLength(4);
expect(result.summary.total).toBe(4);
expect(result.summary.valid).toBe(1);
expect(result.summary.invalid).toBe(3);
});
});
describe('Special MAC addresses', () => {
it('should handle broadcast address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('FF:FF:FF:FF:FF:FF');
expect(result.isValid).toBe(true);
expect(result.details.isUnicast).toBe(false); // Multicast/Broadcast
expect(result.details.isUniversal).toBe(false); // Local
});
it('should handle null address', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:00:00:00:00:00');
expect(result.isValid).toBe(true);
expect(result.details.isUnicast).toBe(true);
expect(result.details.isUniversal).toBe(true);
});
it('should handle IPv4 multicast MAC', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// IPv4 multicast MAC range starts with 01:00:5E
const result = await convertMACAddress('01:00:5E:00:00:01');
expect(result.isValid).toBe(true);
expect(result.details.isUnicast).toBe(false); // Multicast
});
it('should handle IPv6 multicast MAC', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
// IPv6 multicast MAC range starts with 33:33
const result = await convertMACAddress('33:33:00:00:00:01');
expect(result.isValid).toBe(true);
expect(result.details.isUnicast).toBe(false); // Multicast
});
});
describe('Edge cases', () => {
it('should handle MAC with mixed case', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('aA:bB:cC:dD:eE:fF');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('AABBCCDDEEFF');
expect(result.formats.colon).toBe('AA:BB:CC:DD:EE:FF');
});
it('should handle MAC with extra whitespace', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress(' 00:1A:2B:3C:4D:5E ');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('001A2B3C4D5E');
});
it('should reject MAC with invalid separators', async () => {
const result = await convertMACAddress('00/1A/2B/3C/4D/5E');
// Slashes should be removed in parsing, but this would result in wrong length
expect(result.isValid).toBe(false);
});
it('should handle MAC with numbers only', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('00:11:22:33:44:55');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('001122334455');
});
it('should handle MAC with letters only (hexadecimal)', async () => {
const mockResponse = {
ok: false,
status: 404,
};
globalThis.fetch = vi.fn().mockResolvedValueOnce(mockResponse);
const result = await convertMACAddress('AA:BB:CC:DD:EE:FF');
expect(result.isValid).toBe(true);
expect(result.normalized).toBe('AABBCCDDEEFF');
});
});
});
+1 -1
View File
@@ -294,7 +294,7 @@ describe('Mask Conversion Utilities', () => {
const duration = endTime - startTime;
// Should complete 33,000 conversions in reasonable time (< 1 second, allowing some buffer)
expect(duration).toBeLessThan(1000 + 69);
expect(duration).toBeLessThan(1100);
});
it('should maintain consistency across multiple rapid calls', () => {