Add OpenPGP mail encryption: decrypt, verify, encrypt, sign and contact keyring, v0.3.0
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
+150
-1
@@ -38,12 +38,45 @@ async function unlock(armoredPrivateKey, passphrase) {
|
||||
}
|
||||
}
|
||||
|
||||
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
|
||||
const DEFAULT_CACHE_MINUTES = 10;
|
||||
|
||||
function contactInfo(entry) {
|
||||
return {
|
||||
fingerprint: entry.fingerprint,
|
||||
name: entry.name,
|
||||
emails: entry.emails,
|
||||
trust: entry.trust,
|
||||
source: entry.source,
|
||||
addedAt: entry.addedAt
|
||||
};
|
||||
}
|
||||
|
||||
async function readPublicOnly(value) {
|
||||
const armored = readArmored(value);
|
||||
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('That file contains a private key. Import public keys only.');
|
||||
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP public key.');
|
||||
});
|
||||
await key.getPrimaryUser().catch(() => {
|
||||
throw new Error('That key is expired, revoked or has no valid user ID.');
|
||||
});
|
||||
return key;
|
||||
}
|
||||
|
||||
async function keyEmails(key) {
|
||||
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||
}
|
||||
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
|
||||
// (the desktop app wraps it with the OS credential store before writing it).
|
||||
function createKeyStore(storage) {
|
||||
async function read() {
|
||||
const data = await storage.load();
|
||||
return { keys: Array.isArray(data?.keys) ? data.keys : [] };
|
||||
return {
|
||||
keys: Array.isArray(data?.keys) ? data.keys : [],
|
||||
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
|
||||
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
|
||||
};
|
||||
}
|
||||
|
||||
async function add(entry) {
|
||||
@@ -56,6 +89,122 @@ function createKeyStore(storage) {
|
||||
}
|
||||
|
||||
return {
|
||||
async listContacts() {
|
||||
return (await read()).contacts.map(contactInfo);
|
||||
},
|
||||
|
||||
async addContact({ armoredKey, source = 'import' }) {
|
||||
const key = await readPublicOnly(armoredKey);
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
const emails = await keyEmails(key);
|
||||
const data = await read();
|
||||
if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.');
|
||||
if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.');
|
||||
const user = await key.getPrimaryUser();
|
||||
const replaces = data.contacts
|
||||
.filter(entry => entry.emails.some(email => emails.includes(email)))
|
||||
.map(entry => entry.fingerprint);
|
||||
const entry = {
|
||||
fingerprint,
|
||||
name: user.user.userID?.name || '',
|
||||
emails,
|
||||
trust: 'unknown',
|
||||
source: ['import', 'message', 'paste'].includes(source) ? source : 'import',
|
||||
addedAt: Date.now(),
|
||||
publicKey: key.armor()
|
||||
};
|
||||
data.contacts.push(entry);
|
||||
await storage.save(data);
|
||||
return { contact: contactInfo(entry), keyChangedFrom: replaces };
|
||||
},
|
||||
|
||||
async setTrust(fingerprint, trust) {
|
||||
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
|
||||
const data = await read();
|
||||
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That contact key was not found.');
|
||||
entry.trust = trust;
|
||||
await storage.save(data);
|
||||
return contactInfo(entry);
|
||||
},
|
||||
|
||||
async removeContact(fingerprint) {
|
||||
const data = await read();
|
||||
if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.');
|
||||
data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint);
|
||||
await storage.save(data);
|
||||
return { removed: true };
|
||||
},
|
||||
|
||||
async exportContact(fingerprint) {
|
||||
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That contact key was not found.');
|
||||
return entry.publicKey;
|
||||
},
|
||||
|
||||
// Resolves public keys for recipient addresses (contacts and own keys).
|
||||
async findRecipientKeys(addresses) {
|
||||
const data = await read();
|
||||
const pool = [
|
||||
...data.contacts.map(entry => ({ ...entry, own: false })),
|
||||
...data.keys.map(entry => ({ fingerprint: entry.fingerprint, emails: [String(entry.email).toLowerCase()], trust: 'verified', addedAt: entry.createdAt, publicKey: entry.publicKey, own: true }))
|
||||
];
|
||||
const keys = [];
|
||||
const missing = [];
|
||||
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
|
||||
const candidates = pool
|
||||
.filter(entry => entry.emails.includes(address))
|
||||
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
|
||||
let usable = null;
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
|
||||
await key.getEncryptionKey();
|
||||
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
|
||||
break;
|
||||
} catch { /* expired or revoked: try the next key */ }
|
||||
}
|
||||
if (usable) keys.push({ address, ...usable });
|
||||
else missing.push(address);
|
||||
}
|
||||
return { keys, missing };
|
||||
},
|
||||
|
||||
async verificationKeys() {
|
||||
const data = await read();
|
||||
const result = [];
|
||||
for (const entry of [...data.contacts.map(item => ({ ...item, own: false })), ...data.keys.map(item => ({ ...item, trust: 'verified', emails: [String(item.email).toLowerCase()], own: true }))]) {
|
||||
try {
|
||||
result.push({ key: await openpgp.readKey({ armoredKey: entry.publicKey }), fingerprint: entry.fingerprint, trust: entry.trust, emails: entry.emails, own: entry.own });
|
||||
} catch { /* skip unreadable entries */ }
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async privateEntries() {
|
||||
return (await read()).keys.map(entry => ({ fingerprint: entry.fingerprint, email: entry.email, name: entry.name, privateKey: entry.privateKey, publicKey: entry.publicKey }));
|
||||
},
|
||||
|
||||
async unlockKey(fingerprint, passphrase) {
|
||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
return unlock(entry.privateKey, passphrase);
|
||||
},
|
||||
|
||||
async getSettings() {
|
||||
const settings = (await read()).settings;
|
||||
return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES };
|
||||
},
|
||||
|
||||
async setSettings({ cacheMinutes }) {
|
||||
const minutes = Number(cacheMinutes);
|
||||
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
||||
const data = await read();
|
||||
data.settings.cacheMinutes = Math.round(minutes);
|
||||
await storage.save(data);
|
||||
return { cacheMinutes: data.settings.cacheMinutes };
|
||||
},
|
||||
|
||||
async list() {
|
||||
return (await read()).keys.map(publicInfo);
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user