This repository has been archived by the owner on Dec 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpg.js
103 lines (95 loc) · 2.48 KB
/
gpg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// execa based interface to gpg
const execa = require('execa');
const execaSync = execa.commandSync;
const { $ } = require('zx');
$.verbose = false;
// each method will fail silently and not obstruct the program
// although a log message will be issued
const encryptMessage = async (message, recipientId) => {
// should return an encrypted message
let encryptedMessage;
try {
encryptedMessage =
await $`echo ${message} | gpg --always-trust --encrypt -r ${recipientId} -a`;
} catch (e) {
// log this to the logger
console.log(e);
return null;
}
return encryptedMessage.stdout;
};
// should return a decrypted message
// the message was intended for my private key
const decryptMessage = async (message) => {
let decryptedMessage;
try {
decryptedMessage =
await $`echo ${message} | gpg --always-trust --decrypt -a`;
} catch (e) {
console.error(e);
return null;
}
return decryptedMessage.stdout.trim();
};
const myGpgKey = () => {
const re = /<(\S+@\S+\.\S+)>/gim;
const myKeysCommand = `gpg -K`;
let myKeysResult;
try {
myKeysResult = execaSync(myKeysCommand).stdout.matchAll(re);
} catch (e) {
console.error(e);
return null;
}
const myKeysArray = Array.from(myKeysResult);
const myKeys = myKeysArray.map((match) => match[1]);
return getPublicKey(myKeys[0]);
};
// returns a public key for specified id
const getPublicKey = (id) => {
const gpgCommand = `gpg --export -a ${id}`;
let result;
try {
result = execaSync(gpgCommand).stdout;
} catch (e) {
console.log(e);
return null;
}
return result;
};
// lists all the available gpg keys
const listRecipients = () => {
const gpgCommand = `gpg --list-keys`;
let result;
try {
result = execaSync(gpgCommand).stdout;
} catch (e) {
console.log(e);
return null;
}
// pull out all the email addresses
const re = /<(\S+@\S+\.\S+)>/gim;
const matchesIterator = result.matchAll(re);
const matches2DArray = Array.from(matchesIterator);
const myKeysCommand = `gpg -K`;
let myKeysResult;
try {
myKeysResult = execaSync(myKeysCommand).stdout.matchAll(re);
} catch (e) {
console.log(e);
return null;
}
const myKeysArray = Array.from(myKeysResult);
const myKeys = myKeysArray.map((match) => match[1]);
return matches2DArray
.map((match) => match[1])
.filter((key) => myKeys.indexOf(key) === -1);
};
const gpg = {
encryptMessage,
decryptMessage,
listRecipients,
myGpgKey,
getPublicKey,
};
module.exports = gpg;