Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ While the config is being rewritten — by the server rotating a refresh token,
| `autoUpdate` | Set to `false` to disable the background [self-update](usage.md#auto-update) check |
| `upstreamProxy` | Outbound HTTP proxy for **everything TeamClaude sends to Anthropic** — request forwarding, OAuth login, token refresh, profile and usage. `"http://user:pass@host:3128"`, or just `"host:3128"`. `false` disables it *and* ignores the environment. Unset = use `HTTPS_PROXY`/`ALL_PROXY` if present. A value addressing TeamClaude's own listener is ignored (it would proxy the server through itself). TUI settings screen: **Upstream proxy**. See [Upstream proxy](proxy-modes.md#upstream-proxy) |
| `noProxy` | Comma-separated hosts that bypass `upstreamProxy` (suffix match, `*` = all). Defaults to `NO_PROXY` from the environment |
| `fallbackProxy` | Automatic, sticky egress fallback: an HTTP CONNECT proxy (same syntax as `upstreamProxy`) used **only while the direct route to Anthropic is failing**. A direct attempt that fails *while connecting* (`ETIMEDOUT`, `ENETUNREACH`, `EHOSTUNREACH`, `ECONNREFUSED`, DNS `EAI_AGAIN`) is retried once through it and traffic stays on it until the direct path has answered 6 background probes in a row **and** 15 min have passed. A fallback proxy that itself cannot be reached is skipped for 60 s. Inert when `upstreamProxy`/`HTTPS_PROXY` is in effect. A bad value is logged and ignored (never fatal). State: `egressFallback` in `GET /teamclaude/status`. The same `fallbackProxy` pointing at TeamClaude's own listener is ignored. Not applied to `/v1/code/*` or `/api/oauth/*` passthrough, websocket upgrades, or MITM CONNECT passthrough |
| `fallbackProxyHosts` | Hostnames the fallback may carry. Default `["api.anthropic.com", "platform.claude.com"]`. **Must be a subset of the fallback proxy's own allowlist (e.g. tinyproxy `Filter`/`ConnectPort`):** a CONNECT the proxy refuses is indistinguishable from a dead proxy, so one unlisted host marks the whole proxy down for 60 s and traffic goes direct. If the tunnel to the proxy cannot be set up, the request is retried once direct on the same account |
| `mitm.http1Only` | Offer only HTTP/1.1 on the intercepted MITM connection (default `false`). Needed for **Remote Control from the Claude Code Desktop app**: a WebSocket over HTTP/2 requires RFC 8441 extended CONNECT, which is not relayed, so a client negotiating h2 has its handshake dropped with no error — the session syncs one way and messages from the phone are never delivered ([#164](https://github.com/KarpelesLab/teamclaude/issues/164)). Costs client→proxy multiplexing on a loopback hop; upstream is already pooled HTTP/1.1 |
| `sx.apiKey` | [sx.org](https://sx.org) API key. When set, TeamClaude auto-provisions a residential proxy (egress-IP 429 workaround). Absent/empty = off — see [sx.org proxy mode](proxy-modes.md#sxorg-proxy-mode). New to sx.org? Signing up via <https://sx.org/c/ufVrLW> supports TeamClaude development |
| `sx.mode` | `always` (route all upstream traffic), `429` (direct, fail over to the proxy after a 429), or `off` (keep the key but don't use it). Defaults to `always` when a key is set |
Expand Down
31 changes: 30 additions & 1 deletion src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { openSync, writeSync, closeSync, readFileSync, statSync } from 'node:fs'
import { join, dirname } from 'node:path';
import { homedir } from 'node:os';
import { randomBytes } from 'node:crypto';
import { resolveUpstreamProxy, setUpstreamProxy } from './upstream-proxy.js';
import { resolveUpstreamProxy, setUpstreamProxy, resolveFallbackProxy } from './upstream-proxy.js';
import { configureEgressFallback } from './egress-fallback.js';
import { ensureAccountIds } from './account-id.js';

export function getConfigPath() {
Expand Down Expand Up @@ -183,6 +184,7 @@ export async function loadConfig() {
// ids here, before anything can read one. The next save persists them.
ensureAccountIds(config.accounts);
applyUpstreamProxy(config);
applyFallbackProxy(config);
return config;
} catch (err) {
if (err.code === 'ENOENT') return null;
Expand Down Expand Up @@ -212,6 +214,32 @@ function applyUpstreamProxy(config) {
}
}

// The last bad fallbackProxy value reported, so a typo is logged once rather
// than on every config load (each token persist reloads the file).
let reportedBadFallback = null;

/**
* Publish `fallbackProxy` to the process-wide egress fallback.
*
* Not fatal, unlike applyUpstreamProxy: the fallback is optional, and this runs
* on every config load, including the one after each token persist — a typo in
* it must cost the fallback, not the server. Applying an unchanged value keeps
* a live episode (configureEgressFallback compares), so a reload mid-outage
* does not drop back to DIRECT.
*/
function applyFallbackProxy(config) {
const { proxy, hosts, error } = resolveFallbackProxy(config);
if (error) {
if (reportedBadFallback !== error) {
reportedBadFallback = error;
console.error(`[TeamClaude] Ignoring bad fallbackProxy in ${getConfigPath()}: ${error}`);
}
} else {
reportedBadFallback = null;
}
configureEgressFallback({ proxy, hosts });
}

export async function loadOrCreateConfig() {
let config = await loadConfig();
if (!config) {
Expand All @@ -227,6 +255,7 @@ export async function loadOrCreateConfig() {
// their own TeamClaude gets a CONNECT back into the proxy and a timeout,
// on the one run where there is no config to explain it.
applyUpstreamProxy(config);
applyFallbackProxy(config);
}
return config;
}
Expand Down
313 changes: 313 additions & 0 deletions src/egress-fallback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,313 @@
// Automatic, sticky egress fallback.
//
// The host's direct route to api.anthropic.com sometimes goes dark for a minute
// at a time (connect ETIMEDOUT / ENETUNREACH), while a CONNECT proxy on another
// host reaches Anthropic by an independent path. `upstreamProxy` can send
// everything through such a proxy, but only always. This module is the other
// half: go direct by default, switch to the fallback proxy when a direct
// attempt fails to CONNECT, and come back once the direct path has been
// healthy for a while.
//
// DIRECT --connect-phase failure of a direct attempt--> FALLBACK
// FALLBACK --now >= stickyUntil AND 6 consecutive clean probes--> DIRECT
//
// While in FALLBACK a background probe (an ordinary TCP+TLS connect to
// api.anthropic.com:443, no HTTP request, no credentials) tests the direct
// path every 30 s. The sticky window keeps a flapping route from bouncing
// traffic between paths: a path that failed is not trusted again for 15 min.
//
// The fallback proxy has its own health: a failure to connect TO THE PROXY
// (refused, timed out, or answering the CONNECT with a non-200) takes it out of
// rotation for 60 s, and traffic goes direct meanwhile — a dead fallback must
// not turn a flaky route into no route.
//
// Operator contract: `fallbackProxyHosts` must be a subset of the proxy's own
// allowlist. A CONNECT the proxy refuses (403, or a 502 for a host it will not
// reach) looks exactly like a dead proxy from here, so one unlisted host would
// mark the whole proxy down for PROXY_DOWN_MS. We do not try to tell the cases
// apart: the proxy's refusal says nothing about WHY, and guessing wrong either
// way costs a route.
//
// Routing is decided by proxyForHost() in upstream-proxy.js, which consults
// this module; an explicit `upstreamProxy` (or HTTPS_PROXY) wins over it.
//
// Out of scope, deliberately: relayStream (/v1/code/*, /api/oauth/*
// passthrough), relayUpgrade (websockets) and the MITM CONNECT passthrough keep
// going direct. They already bypass `upstreamProxy`, so a fallback that covered
// them would be a different feature.

import tls from 'node:tls';

export const DEFAULT_FALLBACK_HOSTS = ['api.anthropic.com', 'platform.claude.com'];

export const STICKY_MS = 15 * 60_000;
export const PROBE_INTERVAL_MS = 30_000;
export const PROBE_TIMEOUT_MS = 5_000;
export const CLEAN_PROBES_TO_RETURN = 6;
export const PROXY_DOWN_MS = 60_000;
/** Connect timeout for the tunnel to the FALLBACK proxy (sx's default is 30 s). */
export const FALLBACK_CONNECT_TIMEOUT_MS = 5_000;
const PROBE_HOST = 'api.anthropic.com';

// ── Classification ───────────────────────────────────────────

// Codes that, together with a connect-phase signal, prove no byte reached upstream.
const CONNECT_CODES = new Set([
'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ECONNREFUSED', 'UND_ERR_CONNECT_TIMEOUT', 'EAI_AGAIN',
]);
// undici reports its connect timeout with no syscall; the code itself is the phase.
const PHASE_IN_CODE = new Set(['UND_ERR_CONNECT_TIMEOUT']);
// Syscalls that run before there is a connected socket. A name lookup is
// earlier still, and EAI_AGAIN is its only member of the code set.
const CONNECT_SYSCALLS = new Set(['connect', 'getaddrinfo']);

/**
* The individual failures inside `err`: itself, its `.cause`, and the children
* of an AggregateError at either level (happy-eyeballs reports an
* all-addresses-failed connect that way, with no usable code of its own).
*/
function leaves(err) {
const out = [];
const add = (e) => { if (e && typeof e === 'object') out.push(e); };
add(err);
add(err?.cause);
for (const c of err?.errors || []) add(c);
for (const c of err?.cause?.errors || []) add(c);
return out;
}

/**
* Did this failure happen before any byte reached upstream — i.e. while
* connecting? Retrying such a request cannot double-send a prompt.
*
* Conservative on purpose: a code from the connect set alone is not enough
* (`read ETIMEDOUT` carries the same code as `connect ETIMEDOUT`, and the first
* can follow a fully sent request), so the failing syscall must say "connect"
* as well. Every leaf that carries a code or syscall has to agree: one
* read-phase child among connect children means bytes may have flowed on some
* path, and the answer is no.
*/
export function isConnectPhaseError(err) {
const marked = leaves(err).filter(e => e.code != null || e.syscall != null);
if (!marked.length) return false;
let sawConnect = false;
for (const e of marked) {
if (e.syscall != null) {
// Any leaf that names another phase (read, write, ...), or a code outside
// the set, vetoes: bytes may have flowed on that path.
if (!CONNECT_SYSCALLS.has(e.syscall) || !CONNECT_CODES.has(e.code)) return false;
sawConnect = true;
} else if (PHASE_IN_CODE.has(e.code)) {
sawConnect = true;
}
// A syscall-less leaf with any other code is a wrapper's (an AggregateError
// may carry its last child's) or a bare code with no phase: no evidence
// either way, so it neither proves nor vetoes.
}
return sawConnect;
}

/** A short code string for the log line and `reason` — never a URL or message. */
export function connectErrorCode(err) {
for (const e of leaves(err)) if (CONNECT_CODES.has(e.code)) return e.code;
for (const e of leaves(err)) if (e.code) return String(e.code);
return 'ERROR';
}

// ── Probe ────────────────────────────────────────────────────

/** A direct TCP+TLS connect to api.anthropic.com:443. No HTTP request, no credentials. */
export function directProbe({ host = PROBE_HOST, port = 443, timeoutMs = PROBE_TIMEOUT_MS } = {}) {
return new Promise((resolve) => {
let done = false;
const sock = tls.connect({ host, port, servername: host });
const finish = (ok) => {
if (done) return;
done = true;
clearTimeout(timer);
sock.destroy();
resolve(ok);
};
const timer = setTimeout(() => finish(false), timeoutMs);
timer.unref?.();
sock.once('secureConnect', () => finish(true));
sock.once('error', () => finish(false));
});
}

function describeHostPort(proxy) { return `${proxy.host}:${proxy.port}`; }

function formatDuration(ms) {
const s = Math.max(0, Math.round(ms / 1000));
if (s < 60) return `${s}s`;
const m = Math.round(s / 60);
if (m < 60) return `${m}m`;
const h = Math.floor(m / 60);
return m % 60 ? `${h}h${m % 60}m` : `${h}h`;
}

// ── State machine ────────────────────────────────────────────

export class EgressFallback {
/**
* @param {{ proxy?: any, hosts?: string[], now?: () => number, probe?: () => Promise<boolean>,
* log?: (line: string) => void, setInterval?: Function, clearInterval?: Function }} [opts]
*/
constructor({
proxy = null, hosts = DEFAULT_FALLBACK_HOSTS, now = Date.now, probe = directProbe,
log = (line) => console.log(line),
setInterval: setIntervalFn = setInterval, clearInterval: clearIntervalFn = clearInterval,
} = {}) {
this.proxy = proxy;
this.hosts = hosts.map(h => String(h).toLowerCase());
this._now = now;
this._probe = probe;
this._log = log;
this._setInterval = setIntervalFn;
this._clearInterval = clearIntervalFn;
this.state = 'DIRECT';
this.since = null;
this.reason = null;
this.stickyUntil = null;
this.cleanProbes = 0;
this.proxyDownUntil = null;
this.episodes = 0;
this._timer = null;
this._probing = false;
}

get configured() { return !!this.proxy; }

/** True when `hostname` is one the fallback may carry. */
covers(hostname) {
return this.configured && this.hosts.includes(String(hostname).toLowerCase());
}

/** The fallback proxy to use for `hostname` right now, or null for direct. */
proxyFor(hostname) {
if (this.state !== 'FALLBACK' || !this.covers(hostname)) return null;
if (this.proxyDownUntil != null && this._now() < this.proxyDownUntil) return null;
return this.proxy;
}

isFallbackProxy(proxy) { return !!proxy && proxy === this.proxy; }

/**
* A DIRECT attempt failed. Flips to FALLBACK when the failure was
* connect-phase. Returns true only when this call started a new episode.
*/
noteConnectFailure(err) {
if (!this.configured || !isConnectPhaseError(err)) return false;
if (this.state === 'FALLBACK') return false;
const now = this._now();
this.state = 'FALLBACK';
this.since = now;
this.reason = connectErrorCode(err);
this.stickyUntil = now + STICKY_MS;
this.cleanProbes = 0;
this.episodes += 1;
this._log(`[TeamClaude] Egress fallback ON via ${describeHostPort(this.proxy)} (${this.reason})`);
this._startTimer();
return true;
}

/** The tunnel to the fallback proxy could not be established. */
noteProxyConnectFailure() {
if (!this.configured) return;
const wasUp = this.proxyDownUntil == null || this._now() >= this.proxyDownUntil;
this.proxyDownUntil = this._now() + PROXY_DOWN_MS;
if (wasUp) this._log(`[TeamClaude] Egress fallback proxy ${describeHostPort(this.proxy)} unreachable — going direct for ${PROXY_DOWN_MS / 1000}s`);
}

/** One probe of the direct path; may end the episode. Exposed for tests. */
async tick() {
if (this.state !== 'FALLBACK' || this._probing) return;
this._probing = true;
let ok = false;
try { ok = !!(await this._probe()); } catch { ok = false; } finally { this._probing = false; }
if (this.state !== 'FALLBACK') return;
if (!ok) { this.cleanProbes = 0; return; }
this.cleanProbes += 1;
if (this._now() >= this.stickyUntil && this.cleanProbes >= CLEAN_PROBES_TO_RETURN) {
this._log(`[TeamClaude] Egress fallback OFF after ${formatDuration(this._now() - this.since)}`);
this.state = 'DIRECT';
this._stopTimer();
}
}

_startTimer() {
if (this._timer) return;
this._timer = this._setInterval(() => { this.tick().catch(() => {}); }, PROBE_INTERVAL_MS);
this._timer?.unref?.();
}

_stopTimer() {
if (!this._timer) return;
this._clearInterval(this._timer);
this._timer = null;
}

/** Cancel the probe timer. State is left as it is. */
stop() { this._stopTimer(); }

/** For GET /teamclaude/status. The proxy is rendered masked: never credentials. */
status() {
return {
configured: this.configured,
state: this.state,
since: this.since,
stickyUntil: this.stickyUntil,
cleanProbes: this.cleanProbes,
reason: this.reason,
proxyDownUntil: this.proxyDownUntil,
episodes: this.episodes,
proxy: this.proxy ? describeMasked(this.proxy) : null,
hosts: this.hosts,
};
}
}

function describeMasked(proxy) {
const auth = proxy.username ? `${proxy.username}:***@` : '';
return `http://${auth}${describeHostPort(proxy)}`;
}

// ── Process-wide instance ────────────────────────────────────
//
// Like the upstream proxy setting, one value for the whole process: it
// describes how this HOST reaches Anthropic, and request forwarding, token
// refresh and the status endpoint must all agree on it.

let current = new EgressFallback();

export function getEgressFallback() { return current; }

function sameConfig(fb, proxy, hosts) {
if (!proxy || !fb.proxy) return !proxy && !fb.proxy;
const a = fb.proxy;
return a.host === proxy.host && a.port === proxy.port
&& (a.username ?? null) === (proxy.username ?? null)
&& (a.password ?? null) === (proxy.password ?? null)
&& fb.hosts.length === hosts.length
&& fb.hosts.every((h, i) => h === String(hosts[i]).toLowerCase());
}

/**
* Publish the configured fallback. Called on every config load, so applying an
* unchanged value must leave a live episode alone: it keeps the same instance
* rather than building a fresh DIRECT one.
*/
export function configureEgressFallback(cfg, opts = {}) {
const { proxy = null, hosts = DEFAULT_FALLBACK_HOSTS } = cfg ?? {};
const wanted = proxy ? hosts : DEFAULT_FALLBACK_HOSTS;
if (current && sameConfig(current, proxy, wanted)) return current;
current?.stop();
current = new EgressFallback({ proxy, hosts: wanted, ...opts });
return current;
}

/** Reset to the unconfigured state. Tests only. */
export function resetEgressFallback() {
current?.stop();
current = new EgressFallback();
}
Loading