const openpgp = require('openpgp'); const { simpleParser } = require('mailparser'); const addressParser = require('nodemailer/lib/addressparser'); const MailComposer = require('nodemailer/lib/mail-composer'); const { randomBytes } = require('node:crypto'); const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/; const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/; const MAX_ENCRYPTED_BYTES = 60 * 1048576; class PgpError extends Error { constructor(code, message, details = {}) { super(message); this.code = code; this.details = details; } } // Remembers unlocked-key passphrases in memory only, for a limited time. function createPassphraseCache(getMinutes, now = () => Date.now()) { const entries = new Map(); return { async remember(fingerprint, passphrase) { const minutes = await getMinutes(); if (!minutes) { entries.delete(fingerprint); return; } entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 }); }, get(fingerprint) { const entry = entries.get(fingerprint); if (!entry) return null; if (entry.expires <= now()) { entries.delete(fingerprint); return null; } return entry.passphrase; }, has(fingerprint) { return this.get(fingerprint) !== null; }, clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); } }; } function headerValue(parsed, name) { const value = parsed.headers?.get(name); return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} }; } // Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP. function detect(parsed) { const type = String(headerValue(parsed, 'content-type').value).toLowerCase(); const protocol = String(headerValue(parsed, 'content-type').params?.protocol || '').toLowerCase(); if (type === 'multipart/encrypted' && protocol === 'application/pgp-encrypted') return 'encrypted-mime'; if (type === 'multipart/signed' && protocol === 'application/pgp-signature') return 'signed-mime'; const text = String(parsed.text || ''); if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline'; if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline'; return null; } function encryptedArmor(parsed, kind) { if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0]; for (const file of parsed.attachments || []) { const content = file.content.toString('latin1'); const match = ARMORED_MESSAGE.exec(content); if (match) return match[0]; } throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.'); } function emailsOf(key) { return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean); } function fingerprintsByKeyId(verification) { const map = new Map(); for (const item of verification) { for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item); } return map; } // Interprets signature results and flags a sender whose key changed. async function describeSignatures(signatures, verification, senderEmail) { const byKeyId = fingerprintsByKeyId(verification); const sender = String(senderEmail || '').toLowerCase(); const results = []; for (const signature of signatures) { const keyId = signature.keyID.toHex().toUpperCase(); const known = byKeyId.get(keyId); let status; try { await signature.verified; status = 'valid'; } catch (error) { status = /could not find signing key|no signing key|not found/i.test(String(error?.message)) || !known ? 'unknown-key' : 'invalid'; } const result = { status, keyId, fingerprint: known?.fingerprint || null, trust: known?.trust || null, email: null, matchesSender: false, keyChanged: false }; if (known) { result.email = known.emails[0] || null; result.matchesSender = Boolean(sender) && known.emails.includes(sender); } if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true; if (sender && status !== 'unknown-key') { const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint); if (others.length && !result.matchesSender) result.keyChanged = true; } if (sender && status === 'unknown-key' && verification.some(item => !item.own && item.emails.includes(sender))) result.keyChanged = true; results.push(result); } return results; } function chunkBase64(buffer) { return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, ''); } function encodeHeader(value) { const clean = String(value).replace(/[\r\n]+/g, ' ').trim(); if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean; const chars = Array.from(clean); const words = []; for (let index = 0; index < chars.length; index += 24) { words.push(`=?UTF-8?B?${Buffer.from(chars.slice(index, index + 24).join(''), 'utf8').toString('base64')}?=`); } return words.join('\r\n '); } function formatAddress(entry) { const address = String(entry.address || '').trim(); if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+$/.test(address)) throw new Error(`"${address || entry.name}" is not a valid email address.`); const name = String(entry.name || '').replace(/[\r\n"\\]+/g, ' ').trim(); return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address; } function parseAddresses(value) { return addressParser(String(value || '')).filter(entry => entry.address || entry.name); } async function innerEntity(text, attachments) { if (attachments.length) { return new Promise((resolve, reject) => { new MailComposer({ text: String(text || ''), attachments: attachments.map(file => ({ filename: file.filename, contentType: file.contentType, content: file.content })) }).compile().build((error, message) => error ? reject(error) : resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1'))); }); } const body = Buffer.from(String(text || ''), 'utf8'); return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1'); } function boundary() { return `=_ep-${randomBytes(12).toString('hex')}`; } function createPgpMail({ keyStore, cache }) { async function findDecryptionKey(message) { const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase())); const entries = await keyStore.privateEntries(); const candidates = []; for (const entry of entries) { const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey }); if (publicKey.getKeys().some(key => wanted.has(key.getKeyID().toHex().toUpperCase()))) candidates.push(entry); } if (!candidates.length) throw new PgpError('NO_KEY', 'None of your keys can decrypt this message.'); return candidates; } async function unlockAny(candidates, passphrase) { let lastError = null; for (const candidate of candidates) { const secret = passphrase || cache.get(candidate.fingerprint); if (!secret) continue; try { const key = await keyStore.unlockKey(candidate.fingerprint, secret); await cache.remember(candidate.fingerprint, secret); return key; } catch (error) { cache.clear(candidate.fingerprint); lastError = error; } } if (lastError) throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: candidates[0].fingerprint }); throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to read this message.', { fingerprint: candidates[0].fingerprint, email: candidates[0].email }); } return { detect, async decrypt(parsed, { passphrase = null } = {}) { const kind = detect(parsed); if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.'); const armored = encryptedArmor(parsed, kind); if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.'); let message; try { message = await openpgp.readMessage({ armoredMessage: armored }); } catch { throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.'); } const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase); const verification = await keyStore.verificationKeys(); let result; try { result = await openpgp.decrypt({ message, decryptionKeys: decryptionKey, verificationKeys: verification.map(item => item.key), format: 'binary' }); } catch { throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.'); } const data = Buffer.from(result.data); const sender = parsed.from?.value?.[0]?.address || ''; const signatures = await describeSignatures(result.signatures, verification, sender); const inner = kind === 'encrypted-mime' ? await simpleParser(data) : await simpleParser(Buffer.concat([ Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'), data ])); return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) }; }, // Public keys attached to a message (offered to the user, never added silently). async attachedKeys(parsed) { const keys = []; for (const file of parsed.attachments || []) { const type = String(file.contentType || '').toLowerCase(); if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue; const armored = file.content.toString('utf8'); if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue; try { const key = await openpgp.readKey({ armoredKey: armored }); keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) }); } catch { /* ignore unreadable attachments */ } } return keys.slice(0, 5); }, // Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail. async verifySigned(parsed, source) { const kind = detect(parsed); const verification = await keyStore.verificationKeys(); const sender = parsed.from?.value?.[0]?.address || ''; try { if (kind === 'signed-inline') { const message = await openpgp.readCleartextMessage({ cleartextMessage: CLEARTEXT_SIGNED.exec(String(parsed.text))[0] }); const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) }); return describeSignatures(result.signatures, verification, sender); } if (kind !== 'signed-mime') return null; const parts = splitSigned(source, headerValue(parsed, 'content-type').params?.boundary); if (!parts) return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }]; const signature = await openpgp.readSignature({ armoredSignature: parts.signature }); const result = await openpgp.verify({ message: await openpgp.createMessage({ binary: parts.signed }), signature, verificationKeys: verification.map(item => item.key) }); return describeSignatures(result.signatures, verification, sender); } catch { return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }]; } }, // Builds a complete RFC 3156 message. Returns { raw, envelope }. async build({ from, to, cc, subject, text, messageId, inReplyTo, references, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) { const toList = parseAddresses(to); const ccList = parseAddresses(cc); if (!toList.length) throw new Error('Add at least one recipient.'); const everyone = [...toList, ...ccList]; everyone.forEach(entry => formatAddress(entry)); let signingKey = null; let signerEntry = null; if (sign) { const entries = await keyStore.privateEntries(); signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint) || entries.find(entry => entry.email.toLowerCase() === String(from.address).toLowerCase()); if (!signerEntry) throw new PgpError('NO_SIGNING_KEY', 'Create or import an encryption key for this address first.'); const secret = passphrase || cache.get(signerEntry.fingerprint); if (!secret) throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to sign this message.', { fingerprint: signerEntry.fingerprint, email: signerEntry.email }); try { signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret); } catch { cache.clear(signerEntry.fingerprint); throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint }); } await cache.remember(signerEntry.fingerprint, secret); } const { messageIds } = require('../conversation-threads.js'); const parentIds = messageIds(inReplyTo).slice(0, 1); const referenceIds = messageIds(references); const headers = [ `From: ${formatAddress(from)}`, `To: ${toList.map(formatAddress).join(', ')}`, ...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []), `Subject: ${encodeHeader(subject || '(no subject)')}`, `Date: ${date.toUTCString().replace('GMT', '+0000')}`, `Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`, ...parentIds.map(id => `In-Reply-To: ${id}`), ...(referenceIds.length ? [`References: ${referenceIds.join(' ')}`] : []), 'MIME-Version: 1.0' ]; const inner = await innerEntity(text, attachments); const mark = boundary(); let body; let contentType; if (encrypt) { const { keys, missing } = await keyStore.findRecipientKeys(everyone.map(entry => entry.address)); if (missing.length) throw new PgpError('NO_RECIPIENT_KEY', `No public key for ${missing.join(', ')}.`, { missing }); const own = signerEntry ? [await openpgp.readKey({ armoredKey: signerEntry.publicKey })] : []; const ownKeys = own.length ? own : (await keyStore.findRecipientKeys([from.address])).keys.map(item => item.key); const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ binary: inner }), encryptionKeys: [...keys.map(item => item.key), ...ownKeys], signingKeys: signingKey || undefined, format: 'armored' }); contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`; body = [ `--${mark}`, 'Content-Type: application/pgp-encrypted', 'Content-Description: PGP/MIME version identification', '', 'Version: 1', '', `--${mark}`, 'Content-Type: application/octet-stream; name="encrypted.asc"', 'Content-Description: OpenPGP encrypted message', 'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, '' ].join('\r\n'); } else if (sign) { const signedBytes = inner.subarray(0, inner.length - 2); const detached = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signingKey, detached: true, format: 'armored' }); contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`; const signedPart = signedBytes.toString('latin1'); body = [ `--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"', 'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '', String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, '' ].join('\r\n'); } else { throw new Error('Choose encryption or signing for this message.'); } const raw = Buffer.from(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`, 'latin1'); return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null }; }, async recipientStatus(addresses, { sign = false, from = '' } = {}) { const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean); const { keys, missing } = await keyStore.findRecipientKeys(list); let signer = null; if (sign) { const entries = await keyStore.privateEntries(); const entry = entries.find(item => item.email.toLowerCase() === String(from).toLowerCase()) || null; if (entry) signer = { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: cache.has(entry.fingerprint) }; } return { recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })), missing, signer }; } }; } // Extracts the signed part and detached signature from a multipart/signed source. function splitSigned(source, boundaryValue) { if (!boundaryValue) return null; const text = Buffer.from(source).toString('latin1'); const escaped = String(boundaryValue).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g'); const marks = [...text.matchAll(delimiter)]; if (marks.length < 3) return null; const contentAfter = mark => { const lineEnd = text.indexOf('\n', mark.index + mark[0].length); return lineEnd < 0 ? text.length : lineEnd + 1; }; const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n'); const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index); const armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0]; if (!armored) return null; return { signed: Buffer.from(signed, 'latin1'), signature: armored }; } module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };