fix: preserve user-configured NO_PROXY when loopback already covered

Only restore env vars when we actually modified them (noProxyDidModify
flag). Prevents silently deleting a user's NO_PROXY that already
contains loopback entries. Added regression test.
This commit is contained in:
Marcus Widing
2026-03-02 09:48:59 +01:00
committed by Peter Steinberger
parent dd8c76110f
commit 2bec80cd97
2 changed files with 31 additions and 1 deletions

View File

@@ -248,3 +248,30 @@ describe("withNoProxyForLocalhost reverse exit order", () => {
}
});
});
describe("withNoProxyForLocalhost preserves user-configured NO_PROXY", () => {
it("does not delete NO_PROXY when loopback entries already present", async () => {
const userNoProxy = "localhost,127.0.0.1,[::1],myhost.internal";
process.env.NO_PROXY = userNoProxy;
process.env.no_proxy = userNoProxy;
process.env.HTTP_PROXY = "http://proxy:8080";
try {
const { withNoProxyForLocalhost } = await import("./cdp-proxy-bypass.js");
await withNoProxyForLocalhost(async () => {
// Should not modify since loopback is already covered
expect(process.env.NO_PROXY).toBe(userNoProxy);
return "ok";
});
// After call completes, user's NO_PROXY must still be intact
expect(process.env.NO_PROXY).toBe(userNoProxy);
expect(process.env.no_proxy).toBe(userNoProxy);
} finally {
delete process.env.HTTP_PROXY;
delete process.env.NO_PROXY;
delete process.env.no_proxy;
}
});
});

View File

@@ -63,6 +63,7 @@ let savedNoProxy: string | undefined;
let savedNoProxyLower: string | undefined;
const LOOPBACK_ENTRIES = "localhost,127.0.0.1,[::1]";
let noProxyDidModify = false;
function noProxyAlreadyCoversLocalhost(): boolean {
const current = process.env.NO_PROXY || process.env.no_proxy || "";
@@ -86,13 +87,14 @@ export async function withNoProxyForLocalhost<T>(fn: () => Promise<T>): Promise<
const extended = current ? `${current},${LOOPBACK_ENTRIES}` : LOOPBACK_ENTRIES;
process.env.NO_PROXY = extended;
process.env.no_proxy = extended;
noProxyDidModify = true;
}
try {
return await fn();
} finally {
noProxyRefCount--;
if (noProxyRefCount === 0) {
if (noProxyRefCount === 0 && noProxyDidModify) {
if (savedNoProxy !== undefined) {
process.env.NO_PROXY = savedNoProxy;
} else {
@@ -105,6 +107,7 @@ export async function withNoProxyForLocalhost<T>(fn: () => Promise<T>): Promise<
}
savedNoProxy = undefined;
savedNoProxyLower = undefined;
noProxyDidModify = false;
}
}
}