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); });