import { sql } from 'drizzle-orm' import { sshKey } from '../db/schema' import { useDb } from './db' import { decrypt } from './encryption' import { pkcs8ToOpenSshPrivate } from './ssh-keypair' /** * Decrypt the install's SSH private key and return it as an in-memory * OpenSSH-format string, ready to hand to the `ssh2` client. * * The push transport runs in-process via `ssh2` (no `ssh` binary, which the * Vercel runtime doesn't provide), so the key never touches disk: it's * decrypted, used for one connection, and dropped when the function returns. */ export async function loadSshKeyForInstall(installationId: number): Promise { const db = useDb() const rows = await db.select({ privateKeyCiphertext: sshKey.privateKeyCiphertext, privateKeyNonce: sshKey.privateKeyNonce, }) .from(sshKey) .where(sql`${sshKey.installationId} = ${installationId}`) .limit(1) if (rows.length === 0) { throw new Error(`no ssh key for installation ${installationId}`) } const row = rows[0]! const pem = decrypt(row.privateKeyCiphertext, row.privateKeyNonce) return pkcs8ToOpenSshPrivate(pem, `synchub.to/${installationId}`) }