Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript
4.1 KB
Raw Blame
/**
 * Daemon startup for public-only mode (#4812): read the setting, then give
 * Chromium its only proxy, either the guard (direct, or chained to a SOCKS5
 * upstream) or an HTTP(S) upstream the user marked trusted, with no bypass
 * list; pin it for the launch invariant and install the navigation check.
 * Kept out of server.ts so the default proxy path there stays as it was.
 */

import { startAddressGuard } from './address-guard';
import { parseProxyConfig, toUpstreamConfig, ProxyConfigError } from './proxy-config';
import { redactProxyUrl } from './proxy-redact';
import { checkDestination, publicOnlyFromEnv, refusalMessage, type PublicOnlySetting } from './public-only';
import { testUpstream, type BridgeHandle } from './socks-bridge';
import { setPublicOnlyCheck } from './url-validation';

function exitWith(message: string): never {
  console.error(`[browse] error: ${message}`);
  process.exit(1);
}

/** The daemon's public-only setting; a value that does not parse, or public-only with headed mode, stops the daemon. */
export function readPublicOnlySetting(env: NodeJS.ProcessEnv): PublicOnlySetting {
  let setting: PublicOnlySetting;
  try {
    setting = publicOnlyFromEnv(env);
  } catch (err) {
    if (err instanceof ProxyConfigError) exitWith(`${err.message} (${err.hint})`);
    throw err;
  }
  if (setting.on && env.BROWSE_HEADED === '1') exitWith('public-only mode cannot drive the headed browser yet (run without BROWSE_PUBLIC_ONLY)');
  return setting;
}

export async function startPublicOnlyProxy(
  browserManager: { setProxyConfig(cfg: { server: string; username?: string; password?: string }): void; setPublicOnly(): void },
  setting: PublicOnlySetting,
  proxyUrl: string | undefined,
  proxySource: string,
  env: NodeJS.ProcessEnv = process.env,
): Promise<BridgeHandle | null> {
  let guard: BridgeHandle | null = null;
  let parsed: ReturnType<typeof parseProxyConfig> | null = null;
  if (proxyUrl) {
    try {
      parsed = parseProxyConfig({ proxyUrl, envUser: env.BROWSE_PROXY_USER, envPass: env.BROWSE_PROXY_PASS, source: proxySource });
    } catch (err) {
      if (err instanceof ProxyConfigError) exitWith(`${err.message} (${err.hint})`);
      throw err;
    }
  }
  if (parsed && parsed.scheme !== 'socks5') {
    if (!setting.trustedUpstream) {
      exitWith(`public-only mode cannot guard page traffic through the HTTP(S) proxy from ${proxySource} (use a socks5:// proxy, or set BROWSE_PUBLIC_ONLY_UPSTREAM=trusted if that proxy blocks private addresses itself)`);
    }
    browserManager.setProxyConfig({
      server: `${parsed.scheme}://${parsed.host}:${parsed.port}`,
      ...(parsed.userId ? { username: parsed.userId } : {}),
      ...(parsed.password ? { password: parsed.password } : {}),
    });
    console.log(`[browse] [public-only] on: the trusted HTTP(S) proxy ${redactProxyUrl(proxyUrl!)} from ${proxySource} blocks private addresses for page traffic; browse checks navigations, downloads and redirects`);
  } else {
    if (parsed) {
      try {
        const test = await testUpstream({ upstream: toUpstreamConfig(parsed), budgetMs: 5000, retries: 3, backoffMs: 500 });
        console.log(`[browse] [proxy] upstream test ok in ${test.ms}ms`);
      } catch (err) {
        exitWith(`[proxy] upstream ${redactProxyUrl(proxyUrl!)}: ${err instanceof Error ? err.message : String(err)}`);
      }
    }
    guard = await startAddressGuard(parsed ? { upstream: toUpstreamConfig(parsed) } : {});
    browserManager.setProxyConfig({ server: `socks5://127.0.0.1:${guard.port}` });
    const handle = guard;
    process.on('exit', () => { handle.close().catch(() => { /* shutting down anyway */ }); });
    console.log(`[browse] [public-only] on: every Chromium connection goes through the guard on 127.0.0.1:${guard.port}${parsed ? `, then ${redactProxyUrl(proxyUrl!)}` : ''}; loopback, private and other non-public addresses are refused`);
  }
  browserManager.setPublicOnly();
  setPublicOnlyCheck(async (url) => {
    const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80);
    const checked = await checkDestination(url.hostname, port);
    return 'reason' in checked ? refusalMessage(url.host, checked.reason) : null;
  });
  return guard;
}