| 9 | import * as os from 'os' |
| 10 | |
| 11 | export class PostgresSshEngine implements DatabaseEngine { |
| 12 | private tunnel: SshTunnel | null = null |
| 13 | private wrappedEngine: PostgresEngine | null = null |
| 14 | private config: PostgresSshConfigFile |
| 15 | private credentialService: RemoteCredentialService |
| 16 | |
| 17 | constructor(config: PostgresSshConfigFile, credentialService: RemoteCredentialService) { |
| 18 | this.config = config |
| 19 | this.credentialService = credentialService |
| 20 | } |
| 21 | |
| 22 | async connect(): Promise<boolean> { |
| 23 | try { |
| 24 | const dbPassword = await this.credentialService.getCredential(this.config.name, 'password') |
| 25 | ?? await this.credentialService.promptForCredential(this.config.name, 'password') |
| 26 | |
| 27 | let sshAuth: { privateKey?: Buffer; passphrase?: string; password?: string } = {} |
| 28 | |
| 29 | if (this.config.sshPrivateKeyPath) { |
| 30 | const keyPath = this.config.sshPrivateKeyPath.startsWith('~') |
| 31 | ? this.config.sshPrivateKeyPath.replace('~', os.homedir()) |
| 32 | : this.config.sshPrivateKeyPath |
| 33 | const privateKey = fs.readFileSync(keyPath) |
| 34 | const passphrase = await this.credentialService.getCredential(this.config.name, 'sshPassphrase') |
| 35 | sshAuth = { privateKey, passphrase: passphrase ?? undefined } |
| 36 | } else { |
| 37 | const sshPassword = await this.credentialService.getCredential(this.config.name, 'sshPassword') |
| 38 | ?? await this.credentialService.promptForCredential(this.config.name, 'sshPassword') |
| 39 | sshAuth = { password: sshPassword ?? undefined } |
| 40 | } |
| 41 | |
| 42 | this.tunnel = await createSshTunnel({ |
| 43 | sshHost: this.config.sshHost, |
| 44 | sshPort: this.config.sshPort ?? 22, |
| 45 | sshUsername: this.config.sshUsername, |
| 46 | sshPassword: sshAuth.password, |
| 47 | sshPrivateKeyPath: this.config.sshPrivateKeyPath, |
| 48 | sshPassphrase: sshAuth.passphrase, |
| 49 | remoteHost: this.config.host ?? '127.0.0.1', |
| 50 | remotePort: this.config.port ?? 5432, |
| 51 | }) |
| 52 | |
| 53 | const connection = await getConnectionFor( |
| 54 | this.config.name, 'postgres', |
| 55 | '127.0.0.1', this.tunnel.localPort, |
| 56 | this.config.username ?? 'postgres', dbPassword ?? '', |
| 57 | this.config.database, false |
| 58 | ) |
| 59 | |
| 60 | if (!connection) return false |
| 61 | |
| 62 | this.wrappedEngine = new PostgresEngine(connection) |
| 63 | return this.wrappedEngine.isOkay() |
| 64 | } catch { |
| 65 | return false |
| 66 | } |
| 67 | } |
| 68 |
nothing calls this directly
no outgoing calls
no test coverage detected