mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
refactor(ocm): pair linked servers with native OpenCode links and drop legacy CLI stubs
This commit is contained in:
1 parent
bf2f81f921
commit
3c7bc80988
20 files changed
+483
-1595
No files matched your search
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user