199 lines
11 KiB
JavaScript
199 lines
11 KiB
JavaScript
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
|
|
const mailUi = window.epMailFeatures.mail;
|
|
const $ = mailUi.select;
|
|
const $$ = mailUi.selectAll;
|
|
const toast = mailUi.toast;
|
|
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 ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(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 ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(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' });
|
|
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
|
} catch (error) {
|
|
toast(error.message || 'Could not add the key');
|
|
}
|
|
}
|
|
|
|
function pgpRenderReaderState(message) {
|
|
const reader = $('#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.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>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(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 = $('#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) {
|
|
toast(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 (mailUi.state.activeMessage === message.id) mailUi.openMessage(message.id);
|
|
return;
|
|
}
|
|
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
|
if (!interactive) { pgpRenderReaderState(message); return; }
|
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
|
if (passphrase === null) return;
|
|
continue;
|
|
}
|
|
const text = $('#pgp-banner-text');
|
|
if (text) text.textContent = result.message;
|
|
else toast(result.message);
|
|
return;
|
|
}
|
|
}
|
|
|
|
mailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
|
baseOpenMessage(id);
|
|
const message = mailUi.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);
|
|
}
|
|
});
|
|
|
|
// Compose: encrypt/sign options.
|
|
mailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|
baseShowCompose(reply, forward);
|
|
const footer = $('#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><small id="pgp-hint"></small>`;
|
|
footer.prepend(box);
|
|
let touched = false;
|
|
const encrypt = $('#pgp-encrypt');
|
|
const sign = $('#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 = $('#compose-to')?.value || '';
|
|
const cc = $('#compose-cc')?.value || '';
|
|
const hint = $('#pgp-hint');
|
|
if (!hint) return;
|
|
if (!to.trim()) { hint.textContent = ''; return; }
|
|
try {
|
|
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
|
if (!$('#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 === 'unknown') ? '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 => $(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;
|
|
let encrypt = Boolean($('#pgp-encrypt')?.checked);
|
|
const sign = Boolean($('#pgp-sign')?.checked);
|
|
if (!encrypt && !sign && $('#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 && $('#pgp-encrypt')?.dataset.touched !== '1') {
|
|
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
|
if (!sign) return null;
|
|
} 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 null;
|
|
}
|
|
let passphrase = null;
|
|
if (sign) {
|
|
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
|
|
if (!status.signer.unlocked) {
|
|
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 });
|