import * as openpgp from 'openpgp'; const MAX_KEY_LENGTH = 200000; const MAX_MESSAGE_BYTES = 25 * 1024 * 1024; const TRUST = ['unknown', 'trusted', 'verified']; const encoder = new TextEncoder(); const decoder = new TextDecoder(); function parseAddresses(value) { return String(value || '').split(',').map(part => { const text = part.trim(); if (!text) return null; const match = /^(.*?)\s*<([^<>]+)>$/.exec(text); const address = (match?.[2] || text).trim().toLowerCase(); const name = (match?.[1] || '').replace(/^"|"$/g, '').trim(); if (!/^[^\s@<>(),;]+@[^\s@<>(),;]+\.[^\s@<>(),;]+$/.test(address)) { throw new Error(`"${text || 'recipient'}" is not a valid email address.`); } return { address, name }; }).filter(Boolean); } function emailsOf(key) { return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))]; } function splitEntity(value) { const text = typeof value === 'string' ? value : decoder.decode(value); const normalized = text.replace(/\r?\n/g, '\r\n'); const split = normalized.indexOf('\r\n\r\n'); if (split < 0) throw new Error('Malformed MIME message.'); const headerText = normalized.slice(0, split); const body = normalized.slice(split + 4); const headers = {}; let current = ''; for (const line of headerText.split('\r\n')) { if (/^[ \t]/.test(line) && current) headers[current] += ` ${line.trim()}`; else { const colon = line.indexOf(':'); if (colon > 0) { current = line.slice(0, colon).trim().toLowerCase(); headers[current] = line.slice(colon + 1).trim(); } } } return { headers, body }; } function parameter(value, name) { const match = new RegExp(`(?:^|;)\\s*${name}\\s*=\\s*(?:"([^"]+)"|([^;\\s]+))`, 'i').exec(value || ''); return match?.[1] || match?.[2] || ''; } function decodePart(body, transferEncoding) { const value = body.replace(/\r\n--[^\r\n]*$/, '').replace(/\r\n$/, ''); if (/base64/i.test(transferEncoding || '')) { const compact = value.replace(/[\r\n\t ]/g, ''); const binary = atob(compact); return Uint8Array.from(binary, char => char.charCodeAt(0)); } if (/quoted-printable/i.test(transferEncoding || '')) { const bytes = []; for (let index = 0; index < value.length; index += 1) { if (value[index] === '=' && value[index + 1] === '\r' && value[index + 2] === '\n') { index += 2; continue; } if (value[index] === '=' && /^[0-9a-f]{2}$/i.test(value.slice(index + 1, index + 3))) { bytes.push(parseInt(value.slice(index + 1, index + 3), 16)); index += 2; } else bytes.push(value.charCodeAt(index) & 255); } return Uint8Array.from(bytes); } return encoder.encode(value); } function splitMultipart(body, boundary) { if (!boundary || boundary.length > 200) return []; const mark = `--${boundary}`; return body.split(mark).slice(1).filter(part => !part.startsWith('--')) .map(part => part.replace(/^\r?\n/, '').replace(/\r?\n$/, '')) .filter(part => part.trim()); } function parseInnerMime(bytes) { const result = { body: '', html: '', attachments: [] }; const visit = (source, depth = 0) => { if (depth > 8) return; const entity = splitEntity(source); const type = entity.headers['content-type'] || 'text/plain; charset=utf-8'; const transfer = entity.headers['content-transfer-encoding'] || ''; const disposition = entity.headers['content-disposition'] || ''; const boundary = parameter(type, 'boundary'); if (/^multipart\//i.test(type) && boundary) { for (const part of splitMultipart(entity.body, boundary)) visit(part, depth + 1); return; } const data = decodePart(entity.body, transfer); const filename = parameter(disposition, 'filename') || parameter(type, 'name'); if (filename || /^attachment/i.test(disposition)) { if (result.attachments.length < 50 && data.length <= 25 * 1024 * 1024) { let binary = ''; for (let index = 0; index < data.length; index += 0x8000) { binary += String.fromCharCode(...data.subarray(index, index + 0x8000)); } result.attachments.push({ filename: (filename || 'attachment').replace(/[\\/\r\n\u0000]/g, '').slice(0, 255) || 'attachment', contentType: type.split(';')[0].trim() || 'application/octet-stream', size: data.length, contentBase64: btoa(binary) }); } return; } const text = decoder.decode(data); if (/^text\/html/i.test(type) && !result.html) result.html = text.slice(0, 100000); else if (/^text\/plain/i.test(type) && !result.body) result.body = text.slice(0, 500000); }; visit(bytes); return result; } async function attachedPublicKeys(attachments) { const found = []; for (const file of attachments || []) { const type = String(file.contentType || '').toLowerCase(); if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue; if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue; try { const binary = atob(file.contentBase64); const armoredKey = decoder.decode(Uint8Array.from(binary, char => char.charCodeAt(0))).trim(); if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) || /-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue; const key = await openpgp.readKey({ armoredKey }); await key.getPrimaryUser(); found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) }); if (found.length === 5) break; } catch { /* ignore malformed, expired or non-public key attachments */ } } return found; } function randomBoundary() { const bytes = crypto.getRandomValues(new Uint8Array(18)); return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`; } function safeHeader(value, max = 900) { return String(value || '').replace(/[\r\n\u0000]+/g, ' ').trim().slice(0, max); } function formatAddress(entry) { const address = entry.address; const name = safeHeader(entry.name, 100).replace(/["\\]/g, ' '); return name ? `${encodeHeader(name)} <${address}>` : address; } function encodeHeader(value) { const clean = safeHeader(value, 998); if (/^[\x20-\x7e]*$/.test(clean)) return clean; return `=?UTF-8?B?${toBase64(encoder.encode(clean))}?=`; } function mimeInner(text, attachments) { const files = Array.isArray(attachments) ? attachments : []; if (files.length > 50 || files.reduce((total, file) => total + String(file?.contentBase64 || '').length, 0) > 36_000_000) { throw new Error('The encrypted message attachments exceed the Android testing size limit.'); } if (!files.length) { const bytes = encoder.encode(String(text || '')); let binary = ''; for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000)); const base64 = btoa(binary).replace(/.{1,76}/g, '$&\r\n').trim(); return `Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${base64}\r\n`; } const mark = randomBoundary(); const parts = [`--${mark}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n${String(text || '').replace(/\r?\n/g, '\r\n')}\r\n`]; for (const file of files) { const filename = safeHeader(file.filename || 'attachment', 180).replace(/["\\]/g, '_') || 'attachment'; const type = String(file.contentType || 'application/octet-stream').toLowerCase(); if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(type)) throw new Error(`The content type for ${filename} is invalid.`); const base64 = String(file.contentBase64 || '').replace(/\s/g, ''); if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(base64)) throw new Error(`The contents of ${filename} are invalid.`); parts.push(`--${mark}\r\nContent-Type: ${type}; name="${filename}"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename="${filename}"\r\n\r\n${base64.replace(/.{1,76}/g, '$&\r\n').trim()}\r\n`); } parts.push(`--${mark}--\r\n`); return `Content-Type: multipart/mixed; boundary="${mark}"\r\n\r\n${parts.join('')}`; } function toBase64(bytes) { let binary = ''; for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000)); return btoa(binary); } function bytesToLatin1(bytes) { let text = ''; for (let index = 0; index < bytes.length; index += 0x8000) { text += String.fromCharCode(...bytes.subarray(index, index + 0x8000)); } return text; } function splitSignedMime(source, boundary) { if (!boundary || boundary.length > 200) return null; const text = bytesToLatin1(source); const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g'); const marks = [...text.matchAll(delimiter)]; if (marks.length < 3) return null; const contentAfter = mark => { const lineEnd = text.indexOf('\n', mark.index + mark[0].length); return lineEnd < 0 ? text.length : lineEnd + 1; }; const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n'); const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index); const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0]; if (!signature) return null; return { signed: Uint8Array.from(signed, char => char.charCodeAt(0) & 255), signature }; } function senderFrom(headers) { const value = String(headers.from || ''); return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || '').toLowerCase(); } function invalidSignature() { return { status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }; } async function signatureStatuses(signatures, verification, sender) { const results = []; for (const signature of signatures || []) { const keyId = signature.keyID.toHex().toUpperCase(); const known = verification.find(candidate => candidate.key.getKeys() .some(key => key.getKeyID().toHex().toUpperCase() === keyId)); let status = 'valid'; try { await signature.verified; } catch { status = known ? 'invalid' : 'unknown-key'; } const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); const matchesSender = Boolean(sender && keyEmails.includes(sender)); const changed = Boolean(sender && verification.some(candidate => !candidate.entry.own && candidate.entry.emails?.includes(sender) && candidate.entry.fingerprint !== known?.entry.fingerprint)); results.push({ status, keyId, fingerprint: known?.entry.fingerprint || null, trust: known?.entry.trust || null, email: keyEmails[0] || null, matchesSender, keyChanged: changed, ...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) }); } return results; } export function createAndroidPgp({ EpMail, getAccount }) { let storePromise; const passphrases = new Map(); let cacheMinutes = 10; async function store() { if (!storePromise) storePromise = EpMail.pgpLoadStore().then(value => { const savedMinutes = Number(value?.settings?.cacheMinutes); if (Number.isFinite(savedMinutes) && savedMinutes >= 0 && savedMinutes <= 1440) cacheMinutes = Math.round(savedMinutes); return value; }).catch(error => { storePromise = null; throw error; }); return storePromise.then(value => JSON.parse(JSON.stringify(value))); } async function persist(value) { await EpMail.pgpSaveStore({ store: value }); storePromise = Promise.resolve(JSON.parse(JSON.stringify(value))); } function cache(fingerprint, passphrase) { if (!cacheMinutes) { passphrases.delete(fingerprint); return; } passphrases.set(fingerprint, { passphrase, expires: Date.now() + cacheMinutes * 60000 }); } function cached(fingerprint) { const item = passphrases.get(fingerprint); if (!item) return null; if (item.expires <= Date.now()) { passphrases.delete(fingerprint); return null; } return item.passphrase; } function clear(fingerprint) { if (fingerprint) passphrases.delete(fingerprint); else passphrases.clear(); } function publicInfo(entry) { return { fingerprint: entry.fingerprint, name: entry.name, email: entry.email, accountId: entry.accountId || null, createdAt: entry.createdAt, algorithm: entry.algorithm, hasRevocationCertificate: Boolean(entry.revocationCertificate) }; } async function verificationKeys(data) { const output = []; for (const entry of [...data.contacts, ...data.keys.map(key => ({ ...key, emails: [String(key.email).toLowerCase()], trust: 'verified', own: true }))]) { try { output.push({ entry, key: await openpgp.readKey({ armoredKey: entry.publicKey }) }); } catch { /* malformed records are ignored, never trusted */ } } return output; } async function addContact({ armoredKey, source = 'import' }) { const armored = String(armoredKey || '').trim(); if (!armored || armored.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('Import a valid public key (maximum 200 KB).'); const key = await openpgp.readKey({ armoredKey: armored }).catch(() => { throw new Error('That is not a valid OpenPGP public key.'); }); await key.getPrimaryUser().catch(() => { throw new Error('That key is expired, revoked or has no valid user ID.'); }); const fingerprint = key.getFingerprint().toUpperCase(); const emails = emailsOf(key); const data = await store(); if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.'); if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.'); const keyChangedFrom = data.contacts.filter(entry => entry.emails.some(email => emails.includes(email))).map(entry => entry.fingerprint); if (keyChangedFrom.length && !confirm(`A different public key is already stored for ${emails.join(', ')}.\n\nNew fingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nExisting fingerprint(s):\n${keyChangedFrom.map(value => value.match(/.{1,4}/g).join(' ')).join('\n')}\n\nAdd the new key as an unverified key? Compare fingerprints with the owner before trusting it.`)) { return { canceled: true, keyChangedFrom }; } const user = await key.getPrimaryUser(); data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source: ['import', 'message', 'paste'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() }); await persist(data); return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom }; } async function resolveRecipients(addresses) { const data = await store(); const pool = [ ...data.contacts.map(entry => ({ ...entry, own: false })), ...data.keys.map(entry => ({ ...entry, emails: [String(entry.email).toLowerCase()], trust: 'verified', own: true })) ]; const resolved = []; const missing = []; for (const address of addresses) { const candidates = pool.filter(entry => entry.emails.includes(address)).sort((a, b) => TRUST.indexOf(b.trust) - TRUST.indexOf(a.trust) || b.addedAt - a.addedAt); let found = null; for (const candidate of candidates) { try { const key = await openpgp.readKey({ armoredKey: candidate.publicKey }); await key.getEncryptionKey(); found = { address, key, fingerprint: candidate.fingerprint, trust: candidate.trust }; break; } catch { /* try next usable key */ } } if (found) resolved.push(found); else missing.push(address); } return { keys: resolved, missing }; } async function unlock(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: entry.privateKey }), passphrase }); } catch { throw new Error('The passphrase is incorrect.'); } } async function signerFor(account, passphrase) { const data = await store(); const entry = data.keys.find(item => item.email.toLowerCase() === String(account.email).toLowerCase()); if (!entry) throw Object.assign(new Error('Create or import an encryption key for this address first.'), { code: 'NO_SIGNING_KEY' }); const secret = passphrase || cached(entry.fingerprint); if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email} to sign this message.`), { code: 'PASSPHRASE_REQUIRED', fingerprint: entry.fingerprint, email: entry.email }); try { const key = await unlock(entry.fingerprint, secret); cache(entry.fingerprint, secret); return { key, entry }; } catch { clear(entry.fingerprint); throw Object.assign(new Error('The passphrase is incorrect.'), { code: 'BAD_PASSPHRASE', fingerprint: entry.fingerprint, email: entry.email }); } } async function buildOutgoing(message) { const account = await getAccount(); if (!account?.email) throw new Error('Add a mail account before encrypting messages.'); const to = parseAddresses(message.to); const cc = parseAddresses(message.cc); const everyone = [...to, ...cc]; if (!to.length) throw new Error('Add at least one recipient.'); const from = { name: safeHeader(account.displayName || message.displayName || account.email, 100), address: account.email }; const pgp = message.pgp || {}; const data = await store(); let signer = null; if (pgp.sign) signer = await signerFor(account, pgp.passphrase || null); const recipientKeys = pgp.encrypt ? await resolveRecipients(everyone.map(item => item.address)) : { keys: [], missing: [] }; if (pgp.encrypt && recipientKeys.missing.length) { throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(', ')}.`), { code: 'NO_RECIPIENT_KEY', missing: recipientKeys.missing }); } let inner = mimeInner(`${String(message.text || '').slice(0, 500000)}${account.signature ? `\n\n${String(account.signature).slice(0, 5000)}` : ''}`, message.attachments || []); const headers = [ `From: ${formatAddress(from)}`, `To: ${to.map(formatAddress).join(', ')}`, ...(cc.length ? [`Cc: ${cc.map(formatAddress).join(', ')}`] : []), `Subject: ${encodeHeader(message.subject || '(no subject)')}`, `Date: ${new Date().toUTCString().replace('GMT', '+0000')}`, `Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`, 'MIME-Version: 1.0' ]; let contentType; let body; const boundary = randomBoundary(); if (pgp.encrypt) { const own = data.keys.find(entry => entry.email.toLowerCase() === account.email.toLowerCase()); const encryptionKeys = [...recipientKeys.keys.map(item => item.key)]; if (own) encryptionKeys.push(await openpgp.readKey({ armoredKey: own.publicKey })); if (signer && !encryptionKeys.some(key => key.getFingerprint().toUpperCase() === signer.entry.fingerprint)) encryptionKeys.push(await openpgp.readKey({ armoredKey: signer.entry.publicKey })); const encrypted = await openpgp.encrypt({ message: await openpgp.createMessage({ binary: encoder.encode(inner) }), encryptionKeys, signingKeys: signer?.key, format: 'armored' }); contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`; body = `--${boundary}\r\nContent-Type: application/pgp-encrypted\r\nContent-Description: PGP/MIME version identification\r\n\r\nVersion: 1\r\n--${boundary}\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\nContent-Description: OpenPGP encrypted message\r\nContent-Disposition: inline; filename="encrypted.asc"\r\n\r\n${String(encrypted).replace(/\r?\n/g, '\r\n')}\r\n--${boundary}--\r\n`; } else { if (!pgp.sign || !signer) throw new Error('Choose encryption or signing for this message.'); const signedBytes = encoder.encode(inner.replace(/\r?\n/g, '\r\n')); const signature = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signer.key, detached: true, format: 'armored' }); contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${boundary}"`; body = `--${boundary}\r\n${decoder.decode(signedBytes)}\r\n--${boundary}\r\nContent-Type: application/pgp-signature; name="signature.asc"\r\nContent-Description: OpenPGP digital signature\r\nContent-Disposition: attachment; filename="signature.asc"\r\n\r\n${String(signature).replace(/\r?\n/g, '\r\n')}\r\n--${boundary}--\r\n`; } const raw = encoder.encode(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`); if (raw.byteLength > MAX_MESSAGE_BYTES) throw new Error('This encrypted message is too large to send.'); return { rawBase64: toBase64(raw), to: everyone.map(item => item.address), from: account.email }; } async function decryptMessage({ folder = 'Inbox', uid, passphrase = null }) { try { const source = await EpMail.pgpGetMessageSource({ folder, uid }); const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0)); if (raw.byteLength > MAX_MESSAGE_BYTES) return { failed: true, code: 'TOO_LARGE', message: 'This encrypted message is too large to open.' }; const text = decoder.decode(raw); const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(text)?.[0]; if (!armor) return { failed: true, code: 'CORRUPT', message: 'The encrypted part of this message is missing or damaged.' }; const message = await openpgp.readMessage({ armoredMessage: armor }).catch(() => null); if (!message) return { failed: true, code: 'CORRUPT', message: 'The encrypted part of this message is damaged.' }; const wanted = new Set(message.getEncryptionKeyIDs().map(item => item.toHex().toUpperCase())); const data = await store(); const candidates = []; for (const entry of data.keys) { const key = await openpgp.readKey({ armoredKey: entry.publicKey }).catch(() => null); if (key?.getKeys().some(item => wanted.has(item.getKeyID().toHex().toUpperCase()))) candidates.push(entry); } if (!candidates.length) return { failed: true, code: 'NO_KEY', message: 'None of your keys can decrypt this message.' }; let secret = passphrase; let selected = candidates[0]; if (!secret) { selected = candidates.find(entry => cached(entry.fingerprint)) || selected; secret = cached(selected.fingerprint); } if (!secret) return { failed: true, code: 'PASSPHRASE_REQUIRED', fingerprint: selected.fingerprint, email: selected.email, message: 'Enter your key passphrase to read this message.' }; let privateKey; try { privateKey = await unlock(selected.fingerprint, secret); } catch { clear(selected.fingerprint); return { failed: true, code: 'BAD_PASSPHRASE', fingerprint: selected.fingerprint, email: selected.email, message: 'The passphrase is incorrect.' }; } cache(selected.fingerprint, secret); const verify = await verificationKeys(data); let decrypted; try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); } catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; } const content = parseInnerMime(decrypted.data); const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers)); const attachedKeys = await attachedPublicKeys(content.attachments); return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html, links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null, size: content.attachments[0]?.size || '', signatures, attachedKeys }; } catch (error) { return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' }; } } async function verifyMessage({ folder = 'Inbox', uid }) { try { const source = await EpMail.pgpGetMessageSource({ folder, uid }); const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0)); if (raw.byteLength > MAX_MESSAGE_BYTES) { return { failed: true, code: 'TOO_LARGE', message: 'This signed message is too large to verify.' }; } const entity = splitEntity(raw); const contentType = entity.headers['content-type'] || ''; const sender = senderFrom(entity.headers); const data = await store(); const verification = await verificationKeys(data); if (/^multipart\/signed/i.test(contentType) && parameter(contentType, 'protocol').toLowerCase() === 'application/pgp-signature') { const parts = splitSignedMime(raw, parameter(contentType, 'boundary')); if (!parts) return { signatures: [invalidSignature()] }; try { const result = await openpgp.verify({ message: await openpgp.createMessage({ binary: parts.signed }), signature: await openpgp.readSignature({ armoredSignature: parts.signature }), verificationKeys: verification.map(item => item.key) }); return { signatures: await signatureStatuses(result.signatures, verification, sender) }; } catch { return { signatures: [invalidSignature()] }; } } const body = decoder.decode(decodePart(entity.body, entity.headers['content-transfer-encoding'])); const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0]; if (!armored) return { signatures: [] }; try { const message = await openpgp.readCleartextMessage({ cleartextMessage: armored }); const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) }); return { signatures: await signatureStatuses(result.signatures, verification, sender) }; } catch { return { signatures: [invalidSignature()] }; } } catch (error) { return { failed: true, code: error.code || 'VERIFY_ERROR', message: error.message || 'Could not verify this message.' }; } } const api = { platform: 'android', async list() { return (await store()).keys.map(publicInfo); }, async generate({ name, email, passphrase, accountId = null }) { const cleanEmail = String(email || '').trim().toLowerCase(); if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.'); if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.'); const generated = await openpgp.generateKey({ type: 'ecc', curve: 'curve25519Legacy', userIDs: [{ name: safeHeader(name, 100), email: cleanEmail }], passphrase, format: 'armored' }); const key = await openpgp.readKey({ armoredKey: generated.publicKey }); const data = await store(); if (data.keys.some(item => item.fingerprint === key.getFingerprint().toUpperCase())) throw new Error('That key is already in your keyring.'); const entry = { fingerprint: key.getFingerprint().toUpperCase(), name: safeHeader(name, 100), email: cleanEmail, accountId, createdAt: Date.now(), algorithm: 'Curve25519', privateKey: generated.privateKey, publicKey: generated.publicKey, revocationCertificate: generated.revocationCertificate }; data.keys.push(entry); await persist(data); return { key: publicInfo(entry), revocationCertificate: generated.revocationCertificate }; }, async importKey({ armoredKey, passphrase, accountId = null }) { if (!armoredKey) armoredKey = prompt('Paste an ASCII-armored OpenPGP private key (up to 200 KB):') || ''; const armored = String(armoredKey).trim(); if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.'); if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.'); const parsed = await openpgp.readPrivateKey({ armoredKey: armored }).catch(() => { throw new Error('That is not a valid OpenPGP private key.'); }); const protectedKey = parsed.isDecrypted() ? await openpgp.encryptKey({ privateKey: parsed, passphrase }) : parsed; if (!parsed.isDecrypted()) await openpgp.decryptKey({ privateKey: parsed, passphrase }).catch(() => { throw new Error('The passphrase is incorrect.'); }); const publicKey = protectedKey.toPublic(); const user = await protectedKey.getPrimaryUser().catch(() => null); const entry = { fingerprint: protectedKey.getFingerprint().toUpperCase(), name: user?.user?.userID?.name || '', email: user?.user?.userID?.email || '', accountId, createdAt: protectedKey.getCreationTime().getTime(), algorithm: protectedKey.getAlgorithmInfo().algorithm, privateKey: protectedKey.armor(), publicKey: publicKey.armor(), revocationCertificate: null }; const data = await store(); if (data.keys.some(item => item.fingerprint === entry.fingerprint)) throw new Error('That key is already in your keyring.'); data.keys.push(entry); await persist(data); return { key: publicInfo(entry) }; }, async exportPublic(fingerprint) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); return entry.publicKey; }, async exportPrivate(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); return entry.privateKey; }, async exportRevocation(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry?.revocationCertificate) throw new Error('No revocation certificate is stored for this key.'); await unlock(fingerprint, passphrase); return entry.revocationCertificate; }, async changePassphrase({ fingerprint, currentPassphrase, newPassphrase }) { if (String(newPassphrase || '').length < 8) throw new Error('Use a new passphrase of at least 8 characters.'); const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); const secret = await unlock(fingerprint, currentPassphrase); const protectedKey = await openpgp.encryptKey({ privateKey: secret, passphrase: newPassphrase }); entry.privateKey = protectedKey.armor(); await persist(data); clear(fingerprint); return { changed: true }; }, async remove(fingerprint, passphrase) { const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); data.keys = data.keys.filter(item => item.fingerprint !== fingerprint); await persist(data); clear(fingerprint); return { removed: true }; }, async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); }, async addContact(input = {}) { const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || ''; return addContact({ ...input, armoredKey }); }, async setTrust(fingerprint, trust) { if (!TRUST.includes(trust)) throw new Error('Unknown trust level.'); const data = await store(); const contact = data.contacts.find(item => item.fingerprint === fingerprint); if (!contact) throw new Error('That contact key was not found.'); if (TRUST.indexOf(trust) > TRUST.indexOf(contact.trust) && !confirm(`Mark ${contact.emails.join(', ')} as ${trust}?\n\nFingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nOnly continue if you checked this fingerprint with the owner.`)) throw new Error('Trust change cancelled.'); contact.trust = trust; await persist(data); return { ...contact }; }, async removeContact(fingerprint) { const data = await store(); if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.'); data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint); await persist(data); return { removed: true }; }, async exportContact(fingerprint) { const entry = (await store()).contacts.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That contact key was not found.'); return entry.publicKey; }, async checkSend({ to, cc, sign = false }) { const addresses = [...parseAddresses(to || ''), ...parseAddresses(cc || '')].map(item => item.address); const { keys, missing } = await resolveRecipients(addresses); const account = await getAccount(); const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null; return { recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })), missing, signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null }; }, decryptMessage, verifyMessage, async getSettings() { const data = await store(); return { cacheMinutes }; }, async setSettings({ cacheMinutes: value }) { const number = Number(value); if (!Number.isFinite(number) || number < 0 || number > 1440) throw new Error('Choose between 0 and 1440 minutes.'); const data = await store(); cacheMinutes = Math.round(number); data.settings = { ...(data.settings || {}), cacheMinutes }; await persist(data); if (!cacheMinutes) clear(); return { cacheMinutes }; }, async forgetPassphrases() { clear(); return { cleared: true }; }, async keyServers() { return []; }, async findKey() { throw new Error('Key-server lookup is not included in Android testing. Import a public key directly.'); }, async addKeyServer() { throw new Error('Key-server support is not included in Android testing.'); }, async removeKeyServer() { throw new Error('Key-server support is not included in Android testing.'); }, async setKeyServerEnabled() { throw new Error('Key-server support is not included in Android testing.'); }, async publishKey() { throw new Error('Key-server support is not included in Android testing.'); }, clearPassphrases: clear, buildOutgoing }; document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') clear(); }); return api; }