Files

234 lines
13 KiB
JavaScript

(() => {
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
const pgpMailUi = window.epMailFeatures.mail;
const selectPgpMailUi = pgpMailUi.select;
const selectAllPgpMailUi = pgpMailUi.selectAll;
const toastPgpMailUi = pgpMailUi.toast;
const escapePgpMailUi = pgpMailUi.escapeHtml;
const pgpApi = () => window.daybreakMail?.pgp;
function pgpAskPassphrase(title, detail) {
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay pgp-prompt';
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
overlay.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.account-note').textContent = detail;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => {
event.preventDefault();
const value = overlay.querySelector('input').value;
if (value) finish(value);
};
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
overlay.querySelector('input').focus();
});
}
function pgpFormatFingerprint(value) {
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
}
function pgpSignatureHtml(signatures, encrypted) {
const items = Array.isArray(signatures) ? signatures : [];
const lock = encrypted ? '🔒 Encrypted. ' : '';
if (!items.length) {
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
}
return items.map(signature => {
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
const notes = [];
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
if (signature.status === 'valid') {
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
}
if (signature.status === 'unknown-key') {
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
}
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
}).join('');
}
async function pgpAddAttachedKey(key) {
const emails = key.emails.join(', ') || 'unknown address';
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
try {
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
} catch (error) {
toastPgpMailUi(error.message || 'Could not add the key');
}
}
function pgpRenderReaderState(message) {
const reader = selectPgpMailUi('#reader-pane');
const header = reader.querySelector('.reader-header');
if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
let html = '';
if (message.encrypted && !message.pgpDecrypted) {
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
} else if (message.encrypted) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.signed && Array.isArray(message.pgpSignatures)) {
html = pgpSignatureHtml(message.pgpSignatures, false);
} else if (message.signed && message.pgpVerifyFailed) {
html = `<section class="pgp-status pgp-warn" role="status"><strong>Could not check the OpenPGP signature</strong><span>${escapePgpMailUi(message.pgpVerifyFailed)}</span></section>`;
} else if (message.signed) {
html = '<section class="pgp-status pgp-warn" role="status"><strong>Checking OpenPGP signature…</strong><span>Do not rely on this message until verification completes.</span></section>';
} else if (message.pgpSignatures) {
html = pgpSignatureHtml(message.pgpSignatures, false);
}
const keys = message.pgpResult?.attachedKeys || [];
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
});
const unlock = selectPgpMailUi('#pgp-unlock');
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
}
async function pgpUnlockMessage(message, interactive) {
let passphrase = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
let result;
try {
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
} catch (error) {
toastPgpMailUi(error.message || 'Could not open this message');
return;
}
if (result.ok) {
Object.assign(message, {
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
});
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') {
if (!interactive) { pgpRenderReaderState(message); return; }
const prompt = result.code === 'BAD_PASSPHRASE'
? 'That passphrase was incorrect. Try again.'
: result.code === 'BIOMETRIC_INVALIDATED'
? `${result.message} Enter the passphrase to continue.`
: `Enter the passphrase for ${result.email || 'your key'}.`;
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
if (passphrase === null) return;
continue;
}
const text = selectPgpMailUi('#pgp-banner-text');
if (text) text.textContent = result.message;
else toastPgpMailUi(result.message);
return;
}
}
async function pgpVerifyMessage(message) {
try {
const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid });
if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.';
else {
message.pgpSignatures = result.signatures || [];
message.pgpVerifyFailed = null;
}
} catch (error) {
message.pgpVerifyFailed = error.message || 'The signature could not be checked.';
}
if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message);
}
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id);
const message = pgpMailUi.state.messages.find(item => item.id === id);
if (!message || !pgpApi()) return;
pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
message.pgpAutoTried = true;
void pgpUnlockMessage(message, false);
}
if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) {
message.pgpVerifyTried = true;
void pgpVerifyMessage(message);
}
});
// Compose: encrypt/sign options.
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false, draft = null) {
baseShowCompose(reply, forward, draft);
const footer = selectPgpMailUi('#modal-root .compose-footer');
if (!footer || !pgpApi()) return;
const box = document.createElement('div');
box.className = 'pgp-compose';
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
footer.prepend(box);
let touched = false;
const encrypt = selectPgpMailUi('#pgp-encrypt');
const sign = selectPgpMailUi('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null;
const refresh = async () => {
const to = selectPgpMailUi('#compose-to')?.value || '';
const cc = selectPgpMailUi('#compose-cc')?.value || '';
const hint = selectPgpMailUi('#pgp-hint');
if (!hint) return;
if (!to.trim()) { hint.textContent = ''; return; }
try {
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
if (!selectPgpMailUi('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else {
hint.textContent = status.recipients.some(item => item.trust !== 'verified') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
if (!touched && !encrypt.checked) encrypt.checked = true;
}
} catch { hint.textContent = ''; }
};
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
sign.addEventListener('change', schedule);
schedule();
});
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
async function prepareSend(to, cc) {
if (!pgpApi()) return null;
const plaintextFallback = () => pgpApi().platform === 'android'
? { encrypt: false, sign: false, plaintextFallback: true }
: null;
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return plaintextFallback();
} else return false;
}
if (!encrypt && !sign) return null;
if (encrypt && status.missing.length) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false;
encrypt = false;
if (!sign) return plaintextFallback();
}
let passphrase = null;
if (sign) {
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
}
}
return { encrypt, sign, passphrase };
}
window.epMailFeatures.pgp = Object.freeze({ prepareSend });
})();