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
10.1 KB
Raw Blame
/**
 * Public-only mode (#4812): an opt-in daemon mode for reading untrusted pages.
 * Every connection Chromium makes goes through the guard (address-guard.ts),
 * which refuses any destination that is not a public internet address.
 *
 * This module holds the parts the CLI, the daemon, the guard and navigation
 * share: the environment switch, the destination check (one resolver for the
 * guard and the navigation pre-check), the recent-refusal ring the daemon
 * turns into a clear command error, and the launch invariant.
 *
 * Threat model and what stays out of scope: BROWSER.md, "Public-only mode".
 */

import * as net from 'node:net';
import * as os from 'node:os';
import { lookup } from 'node:dns/promises';
import { ProxyConfigError } from './proxy-config';
import { ipBytes, nonPublicAddressReason } from './url-validation';

export const PUBLIC_ONLY_DOCS = 'https://github.com/garrytan/gstack/blob/main/BROWSER.md#public-only-mode';
export const PUBLIC_ONLY_CODE = 'PUBLIC_ONLY_REFUSED';
/** WebRTC may not send UDP outside the proxy, so ICE/STUN cannot reach private addresses directly. */
export const WEBRTC_PROXIED_ONLY_ARG = '--force-webrtc-ip-handling-policy=disable_non_proxied_udp';
/** Playwright's escape hatch that drops the <-loopback> rule, which would let loopback go direct. */
export const PLAYWRIGHT_LOOPBACK_ESCAPE = 'PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK';

/** A public-only setting that does not parse: the CLI exits 2, the daemon refuses to start. */
export class PublicOnlyConfigError extends ProxyConfigError {
  constructor(hint: string, message: string) {
    super(hint, message);
    this.name = 'PublicOnlyConfigError';
  }
}

export interface PublicOnlySetting {
  on: boolean;
  /** BROWSE_PUBLIC_ONLY_UPSTREAM=trusted: the user's HTTP(S) proxy enforces public-only on its own. */
  trustedUpstream: boolean;
}

/**
 * Read BROWSE_PUBLIC_ONLY (1, true or on; unset, empty, 0, false or off) and
 * BROWSE_PUBLIC_ONLY_UPSTREAM (unset, empty or trusted). Any other value
 * throws, so a typo never silently leaves the guard off.
 */
export function publicOnlyFromEnv(env: NodeJS.ProcessEnv, flag = false): PublicOnlySetting {
  const value = env.BROWSE_PUBLIC_ONLY ?? '';
  if (!['', '0', 'false', 'off', '1', 'true', 'on'].includes(value)) {
    throw new PublicOnlyConfigError('set BROWSE_PUBLIC_ONLY=1 to turn public-only mode on, or unset it', 'BROWSE_PUBLIC_ONLY must be 1, true or on (or 0, false, off or empty)');
  }
  const upstream = env.BROWSE_PUBLIC_ONLY_UPSTREAM ?? '';
  if (upstream !== '' && upstream !== 'trusted') {
    throw new PublicOnlyConfigError('set BROWSE_PUBLIC_ONLY_UPSTREAM=trusted only if your HTTP(S) proxy blocks private addresses itself, or unset it', 'BROWSE_PUBLIC_ONLY_UPSTREAM must be trusted or empty');
  }
  const on = flag || ['1', 'true', 'on'].includes(value);
  return { on, trustedUpstream: on && upstream === 'trusted' };
}

/** The refusal message every public-only path uses, with its code and fix. */
export function refusalMessage(target: string, reason: string): string {
  return `public-only refused ${target} (${reason}) [${PUBLIC_ONLY_CODE}]. fix: this session loads only public internet addresses; to reach local or private ones, run 'browse disconnect' and start browse without --public-only or BROWSE_PUBLIC_ONLY. see ${PUBLIC_ONLY_DOCS}`;
}

function inPrefix(address: number[], network: number[], bits: number): boolean {
  if (address.length !== network.length) return false;
  for (let i = 0; i < address.length && bits > 0; i++, bits -= 8) {
    const mask = bits >= 8 ? 0xff : (0xff << (8 - bits)) & 0xff;
    if ((address[i] & mask) !== (network[i] & mask)) return false;
  }
  return true;
}

export interface LocalNetwork { bytes: number[]; bits: number; cidr: string }

let interfaceCache: { at: number; nets: LocalNetwork[] } | null = null;

/** This machine's own networks (each interface address with its on-link prefix), cached briefly. */
function localNetworks(): LocalNetwork[] {
  if (interfaceCache && Date.now() - interfaceCache.at < 30_000) return interfaceCache.nets;
  const nets: LocalNetwork[] = [];
  for (const entries of Object.values(os.networkInterfaces())) {
    for (const entry of entries ?? []) {
      const bytes = ipBytes(entry.address);
      const bits = Number(entry.cidr?.split('/')[1]);
      if (bytes && Number.isInteger(bits)) nets.push({ bytes, bits, cidr: entry.cidr! });
    }
  }
  interfaceCache = { at: Date.now(), nets };
  return nets;
}

/** Why an address is refused in public-only mode, or null when it is a public address outside this machine's own networks. */
export function addressRefusalReason(address: string, networks: LocalNetwork[] = localNetworks()): string | null {
  const reason = nonPublicAddressReason(address);
  if (reason) return reason;
  const raw = ipBytes(address);
  if (!raw) return 'not an IP address';
  const mapped = raw.length === 16 && raw.slice(0, 10).every(b => b === 0) && raw[10] === 0xff && raw[11] === 0xff;
  const bytes = mapped ? raw.slice(12) : raw;
  const own = networks.find(n => inPrefix(bytes, n.bytes, n.bits));
  return own ? `address on this machine's own network (${own.cidr})` : null;
}

export type Resolver = (host: string) => Promise<string[]>;

const systemResolver: Resolver = async (host) => (await lookup(host, { all: true, verbatim: true })).map(a => a.address);
const answerCache = new Map<string, { at: number; answer: Promise<string[]> }>();

/** The OS resolver (hosts file included), with a 30 s cache that also shares in-flight lookups. */
export function cachedResolver(resolve: Resolver = systemResolver): Resolver {
  return (host) => {
    const hit = answerCache.get(host);
    if (hit && Date.now() - hit.at < 30_000) return hit.answer;
    if (answerCache.size > 500) answerCache.clear();
    const answer = resolve(host);
    answerCache.set(host, { at: Date.now(), answer });
    answer.catch(() => answerCache.delete(host));
    return answer;
  };
}

export interface CheckOptions {
  resolver?: Resolver;
  /** Refusal reason for one address; defaults to addressRefusalReason. Tests key fixtures by port. */
  reason?: (address: string, port: number) => string | null;
}

/**
 * Check one destination: refuse localhost names without DNS, refuse when the
 * literal or ANY resolved address is refused, refuse when DNS fails. On
 * success, the checked addresses are the only ones a caller may connect to.
 */
export async function checkDestination(host: string, port: number, opts: CheckOptions = {}): Promise<{ addresses: string[] } | { reason: string }> {
  const name = host.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
  if (name === 'localhost' || name.endsWith('.localhost')) return { reason: 'loopback name' };
  const reasonFor = opts.reason ?? ((address: string) => addressRefusalReason(address));
  if (net.isIP(name)) {
    const reason = reasonFor(name, port);
    return reason ? { reason } : { addresses: [name] };
  }
  let addresses: string[];
  try {
    addresses = await (opts.resolver ?? cachedResolver())(name);
  } catch {
    return { reason: 'DNS lookup failed' };
  }
  if (addresses.length === 0) return { reason: 'DNS lookup returned no address' };
  for (const address of addresses) {
    const reason = reasonFor(address, port);
    if (reason) return { reason: `resolves to ${address}, a ${reason}` };
  }
  return { addresses };
}

export interface Refusal { target: string; reason: string; at: number }

const recent: Refusal[] = [];
let refusedTotal = 0;
const loggedTargets = new Map<string, number>();

/** Record a guard refusal: kept for the command error, counted for /health, logged at most once a minute per target. */
export function recordRefusal(target: string, reason: string): void {
  const at = Date.now();
  recent.push({ target, reason, at });
  if (recent.length > 50) recent.shift();
  refusedTotal++;
  if (at - (loggedTargets.get(target) ?? 0) < 60_000) return;
  if (loggedTargets.size > 500) loggedTargets.clear();
  loggedTargets.set(target, at);
  console.warn(`[browse] [public-only] refused ${target} (${reason})`);
}

export function refusalsSince(at: number): Refusal[] {
  return recent.filter(r => r.at >= at);
}

export function refusalCount(): number {
  return refusedTotal;
}

/**
 * A command error that names a host the guard refused while the command ran
 * leads with that refusal, so the agent sees what was refused and the fix
 * instead of a bare ERR_SOCKS_CONNECTION_FAILED. A refusal of some other host
 * (another session's, or a page's tracker) is left out. Refusals exist only in
 * public-only mode.
 */
export function withRefusal(message: string, since: number): string {
  if (message.includes(PUBLIC_ONLY_CODE)) return message;
  const names = (r: Refusal) => {
    const host = r.target.replace(/:\d+$/, '');
    for (let i = message.indexOf(host); i !== -1; i = message.indexOf(host, i + 1)) {
      if (!/[\w.-]/.test(message[i - 1] ?? '') && !/[\w-]/.test(message[i + host.length] ?? '')) return true;
    }
    return false;
  };
  const refusal = refusalsSince(since).find(names);
  return refusal ? `${refusalMessage(refusal.target, refusal.reason)}\n(${message})` : message;
}

/**
 * The launch invariant (#4812): in public-only mode Chromium's only proxy is
 * the guard (or the trusted upstream), with no bypass list from any source,
 * and Playwright's switch that drops <-loopback> is not set. Throws with a
 * fix line otherwise; every launch path calls this before chromium.launch.
 */
export function assertPublicOnlyLaunch(
  proxy: { server: string; bypass?: string } | null,
  expectedServer: string,
  env: NodeJS.ProcessEnv = process.env,
): void {
  const fail = (what: string, fix: string) => {
    throw new Error(`public-only: refusing to launch Chromium because ${what}. fix: ${fix}. see ${PUBLIC_ONLY_DOCS}`);
  };
  if (!proxy || proxy.server !== expectedServer) fail(`its proxy is ${proxy?.server ?? 'none'}, not the public-only guard`, "run 'browse disconnect' and start again");
  if (proxy!.bypass) fail(`its proxy bypass list is set (${proxy!.bypass})`, "unset BROWSE_PROXY_BYPASS");
  if (env[PLAYWRIGHT_LOOPBACK_ESCAPE]) fail(`${PLAYWRIGHT_LOOPBACK_ESCAPE} is set, which would let loopback skip the guard`, `unset ${PLAYWRIGHT_LOOPBACK_ESCAPE}`);
}