Add Android security Phase 0

This commit is contained in:
2026-11-03 07:32:34 +02:00
parent af224beda4
commit 790051f440
98 changed files with 16497 additions and 16287 deletions
+13
View File
@@ -8,6 +8,8 @@ const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'),
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
const androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
test('package metadata and lockfile share one release version', () => {
@@ -32,3 +34,14 @@ test('release scripts and desktop artifact labels use package.json version', ()
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
});
test('Android debug APK is labeled as debug and release APK requires signing credentials', () => {
assert.match(androidDebugScript, /assembleDebug/);
assert.match(androidDebugScript, /ep-mail \$\{version\}-debug\.apk/);
assert.match(androidReleaseScript, /assembleRelease/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_FILE/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_PASSWORD/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_ALIAS/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
});
+38 -38
View File
@@ -1,38 +1,38 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs');
test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => {
const bytes = Buffer.from([0, 1, 2, 127, 128, 255]);
const [file] = normalizeOutgoingAttachments([{
filename: 'folder\\report.bin',
contentType: 'APPLICATION/OCTET-STREAM',
size: 999,
contentBase64: bytes.toString('base64')
}]);
assert.equal(file.filename, 'report.bin');
assert.equal(file.contentType, 'application/octet-stream');
assert.equal(file.size, bytes.length);
assert.deepEqual(file.content, bytes);
const [serialized] = serializeOutgoingAttachments([file]);
assert.equal(serialized.contentBase64, bytes.toString('base64'));
assert.equal('content' in serialized, false);
});
test('rejects malformed attachment data and unsafe content types', () => {
assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/);
assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/);
assert.throws(() => normalizeOutgoingAttachments([{
filename: 'x',
contentType: 'text/plain\r\nBcc: bad@example.com',
contentBase64: ''
}]), /content type.*invalid/);
});
test('uses fallback names and MIME types for empty metadata', () => {
const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]);
assert.equal(file.filename, 'attachment');
assert.equal(file.contentType, 'application/octet-stream');
assert.equal(file.size, 0);
});
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs');
test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => {
const bytes = Buffer.from([0, 1, 2, 127, 128, 255]);
const [file] = normalizeOutgoingAttachments([{
filename: 'folder\\report.bin',
contentType: 'APPLICATION/OCTET-STREAM',
size: 999,
contentBase64: bytes.toString('base64')
}]);
assert.equal(file.filename, 'report.bin');
assert.equal(file.contentType, 'application/octet-stream');
assert.equal(file.size, bytes.length);
assert.deepEqual(file.content, bytes);
const [serialized] = serializeOutgoingAttachments([file]);
assert.equal(serialized.contentBase64, bytes.toString('base64'));
assert.equal('content' in serialized, false);
});
test('rejects malformed attachment data and unsafe content types', () => {
assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/);
assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/);
assert.throws(() => normalizeOutgoingAttachments([{
filename: 'x',
contentType: 'text/plain\r\nBcc: bad@example.com',
contentBase64: ''
}]), /content type.*invalid/);
});
test('uses fallback names and MIME types for empty metadata', () => {
const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]);
assert.equal(file.filename, 'attachment');
assert.equal(file.contentType, 'application/octet-stream');
assert.equal(file.size, 0);
});
+104 -104
View File
@@ -1,104 +1,104 @@
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 <gina@example.com>', '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 <gina@example.com>',
subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '<interop@ep-mail.local>', 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 <eppu@example.com>"/);
} 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 <gina@example.com>\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 }); }
});
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 <gina@example.com>', '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 <gina@example.com>',
subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '<interop@ep-mail.local>', 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 <eppu@example.com>"/);
} 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 <gina@example.com>\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 }); }
});
+244 -244
View File
@@ -1,244 +1,244 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const openpgp = require('openpgp');
const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs');
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
const email = 'ada@example.org';
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 makeKey() {
const generated = await openpgp.generateKey({
type: 'ecc',
curve: 'curve25519Legacy',
userIDs: [{ name: 'Ada Lovelace', email }],
passphrase: 'correct horse battery',
format: 'armored'
});
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
return { fingerprint: key.getFingerprint().toUpperCase(), armoredKey: key.armor() };
}
test('validates custom HTTPS key server configuration', () => {
assert.deepEqual(normalizeCustomServer({
id: 'custom',
name: 'Internal server',
url: 'https://keys.example.org/openpgp',
protocol: 'hkp'
}), {
id: 'custom',
name: 'Internal server',
url: 'https://keys.example.org/openpgp/',
protocol: 'hkp',
builtin: false
});
assert.throws(() => normalizeCustomServer({ name: 'Plain HTTP', url: 'http://keys.example.org', protocol: 'hkp' }), /HTTPS/);
assert.throws(() => normalizeCustomServer({ name: 'Credential URL', url: 'https://user:pass@keys.example.org', protocol: 'vks' }), /credentials/);
assert.throws(() => normalizeCustomServer({ name: 'Query URL', url: 'https://keys.example.org/?token=x', protocol: 'vks' }), /query/);
assert.throws(() => normalizeCustomServer({ name: 'Unknown protocol', url: 'https://keys.example.org', protocol: 'unknown' }), /protocol/);
});
test('all built-in and custom key servers start disabled', () => {
const servers = listServers([{
id: 'custom',
name: 'Internal server',
url: 'https://keys.example.org',
protocol: 'hkp'
}]);
assert.equal(servers.length, 3);
assert.ok(servers.every(server => server.enabled === false));
const enabled = listServers([], ['openpgp-vks']);
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
});
test('VKS lookup returns only valid keys matching the requested address', async () => {
const key = await makeKey();
let requestedUrl;
const service = createKeyServerService({
async fetchImpl(url, options) {
requestedUrl = new URL(url);
assert.equal(options.redirect, 'error');
return new Response(key.armoredKey, { status: 200, headers: { 'content-type': 'application/pgp-keys' } });
}
});
const found = await service.lookup({
id: 'openpgp-vks',
name: 'keys.openpgp.org',
url: 'https://keys.openpgp.org',
protocol: 'vks'
}, email);
assert.equal(requestedUrl.pathname, '/vks/v1/by-email/ada%40example.org');
assert.equal(found.length, 1);
assert.equal(found[0].fingerprint, key.fingerprint);
assert.deepEqual(found[0].emails, [email]);
});
test('HKP lookup filters unrelated keys and reports an empty result', async () => {
const key = await makeKey();
let requestedUrl;
const service = createKeyServerService({
async fetchImpl(url) {
requestedUrl = new URL(url);
return new Response(`not a key\n${key.armoredKey}`, { status: 200 });
}
});
const server = { id: 'custom', name: 'Example', url: 'https://keys.example.org/base/', protocol: 'hkp' };
const found = await service.lookup(server, email);
assert.equal(requestedUrl.pathname, '/base/pks/lookup');
assert.equal(requestedUrl.searchParams.get('op'), 'get');
assert.equal(requestedUrl.searchParams.get('search'), email);
assert.equal(found.length, 1);
assert.deepEqual(await service.lookup(server, 'other@example.org'), []);
});
test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => {
const key = await makeKey();
const requested = [];
const service = createKeyServerService({
async fetchImpl(url) {
const target = new URL(url);
requested.push(target.hostname);
if (target.hostname === 'broken.example.org') throw new Error('server unavailable');
return new Response(key.armoredKey, { status: 200 });
}
});
const results = await service.lookupEnabled([
{ id: 'one', name: 'First', url: 'https://first.example.org', protocol: 'hkp', enabled: true },
{ id: 'two', name: 'Second', url: 'https://second.example.org', protocol: 'vks', enabled: true },
{ id: 'bad', name: 'Offline', url: 'https://broken.example.org', protocol: 'hkp', enabled: true },
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
], email);
assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']);
assert.equal(results.keys.length, 1);
assert.deepEqual(results.keys[0].sources, ['First', 'Second']);
assert.deepEqual(results.errors.map(error => error.name), ['Offline']);
assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']);
await assert.rejects(() => service.lookupEnabled([
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
], email), /Enable at least one key server/);
});
test('VKS publication uploads only the public key and requests email verification', async () => {
const key = await makeKey();
const calls = [];
const service = createKeyServerService({
async fetchImpl(url, options) {
calls.push({ url: new URL(url), options });
if (calls.length === 1) {
return Response.json({
key_fpr: key.fingerprint,
token: 'temporary-upload-token',
status: { [email]: 'unpublished' }
});
}
return Response.json({ key_fpr: key.fingerprint, token: 'temporary-upload-token', status: { [email]: 'pending' } });
}
});
const result = await service.publish({
id: 'openpgp-vks',
name: 'keys.openpgp.org',
url: 'https://keys.openpgp.org',
protocol: 'vks'
}, email, key.armoredKey, key.fingerprint);
assert.equal(calls[0].url.pathname, '/vks/v1/upload');
assert.equal(calls[1].url.pathname, '/vks/v1/request-verify');
assert.equal(result.verification, 'pending');
const upload = JSON.parse(calls[0].options.body);
assert.equal(upload.keytext, key.armoredKey);
assert.equal(upload.keytext.includes('PRIVATE KEY'), false);
assert.deepEqual(JSON.parse(calls[1].options.body).addresses, [email]);
});
test('HKP publication posts armored public material only', async () => {
const key = await makeKey();
let requestInfo;
const service = createKeyServerService({
async fetchImpl(url, options) {
requestInfo = { url: new URL(url), options };
return new Response('Upload successful. Check your inbox to verify your email address.', { status: 200 });
}
});
const result = await service.publish({
id: 'mailvelope-hkp',
name: 'keys.mailvelope.com',
url: 'https://keys.mailvelope.com',
protocol: 'hkp'
}, email, key.armoredKey, key.fingerprint);
assert.equal(requestInfo.url.pathname, '/pks/add');
assert.equal(requestInfo.options.headers['content-type'], 'application/x-www-form-urlencoded');
assert.equal(new URLSearchParams(requestInfo.options.body).get('keytext'), key.armoredKey);
assert.equal(requestInfo.options.body.includes('PRIVATE KEY'), false);
assert.equal(result.verification, 'check-email');
});
test('key-server contact imports stay untrusted and retain keyserver provenance', async () => {
const key = await makeKey();
const keyStore = createKeyStore(memoryStore());
const added = await keyStore.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
assert.equal(added.contact.trust, 'unknown');
assert.equal(added.contact.source, 'keyserver');
});
test('lookup rejects oversized responses and HTTP failures', async () => {
const server = { id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks' };
const tooLarge = createKeyServerService({
async fetchImpl() { return new Response('x'.repeat(600001), { status: 200 }); }
});
await assert.rejects(() => tooLarge.lookup(server, email), /too large/);
const failure = createKeyServerService({
async fetchImpl() { return new Response('', { status: 503 }); }
});
await assert.rejects(() => failure.lookup(server, email), /HTTP 503/);
const invalid = createKeyServerService({
async fetchImpl() { return new Response('<html>unexpected response</html>', { status: 200 }); }
});
await assert.rejects(() => invalid.lookup(server, email), /did not contain an OpenPGP public key/);
});
test('VKS verification failure reports that the key upload already succeeded', async () => {
const key = await makeKey();
let calls = 0;
const service = createKeyServerService({
async fetchImpl() {
calls += 1;
if (calls === 1) {
return Response.json({
key_fpr: key.fingerprint,
token: 'temporary-upload-token',
status: { [email]: 'unpublished' }
});
}
throw new Error('network unavailable');
}
});
const result = await service.publish({
id: 'openpgp-vks',
name: 'keys.openpgp.org',
url: 'https://keys.openpgp.org',
protocol: 'vks'
}, email, key.armoredKey, key.fingerprint);
assert.equal(result.uploaded, true);
assert.equal(result.verification, 'request-failed');
assert.match(result.warning, /key was uploaded/);
});
test('publication rejects a fingerprint that does not match the public key', async () => {
const key = await makeKey();
const service = createKeyServerService({
async fetchImpl() { throw new Error('unexpected network request'); }
});
await assert.rejects(() => service.publish({
id: 'mailvelope-hkp',
name: 'keys.mailvelope.com',
url: 'https://keys.mailvelope.com',
protocol: 'hkp'
}, email, key.armoredKey, '0'.repeat(40)), /does not match/);
});
const test = require('node:test');
const assert = require('node:assert/strict');
const openpgp = require('openpgp');
const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs');
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
const email = 'ada@example.org';
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 makeKey() {
const generated = await openpgp.generateKey({
type: 'ecc',
curve: 'curve25519Legacy',
userIDs: [{ name: 'Ada Lovelace', email }],
passphrase: 'correct horse battery',
format: 'armored'
});
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
return { fingerprint: key.getFingerprint().toUpperCase(), armoredKey: key.armor() };
}
test('validates custom HTTPS key server configuration', () => {
assert.deepEqual(normalizeCustomServer({
id: 'custom',
name: 'Internal server',
url: 'https://keys.example.org/openpgp',
protocol: 'hkp'
}), {
id: 'custom',
name: 'Internal server',
url: 'https://keys.example.org/openpgp/',
protocol: 'hkp',
builtin: false
});
assert.throws(() => normalizeCustomServer({ name: 'Plain HTTP', url: 'http://keys.example.org', protocol: 'hkp' }), /HTTPS/);
assert.throws(() => normalizeCustomServer({ name: 'Credential URL', url: 'https://user:pass@keys.example.org', protocol: 'vks' }), /credentials/);
assert.throws(() => normalizeCustomServer({ name: 'Query URL', url: 'https://keys.example.org/?token=x', protocol: 'vks' }), /query/);
assert.throws(() => normalizeCustomServer({ name: 'Unknown protocol', url: 'https://keys.example.org', protocol: 'unknown' }), /protocol/);
});
test('all built-in and custom key servers start disabled', () => {
const servers = listServers([{
id: 'custom',
name: 'Internal server',
url: 'https://keys.example.org',
protocol: 'hkp'
}]);
assert.equal(servers.length, 3);
assert.ok(servers.every(server => server.enabled === false));
const enabled = listServers([], ['openpgp-vks']);
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
});
test('VKS lookup returns only valid keys matching the requested address', async () => {
const key = await makeKey();
let requestedUrl;
const service = createKeyServerService({
async fetchImpl(url, options) {
requestedUrl = new URL(url);
assert.equal(options.redirect, 'error');
return new Response(key.armoredKey, { status: 200, headers: { 'content-type': 'application/pgp-keys' } });
}
});
const found = await service.lookup({
id: 'openpgp-vks',
name: 'keys.openpgp.org',
url: 'https://keys.openpgp.org',
protocol: 'vks'
}, email);
assert.equal(requestedUrl.pathname, '/vks/v1/by-email/ada%40example.org');
assert.equal(found.length, 1);
assert.equal(found[0].fingerprint, key.fingerprint);
assert.deepEqual(found[0].emails, [email]);
});
test('HKP lookup filters unrelated keys and reports an empty result', async () => {
const key = await makeKey();
let requestedUrl;
const service = createKeyServerService({
async fetchImpl(url) {
requestedUrl = new URL(url);
return new Response(`not a key\n${key.armoredKey}`, { status: 200 });
}
});
const server = { id: 'custom', name: 'Example', url: 'https://keys.example.org/base/', protocol: 'hkp' };
const found = await service.lookup(server, email);
assert.equal(requestedUrl.pathname, '/base/pks/lookup');
assert.equal(requestedUrl.searchParams.get('op'), 'get');
assert.equal(requestedUrl.searchParams.get('search'), email);
assert.equal(found.length, 1);
assert.deepEqual(await service.lookup(server, 'other@example.org'), []);
});
test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => {
const key = await makeKey();
const requested = [];
const service = createKeyServerService({
async fetchImpl(url) {
const target = new URL(url);
requested.push(target.hostname);
if (target.hostname === 'broken.example.org') throw new Error('server unavailable');
return new Response(key.armoredKey, { status: 200 });
}
});
const results = await service.lookupEnabled([
{ id: 'one', name: 'First', url: 'https://first.example.org', protocol: 'hkp', enabled: true },
{ id: 'two', name: 'Second', url: 'https://second.example.org', protocol: 'vks', enabled: true },
{ id: 'bad', name: 'Offline', url: 'https://broken.example.org', protocol: 'hkp', enabled: true },
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
], email);
assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']);
assert.equal(results.keys.length, 1);
assert.deepEqual(results.keys[0].sources, ['First', 'Second']);
assert.deepEqual(results.errors.map(error => error.name), ['Offline']);
assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']);
await assert.rejects(() => service.lookupEnabled([
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
], email), /Enable at least one key server/);
});
test('VKS publication uploads only the public key and requests email verification', async () => {
const key = await makeKey();
const calls = [];
const service = createKeyServerService({
async fetchImpl(url, options) {
calls.push({ url: new URL(url), options });
if (calls.length === 1) {
return Response.json({
key_fpr: key.fingerprint,
token: 'temporary-upload-token',
status: { [email]: 'unpublished' }
});
}
return Response.json({ key_fpr: key.fingerprint, token: 'temporary-upload-token', status: { [email]: 'pending' } });
}
});
const result = await service.publish({
id: 'openpgp-vks',
name: 'keys.openpgp.org',
url: 'https://keys.openpgp.org',
protocol: 'vks'
}, email, key.armoredKey, key.fingerprint);
assert.equal(calls[0].url.pathname, '/vks/v1/upload');
assert.equal(calls[1].url.pathname, '/vks/v1/request-verify');
assert.equal(result.verification, 'pending');
const upload = JSON.parse(calls[0].options.body);
assert.equal(upload.keytext, key.armoredKey);
assert.equal(upload.keytext.includes('PRIVATE KEY'), false);
assert.deepEqual(JSON.parse(calls[1].options.body).addresses, [email]);
});
test('HKP publication posts armored public material only', async () => {
const key = await makeKey();
let requestInfo;
const service = createKeyServerService({
async fetchImpl(url, options) {
requestInfo = { url: new URL(url), options };
return new Response('Upload successful. Check your inbox to verify your email address.', { status: 200 });
}
});
const result = await service.publish({
id: 'mailvelope-hkp',
name: 'keys.mailvelope.com',
url: 'https://keys.mailvelope.com',
protocol: 'hkp'
}, email, key.armoredKey, key.fingerprint);
assert.equal(requestInfo.url.pathname, '/pks/add');
assert.equal(requestInfo.options.headers['content-type'], 'application/x-www-form-urlencoded');
assert.equal(new URLSearchParams(requestInfo.options.body).get('keytext'), key.armoredKey);
assert.equal(requestInfo.options.body.includes('PRIVATE KEY'), false);
assert.equal(result.verification, 'check-email');
});
test('key-server contact imports stay untrusted and retain keyserver provenance', async () => {
const key = await makeKey();
const keyStore = createKeyStore(memoryStore());
const added = await keyStore.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
assert.equal(added.contact.trust, 'unknown');
assert.equal(added.contact.source, 'keyserver');
});
test('lookup rejects oversized responses and HTTP failures', async () => {
const server = { id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks' };
const tooLarge = createKeyServerService({
async fetchImpl() { return new Response('x'.repeat(600001), { status: 200 }); }
});
await assert.rejects(() => tooLarge.lookup(server, email), /too large/);
const failure = createKeyServerService({
async fetchImpl() { return new Response('', { status: 503 }); }
});
await assert.rejects(() => failure.lookup(server, email), /HTTP 503/);
const invalid = createKeyServerService({
async fetchImpl() { return new Response('<html>unexpected response</html>', { status: 200 }); }
});
await assert.rejects(() => invalid.lookup(server, email), /did not contain an OpenPGP public key/);
});
test('VKS verification failure reports that the key upload already succeeded', async () => {
const key = await makeKey();
let calls = 0;
const service = createKeyServerService({
async fetchImpl() {
calls += 1;
if (calls === 1) {
return Response.json({
key_fpr: key.fingerprint,
token: 'temporary-upload-token',
status: { [email]: 'unpublished' }
});
}
throw new Error('network unavailable');
}
});
const result = await service.publish({
id: 'openpgp-vks',
name: 'keys.openpgp.org',
url: 'https://keys.openpgp.org',
protocol: 'vks'
}, email, key.armoredKey, key.fingerprint);
assert.equal(result.uploaded, true);
assert.equal(result.verification, 'request-failed');
assert.match(result.warning, /key was uploaded/);
});
test('publication rejects a fingerprint that does not match the public key', async () => {
const key = await makeKey();
const service = createKeyServerService({
async fetchImpl() { throw new Error('unexpected network request'); }
});
await assert.rejects(() => service.publish({
id: 'mailvelope-hkp',
name: 'keys.mailvelope.com',
url: 'https://keys.mailvelope.com',
protocol: 'hkp'
}, email, key.armoredKey, '0'.repeat(40)), /does not match/);
});
+123 -123
View File
@@ -1,123 +1,123 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const openpgp = require('openpgp');
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
function memoryStore() {
let data = null;
return { load: async () => data, save: async value => { data = JSON.parse(JSON.stringify(value)); } };
}
const passphrase = 'correct horse battery';
test('generates a passphrase-protected key and never lists secrets', async () => {
const storage = memoryStore();
const keys = createKeyStore(storage);
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
assert.match(key.fingerprint, /^[0-9A-F]{40,64}$/);
assert.ok(revocationCertificate.includes('BEGIN PGP PUBLIC KEY BLOCK'));
const listed = await keys.list();
assert.equal(listed.length, 1);
assert.equal(JSON.stringify(listed).includes('PRIVATE'), false);
const stored = (await storage.load()).keys[0];
const parsed = await openpgp.readPrivateKey({ armoredKey: stored.privateKey });
assert.equal(parsed.isDecrypted(), false);
});
test('rejects weak passphrases and bad addresses', async () => {
const keys = createKeyStore(memoryStore());
await assert.rejects(keys.generate({ name: 'A', email: 'a@example.com', passphrase: 'short' }), /at least 8/);
await assert.rejects(keys.generate({ name: 'A', email: 'nope', passphrase }), /valid email/);
});
test('export requires the right passphrase and round-trips through import', async () => {
const first = createKeyStore(memoryStore());
const { key } = await first.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
await assert.rejects(first.exportPrivate(key.fingerprint, 'wrong passphrase'), /incorrect/);
const armored = await first.exportPrivate(key.fingerprint, passphrase);
const second = createKeyStore(memoryStore());
const imported = await second.import({ armoredKey: armored, passphrase });
assert.equal(imported.fingerprint, key.fingerprint);
assert.equal(imported.email, 'ada@example.com');
await assert.rejects(second.import({ armoredKey: armored, passphrase }), /already/);
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
test('changes a key passphrase without changing its public identity or revocation certificate', async () => {
const storage = memoryStore();
const keys = createKeyStore(storage);
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
const original = JSON.parse(JSON.stringify((await storage.load()).keys[0]));
const newPassphrase = 'new passphrase securely';
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
assert.deepEqual((await storage.load()).keys[0], original);
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
const changed = (await storage.load()).keys[0];
assert.equal(changed.fingerprint, original.fingerprint);
assert.equal(changed.publicKey, original.publicKey);
assert.equal(changed.name, original.name);
assert.equal(changed.email, original.email);
assert.equal(changed.accountId, original.accountId);
assert.equal(changed.createdAt, original.createdAt);
assert.equal(changed.algorithm, original.algorithm);
assert.equal(changed.revocationCertificate, original.revocationCertificate);
assert.notEqual(changed.privateKey, original.privateKey);
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
});
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
let data = null;
let failSave = false;
const storage = {
load: async () => data,
save: async value => {
if (failSave) throw new Error('Storage unavailable.');
data = JSON.parse(JSON.stringify(value));
}
};
const keys = createKeyStore(storage);
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
const original = JSON.parse(JSON.stringify(data.keys[0]));
failSave = true;
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
assert.deepEqual(data.keys[0], original);
});
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
const keys = createKeyStore(memoryStore());
const imported = await keys.import({ armoredKey: privateKey, passphrase });
const exported = await keys.exportPrivate(imported.fingerprint, passphrase);
assert.equal((await openpgp.readPrivateKey({ armoredKey: exported })).isDecrypted(), false);
});
test('rejects invalid key material and a wrong passphrase on import', async () => {
const keys = createKeyStore(memoryStore());
await assert.rejects(keys.import({ armoredKey: 'not a key', passphrase }), /valid OpenPGP/);
const source = createKeyStore(memoryStore());
const { key } = await source.generate({ name: 'C', email: 'c@example.com', passphrase });
const armored = await source.exportPrivate(key.fingerprint, passphrase);
await assert.rejects(keys.import({ armoredKey: armored, passphrase: 'another passphrase' }), /incorrect/);
});
test('deleting a key needs the passphrase', async () => {
const keys = createKeyStore(memoryStore());
const { key } = await keys.generate({ name: 'D', email: 'd@example.com', passphrase });
await assert.rejects(keys.remove(key.fingerprint, 'wrong passphrase'), /incorrect/);
assert.equal((await keys.list()).length, 1);
await keys.remove(key.fingerprint, passphrase);
assert.equal((await keys.list()).length, 0);
});
test('stored revocation certificate is returned only after unlocking', async () => {
const keys = createKeyStore(memoryStore());
const { key } = await keys.generate({ name: 'E', email: 'e@example.com', passphrase });
await assert.rejects(keys.exportRevocation(key.fingerprint, 'wrong passphrase'), /incorrect/);
assert.ok((await keys.exportRevocation(key.fingerprint, passphrase)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
const test = require('node:test');
const assert = require('node:assert/strict');
const openpgp = require('openpgp');
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
function memoryStore() {
let data = null;
return { load: async () => data, save: async value => { data = JSON.parse(JSON.stringify(value)); } };
}
const passphrase = 'correct horse battery';
test('generates a passphrase-protected key and never lists secrets', async () => {
const storage = memoryStore();
const keys = createKeyStore(storage);
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
assert.match(key.fingerprint, /^[0-9A-F]{40,64}$/);
assert.ok(revocationCertificate.includes('BEGIN PGP PUBLIC KEY BLOCK'));
const listed = await keys.list();
assert.equal(listed.length, 1);
assert.equal(JSON.stringify(listed).includes('PRIVATE'), false);
const stored = (await storage.load()).keys[0];
const parsed = await openpgp.readPrivateKey({ armoredKey: stored.privateKey });
assert.equal(parsed.isDecrypted(), false);
});
test('rejects weak passphrases and bad addresses', async () => {
const keys = createKeyStore(memoryStore());
await assert.rejects(keys.generate({ name: 'A', email: 'a@example.com', passphrase: 'short' }), /at least 8/);
await assert.rejects(keys.generate({ name: 'A', email: 'nope', passphrase }), /valid email/);
});
test('export requires the right passphrase and round-trips through import', async () => {
const first = createKeyStore(memoryStore());
const { key } = await first.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
await assert.rejects(first.exportPrivate(key.fingerprint, 'wrong passphrase'), /incorrect/);
const armored = await first.exportPrivate(key.fingerprint, passphrase);
const second = createKeyStore(memoryStore());
const imported = await second.import({ armoredKey: armored, passphrase });
assert.equal(imported.fingerprint, key.fingerprint);
assert.equal(imported.email, 'ada@example.com');
await assert.rejects(second.import({ armoredKey: armored, passphrase }), /already/);
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
test('changes a key passphrase without changing its public identity or revocation certificate', async () => {
const storage = memoryStore();
const keys = createKeyStore(storage);
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
const original = JSON.parse(JSON.stringify((await storage.load()).keys[0]));
const newPassphrase = 'new passphrase securely';
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
assert.deepEqual((await storage.load()).keys[0], original);
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
const changed = (await storage.load()).keys[0];
assert.equal(changed.fingerprint, original.fingerprint);
assert.equal(changed.publicKey, original.publicKey);
assert.equal(changed.name, original.name);
assert.equal(changed.email, original.email);
assert.equal(changed.accountId, original.accountId);
assert.equal(changed.createdAt, original.createdAt);
assert.equal(changed.algorithm, original.algorithm);
assert.equal(changed.revocationCertificate, original.revocationCertificate);
assert.notEqual(changed.privateKey, original.privateKey);
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
});
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
let data = null;
let failSave = false;
const storage = {
load: async () => data,
save: async value => {
if (failSave) throw new Error('Storage unavailable.');
data = JSON.parse(JSON.stringify(value));
}
};
const keys = createKeyStore(storage);
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
const original = JSON.parse(JSON.stringify(data.keys[0]));
failSave = true;
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
assert.deepEqual(data.keys[0], original);
});
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
const keys = createKeyStore(memoryStore());
const imported = await keys.import({ armoredKey: privateKey, passphrase });
const exported = await keys.exportPrivate(imported.fingerprint, passphrase);
assert.equal((await openpgp.readPrivateKey({ armoredKey: exported })).isDecrypted(), false);
});
test('rejects invalid key material and a wrong passphrase on import', async () => {
const keys = createKeyStore(memoryStore());
await assert.rejects(keys.import({ armoredKey: 'not a key', passphrase }), /valid OpenPGP/);
const source = createKeyStore(memoryStore());
const { key } = await source.generate({ name: 'C', email: 'c@example.com', passphrase });
const armored = await source.exportPrivate(key.fingerprint, passphrase);
await assert.rejects(keys.import({ armoredKey: armored, passphrase: 'another passphrase' }), /incorrect/);
});
test('deleting a key needs the passphrase', async () => {
const keys = createKeyStore(memoryStore());
const { key } = await keys.generate({ name: 'D', email: 'd@example.com', passphrase });
await assert.rejects(keys.remove(key.fingerprint, 'wrong passphrase'), /incorrect/);
assert.equal((await keys.list()).length, 1);
await keys.remove(key.fingerprint, passphrase);
assert.equal((await keys.list()).length, 0);
});
test('stored revocation certificate is returned only after unlocking', async () => {
const keys = createKeyStore(memoryStore());
const { key } = await keys.generate({ name: 'E', email: 'e@example.com', passphrase });
await assert.rejects(keys.exportRevocation(key.fingerprint, 'wrong passphrase'), /incorrect/);
assert.ok((await keys.exportRevocation(key.fingerprint, passphrase)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
+216 -216
View File
@@ -1,216 +1,216 @@
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: '<abc@ep-mail.local>', ...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 <bob@example.com>', { 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('encrypts and signs outgoing attachments with the message body', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
const contents = Buffer.from([0, 1, 2, 127, 128, 255]);
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
encrypt: true,
sign: true,
passphrase: alice.passphrase,
attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }]
}));
assert.ok(!raw.toString('latin1').includes(contents.toString('latin1')));
const parsed = await simpleParser(raw);
const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two');
assert.equal(decrypted.parsed.attachments.length, 1);
assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin');
assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream');
assert.deepEqual(decrypted.parsed.attachments[0].content, contents);
assert.equal(decrypted.signatures[0].status, 'valid');
});
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 attachment = Buffer.from('signed attachment data');
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
sign: true,
passphrase: alice.passphrase,
attachments: [{ filename: 'signed.txt', contentType: 'text/plain', content: attachment }]
}));
const parsed = await simpleParser(raw);
assert.equal(detect(parsed), 'signed-mime');
assert.match(parsed.text, /Top secret/);
assert.deepEqual(parsed.attachments[0].content, attachment);
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 <alice@example.com>\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: [], enabledKeyServers: [] });
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
await alice.keyStore.setSettings({ cacheMinutes: 5 });
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']);
await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] });
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, []);
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);
});
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: '<abc@ep-mail.local>', ...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 <bob@example.com>', { 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('encrypts and signs outgoing attachments with the message body', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
const contents = Buffer.from([0, 1, 2, 127, 128, 255]);
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
encrypt: true,
sign: true,
passphrase: alice.passphrase,
attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }]
}));
assert.ok(!raw.toString('latin1').includes(contents.toString('latin1')));
const parsed = await simpleParser(raw);
const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two');
assert.equal(decrypted.parsed.attachments.length, 1);
assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin');
assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream');
assert.deepEqual(decrypted.parsed.attachments[0].content, contents);
assert.equal(decrypted.signatures[0].status, 'valid');
});
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 attachment = Buffer.from('signed attachment data');
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
sign: true,
passphrase: alice.passphrase,
attachments: [{ filename: 'signed.txt', contentType: 'text/plain', content: attachment }]
}));
const parsed = await simpleParser(raw);
assert.equal(detect(parsed), 'signed-mime');
assert.match(parsed.text, /Top secret/);
assert.deepEqual(parsed.attachments[0].content, attachment);
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 <alice@example.com>\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: [], enabledKeyServers: [] });
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
await alice.keyStore.setSettings({ cacheMinutes: 5 });
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']);
await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] });
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, []);
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);
});