diff --git a/ocm-cli/README.md b/ocm-cli/README.md index 76929d0f..77dee820 100644 --- a/ocm-cli/README.md +++ b/ocm-cli/README.md @@ -163,17 +163,32 @@ Run `ocm link` on a machine that hosts a bare `opencode serve` to pair it with OpenCode Manager without copying the password by hand: ```bash -OPENCODE_SERVER_PASSWORD=... ocm link +ocm link ``` It prints a terminal QR code and an `ocm://link` URL. Scanning or pasting that into the Manager adds the server with its name, base URL, username, and password. +It auto-detects the OpenCode background service (`opencode serve --service`). +The service registration in `$XDG_STATE_HOME/opencode/service.json` (default +`~/.local/state/opencode/service.json`) is read first, then the `opencode +service` config in `$XDG_CONFIG_HOME/opencode/service.json` (default +`~/.config/opencode/service.json`), which provides the hostname (default +`127.0.0.1`) and port (default `49374`, or `45278` on Windows). A wildcard host +such as `0.0.0.0` is replaced with this machine's LAN IPv4 address, and the +service password is used when none is passed. A service bound to loopback +produces a warning because a remote Manager cannot reach it; run `opencode +service set hostname 0.0.0.0` to expose it. + +An explicit `--url` or `$OPENCODE_SERVER_URL` skips service detection, so the +detected service password is not reused; pass `--password` or set +`$OPENCODE_SERVER_PASSWORD` in that case. + | Flag | Default | |---|---| -| `--url ` | `$OPENCODE_SERVER_URL`, else `http://:4096` | -| `--password ` | `$OPENCODE_SERVER_PASSWORD` (required) | +| `--url ` | `$OPENCODE_SERVER_URL`, else the detected OpenCode service URL, else `http://:4096`; an explicit value skips service detection | +| `--password ` | `$OPENCODE_SERVER_PASSWORD`, else the detected OpenCode service password; an explicit URL needs one of the first two | | `--username ` | `$OPENCODE_SERVER_USERNAME`, else `opencode` | | `--name ` | the machine hostname | | `--pair-host ` | the host of `--url` | diff --git a/ocm-cli/bin/ocm.ts b/ocm-cli/bin/ocm.ts index 9f469be2..c9169438 100644 --- a/ocm-cli/bin/ocm.ts +++ b/ocm-cli/bin/ocm.ts @@ -19,7 +19,7 @@ import { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/mana import { OCM_VERSION as VERSION, warmRepoProxy } from '../src/repo-proxy.js' import { resolveManagerAuth } from '../src/manager-auth.js' import type { ManagerAuthOk } from '../src/manager-auth.js' -import { generatePairingCode, probeOpenCodeServer, renderPairingQr, resolveDefaultBaseUrl, startPairingServer } from '../src/link.js' +import { discoverOpenCodeService, generatePairingCode, probeOpenCodeServer, renderPairingQr, resolveDefaultBaseUrl, startPairingServer } from '../src/link.js' const USAGE = `ocm v${VERSION} - OpenCode Manager workspace launcher @@ -637,6 +637,8 @@ interface LinkCommandOptions { pairPort: number ttlMs: number showQr: boolean + serviceSource: 'registration' | 'config' | null + serviceLoopbackOnly: boolean } function parseLinkInteger(value: string, flag: string, min: number, max: number): number { @@ -678,9 +680,13 @@ function parseLinkArgs(args: string[]): LinkCommandOptions { index++ } - const baseUrl = normalizeLinkBaseUrl(values.url ?? process.env.OPENCODE_SERVER_URL ?? resolveDefaultBaseUrl()) - const password = values.password ?? process.env.OPENCODE_SERVER_PASSWORD - if (!password) die('no OpenCode password: pass --password or set OPENCODE_SERVER_PASSWORD') + const explicitUrl = values.url ?? (process.env.OPENCODE_SERVER_URL || undefined) + const service = explicitUrl === undefined ? discoverOpenCodeService() : null + const baseUrl = normalizeLinkBaseUrl(explicitUrl ?? service?.baseUrl ?? resolveDefaultBaseUrl()) + const password = values.password ?? (process.env.OPENCODE_SERVER_PASSWORD || undefined) ?? service?.password + if (!password) { + die('no OpenCode password: pass --password, set OPENCODE_SERVER_PASSWORD, or configure the OpenCode service') + } return { baseUrl, @@ -691,6 +697,8 @@ function parseLinkArgs(args: string[]): LinkCommandOptions { pairPort: parseLinkInteger(values.pairPort ?? '0', '--pair-port', 0, 65535), ttlMs: parseLinkInteger(values.ttl ?? '300', '--ttl', 1, 86400) * 1000, showQr, + serviceSource: service?.source ?? null, + serviceLoopbackOnly: service?.loopbackOnly ?? false, } } @@ -703,6 +711,13 @@ export async function cmdLink(args: string[]): Promise { const options = parseLinkArgs(args) const credentials = { username: options.username, password: options.password } + if (options.serviceSource) { + info(`using the OpenCode service at ${options.baseUrl} (from ${options.serviceSource})`) + if (options.serviceLoopbackOnly) { + warn(`it only listens on loopback, so a remote Manager cannot reach ${options.baseUrl}; run \`opencode service set hostname 0.0.0.0\` to expose it on the LAN`) + } + } + const probe = await probeOpenCodeServer(options.baseUrl, credentials) if (probe.status === 'unauthorized') { die(`OpenCode at ${options.baseUrl} rejected the credentials (401); check --username and --password`) diff --git a/ocm-cli/src/link.ts b/ocm-cli/src/link.ts index 887f168c..585920c0 100644 --- a/ocm-cli/src/link.ts +++ b/ocm-cli/src/link.ts @@ -1,6 +1,8 @@ import { randomBytes } from 'node:crypto' +import { readFileSync } from 'node:fs' import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' -import { networkInterfaces, type NetworkInterfaceInfo } from 'node:os' +import { homedir, networkInterfaces, type NetworkInterfaceInfo } from 'node:os' +import { join } from 'node:path' import { renderUnicodeCompact } from 'uqr' import { buildOpenCodeBasicAuth, @@ -13,6 +15,10 @@ import { import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils' const DEFAULT_OPENCODE_PORT = 4096 +const DEFAULT_SERVICE_PORT = process.platform === 'win32' ? 45278 : 49374 +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 @@ -46,18 +52,125 @@ export function generatePairingCode(): string { return randomBytes(32).toString('base64url') } +/** Returns the first non-internal IPv4 address, or null when the machine exposes none. */ +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 +} + /** Picks the OpenCode base URL from the first non-internal IPv4 interface, else loopback. */ export function resolveDefaultBaseUrl( interfaces: NodeJS.Dict = networkInterfaces(), ): string { - for (const entries of Object.values(interfaces)) { - for (const entry of entries ?? []) { - if (entry.family === 'IPv4' && !entry.internal) { - return `http://${entry.address}:${DEFAULT_OPENCODE_PORT}` - } + 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 +} + +/** + * Reads the OpenCode background service registration, then its config, and resolves the URL a + * Manager should pair with. Never throws; returns null when neither file yields a usable service. + */ +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', } } - return `http://127.0.0.1:${DEFAULT_OPENCODE_PORT}` + + 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 ?? DEFAULT_SERVICE_PORT}`, + 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): Record | null { + try { + const parsed: unknown = JSON.parse(readFileSync(file, 'utf8')) + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null + return parsed as Record + } catch { + return null + } +} + +function readString(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 ? value : null +} + +function readPort(value: unknown): number | null { + return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 65535 ? value : null } /** Renders the pairing link as a half-block QR code for terminals. */ diff --git a/ocm-cli/test/link.test.ts b/ocm-cli/test/link.test.ts index 563ee791..11a05b7a 100644 --- a/ocm-cli/test/link.test.ts +++ b/ocm-cli/test/link.test.ts @@ -1,16 +1,93 @@ -import { describe, it, expect } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir, type NetworkInterfaceInfo } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, it, expect, vi } from 'vitest' import { createOpenCodePairingNonce, createOpenCodePairingProof, decryptOpenCodePairingCredentials, } from '@opencode-manager/shared/opencode' -import { generatePairingCode, resolveDefaultBaseUrl, startPairingServer } from '../src/link' +import { discoverOpenCodeService, generatePairingCode, resolveDefaultBaseUrl, resolveLanIPv4, startPairingServer } from '../src/link' import type { PairingServerOptions } from '../src/link' import { buildOpenCodeServerLink, parseOpenCodeServerLink } from '@opencode-manager/shared/schemas' const CODE = 'test-pairing-code-0123456789abcdef' const CREDENTIALS = { username: 'opencode', password: 'secret-password' } +const LAN_INTERFACES: NodeJS.Dict = { + lo: [{ address: '127.0.0.1', family: 'IPv4', internal: true, netmask: '255.0.0.0', mac: '00:00:00:00:00:00', cidr: '127.0.0.1/8' }], + eth0: [{ address: '192.168.1.20', family: 'IPv4', internal: false, netmask: '255.255.255.0', mac: '00:11:22:33:44:55', cidr: '192.168.1.20/24' }], +} + +const INTERNAL_ONLY_INTERFACES: NodeJS.Dict = { + lo: [ + { address: '127.0.0.1', family: 'IPv4', internal: true, netmask: '255.0.0.0', mac: '00:00:00:00:00:00', cidr: '127.0.0.1/8' }, + { address: '::1', family: 'IPv6', internal: true, netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', mac: '00:00:00:00:00:00', scopeid: 0, cidr: '::1/128' }, + ], +} + +const PLATFORM_SERVICE_PORT = process.platform === 'win32' ? 45278 : 49374 + +interface ServiceHome { + home: string + state: string + config: string +} + +const tempDirs: string[] = [] + +afterEach(() => { + for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true }) +}) + +function createServiceHome(): ServiceHome { + const home = mkdtempSync(join(tmpdir(), 'ocm-service-')) + tempDirs.push(home) + const state = join(home, 'state') + const config = join(home, 'config') + mkdirSync(join(state, 'opencode'), { recursive: true }) + mkdirSync(join(config, 'opencode'), { recursive: true }) + return { home, state, config } +} + +function discover(paths: ServiceHome, interfaces: NodeJS.Dict = LAN_INTERFACES) { + return discoverOpenCodeService({ + env: { XDG_STATE_HOME: paths.state, XDG_CONFIG_HOME: paths.config }, + home: paths.home, + interfaces, + }) +} + +async function discoverOnPlatform( + platform: NodeJS.Platform, + paths: ServiceHome, + interfaces: NodeJS.Dict = LAN_INTERFACES, +) { + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { value: platform }) + try { + vi.resetModules() + const { discoverOpenCodeService: discoverService } = await import('../src/link') + return discoverService({ + env: { XDG_STATE_HOME: paths.state, XDG_CONFIG_HOME: paths.config }, + home: paths.home, + interfaces, + }) + } finally { + Object.defineProperty(process, 'platform', { value: originalPlatform }) + } +} + +function writeRegistration(paths: ServiceHome, content: unknown): void { + const file = join(paths.state, 'opencode', 'service.json') + writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content)) +} + +function writeServiceConfig(paths: ServiceHome, content: unknown): void { + const file = join(paths.config, 'opencode', 'service.json') + writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content)) +} + function startPairing(overrides: Partial = {}) { return startPairingServer({ code: CODE, @@ -56,6 +133,162 @@ describe('resolveDefaultBaseUrl', () => { }) }) +describe('resolveLanIPv4', () => { + it('returns null when no external IPv4 interface exists', () => { + expect(resolveLanIPv4(INTERNAL_ONLY_INTERFACES)).toBeNull() + expect(resolveLanIPv4({})).toBeNull() + }) +}) + +describe('discoverOpenCodeService', () => { + it('substitutes the LAN address for a wildcard registration host and keeps the port', () => { + const paths = createServiceHome() + writeRegistration(paths, { + id: 'registration-id', + version: '2.0.32', + url: 'http://0.0.0.0:49374', + pid: 4242, + password: 'service-secret', + }) + + expect(discover(paths)).toEqual({ + baseUrl: 'http://192.168.1.20:49374', + password: 'service-secret', + source: 'registration', + loopbackOnly: false, + }) + }) + + it('falls back to the service config with the default hostname and port', () => { + const paths = createServiceHome() + writeServiceConfig(paths, { password: 'config-secret' }) + + expect(discover(paths)).toEqual({ + baseUrl: `http://127.0.0.1:${PLATFORM_SERVICE_PORT}`, + password: 'config-secret', + source: 'config', + loopbackOnly: true, + }) + }) + + it('uses the configured hostname and port when present', () => { + const paths = createServiceHome() + writeServiceConfig(paths, { hostname: '0.0.0.0', port: 5000 }) + + expect(discover(paths)).toEqual({ + baseUrl: 'http://192.168.1.20:5000', + password: null, + source: 'config', + loopbackOnly: false, + }) + }) + + it('brackets an IPv6 wildcard config hostname and substitutes the LAN address', () => { + const paths = createServiceHome() + writeServiceConfig(paths, { hostname: '::', port: 5000 }) + + expect(discover(paths)).toEqual({ + baseUrl: 'http://192.168.1.20:5000', + password: null, + source: 'config', + loopbackOnly: false, + }) + }) + + it('brackets an IPv6 loopback config hostname', () => { + const paths = createServiceHome() + writeServiceConfig(paths, { hostname: '::1' }) + + expect(discover(paths)).toEqual({ + baseUrl: `http://[::1]:${PLATFORM_SERVICE_PORT}`, + password: null, + source: 'config', + loopbackOnly: true, + }) + }) + + it('marks loopback registrations as loopback only', () => { + const cases = [ + { host: '127.0.0.1', url: 'http://127.0.0.1:49374' }, + { host: 'localhost', url: 'http://localhost:49374' }, + { host: '::1', url: 'http://[::1]:49374' }, + ] + + for (const { host, url } of cases) { + const paths = createServiceHome() + writeRegistration(paths, { url, pid: 4242 }) + + expect(discover(paths), host).toEqual({ + baseUrl: url, + password: null, + source: 'registration', + loopbackOnly: true, + }) + } + }) + + it('returns null when neither the registration nor the config exists', () => { + expect(discover(createServiceHome())).toBeNull() + }) + + it('ignores a malformed registration and falls back to the config', () => { + const paths = createServiceHome() + writeRegistration(paths, '{ not json') + writeServiceConfig(paths, { hostname: '192.168.1.50', port: 5000, password: 'config-secret' }) + + expect(discover(paths)).toEqual({ + baseUrl: 'http://192.168.1.50:5000', + password: 'config-secret', + source: 'config', + loopbackOnly: false, + }) + }) + + it('marks a wildcard registration as loopback when no LAN address exists', () => { + const paths = createServiceHome() + writeRegistration(paths, { url: 'http://0.0.0.0:49374', password: 'service-secret' }) + + expect(discover(paths, INTERNAL_ONLY_INTERFACES)).toEqual({ + baseUrl: 'http://127.0.0.1:49374', + password: 'service-secret', + source: 'registration', + loopbackOnly: true, + }) + }) + + it('uses the config password when the registration URL is unusable', () => { + const paths = createServiceHome() + writeRegistration(paths, { url: 'not-a-url', password: 'stale-secret' }) + writeServiceConfig(paths, { hostname: '192.168.1.50', port: 5000, password: 'config-secret' }) + + expect(discover(paths)).toEqual({ + baseUrl: 'http://192.168.1.50:5000', + password: 'config-secret', + source: 'config', + loopbackOnly: false, + }) + }) + + it('uses the platform default service port when the config omits one', async () => { + const cases: Array<{ platform: NodeJS.Platform; port: number }> = [ + { platform: 'linux', port: 49374 }, + { platform: 'win32', port: 45278 }, + ] + + for (const { platform, port } of cases) { + const paths = createServiceHome() + writeServiceConfig(paths, { password: 'config-secret' }) + + expect(await discoverOnPlatform(platform, paths), platform).toEqual({ + baseUrl: `http://127.0.0.1:${port}`, + password: 'config-secret', + source: 'config', + loopbackOnly: true, + }) + } + }) +}) + describe('startPairingServer', () => { it('redeems a valid proof and returns credentials that decrypt with the code and nonce', async () => { const pairing = await startPairing()