const test = require('node:test'); const assert = require('node:assert/strict'); const { spawnSync } = require('node:child_process'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const { simpleParser } = require('mailparser'); const { createKeyStore } = require('../desktop/pgp-keystore.cjs'); const { createPgpMail, createPassphraseCache } = require('../desktop/pgp-mail.cjs'); const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe'] .filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0); const skip = gpgPath ? false : 'GnuPG is not installed'; const PASS = 'interop passphrase'; function gpgIn(home) { return (args, input) => { const result = spawnSync(gpgPath, ['--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback', '--passphrase', PASS, '--trust-model', 'always', ...args], { input }); if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`); return { out: result.stdout, err: result.stderr.toString() }; }; } async function setup() { const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-gnupg-')); const gpg = gpgIn(home); gpg(['--quick-generate-key', 'Gina Gnu ', 'ed25519', 'cert', 'never']); const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(gpg(['--list-keys', '--with-colons', 'gina@example.com']).out.toString())[1]; gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']); gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']); let data = null; const keyStore = createKeyStore({ async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } }); const mail = createPgpMail({ keyStore, cache: createPassphraseCache(async () => 10) }); const { key } = await keyStore.generate({ name: 'Eppu Mail', email: 'eppu@example.com', passphrase: PASS }); gpg(['--import'], Buffer.from(await keyStore.exportPublic(key.fingerprint))); await keyStore.addContact({ armoredKey: gpg(['--armor', '--export', 'gina@example.com']).out.toString() }); return { home, gpg, keyStore, mail }; } const options = extra => ({ from: { name: 'Eppu Mail', address: 'eppu@example.com' }, to: 'Gina Gnu ', subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '', passphrase: PASS, ...extra }); test('GnuPG decrypts and verifies mail encrypted and signed by ep-mail', { skip }, async () => { const { home, gpg, mail } = await setup(); try { const { raw } = await mail.build(options({ encrypt: true, sign: true })); const parsed = await simpleParser(raw); const armored = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(parsed.attachments[1]?.content?.toString() || parsed.attachments[0].content.toString())[0]; const { out, err } = gpg(['--decrypt'], Buffer.from(armored)); assert.match((await simpleParser(out)).text, /Hello from ep-mail ✓/); assert.match(err, /Good signature from "Eppu Mail "/); } finally { fs.rmSync(home, { recursive: true, force: true }); } }); test('GnuPG verifies PGP/MIME signed-only mail from ep-mail', { skip }, async () => { const { home, gpg, mail } = await setup(); try { const { raw } = await mail.build(options({ sign: true })); const text = raw.toString('latin1'); const { splitSigned } = require('../desktop/pgp-mail.cjs'); const boundary = /boundary="([^"]+)"/.exec(text)[1]; const parts = splitSigned(raw, boundary); const signaturePath = path.join(home, 'sig.asc'); const dataPath = path.join(home, 'data.bin'); fs.writeFileSync(signaturePath, parts.signature); fs.writeFileSync(dataPath, parts.signed); const { err } = gpg(['--verify', signaturePath, dataPath]); assert.match(err, /Good signature from "Eppu Mail/); } finally { fs.rmSync(home, { recursive: true, force: true }); } }); test('ep-mail decrypts GnuPG-encrypted PGP/MIME mail and verifies its signature', { skip }, async () => { const { home, gpg, mail, keyStore } = await setup(); try { const inner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nHello from GnuPG ✓\r\n'); const armored = gpg(['--armor', '--encrypt', '--sign', '--local-user', 'gina@example.com', '--recipient', 'eppu@example.com'], inner).out.toString(); const source = Buffer.from(`From: Gina Gnu \r\nTo: eppu@example.com\r\nSubject: from gpg\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="gb"\r\n\r\n--gb\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--gb\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\n\r\n${armored}\r\n--gb--\r\n`); const result = await mail.decrypt(await simpleParser(source), { passphrase: PASS }); assert.match(result.parsed.text, /Hello from GnuPG ✓/); assert.equal(result.signatures[0].status, 'valid'); assert.equal(result.signatures[0].matchesSender, true); assert.ok(await keyStore.listContacts()); } finally { fs.rmSync(home, { recursive: true, force: true }); } }); test('ep-mail decrypts GnuPG inline PGP and verifies GnuPG clear-signed and PGP/MIME signed mail', { skip }, async () => { const { home, gpg, mail } = await setup(); try { const inline = gpg(['--armor', '--encrypt', '--recipient', 'eppu@example.com'], Buffer.from('inline from gpg')).out.toString(); const inlineSource = Buffer.from(`From: gina@example.com\r\nSubject: i\r\nContent-Type: text/plain\r\n\r\n${inline}\r\n`); assert.match((await mail.decrypt(await simpleParser(inlineSource), { passphrase: PASS })).parsed.text, /inline from gpg/); const clear = gpg(['--clearsign', '--local-user', 'gina@example.com'], Buffer.from('clear signed text\n')).out.toString().replace(/\r?\n/g, '\r\n'); const clearSource = Buffer.from(`From: gina@example.com\r\nSubject: c\r\nContent-Type: text/plain\r\n\r\n${clear}\r\n`); assert.equal((await mail.verifySigned(await simpleParser(clearSource), clearSource))[0].status, 'valid'); const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nsigned by gpg'; const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.com'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim(); const mimeSource = Buffer.from(`From: gina@example.com\r\nSubject: m\r\nMIME-Version: 1.0\r\nContent-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha512; boundary="sb"\r\n\r\n--sb\r\n${signedPart}\r\n--sb\r\nContent-Type: application/pgp-signature\r\n\r\n${detached}\r\n--sb--\r\n`); assert.equal((await mail.verifySigned(await simpleParser(mimeSource), mimeSource))[0].status, 'valid'); } finally { fs.rmSync(home, { recursive: true, force: true }); } });