Skip to content

Commit

Permalink
fix: trim string before parsing IP address (#269)
Browse files Browse the repository at this point in the history
Remove leading and training spaces, also adds tests.
  • Loading branch information
achingbrain authored Sep 12, 2022
1 parent d6b7f69 commit 9924afa
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ const anybaseDecoder = (function () {

function ip2bytes (ipString: string) {
if (!ip.isIP(ipString)) {
throw new Error('invalid ip address')
throw new Error(`invalid ip address "${ipString}"`)
}
return ip.toBytes(ipString)
}
Expand Down
5 changes: 3 additions & 2 deletions src/ip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const isV6 = isIPv6
export const toBytes = function (ip: string): Uint8Array {
let offset = 0
let result
ip = ip.trim()

if (isV4(ip)) {
result = new Uint8Array(offset + 4)
Expand Down Expand Up @@ -56,14 +57,14 @@ export const toBytes = function (ip: string): Uint8Array {
}

if (result == null) {
throw Error('Invalid ip address: ' + ip)
throw new Error(`invalid ip address "${ip}"`)
}

return result
}

// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
export const toString = function (buf: Uint8Array, offset: number, length: number) {
export const toString = function (buf: Uint8Array, offset: number = 0, length?: number) {
offset = ~~offset
length = length ?? (buf.length - offset)

Expand Down
29 changes: 29 additions & 0 deletions test/ip.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* eslint max-nested-callbacks: ["error", 8] */
/* eslint-env mocha */
import { expect } from 'aegir/chai'
import { toBytes, toString } from '../src/ip.js'

describe('ip', () => {
describe('toBytes', () => {
it('should handle extra characters', () => {
const address = '127.0.0.1 '
const bytes = toBytes(address)

expect(toString(bytes)).to.equal(address.trim())
})

it('should turn loopback into bytes', () => {
const address = '127.0.0.1'
const bytes = toBytes(address)

expect(toString(bytes)).to.equal(address)
})

it('should turn private address into bytes', () => {
const address = '192.168.1.1'
const bytes = toBytes(address)

expect(toString(bytes)).to.equal(address)
})
})
})

0 comments on commit 9924afa

Please sign in to comment.