import { randomBytes } from 'node:crypto' import { readFileSync } from 'node:fs' import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' import { homedir, networkInterfaces, type NetworkInterfaceInfo } from 'node:os' import { join } from 'node:path' import { renderUnicodeCompact } from 'uqr' import { buildOpenCodeBasicAuth, createOpenCodeApi, encryptOpenCodePairingCredentials, isOpenCodePairingNonce, openCodeErrorStatus, verifyOpenCodePairingProof, type OpenCodePairingCredentials, type OpenCodePairingEncryptedCredentials, } from '@opencode-manager/shared/opencode' import { z } from 'zod' import { JsonObjectSchema, parseJsonText, trimUrlTrailingSlashes, type JsonObject, type JsonValue, } from '@opencode-manager/shared/utils' const DEFAULT_OPENCODE_PORT = 4096 const DEFAULT_SERVICE_HOSTNAME = '127.0.0.1' const WILDCARD_HOSTS = new Set(['0.0.0.0', '::', '[::]']) const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']) const REDEEM_PATH = '/redeem' const MAX_BODY_BYTES = 4096 export type PairingCredentials = OpenCodePairingCredentials export type PairingOutcome = 'linked' | 'expired' | 'rejected' export interface PairingServerOptions { code: string credentials: PairingCredentials ttlMs: number maxAttempts: number port?: number hostname?: string } export interface PairingServerHandle { url: string port: number done: Promise close: () => Promise } export type OpenCodeServerProbe = | { status: 'ok'; version: string | null } | { status: 'unauthorized' } | { status: 'unreachable'; message: string } export function generatePairingCode(): string { return randomBytes(32).toString('base64url') } export function resolveLanIPv4( interfaces: NodeJS.Dict = networkInterfaces(), ): string | null { for (const entries of Object.values(interfaces)) { for (const entry of entries ?? []) { if (entry.family === 'IPv4' && !entry.internal) { return entry.address } } } return null } export function resolveDefaultBaseUrl( interfaces: NodeJS.Dict = networkInterfaces(), ): string { const lanAddress = resolveLanIPv4(interfaces) return `http://${lanAddress ?? '127.0.0.1'}:${DEFAULT_OPENCODE_PORT}` } export interface OpenCodeServiceDiscovery { baseUrl: string password: string | null source: 'registration' | 'config' loopbackOnly: boolean } export interface OpenCodeServiceDiscoveryOptions { env?: NodeJS.ProcessEnv home?: string interfaces?: NodeJS.Dict platform?: NodeJS.Platform } function defaultServicePort(platform: NodeJS.Platform): number { return platform === 'win32' ? 45278 : 49374 } export function discoverOpenCodeService( options: OpenCodeServiceDiscoveryOptions = {}, ): OpenCodeServiceDiscovery | null { const env = options.env ?? process.env const home = options.home ?? homedir() const registration = readServiceFile(join(resolveXdgDir(env.XDG_STATE_HOME, home, '.local', 'state'), 'opencode', 'service.json')) const config = readServiceFile(join(resolveXdgDir(env.XDG_CONFIG_HOME, home, '.config'), 'opencode', 'service.json')) const configPassword = readString(config?.password) const registered = resolveServiceUrl(readString(registration?.url), options.interfaces) if (registered) { return { ...registered, password: readString(registration?.password) ?? configPassword ?? null, source: 'registration', } } if (!config) return null const hostname = readString(config.hostname) const port = readPort(config.port) if (hostname === null && port === null && configPassword === null) return null const configured = resolveServiceUrl( `http://${bracketHostname(hostname ?? DEFAULT_SERVICE_HOSTNAME)}:${port ?? defaultServicePort(options.platform ?? process.platform)}`, options.interfaces, ) if (!configured) return null return { ...configured, password: configPassword, source: 'config' } } function bracketHostname(hostname: string): string { return hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname } function resolveXdgDir(override: string | undefined, home: string, ...fallback: string[]): string { const configured = override?.trim() return configured || join(home, ...fallback) } function resolveServiceUrl( rawUrl: string | null, interfaces?: NodeJS.Dict, ): { baseUrl: string; loopbackOnly: boolean } | null { if (rawUrl === null) return null let parsed: URL try { parsed = new URL(rawUrl) } catch { return null } if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null if (WILDCARD_HOSTS.has(parsed.hostname)) { parsed.hostname = resolveLanIPv4(interfaces) ?? '127.0.0.1' } const loopbackOnly = LOOPBACK_HOSTS.has(parsed.hostname) return { baseUrl: trimUrlTrailingSlashes(parsed.href), loopbackOnly } } function readServiceFile(file: string): JsonObject | null { try { const parsed = JsonObjectSchema.safeParse(parseJsonText(readFileSync(file, 'utf8'))) return parsed.success ? parsed.data : null } catch { return null } } function readString(value: JsonValue | undefined): string | null { const text = z.string().min(1).safeParse(value) return text.success ? text.data : null } function readPort(value: JsonValue | undefined): number | null { const port = z.number().int().min(1).max(65535).safeParse(value) return port.success ? port.data : null } export function renderPairingQr(link: string): string { return renderUnicodeCompact(link, { ecc: 'M', border: 2 }) } export async function probeOpenCodeServer( baseUrl: string, credentials: PairingCredentials, timeoutMs = 3000, ): Promise { let responseStatus: number | undefined const api = createOpenCodeApi({ baseUrl: trimUrlTrailingSlashes(baseUrl), headers: { authorization: buildOpenCodeBasicAuth(credentials.password, credentials.username) }, fetch: Object.assign( async (input: RequestInfo | URL, init?: RequestInit) => { const response = await fetch(input, init) responseStatus = response.status return response }, { preconnect: fetch.preconnect }, ), }) try { const info = await api.server.info({ signal: AbortSignal.timeout(timeoutMs) }) return { status: 'ok', version: info.version ?? null } } catch (error) { if (responseStatus === 401 || openCodeErrorStatus(error) === 401) return { status: 'unauthorized' } const status = responseStatus !== undefined && responseStatus >= 400 ? responseStatus : undefined return { status: 'unreachable', message: status === undefined ? messageOf(error) : `HTTP ${status}`, } } } function messageOf(cause: unknown): string { return cause instanceof Error ? cause.message : String(cause) } export async function startPairingServer(options: PairingServerOptions): Promise { const { code, credentials, ttlMs, maxAttempts, port = 0, hostname = '0.0.0.0' } = options let settled = false let failures = 0 let resolveDone: (outcome: PairingOutcome) => void = () => {} const done = new Promise((resolve) => { resolveDone = resolve }) let closePromise: Promise | undefined const closeServer = (): Promise => { closePromise ??= new Promise((resolve) => { if (!server.listening) { resolve() return } server.close(() => resolve()) }) return closePromise } const timer = setTimeout(() => { settle('expired') }, ttlMs) function settle(outcome: PairingOutcome): void { if (settled) return settled = true clearTimeout(timer) resolveDone(outcome) void closeServer() } async function handleRequest(request: IncomingMessage, response: ServerResponse): Promise { const pathname = new URL(request.url ?? '/', 'http://pairing.local').pathname if (settled || pathname !== REDEEM_PATH || request.method !== 'POST') { sendJson(response, 404, { error: 'not found' }) return } const challenge = readPairingChallenge(await readJsonBody(request)) if (settled) { sendJson(response, 404, { error: 'not found' }) return } if (challenge === null) { rejectRequest(response, 400, 'invalid pairing request') return } if (!(await verifyOpenCodePairingProof(code, challenge.nonce, challenge.proof))) { rejectRequest(response, 401, 'invalid pairing proof') return } let encrypted: OpenCodePairingEncryptedCredentials try { encrypted = await encryptOpenCodePairingCredentials({ code, nonce: challenge.nonce, credentials }) } catch { sendJson(response, 500, { error: 'pairing encryption failed' }) return } if (settled) { sendJson(response, 404, { error: 'not found' }) return } sendJson(response, 200, { ...encrypted }, () => { settle('linked') }) } function rejectRequest(response: ServerResponse, status: number, error: string): void { failures += 1 sendJson(response, status, { error }, failures >= maxAttempts ? () => { settle('rejected') } : undefined) } const server = createServer((request, response) => { void handleRequest(request, response) }) try { await new Promise((resolve, reject) => { const onError = (error: Error) => { reject(error) } server.once('error', onError) server.listen(port, '0.0.0.0', () => { server.off('error', onError) resolve() }) }) } catch (error) { clearTimeout(timer) throw error } const address = server.address() const parsedAddress = z.object({ port: z.number() }).safeParse(address) const boundPort = parsedAddress.success ? parsedAddress.data.port : port return { url: `http://${hostname}:${boundPort}${REDEEM_PATH}`, port: boundPort, done, close: async () => { clearTimeout(timer) await closeServer() }, } } interface PairingChallenge { nonce: string proof: string } const PairingChallengeSchema = z.object({ nonce: z.string(), proof: z.string().min(1), }) function readPairingChallenge(body: JsonValue | null): PairingChallenge | null { const challenge = PairingChallengeSchema.safeParse(body) if (!challenge.success) return null if (!isOpenCodePairingNonce(challenge.data.nonce)) return null return challenge.data } function readJsonBody(request: IncomingMessage): Promise { return new Promise((resolve) => { const chunks: Buffer[] = [] let size = 0 let finished = false const finish = (value: JsonValue | null) => { if (finished) return finished = true resolve(value) } request.on('data', (chunk: Buffer) => { if (size > MAX_BODY_BYTES) return size += chunk.length if (size > MAX_BODY_BYTES) { chunks.length = 0 return } chunks.push(chunk) }) request.on('end', () => { finish(parseJsonText(Buffer.concat(chunks).toString('utf8'))) }) request.on('error', () => finish(null)) }) } function sendJson(response: ServerResponse, status: number, body: JsonValue, onFlushed?: () => void): void { const payload = JSON.stringify(body) response.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload), connection: 'close', }) response.end(payload, onFlushed) }