refactor(ocm): pair linked servers with native OpenCode links and drop legacy CLI stubs

This commit is contained in:
Chris Scott committed 2026-11-28 20:18:05 -05:00
1 parent bf2f81f921
commit 3c7bc80988
20 files changed
+483 -1595

No files matched your search

@@ -106,9 +106,6 @@ const PatchBodySchema = z.object({
directory: z.string().optional(),
})
const LEGACY_UPGRADE_MESSAGE = 'this ocm CLI is too old for this server; upgrade to ocm-cli >= 0.1.2 (the mirror upload protocol changed to chunked uploads)'
const LEGACY_MOVE_UPGRADE_MESSAGE = 'this ocm CLI is too old for this server; upgrade to ocm-cli >= 0.4.0 (/ocm-move now moves sessions into OpenCode worktrees)'
function gitRaw(repoPath: string, args: string[], env: NodeJS.ProcessEnv = process.env, input?: string): Promise<string> {
return new Promise((resolve, reject) => {
const child = spawn('git', args, { cwd: repoPath, env })
@@ -371,10 +368,6 @@ export function createInternalRepoMirrorRoutes(
) {
const app = new Hono()
app.post('/:repoId/mirror', (c) => {
return c.json({ error: 'cli_too_old', message: LEGACY_UPGRADE_MESSAGE }, 410)
})
app.post('/:repoId/mirror/begin', async (c) => {
const repoIdRaw = c.req.param('repoId')
const parsedBody = await parseJsonBody(c, BeginBodySchema, { invalidMessage: 'invalid json body' })
@@ -611,14 +604,6 @@ export function createInternalRepoMirrorRoutes(
}
})
app.get('/:repoId/mirror/target', (c) => {
return c.json({ error: 'cli_too_old', message: LEGACY_MOVE_UPGRADE_MESSAGE }, 410)
})
app.post('/:repoId/mirror/target', (c) => {
return c.json({ error: 'cli_too_old', message: LEGACY_MOVE_UPGRADE_MESSAGE }, 410)
})
app.get('/:repoId/mirror/checkouts', async (c) => {
const repoId = Number(c.req.param('repoId'))
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
@@ -1,11 +1,11 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Database } from 'bun:sqlite'
import { z } from 'zod'
import type { OpenCodeServer } from '@opencode-manager/shared/schemas'
import { encryptOpenCodePairingCredentials, verifyOpenCodePairingProof } from '@opencode-manager/shared/opencode'
import type { JsonValue } from '@opencode-manager/shared/utils'
import { selectRow } from '../db/rows'
import { decryptSecret } from '../utils/crypto'
import { logger } from '../utils/logger'
import {
OpenCodeServerCredentialsRequiredError,
OpenCodeServerError,
@@ -19,10 +19,7 @@ import { createTestDatabase } from '../../test/helpers/test-database'
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
import { createFetchStub, type FetchStub } from '../../test/helpers/fetch-stub'
const PAIR_URL = 'https://remote.example.com/pair'
const PAIR_CODE = '0123456789abcdef'
const PairingRequestSchema = z.object({ nonce: z.string(), proof: z.string() })
const DAY_MS = 24 * 60 * 60 * 1000
const SecretValueRowSchema = z.object({ value: z.string() })
function jsonResponse(body: JsonValue, status = 200): Response {
@@ -33,8 +30,8 @@ function readStoredSecret(db: Database, serverId: string): { value: string } | n
return selectRow(db, SecretValueRowSchema, 'SELECT value FROM app_secrets WHERE key = ?', `opencode_server:${serverId}:password`)
}
function readPairingRequest(init: RequestInit | undefined): z.infer<typeof PairingRequestSchema> {
return PairingRequestSchema.parse(JSON.parse(String(init?.body)))
function pairingToken(expiresAtMs: number): string {
return `${Math.floor(expiresAtMs / 1000)}.${'a'.repeat(43)}`
}
async function captureServerError(promise: Promise<unknown>): Promise<OpenCodeServerError> {
@@ -47,13 +44,6 @@ async function captureServerError(promise: Promise<unknown>): Promise<OpenCodeSe
throw new Error('Expected the promise to reject with an OpenCodeServerError')
}
function flipLastByte(value: string): string {
const bytes = Buffer.from(value.replace(/-/g, '+').replace(/_/g, '/'), 'base64')
const last = bytes.length - 1
bytes[last] = (bytes[last] ?? 0) ^ 0x01
return bytes.toString('base64url')
}
describe('OpenCodeServerRegistry', () => {
let db: Database
let localClient: OpenCodeClient
@@ -107,53 +97,33 @@ describe('OpenCodeServerRegistry', () => {
expect(readStoredSecret(db, server.id)).toBeNull()
})
it('redeems a pairing code and stores the returned credentials', async () => {
const requests: Array<z.infer<typeof PairingRequestSchema>> = []
fetchFn.mockImplementationOnce(async (_url, init) => {
const body = readPairingRequest(init)
requests.push(body)
return jsonResponse({ ...await encryptOpenCodePairingCredentials({
code: PAIR_CODE,
nonce: body.nonce,
credentials: { username: 'alice', password: 'paired-pass' },
}) })
})
it('redeems a native pairing link and stores the session token', async () => {
fetchFn.mockResolvedValueOnce(jsonResponse({ token: 'session-token' }))
const server = await createServer({
name: 'Paired',
baseUrl: 'https://remote.example.com',
name: 'Tunnel',
baseUrl: 'https://abc.def.opentunnel.xyz/',
username: 'ignored',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
pairing: { connectCode: 'AbC_12-x' },
})
expect(server.username).toBe('alice')
expect(server.username).toBe('opencode')
expect(server.hasPassword).toBe(true)
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('paired-pass')
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('session-token')
const [url, init] = fetchFn.mock.calls[0]!
expect(url).toBe(PAIR_URL)
expect(init?.method).toBe('POST')
expect(requests).toHaveLength(1)
expect(Object.keys(requests[0]!).sort()).toEqual(['nonce', 'proof'])
expect(String(init?.body)).not.toContain(PAIR_CODE)
await expect(verifyOpenCodePairingProof(PAIR_CODE, requests[0]!.nonce, requests[0]!.proof)).resolves.toBe(true)
expect(url).toBe('https://abc.def.opentunnel.xyz/auth/connect/AbC_12-x')
expect(init?.method).toBeUndefined()
expect(new Headers(init?.headers).get('accept')).toBe('application/json')
})
it('rejects a tampered encrypted payload', async () => {
fetchFn.mockImplementationOnce(async (_url, init) => {
const { nonce } = readPairingRequest(init)
const encrypted = await encryptOpenCodePairingCredentials({
code: PAIR_CODE,
nonce,
credentials: { username: 'alice', password: 'paired-pass' },
})
return jsonResponse({ ...encrypted, ciphertext: flipLastByte(encrypted.ciphertext) })
})
it('fails with a pairing error when the native pairing endpoint rejects the code', async () => {
fetchFn.mockResolvedValueOnce(new Response(null, { status: 401 }))
const error = await captureServerError(createServer({
name: 'Paired',
baseUrl: 'https://remote.example.com',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
name: 'Tunnel',
baseUrl: 'https://abc.def.opentunnel.xyz',
pairing: { connectCode: 'AbC_12-x' },
}))
expect(error).toBeInstanceOf(OpenCodeServerPairingError)
@@ -161,65 +131,30 @@ describe('OpenCodeServerRegistry', () => {
expect(registry.list()).toEqual([])
})
it('rejects a response without an encrypted payload', async () => {
fetchFn.mockResolvedValueOnce(jsonResponse({ username: 'alice', password: 'paired-pass' }))
it('fails with a pairing error when the native pairing response has no token', async () => {
fetchFn.mockResolvedValueOnce(jsonResponse({ token: '' }))
const error = await captureServerError(createServer({
name: 'Paired',
baseUrl: 'https://remote.example.com',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
name: 'Tunnel',
baseUrl: 'https://abc.def.opentunnel.xyz',
pairing: { connectCode: 'AbC_12-x' },
}))
expect(error).toBeInstanceOf(OpenCodeServerPairingError)
expect(registry.list()).toEqual([])
})
it('rejects decrypted credentials with an empty username', async () => {
fetchFn.mockImplementationOnce(async (_url, init) => {
const { nonce } = readPairingRequest(init)
return jsonResponse({ ...await encryptOpenCodePairingCredentials({
code: PAIR_CODE,
nonce,
credentials: { username: '', password: 'paired-pass' },
}) })
})
const error = await captureServerError(createServer({
name: 'Paired',
baseUrl: 'https://remote.example.com',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
}))
expect(error).toBeInstanceOf(OpenCodeServerPairingError)
expect(registry.list()).toEqual([])
})
it('fails with a pairing error when the pairing endpoint rejects the code', async () => {
fetchFn.mockResolvedValueOnce(new Response(null, { status: 403 }))
await expect(
createServer({
name: 'Paired',
baseUrl: 'https://remote.example.com',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
}),
).rejects.toMatchObject({ status: 502 })
expect(registry.list()).toEqual([])
expect(fetchFn).toHaveBeenCalledTimes(1)
})
it('fails with a pairing error when the pairing endpoint is unreachable', async () => {
it('fails with a pairing error when the native pairing endpoint is unreachable', async () => {
fetchFn.mockRejectedValueOnce(new Error('connect ECONNREFUSED'))
const error = await captureServerError(createServer({
name: 'Paired',
baseUrl: 'https://remote.example.com',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
name: 'Tunnel',
baseUrl: 'https://abc.def.opentunnel.xyz',
pairing: { connectCode: 'AbC_12-x' },
}))
expect(error).toBeInstanceOf(OpenCodeServerPairingError)
expect(error.message).not.toContain(PAIR_CODE)
expect(error.message).toBe('Could not reach the pairing endpoint')
})
})
@@ -331,14 +266,7 @@ describe('OpenCodeServerRegistry', () => {
})
it('allows an origin change with pairing credentials', async () => {
fetchFn.mockImplementationOnce(async (_url, init) => {
const { nonce } = readPairingRequest(init)
return jsonResponse({ ...await encryptOpenCodePairingCredentials({
code: PAIR_CODE,
nonce,
credentials: { username: 'alice', password: 'paired-pass' },
}) })
})
fetchFn.mockResolvedValueOnce(jsonResponse({ token: 'paired-pass' }))
const server = await createServer({
name: 'Studio',
baseUrl: 'https://studio.example.com',
@@ -347,12 +275,28 @@ describe('OpenCodeServerRegistry', () => {
const updated = await registry.update(server.id, {
baseUrl: 'https://other-host.example.com',
pairing: { pairUrl: PAIR_URL, code: PAIR_CODE },
pairing: { connectCode: 'AbC_12-x' },
})
expect(updated.baseUrl).toBe('https://other-host.example.com')
expect(updated.username).toBe('alice')
expect(updated.username).toBe('opencode')
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('paired-pass')
expect(fetchFn.mock.calls[0]?.[0]).toBe('https://other-host.example.com/auth/connect/AbC_12-x')
})
it('redeems a native pairing link against the stored base URL', async () => {
fetchFn.mockResolvedValueOnce(jsonResponse({ token: 'session-token' }))
const server = await createServer({
name: 'Studio',
baseUrl: 'https://studio.example.com',
password: 'super-secret',
})
const updated = await registry.update(server.id, { pairing: { connectCode: 'abc' } })
expect(updated.username).toBe('opencode')
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('session-token')
expect(fetchFn.mock.calls[0]?.[0]).toBe('https://studio.example.com/auth/connect/abc')
})
})
@@ -582,6 +526,98 @@ describe('OpenCodeServerRegistry', () => {
})
})
describe('renewExpiringPairingTokens', () => {
const renewedToken = pairingToken(Date.now() + 30 * DAY_MS)
it('renews a pairing token that expires within seven days', async () => {
const originalToken = pairingToken(Date.now() + 3 * DAY_MS)
const server = await createServer({
name: 'Tunnel',
baseUrl: 'https://studio.example.com',
password: originalToken,
})
const requests: Array<{ url: string; init: RequestInit | undefined }> = []
fetchFn.mockImplementation(async (url, init) => {
requests.push({ url: String(url), init })
if (String(url).endsWith('/api/pair')) return jsonResponse({ code: 'renew-code', expires_in: 300 })
return jsonResponse({ token: renewedToken })
})
await registry.renewExpiringPairingTokens()
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe(renewedToken)
expect(requests.map((request) => request.url)).toEqual([
'https://studio.example.com/api/pair',
'https://studio.example.com/auth/connect/renew-code',
])
expect(requests[0]!.init?.method).toBe('POST')
expect(new Headers(requests[0]!.init?.headers).get('authorization')).toBe(
`Basic ${btoa(`opencode:${originalToken}`)}`,
)
})
it('leaves a token that expires beyond the renewal window unchanged', async () => {
const originalToken = pairingToken(Date.now() + 20 * DAY_MS)
const server = await createServer({
name: 'Tunnel',
baseUrl: 'https://studio.example.com',
password: originalToken,
})
await registry.renewExpiringPairingTokens()
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe(originalToken)
expect(fetchFn).not.toHaveBeenCalled()
})
it('never renews a plain password', async () => {
const server = await createServer({
name: 'Studio',
baseUrl: 'https://studio.example.com',
password: 'super-secret',
})
await registry.renewExpiringPairingTokens()
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('super-secret')
expect(fetchFn).not.toHaveBeenCalled()
})
it('skips disabled servers', async () => {
const originalToken = pairingToken(Date.now() + 3 * DAY_MS)
const server = await createServer({
name: 'Tunnel',
baseUrl: 'https://studio.example.com',
password: originalToken,
})
await registry.update(server.id, { enabled: false })
await registry.renewExpiringPairingTokens()
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe(originalToken)
expect(fetchFn).not.toHaveBeenCalled()
})
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({
name: 'Tunnel',
baseUrl: 'https://studio.example.com',
password: originalToken,
})
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})
fetchFn.mockResolvedValue(new Response(null, { status: 500 }))
await expect(registry.renewExpiringPairingTokens()).resolves.toBeUndefined()
expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe(originalToken)
expect(fetchFn.mock.calls.map((call) => call[0])).toEqual(['https://studio.example.com/api/pair'])
expect(warn).toHaveBeenCalled()
warn.mockRestore()
})
})
describe('onChange', () => {
it('emits upserted and deleted changes and unsubscribes', async () => {
const changes: OpenCodeServerChange[] = []
@@ -3,19 +3,13 @@ import { z } from 'zod'
import {
CreateOpenCodeServerRequestSchema,
LOCAL_OPENCODE_SERVER_ID,
OPENCODE_SERVER_USERNAME,
TestOpenCodeServerRequestSchema,
UpdateOpenCodeServerRequestSchema,
type OpenCodeServer,
type OpenCodeServerPairing,
type OpenCodeServerTestResult,
} from '@opencode-manager/shared/schemas'
import {
buildOpenCodeBasicAuth,
createOpenCodePairingNonce,
createOpenCodePairingProof,
decryptOpenCodePairingCredentials,
isSupportedOpenCodeVersion,
} from '@opencode-manager/shared/opencode'
import { buildOpenCodeBasicAuth, isSupportedOpenCodeVersion } from '@opencode-manager/shared/opencode'
import { haveSameUrlOrigin, trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
import {
deleteOpenCodeServer,
@@ -31,12 +25,23 @@ import { FetchOpenCodeClient, type OpenCodeClient } from './opencode/client'
const PAIRING_TIMEOUT_MS = 10_000
const TEST_TIMEOUT_MS = 5_000
const TOKEN_RENEWAL_WINDOW_MS = 7 * 24 * 60 * 60 * 1000
const PAIRING_TOKEN_PATTERN = /^(\d+)\.([A-Za-z0-9_-]+)$/
const PairingEncryptedPayloadSchema = z.object({
iv: z.string().min(1),
ciphertext: z.string().min(1),
const ConnectPairingPayloadSchema = z.object({
token: z.string().min(1),
})
const PairCodePayloadSchema = z.object({
code: z.string().min(1).max(256),
})
function pairingTokenExpiryMs(token: string): number | null {
const match = PAIRING_TOKEN_PATTERN.exec(token)
if (!match) return null
return Number(match[1]) * 1000
}
type CreateServerInput = z.output<typeof CreateOpenCodeServerRequestSchema>
type UpdateServerInput = z.output<typeof UpdateOpenCodeServerRequestSchema>
type TestServerInput = z.output<typeof TestOpenCodeServerRequestSchema>
@@ -115,7 +120,7 @@ export class OpenCodeServerRegistry {
}
async create(request: CreateServerInput): Promise<OpenCodeServer> {
const pairing = request.pairing ? await this.redeemPairing(request.pairing) : null
const pairing = request.pairing ? await this.redeemPairing(request.pairing.connectCode, request.baseUrl) : null
const server = insertOpenCodeServer(this.db, {
name: request.name,
@@ -135,7 +140,9 @@ export class OpenCodeServerRegistry {
throw new OpenCodeServerCredentialsRequiredError()
}
const pairing = request.pairing ? await this.redeemPairing(request.pairing) : null
const pairing = request.pairing
? await this.redeemPairing(request.pairing.connectCode, request.baseUrl ?? existing.baseUrl)
: null
const server = updateOpenCodeServer(this.db, serverId, {
name: request.name,
@@ -289,22 +296,93 @@ export class OpenCodeServerRegistry {
}
}
private async redeemPairing(pairing: OpenCodeServerPairing): Promise<{ username: string; password: string }> {
const nonce = createOpenCodePairingNonce()
const proof = await createOpenCodePairingProof(pairing.code, nonce)
async renewExpiringPairingTokens(): Promise<void> {
let servers: OpenCodeServer[]
try {
servers = this.list()
} catch (error) {
logger.warn(`Failed to list OpenCode servers for pairing token renewal: ${String(error)}`)
return
}
for (const server of servers) {
if (server.id === LOCAL_OPENCODE_SERVER_ID || !server.enabled) continue
await this.renewPairingToken(server.id)
}
}
private async renewPairingToken(serverId: string): Promise<void> {
try {
const server = this.requireServer(serverId)
const token = readOpenCodeServerPassword(this.db, serverId)
if (token === null) return
const expiry = pairingTokenExpiryMs(token)
if (expiry === null) return
const remaining = expiry - Date.now()
if (remaining <= 0 || remaining > TOKEN_RENEWAL_WINDOW_MS) return
const renewed = await this.pairWithToken(server.baseUrl, token)
updateOpenCodeServer(this.db, serverId, { password: renewed })
this.invalidateClient(serverId)
} catch (error) {
logger.warn(`Failed to renew the pairing token for OpenCode server ${serverId}: ${String(error)}`)
}
}
private async pairWithToken(baseUrl: string, token: string): Promise<string> {
let response: Response
try {
response = await this.fetchFn(pairing.pairUrl, {
response = await this.fetchFn(`${trimUrlTrailingSlashes(baseUrl)}/api/pair`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nonce, proof }),
headers: {
Accept: 'application/json',
Authorization: buildOpenCodeBasicAuth(token, OPENCODE_SERVER_USERNAME),
},
signal: AbortSignal.timeout(PAIRING_TIMEOUT_MS),
})
} catch {
throw new OpenCodeServerPairingError('Could not reach the pairing endpoint')
}
if (!response.ok) {
throw new OpenCodeServerPairingError(`Pairing was rejected with status ${response.status}`)
}
let payload: unknown
try {
payload = await response.json()
} catch {
throw new OpenCodeServerPairingError('Pairing returned an invalid response')
}
const parsed = PairCodePayloadSchema.safeParse(payload)
if (!parsed.success) {
throw new OpenCodeServerPairingError('Pairing returned an invalid response')
}
const pairing = await this.redeemPairing(parsed.data.code, baseUrl)
return pairing.password
}
private async redeemPairing(
connectCode: string,
baseUrl: string,
): Promise<{ username: string; password: string }> {
let response: Response
try {
response = await this.fetchFn(
`${trimUrlTrailingSlashes(baseUrl)}/auth/connect/${encodeURIComponent(connectCode)}`,
{
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(PAIRING_TIMEOUT_MS),
},
)
} catch {
throw new OpenCodeServerPairingError('Could not reach the pairing endpoint')
}
if (response.status !== 200) {
throw new OpenCodeServerPairingError(`Pairing was rejected with status ${response.status}`)
}
@@ -316,21 +394,12 @@ export class OpenCodeServerRegistry {
throw new OpenCodeServerPairingError('Pairing returned an invalid response')
}
const parsed = PairingEncryptedPayloadSchema.safeParse(payload)
const parsed = ConnectPairingPayloadSchema.safeParse(payload)
if (!parsed.success) {
throw new OpenCodeServerPairingError('Pairing returned an invalid response')
}
try {
return await decryptOpenCodePairingCredentials({
code: pairing.code,
nonce,
iv: parsed.data.iv,
ciphertext: parsed.data.ciphertext,
})
} catch {
throw new OpenCodeServerPairingError('Pairing returned invalid credentials')
}
return { username: OPENCODE_SERVER_USERNAME, password: parsed.data.token }
}
private requireServer(serverId: string): OpenCodeServer {
+17 -1
View File
@@ -22,7 +22,7 @@ export interface RemoteServerEventApi {
export type RemoteServerEventHubRegistry = Pick<
OpenCodeServerRegistry,
'list' | 'get' | 'getConnection' | 'onChange' | 'test'
'list' | 'get' | 'getConnection' | 'onChange' | 'test' | 'renewExpiringPairingTokens'
> & {
getClient(serverId: string): { api: RemoteServerEventApi }
}
@@ -73,6 +73,8 @@ const streamErrorSchema = z.object({
const streamErrorTextSchema = z.string()
const PAIRING_TOKEN_RENEWAL_INTERVAL_MS = 12 * 60 * 60 * 1000
function describeStreamError(cause: unknown): string {
const text = streamErrorTextSchema.safeParse(cause)
if (text.success && text.data) return text.data
@@ -90,6 +92,7 @@ export class RemoteServerEventHub {
private unsubscribeRegistry: (() => void) | null = null
private started = false
private versionProbeSequence = 0
private renewalTimer: ReturnType<typeof setInterval> | null = null
private readonly buildReplayEvent: ReplayEventBuilder = createReplayEventBuilder('ocm_replay_remote_')
constructor(
@@ -105,11 +108,18 @@ export class RemoteServerEventHub {
this.replayPendingActions(clientId, serverId, directory))
this.aggregator.setRemoteSubagentResolver((serverId, sessionId) => this.isSubagentSession(serverId, sessionId))
this.unsubscribeRegistry = this.registry.onChange(change => this.handleRegistryChange(change))
this.renewPairingTokens()
this.renewalTimer = setInterval(() => this.renewPairingTokens(), PAIRING_TOKEN_RENEWAL_INTERVAL_MS)
this.renewalTimer.unref?.()
this.connectAll()
}
shutdown(): void {
this.started = false
if (this.renewalTimer) {
clearInterval(this.renewalTimer)
this.renewalTimer = null
}
if (this.unsubscribeRegistry) {
this.unsubscribeRegistry()
this.unsubscribeRegistry = null
@@ -380,6 +390,12 @@ export class RemoteServerEventHub {
}))
}
private renewPairingTokens(): void {
void this.registry.renewExpiringPairingTokens().catch((error) => {
logger.warn('Failed to renew OpenCode pairing tokens:', error)
})
}
private async refreshVersion(serverId: string): Promise<void> {
const stream = this.streams.get(serverId)
if (!stream || stream.versionRequested) return
@@ -55,7 +55,6 @@ const AppliedPatchResponseSchema = z.object({
applied: z.boolean(),
})
const ErrorResponseSchema = z.object({ error: z.string(), message: z.string().optional() })
const LegacyErrorResponseSchema = z.object({ error: z.string(), message: z.string() })
const UploadDeletedSchema = z.object({ ok: z.boolean() })
function repoAt(fullPath: string, overrides: Partial<Repo> = {}): Repo {
@@ -325,20 +324,6 @@ describe('internal-repo-mirror routes', () => {
})
})
describe('legacy POST /:repoId/mirror', () => {
it('returns 410 with cli_too_old code so old CLIs get a clear error', async () => {
const res = await app.request('/api/internal/repos/1/mirror', {
method: 'POST',
body: Buffer.from('legacy tarball'),
headers: { 'content-type': 'application/x-tar' },
})
expect(res.status).toBe(410)
const json = await readJson(res, LegacyErrorResponseSchema)
expect(json.error).toBe('cli_too_old')
expect(json.message).toMatch(/upgrade to ocm-cli/i)
})
})
describe('GET /:repoId/mirror/head', () => {
it('returns head, branch and dirty state for the manager repo', async () => {
const repoDir = initRepoAt(join(reposPath(), 'head-repo'))
@@ -1333,27 +1318,6 @@ describe('internal-repo-mirror routes', () => {
})
})
describe('legacy mirror target routes', () => {
it('returns 410 for the old GET contract', async () => {
const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature')
expect(res.status).toBe(410)
const json = await readJson(res, LegacyErrorResponseSchema)
expect(json.error).toBe('cli_too_old')
expect(json.message).toMatch(/upgrade to ocm-cli/i)
})
it('returns 410 for the old POST contract', async () => {
const res = await app.request('/api/internal/repos/1/mirror/target', {
method: 'POST',
body: JSON.stringify({ branch: 'feature' }),
headers: { 'content-type': 'application/json' },
})
expect(res.status).toBe(410)
const json = await readJson(res, ErrorResponseSchema)
expect(json.error).toBe('cli_too_old')
})
})
describe('GET /:repoId/mirror/checkouts', () => {
let baseDir: string
+2 -2
View File
@@ -147,14 +147,14 @@ describe('opencode server routes', () => {
it('returns 502 when pairing fails', async () => {
fetchMock.mockImplementation(async (input) => {
expect(String(input)).toBe(`${SERVER_BASE_URL}/pair`)
expect(String(input)).toBe(`${SERVER_BASE_URL}/auth/connect/AbC_12-x`)
return new Response(null, { status: 403 })
})
const response = await createServer({
name: 'Studio',
baseUrl: SERVER_BASE_URL,
pairing: { pairUrl: `${SERVER_BASE_URL}/pair`, code: '0123456789abcdef' },
pairing: { connectCode: 'AbC_12-x' },
})
expect(response.status).toBe(502)
@@ -320,6 +320,7 @@ function createRegistry(servers: OpenCodeServer[], fixture: ApiFixture = {}): Fa
return () => { listeners.delete(listener) }
}),
test: vi.fn(async () => ({ ok: true, version: '2.0.15', versionSupported: true, error: null })),
renewExpiringPairingTokens: vi.fn(async () => {}),
}
return {
@@ -804,6 +805,39 @@ describe('RemoteServerEventHub reconnection', () => {
})
})
describe('RemoteServerEventHub pairing token renewal', () => {
let hub: RemoteServerEventHub
let fake: FakeRegistry
beforeEach(() => {
vi.useFakeTimers()
sseAggregator.shutdown()
sseAggregator.setOpenCodeClient(null)
sseAggregator.setScheduledSessionsResolver(() => [])
fake = createRegistry([SERVER_A])
hub = new RemoteServerEventHub(fake.registry, sseAggregator)
})
afterEach(() => {
hub.shutdown()
sseAggregator.shutdown()
vi.useRealTimers()
})
it('renews pairing tokens on start and every twelve hours until shutdown', async () => {
hub.start()
const renew = vi.mocked(fake.registry.renewExpiringPairingTokens)
expect(renew).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000)
expect(renew).toHaveBeenCalledTimes(2)
hub.shutdown()
await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000)
expect(renew).toHaveBeenCalledTimes(2)
})
})
describe('RemoteServerEventHub failure handling', () => {
let hub: RemoteServerEventHub
let fake: FakeRegistry
+72 -24
View File
@@ -2,9 +2,8 @@ import { describe, expect, it } from 'vitest'
import {
OPENCODE_SERVER_LINK_VERSION,
buildManagerAppLink,
buildOpenCodeServerLink,
parseManagerAppLink,
parseOpenCodeServerLink,
parseOpenCodeConnectLink,
type ManagerAppLink,
} from '@opencode-manager/shared/schemas'
@@ -21,13 +20,6 @@ const MANAGER_LINK: ManagerAppLink = {
],
}
const OPENCODE_LINK = {
kind: 'opencode' as const,
name: 'build-host',
baseUrl: 'http://192.168.1.20:4096',
pairing: { pairUrl: 'http://127.0.0.1:4096/redeem', code: CODE },
}
function managerLink(extra: Record<string, string | string[]>): string {
const params = new URLSearchParams({
v: OPENCODE_SERVER_LINK_VERSION,
@@ -67,15 +59,6 @@ describe('buildManagerAppLink', () => {
})
})
describe('buildOpenCodeServerLink', () => {
it('keeps the exact wire format of an opencode link', () => {
expect(buildOpenCodeServerLink(OPENCODE_LINK)).toBe(
`ocm://link?v=2&kind=opencode&name=build-host&url=http%3A%2F%2F192.168.1.20%3A4096` +
`&pair=http%3A%2F%2F127.0.0.1%3A4096%2Fredeem&code=${CODE}`,
)
})
})
describe('parseManagerAppLink', () => {
it('round-trips a manager link with headers in order', () => {
expect(parseManagerAppLink(buildManagerAppLink(MANAGER_LINK))).toEqual(MANAGER_LINK)
@@ -88,7 +71,6 @@ describe('parseManagerAppLink', () => {
})
it.each([
['an opencode link', buildOpenCodeServerLink(OPENCODE_LINK)],
['a wrong version', managerLink({ v: '3' })],
['a header without a colon', managerLink({ h: 'X-Secret' })],
['a blocked header name', managerLink({ h: 'Cookie:session' })],
@@ -100,12 +82,78 @@ describe('parseManagerAppLink', () => {
})
})
describe('manager and opencode link kinds', () => {
it('does not parse a manager link as an opencode link', () => {
expect(parseOpenCodeServerLink(buildManagerAppLink(MANAGER_LINK))).toBeNull()
describe('parseOpenCodeConnectLink', () => {
it('reads a native link exposed through a tunnel', () => {
expect(parseOpenCodeConnectLink('https://abc.def.opentunnel.xyz/auth/connect/AbC_12-x')).toEqual({
name: 'abc.def.opentunnel.xyz',
baseUrl: 'https://abc.def.opentunnel.xyz',
pairing: { connectCode: 'AbC_12-x' },
})
})
it('keeps the opencode link round trip unchanged', () => {
expect(parseOpenCodeServerLink(buildOpenCodeServerLink(OPENCODE_LINK))).toEqual(OPENCODE_LINK)
it('reads a native LAN link and keeps its port', () => {
expect(parseOpenCodeConnectLink('http://192.168.1.2:49374/auth/connect/abc')).toEqual({
name: '192.168.1.2',
baseUrl: 'http://192.168.1.2:49374',
pairing: { connectCode: 'abc' },
})
})
it('trims surrounding whitespace', () => {
expect(parseOpenCodeConnectLink(' https://abc.def.opentunnel.xyz/auth/connect/abc\n')).toMatchObject({
baseUrl: 'https://abc.def.opentunnel.xyz',
pairing: { connectCode: 'abc' },
})
})
it('reads the QR JSON payload and uses the first URL with its name', () => {
const payload = JSON.stringify({
code: 'AbC_12-x',
urls: ['https://abc.def.opentunnel.xyz', 'http://192.168.1.2:49374'],
name: 'Kitchen',
})
expect(parseOpenCodeConnectLink(payload)).toEqual({
name: 'Kitchen',
baseUrl: 'https://abc.def.opentunnel.xyz',
pairing: { connectCode: 'AbC_12-x' },
})
})
it('falls back to the first URL hostname when the QR payload has no name', () => {
const payload = JSON.stringify({ code: 'abc', urls: ['http://192.168.1.2:49374'] })
expect(parseOpenCodeConnectLink(payload)).toEqual({
name: '192.168.1.2',
baseUrl: 'http://192.168.1.2:49374',
pairing: { connectCode: 'abc' },
})
})
it.each([
['no urls', JSON.stringify({ code: 'abc', urls: [] })],
['a non-string url', JSON.stringify({ code: 'abc', urls: [42] })],
['a url with a path', JSON.stringify({ code: 'abc', urls: ['https://host.example.com/path'] })],
['a url with a query', JSON.stringify({ code: 'abc', urls: ['https://host.example.com?x=1'] })],
['a url with credentials', JSON.stringify({ code: 'abc', urls: ['https://user:pass@host.example.com'] })],
['a non-http url', JSON.stringify({ code: 'abc', urls: ['ftp://host.example.com'] })],
['an invalid code', JSON.stringify({ code: 'a.b', urls: ['https://host.example.com'] })],
['malformed json', '{"code":'],
])('returns null for a QR payload with %s', (_label, text) => {
expect(parseOpenCodeConnectLink(text)).toBeNull()
})
it.each([
['an extra path segment', 'https://abc.def.opentunnel.xyz/auth/connect/abc/extra'],
['an empty code', 'https://abc.def.opentunnel.xyz/auth/connect/'],
['a code with a dot', 'https://abc.def.opentunnel.xyz/auth/connect/a.b'],
['a query string', 'https://abc.def.opentunnel.xyz/auth/connect/abc?x=1'],
['a hash', 'https://abc.def.opentunnel.xyz/auth/connect/abc#frag'],
['user credentials', 'https://user:pass@abc.def.opentunnel.xyz/auth/connect/abc'],
['a non-http scheme', 'ftp://abc.def.opentunnel.xyz/auth/connect/abc'],
['an ocm link', `ocm://link?v=2&kind=manager&name=Home&url=https%3A%2F%2Fm.example.com&code=${CODE}`],
['garbage text', 'not a link'],
])('returns null for %s', (_label, text) => {
expect(parseOpenCodeConnectLink(text)).toBeNull()
})
})
@@ -1,7 +1,7 @@
import { beforeAll, describe, expect, it, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { buildOpenCodeServerLink, OPENCODE_SERVER_LINK_VERSION, type OpenCodeServer, type OpenCodeServerTestResult } from '@opencode-manager/shared/schemas'
import type { OpenCodeServer, OpenCodeServerTestResult } from '@opencode-manager/shared/schemas'
import { OpenCodeServerDialog, type OpenCodeServerFormValues } from './OpenCodeServerDialog'
const testResult: OpenCodeServerTestResult = {
@@ -11,12 +11,7 @@ const testResult: OpenCodeServerTestResult = {
error: null,
}
const pairingLink = buildOpenCodeServerLink({
kind: 'opencode',
name: 'Kitchen',
baseUrl: 'https://kitchen.example.com',
pairing: { pairUrl: 'https://kitchen.example.com/pair', code: 'pairing-code-0123456789' },
})
const nativePairingLink = 'https://abc.def.opentunnel.xyz/auth/connect/AbC_12-x'
const savedServer: OpenCodeServer = {
id: 'srv_1',
@@ -58,26 +53,27 @@ describe('OpenCodeServerDialog', () => {
Element.prototype.scrollIntoView ??= () => {}
})
it('prefills name and URL from a pasted pairing link and sends pairing on save', async () => {
it('accepts a native pairing link and sends its connect code on save', async () => {
const user = userEvent.setup()
const { onSubmit } = renderDialog()
await user.type(screen.getByLabelText('Pairing link'), pairingLink)
await user.type(screen.getByLabelText('Pairing link'), nativePairingLink)
await user.click(screen.getByRole('button', { name: 'Use link' }))
expect(screen.getByText('Pairing with Kitchen')).toBeInTheDocument()
expect(screen.getByLabelText('Name')).toHaveValue('Kitchen')
expect(screen.getByLabelText('URL')).toHaveValue('https://kitchen.example.com')
expect(screen.getByText('Pairing with abc.def.opentunnel.xyz')).toBeInTheDocument()
expect(screen.getByLabelText('Name')).toHaveValue('abc.def.opentunnel.xyz')
expect(screen.getByLabelText('URL')).toHaveValue('https://abc.def.opentunnel.xyz')
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument()
expect(screen.getByText(/sign this Manager in for 30 days/)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Add server' }))
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0]).toMatchObject({
name: 'Kitchen',
baseUrl: 'https://kitchen.example.com',
name: 'abc.def.opentunnel.xyz',
baseUrl: 'https://abc.def.opentunnel.xyz',
password: '',
pairing: { pairUrl: 'https://kitchen.example.com/pair', code: 'pairing-code-0123456789' },
pairing: { connectCode: 'AbC_12-x' },
})
})
@@ -88,20 +84,8 @@ describe('OpenCodeServerDialog', () => {
await user.type(screen.getByLabelText('Pairing link'), 'not-a-pairing-link')
await user.click(screen.getByRole('button', { name: 'Use link' }))
expect(screen.getByRole('alert')).toHaveTextContent('That is not a valid OpenCode pairing link.')
expect(screen.queryByText(/Pairing with/)).not.toBeInTheDocument()
})
it('explains that a pairing link from an unsupported version cannot be used', async () => {
const user = userEvent.setup()
renderDialog()
const outdated = pairingLink.replace(`v=${OPENCODE_SERVER_LINK_VERSION}`, 'v=1')
await user.type(screen.getByLabelText('Pairing link'), outdated)
await user.click(screen.getByRole('button', { name: 'Use link' }))
expect(screen.getByRole('alert')).toHaveTextContent(
`This pairing link uses link version 1, but this Manager expects version ${OPENCODE_SERVER_LINK_VERSION}. Update the Manager or the ocm CLI and generate a new QR code.`,
'That is not a valid OpenCode pairing link. Run `opencode pair --remote` on the server and paste the link it prints.',
)
expect(screen.queryByText(/Pairing with/)).not.toBeInTheDocument()
})
@@ -4,12 +4,10 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { AlertTriangle, CheckCircle2, Loader2, ScanLine, XCircle } from 'lucide-react'
import {
OPENCODE_SERVER_LINK_VERSION,
OPENCODE_SERVER_USERNAME,
parseOpenCodeServerLink,
readOpenCodeServerLinkVersion,
parseOpenCodeConnectLink,
type OpenCodeConnectPairing,
type OpenCodeServer,
type OpenCodeServerLink,
type OpenCodeServerTestResult,
} from '@opencode-manager/shared/schemas'
import { isSameOpenCodeMajor } from '@opencode-manager/shared/opencode'
@@ -47,7 +45,7 @@ export interface OpenCodeServerFormValues {
password: string
enabled: boolean
clearPassword: boolean
pairing: OpenCodeServerLink['pairing'] | null
pairing: OpenCodeConnectPairing | null
}
interface OpenCodeServerDialogProps {
@@ -137,7 +135,7 @@ export function OpenCodeServerDialog({
resolver: zodResolver(serverFormSchema),
defaultValues: buildDefaultValues(server),
})
const [pairingLink, setPairingLink] = useState<OpenCodeServerLink | null>(null)
const [pairingLink, setPairingLink] = useState<ReturnType<typeof parseOpenCodeConnectLink>>(null)
const [linkInput, setLinkInput] = useState('')
const [linkError, setLinkError] = useState<string | null>(null)
const [isScannerOpen, setIsScannerOpen] = useState(false)
@@ -169,12 +167,11 @@ export function OpenCodeServerDialog({
const isSubmitting = form.formState.isSubmitting
const applyPairingLink = (text: string) => {
const link = parseOpenCodeServerLink(text)
const link = parseOpenCodeConnectLink(text)
if (!link) {
const version = readOpenCodeServerLinkVersion(text)
setLinkError(version !== null && version !== OPENCODE_SERVER_LINK_VERSION
? `This pairing link uses link version ${version}, but this Manager expects version ${OPENCODE_SERVER_LINK_VERSION}. Update the Manager or the ocm CLI and generate a new QR code.`
: 'That is not a valid OpenCode pairing link.')
setLinkError(
'That is not a valid OpenCode pairing link. Run `opencode pair --remote` on the server and paste the link it prints.',
)
return
}
setPairingLink(link)
@@ -243,7 +240,8 @@ export function OpenCodeServerDialog({
<div>
<p className="text-sm font-medium">Pair from QR code</p>
<p className="text-xs text-muted-foreground">
Scan the code shown by the server, or paste its pairing link.
Run <code>opencode pair --remote</code> on the server (or <code>opencode pair</code> on the same
network), then scan its QR code or paste the link.
</p>
</div>
<Button type="button" variant="outline" size="sm" onClick={() => setIsScannerOpen(true)}>
@@ -261,7 +259,7 @@ export function OpenCodeServerDialog({
setLinkInput(event.target.value)
setLinkError(null)
}}
placeholder={`ocm://link?v=${OPENCODE_SERVER_LINK_VERSION}&kind=opencode&...`}
placeholder="https://…/auth/connect/…"
rows={2}
className="font-mono"
/>
@@ -289,6 +287,12 @@ export function OpenCodeServerDialog({
{linkError}
</p>
)}
{pairingLink && (
<p className="text-xs text-muted-foreground">
OpenCode pairing links sign this Manager in for 30 days. The Manager renews them automatically
while the server stays reachable.
</p>
)}
</div>
</section>
)}
+6 -54
View File
@@ -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 <repoId|name>
ocm push [repoId] [--force] [--create] [--yes] [--full]
ocm pull [repoId] [--force] [--full]
ocm install [--dir <path>] [--force] [--no-link]
ocm link [--url <url>] [--password <pw>] [--username <name>] [--name <name>]
[--pair-host <host>] [--pair-port <port>] [--ttl <seconds>] [--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 <url>` | `$OPENCODE_SERVER_URL`, else the detected OpenCode service URL, else `http://<first non-internal IPv4>:4096`; an explicit value skips service detection |
| `--password <pw>` | `$OPENCODE_SERVER_PASSWORD`, else the detected OpenCode service password; an explicit URL needs one of the first two |
| `--username <name>` | `$OPENCODE_SERVER_USERNAME`, else `opencode` |
| `--name <name>` | the machine hostname |
| `--pair-host <host>` | the host of `--url` |
| `--pair-port <port>` | `0` (ephemeral) |
| `--ttl <seconds>` | `300` |
| `--no-qr` | off; print only the link |
Before showing the code it calls `GET <url>/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
-171
View File
@@ -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 <path>] [--force] [--no-link]
Vendor the CLI + TUI plugin into the OpenCode config dir
ocm link [--url <url>] [--password <pw>] [--username <name>] [--name <name>]
[--pair-host <host>] [--pair-port <port>] [--ttl <seconds>] [--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<void> {
}
}
const LINK_USAGE = `usage: ocm link [--url <url>] [--password <pw>] [--username <name>] [--name <name>]
[--pair-host <host>] [--pair-port <port>] [--ttl <seconds>] [--no-qr]`
type LinkFlag = 'url' | 'password' | 'username' | 'name' | 'pairHost' | 'pairPort' | 'ttl'
const LINK_FLAGS = new Map<string, LinkFlag>([
['--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<Record<'url' | 'password' | 'username' | 'name' | 'pairHost' | 'pairPort' | 'ttl', string>> = {}
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<void> {
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<void> {
const [, , cmd, ...rest] = process.argv
@@ -815,9 +647,6 @@ async function main(): Promise<void> {
case 'install':
await cmdInstall(rest)
break
case 'link':
await cmdLink(rest)
break
default:
die(`unknown command: ${cmd}. run \`ocm --help\``)
}
-1
View File
@@ -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"
}
-394
View File
@@ -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<PairingOutcome>
close: () => Promise<void>
}
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<NetworkInterfaceInfo[]> = 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<NetworkInterfaceInfo[]> = 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<NetworkInterfaceInfo[]>
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<NetworkInterfaceInfo[]>,
): { 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<OpenCodeServerProbe> {
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<PairingServerHandle> {
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<PairingOutcome>((resolve) => {
resolveDone = resolve
})
let closePromise: Promise<void> | undefined
const closeServer = (): Promise<void> => {
closePromise ??= new Promise<void>((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<void> {
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<void>((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<JsonValue | null> {
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)
}
+3
View File
@@ -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 })
},
}
-506
View File
@@ -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<NetworkInterfaceInfo[]> = {
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<NetworkInterfaceInfo[]> = {
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<NetworkInterfaceInfo[]> = 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<NetworkInterfaceInfo[]> = 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<PairingServerOptions> = {}) {
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<Response> {
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<void>
}
async function startProbeServer(
respond: (request: IncomingMessage, response: ServerResponse) => void,
): Promise<ProbeServer> {
const requests: ProbeServer['requests'] = []
const server = createServer((request, response) => {
requests.push({ url: request.url, authorization: request.headers.authorization })
respond(request, response)
})
await new Promise<void>((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<void>((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()
})
})
-3
View File
@@ -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)
-17
View File
@@ -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,
-168
View File
@@ -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<ReturnType<typeof globalThis.crypto.subtle.importKey>>
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<string> {
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<boolean> {
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<OpenCodePairingEncryptedCredentials> {
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<OpenCodePairingCredentials> {
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<ArrayBuffer> {
return new Uint8Array(textEncoder.encode(value))
}
function pairingProofMessage(nonce: string): Uint8Array<ArrayBuffer> {
return encodeText(`${PAIRING_PROOF_PREFIX}${nonce}`)
}
function pairingAdditionalData(): Uint8Array<ArrayBuffer> {
return encodeText(PAIRING_PROTOCOL)
}
async function importHmacKey(code: string): Promise<WebCryptoKey> {
return globalThis.crypto.subtle.importKey(
'raw',
encodeText(code),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify'],
)
}
async function deriveCredentialsKey(code: string, nonce: string): Promise<WebCryptoKey> {
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<ArrayBuffer> | 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
}
}
+80 -27
View File
@@ -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<typeof OpenCodeServerSchema>;
export type OpenCodeServerPairing = z.infer<typeof OpenCodeServerPairingSchema>;
export type OpenCodeConnectPairing = z.infer<typeof OpenCodeConnectPairingSchema>;
export type CreateOpenCodeServerRequest = z.input<typeof CreateOpenCodeServerRequestSchema>;
export type UpdateOpenCodeServerRequest = z.input<typeof UpdateOpenCodeServerRequestSchema>;
export type TestOpenCodeServerRequest = z.input<typeof TestOpenCodeServerRequestSchema>;
export type OpenCodeServerTestResult = z.infer<typeof OpenCodeServerTestResultSchema>;
export type OpenCodeServerStatus = z.infer<typeof OpenCodeServerStatusSchema>;
export type OpenCodeServerLink = z.infer<typeof OpenCodeServerLinkSchema>;
export type ManagerAppLink = z.infer<typeof ManagerAppLinkSchema>;
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 {