feat(servers): harden pairing and run linked-server sessions in the UI

Replace the plaintext pairing exchange with a nonce and HMAC proof plus
AES-256-GCM encrypted credentials, bumping links to v2. Track session
ownership per linked server so activity, session picker, transcript, MCP
and skills views work against remote servers. Share encrypted secret
access, event routing and URL helpers across backend, shared and CLI.
This commit is contained in:
Chris Scott committed 2026-10-18 20:27:34 -04:00
1 parent c591c15743
commit f566556fd6
77 files changed
+3170 -702

No files matched your search

+10 -5
View File
@@ -183,11 +183,16 @@ password.
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` carrying the pairing code, answers
it with the credentials, prints `Linked`, and exits. A wrong code returns `401`
and the third failure ends the command; the TTL ends it with
`Pairing code expired`. The pairing listener is plain HTTP, so run it only on a
private network.
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.
## OpenCode TUI plugin
+6 -5
View File
@@ -2,7 +2,8 @@ import { spawn, spawnSync } from 'child_process'
import { hostname } from 'os'
import { basename, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { buildOpenCodeServerLink, OPENCODE_SERVER_DEFAULT_USERNAME } from '@opencode-manager/shared/schemas'
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'
import { setToken, deleteToken, hasStoredToken, describeTokenStore, describeTokenWriteTarget, envToken, TOKEN_ENV, TokenStoreError } from '../src/internal-token-store.js'
@@ -16,7 +17,7 @@ import { resolveTarget, formatRepoIdentities, parseRepoIdPositional, restrictMat
import { buildAttachInvocation } from '../src/warp.js'
import { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/manager-repos.js'
import { OCM_VERSION as VERSION, warmRepoProxy } from '../src/repo-proxy.js'
import { normalizeManagerUrl, resolveManagerAuth } from '../src/manager-auth.js'
import { resolveManagerAuth } from '../src/manager-auth.js'
import type { ManagerAuthOk } from '../src/manager-auth.js'
import { generatePairingCode, probeOpenCodeServer, renderPairingQr, resolveDefaultBaseUrl, startPairingServer } from '../src/link.js'
@@ -171,7 +172,7 @@ function parseLoginArgs(args: string[]): { url: string; token?: string; managerN
export async function cmdLogin(args: string[]): Promise<void> {
const { url, token: providedToken, managerName } = parseLoginArgs(args)
const normalisedUrl = normalizeManagerUrl(url)
const normalisedUrl = trimUrlTrailingSlashes(url)
let token = providedToken
if (!token) {
@@ -201,7 +202,7 @@ export async function cmdLogin(args: string[]): Promise<void> {
}
const existing = readState()
const sameManager = existing ? normalizeManagerUrl(existing.managerUrl) === normalisedUrl : false
const sameManager = existing ? trimUrlTrailingSlashes(existing.managerUrl) === normalisedUrl : false
writeState({
...existing,
managerUrl: normalisedUrl,
@@ -683,7 +684,7 @@ function parseLinkArgs(args: string[]): LinkCommandOptions {
return {
baseUrl,
username: values.username ?? process.env.OPENCODE_SERVER_USERNAME ?? OPENCODE_SERVER_DEFAULT_USERNAME,
username: values.username ?? process.env.OPENCODE_SERVER_USERNAME ?? OPENCODE_SERVER_USERNAME,
password,
name: values.name ?? hostname(),
pairHost: values.pairHost ?? new URL(baseUrl).hostname,
+48 -21
View File
@@ -1,16 +1,22 @@
import { randomBytes, timingSafeEqual } from 'node:crypto'
import { randomBytes } from 'node:crypto'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
import { networkInterfaces, type NetworkInterfaceInfo } from 'node:os'
import { renderUnicodeCompact } from 'uqr'
import {
buildOpenCodeBasicAuth,
encryptOpenCodePairingCredentials,
isOpenCodePairingNonce,
verifyOpenCodePairingProof,
type OpenCodePairingCredentials,
type OpenCodePairingEncryptedCredentials,
} from '@opencode-manager/shared/opencode'
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
const DEFAULT_OPENCODE_PORT = 4096
const REDEEM_PATH = '/redeem'
const MAX_BODY_BYTES = 4096
export interface PairingCredentials {
username: string
password: string
}
export type PairingCredentials = OpenCodePairingCredentials
export type PairingOutcome = 'linked' | 'expired' | 'rejected'
@@ -65,9 +71,9 @@ export async function probeOpenCodeServer(
credentials: PairingCredentials,
timeoutMs = 3000,
): Promise<OpenCodeServerProbe> {
const authorization = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`
const authorization = buildOpenCodeBasicAuth(credentials.password, credentials.username)
try {
const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/api/info`, {
const response = await fetch(`${trimUrlTrailingSlashes(baseUrl)}/api/info`, {
headers: { authorization },
signal: AbortSignal.timeout(timeoutMs),
})
@@ -125,21 +131,43 @@ export async function startPairingServer(options: PairingServerOptions): Promise
return
}
const provided = readPairingCode(await readJsonBody(request))
const challenge = readPairingChallenge(await readJsonBody(request))
if (settled) {
sendJson(response, 404, { error: 'not found' })
return
}
if (provided !== null && codesMatch(provided, code)) {
sendJson(response, 200, { username: credentials.username, password: credentials.password }, () => {
settle('linked')
})
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, 401, { error: 'invalid pairing code' }, failures >= maxAttempts
sendJson(response, status, { error }, failures >= maxAttempts
? () => {
settle('rejected')
}
@@ -180,17 +208,16 @@ export async function startPairingServer(options: PairingServerOptions): Promise
}
}
function codesMatch(provided: string, expected: string): boolean {
const providedBytes = Buffer.from(provided, 'utf8')
const expectedBytes = Buffer.from(expected, 'utf8')
if (providedBytes.length !== expectedBytes.length) return false
return timingSafeEqual(providedBytes, expectedBytes)
interface PairingChallenge {
nonce: string
proof: string
}
function readPairingCode(body: unknown): string | null {
function readPairingChallenge(body: unknown): PairingChallenge | null {
if (typeof body !== 'object' || body === null) return null
const code = (body as { code?: unknown }).code
return typeof code === 'string' ? code : null
const { nonce, proof } = body as { nonce?: unknown; proof?: unknown }
if (!isOpenCodePairingNonce(nonce) || typeof proof !== 'string' || proof.length === 0) return null
return { nonce, proof }
}
function readJsonBody(request: IncomingMessage): Promise<unknown> {
+3 -6
View File
@@ -2,6 +2,7 @@ import { readState } from './state.js'
import { getToken, describeTokenStore } from './internal-token-store.js'
import { TokenStoreError } from './token-store.js'
import { ManagerApi } from './manager-api.js'
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
export type ManagerAuthFailureReason = 'no-manager' | 'token-store' | 'no-token'
@@ -15,15 +16,11 @@ export type ResolveManagerApiResult =
| { ok: true; auth: ManagerAuthOk; api: ManagerApi }
| { ok: false; message: string }
/** Canonical Manager URL form used as the token-store account: trimmed, without trailing slashes. */
export function normalizeManagerUrl(url: string): string {
return url.trim().replace(/\/+$/, '')
}
/** Resolves the Manager URL and token used to authenticate CLI requests. */
export async function resolveManagerAuth(
rawManagerUrl: string | undefined = readState()?.managerUrl,
): Promise<ManagerAuth> {
const managerUrl = rawManagerUrl ? normalizeManagerUrl(rawManagerUrl) : ''
const managerUrl = rawManagerUrl ? trimUrlTrailingSlashes(rawManagerUrl) : ''
if (!managerUrl) {
return {
ok: false,
+2 -2
View File
@@ -1,5 +1,5 @@
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
import type { OcmState } from './state.js'
import { normalizeManagerUrl } from './manager-auth.js'
export const REMOTE_MANAGER_URL_ENV = 'OCM_REMOTE_MANAGER_URL'
export const REMOTE_REPO_NAME_ENV = 'OCM_REMOTE_REPO_NAME'
@@ -43,6 +43,6 @@ export function readRemoteContext(env: NodeJS.ProcessEnv): RemoteContext | undef
/** Returns the saved manager name when it belongs to the attached manager, else the manager host. */
export function remoteDisplayName(remote: RemoteContext, state: OcmState | null): string {
if (state?.managerName && normalizeManagerUrl(state.managerUrl) === normalizeManagerUrl(remote.managerUrl)) return state.managerName
if (state?.managerName && trimUrlTrailingSlashes(state.managerUrl) === trimUrlTrailingSlashes(remote.managerUrl)) return state.managerName
return remote.managerHost
}
+58 -10
View File
@@ -1,4 +1,9 @@
import { describe, it, expect } from 'vitest'
import {
createOpenCodePairingNonce,
createOpenCodePairingProof,
decryptOpenCodePairingCredentials,
} from '@opencode-manager/shared/opencode'
import { generatePairingCode, resolveDefaultBaseUrl, startPairingServer } from '../src/link'
import type { PairingServerOptions } from '../src/link'
import { buildOpenCodeServerLink, parseOpenCodeServerLink } from '@opencode-manager/shared/schemas'
@@ -22,6 +27,11 @@ function redeem(url: string, body: unknown, init: RequestInit = {}): Promise<Res
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) }
}
describe('generatePairingCode', () => {
it('returns 32 random bytes as base64url', () => {
const first = generatePairingCode()
@@ -47,36 +57,58 @@ describe('resolveDefaultBaseUrl', () => {
})
describe('startPairingServer', () => {
it('redeems a valid code, returns credentials, and resolves linked', async () => {
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, { code: CODE })
const response = await redeem(pairing.url, challenge)
const raw = await response.text()
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual(CREDENTIALS)
expect(raw).not.toContain(CREDENTIALS.password)
expect(raw).not.toContain(CODE)
const payload = JSON.parse(raw) as { iv: string; ciphertext: string }
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 code with 401 and rejects after three failures', async () => {
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, { code: `${CODE}-wrong` })
const response = await redeem(pairing.url, await createChallenge(`${CODE}-wrong`))
expect(response.status).toBe(401)
await expect(response.json()).resolves.toEqual({ error: 'invalid pairing code' })
await expect(response.json()).resolves.toEqual({ error: 'invalid pairing proof' })
}
await expect(pairing.done).resolves.toBe('rejected')
await pairing.close()
})
it('treats a missing code as a failed attempt', async () => {
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, { notCode: CODE })
const response = await redeem(pairing.url, { nonce: 'not-a-nonce', proof: 'not-a-proof' })
expect(response.status).toBe(401)
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()
})
@@ -85,7 +117,7 @@ describe('startPairingServer', () => {
const pairing = await startPairing({ ttlMs: 50 })
await expect(pairing.done).resolves.toBe('expired')
await expect(redeem(pairing.url, { code: CODE })).rejects.toThrow()
await expect(redeem(pairing.url, await createChallenge())).rejects.toThrow()
await pairing.close()
})
@@ -112,6 +144,7 @@ describe('startPairingServer', () => {
pairing: { pairUrl: pairing.url, code: CODE },
})
expect(link).toContain('v=2')
expect(parseOpenCodeServerLink(link)).toEqual({
kind: 'opencode',
name: 'build-host',
@@ -121,4 +154,19 @@ describe('startPairingServer', () => {
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 = await redeem(pairing.url, challenge).then((response) => response.json()) as { iv: string; ciphertext: string }
await expect(decryptOpenCodePairingCredentials({
code: `${CODE}-other`,
nonce: challenge.nonce,
iv: payload.iv,
ciphertext: payload.ciphertext,
})).rejects.toThrow()
await pairing.close()
})
})