Skip to content

Commit

Permalink
fix: support ipv6 urls
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed May 10, 2023
1 parent 229edbf commit de541a2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
20 changes: 11 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
'use strict'

const URL = globalThis ? globalThis.URL : require('url').URL

const urlRegex = require('url-regex-safe')({
apostrophes: true,
exact: true,
parens: true
})
const urlRegex = require('url-regex-safe')

const REGEX_HTTP_PROTOCOL = /^https?:\/\//i

module.exports = url => {
try {
const { href } = new URL(url)
return REGEX_HTTP_PROTOCOL.test(href) && urlRegex.test(href) && href
} catch (err) {
const { href, hostname } = new URL(url)
const isIPv6 = hostname.startsWith('[') && hostname.endsWith(']')
return (
REGEX_HTTP_PROTOCOL.test(href) &&
urlRegex({ apostrophes: true, exact: !isIPv6, parens: true }).test(
href
) &&
href
)
} catch (_) {
return false
}
}
6 changes: 5 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ const test = require('ava')
].forEach(({ fn: httpUrl, isLightweight }) => {
test(isLightweight ? 'lightweight » true' : 'true', t => {
;[
'http://169.254.169.254:1337/',
'http://[::ffff:a9fe:a9fe]/metadata/v1/',
'http://[0:0:0:0:0:ffff:a9fe:a9fe]/metadata/v1/',
'http://[0:0:0:0:0:ffff:169.254.169.254]/metadata/v1/',
'http://kikobeats.com',
"https://en.wikipedia.org/wiki/Amdahl's_law",
'https://kikobeats.com',
Expand All @@ -16,7 +20,7 @@ const test = require('ava')
'http://www.kikobeats.com'
].forEach(input => {
const url = httpUrl(input)
t.is(typeof url, 'string')
t.is(typeof url, 'string', `'${input}' is not true`)
t.true(!!url)
})
})
Expand Down

0 comments on commit de541a2

Please sign in to comment.