From 62ad170fc9f1676c33e76398e4083e657e488feb Mon Sep 17 00:00:00 2001 From: ArkXiong Date: Mon, 9 Nov 2026 17:28:50 +0800 Subject: [PATCH 1/6] feat(network): honor HTTPS_PROXY, HTTP_PROXY and NO_PROXY Node's fetch ignores the proxy variables unless Node was started with NODE_USE_ENV_PROXY=1 (22.21+, 24+). Cursor's sandbox allows the network only through the proxy it names in them, so every command there failed at its first request, and the Meshy plugin had to start the CLI with NODE_USE_ENV_PROXY=1. At start, when HTTPS_PROXY or HTTP_PROXY is set (lowercase spellings too), install undici's EnvHttpProxyAgent as the global dispatcher, so every fetch goes through the proxy unless NO_PROXY exempts its host, on every Node the CLI supports. Without the variables nothing changes (D-093). Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 24 +++++++++ docs/usage.md | 1 + package.json | 1 + pnpm-lock.yaml | 9 ++++ src/index.ts | 6 ++- src/internal/proxy.ts | 57 ++++++++++++++++++++ src/root.ts | 1 + tests/proxy.test.ts | 120 ++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 src/internal/proxy.ts create mode 100644 tests/proxy.test.ts diff --git a/docs/decisions.md b/docs/decisions.md index d4d8fa0..5d4ca23 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1624,3 +1624,27 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu - Inside DeepSeek Harness the request still ends in `dsh` after the parentheses (D-087) while servers that read only that part are in use; the agent segment says `dsh` too. + +## D-093 Requests honor HTTPS_PROXY, HTTP_PROXY and NO_PROXY + +- Node's fetch ignores the proxy variables unless Node itself was started + with `NODE_USE_ENV_PROXY=1` (22.21+, 24+). Cursor's sandbox allows the + network only through a proxy it names in those variables, so every command + there failed at its first request (`oauth_network`), and the Meshy plugin + had to start the CLI with `NODE_USE_ENV_PROXY=1`, which needs a newer Node + than the CLI requires. +- At start, before any request, the CLI reads `https_proxy`, `HTTPS_PROXY`, + `http_proxy`, `HTTP_PROXY` and `no_proxy`, `NO_PROXY` (lowercase first, as + curl and undici do). When either proxy is set it installs undici's + `EnvHttpProxyAgent` as the global dispatcher once, so every fetch goes + through it: the API, sign-in, downloads, input URL checks, and the update + check's child process, which starts through the same entry point. `https:` + URLs use `HTTPS_PROXY` and fall back to `HTTP_PROXY`; hosts in `NO_PROXY` go + direct. Without a proxy variable nothing changes. +- undici is a dependency for this alone. Node's own `http.setGlobalProxyFromEnv` + does the same, but Node 22 does not have it (24.20 does); one code path + covers every Node the CLI supports (22.12+), and the global dispatcher is + what Node's built-in fetch uses on both 22 and 24. +- The transport's own rules are unchanged: it still follows no redirect and + refuses a URL outside its base. The proxy only carries the request, and for + `https:` URLs it sees a CONNECT tunnel, not the request. diff --git a/docs/usage.md b/docs/usage.md index e36f0ba..33f6ab0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -541,6 +541,7 @@ URI is accepted when its bytes are a GLB. | `MESHY_LOG_LEVEL` | `warn` | | `MESHY_CLI_CLIENT` | unset — a tool that runs meshy-cli for its users names itself here (for example `meshy-dcc/0.2.2 (blender)`); appended to the User-Agent of every request. Inside DeepSeek Harness (`DSH_SHELL=1`) it defaults to `dsh` | | `MESHY_CLI_AGENT` | unset — the AI agent running meshy-cli is detected from the variables it sets on its commands (Cursor, Claude Code, Codex, Copilot, Gemini CLI, Kiro CLI, OpenCode, Hermes, DeepSeek Harness, Cline, Roo Code, or any agent that sets `AI_AGENT`) and named in the User-Agent of API requests to Meshy (`meshy.ai`, `meshy.cn`) as `; agent [/]` inside the parentheses; requests anywhere else, sign-in, input URL checks and asset downloads leave it out. Set a name (`grok-bot`, `claude-code/desktop`: lowercase letters, digits, `.`, `-`) to name it yourself, or `none` to leave it out. `meshy doctor` shows what was detected and from which variable | +| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs and falls back to `HTTP_PROXY`. `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all). Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | | `MESHY_CLI_NO_UPDATE_NOTIFIER` | unset — any non-empty value disables update checks; CI envs (`CI`, `GITHUB_ACTIONS`, `BUILD_NUMBER`, `RUN_ID`) auto-skip | ## Update notifications diff --git a/package.json b/package.json index c434b0f..c097b89 100644 --- a/package.json +++ b/package.json @@ -56,6 +56,7 @@ "dependencies": { "commander": "^15.0.0", "sharp": "^0.35.4", + "undici": "^7.30.2", "zod": "^4.5.2" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index db51ce3..d30f88e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: sharp: specifier: ^0.35.4 version: 0.35.4(@types/node@22.20.4) + undici: + specifier: ^7.30.2 + version: 7.30.2 zod: specifier: ^4.5.2 version: 4.5.2 @@ -522,6 +525,10 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} + engines: {node: '>=20.18.1'} + zod@4.5.2: resolution: {integrity: sha512-XkYXCol10+ba/6F/cueWV+TezUeOqXW0hdeJt5CdXjTYeAgAQg5N03RQdJ80mhfFE72+pblvYMW4wy2Qp4Qbrg==} @@ -885,4 +892,6 @@ snapshots: undici-types@6.21.0: {} + undici@7.30.2: {} + zod@4.5.2: {} diff --git a/src/index.ts b/src/index.ts index 9e1dfb7..33a9eb6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,8 @@ * - turn SIGINT / SIGTERM / SIGHUP into a cooperative abort (exit 130) instead of a hard kill; * - route every failure — including Commander parse errors — through one * exit that renders the v1 error envelope in the format the command would have used; - * - flush stdout before exiting. + * - flush stdout before exiting; + * - route every request through the proxy HTTPS_PROXY / HTTP_PROXY name. */ import type { Command } from "commander"; @@ -22,8 +23,11 @@ import { stopActiveProgress } from "./internal/progress.js"; import { errorEnvelope } from "./internal/result.js"; import { resolveFormat } from "./internal/runtime.js"; import { refreshCache, shouldRunUpdateCheck } from "./internal/update-notifier.js"; +import { useProxyFromEnv } from "./internal/proxy.js"; async function main(): Promise { + // Before any request, the update check's included (D-093). + useProxyFromEnv(); const argv = process.argv; if (argv.includes("--no-update-check")) { // Children (none today, but any future spawn) inherit the opt-out. diff --git a/src/internal/proxy.ts b/src/internal/proxy.ts new file mode 100644 index 0000000..4d348a8 --- /dev/null +++ b/src/internal/proxy.ts @@ -0,0 +1,57 @@ +/** + * Outbound requests honor the standard proxy variables (D-093). + * + * Node's fetch ignores HTTPS_PROXY / HTTP_PROXY / NO_PROXY unless Node itself + * was started with NODE_USE_ENV_PROXY=1 (22.21+, 24+), so a command run behind + * a proxy (Cursor's sandbox enforces its network allowlist through one, and so + * do many corporate networks) failed at its first request. When one of those + * variables is set, the CLI installs undici's EnvHttpProxyAgent as the global + * dispatcher once, at start, so every fetch — API, sign-in, downloads, the + * update check — goes through the proxy unless NO_PROXY exempts its host. On + * every Node version the CLI supports; without the variables nothing changes. + */ + +import { EnvHttpProxyAgent, setGlobalDispatcher, type Dispatcher } from "undici"; + +export interface ProxySettings { + /** Proxy for https: URLs; "" = use httpProxy. */ + httpsProxy: string; + /** Proxy for http: URLs (and https: ones when httpsProxy is ""); "" = none. */ + httpProxy: string; + /** Hosts that go direct, as NO_PROXY lists them; "" = none. */ + noProxy: string; +} + +/** The first non-blank value among names: lowercase first, as curl and undici read them. */ +function first(env: NodeJS.ProcessEnv, ...names: string[]): string { + for (const name of names) { + const value = env[name]?.trim(); + if (value) return value; + } + return ""; +} + +/** + * The proxy the environment names, or null when it names none. Unset values + * are "", never undefined: undici would otherwise read process.env again. + */ +export function proxySettings(env: NodeJS.ProcessEnv = process.env): ProxySettings | null { + const httpsProxy = first(env, "https_proxy", "HTTPS_PROXY"); + const httpProxy = first(env, "http_proxy", "HTTP_PROXY"); + if (!httpsProxy && !httpProxy) return null; + return { httpsProxy, httpProxy, noProxy: first(env, "no_proxy", "NO_PROXY") }; +} + +/** + * Routes every fetch through the proxy the environment names. Returns whether + * it did; a no-op when no proxy variable is set. + */ +export function useProxyFromEnv( + env: NodeJS.ProcessEnv = process.env, + install: (dispatcher: Dispatcher) => void = setGlobalDispatcher, +): boolean { + const settings = proxySettings(env); + if (!settings) return false; + install(new EnvHttpProxyAgent(settings)); + return true; +} diff --git a/src/root.ts b/src/root.ts index b82e484..4345343 100644 --- a/src/root.ts +++ b/src/root.ts @@ -147,6 +147,7 @@ ENVIRONMENT: MESHY_CLI_NO_UPDATE_NOTIFIER set to disable update checks MESHY_CLI_CLIENT name of the tool running meshy-cli, added to the User-Agent MESHY_CLI_AGENT AI agent named to Meshy in the User-Agent (default: detected); none = off + HTTPS_PROXY, HTTP_PROXY proxy every request goes through (lowercase too); NO_PROXY: hosts that go direct Docs: https://docs.meshy.ai/`; diff --git a/tests/proxy.test.ts b/tests/proxy.test.ts new file mode 100644 index 0000000..add3489 --- /dev/null +++ b/tests/proxy.test.ts @@ -0,0 +1,120 @@ +/** + * Outbound requests honor the standard proxy variables (D-093): with + * HTTPS_PROXY / HTTP_PROXY set, every request goes through the proxy unless + * NO_PROXY exempts its host; without them nothing changes. Cursor's sandbox + * enforces its network allowlist through such a proxy. + */ + +import test from "node:test"; +import assert from "node:assert/strict"; +import { createServer, request as httpRequest, type Server } from "node:http"; +import { connect, type AddressInfo } from "node:net"; +import { getGlobalDispatcher, setGlobalDispatcher, type Dispatcher } from "undici"; + +import { proxySettings, useProxyFromEnv } from "../src/internal/proxy.js"; +import { jsonReply, runCli, startMockApi } from "./helpers/cli.js"; + +/** A forward proxy on loopback that counts the requests it carries (plain HTTP and CONNECT). */ +async function startProxy(): Promise<{ url: string; hits: () => number; close: () => Promise }> { + let hits = 0; + const server: Server = createServer((req, res) => { + hits += 1; + const target = new URL(req.url ?? "/"); + const upstream = httpRequest( + { host: target.hostname, port: target.port, path: target.pathname + target.search, method: req.method, headers: req.headers }, + (reply) => { + res.writeHead(reply.statusCode ?? 502, reply.headers); + reply.pipe(res); + }, + ); + req.pipe(upstream); + }); + server.on("connect", (req, socket) => { + hits += 1; + const [host, port] = (req.url ?? "").split(":"); + const upstream = connect(Number(port), host ?? "127.0.0.1", () => { + socket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + upstream.pipe(socket); + socket.pipe(upstream); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `http://127.0.0.1:${port}`, + hits: () => hits, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +test("no proxy variable: no settings, nothing installed", () => { + assert.equal(proxySettings({}), null); + assert.equal(proxySettings({ HTTPS_PROXY: " ", NO_PROXY: "example.com" }), null, "blank values and NO_PROXY alone name no proxy"); + const installed: Dispatcher[] = []; + assert.equal(useProxyFromEnv({ PATH: "/usr/bin" }, (d) => installed.push(d)), false); + assert.equal(installed.length, 0); +}); + +test("proxy settings read both spellings, lowercase first, and fill what is unset with empty strings", () => { + assert.deepEqual(proxySettings({ HTTPS_PROXY: "http://proxy:3128" }), { + httpsProxy: "http://proxy:3128", + httpProxy: "", + noProxy: "", + }); + assert.deepEqual( + proxySettings({ + https_proxy: "http://lower:1", + HTTPS_PROXY: "http://upper:1", + http_proxy: "http://lower:2", + HTTP_PROXY: "http://upper:2", + no_proxy: "lower.example", + NO_PROXY: "upper.example", + }), + { httpsProxy: "http://lower:1", httpProxy: "http://lower:2", noProxy: "lower.example" }, + ); + assert.deepEqual(proxySettings({ HTTP_PROXY: "http://proxy:3128", NO_PROXY: "localhost,.internal" }), { + httpsProxy: "", + httpProxy: "http://proxy:3128", + noProxy: "localhost,.internal", + }); +}); + +test("with a proxy variable, fetch goes through the proxy, and NO_PROXY exempts a host", async (t) => { + const previous = getGlobalDispatcher(); + t.after(() => setGlobalDispatcher(previous)); + const target = createServer((_req, res) => res.end("ok")); + await new Promise((resolve) => target.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => target.close(() => resolve()))); + const proxy = await startProxy(); + t.after(proxy.close); + const url = `http://127.0.0.1:${(target.address() as AddressInfo).port}/x`; + + assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); + assert.equal(await (await fetch(url)).text(), "ok"); + assert.equal(proxy.hits(), 1, "the request went through the proxy"); + + assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url, NO_PROXY: "127.0.0.1" }), true); + assert.equal(await (await fetch(url)).text(), "ok"); + assert.equal(proxy.hits(), 1, "NO_PROXY sent it direct"); +}); + +test("the CLI's API requests go through HTTP_PROXY, and straight to the API without it", async (t) => { + const api = await startMockApi((_req, res) => jsonReply(res, 200, { balance: 7 })); + t.after(() => api.close()); + const proxy = await startProxy(); + t.after(proxy.close); + + const viaProxy = await runCli(["balance"], { env: api.env({ MESHY_API_KEY: "msy_test", HTTP_PROXY: proxy.url }) }); + assert.equal(viaProxy.code, 0, viaProxy.stderr); + assert.equal(proxy.hits(), 1, "the API request went through the proxy"); + + const direct = await runCli(["balance"], { env: api.env({ MESHY_API_KEY: "msy_test" }) }); + assert.equal(direct.code, 0, direct.stderr); + assert.equal(proxy.hits(), 1, "without a proxy variable the request goes direct"); + + const exempt = await runCli(["balance"], { + env: api.env({ MESHY_API_KEY: "msy_test", HTTP_PROXY: proxy.url, NO_PROXY: "127.0.0.1" }), + }); + assert.equal(exempt.code, 0, exempt.stderr); + assert.equal(proxy.hits(), 1, "NO_PROXY sent it direct"); +}); From f232fcba470843aba978c4ac98d7cfcee96bbada Mon Sep 17 00:00:00 2001 From: ArkXiong Date: Mon, 9 Nov 2026 17:43:26 +0800 Subject: [PATCH 2/6] fix(network): forward plain HTTP, keep loopback direct, fail closed on a bad proxy URL - http: URLs go to the proxy as plain forwarded requests (proxyTunnel: false), as curl sends them; https: still tunnels. A proxy that refuses CONNECT but forwards HTTP works. - localhost, 127.0.0.1 and [::1] always go direct, as Go's net/http does, so a local API's credential never crosses the proxy. - A proxy value that is not an http(s) URL no longer throws at start with the value (and any password) in the stack: every request fails before it leaves, naming the variable only. Local commands still run. - A proxy that refuses the request (CONNECT not 200, forwarded 407) is a request never sent: the transport classifies it as connect, so a task is recorded not_submitted rather than unknown, and the error says so. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 19 +++- docs/usage.md | 2 +- src/client/transport.ts | 6 +- src/internal/proxy.ts | 116 +++++++++++++++++---- src/root.ts | 2 +- tests/proxy.test.ts | 225 +++++++++++++++++++++++++++++++--------- 6 files changed, 296 insertions(+), 74 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 5d4ca23..4bd0660 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1639,8 +1639,23 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu `EnvHttpProxyAgent` as the global dispatcher once, so every fetch goes through it: the API, sign-in, downloads, input URL checks, and the update check's child process, which starts through the same entry point. `https:` - URLs use `HTTPS_PROXY` and fall back to `HTTP_PROXY`; hosts in `NO_PROXY` go - direct. Without a proxy variable nothing changes. + URLs use `HTTPS_PROXY` (a CONNECT tunnel) and fall back to `HTTP_PROXY`; + `http:` URLs go to the proxy as plain forwarded requests, as curl sends + them, so a proxy that only forwards still works. Without a proxy variable + nothing changes. +- Hosts in `NO_PROXY` go direct, and so does this machine (`localhost`, + `127.0.0.1`, `::1`) always, as Go's `net/http` does (Ark, 2026-11-09): a + custom `MESHY_BASE_URL_*` on loopback is a development server, and its + credential would otherwise cross the proxy in the clear. +- A proxy value that is not an `http://` or `https://` URL does not fall back + to going direct: every request fails before it leaves, with an error that + names the variable and never its value, which may hold a password. Local + commands still run. +- A request the proxy refuses (a CONNECT answered other than 200, a forwarded + request answered 407) never reached Meshy: the transport records it as + never sent (`not_submitted`), not as a submission whose outcome is unknown, + and the error says it was the proxy. undici reports these only by message; + `tests/proxy.test.ts` pins the messages of the version in the lockfile. - undici is a dependency for this alone. Node's own `http.setGlobalProxyFromEnv` does the same, but Node 22 does not have it (24.20 does); one code path covers every Node the CLI supports (22.12+), and the global dispatcher is diff --git a/docs/usage.md b/docs/usage.md index 33f6ab0..87ce77d 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -541,7 +541,7 @@ URI is accepted when its bytes are a GLB. | `MESHY_LOG_LEVEL` | `warn` | | `MESHY_CLI_CLIENT` | unset — a tool that runs meshy-cli for its users names itself here (for example `meshy-dcc/0.2.2 (blender)`); appended to the User-Agent of every request. Inside DeepSeek Harness (`DSH_SHELL=1`) it defaults to `dsh` | | `MESHY_CLI_AGENT` | unset — the AI agent running meshy-cli is detected from the variables it sets on its commands (Cursor, Claude Code, Codex, Copilot, Gemini CLI, Kiro CLI, OpenCode, Hermes, DeepSeek Harness, Cline, Roo Code, or any agent that sets `AI_AGENT`) and named in the User-Agent of API requests to Meshy (`meshy.ai`, `meshy.cn`) as `; agent [/]` inside the parentheses; requests anywhere else, sign-in, input URL checks and asset downloads leave it out. Set a name (`grok-bot`, `claude-code/desktop`: lowercase letters, digits, `.`, `-`) to name it yourself, or `none` to leave it out. `meshy doctor` shows what was detected and from which variable | -| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs and falls back to `HTTP_PROXY`. `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all). Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | +| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to the proxy as plain forwarded requests, as with curl. `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.1`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not an `http://` or `https://` URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407) was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | | `MESHY_CLI_NO_UPDATE_NOTIFIER` | unset — any non-empty value disables update checks; CI envs (`CI`, `GITHUB_ACTIONS`, `BUILD_NUMBER`, `RUN_ID`) auto-skip | ## Update notifications diff --git a/src/client/transport.ts b/src/client/transport.ts index 939cd27..b46be7b 100644 --- a/src/client/transport.ts +++ b/src/client/transport.ts @@ -23,6 +23,7 @@ import { mapHttpError, MeshyApiError } from "./errors.js"; import { logger } from "../internal/logger.js"; import { apiUserAgent } from "../internal/user-agent.js"; +import { proxyFailure } from "../internal/proxy.js"; export type TransportPhase = "validate" | "connect" | "request" | "response" | "body" | "timeout" | "aborted"; @@ -154,6 +155,8 @@ function errnoOf(err: unknown): string | undefined { const CONNECT_ERRNOS = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT", "ERR_TLS_CERT_ALTNAME_INVALID", "CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "SELF_SIGNED_CERT_IN_CHAIN"]); function classifyFetchFailure(err: unknown, phase: TransportPhase): TransportPhase { + // Failed at the proxy, before the target (D-093). + if (proxyFailure(err)) return "connect"; const errno = errnoOf(err); if (errno && CONNECT_ERRNOS.has(errno)) return "connect"; return phase; @@ -223,9 +226,10 @@ export function createTransport(cfg: TransportConfig): Transport { return new TransportError({ message: `request to ${path} timed out after ${timeoutMs}ms`, phase: "timeout", path, cause: err, credentialKind: cfg.credentialKind }); } const errno = errnoOf(err); + const proxy = proxyFailure(err); const msg = err instanceof Error ? err.message : String(err); return new TransportError({ - message: `network error calling ${path}: ${msg}${errno ? ` (${errno})` : ""}`, + message: proxy ? `${proxy} (calling ${path}); nothing was sent` : `network error calling ${path}: ${msg}${errno ? ` (${errno})` : ""}`, phase: classifyFetchFailure(err, phase), path, errno, diff --git a/src/internal/proxy.ts b/src/internal/proxy.ts index 4d348a8..ffe70d3 100644 --- a/src/internal/proxy.ts +++ b/src/internal/proxy.ts @@ -7,51 +7,127 @@ * do many corporate networks) failed at its first request. When one of those * variables is set, the CLI installs undici's EnvHttpProxyAgent as the global * dispatcher once, at start, so every fetch — API, sign-in, downloads, the - * update check — goes through the proxy unless NO_PROXY exempts its host. On - * every Node version the CLI supports; without the variables nothing changes. + * update check — goes through the proxy, on every Node version the CLI + * supports. Without the variables nothing changes. + * + * As curl does, an http: URL goes to the proxy as a plain forwarded request + * and an https: URL through a CONNECT tunnel. Hosts in NO_PROXY, and this + * machine (localhost, 127.0.0.1, ::1) always, go direct, so a credential for a + * local API never passes through the proxy in the clear. A proxy URL that + * does not parse sends nothing at all, rather than going direct, and the + * error names the variable, never its value, which may hold a password. */ -import { EnvHttpProxyAgent, setGlobalDispatcher, type Dispatcher } from "undici"; +import { Agent, EnvHttpProxyAgent, setGlobalDispatcher, type Dispatcher } from "undici"; export interface ProxySettings { /** Proxy for https: URLs; "" = use httpProxy. */ httpsProxy: string; /** Proxy for http: URLs (and https: ones when httpsProxy is ""); "" = none. */ httpProxy: string; - /** Hosts that go direct, as NO_PROXY lists them; "" = none. */ + /** Hosts that go direct, as NO_PROXY lists them, plus this machine's. */ noProxy: string; } -/** The first non-blank value among names: lowercase first, as curl and undici read them. */ -function first(env: NodeJS.ProcessEnv, ...names: string[]): string { +export type ProxyFromEnv = + | { kind: "none" } + /** The named variable holds something that is not an http: or https: URL. */ + | { kind: "invalid"; variable: string } + | { kind: "proxy"; settings: ProxySettings }; + +/** This machine: never proxied (D-093), as Go's net/http does. */ +// "[::1]" with brackets: undici matches the URL's bracketed host, and reads a +// bare "::1" as host ":" port 1. +const LOOPBACK_HOSTS = "localhost,127.0.0.1,[::1]"; + +/** The code of the error a request fails with while the proxy setting is unusable. */ +export const PROXY_INVALID_CODE = "MESHY_PROXY_INVALID"; + +/** The first variable among names with a non-blank value: lowercase first, as curl and undici read them. */ +function first(env: NodeJS.ProcessEnv, ...names: string[]): { name: string; value: string } | null { for (const name of names) { const value = env[name]?.trim(); - if (value) return value; + if (value) return { name, value }; + } + return null; +} + +function isProxyUrl(value: string): boolean { + try { + const { protocol, hostname } = new URL(value); + return (protocol === "http:" || protocol === "https:") && hostname !== ""; + } catch { + return false; } - return ""; } /** - * The proxy the environment names, or null when it names none. Unset values - * are "", never undefined: undici would otherwise read process.env again. + * The proxy the environment names. Unset values are "", never undefined: + * undici would otherwise read process.env again. */ -export function proxySettings(env: NodeJS.ProcessEnv = process.env): ProxySettings | null { - const httpsProxy = first(env, "https_proxy", "HTTPS_PROXY"); - const httpProxy = first(env, "http_proxy", "HTTP_PROXY"); - if (!httpsProxy && !httpProxy) return null; - return { httpsProxy, httpProxy, noProxy: first(env, "no_proxy", "NO_PROXY") }; +export function proxySettings(env: NodeJS.ProcessEnv = process.env): ProxyFromEnv { + const https = first(env, "https_proxy", "HTTPS_PROXY"); + const http = first(env, "http_proxy", "HTTP_PROXY"); + if (!https && !http) return { kind: "none" }; + for (const named of [https, http]) { + if (named && !isProxyUrl(named.value)) return { kind: "invalid", variable: named.name }; + } + const noProxy = first(env, "no_proxy", "NO_PROXY")?.value; + return { + kind: "proxy", + settings: { + httpsProxy: https?.value ?? "", + httpProxy: http?.value ?? "", + noProxy: noProxy ? `${noProxy},${LOOPBACK_HOSTS}` : LOOPBACK_HOSTS, + }, + }; +} + +function invalidProxyError(variable: string): Error { + const err = new Error(`${variable} is not a valid proxy URL (expected http://host:port or https://host:port); fix or unset it`); + (err as { code?: string }).code = PROXY_INVALID_CODE; + return err; } /** * Routes every fetch through the proxy the environment names. Returns whether - * it did; a no-op when no proxy variable is set. + * it installed a dispatcher; a no-op when no proxy variable is set. With an + * unusable value it installs one whose every connection fails, so nothing + * goes direct behind the user's back. */ export function useProxyFromEnv( env: NodeJS.ProcessEnv = process.env, install: (dispatcher: Dispatcher) => void = setGlobalDispatcher, ): boolean { - const settings = proxySettings(env); - if (!settings) return false; - install(new EnvHttpProxyAgent(settings)); - return true; + const proxy = proxySettings(env); + switch (proxy.kind) { + case "none": + return false; + case "invalid": + install(new Agent({ connect: (_opts, callback) => callback(invalidProxyError(proxy.variable), null) })); + return true; + case "proxy": + install(new EnvHttpProxyAgent({ ...proxy.settings, proxyTunnel: false })); + return true; + } +} + +/** undici's own errors for a proxy that refused a request (pinned by tests/proxy.test.ts). */ +const PROXY_REFUSALS = [/^Proxy response \(\d{3}\) !== 200 when HTTP Tunneling$/, /^Proxy Authentication Required \(407\)$/]; + +/** + * Why a fetch failed at the proxy, before reaching its target: the proxy + * setting is unusable, or the proxy refused the request (a CONNECT answered + * other than 200, a forwarded request answered 407). Undefined for any other + * failure. Either way the target was never reached. + */ +export function proxyFailure(err: unknown): string | undefined { + // fetch wraps it: "fetch failed" → (a refused tunnel: "Request was cancelled.") → undici's error. + let cause: unknown = err; + for (let depth = 0; depth < 5 && cause instanceof Error; depth += 1, cause = cause.cause) { + if ((cause as { code?: unknown }).code === PROXY_INVALID_CODE) return cause.message; + const { message } = cause; + if (PROXY_REFUSALS.some((re) => re.test(message))) return `the proxy refused the request: ${message}`; + } + return undefined; } diff --git a/src/root.ts b/src/root.ts index 4345343..b63fdd7 100644 --- a/src/root.ts +++ b/src/root.ts @@ -147,7 +147,7 @@ ENVIRONMENT: MESHY_CLI_NO_UPDATE_NOTIFIER set to disable update checks MESHY_CLI_CLIENT name of the tool running meshy-cli, added to the User-Agent MESHY_CLI_AGENT AI agent named to Meshy in the User-Agent (default: detected); none = off - HTTPS_PROXY, HTTP_PROXY proxy every request goes through (lowercase too); NO_PROXY: hosts that go direct + HTTPS_PROXY, HTTP_PROXY proxy every request goes through (lowercase too); NO_PROXY and localhost go direct Docs: https://docs.meshy.ai/`; diff --git a/tests/proxy.test.ts b/tests/proxy.test.ts index add3489..01b3366 100644 --- a/tests/proxy.test.ts +++ b/tests/proxy.test.ts @@ -1,8 +1,13 @@ /** * Outbound requests honor the standard proxy variables (D-093): with * HTTPS_PROXY / HTTP_PROXY set, every request goes through the proxy unless - * NO_PROXY exempts its host; without them nothing changes. Cursor's sandbox - * enforces its network allowlist through such a proxy. + * NO_PROXY exempts its host or the host is this machine; without them nothing + * changes. Cursor's sandbox enforces its network allowlist through such a + * proxy. + * + * Targets that must go through the proxy use a `.invalid` host: it never + * resolves, so a request that reaches the target at all went through the + * test proxy, which sends every host to the loopback target. */ import test from "node:test"; @@ -11,17 +16,36 @@ import { createServer, request as httpRequest, type Server } from "node:http"; import { connect, type AddressInfo } from "node:net"; import { getGlobalDispatcher, setGlobalDispatcher, type Dispatcher } from "undici"; +import { createTransport, TransportError } from "../src/client/transport.js"; import { proxySettings, useProxyFromEnv } from "../src/internal/proxy.js"; import { jsonReply, runCli, startMockApi } from "./helpers/cli.js"; -/** A forward proxy on loopback that counts the requests it carries (plain HTTP and CONNECT). */ -async function startProxy(): Promise<{ url: string; hits: () => number; close: () => Promise }> { - let hits = 0; +interface TestProxy { + url: string; + /** Plain forwarded requests, then CONNECT tunnels, it carried. */ + forwarded: () => number; + tunnels: () => number; + close: () => Promise; +} + +/** + * A forward proxy on loopback that sends every host to `targetPort` on + * 127.0.0.1. `connect` decides how it answers CONNECT: open the tunnel, or + * refuse with a status. + */ +async function startProxy(targetPort: () => number, opts: { connect?: "open" | number; forward?: "pass" | number } = {}): Promise { + let forwarded = 0; + let tunnels = 0; const server: Server = createServer((req, res) => { - hits += 1; + if (typeof opts.forward === "number") { + res.writeHead(opts.forward, { "Proxy-Authenticate": "Basic" }); + res.end(); + return; + } + forwarded += 1; const target = new URL(req.url ?? "/"); const upstream = httpRequest( - { host: target.hostname, port: target.port, path: target.pathname + target.search, method: req.method, headers: req.headers }, + { host: "127.0.0.1", port: targetPort(), path: target.pathname + target.search, method: req.method, headers: req.headers }, (reply) => { res.writeHead(reply.statusCode ?? 502, reply.headers); reply.pipe(res); @@ -29,10 +53,13 @@ async function startProxy(): Promise<{ url: string; hits: () => number; close: ( ); req.pipe(upstream); }); - server.on("connect", (req, socket) => { - hits += 1; - const [host, port] = (req.url ?? "").split(":"); - const upstream = connect(Number(port), host ?? "127.0.0.1", () => { + server.on("connect", (_req, socket) => { + if (typeof opts.connect === "number") { + socket.end(`HTTP/1.1 ${opts.connect} Refused\r\nProxy-Authenticate: Basic\r\n\r\n`); + return; + } + tunnels += 1; + const upstream = connect(targetPort(), "127.0.0.1", () => { socket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); upstream.pipe(socket); socket.pipe(upstream); @@ -42,24 +69,47 @@ async function startProxy(): Promise<{ url: string; hits: () => number; close: ( const { port } = server.address() as AddressInfo; return { url: `http://127.0.0.1:${port}`, + forwarded: () => forwarded, + tunnels: () => tunnels, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +async function startTarget(): Promise<{ port: () => number; hits: () => number; close: () => Promise }> { + let hits = 0; + const server = createServer((_req, res) => { + hits += 1; + res.setHeader("Content-Type", "application/json"); + res.end('{"ok":true}'); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { + port: () => (server.address() as AddressInfo).port, hits: () => hits, close: () => new Promise((resolve) => server.close(() => resolve())), }; } -test("no proxy variable: no settings, nothing installed", () => { - assert.equal(proxySettings({}), null); - assert.equal(proxySettings({ HTTPS_PROXY: " ", NO_PROXY: "example.com" }), null, "blank values and NO_PROXY alone name no proxy"); +/** Restores the global dispatcher a test replaced. */ +function keepDispatcher(t: { after: (fn: () => void) => void }): void { + const previous = getGlobalDispatcher(); + t.after(() => setGlobalDispatcher(previous)); +} + +const LOOPBACK = "localhost,127.0.0.1,[::1]"; + +test("no proxy variable: nothing to read, nothing installed", () => { + assert.deepEqual(proxySettings({}), { kind: "none" }); + assert.deepEqual(proxySettings({ HTTPS_PROXY: " ", NO_PROXY: "example.com" }), { kind: "none" }, "blank values and NO_PROXY alone name no proxy"); const installed: Dispatcher[] = []; assert.equal(useProxyFromEnv({ PATH: "/usr/bin" }, (d) => installed.push(d)), false); assert.equal(installed.length, 0); }); -test("proxy settings read both spellings, lowercase first, and fill what is unset with empty strings", () => { +test("proxy settings: both spellings, lowercase first; this machine always goes direct", () => { assert.deepEqual(proxySettings({ HTTPS_PROXY: "http://proxy:3128" }), { - httpsProxy: "http://proxy:3128", - httpProxy: "", - noProxy: "", + kind: "proxy", + settings: { httpsProxy: "http://proxy:3128", httpProxy: "", noProxy: LOOPBACK }, }); assert.deepEqual( proxySettings({ @@ -70,51 +120,128 @@ test("proxy settings read both spellings, lowercase first, and fill what is unse no_proxy: "lower.example", NO_PROXY: "upper.example", }), - { httpsProxy: "http://lower:1", httpProxy: "http://lower:2", noProxy: "lower.example" }, + { kind: "proxy", settings: { httpsProxy: "http://lower:1", httpProxy: "http://lower:2", noProxy: `lower.example,${LOOPBACK}` } }, ); - assert.deepEqual(proxySettings({ HTTP_PROXY: "http://proxy:3128", NO_PROXY: "localhost,.internal" }), { - httpsProxy: "", - httpProxy: "http://proxy:3128", - noProxy: "localhost,.internal", +}); + +test("an invalid proxy URL names the variable, never its value, and no request leaves", async (t) => { + keepDispatcher(t); + const target = await startTarget(); + t.after(target.close); + for (const value of ["http://user:s3cret@proxy.example:notaport", "proxy.example:3128", "ftp://proxy.example:21"]) { + assert.deepEqual(proxySettings({ HTTPS_PROXY: value }), { kind: "invalid", variable: "HTTPS_PROXY" }, value); + } + assert.deepEqual(proxySettings({ http_proxy: "::" }), { kind: "invalid", variable: "http_proxy" }); + + assert.equal(useProxyFromEnv({ HTTP_PROXY: "http://user:s3cret@proxy.example:notaport" }), true); + const transport = createTransport({ baseUrl: `http://api.example.invalid:${target.port()}/openapi/v1`, apiKey: "msy_k", readTimeoutMs: 5000 }); + await assert.rejects(transport.requestJson("POST", "/text-to-3d", { body: {} }), (e: unknown) => { + assert.ok(e instanceof TransportError); + assert.equal(e.neverSent, true, "an unusable proxy setting sends nothing"); + assert.match(e.message, /HTTP_PROXY is not a valid proxy URL/); + assert.doesNotMatch(e.message, /s3cret|user:/); + return true; }); + assert.equal(target.hits(), 0, "the request did not go direct either"); }); -test("with a proxy variable, fetch goes through the proxy, and NO_PROXY exempts a host", async (t) => { - const previous = getGlobalDispatcher(); - t.after(() => setGlobalDispatcher(previous)); - const target = createServer((_req, res) => res.end("ok")); - await new Promise((resolve) => target.listen(0, "127.0.0.1", resolve)); - t.after(() => new Promise((resolve) => target.close(() => resolve()))); - const proxy = await startProxy(); +test("an http: request goes through the proxy as a plain forward, an https: one as a tunnel", async (t) => { + keepDispatcher(t); + const target = await startTarget(); + t.after(target.close); + const proxy = await startProxy(target.port, { connect: 403 }); + t.after(proxy.close); + assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); + + const res = await fetch(`http://api.example.invalid:${target.port()}/x`); + assert.equal(res.status, 200, "a proxy that refuses CONNECT still forwards plain HTTP"); + await res.text(); + assert.equal(proxy.forwarded(), 1); + assert.equal(proxy.tunnels(), 0); +}); + +test("NO_PROXY and this machine's own addresses go direct", async (t) => { + keepDispatcher(t); + const target = await startTarget(); + t.after(target.close); + const proxy = await startProxy(target.port); t.after(proxy.close); - const url = `http://127.0.0.1:${(target.address() as AddressInfo).port}/x`; assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); - assert.equal(await (await fetch(url)).text(), "ok"); - assert.equal(proxy.hits(), 1, "the request went through the proxy"); + for (const host of ["127.0.0.1", "localhost"]) { + const res = await fetch(`http://${host}:${target.port()}/x`); + assert.equal(res.status, 200, host); + await res.text(); + } + assert.equal(proxy.forwarded() + proxy.tunnels(), 0, "this machine goes direct"); - assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url, NO_PROXY: "127.0.0.1" }), true); - assert.equal(await (await fetch(url)).text(), "ok"); - assert.equal(proxy.hits(), 1, "NO_PROXY sent it direct"); + const v6 = createServer((_req, res) => res.end("v6")); + const listening = await new Promise((resolve) => { + v6.once("error", () => resolve(false)); + v6.listen(0, "::1", () => resolve(true)); + }); + if (listening) { + try { + const res = await fetch(`http://[::1]:${(v6.address() as AddressInfo).port}/x`); + assert.equal(await res.text(), "v6"); + assert.equal(proxy.forwarded() + proxy.tunnels(), 0, "[::1] goes direct"); + } finally { + await new Promise((resolve) => v6.close(() => resolve())); + } + } else { + t.diagnostic("no IPv6 loopback here; [::1] not exercised"); + } + + assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url, NO_PROXY: "api.example.invalid" }), true); + await assert.rejects(fetch(`http://api.example.invalid:${target.port()}/x`), "a NO_PROXY host goes direct, and .invalid does not resolve"); + assert.equal(proxy.forwarded() + proxy.tunnels(), 0); }); -test("the CLI's API requests go through HTTP_PROXY, and straight to the API without it", async (t) => { +test("a proxy that refuses the request is a request never sent, and says it was the proxy", async (t) => { + keepDispatcher(t); + const target = await startTarget(); + t.after(target.close); + for (const [name, proxyOpts, scheme] of [ + ["CONNECT refused for https", { connect: 407 }, "https"], + ["plain forward refused with 407 for http", { forward: 407 }, "http"], + ] as const) { + const proxy = await startProxy(target.port, proxyOpts); + try { + assert.equal(useProxyFromEnv({ HTTPS_PROXY: proxy.url, HTTP_PROXY: proxy.url }), true); + const transport = createTransport({ baseUrl: `${scheme}://api.example.invalid:${target.port()}/openapi/v1`, apiKey: "msy_k", readTimeoutMs: 5000 }); + await assert.rejects(transport.requestJson("POST", "/text-to-3d", { body: {} }), (e: unknown) => { + assert.ok(e instanceof TransportError, name); + assert.equal(e.neverSent, true, `${name}: the API was never reached`); + assert.match(e.message, /proxy/i, name); + assert.match(e.message, /407/, name); + return true; + }); + } finally { + await proxy.close(); + } + } + assert.equal(target.hits(), 0); +}); + +test("the CLI's API requests go through HTTP_PROXY", async (t) => { const api = await startMockApi((_req, res) => jsonReply(res, 200, { balance: 7 })); t.after(() => api.close()); - const proxy = await startProxy(); + const port = Number(new URL(api.url).port); + const proxy = await startProxy(() => port); t.after(proxy.close); + const remote = (extra: Record) => + api.env({ + MESHY_API_KEY: "msy_test", + MESHY_BASE_URL_V1: `http://api.example.invalid:${port}/openapi/v1`, + MESHY_BASE_URL_V2: `http://api.example.invalid:${port}/openapi/v2`, + ...extra, + }); - const viaProxy = await runCli(["balance"], { env: api.env({ MESHY_API_KEY: "msy_test", HTTP_PROXY: proxy.url }) }); + const viaProxy = await runCli(["balance"], { env: remote({ HTTP_PROXY: proxy.url }) }); assert.equal(viaProxy.code, 0, viaProxy.stderr); - assert.equal(proxy.hits(), 1, "the API request went through the proxy"); + assert.equal(proxy.forwarded(), 1, "the API request went through the proxy"); - const direct = await runCli(["balance"], { env: api.env({ MESHY_API_KEY: "msy_test" }) }); - assert.equal(direct.code, 0, direct.stderr); - assert.equal(proxy.hits(), 1, "without a proxy variable the request goes direct"); - - const exempt = await runCli(["balance"], { - env: api.env({ MESHY_API_KEY: "msy_test", HTTP_PROXY: proxy.url, NO_PROXY: "127.0.0.1" }), - }); - assert.equal(exempt.code, 0, exempt.stderr); - assert.equal(proxy.hits(), 1, "NO_PROXY sent it direct"); + const loopback = await runCli(["balance"], { env: api.env({ MESHY_API_KEY: "msy_test", HTTP_PROXY: proxy.url }) }); + assert.equal(loopback.code, 0, loopback.stderr); + assert.equal(proxy.forwarded(), 1, "an API on this machine is reached directly"); }); From eb8ff0467e29abf102620fa3173096c4f907eb63 Mon Sep 17 00:00:00 2001 From: ArkXiong Date: Mon, 9 Nov 2026 17:59:11 +0800 Subject: [PATCH 3/6] fix(network): loopback by range, NO_PROXY as given, undici only when a proxy is set - This machine (localhost, 127.0.0.0/8, ::1) goes direct through a thin dispatcher in front of EnvHttpProxyAgent, instead of entries appended to NO_PROXY, which broke NO_PROXY=* and could not express the range. - A proxy URL is checked by building the ProxyAgent undici would build, so values that parse as URLs but that undici rejects (a bad escape, a query) fail closed with the variable named instead of throwing at start. - Sign-in, downloads and input URL checks report a proxy failure the same way, and sign-in points at the proxy variables. - undici loads only when a proxy variable is set (proxy-dispatcher.ts, a dynamic import): it cost every command about 40 ms at start. - Docs: an https:// proxy tunnels http: URLs too (undici has no switch). Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 42 ++++++++----- docs/usage.md | 2 +- src/index.ts | 2 +- src/internal/device.ts | 9 +-- src/internal/download.ts | 3 +- src/internal/file-input.ts | 3 +- src/internal/oauth.ts | 5 +- src/internal/proxy-dispatcher.ts | 79 +++++++++++++++++++++++ src/internal/proxy.ts | 105 ++++++++++++++++--------------- src/root.ts | 2 +- tests/proxy.test.ts | 68 +++++++++++++------- 11 files changed, 220 insertions(+), 100 deletions(-) create mode 100644 src/internal/proxy-dispatcher.ts diff --git a/docs/decisions.md b/docs/decisions.md index 4bd0660..a3d8e23 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1635,22 +1635,32 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu than the CLI requires. - At start, before any request, the CLI reads `https_proxy`, `HTTPS_PROXY`, `http_proxy`, `HTTP_PROXY` and `no_proxy`, `NO_PROXY` (lowercase first, as - curl and undici do). When either proxy is set it installs undici's - `EnvHttpProxyAgent` as the global dispatcher once, so every fetch goes - through it: the API, sign-in, downloads, input URL checks, and the update - check's child process, which starts through the same entry point. `https:` - URLs use `HTTPS_PROXY` (a CONNECT tunnel) and fall back to `HTTP_PROXY`; - `http:` URLs go to the proxy as plain forwarded requests, as curl sends - them, so a proxy that only forwards still works. Without a proxy variable - nothing changes. -- Hosts in `NO_PROXY` go direct, and so does this machine (`localhost`, - `127.0.0.1`, `::1`) always, as Go's `net/http` does (Ark, 2026-11-09): a - custom `MESHY_BASE_URL_*` on loopback is a development server, and its - credential would otherwise cross the proxy in the clear. -- A proxy value that is not an `http://` or `https://` URL does not fall back - to going direct: every request fails before it leaves, with an error that - names the variable and never its value, which may hold a password. Local - commands still run. + curl and undici do). When either proxy is set it installs a global + dispatcher once, so every fetch goes through it: the API, sign-in, + downloads, input URL checks, and the update check's child process, which + starts through the same entry point. Without a proxy variable nothing + changes. +- The dispatcher is undici's `EnvHttpProxyAgent`. `https:` URLs use + `HTTPS_PROXY` (a CONNECT tunnel) and fall back to `HTTP_PROXY`. `http:` URLs + go to an `http://` proxy as plain forwarded requests, as curl sends them, so + a proxy that only forwards still works. undici tunnels through an + `https://` proxy for every URL; curl would forward `http:` there, and the + only `http:` targets are a custom `MESHY_BASE_URL_*` (usually this machine, + which goes direct) and an input URL a user gives. `NO_PROXY` is passed as + given, so `*` still means every host. +- This machine always goes direct: `localhost`, `127.0.0.0/8` and `::1`, as + Go's `net/http` does (Ark, 2026-11-09). A custom `MESHY_BASE_URL_*` on + loopback is a development server, and its credential would otherwise cross + the proxy in the clear. `NO_PROXY` cannot express a range, so a thin + dispatcher in front sends loopback hosts to a plain agent and everything + else to `EnvHttpProxyAgent`. +- A proxy value undici cannot use (not `http://` or `https://`, no host, a + query, a bad escape) does not fall back to going direct: every request + fails before it leaves, with an error that names the variable and never its + value, which may hold a password. The check builds the proxy agent undici + would build, so nothing it accepts is refused. Local commands still run. + Sign-in and downloads report the same message, and sign-in points at the + proxy variables rather than at another way to sign in. - A request the proxy refuses (a CONNECT answered other than 200, a forwarded request answered 407) never reached Meshy: the transport records it as never sent (`not_submitted`), not as a submission whose outcome is unknown, diff --git a/docs/usage.md b/docs/usage.md index 87ce77d..70462c1 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -541,7 +541,7 @@ URI is accepted when its bytes are a GLB. | `MESHY_LOG_LEVEL` | `warn` | | `MESHY_CLI_CLIENT` | unset — a tool that runs meshy-cli for its users names itself here (for example `meshy-dcc/0.2.2 (blender)`); appended to the User-Agent of every request. Inside DeepSeek Harness (`DSH_SHELL=1`) it defaults to `dsh` | | `MESHY_CLI_AGENT` | unset — the AI agent running meshy-cli is detected from the variables it sets on its commands (Cursor, Claude Code, Codex, Copilot, Gemini CLI, Kiro CLI, OpenCode, Hermes, DeepSeek Harness, Cline, Roo Code, or any agent that sets `AI_AGENT`) and named in the User-Agent of API requests to Meshy (`meshy.ai`, `meshy.cn`) as `; agent [/]` inside the parentheses; requests anywhere else, sign-in, input URL checks and asset downloads leave it out. Set a name (`grok-bot`, `claude-code/desktop`: lowercase letters, digits, `.`, `-`) to name it yourself, or `none` to leave it out. `meshy doctor` shows what was detected and from which variable | -| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to the proxy as plain forwarded requests, as with curl. `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.1`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not an `http://` or `https://` URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407) was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | +| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to an `http://` proxy as plain forwarded requests, as with curl (an `https://` proxy tunnels them too). `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.0/8`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not a usable `http://` or `https://` proxy URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407) was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | | `MESHY_CLI_NO_UPDATE_NOTIFIER` | unset — any non-empty value disables update checks; CI envs (`CI`, `GITHUB_ACTIONS`, `BUILD_NUMBER`, `RUN_ID`) auto-skip | ## Update notifications diff --git a/src/index.ts b/src/index.ts index 33a9eb6..9d94012 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,7 +27,7 @@ import { useProxyFromEnv } from "./internal/proxy.js"; async function main(): Promise { // Before any request, the update check's included (D-093). - useProxyFromEnv(); + await useProxyFromEnv(); const argv = process.argv; if (argv.includes("--no-update-check")) { // Children (none today, but any future spawn) inherit the opt-out. diff --git a/src/internal/device.ts b/src/internal/device.ts index 69be08c..6168203 100644 --- a/src/internal/device.ts +++ b/src/internal/device.ts @@ -10,6 +10,7 @@ import { HintedError } from "./errors.js"; import { USER_AGENT } from "./user-agent.js"; import type { TokenResponse } from "./oauth.js"; +import { fetchErrorMessage, PROXY_HINT, proxyFailure } from "./proxy.js"; // --------------------------------------------------------------------------- // Types @@ -112,9 +113,9 @@ export async function deviceAuthorization( }); } catch (err) { throw new HintedError({ - message: `Network error contacting device authorization endpoint: ${err instanceof Error ? err.message : String(err)}`, + message: `Network error contacting device authorization endpoint: ${fetchErrorMessage(err)}`, code: "oauth_network", - hint: "Run: meshy auth login --with-key msy_...", + hint: proxyFailure(err) ? PROXY_HINT : "Run: meshy auth login --with-key msy_...", }); } @@ -227,9 +228,9 @@ async function deviceTokenOnce( }); } catch (err) { throw new HintedError({ - message: `Network error polling device token: ${err instanceof Error ? err.message : String(err)}`, + message: `Network error polling device token: ${fetchErrorMessage(err)}`, code: "oauth_network", - hint: "Run: meshy auth login", + hint: proxyFailure(err) ? PROXY_HINT : "Run: meshy auth login", }); } diff --git a/src/internal/download.ts b/src/internal/download.ts index a33d41c..f22c15a 100644 --- a/src/internal/download.ts +++ b/src/internal/download.ts @@ -34,6 +34,7 @@ import { isInside, looksLikeFile, realpathLenient, resolveWithinRoot, safeExtens import { USER_AGENT } from "./user-agent.js"; import { enumerateAssets, selectDefaultAssets, type Asset, type DefaultSelection, type SkipReason } from "./artifacts.js"; import { fileDigest, relinkMaterials, type MaterialLinkReport } from "./material-links.js"; +import { fetchErrorMessage } from "./proxy.js"; /** Extensions sharp can transcode between. */ const CONVERTIBLE_IMAGE_EXTS = new Set(["jpg", "jpeg", "png", "webp", "gif", "tiff", "tif", "avif"]); @@ -147,7 +148,7 @@ export async function fetchToTemp(rawUrl: string, target: string, opts: FetchOpt } catch (err) { if (opts.signal?.aborted) throw new CliError({ code: "interrupted", message: `download of ${redact(url)} interrupted` }); if (controller.signal.aborted) throw new CliError({ code: "network", message: `download of ${redact(url)} timed out after ${limits.timeoutMs}ms` }); - throw new CliError({ code: "network", message: `download of ${redact(url)} failed: ${err instanceof Error ? err.message : String(err)}`, cause: err }); + throw new CliError({ code: "network", message: `download of ${redact(url)} failed: ${fetchErrorMessage(err)}`, cause: err }); } if (r.status >= 300 && r.status < 400) { const loc = r.headers.get("location"); diff --git a/src/internal/file-input.ts b/src/internal/file-input.ts index a9f73d0..6709020 100644 --- a/src/internal/file-input.ts +++ b/src/internal/file-input.ts @@ -22,6 +22,7 @@ import type { MediaField, MediaKind } from "../client/resource-registry.js"; import { UsageError } from "./errors.js"; import { logger } from "./logger.js"; import { USER_AGENT } from "./user-agent.js"; +import { fetchErrorMessage } from "./proxy.js"; export const DEFAULT_MEDIA_LIMITS = { /** 50 MiB — an engineering default, not a Meshy product limit. */ @@ -179,7 +180,7 @@ async function preflightUrl(url: string, flagLabel: string, limits: MediaLimits, controller.abort(); } } catch (err) { - const msg = err instanceof Error ? err.message : String(err); + const msg = fetchErrorMessage(err); if (timeout.aborted) throw new UsageError(`${flagLabel}: preflight of ${url} timed out after ${limits.preflightTimeoutMs}ms`); throw new UsageError(`${flagLabel}: cannot reach ${url} (${msg})`); } diff --git a/src/internal/oauth.ts b/src/internal/oauth.ts index 779e54f..b324003 100644 --- a/src/internal/oauth.ts +++ b/src/internal/oauth.ts @@ -22,6 +22,7 @@ import type { CredentialAccount } from "./credentials.js"; import { HintedError } from "./errors.js"; import { USER_AGENT } from "./user-agent.js"; import { renderCallbackPage } from "./oauth-page.js"; +import { fetchErrorMessage, PROXY_HINT, proxyFailure } from "./proxy.js"; // --------------------------------------------------------------------------- // PKCE helpers @@ -350,9 +351,9 @@ async function postToken( }); } catch (err) { throw new HintedError({ - message: `Network error contacting token endpoint: ${err instanceof Error ? err.message : String(err)}`, + message: `Network error contacting token endpoint: ${fetchErrorMessage(err)}`, code: "oauth_network", - hint: "Run: meshy auth login", + hint: proxyFailure(err) ? PROXY_HINT : "Run: meshy auth login", }); } diff --git a/src/internal/proxy-dispatcher.ts b/src/internal/proxy-dispatcher.ts new file mode 100644 index 0000000..311e7a2 --- /dev/null +++ b/src/internal/proxy-dispatcher.ts @@ -0,0 +1,79 @@ +/** + * The undici side of D-093, loaded only when a proxy variable is set (see + * proxy.ts): checking proxy URLs as undici would use them, and the global + * dispatcher that sends this machine direct and everything else through + * EnvHttpProxyAgent. + */ + +import { Agent, Dispatcher, EnvHttpProxyAgent, ProxyAgent, setGlobalDispatcher } from "undici"; + +import { isLoopbackHost, PROXY_INVALID_CODE, type ProxyFromEnv } from "./proxy.js"; + +/** Whether undici accepts value as a proxy URL: http(s), a host, nothing it cannot decode. */ +export function isUsableProxyUrl(value: string): boolean { + try { + const { protocol, hostname } = new URL(value); + if ((protocol !== "http:" && protocol !== "https:") || hostname === "") return false; + void new ProxyAgent({ uri: value }).close(); + return true; + } catch { + return false; + } +} + +/** + * Sends requests for this machine (localhost, 127.0.0.0/8, ::1) direct and + * every other one through the proxy dispatcher. NO_PROXY cannot express a + * range, and appending hosts to it would break NO_PROXY=*. + */ +class LoopbackDirect extends Dispatcher { + constructor( + private readonly proxied: Dispatcher, + private readonly direct: Dispatcher, + ) { + super(); + } + + override dispatch(opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean { + const origin = opts.origin === undefined ? undefined : new URL(String(opts.origin)); + return (origin && isLoopbackHost(origin.hostname) ? this.direct : this.proxied).dispatch(opts, handler); + } + + override close(): Promise; + override close(callback: () => void): void; + override close(callback?: () => void): Promise | void { + const done = Promise.all([this.proxied.close(), this.direct.close()]).then(() => undefined); + if (!callback) return done; + void done.then(callback); + } + + override destroy(): Promise; + override destroy(err: Error | null): Promise; + override destroy(callback: () => void): void; + override destroy(err: Error | null, callback: () => void): void; + override destroy(errOrCallback?: Error | null | (() => void), callback?: () => void): Promise | void { + const err = typeof errOrCallback === "function" ? null : (errOrCallback ?? null); + const cb = typeof errOrCallback === "function" ? errOrCallback : callback; + const done = Promise.all([this.proxied.destroy(err), this.direct.destroy(err)]).then(() => undefined); + if (!cb) return done; + void done.then(cb); + } +} + +function invalidProxyError(variable: string): Error { + const err = new Error(`${variable} is not a valid proxy URL (expected http://host:port or https://host:port); fix or unset it`); + (err as { code?: string }).code = PROXY_INVALID_CODE; + return err; +} + +/** Installs the global dispatcher for a proxy setting, or one whose every connection fails for an unusable one. */ +export function installProxy( + proxy: Exclude, + install: (dispatcher: Dispatcher) => void = setGlobalDispatcher, +): void { + if (proxy.kind === "invalid") { + install(new Agent({ connect: (_opts, callback) => callback(invalidProxyError(proxy.variable), null) })); + return; + } + install(new LoopbackDirect(new EnvHttpProxyAgent({ ...proxy.settings, proxyTunnel: false }), new Agent())); +} diff --git a/src/internal/proxy.ts b/src/internal/proxy.ts index ffe70d3..5b95fbe 100644 --- a/src/internal/proxy.ts +++ b/src/internal/proxy.ts @@ -5,44 +5,46 @@ * was started with NODE_USE_ENV_PROXY=1 (22.21+, 24+), so a command run behind * a proxy (Cursor's sandbox enforces its network allowlist through one, and so * do many corporate networks) failed at its first request. When one of those - * variables is set, the CLI installs undici's EnvHttpProxyAgent as the global - * dispatcher once, at start, so every fetch — API, sign-in, downloads, the - * update check — goes through the proxy, on every Node version the CLI - * supports. Without the variables nothing changes. + * variables is set, the CLI installs a global dispatcher once, at start, so + * every fetch — API, sign-in, downloads, the update check — goes through the + * proxy, on every Node version the CLI supports. Without the variables + * nothing changes. * - * As curl does, an http: URL goes to the proxy as a plain forwarded request - * and an https: URL through a CONNECT tunnel. Hosts in NO_PROXY, and this - * machine (localhost, 127.0.0.1, ::1) always, go direct, so a credential for a - * local API never passes through the proxy in the clear. A proxy URL that - * does not parse sends nothing at all, rather than going direct, and the - * error names the variable, never its value, which may hold a password. + * - An http: URL goes to an http:// proxy as a plain forwarded request, as + * curl sends it; an https: URL goes through a CONNECT tunnel. undici always + * tunnels through an https:// proxy, http: URLs included. + * - Hosts in NO_PROXY go direct, and this machine always does (localhost, + * 127.0.0.0/8, ::1), as Go's net/http does, so a credential for a local API + * never crosses the proxy in the clear. + * - A proxy value undici cannot use sends nothing at all, rather than going + * direct, and the error names the variable, never its value, which may hold + * a password. */ -import { Agent, EnvHttpProxyAgent, setGlobalDispatcher, type Dispatcher } from "undici"; +import { BlockList, isIP } from "node:net"; +import type { Dispatcher } from "undici"; export interface ProxySettings { /** Proxy for https: URLs; "" = use httpProxy. */ httpsProxy: string; /** Proxy for http: URLs (and https: ones when httpsProxy is ""); "" = none. */ httpProxy: string; - /** Hosts that go direct, as NO_PROXY lists them, plus this machine's. */ + /** Hosts that go direct, as NO_PROXY lists them; "" = none. */ noProxy: string; } export type ProxyFromEnv = | { kind: "none" } - /** The named variable holds something that is not an http: or https: URL. */ + /** The named variable holds something undici cannot use as a proxy. */ | { kind: "invalid"; variable: string } | { kind: "proxy"; settings: ProxySettings }; -/** This machine: never proxied (D-093), as Go's net/http does. */ -// "[::1]" with brackets: undici matches the URL's bracketed host, and reads a -// bare "::1" as host ":" port 1. -const LOOPBACK_HOSTS = "localhost,127.0.0.1,[::1]"; - /** The code of the error a request fails with while the proxy setting is unusable. */ export const PROXY_INVALID_CODE = "MESHY_PROXY_INVALID"; +/** What to check when a request failed at the proxy. */ +export const PROXY_HINT = "Check HTTPS_PROXY, HTTP_PROXY and NO_PROXY (or unset them)"; + /** The first variable among names with a non-blank value: lowercase first, as curl and undici read them. */ function first(env: NodeJS.ProcessEnv, ...names: string[]): { name: string; value: string } | null { for (const name of names) { @@ -52,64 +54,60 @@ function first(env: NodeJS.ProcessEnv, ...names: string[]): { name: string; valu return null; } -function isProxyUrl(value: string): boolean { - try { - const { protocol, hostname } = new URL(value); - return (protocol === "http:" || protocol === "https:") && hostname !== ""; - } catch { - return false; - } -} - /** * The proxy the environment names. Unset values are "", never undefined: - * undici would otherwise read process.env again. + * undici would otherwise read process.env again. undici, which checks the + * URLs, is loaded only when a proxy variable is set: every command pays for + * it otherwise (~40 ms at start). */ -export function proxySettings(env: NodeJS.ProcessEnv = process.env): ProxyFromEnv { +export async function proxySettings(env: NodeJS.ProcessEnv = process.env): Promise { const https = first(env, "https_proxy", "HTTPS_PROXY"); const http = first(env, "http_proxy", "HTTP_PROXY"); if (!https && !http) return { kind: "none" }; + const { isUsableProxyUrl } = await import("./proxy-dispatcher.js"); for (const named of [https, http]) { - if (named && !isProxyUrl(named.value)) return { kind: "invalid", variable: named.name }; + if (named && !isUsableProxyUrl(named.value)) return { kind: "invalid", variable: named.name }; } - const noProxy = first(env, "no_proxy", "NO_PROXY")?.value; return { kind: "proxy", settings: { httpsProxy: https?.value ?? "", httpProxy: http?.value ?? "", - noProxy: noProxy ? `${noProxy},${LOOPBACK_HOSTS}` : LOOPBACK_HOSTS, + noProxy: first(env, "no_proxy", "NO_PROXY")?.value ?? "", }, }; } -function invalidProxyError(variable: string): Error { - const err = new Error(`${variable} is not a valid proxy URL (expected http://host:port or https://host:port); fix or unset it`); - (err as { code?: string }).code = PROXY_INVALID_CODE; - return err; +// BlockList also matches an IPv4-mapped IPv6 address (::ffff:127.0.0.1) against the IPv4 rule. +const LOOPBACK = new BlockList(); +LOOPBACK.addSubnet("127.0.0.0", 8, "ipv4"); +LOOPBACK.addAddress("::1", "ipv6"); + +/** Whether a URL hostname is this machine: localhost, 127.0.0.0/8, ::1 (bracketed or not). */ +export function isLoopbackHost(hostname: string): boolean { + const host = hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase(); + if (host === "localhost") return true; + const family = isIP(host); + if (family === 4) return LOOPBACK.check(host, "ipv4"); + if (family === 6) return LOOPBACK.check(host, "ipv6"); + return false; } /** * Routes every fetch through the proxy the environment names. Returns whether * it installed a dispatcher; a no-op when no proxy variable is set. With an * unusable value it installs one whose every connection fails, so nothing - * goes direct behind the user's back. + * goes direct behind the user's back. Never throws. */ -export function useProxyFromEnv( +export async function useProxyFromEnv( env: NodeJS.ProcessEnv = process.env, - install: (dispatcher: Dispatcher) => void = setGlobalDispatcher, -): boolean { - const proxy = proxySettings(env); - switch (proxy.kind) { - case "none": - return false; - case "invalid": - install(new Agent({ connect: (_opts, callback) => callback(invalidProxyError(proxy.variable), null) })); - return true; - case "proxy": - install(new EnvHttpProxyAgent({ ...proxy.settings, proxyTunnel: false })); - return true; - } + install?: (dispatcher: Dispatcher) => void, +): Promise { + const proxy = await proxySettings(env); + if (proxy.kind === "none") return false; + const { installProxy } = await import("./proxy-dispatcher.js"); + installProxy(proxy, install); + return true; } /** undici's own errors for a proxy that refused a request (pinned by tests/proxy.test.ts). */ @@ -131,3 +129,8 @@ export function proxyFailure(err: unknown): string | undefined { } return undefined; } + +/** A fetch failure for a message: the proxy's part when it failed there, else the error's own. */ +export function fetchErrorMessage(err: unknown): string { + return proxyFailure(err) ?? (err instanceof Error ? err.message : String(err)); +} diff --git a/src/root.ts b/src/root.ts index b63fdd7..7349949 100644 --- a/src/root.ts +++ b/src/root.ts @@ -147,7 +147,7 @@ ENVIRONMENT: MESHY_CLI_NO_UPDATE_NOTIFIER set to disable update checks MESHY_CLI_CLIENT name of the tool running meshy-cli, added to the User-Agent MESHY_CLI_AGENT AI agent named to Meshy in the User-Agent (default: detected); none = off - HTTPS_PROXY, HTTP_PROXY proxy every request goes through (lowercase too); NO_PROXY and localhost go direct + HTTPS_PROXY, HTTP_PROXY proxy every request goes through (lowercase too); NO_PROXY hosts and this machine go direct Docs: https://docs.meshy.ai/`; diff --git a/tests/proxy.test.ts b/tests/proxy.test.ts index 01b3366..32ba0f1 100644 --- a/tests/proxy.test.ts +++ b/tests/proxy.test.ts @@ -17,7 +17,8 @@ import { connect, type AddressInfo } from "node:net"; import { getGlobalDispatcher, setGlobalDispatcher, type Dispatcher } from "undici"; import { createTransport, TransportError } from "../src/client/transport.js"; -import { proxySettings, useProxyFromEnv } from "../src/internal/proxy.js"; +import { deviceAuthorization } from "../src/internal/device.js"; +import { isLoopbackHost, PROXY_HINT, proxySettings, useProxyFromEnv } from "../src/internal/proxy.js"; import { jsonReply, runCli, startMockApi } from "./helpers/cli.js"; interface TestProxy { @@ -96,23 +97,21 @@ function keepDispatcher(t: { after: (fn: () => void) => void }): void { t.after(() => setGlobalDispatcher(previous)); } -const LOOPBACK = "localhost,127.0.0.1,[::1]"; - -test("no proxy variable: nothing to read, nothing installed", () => { - assert.deepEqual(proxySettings({}), { kind: "none" }); - assert.deepEqual(proxySettings({ HTTPS_PROXY: " ", NO_PROXY: "example.com" }), { kind: "none" }, "blank values and NO_PROXY alone name no proxy"); +test("no proxy variable: nothing to read, nothing installed", async () => { + assert.deepEqual(await proxySettings({}), { kind: "none" }); + assert.deepEqual(await proxySettings({ HTTPS_PROXY: " ", NO_PROXY: "example.com" }), { kind: "none" }, "blank values and NO_PROXY alone name no proxy"); const installed: Dispatcher[] = []; - assert.equal(useProxyFromEnv({ PATH: "/usr/bin" }, (d) => installed.push(d)), false); + assert.equal(await useProxyFromEnv({ PATH: "/usr/bin" }, (d) => installed.push(d)), false); assert.equal(installed.length, 0); }); -test("proxy settings: both spellings, lowercase first; this machine always goes direct", () => { - assert.deepEqual(proxySettings({ HTTPS_PROXY: "http://proxy:3128" }), { +test("proxy settings: both spellings, lowercase first", async () => { + assert.deepEqual(await proxySettings({ HTTPS_PROXY: "http://proxy:3128/" }), { kind: "proxy", - settings: { httpsProxy: "http://proxy:3128", httpProxy: "", noProxy: LOOPBACK }, + settings: { httpsProxy: "http://proxy:3128/", httpProxy: "", noProxy: "" }, }); assert.deepEqual( - proxySettings({ + await proxySettings({ https_proxy: "http://lower:1", HTTPS_PROXY: "http://upper:1", http_proxy: "http://lower:2", @@ -120,20 +119,35 @@ test("proxy settings: both spellings, lowercase first; this machine always goes no_proxy: "lower.example", NO_PROXY: "upper.example", }), - { kind: "proxy", settings: { httpsProxy: "http://lower:1", httpProxy: "http://lower:2", noProxy: `lower.example,${LOOPBACK}` } }, + { kind: "proxy", settings: { httpsProxy: "http://lower:1", httpProxy: "http://lower:2", noProxy: "lower.example" } }, ); }); +test("this machine is localhost, 127.0.0.0/8 and ::1, in any spelling a URL gives", () => { + for (const host of ["localhost", "LOCALHOST", "127.0.0.1", "127.0.0.2", "127.255.255.254", "[::1]", "::1", new URL("http://[::ffff:127.0.0.1]/").hostname]) { + assert.equal(isLoopbackHost(host), true, host); + } + for (const host of ["128.0.0.1", "10.0.0.1", "[::2]", "localhost.example", "example.com", "0.0.0.0"]) { + assert.equal(isLoopbackHost(host), false, host); + } +}); + test("an invalid proxy URL names the variable, never its value, and no request leaves", async (t) => { keepDispatcher(t); const target = await startTarget(); t.after(target.close); - for (const value of ["http://user:s3cret@proxy.example:notaport", "proxy.example:3128", "ftp://proxy.example:21"]) { - assert.deepEqual(proxySettings({ HTTPS_PROXY: value }), { kind: "invalid", variable: "HTTPS_PROXY" }, value); + for (const value of [ + "http://user:s3cret@proxy.example:notaport", + "proxy.example:3128", + "ftp://proxy.example:21", + "http://user:%E0%A4%A@proxy.example:8080", + "http://proxy.example:8080/?x=1", + ]) { + assert.deepEqual(await proxySettings({ HTTPS_PROXY: value }), { kind: "invalid", variable: "HTTPS_PROXY" }, value); } - assert.deepEqual(proxySettings({ http_proxy: "::" }), { kind: "invalid", variable: "http_proxy" }); + assert.deepEqual(await proxySettings({ http_proxy: "::" }), { kind: "invalid", variable: "http_proxy" }); - assert.equal(useProxyFromEnv({ HTTP_PROXY: "http://user:s3cret@proxy.example:notaport" }), true); + assert.equal(await useProxyFromEnv({ HTTP_PROXY: "http://user:s3cret@proxy.example:notaport" }), true); const transport = createTransport({ baseUrl: `http://api.example.invalid:${target.port()}/openapi/v1`, apiKey: "msy_k", readTimeoutMs: 5000 }); await assert.rejects(transport.requestJson("POST", "/text-to-3d", { body: {} }), (e: unknown) => { assert.ok(e instanceof TransportError); @@ -143,6 +157,14 @@ test("an invalid proxy URL names the variable, never its value, and no request l return true; }); assert.equal(target.hits(), 0, "the request did not go direct either"); + + await assert.rejects(deviceAuthorization(`http://api.example.invalid:${target.port()}/openapi/v1`), (e: unknown) => { + const err = e as { message: string; hint?: string }; + assert.match(err.message, /HTTP_PROXY is not a valid proxy URL/, "sign-in names the variable too"); + assert.doesNotMatch(err.message, /s3cret/); + assert.equal(err.hint, PROXY_HINT, "and points at the proxy, not at another way to sign in"); + return true; + }); }); test("an http: request goes through the proxy as a plain forward, an https: one as a tunnel", async (t) => { @@ -151,7 +173,7 @@ test("an http: request goes through the proxy as a plain forward, an https: one t.after(target.close); const proxy = await startProxy(target.port, { connect: 403 }); t.after(proxy.close); - assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); + assert.equal(await useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); const res = await fetch(`http://api.example.invalid:${target.port()}/x`); assert.equal(res.status, 200, "a proxy that refuses CONNECT still forwards plain HTTP"); @@ -167,7 +189,7 @@ test("NO_PROXY and this machine's own addresses go direct", async (t) => { const proxy = await startProxy(target.port); t.after(proxy.close); - assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); + assert.equal(await useProxyFromEnv({ HTTP_PROXY: proxy.url }), true); for (const host of ["127.0.0.1", "localhost"]) { const res = await fetch(`http://${host}:${target.port()}/x`); assert.equal(res.status, 200, host); @@ -192,9 +214,11 @@ test("NO_PROXY and this machine's own addresses go direct", async (t) => { t.diagnostic("no IPv6 loopback here; [::1] not exercised"); } - assert.equal(useProxyFromEnv({ HTTP_PROXY: proxy.url, NO_PROXY: "api.example.invalid" }), true); - await assert.rejects(fetch(`http://api.example.invalid:${target.port()}/x`), "a NO_PROXY host goes direct, and .invalid does not resolve"); - assert.equal(proxy.forwarded() + proxy.tunnels(), 0); + for (const noProxy of ["api.example.invalid", "*"]) { + assert.equal(await useProxyFromEnv({ HTTP_PROXY: proxy.url, NO_PROXY: noProxy }), true); + await assert.rejects(fetch(`http://api.example.invalid:${target.port()}/x`), `NO_PROXY=${noProxy} goes direct, and .invalid does not resolve`); + assert.equal(proxy.forwarded() + proxy.tunnels(), 0, `NO_PROXY=${noProxy}`); + } }); test("a proxy that refuses the request is a request never sent, and says it was the proxy", async (t) => { @@ -207,7 +231,7 @@ test("a proxy that refuses the request is a request never sent, and says it was ] as const) { const proxy = await startProxy(target.port, proxyOpts); try { - assert.equal(useProxyFromEnv({ HTTPS_PROXY: proxy.url, HTTP_PROXY: proxy.url }), true); + assert.equal(await useProxyFromEnv({ HTTPS_PROXY: proxy.url, HTTP_PROXY: proxy.url }), true); const transport = createTransport({ baseUrl: `${scheme}://api.example.invalid:${target.port()}/openapi/v1`, apiKey: "msy_k", readTimeoutMs: 5000 }); await assert.rejects(transport.requestJson("POST", "/text-to-3d", { body: {} }), (e: unknown) => { assert.ok(e instanceof TransportError, name); From 99eb42216762271d3d5b7895ab6148b2445a0e92 Mon Sep 17 00:00:00 2001 From: ArkXiong Date: Mon, 9 Nov 2026 18:07:35 +0800 Subject: [PATCH 4/6] docs(decisions): D-093 records the accepted https-proxy limit Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index a3d8e23..8b8715d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1646,8 +1646,9 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu a proxy that only forwards still works. undici tunnels through an `https://` proxy for every URL; curl would forward `http:` there, and the only `http:` targets are a custom `MESHY_BASE_URL_*` (usually this machine, - which goes direct) and an input URL a user gives. `NO_PROXY` is passed as - given, so `*` still means every host. + which goes direct) and an input URL a user gives; Ark accepted this limit + on 2026-11-09 rather than a hand-written forwarding client. `NO_PROXY` is + passed as given, so `*` still means every host. - This machine always goes direct: `localhost`, `127.0.0.0/8` and `::1`, as Go's `net/http` does (Ark, 2026-11-09). A custom `MESHY_BASE_URL_*` on loopback is a development server, and its credential would otherwise cross From a32fbbb1a43e68fda6d351e9b7b2b13dbc1b1a86 Mon Sep 17 00:00:00 2001 From: ArkXiong Date: Mon, 9 Nov 2026 18:17:41 +0800 Subject: [PATCH 5/6] fix(network): a failed TLS handshake with an https:// proxy is a request never sent undici wraps a certificate-name mismatch with an https:// proxy as SecureProxyConnectionError (UND_ERR_PRX_TLS), which the transport did not count as a connect failure, so a create that never left was recorded with an unknown outcome. proxyFailure() now recognizes it, and the message says the TLS connection to the proxy failed. Other certificate and connection errors with the proxy already arrive as their own errno. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 10 +++++++--- docs/usage.md | 2 +- src/internal/proxy.ts | 16 ++++++++++++---- tests/proxy.test.ts | 21 ++++++++++++++++++++- 4 files changed, 40 insertions(+), 9 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 8b8715d..4ef5e47 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1663,9 +1663,13 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu Sign-in and downloads report the same message, and sign-in points at the proxy variables rather than at another way to sign in. - A request the proxy refuses (a CONNECT answered other than 200, a forwarded - request answered 407) never reached Meshy: the transport records it as - never sent (`not_submitted`), not as a submission whose outcome is unknown, - and the error says it was the proxy. undici reports these only by message; + request answered 407), or whose TLS handshake with an `https://` proxy fails, + never reached Meshy: the transport records it as never sent + (`not_submitted`), not as a submission whose outcome is unknown, and the + error says it was the proxy. undici reports refusals only by message and + wraps only a certificate-name mismatch with the proxy (`UND_ERR_PRX_TLS`); + other certificate and connection errors with the proxy arrive as their own + errno, which the transport already counts as never sent. `tests/proxy.test.ts` pins the messages of the version in the lockfile. - undici is a dependency for this alone. Node's own `http.setGlobalProxyFromEnv` does the same, but Node 22 does not have it (24.20 does); one code path diff --git a/docs/usage.md b/docs/usage.md index 70462c1..b5296c8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -541,7 +541,7 @@ URI is accepted when its bytes are a GLB. | `MESHY_LOG_LEVEL` | `warn` | | `MESHY_CLI_CLIENT` | unset — a tool that runs meshy-cli for its users names itself here (for example `meshy-dcc/0.2.2 (blender)`); appended to the User-Agent of every request. Inside DeepSeek Harness (`DSH_SHELL=1`) it defaults to `dsh` | | `MESHY_CLI_AGENT` | unset — the AI agent running meshy-cli is detected from the variables it sets on its commands (Cursor, Claude Code, Codex, Copilot, Gemini CLI, Kiro CLI, OpenCode, Hermes, DeepSeek Harness, Cline, Roo Code, or any agent that sets `AI_AGENT`) and named in the User-Agent of API requests to Meshy (`meshy.ai`, `meshy.cn`) as `; agent [/]` inside the parentheses; requests anywhere else, sign-in, input URL checks and asset downloads leave it out. Set a name (`grok-bot`, `claude-code/desktop`: lowercase letters, digits, `.`, `-`) to name it yourself, or `none` to leave it out. `meshy doctor` shows what was detected and from which variable | -| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to an `http://` proxy as plain forwarded requests, as with curl (an `https://` proxy tunnels them too). `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.0/8`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not a usable `http://` or `https://` proxy URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407) was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | +| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to an `http://` proxy as plain forwarded requests, as with curl (an `https://` proxy tunnels them too). `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.0/8`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not a usable `http://` or `https://` proxy URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407), or whose TLS handshake with an `https://` proxy fails, was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | | `MESHY_CLI_NO_UPDATE_NOTIFIER` | unset — any non-empty value disables update checks; CI envs (`CI`, `GITHUB_ACTIONS`, `BUILD_NUMBER`, `RUN_ID`) auto-skip | ## Update notifications diff --git a/src/internal/proxy.ts b/src/internal/proxy.ts index 5b95fbe..2561cc4 100644 --- a/src/internal/proxy.ts +++ b/src/internal/proxy.ts @@ -115,15 +115,23 @@ const PROXY_REFUSALS = [/^Proxy response \(\d{3}\) !== 200 when HTTP Tunneling$/ /** * Why a fetch failed at the proxy, before reaching its target: the proxy - * setting is unusable, or the proxy refused the request (a CONNECT answered - * other than 200, a forwarded request answered 407). Undefined for any other - * failure. Either way the target was never reached. + * setting is unusable, the TLS connection to an https:// proxy failed on its + * certificate's name (undici wraps only that one, as UND_ERR_PRX_TLS; other + * certificate and connection errors reach the transport as their own errno), + * or the proxy refused the request (a CONNECT answered other than 200, a + * forwarded request answered 407). Undefined for any other failure. Either + * way the target was never reached. */ export function proxyFailure(err: unknown): string | undefined { // fetch wraps it: "fetch failed" → (a refused tunnel: "Request was cancelled.") → undici's error. let cause: unknown = err; for (let depth = 0; depth < 5 && cause instanceof Error; depth += 1, cause = cause.cause) { - if ((cause as { code?: unknown }).code === PROXY_INVALID_CODE) return cause.message; + const { code } = cause as { code?: unknown }; + if (code === PROXY_INVALID_CODE) return cause.message; + if (code === "UND_ERR_PRX_TLS") { + const reason = cause.cause instanceof Error ? cause.cause.message : cause.message; + return `the TLS connection to the proxy failed: ${reason}`; + } const { message } = cause; if (PROXY_REFUSALS.some((re) => re.test(message))) return `the proxy refused the request: ${message}`; } diff --git a/tests/proxy.test.ts b/tests/proxy.test.ts index 32ba0f1..4e2d937 100644 --- a/tests/proxy.test.ts +++ b/tests/proxy.test.ts @@ -14,7 +14,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createServer, request as httpRequest, type Server } from "node:http"; import { connect, type AddressInfo } from "node:net"; -import { getGlobalDispatcher, setGlobalDispatcher, type Dispatcher } from "undici"; +import { errors, getGlobalDispatcher, setGlobalDispatcher, type Dispatcher } from "undici"; import { createTransport, TransportError } from "../src/client/transport.js"; import { deviceAuthorization } from "../src/internal/device.js"; @@ -247,6 +247,25 @@ test("a proxy that refuses the request is a request never sent, and says it was assert.equal(target.hits(), 0); }); +test("a failed TLS handshake with an https:// proxy is a request never sent", async () => { + // fetch's error when an https:// proxy's certificate does not match its + // name, as undici 7 builds it (TypeError → SecureProxyConnectionError → the + // TLS error). Reproducing it for real needs a CA the test process trusts. + const tls = Object.assign(new Error("Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the cert's list: "), { + code: "ERR_TLS_CERT_ALTNAME_INVALID", + }); + const fetchImpl = (async () => { + throw new TypeError("fetch failed", { cause: new errors.SecureProxyConnectionError(tls) }); + }) as unknown as typeof fetch; + const transport = createTransport({ baseUrl: "https://api.meshy.ai/openapi/v1", apiKey: "msy_k", readTimeoutMs: 5000, fetchImpl }); + await assert.rejects(transport.requestJson("POST", "/text-to-3d", { body: {} }), (e: unknown) => { + assert.ok(e instanceof TransportError); + assert.equal(e.neverSent, true, "the target was never reached"); + assert.match(e.message, /TLS connection to the proxy failed: Hostname\/IP does not match/); + return true; + }); +}); + test("the CLI's API requests go through HTTP_PROXY", async (t) => { const api = await startMockApi((_req, res) => jsonReply(res, 200, { balance: 7 })); t.after(() => api.close()); From cf1234bfe4b1c37309d861bc3ca07123ffda095c Mon Sep 17 00:00:00 2001 From: ArkXiong Date: Mon, 9 Nov 2026 18:22:24 +0800 Subject: [PATCH 6/6] docs(decisions): D-093 narrows never-sent to the proxy certificate check Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 17 +++++++++-------- docs/usage.md | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 4ef5e47..da3ea91 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1663,14 +1663,15 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu Sign-in and downloads report the same message, and sign-in points at the proxy variables rather than at another way to sign in. - A request the proxy refuses (a CONNECT answered other than 200, a forwarded - request answered 407), or whose TLS handshake with an `https://` proxy fails, - never reached Meshy: the transport records it as never sent - (`not_submitted`), not as a submission whose outcome is unknown, and the - error says it was the proxy. undici reports refusals only by message and - wraps only a certificate-name mismatch with the proxy (`UND_ERR_PRX_TLS`); - other certificate and connection errors with the proxy arrive as their own - errno, which the transport already counts as never sent. - `tests/proxy.test.ts` pins the messages of the version in the lockfile. + request answered 407), or whose `https://` proxy fails the certificate check + (a name mismatch, which undici wraps as `UND_ERR_PRX_TLS`; an untrusted or + expired certificate, which arrives as its own errno), never reached Meshy: + the transport records it as never sent (`not_submitted`), not as a + submission whose outcome is unknown, and the error says it was the proxy. + Other TLS failures with the proxy (an `https://` proxy URL pointing at a + plain HTTP port, say) are still recorded as unknown, the conservative side. + undici reports refusals only by message; `tests/proxy.test.ts` pins the + messages of the version in the lockfile. - undici is a dependency for this alone. Node's own `http.setGlobalProxyFromEnv` does the same, but Node 22 does not have it (24.20 does); one code path covers every Node the CLI supports (22.12+), and the global dispatcher is diff --git a/docs/usage.md b/docs/usage.md index b5296c8..99b43a9 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -541,7 +541,7 @@ URI is accepted when its bytes are a GLB. | `MESHY_LOG_LEVEL` | `warn` | | `MESHY_CLI_CLIENT` | unset — a tool that runs meshy-cli for its users names itself here (for example `meshy-dcc/0.2.2 (blender)`); appended to the User-Agent of every request. Inside DeepSeek Harness (`DSH_SHELL=1`) it defaults to `dsh` | | `MESHY_CLI_AGENT` | unset — the AI agent running meshy-cli is detected from the variables it sets on its commands (Cursor, Claude Code, Codex, Copilot, Gemini CLI, Kiro CLI, OpenCode, Hermes, DeepSeek Harness, Cline, Roo Code, or any agent that sets `AI_AGENT`) and named in the User-Agent of API requests to Meshy (`meshy.ai`, `meshy.cn`) as `; agent [/]` inside the parentheses; requests anywhere else, sign-in, input URL checks and asset downloads leave it out. Set a name (`grok-bot`, `claude-code/desktop`: lowercase letters, digits, `.`, `-`) to name it yourself, or `none` to leave it out. `meshy doctor` shows what was detected and from which variable | -| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to an `http://` proxy as plain forwarded requests, as with curl (an `https://` proxy tunnels them too). `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.0/8`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not a usable `http://` or `https://` proxy URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407), or whose TLS handshake with an `https://` proxy fails, was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | +| `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | unset — when `HTTPS_PROXY` or `HTTP_PROXY` is set (lowercase spellings too, lowercase first), every request goes through that proxy: API calls, sign-in, downloads, input URL checks and the update check. `HTTPS_PROXY` covers `https:` URLs (through a CONNECT tunnel) and falls back to `HTTP_PROXY`; `http:` URLs go to an `http://` proxy as plain forwarded requests, as with curl (an `https://` proxy tunnels them too). `NO_PROXY` lists hosts that go direct (comma-separated; `*` for all), and this machine (`localhost`, `127.0.0.0/8`, `::1`) always does, so a local API's credential never crosses the proxy. A value that is not a usable `http://` or `https://` proxy URL stops every request with an error naming the variable (never its value), rather than going direct. A request the proxy refuses (a CONNECT not answered 200, a 407), or whose `https://` proxy fails its certificate check, was never sent. Needed inside sandboxes that allow the network only through a proxy, such as Cursor's | | `MESHY_CLI_NO_UPDATE_NOTIFIER` | unset — any non-empty value disables update checks; CI envs (`CI`, `GITHUB_ACTIONS`, `BUILD_NUMBER`, `RUN_ID`) auto-skip | ## Update notifications