lpgp 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pgp-tool.js CHANGED
@@ -5,1187 +5,1329 @@ import { execSync } from 'child_process';
5
5
  import * as readline from 'readline';
6
6
  import { stdin as input, stdout as output } from 'process';
7
7
  import clipboardy from 'clipboardy';
8
+ import { Command } from 'commander';
8
9
  import { Db } from './db.js';
9
10
  import { KeyManager } from './key-manager.js';
10
11
  import { extractPublicKeyInfo } from './key-utils.js';
11
12
  import { escapeablePrompt, enableGlobalEscape, checkAndResetEscape, EscapeError, } from './prompts.js';
12
13
  import { getStoredPassphrase, storePassphrase, hasStoredPassphrase, } from './keychain.js';
13
14
  import { colors, icons, printBanner, printDivider, showSuccess, showError, showWarning, showLoading, promptMessage, mainMenuChoice, backChoice, exitChoice, } from './ui.js';
14
- // Config to allow weak keys like DSA (not recommended for production)
15
- const weakKeyConfig = {
16
- rejectPublicKeyAlgorithms: new Set(),
17
- rejectHashAlgorithms: new Set(),
18
- rejectMessageHashAlgorithms: new Set(),
19
- rejectCurves: new Set(),
20
- };
21
- // Database and key manager (initialized in main())
22
- let db;
23
- let keyManager;
24
- // Session passphrase cache - stores passphrases by keypair ID
25
- const passphraseCache = new Map();
26
- // Get installed version of lpgp (null if not installed)
27
- function getInstalledVersion() {
15
+ import { generateCommand, exportPublicCommand, listKeysCommand, encryptCommand, decryptCommand, } from './cli-commands.js';
16
+ import { readFileSync } from 'fs';
17
+ import { dirname, join } from 'path';
18
+ import { fileURLToPath } from 'url';
19
+ // Get package version
20
+ const __filename = fileURLToPath(import.meta.url);
21
+ const __dirname = dirname(__filename);
22
+ function getPackageVersion() {
28
23
  try {
29
- // Check if lpgp is in PATH
30
- execSync('which lpgp 2>/dev/null || where lpgp 2>nul', {
31
- encoding: 'utf-8',
32
- stdio: ['pipe', 'pipe', 'pipe'],
33
- });
34
- // Get the installed version
35
- const version = execSync('npm list -g lpgp --json 2>/dev/null', {
36
- encoding: 'utf-8',
37
- stdio: ['pipe', 'pipe', 'pipe'],
38
- });
39
- const parsed = JSON.parse(version);
40
- return parsed.dependencies?.lpgp?.version || null;
24
+ const pkgPath = join(__dirname, '..', 'package.json');
25
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
26
+ return pkg.version;
41
27
  }
42
28
  catch {
43
- return null;
29
+ return '0.0.0';
44
30
  }
45
31
  }
46
- // Get latest version from npm registry
47
- function getLatestVersion() {
48
- try {
49
- const result = execSync('npm view lpgp version 2>/dev/null', {
50
- encoding: 'utf-8',
51
- stdio: ['pipe', 'pipe', 'pipe'],
52
- });
53
- return result.trim();
54
- }
55
- catch {
56
- return null;
57
- }
32
+ // Helper: Collect multiple --to values
33
+ function collect(value, previous) {
34
+ return previous.concat([value]);
58
35
  }
59
- // Detect which package manager to use
60
- function detectPackageManager() {
61
- try {
62
- execSync('which pnpm 2>/dev/null || where pnpm 2>nul', { stdio: ['pipe', 'pipe', 'pipe'] });
63
- return 'pnpm';
64
- }
65
- catch {
36
+ // Check if running in CLI mode (has subcommand arguments)
37
+ function isCLIMode() {
38
+ // If we have arguments beyond the script name that look like commands
39
+ const args = process.argv.slice(2);
40
+ if (args.length === 0)
41
+ return false;
42
+ // Check if first arg is a known command or starts with -
43
+ const commands = [
44
+ 'generate',
45
+ 'export-public',
46
+ 'list-keys',
47
+ 'encrypt',
48
+ 'decrypt',
49
+ '--help',
50
+ '-h',
51
+ '--version',
52
+ '-V',
53
+ ];
54
+ return commands.some((cmd) => args[0] === cmd || args[0]?.startsWith('-'));
55
+ }
56
+ // Set up CLI commands
57
+ function setupCLI() {
58
+ const program = new Command()
59
+ .name('lpgp')
60
+ .description('PGP encryption/decryption CLI tool')
61
+ .version(getPackageVersion());
62
+ program
63
+ .command('generate')
64
+ .description('Generate a new PGP keypair')
65
+ .requiredOption('--name <name>', 'Name for the keypair')
66
+ .requiredOption('--email <email>', 'Email for the keypair')
67
+ .option('--passphrase <pass>', 'Passphrase to protect the key')
68
+ .option('--no-passphrase', 'Generate without passphrase protection')
69
+ .option('--no-set-default', 'Do not set as default keypair')
70
+ .action(generateCommand);
71
+ program
72
+ .command('export-public')
73
+ .description('Export public key to stdout')
74
+ .option('--fingerprint <fp>', 'Fingerprint of key to export (default: default keypair)')
75
+ .option('--json', 'Output as JSON with metadata')
76
+ .action(exportPublicCommand);
77
+ program
78
+ .command('list-keys')
79
+ .description('List all keypairs')
80
+ .option('--json', 'Output as JSON')
81
+ .action(listKeysCommand);
82
+ program
83
+ .command('encrypt [message]')
84
+ .description('Encrypt a message')
85
+ .requiredOption('--to <recipient>', 'Recipient fingerprint or email (can be used multiple times)', collect, [])
86
+ .option('--file <path>', 'Read message from file')
87
+ .option('--output <path>', 'Write to file (default: stdout)')
88
+ .action(encryptCommand);
89
+ program
90
+ .command('decrypt [message]')
91
+ .description('Decrypt a message')
92
+ .option('--passphrase <pass>', 'Passphrase for private key')
93
+ .option('--file <path>', 'Read encrypted message from file')
94
+ .action(decryptCommand);
95
+ program.parse();
96
+ }
97
+ // Run CLI mode if arguments provided
98
+ if (isCLIMode()) {
99
+ setupCLI();
100
+ }
101
+ else {
102
+ // Interactive mode - continue with existing behavior
103
+ startInteractiveMode();
104
+ }
105
+ function startInteractiveMode() {
106
+ // Config to allow weak keys like DSA (not recommended for production)
107
+ const weakKeyConfig = {
108
+ rejectPublicKeyAlgorithms: new Set(),
109
+ rejectHashAlgorithms: new Set(),
110
+ rejectMessageHashAlgorithms: new Set(),
111
+ rejectCurves: new Set(),
112
+ };
113
+ // Database and key manager (initialized in main())
114
+ let db;
115
+ let keyManager;
116
+ // Session passphrase cache - stores passphrases by keypair ID
117
+ const passphraseCache = new Map();
118
+ // Get installed version of lpgp (null if not installed)
119
+ function getInstalledVersion() {
66
120
  try {
67
- execSync('which yarn 2>/dev/null || where yarn 2>nul', { stdio: ['pipe', 'pipe', 'pipe'] });
68
- return 'yarn';
121
+ // Check if lpgp is in PATH
122
+ execSync('which lpgp 2>/dev/null || where lpgp 2>nul', {
123
+ encoding: 'utf-8',
124
+ stdio: ['pipe', 'pipe', 'pipe'],
125
+ });
126
+ // Get the installed version
127
+ const version = execSync('npm list -g lpgp --json 2>/dev/null', {
128
+ encoding: 'utf-8',
129
+ stdio: ['pipe', 'pipe', 'pipe'],
130
+ });
131
+ const parsed = JSON.parse(version);
132
+ return parsed.dependencies?.lpgp?.version || null;
69
133
  }
70
134
  catch {
71
- return 'npm';
135
+ return null;
72
136
  }
73
137
  }
74
- }
75
- // Compare semver versions (returns true if v1 < v2)
76
- function isOlderVersion(v1, v2) {
77
- const p1 = v1.split('.').map(Number);
78
- const p2 = v2.split('.').map(Number);
79
- for (let i = 0; i < 3; i++) {
80
- if ((p1[i] || 0) < (p2[i] || 0))
81
- return true;
82
- if ((p1[i] || 0) > (p2[i] || 0))
83
- return false;
138
+ // Get latest version from npm registry
139
+ function getLatestVersion() {
140
+ try {
141
+ const result = execSync('npm view lpgp version 2>/dev/null', {
142
+ encoding: 'utf-8',
143
+ stdio: ['pipe', 'pipe', 'pipe'],
144
+ });
145
+ return result.trim();
146
+ }
147
+ catch {
148
+ return null;
149
+ }
84
150
  }
85
- return false;
86
- }
87
- // Install or update lpgp globally
88
- async function installOrUpdateGlobally(isUpdate) {
89
- console.clear();
90
- printBanner();
91
- console.log();
92
- const pm = detectPackageManager();
93
- const action = isUpdate ? 'Updating' : 'Installing';
94
- const cmd = pm === 'yarn' ? `yarn global add lpgp` : `${pm} install -g lpgp`;
95
- showLoading(`${action} lpgp globally...`);
96
- console.log();
97
- console.log(colors.muted(`Running: ${cmd}`));
98
- console.log();
99
- try {
100
- execSync(cmd, { stdio: 'inherit' });
101
- console.log();
102
- if (isUpdate) {
103
- showSuccess('lpgp updated successfully!');
151
+ // Detect which package manager to use
152
+ function detectPackageManager() {
153
+ try {
154
+ execSync('which pnpm 2>/dev/null || where pnpm 2>nul', {
155
+ stdio: ['pipe', 'pipe', 'pipe'],
156
+ });
157
+ return 'pnpm';
104
158
  }
105
- else {
106
- showSuccess('lpgp installed globally! You can now run it with just "lpgp"');
159
+ catch {
160
+ try {
161
+ execSync('which yarn 2>/dev/null || where yarn 2>nul', {
162
+ stdio: ['pipe', 'pipe', 'pipe'],
163
+ });
164
+ return 'yarn';
165
+ }
166
+ catch {
167
+ return 'npm';
168
+ }
107
169
  }
108
- console.log();
109
- return true;
110
170
  }
111
- catch {
171
+ // Compare semver versions (returns true if v1 < v2)
172
+ function isOlderVersion(v1, v2) {
173
+ const p1 = v1.split('.').map(Number);
174
+ const p2 = v2.split('.').map(Number);
175
+ for (let i = 0; i < 3; i++) {
176
+ if ((p1[i] || 0) < (p2[i] || 0))
177
+ return true;
178
+ if ((p1[i] || 0) > (p2[i] || 0))
179
+ return false;
180
+ }
181
+ return false;
182
+ }
183
+ // Install or update lpgp globally
184
+ async function installOrUpdateGlobally(isUpdate) {
185
+ console.clear();
186
+ printBanner();
112
187
  console.log();
113
- showError(`Failed to ${isUpdate ? 'update' : 'install'}. You may need to run with sudo:`);
114
- console.log(colors.muted(` sudo ${cmd}`));
188
+ const pm = detectPackageManager();
189
+ const action = isUpdate ? 'Updating' : 'Installing';
190
+ const cmd = pm === 'yarn' ? `yarn global add lpgp` : `${pm} install -g lpgp`;
191
+ showLoading(`${action} lpgp globally...`);
115
192
  console.log();
116
- return false;
193
+ console.log(colors.muted(`Running: ${cmd}`));
194
+ console.log();
195
+ try {
196
+ execSync(cmd, { stdio: 'inherit' });
197
+ console.log();
198
+ if (isUpdate) {
199
+ showSuccess('lpgp updated successfully!');
200
+ }
201
+ else {
202
+ showSuccess('lpgp installed globally! You can now run it with just "lpgp"');
203
+ }
204
+ console.log();
205
+ return true;
206
+ }
207
+ catch {
208
+ console.log();
209
+ showError(`Failed to ${isUpdate ? 'update' : 'install'}. You may need to run with sudo:`);
210
+ console.log(colors.muted(` sudo ${cmd}`));
211
+ console.log();
212
+ return false;
213
+ }
117
214
  }
118
- }
119
- async function encryptMessage(message, publicKeysArmored) {
120
- let publicKeys;
121
- if (publicKeysArmored) {
122
- // Use provided public key(s)
123
- const keysArray = Array.isArray(publicKeysArmored) ? publicKeysArmored : [publicKeysArmored];
124
- publicKeys = await Promise.all(keysArray.map((key) => openpgp.readKey({ armoredKey: key, config: weakKeyConfig })));
215
+ async function encryptMessage(message, publicKeysArmored) {
216
+ let publicKeys;
217
+ if (publicKeysArmored) {
218
+ // Use provided public key(s)
219
+ const keysArray = Array.isArray(publicKeysArmored)
220
+ ? publicKeysArmored
221
+ : [publicKeysArmored];
222
+ publicKeys = await Promise.all(keysArray.map((key) => openpgp.readKey({ armoredKey: key, config: weakKeyConfig })));
223
+ }
224
+ else {
225
+ // Use default keypair's public key (encrypt to self)
226
+ const defaultKeypair = await keyManager.getDefaultKeypair();
227
+ if (!defaultKeypair) {
228
+ throw new Error('No default keypair found. Please set up a keypair first.');
229
+ }
230
+ publicKeys = [
231
+ await openpgp.readKey({
232
+ armoredKey: defaultKeypair.public_key,
233
+ config: weakKeyConfig,
234
+ }),
235
+ ];
236
+ // Update last_used_at
237
+ db.update('keypair', { key: 'id', value: defaultKeypair.id }, { last_used_at: new Date().toISOString() });
238
+ }
239
+ const encrypted = await openpgp.encrypt({
240
+ message: await openpgp.createMessage({ text: message }),
241
+ encryptionKeys: publicKeys,
242
+ config: weakKeyConfig,
243
+ });
244
+ return encrypted;
125
245
  }
126
- else {
127
- // Use default keypair's public key (encrypt to self)
246
+ async function decryptMessage(encryptedMessage) {
128
247
  const defaultKeypair = await keyManager.getDefaultKeypair();
129
248
  if (!defaultKeypair) {
130
249
  throw new Error('No default keypair found. Please set up a keypair first.');
131
250
  }
132
- publicKeys = [await openpgp.readKey({ armoredKey: defaultKeypair.public_key, config: weakKeyConfig })];
133
- // Update last_used_at
134
- db.update('keypair', { key: 'id', value: defaultKeypair.id }, { last_used_at: new Date().toISOString() });
135
- }
136
- const encrypted = await openpgp.encrypt({
137
- message: await openpgp.createMessage({ text: message }),
138
- encryptionKeys: publicKeys,
139
- config: weakKeyConfig,
140
- });
141
- return encrypted;
142
- }
143
- async function decryptMessage(encryptedMessage) {
144
- const defaultKeypair = await keyManager.getDefaultKeypair();
145
- if (!defaultKeypair) {
146
- throw new Error('No default keypair found. Please set up a keypair first.');
147
- }
148
- // Check if passphrase is cached for this keypair
149
- let passphrase = '';
150
- if (defaultKeypair.passphrase_protected) {
151
- if (passphraseCache.has(defaultKeypair.id)) {
152
- // Use session-cached passphrase
153
- passphrase = passphraseCache.get(defaultKeypair.id);
154
- }
155
- else {
156
- // Check if passphrase is stored in system keychain
157
- const storedPassphrase = await getStoredPassphrase(defaultKeypair.fingerprint);
158
- if (storedPassphrase) {
159
- // Validate the stored passphrase
160
- try {
161
- await openpgp.decryptKey({
162
- privateKey: await openpgp.readPrivateKey({ armoredKey: defaultKeypair.private_key, config: weakKeyConfig }),
163
- passphrase: storedPassphrase,
164
- config: weakKeyConfig,
165
- });
166
- // Stored passphrase is valid, use it
167
- passphrase = storedPassphrase;
168
- passphraseCache.set(defaultKeypair.id, passphrase);
169
- console.log(colors.muted('Using passphrase from system keychain'));
170
- }
171
- catch {
172
- // Stored passphrase is invalid (key may have changed), prompt for new one
173
- showWarning('Stored passphrase is invalid. Please enter your passphrase.');
174
- }
251
+ // Check if passphrase is cached for this keypair
252
+ let passphrase = '';
253
+ if (defaultKeypair.passphrase_protected) {
254
+ if (passphraseCache.has(defaultKeypair.id)) {
255
+ // Use session-cached passphrase
256
+ passphrase = passphraseCache.get(defaultKeypair.id);
175
257
  }
176
- // If we still don't have a valid passphrase, prompt for it
177
- if (!passphrase) {
178
- const { passphraseInput } = await escapeablePrompt([
179
- {
180
- type: 'password',
181
- name: 'passphraseInput',
182
- message: promptMessage('Enter your private key passphrase:'),
183
- mask: '*',
184
- },
185
- ]);
186
- passphrase = passphraseInput;
187
- // Validate the passphrase by attempting to decrypt the key
188
- try {
189
- await openpgp.decryptKey({
190
- privateKey: await openpgp.readPrivateKey({ armoredKey: defaultKeypair.private_key, config: weakKeyConfig }),
191
- passphrase,
192
- config: weakKeyConfig,
193
- });
194
- // If successful, cache the passphrase in session
195
- passphraseCache.set(defaultKeypair.id, passphrase);
196
- // Ask if user wants to save passphrase to system keychain
197
- const alreadyStored = await hasStoredPassphrase(defaultKeypair.fingerprint);
198
- if (!alreadyStored) {
199
- const { saveToKeychain } = await escapeablePrompt([
200
- {
201
- type: 'confirm',
202
- name: 'saveToKeychain',
203
- message: promptMessage('Save passphrase to system keychain?'),
204
- default: false,
205
- },
206
- ]);
207
- if (saveToKeychain) {
208
- const saved = await storePassphrase(defaultKeypair.fingerprint, passphrase);
209
- if (saved) {
210
- showSuccess('Passphrase saved to system keychain');
211
- }
212
- else {
213
- showWarning('Could not save to keychain (may not be available on this system)');
258
+ else {
259
+ // Check if passphrase is stored in system keychain
260
+ const storedPassphrase = await getStoredPassphrase(defaultKeypair.fingerprint);
261
+ if (storedPassphrase) {
262
+ // Validate the stored passphrase
263
+ try {
264
+ await openpgp.decryptKey({
265
+ privateKey: await openpgp.readPrivateKey({
266
+ armoredKey: defaultKeypair.private_key,
267
+ config: weakKeyConfig,
268
+ }),
269
+ passphrase: storedPassphrase,
270
+ config: weakKeyConfig,
271
+ });
272
+ // Stored passphrase is valid, use it
273
+ passphrase = storedPassphrase;
274
+ passphraseCache.set(defaultKeypair.id, passphrase);
275
+ console.log(colors.muted('Using passphrase from system keychain'));
276
+ }
277
+ catch {
278
+ // Stored passphrase is invalid (key may have changed), prompt for new one
279
+ showWarning('Stored passphrase is invalid. Please enter your passphrase.');
280
+ }
281
+ }
282
+ // If we still don't have a valid passphrase, prompt for it
283
+ if (!passphrase) {
284
+ const { passphraseInput } = await escapeablePrompt([
285
+ {
286
+ type: 'password',
287
+ name: 'passphraseInput',
288
+ message: promptMessage('Enter your private key passphrase:'),
289
+ mask: '*',
290
+ },
291
+ ]);
292
+ passphrase = passphraseInput;
293
+ // Validate the passphrase by attempting to decrypt the key
294
+ try {
295
+ await openpgp.decryptKey({
296
+ privateKey: await openpgp.readPrivateKey({
297
+ armoredKey: defaultKeypair.private_key,
298
+ config: weakKeyConfig,
299
+ }),
300
+ passphrase,
301
+ config: weakKeyConfig,
302
+ });
303
+ // If successful, cache the passphrase in session
304
+ passphraseCache.set(defaultKeypair.id, passphrase);
305
+ // Ask if user wants to save passphrase to system keychain
306
+ const alreadyStored = await hasStoredPassphrase(defaultKeypair.fingerprint);
307
+ if (!alreadyStored) {
308
+ const { saveToKeychain } = await escapeablePrompt([
309
+ {
310
+ type: 'confirm',
311
+ name: 'saveToKeychain',
312
+ message: promptMessage('Save passphrase to system keychain?'),
313
+ default: false,
314
+ },
315
+ ]);
316
+ if (saveToKeychain) {
317
+ const saved = await storePassphrase(defaultKeypair.fingerprint, passphrase);
318
+ if (saved) {
319
+ showSuccess('Passphrase saved to system keychain');
320
+ }
321
+ else {
322
+ showWarning('Could not save to keychain (may not be available on this system)');
323
+ }
214
324
  }
215
325
  }
216
326
  }
217
- }
218
- catch (error) {
219
- throw new Error('Incorrect passphrase');
327
+ catch (error) {
328
+ throw new Error('Incorrect passphrase');
329
+ }
220
330
  }
221
331
  }
222
332
  }
333
+ const privateKey = await openpgp.decryptKey({
334
+ privateKey: await openpgp.readPrivateKey({
335
+ armoredKey: defaultKeypair.private_key,
336
+ config: weakKeyConfig,
337
+ }),
338
+ passphrase,
339
+ config: weakKeyConfig,
340
+ });
341
+ const message = await openpgp.readMessage({
342
+ armoredMessage: encryptedMessage,
343
+ });
344
+ const { data: decrypted } = await openpgp.decrypt({
345
+ message,
346
+ decryptionKeys: privateKey,
347
+ config: weakKeyConfig,
348
+ });
349
+ // Update last_used_at
350
+ db.update('keypair', { key: 'id', value: defaultKeypair.id }, { last_used_at: new Date().toISOString() });
351
+ return decrypted;
223
352
  }
224
- const privateKey = await openpgp.decryptKey({
225
- privateKey: await openpgp.readPrivateKey({ armoredKey: defaultKeypair.private_key, config: weakKeyConfig }),
226
- passphrase,
227
- config: weakKeyConfig,
228
- });
229
- const message = await openpgp.readMessage({
230
- armoredMessage: encryptedMessage,
231
- });
232
- const { data: decrypted } = await openpgp.decrypt({
233
- message,
234
- decryptionKeys: privateKey,
235
- config: weakKeyConfig,
236
- });
237
- // Update last_used_at
238
- db.update('keypair', { key: 'id', value: defaultKeypair.id }, { last_used_at: new Date().toISOString() });
239
- return decrypted;
240
- }
241
- function checkEditorAvailable(command) {
242
- try {
243
- execSync(`which ${command}`, { stdio: 'ignore' });
244
- return true;
245
- }
246
- catch {
247
- return false;
248
- }
249
- }
250
- function detectAvailableEditors() {
251
- const editors = [
252
- { name: 'VS Code', command: 'code', available: false },
253
- { name: 'Neovim', command: 'nvim', available: false },
254
- { name: 'Vim', command: 'vim', available: false },
255
- { name: 'Nano', command: 'nano', available: false },
256
- { name: 'Emacs', command: 'emacs', available: false },
257
- ];
258
- // Check platform specific editors
259
- if (process.platform === 'darwin') {
260
- editors.push({ name: 'TextEdit', command: 'open -e', available: true });
261
- }
262
- else if (process.platform === 'win32') {
263
- editors.push({ name: 'Notepad', command: 'notepad', available: true });
353
+ function checkEditorAvailable(command) {
354
+ try {
355
+ execSync(`which ${command}`, { stdio: 'ignore' });
356
+ return true;
357
+ }
358
+ catch {
359
+ return false;
360
+ }
264
361
  }
265
- // Check which editors are available
266
- for (const editor of editors) {
267
- if (editor.command.includes('open -e') || editor.command === 'notepad') {
268
- editor.available = true; // TextEdit and Notepad are always available on their platforms
362
+ function detectAvailableEditors() {
363
+ const editors = [
364
+ { name: 'VS Code', command: 'code', available: false },
365
+ { name: 'Neovim', command: 'nvim', available: false },
366
+ { name: 'Vim', command: 'vim', available: false },
367
+ { name: 'Nano', command: 'nano', available: false },
368
+ { name: 'Emacs', command: 'emacs', available: false },
369
+ ];
370
+ // Check platform specific editors
371
+ if (process.platform === 'darwin') {
372
+ editors.push({ name: 'TextEdit', command: 'open -e', available: true });
269
373
  }
270
- else {
271
- editor.available = checkEditorAvailable(editor.command);
374
+ else if (process.platform === 'win32') {
375
+ editors.push({ name: 'Notepad', command: 'notepad', available: true });
272
376
  }
377
+ // Check which editors are available
378
+ for (const editor of editors) {
379
+ if (editor.command.includes('open -e') || editor.command === 'notepad') {
380
+ editor.available = true; // TextEdit and Notepad are always available on their platforms
381
+ }
382
+ else {
383
+ editor.available = checkEditorAvailable(editor.command);
384
+ }
385
+ }
386
+ return editors.filter((e) => e.available);
273
387
  }
274
- return editors.filter((e) => e.available);
275
- }
276
- async function readInlineMultilineInput(promptText) {
277
- console.log(promptMessage(promptText));
278
- console.log(colors.muted('(Type your message. Press Enter, then Ctrl+D to finish)\n'));
279
- const rl = readline.createInterface({ input, output });
280
- rl.setPrompt('');
281
- const lines = [];
282
- return new Promise((resolve) => {
283
- rl.on('line', (line) => {
284
- lines.push(line);
285
- });
286
- rl.on('close', () => {
287
- resolve(lines.join('\n'));
388
+ async function readInlineMultilineInput(promptText) {
389
+ console.log(promptMessage(promptText));
390
+ console.log(colors.muted('(Type your message. Press Enter, then Ctrl+D to finish)\n'));
391
+ const rl = readline.createInterface({ input, output });
392
+ rl.setPrompt('');
393
+ const lines = [];
394
+ return new Promise((resolve) => {
395
+ rl.on('line', (line) => {
396
+ lines.push(line);
397
+ });
398
+ rl.on('close', () => {
399
+ resolve(lines.join('\n'));
400
+ });
288
401
  });
289
- });
290
- }
291
- function extractAllPublicKeys(content) {
292
- const keyRegex = /-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g;
293
- const matches = content.match(keyRegex);
294
- return matches || [];
295
- }
296
- async function addKeysFromClipboard(recipients) {
297
- let clipboardContent = '';
298
- try {
299
- clipboardContent = await clipboardy.read();
300
- }
301
- catch {
302
- showWarning('Could not access clipboard');
303
- return 0;
304
402
  }
305
- const keys = extractAllPublicKeys(clipboardContent);
306
- if (keys.length === 0) {
307
- showWarning('No public keys found in clipboard');
308
- return 0;
403
+ function extractAllPublicKeys(content) {
404
+ const keyRegex = /-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g;
405
+ const matches = content.match(keyRegex);
406
+ return matches || [];
309
407
  }
310
- let addedCount = 0;
311
- for (const publicKey of keys) {
408
+ async function addKeysFromClipboard(recipients) {
409
+ let clipboardContent = '';
312
410
  try {
313
- // Validate the key
314
- await openpgp.readKey({ armoredKey: publicKey, config: weakKeyConfig });
315
- const keyInfo = await extractPublicKeyInfo(publicKey);
316
- const recipientName = keyInfo.email || keyInfo.fingerprint?.slice(-8) || 'Unknown';
317
- // Check for duplicates
318
- const isDuplicate = recipients.some((r) => r.publicKey === publicKey);
319
- if (isDuplicate) {
320
- showWarning(`Skipping duplicate key: ${recipientName}`);
321
- continue;
322
- }
323
- recipients.push({
324
- name: recipientName,
325
- publicKey,
326
- });
327
- showSuccess(`Added recipient: ${recipientName}`);
328
- addedCount++;
411
+ clipboardContent = await clipboardy.read();
329
412
  }
330
- catch (error) {
331
- showError(`Failed to parse a key: ${error instanceof Error ? error.message : 'unknown error'}`);
413
+ catch {
414
+ showWarning('Could not access clipboard');
415
+ return 0;
416
+ }
417
+ const keys = extractAllPublicKeys(clipboardContent);
418
+ if (keys.length === 0) {
419
+ showWarning('No public keys found in clipboard');
420
+ return 0;
332
421
  }
422
+ let addedCount = 0;
423
+ for (const publicKey of keys) {
424
+ try {
425
+ // Validate the key
426
+ await openpgp.readKey({ armoredKey: publicKey, config: weakKeyConfig });
427
+ const keyInfo = await extractPublicKeyInfo(publicKey);
428
+ const recipientName = keyInfo.email || keyInfo.fingerprint?.slice(-8) || 'Unknown';
429
+ // Check for duplicates
430
+ const isDuplicate = recipients.some((r) => r.publicKey === publicKey);
431
+ if (isDuplicate) {
432
+ showWarning(`Skipping duplicate key: ${recipientName}`);
433
+ continue;
434
+ }
435
+ recipients.push({
436
+ name: recipientName,
437
+ publicKey,
438
+ });
439
+ showSuccess(`Added recipient: ${recipientName}`);
440
+ addedCount++;
441
+ }
442
+ catch (error) {
443
+ showError(`Failed to parse a key: ${error instanceof Error ? error.message : 'unknown error'}`);
444
+ }
445
+ }
446
+ return addedCount;
333
447
  }
334
- return addedCount;
335
- }
336
- async function selectMultipleRecipients() {
337
- const recipients = [];
338
- const contacts = db.select({ table: 'contact' });
339
- const defaultKeypair = await keyManager.getDefaultKeypair();
340
- // Build the menu choices
341
- function buildChoices() {
342
- const choices = [];
343
- // Show current recipients count
344
- if (recipients.length > 0) {
448
+ async function selectMultipleRecipients() {
449
+ const recipients = [];
450
+ const contacts = db.select({ table: 'contact' });
451
+ const defaultKeypair = await keyManager.getDefaultKeypair();
452
+ // Build the menu choices
453
+ function buildChoices() {
454
+ const choices = [];
455
+ // Show current recipients count
456
+ if (recipients.length > 0) {
457
+ choices.push({
458
+ name: colors.primary(`── Current recipients: ${recipients.length} ──`),
459
+ value: 'show-recipients',
460
+ });
461
+ }
462
+ // Option to add self (if not already added)
463
+ const selfAdded = recipients.some((r) => r.name === 'Myself');
464
+ if (defaultKeypair && !selfAdded) {
465
+ choices.push({
466
+ name: `${icons.key} Add myself ${colors.muted('(so I can also decrypt)')}`,
467
+ value: 'self',
468
+ });
469
+ }
470
+ // Option to select from contacts
471
+ if (contacts.length > 0) {
472
+ choices.push({
473
+ name: `${icons.contact} Select from saved contacts ${colors.muted(`(${contacts.length} available)`)}`,
474
+ value: 'contacts',
475
+ });
476
+ }
477
+ // Clipboard and manual options
345
478
  choices.push({
346
- name: colors.primary(`── Current recipients: ${recipients.length} ──`),
347
- value: 'show-recipients',
479
+ name: `${icons.clipboard} Paste from clipboard ${colors.muted('(supports multiple keys)')}`,
480
+ value: 'clipboard',
348
481
  });
349
- }
350
- // Option to add self (if not already added)
351
- const selfAdded = recipients.some((r) => r.name === 'Myself');
352
- if (defaultKeypair && !selfAdded) {
353
482
  choices.push({
354
- name: `${icons.key} Add myself ${colors.muted('(so I can also decrypt)')}`,
355
- value: 'self',
483
+ name: `${icons.inline} Type/paste a single key`,
484
+ value: 'manual',
356
485
  });
357
- }
358
- // Option to select from contacts
359
- if (contacts.length > 0) {
486
+ // Done or cancel
360
487
  choices.push({
361
- name: `${icons.contact} Select from saved contacts ${colors.muted(`(${contacts.length} available)`)}`,
362
- value: 'contacts',
488
+ name: recipients.length > 0
489
+ ? `${icons.success} Done adding recipients`
490
+ : `${icons.back} Cancel`,
491
+ value: 'done',
363
492
  });
493
+ return choices;
364
494
  }
365
- // Clipboard and manual options
366
- choices.push({
367
- name: `${icons.clipboard} Paste from clipboard ${colors.muted('(supports multiple keys)')}`,
368
- value: 'clipboard',
369
- });
370
- choices.push({
371
- name: `${icons.inline} Type/paste a single key`,
372
- value: 'manual',
373
- });
374
- // Done or cancel
375
- choices.push({
376
- name: recipients.length > 0 ? `${icons.success} Done adding recipients` : `${icons.back} Cancel`,
377
- value: 'done',
378
- });
379
- return choices;
380
- }
381
- let addMore = true;
382
- while (addMore) {
383
- const { addMethod } = await escapeablePrompt([
384
- {
385
- type: 'list',
386
- name: 'addMethod',
387
- message: promptMessage('Add recipients:'),
388
- choices: buildChoices(),
389
- },
390
- ]);
391
- if (addMethod === 'done') {
392
- addMore = false;
393
- }
394
- else if (addMethod === 'show-recipients') {
395
- // Show current recipients
396
- console.log(colors.primary('\nCurrent recipients:'));
397
- for (const r of recipients) {
398
- console.log(colors.muted(` • ${r.name}`));
399
- }
400
- console.log();
401
- }
402
- else if (addMethod === 'self') {
403
- if (defaultKeypair) {
404
- recipients.push({
405
- name: 'Myself',
406
- publicKey: defaultKeypair.public_key,
407
- });
408
- showSuccess('Added yourself as a recipient');
409
- }
410
- }
411
- else if (addMethod === 'contacts') {
412
- // Show contacts as a checkbox
413
- const { selectedContacts } = await escapeablePrompt([
495
+ let addMore = true;
496
+ while (addMore) {
497
+ const { addMethod } = await escapeablePrompt([
414
498
  {
415
- type: 'checkbox',
416
- name: 'selectedContacts',
417
- message: promptMessage('Select contacts (space to toggle, enter to confirm):'),
418
- choices: contacts.map((c) => {
419
- const alreadyAdded = recipients.some((r) => r.publicKey === c.public_key);
420
- return {
421
- name: `${c.name} <${c.email || 'no email'}>${alreadyAdded ? colors.muted(' (already added)') : ''}`,
422
- value: c.id,
423
- checked: false,
424
- disabled: alreadyAdded,
425
- };
426
- }),
499
+ type: 'list',
500
+ name: 'addMethod',
501
+ message: promptMessage('Add recipients:'),
502
+ choices: buildChoices(),
427
503
  },
428
504
  ]);
429
- let addedCount = 0;
430
- for (const contactId of selectedContacts) {
431
- const contact = contacts.find((c) => c.id === contactId);
432
- if (contact) {
505
+ if (addMethod === 'done') {
506
+ addMore = false;
507
+ }
508
+ else if (addMethod === 'show-recipients') {
509
+ // Show current recipients
510
+ console.log(colors.primary('\nCurrent recipients:'));
511
+ for (const r of recipients) {
512
+ console.log(colors.muted(` • ${r.name}`));
513
+ }
514
+ console.log();
515
+ }
516
+ else if (addMethod === 'self') {
517
+ if (defaultKeypair) {
433
518
  recipients.push({
434
- name: `${contact.name} <${contact.email || 'no email'}>`,
435
- publicKey: contact.public_key,
519
+ name: 'Myself',
520
+ publicKey: defaultKeypair.public_key,
436
521
  });
437
- addedCount++;
522
+ showSuccess('Added yourself as a recipient');
438
523
  }
439
524
  }
440
- if (addedCount > 0) {
441
- showSuccess(`Added ${addedCount} contact${addedCount > 1 ? 's' : ''}`);
442
- }
443
- }
444
- else if (addMethod === 'clipboard') {
445
- const added = await addKeysFromClipboard(recipients);
446
- if (added > 0) {
447
- console.log();
448
- showSuccess(`Added ${added} recipient${added > 1 ? 's' : ''} from clipboard`);
449
- console.log();
450
- }
451
- }
452
- else if (addMethod === 'manual') {
453
- const publicKey = await getRecipientPublicKey();
454
- if (publicKey) {
455
- try {
456
- const keyInfo = await extractPublicKeyInfo(publicKey);
457
- const recipientName = keyInfo.email || keyInfo.fingerprint?.slice(-8) || 'Unknown';
458
- // Check for duplicates
459
- const isDuplicate = recipients.some((r) => r.publicKey === publicKey);
460
- if (isDuplicate) {
461
- showWarning('This recipient is already in the list');
462
- }
463
- else {
525
+ else if (addMethod === 'contacts') {
526
+ // Show contacts as a checkbox
527
+ const { selectedContacts } = await escapeablePrompt([
528
+ {
529
+ type: 'checkbox',
530
+ name: 'selectedContacts',
531
+ message: promptMessage('Select contacts (space to toggle, enter to confirm):'),
532
+ choices: contacts.map((c) => {
533
+ const alreadyAdded = recipients.some((r) => r.publicKey === c.public_key);
534
+ return {
535
+ name: `${c.name} <${c.email || 'no email'}>${alreadyAdded ? colors.muted(' (already added)') : ''}`,
536
+ value: c.id,
537
+ checked: false,
538
+ disabled: alreadyAdded,
539
+ };
540
+ }),
541
+ },
542
+ ]);
543
+ let addedCount = 0;
544
+ for (const contactId of selectedContacts) {
545
+ const contact = contacts.find((c) => c.id === contactId);
546
+ if (contact) {
464
547
  recipients.push({
465
- name: recipientName,
466
- publicKey,
548
+ name: `${contact.name} <${contact.email || 'no email'}>`,
549
+ publicKey: contact.public_key,
467
550
  });
468
- showSuccess(`Added recipient: ${recipientName}`);
551
+ addedCount++;
469
552
  }
470
553
  }
471
- catch (error) {
472
- showError('Failed to parse public key');
554
+ if (addedCount > 0) {
555
+ showSuccess(`Added ${addedCount} contact${addedCount > 1 ? 's' : ''}`);
473
556
  }
474
557
  }
475
- }
476
- }
477
- return recipients;
478
- }
479
- async function getRecipientPublicKey() {
480
- // Check clipboard for public key
481
- let clipboardContent = '';
482
- let hasPublicKeyInClipboard = false;
483
- try {
484
- clipboardContent = await clipboardy.read();
485
- hasPublicKeyInClipboard = clipboardContent.includes('BEGIN PGP PUBLIC KEY BLOCK');
486
- }
487
- catch (e) {
488
- // Clipboard not available, continue without it
489
- }
490
- let publicKey = '';
491
- // If public key found in clipboard, ask if user wants to use it
492
- if (hasPublicKeyInClipboard) {
493
- const { useClipboard } = await escapeablePrompt([
494
- {
495
- type: 'confirm',
496
- name: 'useClipboard',
497
- message: 'Public key detected in clipboard. Use it?',
498
- default: true,
499
- },
500
- ]);
501
- if (useClipboard) {
502
- const publicMatch = clipboardContent.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/);
503
- if (publicMatch) {
504
- publicKey = publicMatch[0];
558
+ else if (addMethod === 'clipboard') {
559
+ const added = await addKeysFromClipboard(recipients);
560
+ if (added > 0) {
561
+ console.log();
562
+ showSuccess(`Added ${added} recipient${added > 1 ? 's' : ''} from clipboard`);
563
+ console.log();
564
+ }
565
+ }
566
+ else if (addMethod === 'manual') {
567
+ const publicKey = await getRecipientPublicKey();
568
+ if (publicKey) {
569
+ try {
570
+ const keyInfo = await extractPublicKeyInfo(publicKey);
571
+ const recipientName = keyInfo.email || keyInfo.fingerprint?.slice(-8) || 'Unknown';
572
+ // Check for duplicates
573
+ const isDuplicate = recipients.some((r) => r.publicKey === publicKey);
574
+ if (isDuplicate) {
575
+ showWarning('This recipient is already in the list');
576
+ }
577
+ else {
578
+ recipients.push({
579
+ name: recipientName,
580
+ publicKey,
581
+ });
582
+ showSuccess(`Added recipient: ${recipientName}`);
583
+ }
584
+ }
585
+ catch (error) {
586
+ showError('Failed to parse public key');
587
+ }
588
+ }
505
589
  }
506
590
  }
591
+ return recipients;
507
592
  }
508
- // If no key from clipboard, prompt for input
509
- if (!publicKey) {
510
- console.log(promptMessage('\nPaste the recipient\'s PGP PUBLIC key:'));
511
- console.log(colors.muted('(Press Enter to finish, or press Enter then Ctrl+D)\n'));
512
- const rl = readline.createInterface({ input, output });
513
- rl.setPrompt('');
514
- const lines = [];
515
- publicKey = await new Promise((resolve) => {
516
- rl.on('line', (line) => {
517
- lines.push(line);
518
- const content = lines.join('\n');
519
- // Check if we have a complete key block and current line is empty
520
- if (line.trim() === '' &&
521
- content.includes('-----BEGIN PGP PUBLIC KEY BLOCK') &&
522
- content.includes('-----END PGP PUBLIC KEY BLOCK')) {
523
- rl.close();
524
- resolve(content.trim());
593
+ async function getRecipientPublicKey() {
594
+ // Check clipboard for public key
595
+ let clipboardContent = '';
596
+ let hasPublicKeyInClipboard = false;
597
+ try {
598
+ clipboardContent = await clipboardy.read();
599
+ hasPublicKeyInClipboard = clipboardContent.includes('BEGIN PGP PUBLIC KEY BLOCK');
600
+ }
601
+ catch (e) {
602
+ // Clipboard not available, continue without it
603
+ }
604
+ let publicKey = '';
605
+ // If public key found in clipboard, ask if user wants to use it
606
+ if (hasPublicKeyInClipboard) {
607
+ const { useClipboard } = await escapeablePrompt([
608
+ {
609
+ type: 'confirm',
610
+ name: 'useClipboard',
611
+ message: 'Public key detected in clipboard. Use it?',
612
+ default: true,
613
+ },
614
+ ]);
615
+ if (useClipboard) {
616
+ const publicMatch = clipboardContent.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/);
617
+ if (publicMatch) {
618
+ publicKey = publicMatch[0];
525
619
  }
620
+ }
621
+ }
622
+ // If no key from clipboard, prompt for input
623
+ if (!publicKey) {
624
+ console.log(promptMessage("\nPaste the recipient's PGP PUBLIC key:"));
625
+ console.log(colors.muted('(Press Enter to finish, or press Enter then Ctrl+D)\n'));
626
+ const rl = readline.createInterface({ input, output });
627
+ rl.setPrompt('');
628
+ const lines = [];
629
+ publicKey = await new Promise((resolve) => {
630
+ rl.on('line', (line) => {
631
+ lines.push(line);
632
+ const content = lines.join('\n');
633
+ // Check if we have a complete key block and current line is empty
634
+ if (line.trim() === '' &&
635
+ content.includes('-----BEGIN PGP PUBLIC KEY BLOCK') &&
636
+ content.includes('-----END PGP PUBLIC KEY BLOCK')) {
637
+ rl.close();
638
+ resolve(content.trim());
639
+ }
640
+ });
641
+ rl.on('close', () => {
642
+ resolve(lines.join('\n'));
643
+ });
526
644
  });
527
- rl.on('close', () => {
528
- resolve(lines.join('\n'));
529
- });
530
- });
531
- }
532
- // Validate public key format
533
- if (!publicKey.includes('BEGIN PGP PUBLIC KEY BLOCK')) {
534
- console.log();
535
- showError('Invalid public key format');
536
- console.log();
537
- return null;
538
- }
539
- // Try to read the key to validate it
540
- try {
541
- await openpgp.readKey({ armoredKey: publicKey, config: weakKeyConfig });
542
- console.log();
543
- showSuccess('Valid public key');
544
- console.log();
545
- return publicKey;
546
- }
547
- catch (error) {
548
- console.log();
549
- showError(`Failed to read public key: ${error instanceof Error ? error.message : error}`);
550
- return null;
551
- }
552
- }
553
- // printBanner is imported from ui.ts
554
- function getEditorInstructions(editorCommand) {
555
- const instructions = {
556
- 'nano': 'Save: Ctrl+O, then Enter. Exit: Ctrl+X',
557
- 'vim': 'Save and exit: :wq | Cancel: :q!',
558
- 'nvim': 'Save and exit: :wq | Cancel: :q!',
559
- 'code': 'Save: Cmd/Ctrl+S, then close the editor tab',
560
- 'emacs': 'Save: Ctrl+X Ctrl+S | Exit: Ctrl+X Ctrl+C',
561
- 'open -e': 'Save: Cmd+S, then close the window',
562
- 'notepad': 'Save: Ctrl+S, then close the window',
563
- };
564
- return instructions[editorCommand] || 'Save and close the editor when done';
565
- }
566
- function clearPassphraseCache() {
567
- // Clear all cached passphrases from memory
568
- passphraseCache.clear();
569
- }
570
- async function main() {
571
- // Initialize database on first run
572
- if (!db) {
573
- db = await Db.init();
574
- keyManager = new KeyManager(db);
645
+ }
646
+ // Validate public key format
647
+ if (!publicKey.includes('BEGIN PGP PUBLIC KEY BLOCK')) {
648
+ console.log();
649
+ showError('Invalid public key format');
650
+ console.log();
651
+ return null;
652
+ }
653
+ // Try to read the key to validate it
654
+ try {
655
+ await openpgp.readKey({ armoredKey: publicKey, config: weakKeyConfig });
656
+ console.log();
657
+ showSuccess('Valid public key');
658
+ console.log();
659
+ return publicKey;
660
+ }
661
+ catch (error) {
662
+ console.log();
663
+ showError(`Failed to read public key: ${error instanceof Error ? error.message : error}`);
664
+ return null;
665
+ }
575
666
  }
576
- printBanner();
577
- // Check for default keypair on first run
578
- const hasKeypair = await keyManager.hasDefaultKeypair();
579
- if (!hasKeypair) {
580
- console.log();
581
- showWarning('No keypair found. Let\'s set up your first keypair.');
582
- console.log();
583
- await keyManager.setupFirstKeypair();
584
- console.log();
585
- showSuccess('Setup complete! You can now use the tool.');
586
- console.log();
667
+ // printBanner is imported from ui.ts
668
+ function getEditorInstructions(editorCommand) {
669
+ const instructions = {
670
+ nano: 'Save: Ctrl+O, then Enter. Exit: Ctrl+X',
671
+ vim: 'Save and exit: :wq | Cancel: :q!',
672
+ nvim: 'Save and exit: :wq | Cancel: :q!',
673
+ code: 'Save: Cmd/Ctrl+S, then close the editor tab',
674
+ emacs: 'Save: Ctrl+X Ctrl+S | Exit: Ctrl+X Ctrl+C',
675
+ 'open -e': 'Save: Cmd+S, then close the window',
676
+ notepad: 'Save: Ctrl+S, then close the window',
677
+ };
678
+ return instructions[editorCommand] || 'Save and close the editor when done';
587
679
  }
588
- // Build menu choices
589
- const menuChoices = [
590
- { name: `${icons.encrypt} Encrypt a message`, value: 'encrypt' },
591
- { name: `${icons.decrypt} Decrypt a message`, value: 'decrypt' },
592
- { name: `${icons.key} Manage keys`, value: 'keys' },
593
- ];
594
- // Check if installed globally and if update is available
595
- const installedVersion = getInstalledVersion();
596
- const latestVersion = getLatestVersion();
597
- if (!installedVersion) {
598
- // Not installed globally - offer to install
599
- menuChoices.push(new inquirer.Separator());
600
- menuChoices.push({
601
- name: `${icons.add} Install lpgp globally ${colors.muted('(for offline use)')}`,
602
- value: 'install',
603
- });
680
+ function clearPassphraseCache() {
681
+ // Clear all cached passphrases from memory
682
+ passphraseCache.clear();
604
683
  }
605
- else if (latestVersion && isOlderVersion(installedVersion, latestVersion)) {
606
- // Installed but outdated - offer to update
684
+ async function main() {
685
+ // Initialize database on first run
686
+ if (!db) {
687
+ db = await Db.init();
688
+ keyManager = new KeyManager(db);
689
+ }
690
+ printBanner();
691
+ // Check for default keypair on first run
692
+ const hasKeypair = await keyManager.hasDefaultKeypair();
693
+ if (!hasKeypair) {
694
+ console.log();
695
+ showWarning("No keypair found. Let's set up your first keypair.");
696
+ console.log();
697
+ await keyManager.setupFirstKeypair();
698
+ console.log();
699
+ showSuccess('Setup complete! You can now use the tool.');
700
+ console.log();
701
+ }
702
+ // Build menu choices
703
+ const menuChoices = [
704
+ { name: `${icons.encrypt} Encrypt a message`, value: 'encrypt' },
705
+ { name: `${icons.decrypt} Decrypt a message`, value: 'decrypt' },
706
+ { name: `${icons.key} Manage keys`, value: 'keys' },
707
+ ];
708
+ // Check if installed globally and if update is available
709
+ const installedVersion = getInstalledVersion();
710
+ const latestVersion = getLatestVersion();
711
+ if (!installedVersion) {
712
+ // Not installed globally - offer to install
713
+ menuChoices.push(new inquirer.Separator());
714
+ menuChoices.push({
715
+ name: `${icons.add} Install lpgp globally ${colors.muted('(for offline use)')}`,
716
+ value: 'install',
717
+ });
718
+ }
719
+ else if (latestVersion &&
720
+ isOlderVersion(installedVersion, latestVersion)) {
721
+ // Installed but outdated - offer to update
722
+ menuChoices.push(new inquirer.Separator());
723
+ menuChoices.push({
724
+ name: `${icons.add} Update lpgp ${colors.muted(`(${installedVersion} → ${latestVersion})`)}`,
725
+ value: 'update',
726
+ });
727
+ }
607
728
  menuChoices.push(new inquirer.Separator());
608
- menuChoices.push({
609
- name: `${icons.add} Update lpgp ${colors.muted(`(${installedVersion} → ${latestVersion})`)}`,
610
- value: 'update',
611
- });
612
- }
613
- menuChoices.push(new inquirer.Separator());
614
- menuChoices.push(exitChoice());
615
- const { action } = await escapeablePrompt([
616
- {
617
- type: 'list',
618
- name: 'action',
619
- message: promptMessage('What would you like to do?'),
620
- choices: menuChoices,
621
- },
622
- ]);
623
- if (action === 'exit') {
624
- clearPassphraseCache();
625
- console.clear();
626
- process.exit(0);
627
- }
628
- if (action === 'install' || action === 'update') {
629
- await installOrUpdateGlobally(action === 'update');
630
- await escapeablePrompt([
729
+ menuChoices.push(exitChoice());
730
+ const { action } = await escapeablePrompt([
631
731
  {
632
- type: 'input',
633
- name: 'continue',
634
- message: promptMessage('Press Enter to continue...'),
732
+ type: 'list',
733
+ name: 'action',
734
+ message: promptMessage('What would you like to do?'),
735
+ choices: menuChoices,
635
736
  },
636
737
  ]);
637
- return main();
638
- }
639
- if (action === 'keys') {
640
- await keyManager.showKeyManagementMenu();
641
- return main();
642
- }
643
- if (action === 'encrypt') {
644
- try {
645
- // Ask who to encrypt for
646
- const { recipient } = await escapeablePrompt([
738
+ if (action === 'exit') {
739
+ clearPassphraseCache();
740
+ console.clear();
741
+ process.exit(0);
742
+ }
743
+ if (action === 'install' || action === 'update') {
744
+ await installOrUpdateGlobally(action === 'update');
745
+ await escapeablePrompt([
647
746
  {
648
- type: 'list',
649
- name: 'recipient',
650
- message: promptMessage('Who do you want to encrypt this message for?'),
651
- choices: [
652
- { name: `${icons.contact} Someone else ${colors.muted('(use their public key)')}`, value: 'other' },
653
- { name: `${icons.multiple} Multiple recipients`, value: 'multiple' },
654
- { name: `${icons.key} Myself ${colors.muted('(use my public key)')}`, value: 'self' },
655
- new inquirer.Separator(),
656
- mainMenuChoice(),
657
- ],
747
+ type: 'input',
748
+ name: 'continue',
749
+ message: promptMessage('Press Enter to continue...'),
658
750
  },
659
751
  ]);
660
- if (recipient === 'back' || recipient === 'main-menu') {
661
- return main();
662
- }
663
- let recipientPublicKeys = [];
664
- let recipientNames = [];
665
- let isNewContact = false;
666
- // Handle multiple recipients
667
- if (recipient === 'multiple') {
668
- const recipients = await selectMultipleRecipients();
669
- if (recipients.length === 0) {
670
- console.log();
671
- showError('No recipients selected. Aborting.');
672
- console.log();
752
+ return main();
753
+ }
754
+ if (action === 'keys') {
755
+ await keyManager.showKeyManagementMenu();
756
+ return main();
757
+ }
758
+ if (action === 'encrypt') {
759
+ try {
760
+ // Ask who to encrypt for
761
+ const { recipient } = await escapeablePrompt([
762
+ {
763
+ type: 'list',
764
+ name: 'recipient',
765
+ message: promptMessage('Who do you want to encrypt this message for?'),
766
+ choices: [
767
+ {
768
+ name: `${icons.contact} Someone else ${colors.muted('(use their public key)')}`,
769
+ value: 'other',
770
+ },
771
+ {
772
+ name: `${icons.multiple} Multiple recipients`,
773
+ value: 'multiple',
774
+ },
775
+ {
776
+ name: `${icons.key} Myself ${colors.muted('(use my public key)')}`,
777
+ value: 'self',
778
+ },
779
+ new inquirer.Separator(),
780
+ mainMenuChoice(),
781
+ ],
782
+ },
783
+ ]);
784
+ if (recipient === 'back' || recipient === 'main-menu') {
673
785
  return main();
674
786
  }
675
- recipientPublicKeys = recipients.map((r) => r.publicKey);
676
- recipientNames = recipients.map((r) => r.name);
677
- // Show summary
678
- console.log(colors.primary('\nEncrypting for the following recipients:'));
679
- for (const name of recipientNames) {
680
- console.log(colors.muted(` • ${name}`));
681
- }
682
- console.log();
683
- }
684
- else if (recipient === 'other') {
685
- // Check if there are any saved contacts
686
- const contacts = db.select({ table: 'contact' });
687
- // Loop for recipient selection (allows going back from contacts submenu)
688
- recipientLoop: while (true) {
689
- // Build main menu choices
690
- const recipientChoices = [];
691
- if (contacts.length > 0) {
692
- recipientChoices.push({
693
- name: `${icons.contact} Saved contacts ${colors.muted(`(${contacts.length} available)`)}`,
694
- value: 'saved-contacts',
695
- });
696
- }
697
- recipientChoices.push({ name: `${icons.add} Use a new public key`, value: 'new' }, new inquirer.Separator(), mainMenuChoice());
698
- const { recipientSource } = await escapeablePrompt([
699
- {
700
- type: 'list',
701
- name: 'recipientSource',
702
- message: promptMessage('How would you like to specify the recipient?'),
703
- choices: recipientChoices,
704
- },
705
- ]);
706
- if (recipientSource === 'main' || recipientSource === 'main-menu') {
787
+ let recipientPublicKeys = [];
788
+ let recipientNames = [];
789
+ let isNewContact = false;
790
+ // Handle multiple recipients
791
+ if (recipient === 'multiple') {
792
+ const recipients = await selectMultipleRecipients();
793
+ if (recipients.length === 0) {
794
+ console.log();
795
+ showError('No recipients selected. Aborting.');
796
+ console.log();
707
797
  return main();
708
798
  }
709
- if (recipientSource === 'saved-contacts') {
710
- // Show contacts submenu
711
- const contactChoices = contacts.map((c) => ({
712
- name: `${icons.contact} ${c.name} ${colors.muted(`<${c.email}>`)}`,
713
- value: c.id,
714
- }));
715
- contactChoices.push(new inquirer.Separator(), backChoice(), mainMenuChoice(), new inquirer.Separator());
716
- const { contactChoice } = await escapeablePrompt([
799
+ recipientPublicKeys = recipients.map((r) => r.publicKey);
800
+ recipientNames = recipients.map((r) => r.name);
801
+ // Show summary
802
+ console.log(colors.primary('\nEncrypting for the following recipients:'));
803
+ for (const name of recipientNames) {
804
+ console.log(colors.muted(` • ${name}`));
805
+ }
806
+ console.log();
807
+ }
808
+ else if (recipient === 'other') {
809
+ // Check if there are any saved contacts
810
+ const contacts = db.select({ table: 'contact' });
811
+ // Loop for recipient selection (allows going back from contacts submenu)
812
+ recipientLoop: while (true) {
813
+ // Build main menu choices
814
+ const recipientChoices = [];
815
+ if (contacts.length > 0) {
816
+ recipientChoices.push({
817
+ name: `${icons.contact} Saved contacts ${colors.muted(`(${contacts.length} available)`)}`,
818
+ value: 'saved-contacts',
819
+ });
820
+ }
821
+ recipientChoices.push({ name: `${icons.add} Use a new public key`, value: 'new' }, new inquirer.Separator(), mainMenuChoice());
822
+ const { recipientSource } = await escapeablePrompt([
717
823
  {
718
824
  type: 'list',
719
- name: 'contactChoice',
720
- message: promptMessage('Select a contact:'),
721
- choices: contactChoices,
825
+ name: 'recipientSource',
826
+ message: promptMessage('How would you like to specify the recipient?'),
827
+ choices: recipientChoices,
722
828
  },
723
829
  ]);
724
- if (contactChoice === 'main' || contactChoice === 'main-menu') {
830
+ if (recipientSource === 'main' || recipientSource === 'main-menu') {
725
831
  return main();
726
832
  }
727
- if (contactChoice === 'back') {
728
- // Go back to recipient source selection
729
- continue recipientLoop;
833
+ if (recipientSource === 'saved-contacts') {
834
+ // Show contacts submenu
835
+ const contactChoices = contacts.map((c) => ({
836
+ name: `${icons.contact} ${c.name} ${colors.muted(`<${c.email}>`)}`,
837
+ value: c.id,
838
+ }));
839
+ contactChoices.push(new inquirer.Separator(), backChoice(), mainMenuChoice(), new inquirer.Separator());
840
+ const { contactChoice } = await escapeablePrompt([
841
+ {
842
+ type: 'list',
843
+ name: 'contactChoice',
844
+ message: promptMessage('Select a contact:'),
845
+ choices: contactChoices,
846
+ },
847
+ ]);
848
+ if (contactChoice === 'main' || contactChoice === 'main-menu') {
849
+ return main();
850
+ }
851
+ if (contactChoice === 'back') {
852
+ // Go back to recipient source selection
853
+ continue recipientLoop;
854
+ }
855
+ // Use saved contact
856
+ const selectedContact = contacts.find((c) => c.id === contactChoice);
857
+ if (selectedContact) {
858
+ recipientPublicKeys = [selectedContact.public_key];
859
+ break recipientLoop;
860
+ }
730
861
  }
731
- // Use saved contact
732
- const selectedContact = contacts.find((c) => c.id === contactChoice);
733
- if (selectedContact) {
734
- recipientPublicKeys = [selectedContact.public_key];
862
+ else if (recipientSource === 'new') {
863
+ const publicKey = await getRecipientPublicKey();
864
+ if (!publicKey) {
865
+ console.log();
866
+ showError('Could not get recipient public key. Aborting.');
867
+ console.log();
868
+ return main();
869
+ }
870
+ recipientPublicKeys = [publicKey];
871
+ isNewContact = true;
735
872
  break recipientLoop;
736
873
  }
737
874
  }
738
- else if (recipientSource === 'new') {
739
- const publicKey = await getRecipientPublicKey();
740
- if (!publicKey) {
741
- console.log();
742
- showError('Could not get recipient public key. Aborting.');
743
- console.log();
744
- return main();
745
- }
746
- recipientPublicKeys = [publicKey];
747
- isNewContact = true;
748
- break recipientLoop;
749
- }
750
- }
751
- }
752
- // Detect available editors
753
- const availableEditors = detectAvailableEditors();
754
- let message;
755
- // Loop for input method selection (allows going back from editor selection)
756
- inputMethodLoop: while (true) {
757
- // Ask for input method
758
- const inputChoices = [];
759
- // Always add clipboard option first
760
- inputChoices.push({
761
- name: `${icons.clipboard} Paste from clipboard`,
762
- value: 'clipboard',
763
- });
764
- if (availableEditors.length > 0) {
765
- inputChoices.push({ name: `${icons.editor} Use an editor`, value: 'editor' }, { name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`, value: 'inline' });
766
875
  }
767
- else {
876
+ // Detect available editors
877
+ const availableEditors = detectAvailableEditors();
878
+ let message;
879
+ // Loop for input method selection (allows going back from editor selection)
880
+ inputMethodLoop: while (true) {
881
+ // Ask for input method
882
+ const inputChoices = [];
883
+ // Always add clipboard option first
768
884
  inputChoices.push({
769
- name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`,
770
- value: 'inline',
885
+ name: `${icons.clipboard} Paste from clipboard`,
886
+ value: 'clipboard',
771
887
  });
772
- }
773
- // Add main menu option
774
- inputChoices.push(new inquirer.Separator(), mainMenuChoice());
775
- const { inputMethod } = await escapeablePrompt([
776
- {
777
- type: 'list',
778
- name: 'inputMethod',
779
- message: promptMessage('How would you like to enter your message?'),
780
- choices: inputChoices,
781
- },
782
- ]);
783
- if (inputMethod === 'back' || inputMethod === 'main-menu') {
784
- return main();
785
- }
786
- if (inputMethod === 'clipboard') {
787
- try {
788
- message = await clipboardy.read();
789
- if (!message || message.trim() === '') {
790
- console.log();
791
- showError('Clipboard is empty.');
792
- console.log();
793
- return main();
794
- }
795
- console.log();
796
- showSuccess('Message loaded from clipboard');
797
- console.log();
798
- break inputMethodLoop;
888
+ if (availableEditors.length > 0) {
889
+ inputChoices.push({ name: `${icons.editor} Use an editor`, value: 'editor' }, {
890
+ name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`,
891
+ value: 'inline',
892
+ });
799
893
  }
800
- catch (clipError) {
801
- console.log();
802
- showError(`Failed to read from clipboard: ${clipError}`);
803
- return main();
894
+ else {
895
+ inputChoices.push({
896
+ name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`,
897
+ value: 'inline',
898
+ });
804
899
  }
805
- }
806
- else if (inputMethod === 'editor') {
807
- // Let user choose editor
808
- const editorChoices = availableEditors.map((e) => ({
809
- name: `${icons.editor} ${e.name} ${colors.muted(`(${getEditorInstructions(e.command)})`)}`,
810
- value: e.command,
811
- }));
812
- editorChoices.push(new inquirer.Separator(), backChoice(), mainMenuChoice());
813
- const { selectedEditor } = await escapeablePrompt([
900
+ // Add main menu option
901
+ inputChoices.push(new inquirer.Separator(), mainMenuChoice());
902
+ const { inputMethod } = await escapeablePrompt([
814
903
  {
815
904
  type: 'list',
816
- name: 'selectedEditor',
817
- message: promptMessage('Choose your editor:'),
818
- choices: editorChoices,
905
+ name: 'inputMethod',
906
+ message: promptMessage('How would you like to enter your message?'),
907
+ choices: inputChoices,
819
908
  },
820
909
  ]);
821
- if (selectedEditor === 'back') {
822
- // Re-ask for input method
823
- continue inputMethodLoop;
824
- }
825
- if (selectedEditor === 'main-menu') {
910
+ if (inputMethod === 'back' || inputMethod === 'main-menu') {
826
911
  return main();
827
912
  }
828
- // Set the EDITOR environment variable before opening inquirer editor
829
- const originalEditor = process.env.EDITOR;
830
- const originalVisual = process.env.VISUAL;
831
- process.env.EDITOR = selectedEditor;
832
- process.env.VISUAL = selectedEditor;
833
- const editorName = availableEditors.find((e) => e.command === selectedEditor)?.name || 'editor';
834
- console.log(colors.muted('\nNote: The temp file is automatically deleted after encryption.\n'));
835
- try {
836
- const { editorInput } = await escapeablePrompt([
913
+ if (inputMethod === 'clipboard') {
914
+ try {
915
+ message = await clipboardy.read();
916
+ if (!message || message.trim() === '') {
917
+ console.log();
918
+ showError('Clipboard is empty.');
919
+ console.log();
920
+ return main();
921
+ }
922
+ console.log();
923
+ showSuccess('Message loaded from clipboard');
924
+ console.log();
925
+ break inputMethodLoop;
926
+ }
927
+ catch (clipError) {
928
+ console.log();
929
+ showError(`Failed to read from clipboard: ${clipError}`);
930
+ return main();
931
+ }
932
+ }
933
+ else if (inputMethod === 'editor') {
934
+ // Let user choose editor
935
+ const editorChoices = availableEditors.map((e) => ({
936
+ name: `${icons.editor} ${e.name} ${colors.muted(`(${getEditorInstructions(e.command)})`)}`,
937
+ value: e.command,
938
+ }));
939
+ editorChoices.push(new inquirer.Separator(), backChoice(), mainMenuChoice());
940
+ const { selectedEditor } = await escapeablePrompt([
837
941
  {
838
- type: 'editor',
839
- name: 'editorInput',
840
- message: promptMessage(`Press Enter to open ${editorName}:`),
841
- postfix: '.txt',
842
- waitForUseInput: false,
942
+ type: 'list',
943
+ name: 'selectedEditor',
944
+ message: promptMessage('Choose your editor:'),
945
+ choices: editorChoices,
843
946
  },
844
947
  ]);
845
- message = editorInput;
846
- break inputMethodLoop;
847
- }
848
- finally {
849
- // Restore original environment variables
850
- if (originalEditor !== undefined) {
851
- process.env.EDITOR = originalEditor;
948
+ if (selectedEditor === 'back') {
949
+ // Re-ask for input method
950
+ continue inputMethodLoop;
852
951
  }
853
- else {
854
- delete process.env.EDITOR;
952
+ if (selectedEditor === 'main-menu') {
953
+ return main();
855
954
  }
856
- if (originalVisual !== undefined) {
857
- process.env.VISUAL = originalVisual;
955
+ // Set the EDITOR environment variable before opening inquirer editor
956
+ const originalEditor = process.env.EDITOR;
957
+ const originalVisual = process.env.VISUAL;
958
+ process.env.EDITOR = selectedEditor;
959
+ process.env.VISUAL = selectedEditor;
960
+ const editorName = availableEditors.find((e) => e.command === selectedEditor)
961
+ ?.name || 'editor';
962
+ console.log(colors.muted('\nNote: The temp file is automatically deleted after encryption.\n'));
963
+ try {
964
+ const { editorInput } = await escapeablePrompt([
965
+ {
966
+ type: 'editor',
967
+ name: 'editorInput',
968
+ message: promptMessage(`Press Enter to open ${editorName}:`),
969
+ postfix: '.txt',
970
+ waitForUseInput: false,
971
+ },
972
+ ]);
973
+ message = editorInput;
974
+ break inputMethodLoop;
858
975
  }
859
- else {
860
- delete process.env.VISUAL;
976
+ finally {
977
+ // Restore original environment variables
978
+ if (originalEditor !== undefined) {
979
+ process.env.EDITOR = originalEditor;
980
+ }
981
+ else {
982
+ delete process.env.EDITOR;
983
+ }
984
+ if (originalVisual !== undefined) {
985
+ process.env.VISUAL = originalVisual;
986
+ }
987
+ else {
988
+ delete process.env.VISUAL;
989
+ }
861
990
  }
862
991
  }
992
+ else {
993
+ message = await readInlineMultilineInput('Enter your message:');
994
+ break inputMethodLoop;
995
+ }
863
996
  }
864
- else {
865
- message = await readInlineMultilineInput('Enter your message:');
866
- break inputMethodLoop;
997
+ if (!message || message.trim() === '') {
998
+ console.log();
999
+ showError('No message provided. Aborting.');
1000
+ console.log();
1001
+ return main();
867
1002
  }
868
- }
869
- if (!message || message.trim() === '') {
870
- console.log();
871
- showError('No message provided. Aborting.');
872
- console.log();
873
- return main();
874
- }
875
- console.log();
876
- showLoading('Encrypting message...');
877
- console.log();
878
- const encrypted = await encryptMessage(message, recipientPublicKeys.length > 0 ? recipientPublicKeys : undefined);
879
- // Clear screen, show encrypted message, then clipboard status
880
- console.clear();
881
- printBanner();
882
- console.log(colors.successBold('Encrypted Message:\n'));
883
- printDivider();
884
- console.log(encrypted);
885
- printDivider();
886
- // Copy to clipboard and show status below the message
887
- try {
888
- await clipboardy.write(encrypted);
889
- console.log();
890
- showSuccess('Encrypted message copied to clipboard');
891
1003
  console.log();
892
- }
893
- catch (clipError) {
894
- console.log();
895
- showWarning('Clipboard unavailable');
1004
+ showLoading('Encrypting message...');
896
1005
  console.log();
897
- }
898
- // Offer to save the contact if it's a new public key (single recipient only)
899
- const newPublicKey = recipientPublicKeys[0];
900
- if (isNewContact && newPublicKey !== undefined && recipientPublicKeys.length === 1) {
901
- const { saveContact } = await escapeablePrompt([
902
- {
903
- type: 'confirm',
904
- name: 'saveContact',
905
- message: promptMessage('Would you like to save this contact for future use?'),
906
- default: true,
907
- },
908
- ]);
909
- if (saveContact) {
910
- try {
911
- // Extract key information
912
- const keyInfo = await extractPublicKeyInfo(newPublicKey);
913
- // Prompt for contact name
914
- const defaultName = (keyInfo.email || 'unknown').split('@')[0] || 'Contact';
915
- const answers = await escapeablePrompt([
916
- {
917
- type: 'input',
918
- name: 'contactName',
919
- message: promptMessage('Contact name:'),
920
- default: defaultName,
921
- validate: (input) => input.trim().length > 0 || 'Name cannot be empty',
922
- },
923
- ]);
924
- const contactName = answers.contactName;
925
- // Check if contact already exists by fingerprint
926
- const existingContacts = db.select({
927
- table: 'contact',
928
- where: { key: 'fingerprint', compare: 'is', value: keyInfo.fingerprint },
929
- });
930
- if (existingContacts.length > 0) {
931
- console.log();
932
- showWarning('This contact already exists.');
933
- console.log();
934
- }
935
- else {
936
- // Save the contact
937
- db.insert('contact', {
938
- name: contactName.trim(),
939
- email: keyInfo.email,
940
- fingerprint: keyInfo.fingerprint,
941
- public_key: newPublicKey,
942
- algorithm: keyInfo.algorithm,
943
- key_size: keyInfo.keySize,
944
- trusted: false,
945
- last_verified_at: null,
946
- notes: null,
947
- expires_at: keyInfo.expiresAt,
948
- revoked: false,
1006
+ const encrypted = await encryptMessage(message, recipientPublicKeys.length > 0 ? recipientPublicKeys : undefined);
1007
+ // Clear screen, show encrypted message, then clipboard status
1008
+ console.clear();
1009
+ printBanner();
1010
+ console.log(colors.successBold('Encrypted Message:\n'));
1011
+ printDivider();
1012
+ console.log(encrypted);
1013
+ printDivider();
1014
+ // Copy to clipboard and show status below the message
1015
+ try {
1016
+ await clipboardy.write(encrypted);
1017
+ console.log();
1018
+ showSuccess('Encrypted message copied to clipboard');
1019
+ console.log();
1020
+ }
1021
+ catch (clipError) {
1022
+ console.log();
1023
+ showWarning('Clipboard unavailable');
1024
+ console.log();
1025
+ }
1026
+ // Offer to save the contact if it's a new public key (single recipient only)
1027
+ const newPublicKey = recipientPublicKeys[0];
1028
+ if (isNewContact &&
1029
+ newPublicKey !== undefined &&
1030
+ recipientPublicKeys.length === 1) {
1031
+ const { saveContact } = await escapeablePrompt([
1032
+ {
1033
+ type: 'confirm',
1034
+ name: 'saveContact',
1035
+ message: promptMessage('Would you like to save this contact for future use?'),
1036
+ default: true,
1037
+ },
1038
+ ]);
1039
+ if (saveContact) {
1040
+ try {
1041
+ // Extract key information
1042
+ const keyInfo = await extractPublicKeyInfo(newPublicKey);
1043
+ // Prompt for contact name
1044
+ const defaultName = (keyInfo.email || 'unknown').split('@')[0] || 'Contact';
1045
+ const answers = await escapeablePrompt([
1046
+ {
1047
+ type: 'input',
1048
+ name: 'contactName',
1049
+ message: promptMessage('Contact name:'),
1050
+ default: defaultName,
1051
+ validate: (input) => input.trim().length > 0 || 'Name cannot be empty',
1052
+ },
1053
+ ]);
1054
+ const contactName = answers.contactName;
1055
+ // Check if contact already exists by fingerprint
1056
+ const existingContacts = db.select({
1057
+ table: 'contact',
1058
+ where: {
1059
+ key: 'fingerprint',
1060
+ compare: 'is',
1061
+ value: keyInfo.fingerprint,
1062
+ },
949
1063
  });
1064
+ if (existingContacts.length > 0) {
1065
+ console.log();
1066
+ showWarning('This contact already exists.');
1067
+ console.log();
1068
+ }
1069
+ else {
1070
+ // Save the contact
1071
+ db.insert('contact', {
1072
+ name: contactName.trim(),
1073
+ email: keyInfo.email,
1074
+ fingerprint: keyInfo.fingerprint,
1075
+ public_key: newPublicKey,
1076
+ algorithm: keyInfo.algorithm,
1077
+ key_size: keyInfo.keySize,
1078
+ trusted: false,
1079
+ last_verified_at: null,
1080
+ notes: null,
1081
+ expires_at: keyInfo.expiresAt,
1082
+ revoked: false,
1083
+ });
1084
+ console.log();
1085
+ showSuccess(`Contact "${contactName}" saved successfully!`);
1086
+ console.log();
1087
+ }
1088
+ }
1089
+ catch (error) {
950
1090
  console.log();
951
- showSuccess(`Contact "${contactName}" saved successfully!`);
952
- console.log();
1091
+ showError(`Failed to save contact: ${error instanceof Error ? error.message : error}`);
953
1092
  }
954
1093
  }
955
- catch (error) {
956
- console.log();
957
- showError(`Failed to save contact: ${error instanceof Error ? error.message : error}`);
958
- }
959
1094
  }
960
1095
  }
1096
+ catch (error) {
1097
+ // Re-throw escape errors to be handled by the main loop
1098
+ if (error instanceof EscapeError)
1099
+ throw error;
1100
+ console.log();
1101
+ showError(`Encryption failed: ${error instanceof Error ? error.message : error}`);
1102
+ }
961
1103
  }
962
- catch (error) {
963
- // Re-throw escape errors to be handled by the main loop
964
- if (error instanceof EscapeError)
965
- throw error;
966
- console.log();
967
- showError(`Encryption failed: ${error instanceof Error ? error.message : error}`);
968
- }
969
- }
970
- else if (action === 'decrypt') {
971
- try {
972
- // Detect available editors
973
- const availableEditors = detectAvailableEditors();
974
- let encrypted;
975
- // Loop for input method selection (allows going back from editor selection)
976
- decryptInputLoop: while (true) {
977
- // Ask for input method
978
- const inputChoices = [];
979
- // Always add clipboard option first
980
- inputChoices.push({
981
- name: `${icons.clipboard} Paste from clipboard`,
982
- value: 'clipboard',
983
- });
984
- if (availableEditors.length > 0) {
985
- inputChoices.push({ name: `${icons.editor} Use an editor`, value: 'editor' }, { name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`, value: 'inline' });
986
- }
987
- else {
1104
+ else if (action === 'decrypt') {
1105
+ try {
1106
+ // Detect available editors
1107
+ const availableEditors = detectAvailableEditors();
1108
+ let encrypted;
1109
+ // Loop for input method selection (allows going back from editor selection)
1110
+ decryptInputLoop: while (true) {
1111
+ // Ask for input method
1112
+ const inputChoices = [];
1113
+ // Always add clipboard option first
988
1114
  inputChoices.push({
989
- name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`,
990
- value: 'inline',
1115
+ name: `${icons.clipboard} Paste from clipboard`,
1116
+ value: 'clipboard',
991
1117
  });
992
- }
993
- // Add main menu option
994
- inputChoices.push(new inquirer.Separator(), mainMenuChoice());
995
- const { inputMethod } = await escapeablePrompt([
996
- {
997
- type: 'list',
998
- name: 'inputMethod',
999
- message: promptMessage('How would you like to enter the encrypted message?'),
1000
- choices: inputChoices,
1001
- },
1002
- ]);
1003
- if (inputMethod === 'back' || inputMethod === 'main-menu') {
1004
- return main();
1005
- }
1006
- if (inputMethod === 'clipboard') {
1007
- try {
1008
- encrypted = await clipboardy.read();
1009
- if (!encrypted || encrypted.trim() === '') {
1010
- console.log();
1011
- showError('Clipboard is empty.');
1012
- console.log();
1013
- return main();
1014
- }
1015
- console.log();
1016
- showSuccess('Encrypted message loaded from clipboard');
1017
- console.log();
1018
- break decryptInputLoop;
1118
+ if (availableEditors.length > 0) {
1119
+ inputChoices.push({ name: `${icons.editor} Use an editor`, value: 'editor' }, {
1120
+ name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`,
1121
+ value: 'inline',
1122
+ });
1019
1123
  }
1020
- catch (clipError) {
1021
- console.log();
1022
- showError(`Failed to read from clipboard: ${clipError}`);
1023
- return main();
1124
+ else {
1125
+ inputChoices.push({
1126
+ name: `${icons.inline} Type inline ${colors.muted('(Enter, then Ctrl+D to finish)')}`,
1127
+ value: 'inline',
1128
+ });
1024
1129
  }
1025
- }
1026
- else if (inputMethod === 'editor') {
1027
- // Let user choose editor
1028
- const editorChoices = availableEditors.map((e) => ({
1029
- name: `${icons.editor} ${e.name} ${colors.muted(`(${getEditorInstructions(e.command)})`)}`,
1030
- value: e.command,
1031
- }));
1032
- editorChoices.push(new inquirer.Separator(), backChoice(), mainMenuChoice());
1033
- const { selectedEditor } = await escapeablePrompt([
1130
+ // Add main menu option
1131
+ inputChoices.push(new inquirer.Separator(), mainMenuChoice());
1132
+ const { inputMethod } = await escapeablePrompt([
1034
1133
  {
1035
1134
  type: 'list',
1036
- name: 'selectedEditor',
1037
- message: promptMessage('Choose your editor:'),
1038
- choices: editorChoices,
1135
+ name: 'inputMethod',
1136
+ message: promptMessage('How would you like to enter the encrypted message?'),
1137
+ choices: inputChoices,
1039
1138
  },
1040
1139
  ]);
1041
- if (selectedEditor === 'back') {
1042
- // Re-ask for input method
1043
- continue decryptInputLoop;
1044
- }
1045
- if (selectedEditor === 'main-menu') {
1140
+ if (inputMethod === 'back' || inputMethod === 'main-menu') {
1046
1141
  return main();
1047
1142
  }
1048
- // Set the EDITOR environment variable before opening inquirer editor
1049
- const originalEditor = process.env.EDITOR;
1050
- const originalVisual = process.env.VISUAL;
1051
- process.env.EDITOR = selectedEditor;
1052
- process.env.VISUAL = selectedEditor;
1053
- const editorName = availableEditors.find((e) => e.command === selectedEditor)?.name || 'editor';
1054
- console.log(colors.muted('\nNote: The temp file is automatically deleted after decryption.\n'));
1055
- try {
1056
- const { editorInput } = await escapeablePrompt([
1143
+ if (inputMethod === 'clipboard') {
1144
+ try {
1145
+ encrypted = await clipboardy.read();
1146
+ if (!encrypted || encrypted.trim() === '') {
1147
+ console.log();
1148
+ showError('Clipboard is empty.');
1149
+ console.log();
1150
+ return main();
1151
+ }
1152
+ console.log();
1153
+ showSuccess('Encrypted message loaded from clipboard');
1154
+ console.log();
1155
+ break decryptInputLoop;
1156
+ }
1157
+ catch (clipError) {
1158
+ console.log();
1159
+ showError(`Failed to read from clipboard: ${clipError}`);
1160
+ return main();
1161
+ }
1162
+ }
1163
+ else if (inputMethod === 'editor') {
1164
+ // Let user choose editor
1165
+ const editorChoices = availableEditors.map((e) => ({
1166
+ name: `${icons.editor} ${e.name} ${colors.muted(`(${getEditorInstructions(e.command)})`)}`,
1167
+ value: e.command,
1168
+ }));
1169
+ editorChoices.push(new inquirer.Separator(), backChoice(), mainMenuChoice());
1170
+ const { selectedEditor } = await escapeablePrompt([
1057
1171
  {
1058
- type: 'editor',
1059
- name: 'editorInput',
1060
- message: promptMessage(`Press Enter to open ${editorName}:`),
1061
- postfix: '.txt',
1062
- waitForUseInput: false,
1172
+ type: 'list',
1173
+ name: 'selectedEditor',
1174
+ message: promptMessage('Choose your editor:'),
1175
+ choices: editorChoices,
1063
1176
  },
1064
1177
  ]);
1065
- encrypted = editorInput;
1066
- break decryptInputLoop;
1067
- }
1068
- finally {
1069
- // Restore original environment variables
1070
- if (originalEditor !== undefined) {
1071
- process.env.EDITOR = originalEditor;
1178
+ if (selectedEditor === 'back') {
1179
+ // Re-ask for input method
1180
+ continue decryptInputLoop;
1072
1181
  }
1073
- else {
1074
- delete process.env.EDITOR;
1182
+ if (selectedEditor === 'main-menu') {
1183
+ return main();
1075
1184
  }
1076
- if (originalVisual !== undefined) {
1077
- process.env.VISUAL = originalVisual;
1185
+ // Set the EDITOR environment variable before opening inquirer editor
1186
+ const originalEditor = process.env.EDITOR;
1187
+ const originalVisual = process.env.VISUAL;
1188
+ process.env.EDITOR = selectedEditor;
1189
+ process.env.VISUAL = selectedEditor;
1190
+ const editorName = availableEditors.find((e) => e.command === selectedEditor)
1191
+ ?.name || 'editor';
1192
+ console.log(colors.muted('\nNote: The temp file is automatically deleted after decryption.\n'));
1193
+ try {
1194
+ const { editorInput } = await escapeablePrompt([
1195
+ {
1196
+ type: 'editor',
1197
+ name: 'editorInput',
1198
+ message: promptMessage(`Press Enter to open ${editorName}:`),
1199
+ postfix: '.txt',
1200
+ waitForUseInput: false,
1201
+ },
1202
+ ]);
1203
+ encrypted = editorInput;
1204
+ break decryptInputLoop;
1078
1205
  }
1079
- else {
1080
- delete process.env.VISUAL;
1206
+ finally {
1207
+ // Restore original environment variables
1208
+ if (originalEditor !== undefined) {
1209
+ process.env.EDITOR = originalEditor;
1210
+ }
1211
+ else {
1212
+ delete process.env.EDITOR;
1213
+ }
1214
+ if (originalVisual !== undefined) {
1215
+ process.env.VISUAL = originalVisual;
1216
+ }
1217
+ else {
1218
+ delete process.env.VISUAL;
1219
+ }
1081
1220
  }
1082
1221
  }
1222
+ else {
1223
+ encrypted = await readInlineMultilineInput('Paste the encrypted message:');
1224
+ break decryptInputLoop;
1225
+ }
1083
1226
  }
1084
- else {
1085
- encrypted = await readInlineMultilineInput('Paste the encrypted message:');
1086
- break decryptInputLoop;
1227
+ if (!encrypted || encrypted.trim() === '') {
1228
+ console.log();
1229
+ showError('No encrypted message provided. Aborting.');
1230
+ console.log();
1231
+ return main();
1087
1232
  }
1088
- }
1089
- if (!encrypted || encrypted.trim() === '') {
1090
- console.log();
1091
- showError('No encrypted message provided. Aborting.');
1092
- console.log();
1093
- return main();
1094
- }
1095
- console.log();
1096
- showLoading('Decrypting message...');
1097
- console.log();
1098
- const decrypted = await decryptMessage(encrypted);
1099
- // Clear screen, show decrypted message, then clipboard status
1100
- console.clear();
1101
- printBanner();
1102
- console.log(colors.successBold('Decrypted Message:\n'));
1103
- printDivider();
1104
- console.log(decrypted);
1105
- printDivider();
1106
- // Copy to clipboard and show status below the message
1107
- try {
1108
- await clipboardy.write(decrypted);
1109
1233
  console.log();
1110
- showSuccess('Decrypted message copied to clipboard');
1234
+ showLoading('Decrypting message...');
1111
1235
  console.log();
1236
+ const decrypted = await decryptMessage(encrypted);
1237
+ // Clear screen, show decrypted message, then clipboard status
1238
+ console.clear();
1239
+ printBanner();
1240
+ console.log(colors.successBold('Decrypted Message:\n'));
1241
+ printDivider();
1242
+ console.log(decrypted);
1243
+ printDivider();
1244
+ // Copy to clipboard and show status below the message
1245
+ try {
1246
+ await clipboardy.write(decrypted);
1247
+ console.log();
1248
+ showSuccess('Decrypted message copied to clipboard');
1249
+ console.log();
1250
+ }
1251
+ catch (clipError) {
1252
+ console.log();
1253
+ showWarning('Clipboard unavailable');
1254
+ console.log();
1255
+ }
1256
+ // Wait for user to press Enter before continuing
1257
+ await escapeablePrompt([
1258
+ {
1259
+ type: 'input',
1260
+ name: 'continue',
1261
+ message: colors.muted('Press Enter to continue...'),
1262
+ },
1263
+ ]);
1112
1264
  }
1113
- catch (clipError) {
1114
- console.log();
1115
- showWarning('Clipboard unavailable');
1265
+ catch (error) {
1266
+ // Re-throw escape errors to be handled by the main loop
1267
+ if (error instanceof EscapeError)
1268
+ throw error;
1116
1269
  console.log();
1270
+ showError(`Decryption failed: ${error instanceof Error ? error.message : error}`);
1117
1271
  }
1118
- // Wait for user to press Enter before continuing
1119
- await escapeablePrompt([
1120
- {
1121
- type: 'input',
1122
- name: 'continue',
1123
- message: colors.muted('Press Enter to continue...'),
1124
- },
1125
- ]);
1126
1272
  }
1127
- catch (error) {
1128
- // Re-throw escape errors to be handled by the main loop
1129
- if (error instanceof EscapeError)
1130
- throw error;
1131
- console.log();
1132
- showError(`Decryption failed: ${error instanceof Error ? error.message : error}`);
1273
+ // Ask if user wants to continue
1274
+ const { nextAction } = await escapeablePrompt([
1275
+ {
1276
+ type: 'list',
1277
+ name: 'nextAction',
1278
+ message: promptMessage('What would you like to do next?'),
1279
+ choices: [
1280
+ {
1281
+ name: `${icons.loop} Perform another operation`,
1282
+ value: 'continue',
1283
+ },
1284
+ exitChoice(),
1285
+ ],
1286
+ },
1287
+ ]);
1288
+ if (nextAction === 'continue') {
1289
+ await main();
1290
+ }
1291
+ else {
1292
+ clearPassphraseCache();
1293
+ console.clear();
1133
1294
  }
1134
1295
  }
1135
- // Ask if user wants to continue
1136
- const { nextAction } = await escapeablePrompt([
1137
- {
1138
- type: 'list',
1139
- name: 'nextAction',
1140
- message: promptMessage('What would you like to do next?'),
1141
- choices: [
1142
- { name: `${icons.loop} Perform another operation`, value: 'continue' },
1143
- exitChoice(),
1144
- ],
1145
- },
1146
- ]);
1147
- if (nextAction === 'continue') {
1148
- await main();
1149
- }
1150
- else {
1296
+ // Graceful exit on Ctrl+C
1297
+ process.on('SIGINT', () => {
1151
1298
  clearPassphraseCache();
1152
1299
  console.clear();
1153
- }
1154
- }
1155
- // Graceful exit on Ctrl+C
1156
- process.on('SIGINT', () => {
1157
- clearPassphraseCache();
1158
- console.clear();
1159
- process.exit(0);
1160
- });
1161
- // Enable global escape key handling and run menu in a loop
1162
- enableGlobalEscape();
1163
- async function runApp() {
1164
- while (true) {
1165
- try {
1166
- await main();
1167
- }
1168
- catch (error) {
1169
- const e = error;
1170
- // If escape was pressed, just restart the menu
1171
- if (error instanceof EscapeError ||
1172
- checkAndResetEscape() ||
1173
- e.message?.includes('prompt was closed')) {
1174
- continue;
1300
+ process.exit(0);
1301
+ });
1302
+ // Enable global escape key handling and run menu in a loop
1303
+ enableGlobalEscape();
1304
+ async function runApp() {
1305
+ while (true) {
1306
+ try {
1307
+ await main();
1175
1308
  }
1176
- // Handle Ctrl+C gracefully (inquirer throws ExitPromptError)
1177
- if (e.message?.includes('force closed the prompt')) {
1309
+ catch (error) {
1310
+ const e = error;
1311
+ // If escape was pressed, just restart the menu
1312
+ if (error instanceof EscapeError ||
1313
+ checkAndResetEscape() ||
1314
+ e.message?.includes('prompt was closed')) {
1315
+ continue;
1316
+ }
1317
+ // Handle Ctrl+C gracefully (inquirer throws ExitPromptError)
1318
+ if (e.message?.includes('force closed the prompt')) {
1319
+ clearPassphraseCache();
1320
+ console.clear();
1321
+ process.exit(0);
1322
+ }
1323
+ // Handle other errors
1178
1324
  clearPassphraseCache();
1179
1325
  console.clear();
1180
- process.exit(0);
1326
+ showError(`Error: ${e.message || error}`);
1327
+ process.exit(1);
1181
1328
  }
1182
- // Handle other errors
1183
- clearPassphraseCache();
1184
- console.clear();
1185
- showError(`Error: ${e.message || error}`);
1186
- process.exit(1);
1187
1329
  }
1188
1330
  }
1189
- }
1190
- runApp();
1331
+ runApp();
1332
+ } // End of startInteractiveMode
1191
1333
  //# sourceMappingURL=pgp-tool.js.map