|
| 1 | +import { constants, existsSync } from 'fs'; |
| 2 | +import { access } from 'node:fs/promises'; |
| 3 | +import { spawn, type StdioOptions } from 'node:child_process'; |
| 4 | +import { dirname, join } from 'node:path'; |
| 5 | +import os, { homedir } from 'node:os'; |
| 6 | +import Debug from 'debug'; |
| 7 | +import type { Config } from '../config'; |
| 8 | +import { GpgError, GpgErrorCode, type GpgErrorContext } from './gpgErrors'; |
| 9 | +import { parseGpgStderr } from './gpgErrorParser'; |
| 10 | +import { execFileCapture, type ExecError, type ExecResult } from './util'; |
| 11 | +import { defaultGnuPgHome, resolveViaGpgConf } from './gpgDiscover'; |
| 12 | + |
| 13 | +const log = Debug('cid::engine::crypto::gpg'); |
| 14 | + |
| 15 | +export interface EncryptWithGpgInput { |
| 16 | + inputPath: string; |
| 17 | + outputPath: string; |
| 18 | + gpgPath: string; |
| 19 | + recipient: string; |
| 20 | + signer?: string; |
| 21 | + armor?: boolean; |
| 22 | + trustAlways?: boolean; |
| 23 | + homedir?: string; |
| 24 | + pinentryMode?: Config.CryptoPinentryMode; |
| 25 | + passphrase?: string; |
| 26 | + allowOverwrite?: boolean, |
| 27 | + timeoutMs?: number, |
| 28 | +} |
| 29 | + |
| 30 | +function hasPubKey(listColons: string): boolean { |
| 31 | + return listColons.split('\n').some(line => line.startsWith('pub:')); |
| 32 | +} |
| 33 | +function hasSecKey(listColons: string): boolean { |
| 34 | + return listColons.split('\n').some(line => line.startsWith('sec:')); |
| 35 | +} |
| 36 | + |
| 37 | +async function assertKeyExists(gpgPath: string, homedir: string, keyId: string, keyType: 'recipient' | 'signer') { |
| 38 | + log(`[DEBUG] Checking for ${keyType} key: ${keyId}`); |
| 39 | + |
| 40 | + const listArgs = keyType === 'signer' |
| 41 | + ? ['--with-colons', '--homedir', homedir, '--batch', '--yes', '--list-secret-keys', keyId] |
| 42 | + : ['--with-colons', '--homedir', homedir, '--batch', '--yes', '--list-keys', keyId]; |
| 43 | + |
| 44 | + let out: ExecResult |
| 45 | + try { out = await execFileCapture(gpgPath, listArgs, { ...process.env, GNUPGHOME: homedir }); } |
| 46 | + catch (err) { |
| 47 | + const e = err as ExecError; |
| 48 | + |
| 49 | + throwDefaultGpgError(e.message, { binary: gpgPath, homedir, args: listArgs }); |
| 50 | + |
| 51 | + throw parseGpgStderr( |
| 52 | + e.stderr?.trim().length ? e.stderr : e.stdout || "", |
| 53 | + { binary: gpgPath, homedir, exitCode: e.code ?? null, args: listArgs, ...(keyType === "recipient" ? { recipient: keyId} : { signer: keyId })} |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + const exists = keyType === 'signer' ? hasSecKey(out.stdout) : hasPubKey(out.stdout); |
| 58 | + |
| 59 | + if (!exists) throw new GpgError( |
| 60 | + keyType === 'signer' ? GpgErrorCode.SIGNER_KEY_NOT_FOUND : GpgErrorCode.RECIPIENT_KEY_NOT_FOUND, |
| 61 | + keyType === 'signer' |
| 62 | + ? `Signing failed: no private key for signer "${keyId}"` |
| 63 | + : `Encryption failed: no public key for recipient "${keyId}"`, |
| 64 | + { binary: gpgPath, homedir, exitCode: 0, args: listArgs, ...(keyType === "recipient" ? { recipient: keyId} : { signer: keyId }) }, |
| 65 | + keyType === 'signer' |
| 66 | + ? [ 'Ensure your signing key (private key) is present in this keyring and not on a different account.' ] |
| 67 | + : [ 'Import or publish the recipient\' public key into this keyring.' ] |
| 68 | + ); |
| 69 | +} |
| 70 | + |
| 71 | +function throwDefaultGpgError(message: string, context: GpgErrorContext) { |
| 72 | + if (message.includes("ENOENT")) throw new GpgError(GpgErrorCode.GPG_NOT_FOUND, `GPG failed to start: ${message}`, context); |
| 73 | +} |
| 74 | + |
| 75 | +async function ensureGpgAvailable(gpgPath: string, homedir: string) { |
| 76 | + log(`[DEBUG] Ensuring GPG is available at: ${gpgPath}`); |
| 77 | + const args = ['--version']; |
| 78 | + |
| 79 | + let out: ExecResult; |
| 80 | + try { out = await execFileCapture(gpgPath, args, { ...process.env, GNUPGHOME: homedir }); } |
| 81 | + catch (err) { |
| 82 | + const e = err as ExecError; |
| 83 | + throwDefaultGpgError(e.message, { binary: gpgPath, homedir, args }); |
| 84 | + |
| 85 | + throw new GpgError( |
| 86 | + GpgErrorCode.GPG_NOT_FOUND, |
| 87 | + `GPG not available (exit ${e.code}) at "${gpgPath}"`, |
| 88 | + { binary: gpgPath, homedir, exitCode: e.code ?? null, args }, |
| 89 | + ['Reinstall Gpg4win (Windows) or GnuPG (Linux/macOS) or adjust the configuration to a working gpg.exe.'] |
| 90 | + ); |
| 91 | + } |
| 92 | + log(`[DEBUG] GPG version output: ${out.stdout.split('\n')[0]}`); |
| 93 | +} |
| 94 | + |
| 95 | + |
| 96 | +export async function encryptFileWithGpg(input: EncryptWithGpgInput) { |
| 97 | + const homedir = input.homedir ?? defaultGnuPgHome(); |
| 98 | + |
| 99 | + await ensureGpgAvailable(input.gpgPath, homedir); |
| 100 | + |
| 101 | + // try { await access(inputPath, constants.R_OK); } |
| 102 | + // catch { |
| 103 | + // throw new GpgError( |
| 104 | + // GpgErrorCode.INPUT_NOT_READABLE, |
| 105 | + // `Cannot read input file: ${inputPath}`, |
| 106 | + // { binary: gpg, homedir, inputPath }, |
| 107 | + // ['Check the file path and permissions.'] |
| 108 | + // ); |
| 109 | + // } |
| 110 | + |
| 111 | + // const outputDir = dirname(outputPath); |
| 112 | + // try { await access(outputDir, constants.W_OK); } |
| 113 | + // catch { |
| 114 | + // throw new GpgError( |
| 115 | + // GpgErrorCode.OUTPUT_NOT_WRITABLE, |
| 116 | + // `Cannot write to output path: ${outputDir}`, |
| 117 | + // { binary: gpg, homedir, outputPath }, |
| 118 | + // ['Check the file path and permissions.'] |
| 119 | + // ); |
| 120 | + // } |
| 121 | + |
| 122 | + // if (!allowOverwrite && existsSync(outputPath)) { |
| 123 | + // throw new GpgError( |
| 124 | + // GpgErrorCode.OUTPUT_WRITE_FAILED, |
| 125 | + // `Refusing to overwrite existing file: ${outputPath}`, |
| 126 | + // { outputPath }, |
| 127 | + // ['Pass allowOverwrite=true to permit overwriting.']); |
| 128 | + // } |
| 129 | + |
| 130 | + // await assertKeyExists(gpg, homedir, recipient, 'recipient'); |
| 131 | + // if (signer) await assertKeyExists(gpg, homedir, signer, 'signer'); |
| 132 | + |
| 133 | + // const args = ['--batch', '--yes', '--status-fd', '2', '--homedir', homedir]; |
| 134 | + // if (armor) args.push('--armor'); |
| 135 | + // if (trustAlways) args.push('--trust-model', 'always'); |
| 136 | + // args.push('--output', outputPath); |
| 137 | + |
| 138 | + // if (signer) { |
| 139 | + // args.push('--sign', '--local-user', signer); |
| 140 | + // if (pinentryMode === 'loopback') { |
| 141 | + // args.push('--pinentry-mode', 'loopback'); |
| 142 | + // if (passphrase) args.push('--passphrase-fd', '0'); |
| 143 | + // } |
| 144 | + // } |
| 145 | + // args.push('--encrypt'); |
| 146 | + // args.push('--recipient', recipient); |
| 147 | + // args.push(inputPath); |
| 148 | + |
| 149 | + // log(`Running: ${JSON.stringify(gpg)} ${args.map(a => JSON.stringify(a)).join(' ')}`); |
| 150 | + |
| 151 | + // let stderr = ''; let stdout = ''; |
| 152 | + // await new Promise<void>((resolve, reject) => { |
| 153 | + // const stdio: StdioOptions = passphrase ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe']; |
| 154 | + // const p = spawn(gpg, args, { stdio, env: { ...process.env, GNUPGHOME: homedir }, timeout: timeoutMs }); |
| 155 | + // p.stdout?.on('data', d => (stdout += String(d))); |
| 156 | + // p.stderr?.on('data', d => (stderr += String(d))); |
| 157 | + // if (p.stdin && passphrase) { p.stdin.write(passphrase + '\n'); p.stdin.end(); } |
| 158 | + // p.once('error', e => reject(new GpgError( |
| 159 | + // GpgErrorCode.GENERAL_GPG_ERROR, `Failed to start GPG: ${(e as Error).message}`, |
| 160 | + // { binary: gpg, homedir, args }, ['Check antivirus/process control tools and try again.'] |
| 161 | + // ))); |
| 162 | + // p.once('close', code => (code === 0 ? resolve() : reject(parseGpgStderr(stderr || stdout, { |
| 163 | + // binary: gpg, homedir, recipient , signer, inputPath, outputPath, exitCode: code, args |
| 164 | + // })))); |
| 165 | + // }); |
| 166 | + |
| 167 | + // return { outputPath, recipient, signed: Boolean(signer) }; |
| 168 | +} |
| 169 | + |
0 commit comments