Skip to content

Commit

Permalink
fix: handle valid CIDR ranges for IPv4 and IPv6 (#394)
Browse files Browse the repository at this point in the history
Add missing case 43 (ipcidr) to ```convert.ts``` to properly handle CIDR ranges
Add two new test cases


Fixes #393

---------

Co-authored-by: Russell Dempsey <1173416+SgtPooki@users.noreply.github.com>
  • Loading branch information
acul71 and SgtPooki authored Dec 3, 2024
1 parent 02579d6 commit 1513768
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export function convert (proto: string, a: string | Uint8Array): Uint8Array | st
/**
* Convert [code,Uint8Array] to string
*/
// eslint-disable-next-line complexity
export function convertToString (proto: number | string, buf: Uint8Array): string {
const protocol = getProtocol(proto)
switch (protocol.code) {
Expand All @@ -40,6 +41,8 @@ export function convertToString (proto: number | string, buf: Uint8Array): strin
return bytes2ip(buf)
case 42: // ipv6zone
return bytes2str(buf)
case 43: // ipcidr
return uint8ArrayToString(buf, 'base10')

case 6: // tcp
case 273: // udp
Expand Down Expand Up @@ -71,6 +74,7 @@ export function convertToString (proto: number | string, buf: Uint8Array): strin
}
}

// eslint-disable-next-line complexity
export function convertToBytes (proto: string | number, str: string): Uint8Array {
const protocol = getProtocol(proto)
switch (protocol.code) {
Expand All @@ -80,6 +84,8 @@ export function convertToBytes (proto: string | number, str: string): Uint8Array
return ip2bytes(str)
case 42: // ipv6zone
return str2bytes(str)
case 43: // ipcidr
return uint8ArrayFromString(str, 'base10')

case 6: // tcp
case 273: // udp
Expand Down
4 changes: 3 additions & 1 deletion test/filter/multiaddr-filter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ describe('MultiaddrFilter', () => {
['/ip4/192.168.10.10/ipcidr/24', '/ip4/192.168.11.2/udp/60', false],
['/ip4/192.168.10.10/ipcidr/24', '/ip6/2001:db8:3333:4444:5555:6666:7777:8888/tcp/60', false],
['/ip6/2001:db8:3333:4444:5555:6666:7777:8888/ipcidr/60', '/ip6/2001:0db8:3333:4440:0000:0000:0000:0000/tcp/60', true],
['/ip6/2001:db8:3333:4444:5555:6666:7777:8888/ipcidr/60', '/ip6/2001:0db8:3333:4450:0000:0000:0000:0000/tcp/60', false]
['/ip6/2001:db8:3333:4444:5555:6666:7777:8888/ipcidr/60', '/ip6/2001:0db8:3333:4450:0000:0000:0000:0000/tcp/60', false],
['/ip6/2001:db8:3333:4444:5555:6666:7777:8888/ipcidr/128', '/ip6/2001:db8:3333:4444:5555:6666:7777:8888/tcp/60', true],
['/ip6/2001:db8:3333:4444:5555:6666:7777:8888/ipcidr/128', '/ip6/2001:db8:3333:4444:5555:6666:7777:8880/tcp/60', false]
]

cases.forEach(([cidr, ip, result]) => {
Expand Down

0 comments on commit 1513768

Please sign in to comment.