From 0777d1ebddd19b48f24ce4a59361b886b9274240 Mon Sep 17 00:00:00 2001 From: Yarchik Date: Fri, 7 Aug 2026 11:13:50 +0100 Subject: [PATCH] fix(pg-connection-string): strip IPv6 URI brackets from the parsed host The WHATWG URL parser keeps the square brackets around an IPv6 literal, so parse('postgres://[::1]:5432/db').host was '[::1]'. That value is unusable: libpq's host keyword takes the bare address, and net.connect / dns.lookup fail on the bracketed form. The brackets are RFC 3986 URI delimiters, not part of the host, so extract the address from them in the parser, the same way the scheme and port are extracted. Matches libpq, which stores the bracket-free literal. Unconditional replace keeps 100% branch coverage; a no-op for non-bracketed hosts. --- packages/pg-connection-string/index.js | 2 +- packages/pg-connection-string/test/parse.ts | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/pg-connection-string/index.js b/packages/pg-connection-string/index.js index 7ee302976..139cc17b1 100644 --- a/packages/pg-connection-string/index.js +++ b/packages/pg-connection-string/index.js @@ -50,7 +50,7 @@ function parse(str, options = {}) { config.client_encoding = result.searchParams.get('encoding') return config } - const hostname = dummyHost ? '' : result.hostname + const hostname = (dummyHost ? '' : result.hostname).replace(/^\[(.+)\]$/, '$1') if (!config.host) { // Only set the host if there is no equivalent query param. config.host = decodeURIComponent(hostname) diff --git a/packages/pg-connection-string/test/parse.ts b/packages/pg-connection-string/test/parse.ts index c2a537581..562c3ece0 100644 --- a/packages/pg-connection-string/test/parse.ts +++ b/packages/pg-connection-string/test/parse.ts @@ -14,6 +14,11 @@ describe('parse', function () { subject.database?.should.equal('lala') }) + it('strips the URI brackets from an IPv6 host', function () { + parse('postgres://brian:pw@[::1]:5432/lala').host?.should.equal('::1') + parse('postgres://brian:pw@[2001:db8::1]:5432/lala').host?.should.equal('2001:db8::1') + }) + it('escape spaces if present', function () { const subject = parse('postgres://localhost/post gres') subject.database?.should.equal('post gres')