mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
section 15: Phase 15: ocm-cli server probe through the client; full repo
This commit is contained in:
1 parent
fbc3e02208
commit
7c4cfd858c
2 files changed
+123
-16
No files matched your search
+24
-14
@@ -5,9 +5,12 @@ import { homedir, networkInterfaces, type NetworkInterfaceInfo } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { renderUnicodeCompact } from 'uqr'
|
||||
import {
|
||||
ClientError,
|
||||
buildOpenCodeBasicAuth,
|
||||
createOpenCodeApi,
|
||||
encryptOpenCodePairingCredentials,
|
||||
isOpenCodePairingNonce,
|
||||
openCodeErrorStatus,
|
||||
verifyOpenCodePairingProof,
|
||||
type OpenCodePairingCredentials,
|
||||
type OpenCodePairingEncryptedCredentials,
|
||||
@@ -178,30 +181,37 @@ export function renderPairingQr(link: string): string {
|
||||
return renderUnicodeCompact(link, { ecc: 'M', border: 2 })
|
||||
}
|
||||
|
||||
/** Probes `<baseUrl>/api/info` with Basic auth to report reachability and credentials validity. */
|
||||
/** Probes the OpenCode server info endpoint with Basic auth to report reachability and credentials validity. */
|
||||
export async function probeOpenCodeServer(
|
||||
baseUrl: string,
|
||||
credentials: PairingCredentials,
|
||||
timeoutMs = 3000,
|
||||
): Promise<OpenCodeServerProbe> {
|
||||
const authorization = buildOpenCodeBasicAuth(credentials.password, credentials.username)
|
||||
const api = createOpenCodeApi({
|
||||
baseUrl: trimUrlTrailingSlashes(baseUrl),
|
||||
headers: { authorization: buildOpenCodeBasicAuth(credentials.password, credentials.username) },
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await fetch(`${trimUrlTrailingSlashes(baseUrl)}/api/info`, {
|
||||
headers: { authorization },
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
})
|
||||
if (response.status === 401) return { status: 'unauthorized' }
|
||||
if (!response.ok) return { status: 'unreachable', message: `HTTP ${response.status}` }
|
||||
const payload: unknown = await response.json().catch(() => null)
|
||||
const version = typeof payload === 'object' && payload !== null && typeof (payload as { version?: unknown }).version === 'string'
|
||||
? (payload as { version: string }).version
|
||||
: null
|
||||
return { status: 'ok', version }
|
||||
const info = await api.server.info({ signal: AbortSignal.timeout(timeoutMs) })
|
||||
return { status: 'ok', version: info.version ?? null }
|
||||
} catch (error) {
|
||||
return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) }
|
||||
if (openCodeErrorStatus(error) === 401) return { status: 'unauthorized' }
|
||||
|
||||
const status = error instanceof ClientError
|
||||
? (error.cause as { status?: number } | undefined)?.status
|
||||
: undefined
|
||||
return {
|
||||
status: 'unreachable',
|
||||
message: status === undefined ? messageOf(error) : `HTTP ${status}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function messageOf(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
/** Serves the one-shot pairing redeem endpoint on `0.0.0.0` and reports how it ended. */
|
||||
export async function startPairingServer(options: PairingServerOptions): Promise<PairingServerHandle> {
|
||||
const { code, credentials, ttlMs, maxAttempts, port = 0, hostname = '0.0.0.0' } = options
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
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, vi } from 'vitest'
|
||||
import {
|
||||
buildOpenCodeBasicAuth,
|
||||
createOpenCodePairingNonce,
|
||||
createOpenCodePairingProof,
|
||||
decryptOpenCodePairingCredentials,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { discoverOpenCodeService, generatePairingCode, resolveDefaultBaseUrl, resolveLanIPv4, startPairingServer } from '../src/link'
|
||||
import {
|
||||
discoverOpenCodeService,
|
||||
generatePairingCode,
|
||||
probeOpenCodeServer,
|
||||
resolveDefaultBaseUrl,
|
||||
resolveLanIPv4,
|
||||
startPairingServer,
|
||||
} from '../src/link'
|
||||
import type { PairingServerOptions } from '../src/link'
|
||||
import { buildOpenCodeServerLink, parseOpenCodeServerLink } from '@opencode-manager/shared/schemas'
|
||||
|
||||
@@ -36,8 +45,11 @@ interface ServiceHome {
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
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 {
|
||||
@@ -109,6 +121,37 @@ async function createChallenge(code = CODE): Promise<{ nonce: string; proof: str
|
||||
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 port = typeof address === 'object' && address !== null ? address.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()
|
||||
@@ -289,6 +332,60 @@ describe('discoverOpenCodeService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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('reports unauthorized when the server rejects the credentials', async () => {
|
||||
const server = await startProbeServer((_request, response) => {
|
||||
response.writeHead(401, { 'content-type': 'application/json' })
|
||||
response.end(JSON.stringify({ _tag: 'UnauthorizedError', message: 'unauthorized' }))
|
||||
})
|
||||
|
||||
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
|
||||
status: 'unauthorized',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports unreachable with the HTTP status for an unexpected response', async () => {
|
||||
const server = await startProbeServer((_request, response) => {
|
||||
response.writeHead(500, { 'content-type': 'application/json' })
|
||||
response.end(JSON.stringify({ error: 'boom' }))
|
||||
})
|
||||
|
||||
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()
|
||||
|
||||
Reference in new issue
Block a user