diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 4d1e757..ad9b410 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "sourcegraph", "description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.", - "version": "0.8.0", + "version": "0.8.1", "author": { "name": "context4ai" }, diff --git a/cli/README.md b/cli/README.md index 9b7cdf7..cd6095e 100644 --- a/cli/README.md +++ b/cli/README.md @@ -42,7 +42,7 @@ A token acts as its owner: it reads what you can read, manages repositories you `sourcegraph read ` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`. -Some networks reach a site over only IPv4 or only IPv6. When an address does not answer within 250 ms the CLI tries the next one, including the other family (on Node 18 too; the Node option `--no-network-family-autoselection` turns this off). If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own: Node 20+ switches the same way; on Node 18 set `NODE_OPTIONS=--network-family-autoselection`. +Some networks reach a site over only IPv4 or only IPv6. An address is used only once its TLS handshake completes (certificate and host name verified): when one does not connect, or connects but never completes TLS, the CLI tries the next address after a second, alternating IPv4 and IPv6, and remembers the family that worked for that host in its configuration file. With a proxy that Node's fetch is told to use (`NODE_USE_ENV_PROXY=1`), requests go through the proxy instead. If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own and keep the first address that connects: when doctor shows one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`). Run `sourcegraph --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations. diff --git a/cli/package.json b/cli/package.json index c797bb9..34854e8 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@c4a/sourcegraph", - "version": "0.8.0", + "version": "0.8.1", "description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.", "license": "MIT", "type": "module", diff --git a/cli/src/api.ts b/cli/src/api.ts index 834ec73..f525fd5 100644 --- a/cli/src/api.ts +++ b/cli/src/api.ts @@ -1,5 +1,6 @@ import { randomBytes } from 'node:crypto'; import { networkDetail, unsent } from './network.js'; +import { request, Response, TransportOptions } from './transport.js'; // One HTTP API request; errors carry the server's code and message. export class ApiError extends Error { @@ -18,7 +19,7 @@ export interface Request { export interface Alternate { site: string; token?: string; onSwitch?: (site: string, why: string) => void } export class Client { - constructor(public site: string, public token?: string, private alternate?: Alternate) {} + constructor(public site: string, public token?: string, private alternate?: Alternate, private transport: TransportOptions = {}) {} url(path: string, query?: Request['query']): string { const u = new URL(this.site + path); @@ -57,7 +58,7 @@ export class Client { const timer = setTimeout(() => ctl.abort(), 60_000); let res: Response; try { - res = await fetch(this.url(path, req.query), { method: req.method || (req.body !== undefined ? 'POST' : 'GET'), headers, body: req.body === undefined ? undefined : JSON.stringify(req.body), signal: ctl.signal, redirect: 'manual' }); + res = await request(this.url(path, req.query), { method: req.method || (req.body !== undefined ? 'POST' : 'GET'), headers, body: req.body === undefined ? undefined : JSON.stringify(req.body), signal: ctl.signal }, this.transport); } catch (e: any) { throw new ApiError(0, 'NETWORK_ERROR', `Cannot reach ${this.site}: ${ctl.signal.aborted ? 'no response within 60 s' : networkDetail(e)}`, null, !ctl.signal.aborted && unsent(e)); } finally { clearTimeout(timer); } diff --git a/cli/src/config.ts b/cli/src/config.ts index b741b3a..ec583d2 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -19,7 +19,22 @@ const ALIASES: Record = DEPLOYMENT.site_aliases || {}; export const DEFAULT_SITE = SITES[DEPLOYMENT.default_site] || trim(DEPLOYMENT.sites[0].url); const SITE_IDS = DEPLOYMENT.sites.map(s => s.id); -export interface Config { site?: string; tokens?: Record } +export interface Config { site?: string; tokens?: Record; routes?: Record } + +// The address family (4 or 6) whose TLS handshake last completed for a host, +// so later commands try it first. Kept for a week; refreshed at most daily. +const ROUTE_TTL = 7 * 24 * 3600_000, ROUTE_REFRESH = 24 * 3600_000; +export const preferredFamily = { + get(host: string): number | undefined { + const r = loadConfig().routes?.[host]; + return r && Date.now() - Date.parse(r.at) < ROUTE_TTL ? r.family : undefined; + }, + set(host: string, family: number): void { + const c = loadConfig(), r = c.routes?.[host]; + if (r && r.family === family && Date.now() - Date.parse(r.at) < ROUTE_REFRESH) return; + try { saveConfig({ ...c, routes: { ...(c.routes || {}), [host]: { family, at: new Date().toISOString() } } }); } catch { /* read-only home: just do not remember */ } + }, +}; export function configPath(): string { const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config'); diff --git a/cli/src/main.ts b/cli/src/main.ts index f500b6c..d997f72 100644 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -5,7 +5,7 @@ import { hostname } from 'node:os'; import { spawn } from 'node:child_process'; import { createInterface } from 'node:readline/promises'; import { Client, ApiError, idempotencyKey } from './api.js'; -import { SITES, DEFAULT_SITE, DEPLOYMENT, loadConfig, saveConfig, resolveSite, resolveToken, normalizeSite, siteName, configPath, alternateSite } from './config.js'; +import { SITES, DEFAULT_SITE, DEPLOYMENT, loadConfig, saveConfig, resolveSite, resolveToken, normalizeSite, siteName, configPath, alternateSite, preferredFamily } from './config.js'; import { settingsUpdate, parseAssignments, SETTING_KEYS } from './settings.js'; import { VERSION } from './version.js'; import { enableFamilyFallback, diagnose, diagnosisText, advise } from './network.js'; @@ -513,7 +513,7 @@ const C: Record = { } }, doctor: { usage: 'doctor', summary: 'Check the connection to the site: DNS, IPv4/IPv6 addresses, HTTPS and sign-in', run: async ctx => { const others = Object.keys(SITES).filter(id => id !== siteName(ctx.site)); - const d = await diagnose(ctx.site, ctx.client.token ? () => ctx.client.call('/auth/me') : undefined, others); + const d = await diagnose(ctx.site, ctx.client.token ? () => ctx.client.call('/auth/me') : undefined, others, { preferred: preferredFamily }); const alt = alternateSite(ctx.site); if (alt && !d.https.ok) { const a = (await diagnose(alt)).https; @@ -556,7 +556,7 @@ export async function main(argv: string[]): Promise { const ctx: Ctx = { site, client: new Client(site, resolveToken(site), alt ? { site: alt, token: resolveToken(alt), onSwitch: (to, why) => { ctx.site = to; console.error(`note: ${site} cannot be reached from here (${why}); used ${to}, the same service with the same data. To use it by default: sourcegraph config set site ${siteName(to)}`); - } } : undefined), json: jsonOutput, yes: !!o.yes }; + } } : undefined, { preferred: preferredFamily }), json: jsonOutput, yes: !!o.yes }; print(await cmd.run(ctx, parsed.positionals.slice(1), o)); return 0; } catch (e: any) { diff --git a/cli/src/network.test.ts b/cli/src/network.test.ts index fcbb54e..9df7df3 100644 --- a/cli/src/network.test.ts +++ b/cli/src/network.test.ts @@ -113,3 +113,15 @@ test('a request the server may have received is never sent to the other entry', assert.equal(other, 0); } finally { drop.close(); live.close(); } }); + +test('advise names a family that connects but does not complete TLS', () => { + const d = base([ + { address: '10.0.0.1', family: 4, ok: true, ms: 5, tls: { ok: false, error: 'TLS_HANDSHAKE_TIMEOUT' } }, + { address: 'fd00::1', family: 6, ok: true, ms: 5, tls: { ok: true, ms: 20 } }, + ]); + const out = advise(d); + assert.match(out[0], /IPv4 addresses accept connections here but do not complete TLS; IPv6 does/); + assert.match(out[1], /--dns-result-order=ipv6first/); + const none = base([{ address: '10.0.0.1', family: 4, ok: true, ms: 5, tls: { ok: false, error: 'TLS_HANDSHAKE_TIMEOUT' } }], { ok: false, ms: 1, error: 'x' }); + assert.match(advise(none, ['cn'])[0], /no address completes TLS.*sourcegraph doctor --site cn/); +}); diff --git a/cli/src/network.ts b/cli/src/network.ts index 01004f3..c739d81 100644 --- a/cli/src/network.ts +++ b/cli/src/network.ts @@ -1,6 +1,8 @@ // Reaching a site over IPv4 or IPv6, and explaining why it cannot be reached. import net from 'node:net'; +import tls from 'node:tls'; import { lookup } from 'node:dns/promises'; +import { request, TransportOptions } from './transport.js'; // Some networks reach a site over only one address family: private IPv4 // addresses of another region are often not routed while IPv6 is. Node 20+ @@ -32,12 +34,12 @@ export function networkDetail(e: any): string { // the same request to another entry of the service. export function unsent(e: any): boolean { const c = e?.cause ?? e; - if (c?.code === 'UND_ERR_CONNECT_TIMEOUT') return true; + if (c?.unsent === true || c?.code === 'UND_ERR_CONNECT_TIMEOUT') return true; if (c instanceof AggregateError && Array.isArray(c.errors) && c.errors.every((x: any) => x?.syscall === 'connect' || x?.address)) return true; return ['connect', 'getaddrinfo'].includes(c?.syscall) && ['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(c?.code); } -export interface Probe { address: string; family: 4 | 6; ok: boolean; ms?: number; error?: string } +export interface Probe { address: string; family: 4 | 6; ok: boolean; ms?: number; error?: string; tls?: { ok: boolean; ms?: number; error?: string } } export interface Diagnosis { site: string; node: string; family_fallback: boolean; dns_error?: string; addresses: Probe[]; @@ -47,6 +49,23 @@ export interface Diagnosis { advice: string[]; } +// usable: the address completes what a request needs (TLS for https sites). +const usable = (a: Probe) => (a.tls ? a.tls.ok : a.ok); + +// probeTLS completes a TLS handshake with one address for host name servername. +function probeTLS(address: string, port: number, servername: string, timeout: number, ca?: string | Buffer): Promise> { + const started = Date.now(); + return new Promise(resolve => { + const s = tls.connect({ host: address, port, servername, ca: ca ? [...tls.rootCertificates, String(ca)] : undefined, ALPNProtocols: ['http/1.1'] }); + let tcp = false; + const done = (r: NonNullable) => { s.destroy(); resolve(r); }; + s.once('connect', () => { tcp = true; }); + s.setTimeout(timeout, () => done({ ok: false, error: tcp ? 'TLS_HANDSHAKE_TIMEOUT' : 'ETIMEDOUT' })); + s.once('secureConnect', () => done({ ok: true, ms: Date.now() - started })); + s.once('error', (e: any) => done({ ok: false, error: e.code || e.message })); + }); +} + // probe opens one TCP connection to one address, without falling back. function probe(address: string, family: 4 | 6, port: number, timeout: number): Promise { const started = Date.now(); @@ -61,16 +80,21 @@ function probe(address: string, family: 4 | 6, port: number, timeout: number): P // diagnose checks a site the way a request reaches it: name resolution, a TCP // connection to each address, an HTTPS request and, with a token, the sign-in. -export async function diagnose(site: string, whoami?: () => Promise, otherSites: string[] = []): Promise { +export async function diagnose(site: string, whoami?: () => Promise, otherSites: string[] = [], transport: TransportOptions = {}): Promise { const u = new URL(site), port = Number(u.port || (u.protocol === 'http:' ? 80 : 443)); const d: Diagnosis = { site, node: process.version, family_fallback: familyFallback(), addresses: [], https: { ok: false, ms: 0 }, advice: [] }; let found: { address: string; family: number }[] = []; try { found = await lookup(u.hostname.replace(/^\[|\]$/g, ''), { all: true, verbatim: true }); } catch (e: any) { d.dns_error = e.code || e.message; } - d.addresses = await Promise.all(found.map(a => probe(a.address, a.family === 6 ? 6 : 4, port, 3000))); + const host = u.hostname.replace(/^\[|\]$/g, ''); + d.addresses = await Promise.all(found.map(async a => { + const p = await probe(a.address, a.family === 6 ? 6 : 4, port, 3000); + if (p.ok && u.protocol === 'https:') p.tls = await probeTLS(a.address, port, host, 5000, transport.ca); + return p; + })); const started = Date.now(); try { - const r = await fetch(site + '/readyz', { signal: AbortSignal.timeout(15_000), redirect: 'manual', headers: { 'User-Agent': 'sourcegraph-cli' } }); - await r.arrayBuffer(); + const r = await request(site + '/readyz', { signal: AbortSignal.timeout(15_000), headers: { 'User-Agent': 'sourcegraph-cli' } }, transport); + await r.text(); d.https = { ok: r.ok, status: r.status, ms: Date.now() - started }; } catch (e) { d.https = { ok: false, ms: Date.now() - started, error: networkDetail(e) }; } if (whoami && !d.https.status) d.sign_in = { ok: false, skipped: true }; @@ -86,18 +110,25 @@ export async function diagnose(site: string, whoami?: () => Promise, otherS export function advise(d: Diagnosis, otherSites: string[] = []): string[] { const out: string[] = []; const by = (f: 4 | 6) => d.addresses.filter(a => a.family === f); - const up = (f: 4 | 6) => by(f).some(a => a.ok), down = (f: 4 | 6) => by(f).length > 0 && !up(f); + const up = (f: 4 | 6) => by(f).some(usable), down = (f: 4 | 6) => by(f).length > 0 && !up(f); + const tlsOnly = (f: 4 | 6) => by(f).some(a => a.ok && a.tls && !a.tls.ok); const others = otherSites.length ? ` Or try another site: ${otherSites.map(s => `sourcegraph doctor --site ${s}`).join(', ')}.` : ''; if (d.dns_error) out.push(`The site name does not resolve on this network (${d.dns_error}). Check DNS, VPN or the office network.${others}`); else if (!d.addresses.some(a => a.ok)) out.push(`No address of the site accepts connections from here. Check VPN, the office network or a firewall.${others}`); + else if (!d.addresses.some(usable)) out.push(`Connections open but no address completes TLS: a proxy, firewall or TLS inspection is in the way.${others}`); else for (const [bad, good] of [[4, 6], [6, 4]] as const) { if (!down(bad) || !up(good)) continue; + if (tlsOnly(bad)) { + out.push(`IPv${bad} addresses accept connections here but do not complete TLS; IPv${good} does. The CLI uses IPv${good} automatically and remembers it.`); + out.push(`MCP clients and other programs keep the first address that connects: start them with NODE_OPTIONS=--dns-result-order=ipv${good}first (Node), or point them at another site that answers.`); + continue; + } out.push(d.family_fallback ? `IPv${bad} addresses do not answer here; IPv${good} does. The CLI switches to IPv${good} automatically.` : `IPv${bad} addresses do not answer here; IPv${good} does. Remove --no-network-family-autoselection so the CLI can switch to IPv${good}.`); out.push(`MCP clients and other programs connect on their own: on Node 20+ they switch the same way; on Node 18 set NODE_OPTIONS=--network-family-autoselection.`); } - if (d.addresses.some(a => a.ok) && !d.https.ok) out.push(d.https.status + if (d.addresses.some(usable) && !d.https.ok) out.push(d.https.status ? `The site answered HTTP ${d.https.status}: it is reachable but not ready; try again later or use another site.` : `Connections open but the HTTPS request failed (${d.https.error}): a proxy or TLS inspection may be in the way.`); if (d.alternate?.ok) out.unshift(`${d.alternate.site} answers from here: it is another entry of the same service, with the same data and tokens. Other commands switch to it automatically; to use it by default: sourcegraph config set site ${d.alternate.site}`); @@ -111,7 +142,10 @@ export function diagnosisText(d: Diagnosis): string { if (d.dns_error) lines.push(`dns failed: ${d.dns_error}`); else { lines.push(`dns ${d.addresses.length} address${d.addresses.length === 1 ? '' : 'es'}`); - for (const a of d.addresses) lines.push(` IPv${a.family} ${a.address.padEnd(40)} ${a.ok ? `connects in ${a.ms} ms` : `fails: ${a.error}`}`); + for (const a of d.addresses) { + const tlsText = !a.tls ? '' : a.tls.ok ? `, TLS in ${a.tls.ms} ms` : `, TLS fails: ${a.tls.error}`; + lines.push(` IPv${a.family} ${a.address.padEnd(40)} ${a.ok ? `connects in ${a.ms} ms${tlsText}` : `fails: ${a.error}`}`); + } } lines.push(`https ${d.https.status ? `/readyz answered ${d.https.status}` : `failed: ${d.https.error}`} in ${d.https.ms} ms`); if (d.alternate) lines.push(`same service ${d.alternate.site}: ${d.alternate.ok ? 'answers' : d.alternate.status ? `answered ${d.alternate.status}` : 'failed: ' + d.alternate.error}`); diff --git a/cli/src/transport.test.ts b/cli/src/transport.test.ts new file mode 100644 index 0000000..cac57b6 --- /dev/null +++ b/cli/src/transport.test.ts @@ -0,0 +1,115 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer as createTCP } from 'node:net'; +import { createServer as createTLS } from 'node:https'; +import { spawn, spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { order, useFetch } from './transport.js'; + +// A self-signed certificate for sg.test. +function certificate() { + const dir = mkdtempSync(join(tmpdir(), 'sg-tls-')); + const r = spawnSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=sg.test', '-addext', 'subjectAltName=DNS:sg.test', '-keyout', join(dir, 'key.pem'), '-out', join(dir, 'cert.pem')]); + assert.equal(r.status, 0, String(r.stderr)); + return { key: readFileSync(join(dir, 'key.pem'), 'utf8'), cert: readFileSync(join(dir, 'cert.pem'), 'utf8') }; +} + +// The same port on two addresses: 127.0.0.1 accepts TCP and never speaks TLS +// (the reported network), ::1 is a working HTTPS site. +async function sites(tls: { key: string; cert: string }) { + const seen: string[] = []; + const silent = createTCP(() => { /* accept, say nothing */ }); + await new Promise(r => silent.listen(0, '127.0.0.1', r)); + const port = (silent.address() as any).port; + const good = createTLS(tls, (req, res) => { seen.push(`${req.method} ${req.url} ${req.headers.authorization || ''}`); res.setHeader('Content-Type', 'application/json'); res.end('{"ok":true}'); }); + await new Promise(r => good.listen({ host: '::1', port, ipv6Only: true }, r)); + return { port, seen, close: () => { silent.close(); good.close(); } }; +} + +// Runs a scenario with the bundled client under node; it prints JSON. +async function underNode(scenario: string, env: Record): Promise { + const dir = mkdtempSync(join(tmpdir(), 'sg-tr-')); + for (const f of ['api.ts', 'transport.ts']) { + const built = spawnSync(process.execPath, ['build', fileURLToPath(new URL(f, import.meta.url)), '--target', 'node', '--outdir', dir]); + assert.equal(built.status, 0, String(built.stderr)); + } + const file = join(dir, 'run.mjs'); + writeFileSync(file, `import { Client } from ${JSON.stringify(join(dir, 'api.js'))};\nimport { connectTLS } from ${JSON.stringify(join(dir, 'transport.js'))};\nconst out = {};\ntry { ${scenario} } catch (e) { out.error = { code: e.code, unsent: e.unsent, message: e.message }; }\nconsole.log(JSON.stringify(out));`); + return new Promise((resolve, reject) => { + const p = spawn('node', [file], { env: { ...process.env, ...env } }); + let out = ''; + p.stdout.on('data', d => { out += d; }); + p.stderr.on('data', d => { out += d; }); + p.on('close', () => { try { resolve(JSON.parse(out.trim().split('\n').pop()!)); } catch { reject(new Error(out)); } }); + }); +} + +const transportFor = `const remembered = {}; +const transport = (host = 'sg.test') => ({ + lookup: async () => [{ address: '127.0.0.1', family: 4 }, { address: '::1', family: 6 }], + ca: process.env.CA, staggerMs: 200, attemptMs: 2000, + preferred: { get: h => remembered[h], set: (h, f) => { remembered[h] = f; } }, +});`; + +test('a site whose IPv4 address connects but never completes TLS is reached over IPv6, which is remembered', async () => { + const tls = certificate(); + const s = await sites(tls); + try { + const r = await underNode(`${transportFor} + const c = new Client('https://sg.test:' + process.env.PORT, 'sgk_t', undefined, transport()); + let t = Date.now(); + out.first = await c.call('/v1/x', { body: { a: 1 } }); out.firstMs = Date.now() - t; + out.remembered = remembered['sg.test']; + t = Date.now(); + out.second = await c.call('/v1/y'); out.secondMs = Date.now() - t;`, { PORT: String(s.port), CA: tls.cert }); + assert.deepEqual(r.first, { ok: true }, JSON.stringify(r)); + assert.ok(r.firstMs < 1500, `first call took ${r.firstMs} ms`); + assert.equal(r.remembered, 6); + assert.ok(r.secondMs < 150, `remembered family still waited ${r.secondMs} ms`); + assert.deepEqual(s.seen, ['POST /v1/x Bearer sgk_t', 'GET /v1/y Bearer sgk_t']); + } finally { s.close(); } +}); + +test('the certificate is still verified for the site name', async () => { + const tls = certificate(); + const s = await sites(tls); + try { + const r = await underNode(`${transportFor} + await connectTLS('other.test', Number(process.env.PORT), transport('other.test'));`, { PORT: String(s.port), CA: tls.cert }); + assert.equal(r.error.code, 'ECONNECT_FAILED'); + assert.match(r.error.message, /::1 ERR_TLS_CERT_ALTNAME_INVALID/); + assert.match(r.error.message, /127\.0\.0\.1 TLS_HANDSHAKE_TIMEOUT/); + } finally { s.close(); } +}); + +test('when no address completes TLS the request is reported unsent and goes to the other entry', async () => { + const tls = certificate(); + const s = await sites(tls); + try { + const r = await underNode(`${transportFor} + const t = { ...transport(), lookup: async () => [{ address: '127.0.0.1', family: 4 }] }; + const c = new Client('https://sg.test:' + process.env.PORT, undefined, { site: 'https://sg.test:' + process.env.PORT, onSwitch: () => { out.switched = true; } }, t); + try { await c.call('/v1/x'); } catch (e) { out.err = { code: e.code, unsent: e.unsent, message: e.message }; }`, { PORT: String(s.port), CA: tls.cert }); + assert.equal(r.err.code, 'NETWORK_ERROR'); + assert.equal(r.err.unsent, true); + assert.match(r.err.message, /127\.0\.0\.1 TLS_HANDSHAKE_TIMEOUT/); + assert.match(r.err.message, /cannot be reached either/); + } finally { s.close(); } +}); + +test('addresses alternate between families, starting with the remembered one', () => { + const a = [{ address: 'a4', family: 4 }, { address: 'b4', family: 4 }, { address: 'a6', family: 6 }]; + assert.deepEqual(order(a).map(x => x.address), ['a4', 'a6', 'b4']); + assert.deepEqual(order(a, 6).map(x => x.address), ['a6', 'a4', 'b4']); + assert.deepEqual(order(a, 6).length, 3); +}); + +test('fetch is kept only when it is told to use the environment proxy', () => { + assert.equal(useFetch({}, []), false); + assert.equal(useFetch({ HTTPS_PROXY: 'http://p:8080' }, []), false); + assert.equal(useFetch({ HTTPS_PROXY: 'http://p:8080', NODE_USE_ENV_PROXY: '1' }, []), true); + assert.equal(useFetch({ http_proxy: 'http://p:8080' }, ['--use-env-proxy']), true); +}); diff --git a/cli/src/transport.ts b/cli/src/transport.ts new file mode 100644 index 0000000..9a18740 --- /dev/null +++ b/cli/src/transport.ts @@ -0,0 +1,154 @@ +// HTTPS requests that fall back across a site's addresses until TLS completes. +// +// Some networks connect to an address but never finish the TLS handshake on it +// (seen for a site's private IPv4 addresses from another region, while its +// IPv6 addresses work). Node's fetch picks the first address whose TCP +// connection opens and then waits for TLS until it times out, so falling back +// between IPv4 and IPv6 (autoSelectFamily) does not help. Here an address only +// wins once its TLS handshake completes, with certificate and host name +// verified as usual; a slow address gets company from the next one after a +// short delay, and the first to finish is used. The address family that worked +// is remembered per host so later commands start with it. +import http from 'node:http'; +import https from 'node:https'; +import net from 'node:net'; +import tls from 'node:tls'; +import { lookup as dnsLookup } from 'node:dns/promises'; + +export interface Address { address: string; family: number } +export interface TransportOptions { + lookup?: (host: string) => Promise; + /** Extra trusted CA (tests). */ + ca?: string | Buffer; + /** Delay before trying the next address while one is still connecting. */ + staggerMs?: number; + /** Time each address may take for TCP plus TLS. */ + attemptMs?: number; + /** Remembered family for a host (read) and the family that worked (write). */ + preferred?: { get(host: string): number | undefined; set(host: string, family: number): void }; +} + +export interface Attempt { address: string; family: number; code: string } + +// ConnectError: no address completed TLS. The request was not sent. +export class ConnectError extends Error { + code = 'ECONNECT_FAILED'; + unsent = true; + constructor(public host: string, public errors: Attempt[]) { + super(errors.length ? `no address completed TLS (${errors.map(e => `${e.address} ${e.code}`).join(', ')})` : `${host} has no address`); + } +} + +const defaultLookup = async (host: string): Promise => dnsLookup(host, { all: true, verbatim: true }); + +// order interleaves the families, starting with the preferred one (else the +// resolver's first answer), as RFC 8305 does. +export function order(addresses: Address[], preferred?: number): Address[] { + const first = preferred && addresses.some(a => a.family === preferred) ? preferred : addresses[0]?.family; + const a = addresses.filter(x => x.family === first), b = addresses.filter(x => x.family !== first); + const out: Address[] = []; + for (let i = 0; i < Math.max(a.length, b.length); i++) { + if (a[i]) out.push(a[i]); + if (b[i]) out.push(b[i]); + } + return out; +} + +// connectTLS returns a socket whose TLS handshake with host completed. +export async function connectTLS(host: string, port: number, opts: TransportOptions = {}, signal?: AbortSignal): Promise { + let addrs: Address[]; + if (net.isIP(host)) addrs = [{ address: host, family: net.isIP(host) }]; + else { + try { addrs = await (opts.lookup || defaultLookup)(host); } catch (e: any) { throw Object.assign(e, { unsent: true }); } + } + const list = order(addrs, opts.preferred?.get(host)); + if (!list.length) throw new ConnectError(host, []); + const stagger = opts.staggerMs ?? 1000, attemptMs = opts.attemptMs ?? 10_000; + return new Promise((resolve, reject) => { + const errors: Attempt[] = [], live = new Set(); + let next = 0, done = false, timer: NodeJS.Timeout | undefined; + const finish = (err?: Error, sock?: tls.TLSSocket) => { + if (done) return; + done = true; + clearTimeout(timer); + signal?.removeEventListener('abort', onAbort); + for (const s of live) if (s !== sock) s.destroy(); + if (sock) resolve(sock); else reject(err); + }; + const onAbort = () => finish(Object.assign(new Error('aborted'), { name: 'AbortError' })); + signal?.addEventListener('abort', onAbort); + const start = () => { + clearTimeout(timer); + if (done || next >= list.length) return; + const a = list[next++]; + const s = tls.connect({ host: a.address, port, servername: host, ca: opts.ca ? [...tls.rootCertificates, String(opts.ca)] : undefined, ALPNProtocols: ['http/1.1'] }); + live.add(s); + let tcp = false; + s.once('connect', () => { tcp = true; }); + const fail = (code: string) => { + if (!live.delete(s)) return; + s.destroy(); + errors.push({ address: a.address, family: a.family, code }); + if (next < list.length) start(); + else if (!live.size) finish(new ConnectError(host, errors)); + }; + s.setTimeout(attemptMs, () => fail(tcp ? 'TLS_HANDSHAKE_TIMEOUT' : 'ETIMEDOUT')); + s.once('error', (e: any) => fail(e.code || e.message)); + s.once('secureConnect', () => { + s.setTimeout(0); + live.delete(s); + opts.preferred?.set(host, a.family); + finish(undefined, s); + }); + if (next < list.length) timer = setTimeout(start, stagger); + }; + start(); + }); +} + +export interface Response { status: number; ok: boolean; headers: http.IncomingHttpHeaders; text(): Promise } +export interface RequestInit { method?: string; headers?: Record; body?: string; signal?: AbortSignal } + +// useFetch: when Node's fetch is told to use the environment's proxy +// (NODE_USE_ENV_PROXY=1 or --use-env-proxy), keep fetch so the proxy is used; +// otherwise fetch connects directly too, and this transport does it better. +export function useFetch(env: NodeJS.ProcessEnv = process.env, argv: string[] = process.execArgv): boolean { + const proxy = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'].some(k => env[k]); + const honoured = env.NODE_USE_ENV_PROXY === '1' || [...argv, ...(env.NODE_OPTIONS || '').split(/\s+/)].includes('--use-env-proxy'); + return proxy && honoured; +} + +// request sends one HTTP request; https URLs connect with connectTLS. +export async function request(url: string, init: RequestInit = {}, opts: TransportOptions = {}): Promise { + const u = new URL(url); + if (u.protocol === 'https:' && useFetch()) return fetchResponse(url, init); + const secure = u.protocol === 'https:'; + const host = u.hostname.replace(/^\[|\]$/g, ''); + const port = Number(u.port || (secure ? 443 : 80)); + const socket = secure ? await connectTLS(host, port, opts, init.signal) : undefined; + return new Promise((resolve, reject) => { + const headers: Record = { ...(init.headers || {}) }; + if (init.body !== undefined) headers['Content-Length'] = String(Buffer.byteLength(init.body)); + // Without an agent and with createConnection, Node uses the connected socket. + const options: https.RequestOptions = { method: init.method || 'GET', host, port, path: u.pathname + u.search, headers, signal: init.signal }; + if (socket) options.createConnection = () => socket; + else options.agent = false; + const req = (secure ? https : http).request(options, res => { + const chunks: Buffer[] = []; + res.on('data', (c: Buffer) => chunks.push(c)); + const status = res.statusCode || 0; + const body = new Promise((ok, bad) => { res.on('end', () => ok(Buffer.concat(chunks).toString('utf8'))); res.on('error', bad); }); + body.catch(() => {}); + resolve({ status, ok: status >= 200 && status < 300, headers: res.headers, text: () => body }); + }); + req.on('error', reject); + req.end(init.body); + }); +} + +async function fetchResponse(url: string, init: RequestInit): Promise { + const r = await fetch(url, { method: init.method, headers: init.headers, body: init.body, signal: init.signal, redirect: 'manual' }); + const headers: http.IncomingHttpHeaders = {}; + r.headers.forEach((v, k) => { headers[k] = v; }); + return { status: r.status, ok: r.ok, headers, text: () => r.text() }; +} diff --git a/cli/src/version.ts b/cli/src/version.ts index ca24a8e..223bb57 100644 --- a/cli/src/version.ts +++ b/cli/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.8.0'; +export const VERSION = '0.8.1'; diff --git a/scripts/deployment/cli-readme.md b/scripts/deployment/cli-readme.md index 4a35939..6b1d724 100644 --- a/scripts/deployment/cli-readme.md +++ b/scripts/deployment/cli-readme.md @@ -42,7 +42,7 @@ A token acts as its owner: it reads what you can read, manages repositories you `sourcegraph read ` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`. -Some networks reach a site over only IPv4 or only IPv6. When an address does not answer within 250 ms the CLI tries the next one, including the other family (on Node 18 too; the Node option `--no-network-family-autoselection` turns this off). If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own: Node 20+ switches the same way; on Node 18 set `NODE_OPTIONS=--network-family-autoselection`. +Some networks reach a site over only IPv4 or only IPv6. An address is used only once its TLS handshake completes (certificate and host name verified): when one does not connect, or connects but never completes TLS, the CLI tries the next address after a second, alternating IPv4 and IPv6, and remembers the family that worked for that host in its configuration file. With a proxy that Node's fetch is told to use (`NODE_USE_ENV_PROXY=1`), requests go through the proxy instead. If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own and keep the first address that connects: when doctor shows one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`). Run `sourcegraph --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations. diff --git a/scripts/deployment/skill.md b/scripts/deployment/skill.md index 1ca4c17..9f9a7d7 100644 --- a/scripts/deployment/skill.md +++ b/scripts/deployment/skill.md @@ -81,4 +81,4 @@ All changes go through the site API with the caller's permissions, exactly as on - `REVISION_NOT_SEARCHABLE` (search): the commit has no index and its files are not on the service. Search one of the commits the message lists, or the branch; do not retry the same commit. `SEARCH_BUSY` (search): scans are busy on that instance; retry once after Retry-After. - `INDEX_NOT_READY`, `SCOPE_NOT_READY`, `CONTENT_NOT_READY` (reads and other tools): the version is not prepared; prepare it if authorized, otherwise report it. To read, list or compare only, prepare its contents without an index (MCP `prepare` with `content_only: true`, or `sourcegraph jobs retry --kind content --commit SHA`), which is faster; search then scans its files. For indexed search use MCP `prepare` or `--kind index`. A reader who does not manage the repository may prepare contents only, of a full 40-character SHA (never a branch), when the site allows it (capabilities list `prepare-content-reader`): an already readable commit answers `stage: ready` with no job; `RATE_LIMITED` (`detail.scope` user or repository), `READER_PREPARE_FULL` and `REPOSITORY_STORAGE_BUSY` carry a retry time — wait for it once or report, do not loop. Without a token, MCP `prepare` answers `LOGIN_REQUIRED`: tell the user to sign in on the website, create a personal token and send it as `Authorization: Bearer `. - `SITE_FROZEN`: the site is read-only for maintenance; retry later. -- `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically; an MCP client on Node 18 needs `NODE_OPTIONS=--network-family-autoselection` (Node 20+ switches by itself). Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output. +- `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection and a TLS handshake to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically, including when an address connects but never completes TLS, and remembers the family that worked. MCP clients keep the first address that connects: when doctor reports one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`); on Node 18 add `--network-family-autoselection`. Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output. diff --git a/skills/sourcegraph/SKILL.md b/skills/sourcegraph/SKILL.md index b2a3c3e..fef97e3 100644 --- a/skills/sourcegraph/SKILL.md +++ b/skills/sourcegraph/SKILL.md @@ -81,4 +81,4 @@ All changes go through the site API with the caller's permissions, exactly as on - `REVISION_NOT_SEARCHABLE` (search): the commit has no index and its files are not on the service. Search one of the commits the message lists, or the branch; do not retry the same commit. `SEARCH_BUSY` (search): scans are busy on that instance; retry once after Retry-After. - `INDEX_NOT_READY`, `SCOPE_NOT_READY`, `CONTENT_NOT_READY` (reads and other tools): the version is not prepared; prepare it if authorized, otherwise report it. To read, list or compare only, prepare its contents without an index (MCP `prepare` with `content_only: true`, or `sourcegraph jobs retry --kind content --commit SHA`), which is faster; search then scans its files. For indexed search use MCP `prepare` or `--kind index`. A reader who does not manage the repository may prepare contents only, of a full 40-character SHA (never a branch), when the site allows it (capabilities list `prepare-content-reader`): an already readable commit answers `stage: ready` with no job; `RATE_LIMITED` (`detail.scope` user or repository), `READER_PREPARE_FULL` and `REPOSITORY_STORAGE_BUSY` carry a retry time — wait for it once or report, do not loop. Without a token, MCP `prepare` answers `LOGIN_REQUIRED`: tell the user to sign in on the website, create a personal token and send it as `Authorization: Bearer `. - `SITE_FROZEN`: the site is read-only for maintenance; retry later. -- `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically; an MCP client on Node 18 needs `NODE_OPTIONS=--network-family-autoselection` (Node 20+ switches by itself). Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output. +- `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection and a TLS handshake to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically, including when an address connects but never completes TLS, and remembers the family that worked. MCP clients keep the first address that connects: when doctor reports one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`); on Node 18 add `--network-family-autoselection`. Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output.