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

-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 {