const test = require('node:test'); const assert = require('node:assert/strict'); const openpgp = require('openpgp'); const MailComposer = require('nodemailer/lib/mail-composer'); const { simpleParser } = require('mailparser'); const { createKeyStore } = require('../desktop/pgp-keystore.cjs'); const { createPgpMail, createPassphraseCache, detect } = require('../desktop/pgp-mail.cjs'); function memoryStore() { let data = null; return { async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } }; } async function actor(name, email, passphrase = 'correct horse') { const keyStore = createKeyStore(memoryStore()); const cache = createPassphraseCache(async () => 10); const mail = createPgpMail({ keyStore, cache }); const { key } = await keyStore.generate({ name, email, passphrase }); return { keyStore, cache, mail, key, email, passphrase, name }; } async function exchange(a, b) { await a.keyStore.addContact({ armoredKey: await b.keyStore.exportPublic(b.key.fingerprint) }); await b.keyStore.addContact({ armoredKey: await a.keyStore.exportPublic(a.key.fingerprint) }); } const sendOptions = (from, to, extra = {}) => ({ from: { name: from.name, address: from.email }, to, subject: 'Héllo secrèt', text: 'Top secret ✓\nline two', messageId: '', ...extra }); test('encrypts and signs for a recipient and the sender can read the copy', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); await exchange(alice, bob); const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob ', { encrypt: true, sign: true, passphrase: alice.passphrase })); assert.deepEqual(envelope.to, ['bob@example.com']); assert.ok(!raw.toString('latin1').includes('Top secret')); const parsed = await simpleParser(raw); assert.equal(parsed.subject, 'Héllo secrèt'); assert.equal(detect(parsed), 'encrypted-mime'); await assert.rejects(() => bob.mail.decrypt(parsed), error => error.code === 'PASSPHRASE_REQUIRED'); await assert.rejects(() => bob.mail.decrypt(parsed, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE'); const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase }); assert.equal(result.parsed.text.trim(), 'Top secret ✓\nline two'); assert.equal(result.signatures[0].status, 'valid'); assert.equal(result.signatures[0].matchesSender, true); const again = await bob.mail.decrypt(await simpleParser(raw)); assert.equal(again.signatures.length, 1); const own = await alice.mail.decrypt(parsed, { passphrase: alice.passphrase }); assert.match(own.parsed.text, /Top secret/); }); test('refuses to encrypt without a recipient key instead of downgrading', async () => { const alice = await actor('Alice', 'alice@example.com'); await assert.rejects( () => alice.mail.build(sendOptions(alice, 'carol@example.com', { encrypt: true })), error => error.code === 'NO_RECIPIENT_KEY' && error.details.missing[0] === 'carol@example.com' ); const status = await alice.mail.recipientStatus(['carol@example.com'], { sign: true, from: 'alice@example.com' }); assert.deepEqual(status.missing, ['carol@example.com']); assert.equal(status.signer.email, 'alice@example.com'); }); test('encrypts to several recipients and each can decrypt', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); const carol = await actor('Carol', 'carol@example.com'); for (const other of [bob, carol]) await alice.keyStore.addContact({ armoredKey: await other.keyStore.exportPublic(other.key.fingerprint) }); const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { cc: 'carol@example.com', encrypt: true })); const parsed = await simpleParser(raw); for (const reader of [bob, carol]) { const result = await reader.mail.decrypt(parsed, { passphrase: reader.passphrase }); assert.match(result.parsed.text, /Top secret/); assert.equal(result.signatures.length, 0); } }); test('detects tampered and corrupted encrypted messages', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); await exchange(alice, bob); const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { encrypt: true, sign: true, passphrase: alice.passphrase })); const text = raw.toString('latin1'); const lines = text.split('\r\n'); const at = lines.findIndex((line, index) => index > 5 && line.length >= 60 && !line.startsWith('-') && !line.includes(':')); lines[at] = lines[at].slice(0, 20) + (lines[at][20] === 'A' ? 'B' : 'A') + lines[at].slice(21); const broken = await simpleParser(Buffer.from(lines.join('\r\n'), 'latin1')); await assert.rejects(() => bob.mail.decrypt(broken, { passphrase: bob.passphrase }), error => ['CORRUPT'].includes(error.code)); const empty = await simpleParser(Buffer.from(text.replace(/-----BEGIN PGP MESSAGE-----[\s\S]*-----END PGP MESSAGE-----/, 'nothing'), 'latin1')); await assert.rejects(() => bob.mail.decrypt(empty), error => error.code === 'CORRUPT'); }); test('reports unknown signers and a changed key for a known sender', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) }); await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }); const impostor = await actor('Alice', 'alice@example.com'); await impostor.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }); const { raw } = await impostor.mail.build(sendOptions(impostor, 'bob@example.com', { encrypt: true, sign: true, passphrase: impostor.passphrase })); const result = await bob.mail.decrypt(await simpleParser(raw), { passphrase: bob.passphrase }); assert.equal(result.signatures[0].status, 'unknown-key'); assert.equal(result.signatures[0].keyChanged, true); const added = await bob.keyStore.addContact({ armoredKey: await impostor.keyStore.exportPublic(impostor.key.fingerprint) }); assert.deepEqual(added.keyChangedFrom, [alice.key.fingerprint]); const second = await bob.mail.decrypt(await simpleParser(raw)); assert.equal(second.signatures[0].status, 'valid'); assert.equal(second.signatures[0].keyChanged, false); }); test('signs without encrypting and verifies PGP/MIME signatures', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) }); const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { sign: true, passphrase: alice.passphrase })); const parsed = await simpleParser(raw); assert.equal(detect(parsed), 'signed-mime'); assert.match(parsed.text, /Top secret/); const [signature] = await bob.mail.verifySigned(parsed, raw); assert.equal(signature.status, 'valid'); const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1'); const [bad] = await bob.mail.verifySigned(await simpleParser(altered), altered); assert.equal(bad.status, 'invalid'); }); test('reads inline PGP messages and cleartext signatures', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); await exchange(alice, bob); const bobKey = (await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) })); const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ text: 'inline body' }), encryptionKeys: bobKey }); const source = Buffer.from(`From: Alice \r\nTo: bob@example.com\r\nSubject: inline\r\nContent-Type: text/plain\r\n\r\n${armored}\r\n`); const parsed = await simpleParser(source); assert.equal(detect(parsed), 'encrypted-inline'); const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase }); assert.equal(result.parsed.text.trim(), 'inline body'); const aliceSigner = await alice.keyStore.unlockKey(alice.key.fingerprint, alice.passphrase); const cleartext = await openpgp.sign({ message: await openpgp.createCleartextMessage({ text: 'hello signed' }), signingKeys: aliceSigner }); const signedSource = Buffer.from(`From: alice@example.com\r\nSubject: s\r\nContent-Type: text/plain\r\n\r\n${cleartext}\r\n`); const signedParsed = await simpleParser(signedSource); assert.equal(detect(signedParsed), 'signed-inline'); assert.equal((await bob.mail.verifySigned(signedParsed, signedSource))[0].status, 'valid'); }); test('decrypts large messages with attachments from other clients', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); const inner = await new Promise((resolve, reject) => new MailComposer({ text: 'with attachment', attachments: [{ filename: 'big.bin', content: Buffer.alloc(8 * 1048576, 7) }] }).compile().build((error, message) => error ? reject(error) : resolve(message))); const bobKey = await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }); const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ binary: inner }), encryptionKeys: bobKey }); const source = Buffer.from(`From: alice@example.com\r\nTo: bob@example.com\r\nSubject: big\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="b1"\r\n\r\n--b1\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--b1\r\nContent-Type: application/octet-stream\r\n\r\n${armored}\r\n--b1--\r\n`); const result = await bob.mail.decrypt(await simpleParser(source), { passphrase: bob.passphrase }); assert.equal(result.parsed.attachments[0].filename, 'big.bin'); assert.equal(result.parsed.attachments[0].content.length, 8 * 1048576); }); test('keyring: contacts, trust levels, expired passphrase cache and settings', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); const { contact } = await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint), source: 'message' }); assert.equal(contact.trust, 'unknown'); assert.equal((await alice.keyStore.setTrust(contact.fingerprint, 'verified')).trust, 'verified'); await assert.rejects(() => alice.keyStore.setTrust(contact.fingerprint, 'bogus')); await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/); await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/); await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/); assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [] }); const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' }; await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer] }); assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0); await alice.keyStore.setSettings({ cacheMinutes: 5 }); assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]); await alice.keyStore.removeContact(contact.fingerprint); assert.equal((await alice.keyStore.listContacts()).length, 0); let clock = 1000; const cache = createPassphraseCache(async () => 1, () => clock); await cache.remember('F', 'secret'); assert.equal(cache.get('F'), 'secret'); clock += 61000; assert.equal(cache.get('F'), null); });