Improve Android OpenPGP, drafts and release builds

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-11-17 22:11:05 +02:00
co-authored by Copilot
parent d0e2ce26bc
commit 96c7b6966b
28 changed files with 747 additions and 187 deletions
+43
View File
@@ -1,6 +1,7 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
const vm = require('node:vm');
const esbuild = require('esbuild');
const { webcrypto } = require('node:crypto');
@@ -20,6 +21,12 @@ const bundled = esbuild.buildSync({
vm.runInThisContext(bundled);
const { createAndroidPgp } = global.AndroidPgpBundle;
function saveMimeFixture(name, rawBase64) {
if (process.env.EP_MAIL_PGP_MIME_FIXTURE_DIR) {
fs.writeFileSync(path.join(process.env.EP_MAIL_PGP_MIME_FIXTURE_DIR, `${name}.eml`), Buffer.from(rawBase64, 'base64'));
}
}
function makeEndpoint(account, { confirm = () => true } = {}) {
const vault = { keys: [], contacts: [], settings: {} };
let messageSource = null;
@@ -36,6 +43,39 @@ function makeEndpoint(account, { confirm = () => true } = {}) {
};
}
test('Android imports an armored private key selected from a file', async () => {
const source = makeEndpoint({ email: 'alice@example.test' });
const target = makeEndpoint({ email: 'alice@example.test' });
const passphrase = 'alice test passphrase';
const generated = await source.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase });
const armoredKey = await source.api.exportPrivate(generated.key.fingerprint, passphrase);
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey });
await assert.rejects(target.api.importKey({ source: 'file', passphrase: 'incorrect passphrase' }), /passphrase is incorrect/);
assert.equal(target.vault.keys.length, 0);
const result = await target.api.importKey({ source: 'file', passphrase, accountId: 'account-1' });
assert.equal(result.key.fingerprint, generated.key.fingerprint);
assert.equal(target.vault.keys[0].accountId, 'account-1');
assert.equal((await openpgp.readPrivateKey({ armoredKey: target.vault.keys[0].privateKey })).isDecrypted(), false);
await assert.rejects(target.api.importKey({ source: 'file', passphrase }), /already in your keyring/);
});
test('Android file import handles cancellation, picker errors and invalid content', async () => {
const target = makeEndpoint({ email: 'alice@example.test' });
const options = { source: 'file', passphrase: 'test passphrase' };
target.EpMail.pickPgpPrivateKey = async () => ({ canceled: true });
assert.deepEqual(await target.api.importKey(options), { canceled: true });
target.EpMail.pickPgpPrivateKey = async () => { throw new Error('Picker failed'); };
await assert.rejects(target.api.importKey(options), /Picker failed/);
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey: '' });
await assert.rejects(target.api.importKey(options), /empty/);
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey: 'not a private key' });
await assert.rejects(target.api.importKey(options), /not a valid OpenPGP private key/);
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey: 'x'.repeat(200001) });
await assert.rejects(target.api.importKey(options), /too large/);
assert.equal(target.vault.keys.length, 0);
});
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
@@ -55,6 +95,7 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke
]
});
assert.ok(built.rawBase64);
saveMimeFixture('encrypted-signed', built.rawBase64);
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i);
assert.doesNotMatch(raw, /hello from Android|private attachment/);
@@ -114,6 +155,7 @@ test('Android verifies PGP/MIME signed-only and clear-signed mail', async () =>
to: 'Bob <bob@example.test>', cc: '', subject: 'Signed note', text: 'signed MIME body',
pgp: { encrypt: false, sign: true, passphrase: 'alice test passphrase' }, attachments: []
});
saveMimeFixture('signed', signedMime.rawBase64);
recipient.setMessage({ rawBase64: signedMime.rawBase64 });
const mimeResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 8 });
assert.equal(mimeResult.signatures[0].status, 'valid');
@@ -169,6 +211,7 @@ test('Android rejects tampered, malformed, and oversized encrypted input', async
to: 'bob@example.test', subject: 'Encrypted test', text: 'tamper test',
pgp: { encrypt: true }, attachments: []
});
saveMimeFixture('encrypted', built.rawBase64);
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(raw)?.[0];
assert.ok(armor);
+19 -1
View File
@@ -17,6 +17,7 @@ const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'a
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
const pgpUi = fs.readFileSync(path.join(root, 'pgp-ui.js'), 'utf8');
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
@@ -39,6 +40,14 @@ test('mobile layout removes desktop minimum width and provides a compact reader
assert.match(app, /if\(!m\)\{state\.activeMessage=null;document\.body\.classList\.remove\('reader-open'\);return;\}/);
});
test('key settings cards keep key details readable and actions wrapped', () => {
assert.match(pgpUi, /compose-modal attachments-modal pgp-keys-modal/);
assert.match(styles, /\.pgp-keys-modal \.attachment-list\{grid-template-columns:minmax\(0,1fr\)\}/);
assert.match(styles, /\.pgp-keys-modal \.attachment-row-info\{flex:1 0 100%\}/);
assert.match(styles, /\.pgp-keys-modal \.attachment-row-info small\{[^}]*white-space:normal;overflow-wrap:anywhere/);
assert.match(styles, /\.pgp-keys-modal \.pgp-actions\{flex-wrap:wrap\}/);
});
test('mailbox setup exposes ports and TLS modes and submits them to Android', () => {
for (const id of ['mail-account-imap-port', 'mail-account-imap-secure', 'mail-account-smtp-port', 'mail-account-smtp-secure']) {
assert.ok(mailUi.includes(`id="${id}"`), `missing account field ${id}`);
@@ -91,6 +100,15 @@ test('Android app lock is native-enforced and requires a secure device credentia
assert.match(mainActivity, /FLAG_SECURE/);
});
test('Android private-key picker preserves WebView restrictions and checks app lock', () => {
assert.match(plugin, /fun pickPgpPrivateKey\(call: PluginCall\)/);
assert.match(plugin, /AndroidAccountVault\.appLockEnabled\(\)/);
assert.match(plugin, /Intent\.ACTION_OPEN_DOCUMENT/);
assert.match(plugin, /uri\.scheme != "content"/);
assert.match(plugin, /BoundedInputReader\.read\(it, 200001\)/);
assert.match(plugin, /bytes\.isEmpty\(\) \|\| bytes\.size > 200000/);
});
test('Android biometric PGP unlock keeps secrets behind an authentication-bound Keystore key', () => {
assert.match(plugin, /fun setPgpBiometricUnlock/);
assert.match(plugin, /fun getPgpBiometricPassphrase/);
@@ -172,7 +190,7 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
assert.match(androidBridge, /buildOutgoing\(message\)/);
assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
assert.match(androidMailService, /private fun validateOpenPgpMime/);
assert.match(androidMailService, /internal fun validateOpenPgpMime/);
assert.match(androidMailService, /"send" -> send\(account, data\)/);
assert.match(androidMailService, /private fun isEncryptedMessage/);
});
+19
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 build = fs.readFileSync(path.join(root, 'scripts', 'build.ps1'), 'utf8');
const linuxBuild = fs.readFileSync(path.join(root, 'scripts', 'build-linux-wsl.sh'), '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');
@@ -34,10 +36,27 @@ test('Android version name and code derive from the canonical package version',
test('release scripts and desktop artifact labels use package.json version', () => {
assert.match(buildAll, /package\.json/);
assert.match(build, /package\.json/);
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
});
test('build scripts retain the basic targets and add the Windows installer and isolated WSL builds', () => {
assert.match(build, /npm run android:apk/);
assert.match(build, /npm run dist:win:portable/);
assert.match(buildAll, /build\.ps1/);
assert.match(buildAll, /npm run dist:win:installer/);
assert.match(buildAll, /--distribution/);
assert.match(buildAll, /build-linux-wsl\.sh/);
assert.match(linuxBuild, /mktemp -d/);
assert.match(linuxBuild, /--exclude='\.\/node_modules'/);
assert.match(linuxBuild, /npm ci/);
assert.match(linuxBuild, /npm run dist:linux/);
assert.match(linuxBuild, /appimages=/);
assert.match(linuxBuild, /debs=/);
assert.doesNotMatch(linuxBuild, /\r/);
});
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/);
+178
View File
@@ -0,0 +1,178 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const root = path.resolve(__dirname, '..');
const mailSource = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
const pgpSource = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
const setupSource = mailSource.slice(mailSource.indexOf('function setupDraftComposer()'), mailSource.indexOf('\nasync function syncMailbox('));
function harness(initialDraft = null) {
const saved = [];
const deleted = [];
const toasts = [];
const elements = new Map();
const timers = new Map();
let nextTimer = 0;
let wrapped;
let saveDraft = async values => { saved.push(structuredClone(values)); return { id: values.id }; };
function node() {
const listeners = {};
return {
value: '', dataset: {}, isConnected: true, files: [], children: [],
classList: { contains: () => false },
append(...items) { this.children.push(...items); },
replaceChildren() { this.children = []; },
insertBefore(item) { this.children.push(item); },
setAttribute() {},
addEventListener(type, handler) { (listeners[type] ||= []).push(handler); },
dispatch(type, event = {}) { for (const handler of listeners[type] || []) handler(event); },
querySelector(selector) { return elements.get(selector); }
};
}
for (const name of ['#compose-to', '#compose-cc', '#compose-subject', '#compose-body', '#send', '#discard', '.modal-head span', '.compose-fields', '.compose-footer', '.modal-close', '.modal-overlay']) elements.set(name, node());
const modal = node();
const modalRoot = node();
modalRoot.querySelector = selector => selector === '.compose-modal' ? modal : elements.get(selector);
const context = {
appShell: { wrapShowCompose(fn) { wrapped = fn(() => {}); } },
selectMailUi: selector => selector === '#modal-root' ? modalRoot : elements.get(selector),
document: { createElement: node },
window: { crypto: { randomUUID: () => 'new-id' }, daybreakMail: {
saveDraft: values => saveDraft(values),
async deleteDraft(id) { deleted.push(id); }
} },
rendererState: { activeFolder: 'Inbox' },
syncMailbox() {},
toastMailUi: message => toasts.push(message),
setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; },
clearTimeout(id) { timers.delete(id); },
btoa: value => Buffer.from(value, 'binary').toString('base64')
};
vm.runInNewContext(`${setupSource}\nsetupDraftComposer();`, context);
wrapped(null, false, initialDraft);
return {
modal, modalRoot, elements, saved, deleted, toasts,
setSave(fn) { saveDraft = fn; },
async runTimers() { for (const fn of [...timers.values()]) fn(); timers.clear(); await new Promise(resolve => setImmediate(resolve)); },
async settle() { await new Promise(resolve => setImmediate(resolve)); }
};
}
test('PGP composer forwards the complete draft to the wrapped composer', () => {
const start = pgpSource.indexOf('pgpMailUi.wrapShowCompose(');
const end = pgpSource.indexOf('\n// Called by the send handler', start);
let args;
const context = {
pgpMailUi: { wrapShowCompose(decorator) { decorator((...values) => { args = values; })(null, false, { id: 'existing', text: 'saved text' }); } },
selectPgpMailUi: () => null
};
vm.runInNewContext(pgpSource.slice(start, end), context);
assert.equal(args[2].id, 'existing');
assert.equal(args[2].text, 'saved text');
});
test('reopening a draft restores fields, attachments, and its identity', () => {
const draft = { id: 'existing', to: 'a@example.test', cc: 'b@example.test', subject: 'Subject', text: 'Message', attachments: [{ filename: 'note.txt' }] };
const h = harness(draft);
assert.equal(h.modal.dataset.draftId, draft.id);
for (const [field, value] of [['to', draft.to], ['cc', draft.cc], ['subject', draft.subject], ['body', draft.text]]) {
assert.equal(h.elements.get(`#compose-${field}`).value, value);
}
assert.equal(h.modal._composeAttachments[0].filename, 'note.txt');
assert.equal(h.elements.get('.modal-head span').textContent, 'Edit draft');
});
test('blank and whitespace-only new messages are not saved on close or manual save', async () => {
const h = harness();
h.elements.get('#compose-body').value = ' \n ';
h.modal.dispatch('input');
await h.runTimers();
const save = h.elements.get('.compose-footer').children.find(item => item.id === 'save-draft');
await save.onclick();
assert.equal(h.toasts.at(-1), 'Nothing to save in this draft');
h.elements.get('.modal-close').dispatch('click');
await h.settle();
assert.equal(h.saved.length, 0);
assert.equal(h.modal.dataset.draftId, '');
});
test('closing via overlay or Escape saves meaningful unsaved text', async () => {
for (const method of ['overlay', 'escape']) {
const h = harness();
h.elements.get('#compose-subject').value = 'Saved subject';
if (method === 'overlay') h.elements.get('.modal-overlay').dispatch('click', { target: { classList: { contains: () => true } } });
else h.modal.dispatch('keydown', { key: 'Escape' });
await h.settle();
assert.equal(h.saved.length, 1);
assert.equal(h.saved[0].subject, 'Saved subject');
}
});
test('attachment-only drafts are saved and picker cancellation creates nothing', async () => {
const h = harness();
const attachmentRow = h.elements.get('.compose-fields').children[0];
const input = attachmentRow.children[1].children[1];
await input.onchange();
assert.equal(h.saved.length, 0);
input.files = [{ name: 'note.txt', type: 'text/plain', size: 3, async arrayBuffer() { return Uint8Array.from([97, 98, 99]).buffer; } }];
await input.onchange();
assert.equal(h.saved.length, 1);
assert.equal(h.saved[0].attachments[0].contentBase64, 'YWJj');
});
test('pending saves are serialized and discard waits before deleting', async () => {
const h = harness();
let finishFirst;
const calls = [];
h.setSave(values => {
calls.push(values.text);
if (calls.length === 1) return new Promise(resolve => { finishFirst = resolve; });
return Promise.resolve({ id: values.id });
});
h.elements.get('#compose-body').value = 'first';
h.modal.dispatch('input');
await h.runTimers();
h.elements.get('#compose-body').value = 'second';
h.modal.dispatch('input');
await h.runTimers();
const discard = h.elements.get('#discard').onclick();
assert.deepEqual(calls, ['first']);
assert.deepEqual(h.deleted, []);
finishFirst({ id: 'new-id' });
await discard;
assert.deepEqual(calls, ['first', 'second']);
assert.deepEqual(h.deleted, ['new-id']);
});
test('sent draft cleanup cancels unsaved timers and waits for in-flight saves', async () => {
const h = harness();
let finishSave;
h.setSave(() => new Promise(resolve => { finishSave = resolve; }));
h.elements.get('#compose-body').value = 'sent message';
h.modal.dispatch('input');
await h.runTimers();
h.elements.get('#compose-body').value = 'newer edit';
h.modal.dispatch('input');
const cleanup = h.modal._deleteSavedDraft();
await h.runTimers();
assert.deepEqual(h.deleted, []);
finishSave({ id: 'new-id' });
await cleanup;
assert.deepEqual(h.deleted, ['new-id']);
});
test('a failed save reports an error and a later save can retry', async () => {
const h = harness();
h.elements.get('#compose-body').value = 'message';
h.setSave(async () => { throw new Error('Storage unavailable'); });
const save = h.elements.get('.compose-footer').children.find(item => item.id === 'save-draft');
await save.onclick();
assert.equal(h.toasts.at(-1), 'Storage unavailable');
h.setSave(async values => { h.saved.push(values); return { id: values.id }; });
await save.onclick();
assert.equal(h.saved.length, 1);
assert.equal(h.toasts.at(-1), 'Draft saved on this device');
});
+70
View File
@@ -0,0 +1,70 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '..', 'pgp-ui.js'), 'utf8');
async function openKeySettings(platform) {
const elements = new Map();
function element(selector) {
if (!elements.has(selector)) elements.set(selector, {
value: '', textContent: '', innerHTML: '',
append() {}, replaceChildren() {}, focus() { this.focused = true; },
querySelector: element
});
return elements.get(selector);
}
const calls = [];
const pgp = {
platform,
async list() { return []; },
async contacts() { return []; },
async keyServers() { return []; },
async getSettings() { return { cacheMinutes: 0 }; },
async importKey(input) { calls.push(input); return { canceled: false }; }
};
let wrap;
const window = {
daybreakMail: { pgp },
epMailFeatures: {
mail: { select: element, selectAll: () => [], escapeHtml: value => value, toast() {}, connectedAccount: { id: 'account-1' } },
productivity: { wrapOpenPreferences(fn) { wrap = fn; } }
}
};
let openButton;
const document = { createElement() { openButton = {}; return openButton; } };
element('#modal-root .compose-fields').append = button => { openButton = button; };
vm.runInNewContext(source, { window, document });
await wrap(async () => {})();
openButton.onclick();
return { element, calls, pgp };
}
test('Android private-key controls route file and paste imports with the account and passphrase', async () => {
const { element, calls, pgp } = await openKeySettings('android');
assert.match(element('#modal-root').innerHTML, /Import private key from file/);
await element('#pgp-import').onclick();
assert.equal(calls.length, 0);
assert.equal(element('#pgp-passphrase').focused, true);
element('#pgp-passphrase').value = 'test passphrase';
await element('#pgp-import').onclick();
await element('#pgp-import-paste').onclick();
assert.equal(calls[0].source, 'file');
assert.equal(calls[1].source, 'paste');
assert.equal(calls[0].passphrase, 'test passphrase');
assert.equal(calls[0].accountId, 'account-1');
pgp.importKey = async () => { throw new Error('File read failed'); };
await element('#pgp-import').onclick();
assert.equal(element('#pgp-status').textContent, 'File read failed');
});
test('desktop private-key import retains its existing file-picker API', async () => {
const { element, calls } = await openKeySettings('desktop');
assert.doesNotMatch(element('#modal-root').innerHTML, /pgp-import-paste/);
element('#pgp-passphrase').value = 'test passphrase';
await element('#pgp-import').onclick();
assert.equal(calls.length, 1);
assert.equal(Object.hasOwn(calls[0], 'source'), false);
});