const openpgp = require('openpgp'); const MAX_KEY_LENGTH = 200000; function publicInfo(entry) { return { fingerprint: entry.fingerprint, name: entry.name, email: entry.email, accountId: entry.accountId || null, createdAt: entry.createdAt, algorithm: entry.algorithm, hasRevocationCertificate: Boolean(entry.revocationCertificate) }; } function requirePassphrase(passphrase) { if (typeof passphrase !== 'string' || passphrase.length < 8) { throw new Error('Use a passphrase of at least 8 characters.'); } return passphrase; } function readArmored(value) { const armored = String(value || '').trim(); if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.'); return armored; } async function unlock(armoredPrivateKey, passphrase) { try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }), passphrase }); } catch { throw new Error('The passphrase is incorrect.'); } } 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 : [], contacts: Array.isArray(data?.contacts) ? data.contacts : [], settings: data?.settings && typeof data.settings === 'object' ? data.settings : {} }; } async function add(entry) { const data = await read(); if (data.keys.some(key => key.fingerprint === entry.fingerprint)) { throw new Error('That key is already in your keyring.'); } data.keys.push(entry); await storage.save(data); } 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); }, async generate({ name, email, passphrase, accountId = null }) { const cleanName = String(name || '').trim().slice(0, 100); const cleanEmail = String(email || '').trim(); if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.'); requirePassphrase(passphrase); const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({ type: 'ecc', curve: 'curve25519Legacy', userIDs: [{ name: cleanName || undefined, email: cleanEmail }], passphrase, format: 'armored' }); const key = await openpgp.readKey({ armoredKey: publicKey }); const entry = { fingerprint: key.getFingerprint().toUpperCase(), name: cleanName, email: cleanEmail, accountId, createdAt: Date.now(), algorithm: 'Curve25519', privateKey, publicKey, revocationCertificate }; await add(entry); return { key: publicInfo(entry), revocationCertificate }; }, async import({ armoredKey, passphrase, accountId = null }) { const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => { throw new Error('That is not a valid OpenPGP private key.'); }); requirePassphrase(passphrase); let protectedKey; if (parsed.isDecrypted()) { protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase }); } else { await unlock(parsed.armor(), passphrase); protectedKey = parsed; } const user = await protectedKey.getPrimaryUser().catch(() => null); const entry = { fingerprint: protectedKey.getFingerprint().toUpperCase(), name: user?.user?.userID?.name || '', email: user?.user?.userID?.email || '', accountId, createdAt: protectedKey.getCreationTime().getTime(), algorithm: protectedKey.getAlgorithmInfo().algorithm, privateKey: protectedKey.armor(), publicKey: protectedKey.toPublic().armor(), revocationCertificate: null }; await add(entry); return publicInfo(entry); }, async exportPublic(fingerprint) { const entry = (await read()).keys.find(key => key.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); return entry.publicKey; }, async exportPrivate(fingerprint, passphrase) { const entry = (await read()).keys.find(key => key.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(entry.privateKey, passphrase); return entry.privateKey; }, async exportRevocation(fingerprint, passphrase) { const entry = (await read()).keys.find(key => key.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.'); await unlock(entry.privateKey, passphrase); return entry.revocationCertificate; }, async remove(fingerprint, passphrase) { const data = await read(); const entry = data.keys.find(key => key.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(entry.privateKey, passphrase); data.keys = data.keys.filter(key => key.fingerprint !== fingerprint); await storage.save(data); return { removed: true }; } }; } module.exports = { createKeyStore };