- Scan the code shown by the server, or paste its pairing link.
+ Run opencode pair --remote on the server (or opencode pair on the same
+ network), then scan its QR code or paste the link.
)}
+ {pairingLink && (
+
+ OpenCode pairing links sign this Manager in for 30 days. The Manager renews them automatically
+ while the server stays reachable.
+
+ )}
)}
diff --git a/ocm-cli/README.md b/ocm-cli/README.md
index 3cd4812a9..c848eb66f 100644
--- a/ocm-cli/README.md
+++ b/ocm-cli/README.md
@@ -46,8 +46,7 @@ Attachment works with OpenCode Manager >= 0.19.0. The sync worktree targeting of
`ocm push` / `ocm pull` and `/ocm-move` worktree moves need ocm 0.4.0+ and
OpenCode Manager 1.0.0+; an older CLI is told to upgrade, and an older Manager is
reported as needing an upgrade (push and pull fall back to the main checkout
-instead). `ocm link` needs ocm 0.4.1+ and OpenCode Manager 1.1.0+ to pair the
-linked server.
+instead).
## Install
@@ -117,8 +116,6 @@ ocm use
ocm push [repoId] [--force] [--create] [--yes] [--full]
ocm pull [repoId] [--force] [--full]
ocm install [--dir ] [--force] [--no-link]
-ocm link [--url ] [--password ] [--username ] [--name ]
- [--pair-host ] [--pair-port ] [--ttl ] [--no-qr]
ocm logout
ocm --version
ocm --help
@@ -177,57 +174,12 @@ repos matching the current project (the command fails clearly otherwise), and
any ambiguity message lists each match with its id, kind (repo or worktree),
branch, and path. The default attach reports the same details.
-## Link a raw OpenCode server
+## Pair an OpenCode server
-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
-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 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` |
-| `--pair-port ` | `0` (ephemeral) |
-| `--ttl ` | `300` |
-| `--no-qr` | off; print only the link |
-
-Before showing the code it calls `GET /api/info` with Basic auth and warns
-when the server is unreachable; a `401` stops the command. The command then
-listens on `0.0.0.0` for one `POST /redeem`. The pairing code never crosses the
-network: the Manager sends a random nonce and an HMAC-SHA256 proof of the code,
-and the listener answers with the credentials encrypted with AES-256-GCM under a
-key derived from the code and the nonce (HKDF-SHA256). It then prints `Linked`
-and exits. A malformed request returns `400`, a wrong proof returns `401`, and
-the third failure ends the command; the TTL ends it with `Pairing code expired`.
-Links use version `v=2`; the Manager rejects older links with a message to
-update. The pairing listener and the OpenCode server itself still use plain HTTP
-unless you put them behind TLS, so use HTTPS or a private network for the
-server traffic.
+Run `opencode pair --remote` on the server (or `opencode pair` on the same
+network), then scan its QR code or paste the printed link in Manager → Settings
+→ Servers → Add server. Pairing links sign the Manager in for 30 days and are
+renewed automatically while the server stays reachable.
## OpenCode TUI plugin
diff --git a/ocm-cli/bin/ocm.ts b/ocm-cli/bin/ocm.ts
index 51167235b..935de0213 100644
--- a/ocm-cli/bin/ocm.ts
+++ b/ocm-cli/bin/ocm.ts
@@ -1,8 +1,6 @@
import { spawn, spawnSync } from 'child_process'
-import { hostname } from 'os'
import { basename, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
-import { buildOpenCodeServerLink, OPENCODE_SERVER_USERNAME } from '@opencode-manager/shared/schemas'
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
import { readState, writeState, clearState, getStatePath, writeInstallNotice, type OcmState } from '../src/state.js'
import { installVendoredOcm, resolveOpenCodeConfigDir, InstallError, OCM_PLUGIN_SPEC } from '../src/vendor-install.js'
@@ -19,7 +17,6 @@ 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 { discoverOpenCodeService, generatePairingCode, probeOpenCodeServer, renderPairingQr, resolveDefaultBaseUrl, startPairingServer } from '../src/link.js'
const USAGE = `ocm v${VERSION} - OpenCode Manager workspace launcher
@@ -40,10 +37,6 @@ Usage:
Mirror the matching Manager repo over $PWD (fast patch sync by default)
ocm install [--dir ] [--force] [--no-link]
Vendor the CLI + TUI plugin into the OpenCode config dir
- ocm link [--url ] [--password ] [--username ] [--name ]
- [--pair-host ] [--pair-port ] [--ttl ] [--no-qr]
- Pair a Manager with this machine's opencode serve
- by scanning a QR code
ocm --version Show the installed ocm version
ocm --help Show this help
`
@@ -57,10 +50,6 @@ function info(msg: string): void {
process.stdout.write(`${msg}\n`)
}
-function warn(msg: string): void {
- process.stderr.write(`ocm: warning: ${msg}\n`)
-}
-
function promptYesNo(question: string): boolean {
process.stderr.write(`${question} [y/N] `)
const res = spawnSync('bash', ['-c', 'read LINE && printf "%s" "$LINE"'], {
@@ -614,163 +603,6 @@ export async function cmdInstall(args: string[]): Promise {
}
}
-const LINK_USAGE = `usage: ocm link [--url ] [--password ] [--username ] [--name ]
- [--pair-host ] [--pair-port ] [--ttl ] [--no-qr]`
-
-type LinkFlag = 'url' | 'password' | 'username' | 'name' | 'pairHost' | 'pairPort' | 'ttl'
-
-const LINK_FLAGS = new Map([
- ['--url', 'url'],
- ['--password', 'password'],
- ['--username', 'username'],
- ['--name', 'name'],
- ['--pair-host', 'pairHost'],
- ['--pair-port', 'pairPort'],
- ['--ttl', 'ttl'],
-])
-
-const PAIRING_MAX_ATTEMPTS = 3
-
-interface LinkCommandOptions {
- baseUrl: string
- username: string
- password: string
- name: string
- pairHost: string
- pairPort: number
- ttlMs: number
- showQr: boolean
- serviceSource: 'registration' | 'config' | null
- serviceLoopbackOnly: boolean
-}
-
-function parseLinkInteger(value: string, flag: string, min: number, max: number): number {
- const parsed = Number(value)
- if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
- die(`${flag} must be an integer between ${min} and ${max}`)
- }
- return parsed
-}
-
-function normalizeLinkBaseUrl(value: string): string {
- let parsed: URL
- try {
- parsed = new URL(value)
- } catch {
- die(`invalid --url: ${value}`)
- }
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- die(`invalid --url: ${value} (expected http:// or https://)`)
- }
- return parsed.href.replace(/\/+$/, '')
-}
-
-function parseLinkArgs(args: string[]): LinkCommandOptions {
- const values: Partial> = {}
- let showQr = true
-
- for (let index = 0; index < args.length; index++) {
- const arg = args[index]!
- if (arg === '--no-qr') {
- showQr = false
- continue
- }
- const key = LINK_FLAGS.get(arg)
- if (!key) die(`unknown option: ${arg}. run \`ocm --help\``)
- const value = args[index + 1]
- if (!value || value.startsWith('--')) die(LINK_USAGE)
- values[key] = value
- index++
- }
-
- 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,
- username: values.username ?? process.env.OPENCODE_SERVER_USERNAME ?? OPENCODE_SERVER_USERNAME,
- password,
- name: values.name ?? hostname(),
- pairHost: values.pairHost ?? new URL(baseUrl).hostname,
- 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,
- }
-}
-
-export async function cmdLink(args: string[]): Promise {
- if (args.includes('--help') || args.includes('-h')) {
- info(LINK_USAGE)
- return
- }
-
- 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`)
- }
- if (probe.status === 'unreachable') {
- warn(`could not reach ${options.baseUrl} (${probe.message}); pairing anyway`)
- } else {
- info(`OpenCode${probe.version ? ` ${probe.version}` : ''} at ${options.baseUrl}`)
- }
-
- const code = generatePairingCode()
- const pairing = await startPairingServer({
- code,
- credentials,
- ttlMs: options.ttlMs,
- maxAttempts: PAIRING_MAX_ATTEMPTS,
- port: options.pairPort,
- hostname: options.pairHost,
- })
-
- const link = buildOpenCodeServerLink({
- kind: 'opencode',
- name: options.name,
- baseUrl: options.baseUrl,
- pairing: { pairUrl: pairing.url, code },
- })
-
- const expiresAt = new Date(Date.now() + options.ttlMs)
- if (options.showQr) {
- info('')
- info(renderPairingQr(link))
- }
- info('')
- info(`Link: ${link}`)
- info(`Pairing URL: ${pairing.url}`)
- info(`Expires: ${expiresAt.toISOString()} (in ${Math.round(options.ttlMs / 1000)}s)`)
- warn('the pairing listener uses plain HTTP; use it only on a private network.')
- info('Waiting for OpenCode Manager to scan the code...')
-
- const outcome = await pairing.done
- await pairing.close()
-
- if (outcome === 'linked') {
- info('Linked')
- return
- }
- if (outcome === 'expired') die('Pairing code expired')
- die('too many invalid pairing attempts; no Manager was linked')
-}
-
async function main(): Promise {
const [, , cmd, ...rest] = process.argv
@@ -815,9 +647,6 @@ async function main(): Promise {
case 'install':
await cmdInstall(rest)
break
- case 'link':
- await cmdLink(rest)
- break
default:
die(`unknown command: ${cmd}. run \`ocm --help\``)
}
diff --git a/ocm-cli/package.json b/ocm-cli/package.json
index a63dcaaff..a4de2916a 100644
--- a/ocm-cli/package.json
+++ b/ocm-cli/package.json
@@ -65,7 +65,6 @@
"jsonc-parser": "^3.3.1",
"solid-js": "catalog:",
"typescript": "^5.5.0",
- "uqr": "^0.1.3",
"vitest": "^3.1.0",
"zod": "^4.3.2"
}
diff --git a/ocm-cli/src/link.ts b/ocm-cli/src/link.ts
deleted file mode 100644
index ef2e74a98..000000000
--- a/ocm-cli/src/link.ts
+++ /dev/null
@@ -1,394 +0,0 @@
-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)
-}
diff --git a/ocm-cli/test/helpers/cli-home.ts b/ocm-cli/test/helpers/cli-home.ts
index f0c6c22c6..45aac68a1 100644
--- a/ocm-cli/test/helpers/cli-home.ts
+++ b/ocm-cli/test/helpers/cli-home.ts
@@ -27,8 +27,10 @@ const DEFAULT_ACCOUNT = 'https://manager.example.com'
export function createCliHome(options: CliHomeOptions = {}): CliHome {
const savedHome = process.env.HOME
const savedToken = process.env.OCM_TOKEN
+ const savedPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
const home = mkdtempSync(join(tmpdir(), 'ocm-home-'))
process.env.HOME = home
+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true })
if (options.envToken) process.env.OCM_TOKEN = options.envToken
else delete process.env.OCM_TOKEN
@@ -63,6 +65,7 @@ export function createCliHome(options: CliHomeOptions = {}): CliHome {
else process.env.HOME = savedHome
if (savedToken === undefined) delete process.env.OCM_TOKEN
else process.env.OCM_TOKEN = savedToken
+ if (savedPlatform) Object.defineProperty(process, 'platform', savedPlatform)
rmSync(home, { recursive: true, force: true })
},
}
diff --git a/ocm-cli/test/link.test.ts b/ocm-cli/test/link.test.ts
deleted file mode 100644
index 64c2341a1..000000000
--- a/ocm-cli/test/link.test.ts
+++ /dev/null
@@ -1,506 +0,0 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
-import { tmpdir, type NetworkInterfaceInfo } from 'node:os'
-import { join } from 'node:path'
-import { afterEach, describe, it, expect } from 'vitest'
-import { z } from 'zod'
-import { parseJsonText, type JsonObject, type JsonValue } from '@opencode-manager/shared/utils'
-import {
- buildOpenCodeBasicAuth,
- createOpenCodePairingNonce,
- createOpenCodePairingProof,
- decryptOpenCodePairingCredentials,
-} from '@opencode-manager/shared/opencode'
-import {
- discoverOpenCodeService,
- generatePairingCode,
- probeOpenCodeServer,
- 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 PairingPayloadSchema = z.object({ iv: z.string(), ciphertext: z.string() })
-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[] = []
-
-const probeServers: ProbeServer[] = []
-
-afterEach(async () => {
- for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true })
- await Promise.all(probeServers.splice(0).map((server) => server.close()))
-})
-
-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,
- })
-}
-
-function discoverOnPlatform(
- platform: NodeJS.Platform,
- paths: ServiceHome,
- interfaces: NodeJS.Dict = LAN_INTERFACES,
-) {
- return discoverOpenCodeService({
- env: { XDG_STATE_HOME: paths.state, XDG_CONFIG_HOME: paths.config },
- home: paths.home,
- interfaces,
- platform,
- })
-}
-
-function writeServiceFile(file: string, content: JsonValue): void {
- const raw = z.string().safeParse(content)
- writeFileSync(file, raw.success ? raw.data : JSON.stringify(content))
-}
-
-function writeRegistration(paths: ServiceHome, content: JsonValue): void {
- writeServiceFile(join(paths.state, 'opencode', 'service.json'), content)
-}
-
-function writeServiceConfig(paths: ServiceHome, content: JsonValue): void {
- writeServiceFile(join(paths.config, 'opencode', 'service.json'), content)
-}
-
-function startPairing(overrides: Partial = {}) {
- return startPairingServer({
- code: CODE,
- credentials: CREDENTIALS,
- ttlMs: 5000,
- maxAttempts: 3,
- port: 0,
- hostname: '127.0.0.1',
- ...overrides,
- })
-}
-
-function redeem(url: string, body: JsonObject, init: RequestInit = {}): Promise {
- return fetch(url, { method: 'POST', body: JSON.stringify(body), ...init })
-}
-
-async function createChallenge(code = CODE): Promise<{ nonce: string; proof: string }> {
- const nonce = createOpenCodePairingNonce()
- return { nonce, proof: await createOpenCodePairingProof(code, nonce) }
-}
-
-interface ProbeServer {
- baseUrl: string
- requests: Array<{ url: string | undefined; authorization: string | undefined }>
- close: () => Promise
-}
-
-async function startProbeServer(
- respond: (request: IncomingMessage, response: ServerResponse) => void,
-): Promise {
- const requests: ProbeServer['requests'] = []
- const server = createServer((request, response) => {
- requests.push({ url: request.url, authorization: request.headers.authorization })
- respond(request, response)
- })
- await new Promise((resolve) => {
- server.listen(0, '127.0.0.1', resolve)
- })
- const address = server.address()
- const bound = z.object({ port: z.number() }).safeParse(address)
- const port = bound.success ? bound.data.port : 0
- const handle: ProbeServer = {
- baseUrl: `http://127.0.0.1:${port}`,
- requests,
- close: () => new Promise((resolve) => {
- server.closeAllConnections()
- server.close(() => resolve())
- }),
- }
- probeServers.push(handle)
- return handle
-}
-
-describe('generatePairingCode', () => {
- it('returns 32 random bytes as base64url', () => {
- const first = generatePairingCode()
- const second = generatePairingCode()
-
- expect(first).toMatch(/^[A-Za-z0-9_-]{43}$/)
- expect(second).toMatch(/^[A-Za-z0-9_-]{43}$/)
- expect(first).not.toBe(second)
- })
-})
-
-describe('resolveDefaultBaseUrl', () => {
- it('uses the first non-internal IPv4 interface on port 4096', () => {
- expect(resolveDefaultBaseUrl({
- 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' }],
- })).toBe('http://192.168.1.20:4096')
- })
-
- it('falls back to loopback when only internal interfaces exist', () => {
- expect(resolveDefaultBaseUrl({})).toBe('http://127.0.0.1:4096')
- })
-})
-
-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.each([
- ['linux', 49374],
- ['win32', 45278],
- ] as const)('uses the %s default service port when the config omits one', (platform, port) => {
- const paths = createServiceHome()
- writeServiceConfig(paths, { password: 'config-secret' })
-
- expect(discoverOnPlatform(platform, paths)).toEqual({
- baseUrl: `http://127.0.0.1:${port}`,
- password: 'config-secret',
- source: 'config',
- loopbackOnly: true,
- })
- })
-})
-
-describe('probeOpenCodeServer', () => {
- it('reports ok with the server version from an authenticated info request', async () => {
- const server = await startProbeServer((_request, response) => {
- response.writeHead(200, { 'content-type': 'application/json' })
- response.end(JSON.stringify({ version: '2.0.32' }))
- })
-
- await expect(probeOpenCodeServer(`${server.baseUrl}/`, CREDENTIALS, 1000)).resolves.toEqual({
- status: 'ok',
- version: '2.0.32',
- })
- expect(server.requests).toEqual([
- {
- url: '/api/info',
- authorization: buildOpenCodeBasicAuth(CREDENTIALS.password, CREDENTIALS.username),
- },
- ])
- })
-
- it.each([
- ['a JSON error body', 'application/json', JSON.stringify({ _tag: 'UnauthorizedError', message: 'unauthorized' })],
- ['an empty body', 'text/plain', ''],
- ['a plain text body', 'text/plain', 'unauthorized'],
- ])('reports unauthorized when the server rejects the credentials with %s', async (_label, contentType, body) => {
- const server = await startProbeServer((_request, response) => {
- response.writeHead(401, { 'content-type': contentType })
- response.end(body)
- })
-
- await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
- status: 'unauthorized',
- })
- })
-
- it.each([
- ['a JSON body', 'application/json', JSON.stringify({ error: 'boom' })],
- ['a plain text body', 'text/plain', 'boom'],
- ])('reports unreachable with the HTTP status for an unexpected %s', async (_label, contentType, body) => {
- const server = await startProbeServer((_request, response) => {
- response.writeHead(500, { 'content-type': contentType })
- response.end(body)
- })
-
- await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
- status: 'unreachable',
- message: 'HTTP 500',
- })
- })
-
- it('reports unreachable when the server refuses the connection', async () => {
- const server = await startProbeServer(() => {})
- const baseUrl = server.baseUrl
- await server.close()
-
- const probe = await probeOpenCodeServer(baseUrl, CREDENTIALS, 1000)
-
- expect(probe.status).toBe('unreachable')
- expect(probe).toMatchObject({ message: expect.stringContaining('Transport') })
- })
-})
-
-describe('startPairingServer', () => {
- it('redeems a valid proof and returns credentials that decrypt with the code and nonce', async () => {
- const pairing = await startPairing()
- const challenge = await createChallenge()
-
- const response = await redeem(pairing.url, challenge)
- const raw = await response.text()
-
- expect(response.status).toBe(200)
- expect(raw).not.toContain(CREDENTIALS.password)
- expect(raw).not.toContain(CODE)
-
- const payload = PairingPayloadSchema.parse(parseJsonText(raw))
- await expect(decryptOpenCodePairingCredentials({
- code: CODE,
- nonce: challenge.nonce,
- iv: payload.iv,
- ciphertext: payload.ciphertext,
- })).resolves.toEqual(CREDENTIALS)
- await expect(pairing.done).resolves.toBe('linked')
- await pairing.close()
- })
-
- it('rejects a wrong proof with 401 and rejects after three failures', async () => {
- const pairing = await startPairing({ maxAttempts: 3 })
-
- for (let attempt = 0; attempt < 3; attempt++) {
- const response = await redeem(pairing.url, await createChallenge(`${CODE}-wrong`))
- expect(response.status).toBe(401)
- await expect(response.json()).resolves.toEqual({ error: 'invalid pairing proof' })
- }
-
- await expect(pairing.done).resolves.toBe('rejected')
- await pairing.close()
- })
-
- it('rejects a malformed body with 400 and counts it as a failure', async () => {
- const pairing = await startPairing({ maxAttempts: 1 })
-
- const response = await redeem(pairing.url, { nonce: 'not-a-nonce', proof: 'not-a-proof' })
-
- expect(response.status).toBe(400)
- await expect(response.json()).resolves.toEqual({ error: 'invalid pairing request' })
- await expect(pairing.done).resolves.toBe('rejected')
- await pairing.close()
- })
-
- it('treats a missing challenge as a failed attempt', async () => {
- const pairing = await startPairing({ maxAttempts: 1 })
-
- const response = await redeem(pairing.url, { notA: 'challenge' })
-
- expect(response.status).toBe(400)
- await expect(pairing.done).resolves.toBe('rejected')
- await pairing.close()
- })
-
- it('resolves expired after the ttl and stops listening', async () => {
- const pairing = await startPairing({ ttlMs: 50 })
-
- await expect(pairing.done).resolves.toBe('expired')
- await expect(redeem(pairing.url, await createChallenge())).rejects.toThrow()
- await pairing.close()
- })
-
- it('answers 404 for non-redeem paths and methods', async () => {
- const pairing = await startPairing()
-
- const otherPath = await fetch(new URL('/status', pairing.url))
- expect(otherPath.status).toBe(404)
- await expect(otherPath.json()).resolves.toEqual({ error: 'not found' })
-
- const wrongMethod = await fetch(pairing.url)
- expect(wrongMethod.status).toBe(404)
-
- await pairing.close()
- })
-
- it('produces a link that parses back with the shared parser', async () => {
- const pairing = await startPairing()
-
- const link = buildOpenCodeServerLink({
- kind: 'opencode',
- name: 'build-host',
- baseUrl: 'http://192.168.1.20:4096',
- pairing: { pairUrl: pairing.url, code: CODE },
- })
-
- expect(link).toContain('v=2')
- expect(parseOpenCodeServerLink(link)).toEqual({
- kind: 'opencode',
- name: 'build-host',
- baseUrl: 'http://192.168.1.20:4096',
- pairing: { pairUrl: `http://127.0.0.1:${pairing.port}/redeem`, code: CODE },
- })
-
- await pairing.close()
- })
-
- it('encrypts credentials under a key derived from the pairing code', async () => {
- const pairing = await startPairing()
- const challenge = await createChallenge()
-
- const payload = PairingPayloadSchema.parse(await redeem(pairing.url, challenge).then((response) => response.json()))
-
- await expect(decryptOpenCodePairingCredentials({
- code: `${CODE}-other`,
- nonce: challenge.nonce,
- iv: payload.iv,
- ciphertext: payload.ciphertext,
- })).rejects.toThrow()
- await pairing.close()
- })
-})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 826c02f4c..9bcf531d7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -343,9 +343,6 @@ importers:
typescript:
specifier: ^5.5.0
version: 5.9.3
- uqr:
- specifier: ^0.1.3
- version: 0.1.3
vitest:
specifier: ^3.1.0
version: 3.2.4(@types/debug@4.1.12)(@types/node@22.19.19)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
diff --git a/shared/src/opencode/index.ts b/shared/src/opencode/index.ts
index c3c44609e..369945b8d 100644
--- a/shared/src/opencode/index.ts
+++ b/shared/src/opencode/index.ts
@@ -129,23 +129,6 @@ export type {
McpTimeoutConfig,
} from './mcp'
-export {
- createOpenCodePairingNonce,
- createOpenCodePairingProof,
- decryptOpenCodePairingCredentials,
- encryptOpenCodePairingCredentials,
- isOpenCodePairingCredentials,
- isOpenCodePairingNonce,
- verifyOpenCodePairingProof,
-} from './pairing'
-
-export type {
- OpenCodePairingCredentials,
- OpenCodePairingDecryptOptions,
- OpenCodePairingEncryptedCredentials,
- OpenCodePairingKeyOptions,
-} from './pairing'
-
export {
OPENCODE_MIN_VERSION,
OPENCODE_PINNED_VERSION,
diff --git a/shared/src/opencode/pairing.ts b/shared/src/opencode/pairing.ts
deleted file mode 100644
index 9c02e015a..000000000
--- a/shared/src/opencode/pairing.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import { z } from 'zod'
-import { JsonValueSchema, type JsonValue } from '../utils/json'
-
-const PAIRING_PROTOCOL = 'ocm-pair-v2'
-const PAIRING_PROOF_PREFIX = `${PAIRING_PROTOCOL}:`
-const PAIRING_KEY_INFO = `${PAIRING_PROTOCOL} credentials`
-const PAIRING_NONCE_BYTES = 32
-const PAIRING_IV_BYTES = 12
-const PAIRING_KEY_BITS = 256
-
-const textEncoder = new TextEncoder()
-const textDecoder = new TextDecoder()
-
-type WebCryptoKey = Awaited>
-
-export type OpenCodePairingCredentials = {
- username: string
- password: string
-}
-
-const OpenCodePairingCredentialsSchema = z.object({
- username: z.string().min(1),
- password: z.string(),
-})
-
-export interface OpenCodePairingEncryptedCredentials {
- iv: string
- ciphertext: string
-}
-
-export interface OpenCodePairingKeyOptions {
- code: string
- nonce: string
-}
-
-export interface OpenCodePairingDecryptOptions extends OpenCodePairingKeyOptions {
- iv: string
- ciphertext: string
-}
-
-export function createOpenCodePairingNonce(): string {
- return base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(PAIRING_NONCE_BYTES)))
-}
-
-export function isOpenCodePairingNonce(value: string): boolean {
- const nonce = z.string().safeParse(value)
- if (!nonce.success) return false
- const bytes = base64UrlDecode(nonce.data)
- return bytes !== null && bytes.length === PAIRING_NONCE_BYTES
-}
-
-export function isOpenCodePairingCredentials(value: JsonValue | undefined): value is OpenCodePairingCredentials {
- return OpenCodePairingCredentialsSchema.safeParse(value).success
-}
-
-export async function createOpenCodePairingProof(code: string, nonce: string): Promise {
- const key = await importHmacKey(code)
- const signature = await globalThis.crypto.subtle.sign('HMAC', key, pairingProofMessage(nonce))
- return base64UrlEncode(new Uint8Array(signature))
-}
-
-export async function verifyOpenCodePairingProof(code: string, nonce: string, proof: string): Promise {
- const signature = base64UrlDecode(proof)
- if (signature === null) return false
- const key = await importHmacKey(code)
- try {
- return await globalThis.crypto.subtle.verify('HMAC', key, signature, pairingProofMessage(nonce))
- } catch {
- return false
- }
-}
-
-export async function encryptOpenCodePairingCredentials(
- options: OpenCodePairingKeyOptions & { credentials: OpenCodePairingCredentials },
-): Promise {
- const key = await deriveCredentialsKey(options.code, options.nonce)
- const iv = globalThis.crypto.getRandomValues(new Uint8Array(PAIRING_IV_BYTES))
- const plaintext = encodeText(JSON.stringify({
- username: options.credentials.username,
- password: options.credentials.password,
- }))
- const ciphertext = await globalThis.crypto.subtle.encrypt(
- { name: 'AES-GCM', iv, additionalData: pairingAdditionalData() },
- key,
- plaintext,
- )
- return {
- iv: base64UrlEncode(iv),
- ciphertext: base64UrlEncode(new Uint8Array(ciphertext)),
- }
-}
-
-export async function decryptOpenCodePairingCredentials(
- options: OpenCodePairingDecryptOptions,
-): Promise {
- const iv = base64UrlDecode(options.iv)
- const ciphertext = base64UrlDecode(options.ciphertext)
- if (iv === null || iv.length !== PAIRING_IV_BYTES || ciphertext === null) {
- throw new Error('Invalid pairing payload')
- }
- const key = await deriveCredentialsKey(options.code, options.nonce)
- const plaintext = await globalThis.crypto.subtle.decrypt(
- { name: 'AES-GCM', iv, additionalData: pairingAdditionalData() },
- key,
- ciphertext,
- )
- const parsed = JsonValueSchema.safeParse(JSON.parse(textDecoder.decode(plaintext)))
- if (!parsed.success || !isOpenCodePairingCredentials(parsed.data)) throw new Error('Invalid pairing payload')
- return parsed.data
-}
-
-function encodeText(value: string): Uint8Array {
- return new Uint8Array(textEncoder.encode(value))
-}
-
-function pairingProofMessage(nonce: string): Uint8Array {
- return encodeText(`${PAIRING_PROOF_PREFIX}${nonce}`)
-}
-
-function pairingAdditionalData(): Uint8Array {
- return encodeText(PAIRING_PROTOCOL)
-}
-
-async function importHmacKey(code: string): Promise {
- return globalThis.crypto.subtle.importKey(
- 'raw',
- encodeText(code),
- { name: 'HMAC', hash: 'SHA-256' },
- false,
- ['sign', 'verify'],
- )
-}
-
-async function deriveCredentialsKey(code: string, nonce: string): Promise {
- const keyMaterial = await globalThis.crypto.subtle.importKey('raw', encodeText(code), 'HKDF', false, ['deriveKey'])
- return globalThis.crypto.subtle.deriveKey(
- {
- name: 'HKDF',
- hash: 'SHA-256',
- salt: encodeText(nonce),
- info: encodeText(PAIRING_KEY_INFO),
- },
- keyMaterial,
- { name: 'AES-GCM', length: PAIRING_KEY_BITS },
- false,
- ['encrypt', 'decrypt'],
- )
-}
-
-function base64UrlEncode(bytes: Uint8Array): string {
- let binary = ''
- for (const byte of bytes) binary += String.fromCharCode(byte)
- return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
-}
-
-function base64UrlDecode(value: string): Uint8Array | null {
- if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) return null
- const base64 = value.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')
- const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4)
- try {
- const binary = atob(padded)
- const bytes = new Uint8Array(binary.length)
- for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)
- return bytes
- } catch {
- return null
- }
-}
diff --git a/shared/src/schemas/opencode-servers.ts b/shared/src/schemas/opencode-servers.ts
index 46724ccd1..ee9cc26b3 100644
--- a/shared/src/schemas/opencode-servers.ts
+++ b/shared/src/schemas/opencode-servers.ts
@@ -27,9 +27,8 @@ export const OpenCodeServerSchema = z.object({
updatedAt: z.number(),
});
-export const OpenCodeServerPairingSchema = z.object({
- pairUrl: HttpUrlSchema,
- code: z.string().min(16).max(256),
+export const OpenCodeConnectPairingSchema = z.object({
+ connectCode: z.string().regex(/^[A-Za-z0-9_-]+$/).min(1).max(256),
});
export const CreateOpenCodeServerRequestSchema = z
@@ -38,7 +37,7 @@ export const CreateOpenCodeServerRequestSchema = z
baseUrl: HttpUrlSchema,
username: z.string().trim().min(1).max(100).default(OPENCODE_SERVER_USERNAME),
password: z.string().min(1).max(1024).optional(),
- pairing: OpenCodeServerPairingSchema.optional(),
+ pairing: OpenCodeConnectPairingSchema.optional(),
enabled: z.boolean().default(true),
})
.refine((value) => !(value.password && value.pairing), "Provide either a password or a pairing code, not both");
@@ -49,7 +48,7 @@ export const UpdateOpenCodeServerRequestSchema = z
baseUrl: HttpUrlSchema.optional(),
username: z.string().trim().min(1).max(100).optional(),
password: z.string().min(1).max(1024).nullable().optional(),
- pairing: OpenCodeServerPairingSchema.optional(),
+ pairing: OpenCodeConnectPairingSchema.optional(),
enabled: z.boolean().optional(),
})
.refine((value) => !(value.password && value.pairing), "Provide either a password or a pairing code, not both");
@@ -75,13 +74,6 @@ export const OpenCodeServerStatusSchema = z.object({
error: z.string().nullable(),
});
-export const OpenCodeServerLinkSchema = z.object({
- kind: z.literal("opencode"),
- name: z.string().trim().min(1).max(100),
- baseUrl: HttpUrlSchema,
- pairing: OpenCodeServerPairingSchema,
-});
-
export const ManagerAppLinkSchema = z.object({
kind: z.literal("manager"),
name: z.string().trim().min(1).max(100),
@@ -91,26 +83,91 @@ export const ManagerAppLinkSchema = z.object({
});
export type OpenCodeServer = z.infer;
-export type OpenCodeServerPairing = z.infer;
+export type OpenCodeConnectPairing = z.infer;
export type CreateOpenCodeServerRequest = z.input;
export type UpdateOpenCodeServerRequest = z.input;
export type TestOpenCodeServerRequest = z.input;
export type OpenCodeServerTestResult = z.infer;
export type OpenCodeServerStatus = z.infer;
-export type OpenCodeServerLink = z.infer;
export type ManagerAppLink = z.infer;
-export function buildOpenCodeServerLink(link: OpenCodeServerLink): string {
- const params = buildLinkParams(link);
- params.set("pair", link.pairing.pairUrl);
- params.set("code", link.pairing.code);
- return buildLinkUrl(params);
+export interface OpenCodeConnectLink {
+ name: string;
+ baseUrl: string;
+ pairing: { connectCode: string };
}
-export function parseOpenCodeServerLink(text: string): OpenCodeServerLink | null {
- return readLink(OpenCodeServerLinkSchema, text, (url) => ({
- pairing: { pairUrl: url.searchParams.get("pair"), code: url.searchParams.get("code") },
- }));
+const CONNECT_CODE_PATTERN = /^[A-Za-z0-9_-]{1,256}$/;
+const CONNECT_LINK_PATH_PATTERN = /^\/auth\/connect\/([A-Za-z0-9_-]{1,256})$/;
+
+function readConnectOrigin(value: string): string | null {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
+ if (url.username || url.password || url.search || url.hash) return null;
+ if (url.pathname !== "/") return null;
+ return url.origin;
+}
+
+const ConnectOriginSchema = z.string().transform((value, ctx) => {
+ const origin = readConnectOrigin(value);
+ if (origin === null) {
+ ctx.addIssue({ code: "custom", message: "URL must be an http(s) origin" });
+ return z.NEVER;
+ }
+ return origin;
+});
+
+const ConnectPayloadSchema = z.object({
+ code: z.string().regex(CONNECT_CODE_PATTERN),
+ urls: z.array(ConnectOriginSchema).min(1),
+ name: z.string().optional(),
+});
+
+function parseConnectPayload(text: string): OpenCodeConnectLink | null {
+ let payload: unknown;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ return null;
+ }
+
+ const parsed = ConnectPayloadSchema.safeParse(payload);
+ if (!parsed.success) return null;
+
+ const baseUrl = parsed.data.urls[0];
+ if (baseUrl === undefined) return null;
+
+ const name = parsed.data.name?.trim();
+ return {
+ name: name !== undefined && name.length > 0 ? name : new URL(baseUrl).hostname,
+ baseUrl,
+ pairing: { connectCode: parsed.data.code },
+ };
+}
+
+function parseConnectUrl(text: string): OpenCodeConnectLink | null {
+ let url: URL;
+ try {
+ url = new URL(text);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
+ if (url.username || url.password || url.search || url.hash) return null;
+ const connectCode = CONNECT_LINK_PATH_PATTERN.exec(url.pathname)?.[1];
+ if (!connectCode) return null;
+ return { name: url.hostname, baseUrl: url.origin, pairing: { connectCode } };
+}
+
+export function parseOpenCodeConnectLink(text: string): OpenCodeConnectLink | null {
+ const trimmed = text.trim();
+ if (trimmed.startsWith("{")) return parseConnectPayload(trimmed);
+ return parseConnectUrl(trimmed);
}
export function buildManagerAppLink(link: ManagerAppLink): string {
@@ -132,10 +189,6 @@ export function parseManagerAppLink(text: string): ManagerAppLink | null {
});
}
-export function readOpenCodeServerLinkVersion(text: string): string | null {
- return parseOpenCodeServerLinkUrl(text)?.searchParams.get("v") ?? null;
-}
-
function parseOpenCodeServerLinkUrl(text: string): URL | null {
let url: URL;
try {
From 12dab07b875336d21045e5eab4294e98dd1a5464 Mon Sep 17 00:00:00 2001
From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
Date: Sat, 28 Nov 2026 20:36:48 -0500
Subject: [PATCH 2/3] Guard pairing token renewal against concurrent edits and
cap pairing names
---
.../services/opencode-server-registry.test.ts | 38 +++++++++++++++++++
.../src/services/opencode-server-registry.ts | 15 +++++++-
backend/test/shared/manager-app-link.test.ts | 10 +++++
shared/src/schemas/opencode-servers.ts | 5 ++-
4 files changed, 65 insertions(+), 3 deletions(-)
diff --git a/backend/src/services/opencode-server-registry.test.ts b/backend/src/services/opencode-server-registry.test.ts
index 147c5f829..0c9a230b1 100644
--- a/backend/src/services/opencode-server-registry.test.ts
+++ b/backend/src/services/opencode-server-registry.test.ts
@@ -599,6 +599,44 @@ describe('OpenCodeServerRegistry', () => {
expect(fetchFn).not.toHaveBeenCalled()
})
+ it('does not overwrite a password changed while the renewal request is in flight', async () => {
+ const originalToken = pairingToken(Date.now() + 3 * DAY_MS)
+ const server = await createServer({
+ name: 'Tunnel',
+ baseUrl: 'https://studio.example.com',
+ password: originalToken,
+ })
+
+ fetchFn.mockImplementation(async (url) => {
+ if (String(url).endsWith('/api/pair')) return jsonResponse({ code: 'renew-code', expires_in: 300 })
+ await registry.update(server.id, { password: 'changed-while-renewing' })
+ return jsonResponse({ token: renewedToken })
+ })
+
+ await registry.renewExpiringPairingTokens()
+
+ expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('changed-while-renewing')
+ })
+
+ it('warns and does not renew an already-expired pairing token', async () => {
+ const originalToken = pairingToken(Date.now() - DAY_MS)
+ const server = await createServer({
+ name: 'Tunnel',
+ baseUrl: 'https://studio.example.com',
+ password: originalToken,
+ })
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})
+
+ await registry.renewExpiringPairingTokens()
+
+ expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe(originalToken)
+ expect(fetchFn).not.toHaveBeenCalled()
+ expect(warn).toHaveBeenCalledWith(
+ `The pairing token for OpenCode server ${server.id} has expired; pair the server again`,
+ )
+ warn.mockRestore()
+ })
+
it('keeps the current token and does not throw when renewal fails', async () => {
const originalToken = pairingToken(Date.now() + 3 * DAY_MS)
const server = await createServer({
diff --git a/backend/src/services/opencode-server-registry.ts b/backend/src/services/opencode-server-registry.ts
index 8ad400098..3b982beb9 100644
--- a/backend/src/services/opencode-server-registry.ts
+++ b/backend/src/services/opencode-server-registry.ts
@@ -321,9 +321,22 @@ export class OpenCodeServerRegistry {
if (expiry === null) return
const remaining = expiry - Date.now()
- if (remaining <= 0 || remaining > TOKEN_RENEWAL_WINDOW_MS) return
+ if (remaining <= 0) {
+ logger.warn(`The pairing token for OpenCode server ${serverId} has expired; pair the server again`)
+ return
+ }
+ if (remaining > TOKEN_RENEWAL_WINDOW_MS) return
const renewed = await this.pairWithToken(server.baseUrl, token)
+ const current = this.get(serverId)
+ if (
+ current === null ||
+ current.baseUrl !== server.baseUrl ||
+ readOpenCodeServerPassword(this.db, serverId) !== token
+ ) {
+ return
+ }
+
updateOpenCodeServer(this.db, serverId, { password: renewed })
this.invalidateClient(serverId)
} catch (error) {
diff --git a/backend/test/shared/manager-app-link.test.ts b/backend/test/shared/manager-app-link.test.ts
index 4cbaab70f..1a049cad1 100644
--- a/backend/test/shared/manager-app-link.test.ts
+++ b/backend/test/shared/manager-app-link.test.ts
@@ -130,6 +130,16 @@ describe('parseOpenCodeConnectLink', () => {
})
})
+ it('caps a long QR payload name to the create request maximum', () => {
+ const payload = JSON.stringify({
+ code: 'abc',
+ urls: ['https://abc.def.opentunnel.xyz'],
+ name: 'n'.repeat(150),
+ })
+
+ expect(parseOpenCodeConnectLink(payload)?.name).toBe('n'.repeat(100))
+ })
+
it.each([
['no urls', JSON.stringify({ code: 'abc', urls: [] })],
['a non-string url', JSON.stringify({ code: 'abc', urls: [42] })],
diff --git a/shared/src/schemas/opencode-servers.ts b/shared/src/schemas/opencode-servers.ts
index ee9cc26b3..4c6acda26 100644
--- a/shared/src/schemas/opencode-servers.ts
+++ b/shared/src/schemas/opencode-servers.ts
@@ -166,8 +166,9 @@ function parseConnectUrl(text: string): OpenCodeConnectLink | null {
export function parseOpenCodeConnectLink(text: string): OpenCodeConnectLink | null {
const trimmed = text.trim();
- if (trimmed.startsWith("{")) return parseConnectPayload(trimmed);
- return parseConnectUrl(trimmed);
+ const link = trimmed.startsWith("{") ? parseConnectPayload(trimmed) : parseConnectUrl(trimmed);
+ if (link === null) return null;
+ return { ...link, name: link.name.slice(0, 100) };
}
export function buildManagerAppLink(link: ManagerAppLink): string {
From 6c6011e8aeded2555267edf7a9f42dd574a5121f Mon Sep 17 00:00:00 2001
From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
Date: Sat, 28 Nov 2026 20:37:36 -0500
Subject: [PATCH 3/3] Drop the README note about upgrading older CLIs
---
ocm-cli/README.md | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/ocm-cli/README.md b/ocm-cli/README.md
index c848eb66f..ddc933cfd 100644
--- a/ocm-cli/README.md
+++ b/ocm-cli/README.md
@@ -44,9 +44,8 @@ Manager is too old for ocm goals; the Manager is not too old. Upgrade ocm to
Attachment works with OpenCode Manager >= 0.19.0. The sync worktree targeting of
`ocm push` / `ocm pull` and `/ocm-move` worktree moves need ocm 0.4.0+ and
-OpenCode Manager 1.0.0+; an older CLI is told to upgrade, and an older Manager is
-reported as needing an upgrade (push and pull fall back to the main checkout
-instead).
+OpenCode Manager 1.0.0+; an older Manager is reported as needing an upgrade
+(push and pull fall back to the main checkout instead).
## Install