diff --git a/backend/src/routes/internal/repo-mirror.ts b/backend/src/routes/internal/repo-mirror.ts index b6cf2da8f..cac218304 100644 --- a/backend/src/routes/internal/repo-mirror.ts +++ b/backend/src/routes/internal/repo-mirror.ts @@ -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 { 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) diff --git a/backend/src/services/opencode-server-registry.test.ts b/backend/src/services/opencode-server-registry.test.ts index 97cd50a2e..9344c9112 100644 --- a/backend/src/services/opencode-server-registry.test.ts +++ b/backend/src/services/opencode-server-registry.test.ts @@ -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 { - 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): Promise { @@ -47,13 +44,6 @@ async function captureServerError(promise: Promise): Promise { 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> = [] - 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,136 @@ 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('does not overwrite a password changed while the renewal request is in flight', async () => { + const originalToken = pairingToken(Date.now() + 3 * DAY_MS) + const server = await createServer({ + name: 'Tunnel', + baseUrl: 'https://studio.example.com', + password: originalToken, + }) + + fetchFn.mockImplementation(async (url) => { + if (String(url).endsWith('/api/pair')) return jsonResponse({ code: 'renew-code', expires_in: 300 }) + await registry.update(server.id, { password: 'changed-while-renewing' }) + return jsonResponse({ token: renewedToken }) + }) + + await registry.renewExpiringPairingTokens() + + expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe('changed-while-renewing') + }) + + it('warns and does not renew an already-expired pairing token', async () => { + const originalToken = pairingToken(Date.now() - DAY_MS) + const server = await createServer({ + name: 'Tunnel', + baseUrl: 'https://studio.example.com', + password: originalToken, + }) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) + + await registry.renewExpiringPairingTokens() + + expect(decryptSecret(readStoredSecret(db, server.id)!.value)).toBe(originalToken) + expect(fetchFn).not.toHaveBeenCalled() + expect(warn).toHaveBeenCalledWith( + `The pairing token for OpenCode server ${server.id} has expired; pair the server again`, + ) + warn.mockRestore() + }) + + it('keeps the current token and does not throw when renewal fails', async () => { + const originalToken = pairingToken(Date.now() + 3 * DAY_MS) + const server = await createServer({ + 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[] = [] diff --git a/backend/src/services/opencode-server-registry.ts b/backend/src/services/opencode-server-registry.ts index db28fb291..3b982beb9 100644 --- a/backend/src/services/opencode-server-registry.ts +++ b/backend/src/services/opencode-server-registry.ts @@ -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 ConnectPairingPayloadSchema = z.object({ + token: z.string().min(1), +}) -const PairingEncryptedPayloadSchema = z.object({ - iv: z.string().min(1), - ciphertext: 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 type UpdateServerInput = z.output type TestServerInput = z.output @@ -115,7 +120,7 @@ export class OpenCodeServerRegistry { } async create(request: CreateServerInput): Promise { - 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,23 +296,70 @@ 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 { + 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 { + 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) { + logger.warn(`The pairing token for OpenCode server ${serverId} has expired; pair the server again`) + return + } + if (remaining > TOKEN_RENEWAL_WINDOW_MS) return + + const renewed = await this.pairWithToken(server.baseUrl, token) + const current = this.get(serverId) + if ( + current === null || + current.baseUrl !== server.baseUrl || + readOpenCodeServerPassword(this.db, serverId) !== token + ) { + return + } + + updateOpenCodeServer(this.db, serverId, { password: renewed }) + this.invalidateClient(serverId) + } catch (error) { + logger.warn(`Failed to renew the pairing token for OpenCode server ${serverId}: ${String(error)}`) + } + } + + private async pairWithToken(baseUrl: string, token: string): Promise { 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.status !== 200) { + if (!response.ok) { throw new OpenCodeServerPairingError(`Pairing was rejected with status ${response.status}`) } @@ -316,21 +370,49 @@ export class OpenCodeServerRegistry { throw new OpenCodeServerPairingError('Pairing returned an invalid response') } - const parsed = PairingEncryptedPayloadSchema.safeParse(payload) + 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 { - return await decryptOpenCodePairingCredentials({ - code: pairing.code, - nonce, - iv: parsed.data.iv, - ciphertext: parsed.data.ciphertext, - }) + response = await this.fetchFn( + `${trimUrlTrailingSlashes(baseUrl)}/auth/connect/${encodeURIComponent(connectCode)}`, + { + headers: { Accept: 'application/json' }, + signal: AbortSignal.timeout(PAIRING_TIMEOUT_MS), + }, + ) } catch { - throw new OpenCodeServerPairingError('Pairing returned invalid credentials') + throw new OpenCodeServerPairingError('Could not reach the pairing endpoint') } + + if (response.status !== 200) { + 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 = ConnectPairingPayloadSchema.safeParse(payload) + if (!parsed.success) { + throw new OpenCodeServerPairingError('Pairing returned an invalid response') + } + + return { username: OPENCODE_SERVER_USERNAME, password: parsed.data.token } } private requireServer(serverId: string): OpenCodeServer { diff --git a/backend/src/services/remote-server-events.ts b/backend/src/services/remote-server-events.ts index df5d23aeb..b133bbc52 100644 --- a/backend/src/services/remote-server-events.ts +++ b/backend/src/services/remote-server-events.ts @@ -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 | 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 { const stream = this.streams.get(serverId) if (!stream || stream.versionRequested) return diff --git a/backend/test/routes/internal/repo-mirror.test.ts b/backend/test/routes/internal/repo-mirror.test.ts index f4fc74511..d829e31c0 100644 --- a/backend/test/routes/internal/repo-mirror.test.ts +++ b/backend/test/routes/internal/repo-mirror.test.ts @@ -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 { @@ -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 diff --git a/backend/test/routes/opencode-servers.test.ts b/backend/test/routes/opencode-servers.test.ts index a689fb304..d608c860c 100644 --- a/backend/test/routes/opencode-servers.test.ts +++ b/backend/test/routes/opencode-servers.test.ts @@ -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) diff --git a/backend/test/services/remote-server-events.test.ts b/backend/test/services/remote-server-events.test.ts index 311210ef3..ee62335e9 100644 --- a/backend/test/services/remote-server-events.test.ts +++ b/backend/test/services/remote-server-events.test.ts @@ -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 diff --git a/backend/test/shared/manager-app-link.test.ts b/backend/test/shared/manager-app-link.test.ts index 5adbb3893..1a049cad1 100644 --- a/backend/test/shared/manager-app-link.test.ts +++ b/backend/test/shared/manager-app-link.test.ts @@ -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 { 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,88 @@ 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('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('keeps the opencode link round trip unchanged', () => { - expect(parseOpenCodeServerLink(buildOpenCodeServerLink(OPENCODE_LINK))).toEqual(OPENCODE_LINK) + 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('caps a long QR payload name to the create request maximum', () => { + const payload = JSON.stringify({ + code: 'abc', + urls: ['https://abc.def.opentunnel.xyz'], + name: 'n'.repeat(150), + }) + + expect(parseOpenCodeConnectLink(payload)?.name).toBe('n'.repeat(100)) + }) + + it.each([ + ['no urls', JSON.stringify({ code: 'abc', urls: [] })], + ['a non-string url', JSON.stringify({ code: 'abc', urls: [42] })], + ['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() }) }) diff --git a/frontend/src/components/settings/OpenCodeServerDialog.test.tsx b/frontend/src/components/settings/OpenCodeServerDialog.test.tsx index b71071dd6..a420f3347 100644 --- a/frontend/src/components/settings/OpenCodeServerDialog.test.tsx +++ b/frontend/src/components/settings/OpenCodeServerDialog.test.tsx @@ -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() }) diff --git a/frontend/src/components/settings/OpenCodeServerDialog.tsx b/frontend/src/components/settings/OpenCodeServerDialog.tsx index 0f4d26e64..bae1e7025 100644 --- a/frontend/src/components/settings/OpenCodeServerDialog.tsx +++ b/frontend/src/components/settings/OpenCodeServerDialog.tsx @@ -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(null) + const [pairingLink, setPairingLink] = useState>(null) const [linkInput, setLinkInput] = useState('') const [linkError, setLinkError] = useState(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({

Pair from QR code

- Scan the code shown by the server, or paste its pairing link. + Run opencode pair --remote on the server (or opencode pair on the same + network), then scan its QR code or paste the link.