refactor: use async func to decrypt

This commit is contained in:
quenousimporte 2023-09-21 21:45:09 +02:00
parent 8024a513b1
commit 78e68bbef2
1 changed files with 28 additions and 34 deletions

28
main.js
View File

@ -421,6 +421,11 @@ function encryptstring(str)
function decryptstring(str) function decryptstring(str)
{ {
if (!str.startsWith("-----BEGIN PGP MESSAGE-----"))
{
console.log("string is not encrypted");
return Promise.resolve(str);
}
console.log("decrypting..."); console.log("decrypting...");
var key = localStorage.getItem("pgpkeys").split("-----END PGP PUBLIC KEY BLOCK-----")[1]; var key = localStorage.getItem("pgpkeys").split("-----END PGP PUBLIC KEY BLOCK-----")[1];
var privateKey = null; var privateKey = null;
@ -1499,7 +1504,7 @@ function checkevents()
.catch(remotecallfailed); .catch(remotecallfailed);
} }
async function queryremote(params) function queryremote(params)
{ {
return new Promise( (apply, failed) => { return new Promise( (apply, failed) => {
@ -1526,7 +1531,7 @@ async function queryremote(params)
failed("XMLHttpRequest error"); failed("XMLHttpRequest error");
} }
xhr.onload = async function() xhr.onload = function()
{ {
if (xhr.status !== 200) if (xhr.status !== 200)
{ {
@ -1537,22 +1542,10 @@ async function queryremote(params)
var data = {}; var data = {};
try try
{ {
var response = xhr.responseText; return decryptstring(xhr.responseText)
if (localStorage.getItem("pgpkeys") && response.startsWith("-----BEGIN PGP MESSAGE-----")) .then(decrypted =>
{ {
console.log("decrypting..."); data = JSON.parse(decrypted);
var key = localStorage.getItem("pgpkeys").split("-----END PGP PUBLIC KEY BLOCK-----")[1];
var privateKey = await openpgp.readKey({ armoredKey: key });
var decrypted = await openpgp.decrypt({
message: await openpgp.readMessage({ armoredMessage: response }),
decryptionKeys: privateKey });
const chunks = [];
for await (const chunk of decrypted.data) {
chunks.push(chunk);
}
response = chunks.join('');
}
data = JSON.parse(response);
if (data.error) if (data.error)
{ {
@ -1576,6 +1569,7 @@ async function queryremote(params)
notepage.style.display = "table"; notepage.style.display = "table";
apply(data); apply(data);
} }
});
} }
catch(error) catch(error)
{ {