mirror your GitHub repos to tangled.org automatically
1import { sql } from 'drizzle-orm'
2import { sshKey } from '../db/schema'
3import { useDb } from './db'
4import { decrypt } from './encryption'
5import { pkcs8ToOpenSshPrivate } from './ssh-keypair'
6
7/**
8 * Decrypt the install's SSH private key and return it as an in-memory
9 * OpenSSH-format string, ready to hand to the `ssh2` client.
10 *
11 * The push transport runs in-process via `ssh2` (no `ssh` binary, which the
12 * Vercel runtime doesn't provide), so the key never touches disk: it's
13 * decrypted, used for one connection, and dropped when the function returns.
14 */
15export async function loadSshKeyForInstall(installationId: number): Promise<string> {
16 const db = useDb()
17 const rows = await db.select({
18 privateKeyCiphertext: sshKey.privateKeyCiphertext,
19 privateKeyNonce: sshKey.privateKeyNonce,
20 })
21 .from(sshKey)
22 .where(sql`${sshKey.installationId} = ${installationId}`)
23 .limit(1)
24
25 if (rows.length === 0) {
26 throw new Error(`no ssh key for installation ${installationId}`)
27 }
28 const row = rows[0]!
29
30 const pem = decrypt(row.privateKeyCiphertext, row.privateKeyNonce)
31 return pkcs8ToOpenSshPrivate(pem, `synchub.to/${installationId}`)
32}