|
| 1 | +import fs from 'fs'; |
| 2 | +import { input, password } from '@inquirer/prompts'; |
| 3 | +import crypto from 'crypto'; |
| 4 | +import signale from 'signale'; |
| 5 | +import { decryptString } from '@trustvc/trustvc'; |
| 6 | +import { |
| 7 | + readDocumentFile, |
| 8 | + getCliErrorMessage, |
| 9 | + isErrorWithMessage, |
| 10 | + ensureInputFileExists, |
| 11 | + resolveOutputJsonPath, |
| 12 | + validateInputFileExists, |
| 13 | +} from '../../utils'; |
| 14 | + |
| 15 | +/** Derive a 64-char hex key from passphrase for AES-256 (OPEN-ATTESTATION-TYPE-1). */ |
| 16 | +const deriveKey = (passphrase: string): string => |
| 17 | + crypto.createHash('sha256').update(passphrase, 'utf8').digest('hex'); |
| 18 | + |
| 19 | +export const command = 'oa-decrypt'; |
| 20 | +export const describe = |
| 21 | + 'Decrypt a document that was encrypted using oa-encrypt. You will be asked for the decryption key.'; |
| 22 | + |
| 23 | +type DecryptInput = { |
| 24 | + inputEncryptedPath: string; |
| 25 | + outputPath: string; |
| 26 | + key: string; |
| 27 | +}; |
| 28 | + |
| 29 | +// Payload format: OPEN-ATTESTATION-TYPE-1 (cipherText, iv, tag, type) |
| 30 | +const ENCRYPTED_DOCUMENT_TYPE = 'OPEN-ATTESTATION-TYPE-1'; |
| 31 | + |
| 32 | +/** Message thrown by @trustvc/trustvc when decryption fails (wrong key or corrupted data). */ |
| 33 | +const DECRYPT_FAILED_LIBRARY_MESSAGE = 'Error decrypting message'; |
| 34 | + |
| 35 | +const INVALID_PAYLOAD_MESSAGE = |
| 36 | + 'Invalid encrypted document: expected cipherText, iv, tag and type "OPEN-ATTESTATION-TYPE-1".'; |
| 37 | + |
| 38 | +export const promptForInputs = async (): Promise<DecryptInput | null> => { |
| 39 | + const inputEncryptedPath = await input({ |
| 40 | + message: 'Enter the path to the encrypted document:', |
| 41 | + required: true, |
| 42 | + validate: (value: string) => { |
| 43 | + if (!value || value.trim() === '') return 'Encrypted document path is required'; |
| 44 | + return validateInputFileExists(value); |
| 45 | + }, |
| 46 | + }); |
| 47 | + |
| 48 | + const outputPath = await input({ |
| 49 | + message: 'Enter the path to save the decrypted document:', |
| 50 | + required: true, |
| 51 | + validate: (value: string) => { |
| 52 | + if (!value || value.trim() === '') return 'Output path is required'; |
| 53 | + return true; |
| 54 | + }, |
| 55 | + }); |
| 56 | + |
| 57 | + const key = await password({ |
| 58 | + message: 'Enter the decryption key:', |
| 59 | + mask: '*', |
| 60 | + validate: (value: string) => { |
| 61 | + if (!value || value.trim() === '') return 'Decryption key is required'; |
| 62 | + return true; |
| 63 | + }, |
| 64 | + }); |
| 65 | + |
| 66 | + return { |
| 67 | + inputEncryptedPath: inputEncryptedPath.trim(), |
| 68 | + outputPath: outputPath.trim(), |
| 69 | + key: key.trim(), |
| 70 | + }; |
| 71 | +}; |
| 72 | + |
| 73 | +type EncryptedPayload = { |
| 74 | + cipherText: string; |
| 75 | + iv: string; |
| 76 | + tag: string; |
| 77 | + type: string; |
| 78 | +}; |
| 79 | + |
| 80 | +const DECRYPT_ERROR_OPTIONS = { |
| 81 | + defaultMessage: 'An unexpected error occurred while decrypting the document.', |
| 82 | + fileNotFound: 'Unable to read encrypted document. File not found at: {path}', |
| 83 | + permissionDenied: 'Permission denied. Cannot write to: {path}', |
| 84 | + invalidJson: (msg: string) => `Invalid encrypted file: the file is not valid JSON. ${msg}`, |
| 85 | +} as const; |
| 86 | + |
| 87 | +/** Validates raw payload and returns typed fields or throws with a clear message. */ |
| 88 | +function validateEncryptedPayload(payload: unknown): EncryptedPayload { |
| 89 | + if ( |
| 90 | + payload === null || |
| 91 | + typeof payload !== 'object' || |
| 92 | + !('cipherText' in payload) || |
| 93 | + !('iv' in payload) || |
| 94 | + !('tag' in payload) || |
| 95 | + !('type' in payload) |
| 96 | + ) { |
| 97 | + throw new Error(INVALID_PAYLOAD_MESSAGE); |
| 98 | + } |
| 99 | + const { cipherText, iv, tag, type } = payload as EncryptedPayload; |
| 100 | + if ( |
| 101 | + typeof cipherText !== 'string' || |
| 102 | + typeof iv !== 'string' || |
| 103 | + typeof tag !== 'string' || |
| 104 | + type !== ENCRYPTED_DOCUMENT_TYPE |
| 105 | + ) { |
| 106 | + throw new Error(INVALID_PAYLOAD_MESSAGE); |
| 107 | + } |
| 108 | + return { cipherText, iv, tag, type }; |
| 109 | +} |
| 110 | + |
| 111 | +/** Decrypts payload with derived key; rethrows a user-friendly error on library failure. */ |
| 112 | +function decryptPayload(payload: EncryptedPayload, key: string): string { |
| 113 | + try { |
| 114 | + return decryptString({ |
| 115 | + ...payload, |
| 116 | + key: deriveKey(key), |
| 117 | + }); |
| 118 | + } catch (err: unknown) { |
| 119 | + if (isErrorWithMessage(err) && err.message === DECRYPT_FAILED_LIBRARY_MESSAGE) { |
| 120 | + throw new Error( |
| 121 | + 'Failed to decrypt document. The password/key is likely incorrect or the file is corrupted.', |
| 122 | + ); |
| 123 | + } |
| 124 | + throw err; |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/** Loads encrypted file, validates, decrypts, writes plaintext and shows success message. */ |
| 129 | +async function runDecrypt(answers: DecryptInput): Promise<void> { |
| 130 | + const { inputEncryptedPath, outputPath, key } = answers; |
| 131 | + |
| 132 | + ensureInputFileExists(inputEncryptedPath); |
| 133 | + const rawPayload = readDocumentFile(inputEncryptedPath); |
| 134 | + const payload = validateEncryptedPayload(rawPayload); |
| 135 | + const documentString = decryptPayload(payload, key); |
| 136 | + |
| 137 | + const { path: outputFilePath, generated } = resolveOutputJsonPath(outputPath, 'decrypted'); |
| 138 | + fs.writeFileSync(outputFilePath, documentString, 'utf8'); |
| 139 | + if (generated) { |
| 140 | + signale.success(`No output filename provided. Decrypted document saved to: ${outputFilePath}`); |
| 141 | + } else { |
| 142 | + signale.success(`Decrypted document saved to: ${outputFilePath}`); |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +export const handler = async (): Promise<void> => { |
| 147 | + try { |
| 148 | + const answers = await promptForInputs(); |
| 149 | + if (!answers) return; |
| 150 | + await runDecrypt(answers); |
| 151 | + } catch (err: unknown) { |
| 152 | + signale.error(getCliErrorMessage(err, DECRYPT_ERROR_OPTIONS)); |
| 153 | + process.exitCode = 1; |
| 154 | + } |
| 155 | +}; |
0 commit comments