Bracketed IPv6 host in a connection string resolves to "[" and cannot connect
Description
A connection string whose host is a bracketed IPv6 literal resolves to a truncated host, so every connection attempt fails. With [email protected]:
import postgres from 'postgres'
for (const url of [
'postgresql://u:p@[::1]:5432/db',
'postgresql://u:p@[2001:db8::1]/db',
'postgresql://u:[email protected]:5432/db',
'postgresql://u:p@h1:1,h2:2/db'
]) {
const sql = postgres(url, { max: 1 })
console.log(url, '->', JSON.stringify({ host: sql.options.host, port: sql.options.port }))
await sql.end()
}prints
postgresql://u:p@[::1]:5432/db -> {"host":["["],"port":[5432]}
postgresql://u:p@[2001:db8::1]/db -> {"host":["[2001"],"port":[null]}
postgresql://u:[email protected]:5432/db -> {"host":["127.0.0.1"],"port":[5432]}
postgresql://u:p@h1:1,h2:2/db -> {"host":["h1","h2"],"port":[1,2]}(null is JSON.stringify of NaN.) Connecting with the first URL fails with getaddrinfo ENOTFOUND [. A bare IPv6 address passed as the host option or PGHOST (for example ::1) resolves to host ''.
Expected Behavior
A bracketed IPv6 literal ([::1], [2001:db8::1], with or without a port, alone or in a multi-host list) resolves to the address without brackets and to its port, or the default port when none is given, as new URL() parses it. A bare IPv6 address in the host option or PGHOST resolves to that address.
Reproduction Steps
npm install [email protected]- Save the snippet above as
probe.mjsand runnode probe.mjs. - Observe host
["["]for[::1]and host["[2001"], port[NaN]for[2001:db8::1].
Environment / Context
[email protected] and current master (src/index.js lines 466-467 are unchanged there); Node 24.
Discovered During
Nitjsefnie/Overflow issue 801 (https://github.com/Nitjsefnie/Overflow/issues/801), where a test server published only on ::1 could not be reached through a DATABASE_URL.
Suggested Fix
Unverified as a design choice, verified as a fix in our fork: parseOptions splits each comma-separated host at its first : (src/index.js:466-467), while url.hostname from new URL() keeps the brackets ([::1]). Parsing each host entry with bracket awareness — [addr] or [addr]:port, a bare value with more than one : taken whole, anything else split as today — fixes it without changing hostname, IPv4, host:port or socket behaviour.
Two open pull requests touch this: #663 handles the bracketed URL case but throws ERR_INVALID_URL for a bare ::1 host option and adds no tests, and #1127 turns a multi-host entry [::1]:5432 into host ::1]:543. I'd be happy to send a pull request with the fix and regression tests.
Source: porsager/postgres