📧✨ Beautiful email. For everyone.
feat: add OpenPGP email encryption (#39)
Paul Koeck83673fb6ad5f
diff --git a/README.md b/README.mdindex c6424f5..baec2b9 100644--- a/README.md+++ b/README.md@@ -109,6 +109,8 @@ IMAP accounts build a local index in the background, newest Inbox mail first. UnGmail and Microsoft sign-in (OAuth) aren't supported yet.+Optional OpenPGP email encryption is available for each sending address under **Settings → Encryption**. Read the [encryption guide](docs/encryption.md) for setup, backups, protected drafts, key discovery and device transfer. Cross-platform and Thunderbird release checks remain required before publishing this feature.+## Build from sourceYou'll need Node 24 and pnpm 12.3.4.@@ -129,6 +131,8 @@ The desktop UI uses Tailwind CSS v4 through the Vite plugin, with its CSS-first```shpnpm check # formatting, types, tests and a production buildpnpm test:stalwart # real JMAP, IMAP and SMTP against a disposable Stalwart server (Podman or CONTAINER_RUNTIME=docker)+pnpm test:packaged-crypto # bundled worker encryption and locking smoke test+pnpm test:crypto-interop # independent GnuPG verification of Inlark outputnix build path:. # Nix package in ./result/bin/inlarkpnpm package:linux # AppImage, .deb and .rpm in apps/desktop/releasepnpm test:deb # Debian packaging smoke test (Podman)@@ -158,6 +162,8 @@ Normal app data lives in Electron's `userData` directory, usually `~/.config/Inl| `packages/core` | Platform-independent types, validation, search and merge logic || `packages/jmap` | The JMAP provider || `packages/imap` | The IMAP/SMTP provider |+| `packages/mime` | Shared composition and parsing of complete mail messages |+| `packages/crypto` | OpenPGP, authenticated local vault, PGP/MIME and discovery rules || `packages/ui` | Shared components and the Tailwind theme || `tests` | Domain, protocol, storage and real-server tests |diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 47e638f..837d13a 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -38,7 +38,9 @@"idb": "^8.0.0","react": "^19.0.0","react-dom": "^19.0.0",- "zod": "^4.0.0"+ "zod": "^4.0.0",+ "@inlark/mime": "workspace:*",+ "@inlark/crypto": "workspace:*"},"devDependencies": {"@tailwindcss/vite": "^4.1.0",diff --git a/apps/desktop/src/main/crypto-client.ts b/apps/desktop/src/main/crypto-client.tsnew file mode 100644index 0000000..d917b8d--- /dev/null+++ b/apps/desktop/src/main/crypto-client.ts@@ -0,0 +1,53 @@+import type { CryptoMethods } from '@inlark/crypto'+export interface CryptoPort {+ postMessage(value: unknown): void+ on(event: 'message' | 'error' | 'exit', listener: (...args: any[]) => void): unknown+ terminate(): Promise<number>+}+export class CryptoClient {+ private next = 1+ private failure?: Error+ private pending = new Map<+ number,+ { resolve: (value: any) => void; reject: (error: Error) => void }+ >()+ constructor(private port: CryptoPort) {+ port.on('message', ({ id, result, error }) => {+ const pending = this.pending.get(id)+ if (!pending) return+ this.pending.delete(id)+ if (error) pending.reject(new Error(error))+ else pending.resolve(result)+ })+ const fail = () => {+ this.failure = new Error(+ 'The encryption worker stopped. Lock and unlock the vault before trying again.',+ )+ for (const p of this.pending.values()) p.reject(this.failure)+ this.pending.clear()+ }+ port.on('error', fail)+ port.on('exit', fail)+ }+ call<K extends keyof CryptoMethods>(+ method: K,+ ...args: Parameters<CryptoMethods[K]>+ ): Promise<Awaited<ReturnType<CryptoMethods[K]>>> {+ return new Promise((resolve, reject) => {+ if (this.failure) return reject(this.failure)+ if (this.pending.size >= 100)+ return reject(new Error('Too many encryption operations. Try again shortly.'))+ const id = this.next+++ this.pending.set(id, { resolve, reject })+ try {+ this.port.postMessage({ id, method, args })+ } catch (error) {+ this.pending.delete(id)+ reject(error)+ }+ })+ }+ async close() {+ await this.port.terminate()+ }+}diff --git a/apps/desktop/src/main/crypto-open.ts b/apps/desktop/src/main/crypto-open.tsnew file mode 100644index 0000000..5bc539a--- /dev/null+++ b/apps/desktop/src/main/crypto-open.ts@@ -0,0 +1,4 @@+import { Worker } from 'node:worker_threads'+import workerPath from './crypto-worker?modulePath'+import { CryptoClient } from './crypto-client'+export const openCryptoWorker = () => new CryptoClient(new Worker(workerPath))diff --git a/apps/desktop/src/main/crypto-worker.ts b/apps/desktop/src/main/crypto-worker.tsnew file mode 100644index 0000000..0b03582--- /dev/null+++ b/apps/desktop/src/main/crypto-worker.ts@@ -0,0 +1,39 @@+import { parentPort } from 'node:worker_threads'+import { CryptoEngine, type CryptoMethods } from '@inlark/crypto'+const engine = new CryptoEngine()+let queue = Promise.resolve()+const methods: (keyof CryptoMethods)[] = [+ 'load',+ 'lock',+ 'inspect',+ 'generate',+ 'importPrivate',+ 'backup',+ 'revoke',+ 'encrypt',+ 'decrypt',+ 'sign',+ 'verify',+ 'setupExport',+ 'setupImport',+ 'verifyInline',+ 'mergePublic',+ 'autocryptKey',+]+parentPort!.on('message', ({ id, method, args }) => {+ queue = queue.then(async () => {+ try {+ if (!methods.includes(method)) throw new Error('Unsupported cryptographic operation.')+ const result = await (+ engine[method as keyof CryptoMethods] as (...args: any[]) => unknown+ ).apply(engine, args)+ parentPort!.postMessage({ id, result })+ } catch (error) {+ // Never serialize stacks or payloads containing key/message material.+ parentPort!.postMessage({+ id,+ error: error instanceof Error ? error.message : 'Cryptographic operation failed.',+ })+ }+ })+})diff --git a/apps/desktop/src/main/encryption.ts b/apps/desktop/src/main/encryption.tsnew file mode 100644index 0000000..4a97424--- /dev/null+++ b/apps/desktop/src/main/encryption.ts@@ -0,0 +1,933 @@+import { createHash, randomUUID } from 'node:crypto'+import { readFile, writeFile, stat } from 'node:fs/promises'+import { join } from 'node:path'+import { lookup } from 'node:dns/promises'+import { dialog } from 'electron'+import { z } from 'zod'+import { composeMime, parseMime } from '@inlark/mime'+import {+ identityKey,+ type Draft,+ type Identity,+ type Message,+ type EncryptionStatus,+ type EncryptionIdentity,+ type EncryptionKeySummary,+ type EncryptionReadiness,+ type RecipientReadiness,+} from '@inlark/core'+import {+ Vault,+ canonicalEmail,+ wkdUrls,+ parseAutocrypt,+ autocryptHeader,+ peerUpdate,+ peerPrefersEncryption,+ setupCode,+ splitEntity,+ header,+ securityKind,+ armoredPayload,+ mimeContent,+ replaceContent,+ encryptedMime,+ signedMime,+ multipart,+ decodedBody,+ type PrivateRecord,+ type CryptoMethods,+ type PeerState,+} from '@inlark/crypto'+import { JsonStore, encryptSecret, decryptSecret, secureStorageAvailable } from './storage'+import { publicFetch } from './public-fetch'++export interface CryptoTransport {+ call<K extends keyof CryptoMethods>(+ method: K,+ ...args: Parameters<CryptoMethods[K]>+ ): Promise<Awaited<ReturnType<CryptoMethods[K]>>>+ close(): Promise<void>+}+const candidateSchema = z.object({+ fingerprint: z.string().regex(/^[a-f0-9]{40,64}$/),+ email: z.string(),+ publicKey: z.string().max(1024 * 1024),+ binary: z.string().max(2 * 1024 * 1024),+ sources: z.array(z.enum(['own', 'import', 'wkd', 'autocrypt', 'gossip'])),+ confirmed: z.boolean(),+ accepted: z.boolean(),+ usable: z.boolean(),+ problem: z.string().optional(),+ retired: z.boolean().optional(),+ backup: z.enum(['needed', 'postponed', 'done']).optional(),+})+type Candidate = z.infer<typeof candidateSchema>+const stateSchema = z.object({+ identities: z.record(+ z.string(),+ z.object({+ accountId: z.string(),+ identityId: z.string(),+ email: z.string(),+ fingerprint: z.string(),+ enabled: z.boolean(),+ prefer: z.boolean(),+ }),+ ),+ keys: z.array(candidateSchema),+ accepted: z.record(z.string(), z.string()),+ peers: z.record(+ z.string(),+ z.object({+ lastSeen: z.string().optional(),+ autocryptAt: z.string().optional(),+ gossipAt: z.string().optional(),+ fingerprint: z.string().optional(),+ gossipFingerprint: z.string().optional(),+ mutual: z.boolean().optional(),+ }),+ ),+ refreshed: z.record(z.string(), z.number()),+})+type State = z.infer<typeof stateSchema>+const empty = (): State => ({ identities: {}, keys: [], accepted: {}, peers: {}, refreshed: {} })+export class EncryptionService {+ readonly vault: Vault+ private state = empty()+ private transport?: CryptoTransport+ private queue = Promise.resolve()+ private epoch = 0+ private locking = false+ private hintsAt = new Map<string, number>()+ readonly attachments = new Map<string, { accountId: string; content: Uint8Array }>()+ constructor(+ private store: JsonStore,+ private factory?: () => CryptoTransport,+ private hints?: (+ accountId: string,+ email: string,+ ) => Promise<{ message: Message; headers: Uint8Array }[]>,+ ) {+ this.vault = new Vault(join(store.directory, 'encryption-vault.json'), {+ available: secureStorageAvailable,+ wrap: encryptSecret,+ unwrap: decryptSecret,+ })+ }+ async init() {+ await this.vault.init()+ this.state = stateSchema.parse(await this.store.read('encryption-state', empty()))+ }+ private get worker() {+ if (this.locking) throw new Error('The encryption vault is locking. Try again after unlocking.')+ if (!this.transport) {+ if (!this.factory) throw new Error('The encryption worker is unavailable.')+ this.transport = this.factory()+ }+ return this.transport+ }+ private save() {+ return this.store.write('encryption-state', this.state)+ }+ serial<T>(task: () => Promise<T>): Promise<T> {+ const operation = this.queue.then(task)+ this.queue = operation.then(+ () => {},+ () => {},+ )+ return operation+ }+ status = async (): Promise<EncryptionStatus> => ({+ vault: this.vault.exists ? (this.vault.unlocked ? 'unlocked' : 'locked') : 'absent',+ protection: this.vault.mode,+ identities: Object.values(this.state.identities),+ keys: this.state.keys.map(({ binary: _, ...key }) => key),+ })+ identity(accountId: string, identityId: string) {+ return this.state.identities[identityKey(accountId, identityId)]+ }+ private async load() {+ await this.worker.call(+ 'load',+ this.vault.ids('private:').map((id) => this.vault.json<PrivateRecord>(id)!),+ )+ }+ unlock = (password?: string) =>+ this.serial(async () => {+ await this.vault.unlock(password)+ try {+ await this.load()+ } catch (error) {+ await this.vault.lock()+ throw error+ }+ return this.status()+ })+ async lock() {+ await this.queue+ this.locking = true+ this.epoch+++ try {+ await this.transport?.close()+ this.transport = undefined+ await this.vault.lock()+ for (const a of this.attachments.values()) a.content.fill(0)+ this.attachments.clear()+ } finally {+ this.locking = false+ }+ }+ private async ensureVault(password?: string) {+ if (!this.vault.exists) await this.vault.create(password)+ else if (!this.vault.unlocked) await this.vault.unlock(password)+ }+ setup(+ identity: Identity,+ action: 'create' | 'import' | 'replace' | 'historical',+ password?: string,+ keyPassword?: string,+ importReplacement = false,+ ) {+ return this.serial(async () => {+ const email = canonicalEmail(identity.email),+ current = this.identity(identity.accountId, identity.id)+ if (action === 'create' && (current || this.state.keys.some((k) => k.email === email)))+ throw new Error(+ 'A key already exists for this address. Import the existing private key instead of creating a replacement.',+ )+ if (action === 'create') {+ const discovered = await this.discover(email, true)+ if (discovered.length)+ throw new Error(+ 'An existing key was discovered for this address. Import its private key instead of generating a replacement.',+ )+ }+ if (current && action === 'import')+ throw new Error('This identity already has a key. Use explicit replacement to change it.')+ let record: PrivateRecord+ if (+ action === 'import' ||+ action === 'historical' ||+ (action === 'replace' && importReplacement)+ ) {+ const file = await this.readKeyFile('Import an existing private key')+ if (!file) return this.status()+ record = await this.worker.call(+ 'importPrivate',+ file,+ email,+ keyPassword,+ action === 'historical',+ )+ } else record = await this.worker.call('generate', identity.name, email)+ await this.ensureVault(password)+ if (action === 'historical') {+ await this.vault.putJSON('private:' + record.fingerprint, record)+ const [info] = await this.worker.call('inspect', record.publicKey, email)+ const candidate = await this.candidate(info, email, 'import')+ candidate.backup = candidate.backup || 'needed'+ if (candidate.fingerprint !== current?.fingerprint) candidate.retired = true+ await this.save()+ await this.load()+ } else await this.install(identity, record, current)+ return this.status()+ })+ }+ private async install(identity: Identity, record: PrivateRecord, current?: EncryptionIdentity) {+ const email = canonicalEmail(identity.email),+ [info] = await this.worker.call('inspect', record.publicKey, email)+ if (!info.usable) throw new Error('This private key is expired, revoked, or unusable.')+ await this.vault.putJSON('private:' + record.fingerprint, record)+ if (current && current.fingerprint !== record.fingerprint) {+ const old = this.state.keys.find(+ (k) => k.email === email && k.fingerprint === current.fingerprint,+ )+ if (old) old.retired = true+ }+ await this.candidate(info, email, 'own')+ const key = this.state.keys.find(+ (k) => k.email === email && k.fingerprint === info.fingerprint,+ )!+ key.backup = key.backup || 'needed'+ for (const candidate of this.state.keys.filter((candidate) => candidate.email === email))+ candidate.accepted = candidate === key+ key.retired = false+ key.confirmed = true+ this.state.accepted[email] = info.fingerprint+ this.state.identities[identityKey(identity.accountId, identity.id)] = {+ accountId: identity.accountId,+ identityId: identity.id,+ email,+ fingerprint: info.fingerprint,+ enabled: current?.enabled ?? true,+ prefer: record.transferPreference ?? current?.prefer ?? false,+ }+ await this.save()+ await this.load()+ }+ preference(accountId: string, identityId: string, enabled: boolean, prefer: boolean) {+ return this.serial(async () => {+ const identity = this.identity(accountId, identityId)+ if (!identity) throw new Error('Create or import a key for this identity first.')+ identity.enabled = enabled+ identity.prefer = enabled && prefer+ await this.save()+ return this.status()+ })+ }+ private async readKeyFile(title: string) {+ const result = await dialog.showOpenDialog({ title, properties: ['openFile'] })+ if (result.canceled || !result.filePaths[0]) return+ if ((await stat(result.filePaths[0])).size > 1024 * 1024)+ throw new Error('Key file is too large.')+ return readFile(result.filePaths[0], 'utf8')+ }+ exportKey(fingerprint: string, kind: 'public' | 'backup', password?: string) {+ return this.serial(async () => {+ const key = this.state.keys.find((k) => k.fingerprint === fingerprint)+ if (!key) throw new Error('Key not found.')+ if (kind === 'backup' && !this.vault.unlocked)+ throw new Error('Unlock the encryption vault first.')+ const result = await dialog.showSaveDialog({+ title: kind === 'backup' ? 'Save password-protected key backup' : 'Export public key',+ defaultPath: `${key.email}-${fingerprint.slice(-8)}-${kind}.asc`,+ })+ if (result.canceled || !result.filePath) return+ const data =+ kind === 'public'+ ? key.publicKey+ : await this.worker.call('backup', fingerprint, password || '')+ await writeFile(result.filePath, data, { mode: 0o600 })+ if (kind === 'backup') {+ for (const k of this.state.keys) if (k.fingerprint === fingerprint) k.backup = 'done'+ await this.save()+ }+ })+ }+ postpone(fingerprint: string) {+ return this.serial(async () => {+ const key = this.state.keys.find(+ (k) =>+ k.fingerprint === fingerprint &&+ this.vault.ids('private:').includes('private:' + fingerprint),+ )+ if (!key) throw new Error('Key not found.')+ key.backup = 'postponed'+ await this.save()+ return this.status()+ })+ }+ revoke(fingerprint: string) {+ return this.serial(async () => {+ if (!this.vault.unlocked) throw new Error('Unlock the encryption vault first.')+ const revoked = await this.worker.call('revoke', fingerprint)+ for (const key of this.state.keys.filter((k) => k.fingerprint === fingerprint)) {+ key.publicKey = revoked+ key.usable = false+ key.problem = 'revoked'+ key.retired = true+ }+ for (const identity of Object.values(this.state.identities))+ if (identity.fingerprint === fingerprint) {+ identity.enabled = false+ identity.prefer = false+ }+ // Keep the original private key so historical ciphertext remains decryptable.+ await this.save()+ return this.status()+ })+ }+ private async candidate(+ info: Awaited<ReturnType<CryptoMethods['inspect']>>[number],+ email: string,+ source: Candidate['sources'][number],+ ) {+ let key = this.state.keys.find((k) => k.email === email && k.fingerprint === info.fingerprint)+ if (key) {+ const merged = await this.worker.call('mergePublic', key.publicKey, info.publicKey)+ ;[info] = await this.worker.call('inspect', merged, email)+ key.publicKey = info.publicKey+ key.binary = Buffer.from(info.binary).toString('base64')+ key.usable = info.usable+ key.problem = info.problem+ if (!key.sources.includes(source)) key.sources.push(source)+ } else {+ key = {+ email,+ fingerprint: info.fingerprint,+ publicKey: info.publicKey,+ binary: Buffer.from(info.binary).toString('base64'),+ sources: [source],+ confirmed: false,+ accepted: false,+ usable: info.usable,+ problem: info.problem,+ }+ this.state.keys.push(key)+ }+ return key+ }+ async discover(address: string, refresh = false): Promise<EncryptionKeySummary[]> {+ const email = canonicalEmail(address),+ accepted = this.state.accepted[email]+ if (refresh)+ for (const key of this.hintsAt.keys())+ if (key.endsWith('\n' + email)) this.hintsAt.delete(key)+ if (+ (!accepted || refresh) &&+ (refresh ||+ !this.state.refreshed[email] ||+ Date.now() - this.state.refreshed[email] > 86400_000)+ ) {+ const urls = wkdUrls(address)+ let url = urls.advanced+ try {+ await lookup(urls.host, { all: true })+ } catch (error) {+ if (['ENOTFOUND', 'ENODATA'].includes((error as NodeJS.ErrnoException).code || ''))+ url = urls.direct+ else throw new Error('Key discovery DNS lookup failed. Refresh to try again.')+ }+ try {+ const response = await publicFetch(url, { maxBytes: 1024 * 1024, timeoutMs: 10000 })+ if (response.status === 200)+ for (const info of await this.worker.call(+ 'inspect',+ new Uint8Array(response.bytes),+ email,+ ))+ await this.candidate(info, email, 'wkd')+ else if (![404, 410].includes(response.status))+ throw new Error('The key directory could not be reached.')+ this.state.refreshed[email] = Date.now()+ await this.save()+ } catch (error) {+ // Never switch to direct after a connection/TLS/HTTP error at an existing advanced host.+ if (!this.state.keys.some((k) => k.email === email)) throw error+ }+ }+ return this.state.keys.filter((k) => k.email === email).map(({ binary: _, ...key }) => key)+ }+ accept(email: string, fingerprint: string, confirmed: boolean) {+ return this.serial(async () => {+ email = canonicalEmail(email)+ const selected = this.state.keys.find(+ (k) => k.email === email && k.fingerprint === fingerprint,+ )+ if (!selected) throw new Error('Choose a discovered key for this address.')+ const [info] = await this.worker.call('inspect', selected.publicKey, email)+ if (!info.usable) throw new Error('This key cannot be used for encryption.')+ for (const key of this.state.keys.filter((k) => k.email === email)) {+ key.accepted = key === selected+ if (key !== selected) key.retired = true+ }+ selected.confirmed = confirmed+ selected.retired = false+ this.state.accepted[email] = fingerprint+ await this.save()+ return this.status()+ })+ }+ async readiness(+ accountId: string,+ identityId: string,+ addresses: string[],+ ): Promise<EncryptionReadiness> {+ const identity = this.identity(accountId, identityId)+ if (!identity?.enabled)+ return {+ senderReady: false,+ recommend: false,+ recipients: [...new Set(addresses.map(canonicalEmail))].map((email) => ({+ email,+ status: 'missing',+ confirmed: false,+ prefers: false,+ })),+ }+ const own =+ identity &&+ this.state.keys.find(+ (k) => k.email === identity.email && k.fingerprint === identity.fingerprint,+ )+ if (own) {+ try {+ const [info] = await this.worker.call('inspect', own.publicKey, own.email)+ own.usable = info.usable+ own.problem = info.problem+ } catch {+ own.usable = false+ }+ }+ const senderReady = !!(identity?.enabled && own?.usable && this.vault.unlocked)+ const recipients: RecipientReadiness[] = []+ for (const email of [...new Set(addresses.map(canonicalEmail))]) {+ let discoveryFailed = false+ try {+ await this.discover(email)+ } catch {+ discoveryFailed = true+ }+ const hintKey = accountId + '\n' + email+ if (this.hints && Date.now() - (this.hintsAt.get(hintKey) || 0) > 120_000) {+ try {+ const hints = await this.hints(accountId, email)+ for (const hint of hints+ .slice(0, 40)+ .sort((a, b) => a.message.receivedAt.localeCompare(b.message.receivedAt)))+ if (hint.headers.byteLength <= 20 * 1024)+ await this.observe(hint.message, hint.headers).catch(() => {})+ this.hintsAt.set(hintKey, Date.now())+ } catch {+ /* Discovery failure cannot trigger a downgrade. */+ }+ }+ const keys = this.state.keys.filter((k) => k.email === email && !k.retired)+ for (const key of keys) {+ try {+ const [info] = await this.worker.call('inspect', key.publicKey, email)+ key.usable = info.usable+ key.problem = info.problem+ } catch {+ key.usable = false+ key.problem = 'unusable'+ }+ }+ const accepted = this.state.accepted[email],+ usable = keys.filter((k) => k.usable)+ let key = keys.find((k) => k.fingerprint === accepted),+ status: RecipientReadiness['status'] = 'missing'+ if (key)+ status = usable.some((k) => k.fingerprint !== accepted)+ ? 'changed'+ : key.usable+ ? 'ready'+ : ['expired', 'revoked'].includes(key.problem || '')+ ? (key.problem as 'expired' | 'revoked')+ : 'unusable'+ else if (usable.length > 1) status = 'conflict'+ else if (usable.length === 1) {+ // A sole first-discovered key is accepted for use, but stays visibly unconfirmed.+ key = usable[0]+ status = 'ready'+ key.accepted = true+ this.state.accepted[email] = key.fingerprint+ await this.save()+ } else if (keys.length)+ status = (keys[0].problem as RecipientReadiness['status']) || 'unusable'+ if (discoveryFailed && !key) status = 'missing'+ recipients.push({+ email,+ status,+ fingerprint: key?.fingerprint,+ confirmed: key?.confirmed || false,+ prefers:+ email === identity.email+ ? identity.prefer+ : peerPrefersEncryption(this.state.peers[email]),+ })+ }+ return {+ senderReady,+ recipients,+ recommend:+ senderReady &&+ !!identity?.prefer &&+ !!recipients.length &&+ recipients.every((r) => r.status === 'ready' && r.prefers),+ }+ }+ observe(message: Message, raw: Uint8Array, gossip = false) {+ return this.serial(() => this.observeNow(message, raw, gossip))+ }+ private async observeNow(message: Message, raw: Uint8Array, gossip = false) {+ const entity = splitEntity(raw)+ if (+ message.from.length !== 1 ||+ message.keywords.$junk ||+ message.keywords.$draft ||+ /^multipart\/report/i.test(header(entity, 'content-type'))+ )+ return+ const email = canonicalEmail(message.from[0].email),+ values = entity.headers.get(gossip ? 'autocrypt-gossip' : 'autocrypt') || [],+ parsed = values+ .map((v) => parseAutocrypt(v, gossip ? undefined : email))+ .filter((v) => v !== undefined)+ if (gossip) {+ const visible = new Set([...message.to, ...message.cc].map((a) => canonicalEmail(a.email)))+ for (const value of parsed)+ if (visible.has(value.email)) {+ const old = this.state.peers[value.email] || {},+ date = peerUpdate({}, message.receivedAt, message.sentAt).lastSeen!+ if (old.gossipAt && date <= old.gossipAt) continue+ const infos = await this.worker.call('inspect', value.data, value.email).catch(() => [])+ if (infos.length === 1) {+ await this.candidate(infos[0], value.email, 'gossip')+ this.state.peers[value.email] = {+ ...old,+ gossipAt: date,+ gossipFingerprint: infos[0].fingerprint,+ }+ }+ }+ } else {+ const old: PeerState = this.state.peers[email] || {},+ date = peerUpdate({}, message.receivedAt, message.sentAt).lastSeen!+ let valid: { fingerprint: string; mutual: boolean } | undefined+ if (+ values.length === 1 &&+ parsed.length === 1 &&+ (!old.autocryptAt || date > old.autocryptAt)+ ) {+ const infos = await this.worker.call('inspect', parsed[0].data, email).catch(() => [])+ if (infos.length === 1) {+ await this.candidate(infos[0], email, 'autocrypt')+ valid = { fingerprint: infos[0].fingerprint, mutual: parsed[0].mutual }+ }+ }+ this.state.peers[email] = peerUpdate(old, message.receivedAt, message.sentAt, valid)+ }+ await this.save()+ }+ async compose(+ draft: Draft,+ identity: Identity,+ messageId: string,+ attachments: { name: string; type: string; cid?: string; content: Uint8Array }[],+ serverDraft = false,+ ) {+ const own = this.identity(draft.accountId, draft.identityId)+ if (!own?.enabled) throw new Error('Enable encryption for this sending identity first.')+ if (draft.encryption && draft.encryption !== 'none' && !this.vault.unlocked)+ throw new Error('Unlock the encryption vault.')+ const key = this.state.keys.find(+ (k) => k.fingerprint === own.fingerprint && k.email === own.email,+ )+ const [info] = await this.worker.call('inspect', key!.publicKey, identity.email)+ if (!info.usable && draft.encryption && draft.encryption !== 'none')+ throw new Error('The sender’s key is expired, revoked, or unusable.')+ const encrypted = draft.encryption === 'encrypt',+ extra: string[] = []+ if (!serverDraft && info.usable)+ extra.push(+ autocryptHeader(+ identity.email,+ await this.worker.call('autocryptKey', key!.publicKey, identity.email),+ own.prefer,+ ),+ )+ if (serverDraft)+ extra.push(+ 'Autocrypt-Draft-State: encrypt=yes; _by-choice=yes; _is-reply-to-encrypted=' ++ (draft.encryptionRequired ? 'yes' : 'no'),+ )+ const mime = await composeMime({+ from: identity,+ to: draft.to,+ cc: draft.cc,+ bcc: [],+ subject: draft.subject,+ html: draft.html,+ text: draft.text,+ messageId,+ inReplyTo: draft.inReplyTo,+ references: draft.references,+ attachments,+ })+ if (!draft.encryption || draft.encryption === 'none') {+ const entity = splitEntity(mime)+ return Buffer.concat([+ Buffer.from(extra.length ? extra.join('\r\n') + '\r\n' : ''),+ entity.headerBytes,+ Buffer.from('\r\n\r\n'),+ entity.body,+ ])+ }+ let content = mimeContent(mime)+ const encryptionKeys = [key!.publicKey]+ const gossip: string[] = []+ if (encrypted && !serverDraft) {+ const ready = await this.readiness(+ draft.accountId,+ draft.identityId,+ [...draft.to, ...draft.cc, ...draft.bcc].map((a) => a.email),+ )+ const blocked = ready.recipients.filter((r) => r.status !== 'ready')+ if (!ready.senderReady || blocked.length)+ throw new Error(+ 'Encrypted send blocked: ' ++ blocked.map((r) => r.email + ' (' + r.status + ')').join(', '),+ )+ for (const recipient of ready.recipients) {+ const key = this.state.keys.find(+ (k) => k.email === recipient.email && k.fingerprint === recipient.fingerprint,+ )!+ encryptionKeys.push(key.publicKey)+ }+ }+ if (encrypted) {+ // Gossip contains visible recipients only, even when hidden recipient packets are used.+ for (const address of [...draft.to, ...draft.cc]) {+ const email = canonicalEmail(address.email),+ fingerprint = this.state.accepted[email],+ key = this.state.keys.find((k) => k.email === email && k.fingerprint === fingerprint)+ if (key?.usable) {+ try {+ gossip.push(+ autocryptHeader(+ email,+ await this.worker.call('autocryptKey', key.publicKey, email),+ false,+ true,+ ),+ )+ } catch (error) {+ if (!serverDraft) throw error+ }+ }+ }+ if (gossip.length)+ content = Buffer.concat([Buffer.from(gossip.join('\r\n') + '\r\n'), content])+ if (serverDraft && draft.bcc.length)+ content = Buffer.concat([+ Buffer.from(+ 'X-Inlark-Draft-Bcc: ' ++ Buffer.from(JSON.stringify(draft.bcc)).toString('base64') ++ '\r\n',+ ),+ content,+ ])+ const armor = await this.worker.call(+ 'encrypt',+ content,+ [...new Set(encryptionKeys)],+ serverDraft ? undefined : own.fingerprint,+ !!draft.bcc.length,+ )+ return replaceContent(mime, encryptedMime(armor), extra)+ }+ return replaceContent(+ mime,+ signedMime(content, await this.worker.call('sign', content, own.fingerprint)),+ extra,+ )+ }+ async read(message: Message, raw: Uint8Array): Promise<Message> {+ const epoch = this.epoch,+ kind = securityKind(raw),+ entity = splitEntity(raw)+ await this.observe(message, raw).catch(() => {})+ if (!kind) return message+ const safe = {+ ...message,+ html: '',+ text: '',+ preview: '',+ attachments: [],+ protectedRevision: createHash('sha256').update(raw).digest('hex'),+ encryptionIntent:+ /\bencrypt=yes\b/i.test(header(entity, 'autocrypt-draft-state')) || kind === 'encrypted',+ }+ const failure = (+ state: 'locked' | 'missingKey' | 'integrityFailure',+ detail: string,+ ): Message => ({+ ...safe,+ security: {+ encrypted: kind === 'encrypted',+ state,+ signature: 'unknown',+ confirmed: false,+ detail,+ },+ })+ if (kind === 'encrypted' && !this.vault.unlocked)+ return failure(+ 'locked',+ 'Unlock the vault to read this message. If this device has no key, import the original private key.',+ )+ let content: Uint8Array,+ signatures: { valid: boolean; fingerprint?: string; keyId: string }[] = []+ const publicKeys = this.state.keys.map((k) => k.publicKey)+ try {+ if (kind === 'encrypted') {+ const result = await this.worker.call('decrypt', armoredPayload(raw), publicKeys)+ content = result.data+ signatures = result.signatures+ } else content = raw+ if (+ !/^Content-[A-Za-z-]+:|^Autocrypt-Gossip:|^X-Inlark-Draft-Bcc:/im.test(+ Buffer.from(content).toString('utf8').slice(0, 4096),+ )+ )+ content = Buffer.concat([+ Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'),+ Buffer.from(content),+ ])+ if (kind === 'signed' && !/^multipart\/signed/i.test(header(entity, 'content-type'))) {+ const text = decodedBody(raw).toString('utf8'),+ armor = text.match(+ /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]*?-----END PGP SIGNATURE-----/,+ )?.[0]+ if (!armor) throw new Error('Invalid inline signature.')+ const result = await this.worker.call('verifyInline', armor, publicKeys)+ signatures = result.signatures+ content = Buffer.concat([+ Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'),+ Buffer.from(result.text),+ ])+ }+ const part = splitEntity(content)+ if (/^multipart\/signed\b/i.test(header(part, 'content-type'))) {+ if (!/\bprotocol\s*=\s*"?application\/pgp-signature/i.test(header(part, 'content-type')))+ throw new Error('Invalid signature envelope.')+ const parts = multipart(content)+ if (parts.length !== 2) throw new Error('Invalid signed message.')+ signatures = await this.worker.call(+ 'verify',+ parts[0],+ decodedBody(parts[1]).toString('utf8'),+ publicKeys,+ )+ content = parts[0]+ }+ const parsed = await parseMime(content)+ if (epoch !== this.epoch || this.locking)+ return failure('locked', 'The vault was locked while opening this message.')+ if (kind === 'encrypted') await this.observe(message, content, true).catch(() => {})+ if (epoch !== this.epoch || this.locking || (kind === 'encrypted' && !this.vault.unlocked))+ return failure('locked', 'The vault was locked while opening this message.')+ const signature = signatures.length+ ? signatures.some((s) => !s.valid && s.fingerprint)+ ? 'invalid'+ : signatures.every((s) => s.valid)+ ? 'valid'+ : 'unknown'+ : 'unsigned',+ fingerprint = signatures.find((s) => s.valid)?.fingerprint+ const sender = message.from.length === 1 ? canonicalEmail(message.from[0].email) : '',+ trusted = this.state.keys.find((k) => k.email === sender && k.fingerprint === fingerprint)+ const attachments = parsed.attachments.map((a) => {+ const blobId = 'decrypted:' + randomUUID()+ this.attachments.set(blobId, { accountId: message.accountId, content: a.content })+ const { content: _, ...rest } = a+ return { ...rest, blobId }+ })+ const inner = splitEntity(content),+ bcc = header(inner, 'x-inlark-draft-bcc')+ return {+ ...safe,+ html: parsed.html,+ text: parsed.text,+ attachments,+ ...(message.keywords.$draft && bcc+ ? { bcc: JSON.parse(Buffer.from(bcc, 'base64').toString()) }+ : {}),+ security: {+ encrypted: kind === 'encrypted',+ state: kind === 'encrypted' ? 'decrypted' : 'signed',+ signature,+ fingerprint,+ confirmed: signature === 'valid' && !!trusted?.confirmed,+ detail:+ signature === 'invalid'+ ? 'The signature could not be verified. Treat the sender and content with caution.'+ : signature === 'unknown'+ ? 'The sender’s signing key is unavailable. Signature validity could not be checked.'+ : undefined,+ },+ }+ } catch (error) {+ const text = error instanceof Error ? error.message : ''+ if (/no private key|session key decryption failed|no decryption key/i.test(text))+ return failure(+ 'missingKey',+ 'The original private key is needed to decrypt this message. Import it, including retired keys.',+ )+ return failure(+ 'integrityFailure',+ 'Message integrity could not be verified. Content and attachments are blocked.',+ )+ }+ }+ async transfer(+ identity: Identity,+ action: 'export' | 'import',+ code?: string,+ password?: string,+ ) {+ return this.serial(async () => {+ if (action === 'export') {+ const own = this.identity(identity.accountId, identity.id)+ if (!own || !this.vault.unlocked)+ throw new Error('Unlock this identity’s key before transferring it.')+ const generated = setupCode(),+ armor = await this.worker.call('setupExport', own.fingerprint, generated, own.prefer)+ const payload = armor.replace(+ '-----BEGIN PGP MESSAGE-----\n',+ '-----BEGIN PGP MESSAGE-----\nPassphrase-Format: numeric9x4\nPassphrase-Begin: ' ++ generated.slice(0, 2) ++ '\n',+ )+ const mime = await composeMime({+ from: identity,+ to: [identity],+ cc: [],+ bcc: [],+ subject: 'Autocrypt Setup Message',+ html: '',+ text: 'Import this Setup Message on your other device using the Setup Code shown by Inlark. Keep that code separately and securely.',+ messageId: randomUUID() + '@' + identity.email.split('@')[1],+ attachments: [+ {+ name: 'autocrypt-setup-message.html',+ type: 'application/autocrypt-setup',+ content: Buffer.from('<html><body><pre>' + payload + '</pre></body></html>'),+ },+ ],+ })+ const result = await dialog.showSaveDialog({+ title: 'Export Autocrypt Setup Message',+ defaultPath: 'autocrypt-setup.eml',+ })+ if (result.canceled || !result.filePath) return {}+ const entity = splitEntity(mime)+ await writeFile(+ result.filePath,+ Buffer.concat([+ Buffer.from('Autocrypt-Setup-Message: v1\r\n'),+ entity.headerBytes,+ Buffer.from('\r\n\r\n'),+ entity.body,+ ]),+ { mode: 0o600 },+ )+ return { code: generated }+ }+ const file = await this.readKeyFile('Import Autocrypt Setup Message')+ if (!file) return {}+ let payload = file+ if (/Autocrypt-Setup-Message:\s*v1/i.test(file)) {+ const parsed = await parseMime(Buffer.from(file))+ const attachment = parsed.attachments.find((a) => a.type === 'application/autocrypt-setup')+ if (!attachment) throw new Error('The Setup Message has no transfer attachment.')+ payload = Buffer.from(attachment.content).toString('utf8')+ }+ const armor = payload.match(+ /-----BEGIN PGP MESSAGE-----[\s\S]*?-----END PGP MESSAGE-----/,+ )?.[0]+ if (!armor || !code) throw new Error('Choose a Setup Message and enter its Setup Code.')+ const record = await this.worker.call('setupImport', armor, code, identity.email)+ const current = this.identity(identity.accountId, identity.id)+ if (current && current.fingerprint !== record.fingerprint)+ throw new Error(+ 'This transfer contains a different key. Review the existing identity before replacing it.',+ )+ await this.ensureVault(password)+ await this.install(identity, record, current)+ return {}+ })+ }+}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 6279488..ca19881 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -1,3 +1,4 @@+import { openCryptoWorker } from './crypto-open'import {app,BrowserWindow,@@ -236,6 +237,7 @@ else {})service = new MailService(new JsonStore(join(app.getPath('userData'), 'mail')), send, {providers: imapProviders,+ crypto: openCryptoWorker,discover,})await service.init()@@ -247,6 +249,18 @@ else {rendererReady = truefor (const event of pendingEvents.splice(0)) window?.webContents.send('mail:event', event)},+ encryptionStatus: service.encryptionStatus,+ setupEncryption: service.setupEncryption,+ setEncryptionPreference: service.setEncryptionPreference,+ exportEncryptionKey: service.exportEncryptionKey,+ revokeEncryptionKey: service.revokeEncryptionKey,+ postponeEncryptionBackup: service.postponeEncryptionBackup,+ discoverEncryptionKeys: service.discoverEncryptionKeys,+ acceptEncryptionKey: service.acceptEncryptionKey,+ encryptionReadiness: service.encryptionReadiness,+ unlockEncryption: service.unlockEncryption,+ lockEncryption: service.lockEncryption,+ transferEncryption: service.transferEncryption,bootstrap: service.bootstrap,updateStatus: updates.getStatus,discover: service.discover,diff --git a/apps/desktop/src/main/service.ts b/apps/desktop/src/main/service.tsindex dcc142e..ebe4a01 100644--- a/apps/desktop/src/main/service.ts+++ b/apps/desktop/src/main/service.ts@@ -1,4 +1,6 @@-import { randomUUID, X509Certificate } from 'node:crypto'+import { EncryptionService, type CryptoTransport } from './encryption'+import { securityKind, maxMessageBytes } from '@inlark/crypto'+import { randomUUID, X509Certificate, createHash } from 'node:crypto'import { mkdir, readFile, writeFile, copyFile, rm, stat, chmod, open } from 'node:fs/promises'import { join, basename, extname } from 'node:path'import { app, dialog, shell, Notification } from 'electron'@@ -147,6 +149,7 @@ export type ProviderFactory = (input: {export interface ServiceOptions {providers?: ProviderFactorydiscover?: (email: string) => Promise<DiscoveryResult>+ crypto?: () => CryptoTransport}/** Fingerprints shown to the user are computed here from the certificate itself, never taken on trust. */function verifiedCertificates(config: ConnectionConfig): ConnectionConfig {@@ -201,17 +204,29 @@ export class MailService {private timer?: ReturnType<typeof setInterval>private logs: { at: string; event: string; state?: string }[] = []private senderAvatars = new SenderAvatarResolver()+ readonly encryption: EncryptionService+ private protectedLoaded = new Set<string>()+ private protectionTransition = false+ private draftWrites: Promise<unknown> = Promise.resolve()constructor(private store: JsonStore,private emit: (event: AppEvent) => void,private options: ServiceOptions = {},- ) {}+ ) {+ this.encryption = new EncryptionService(store, options.crypto, (accountId, email) =>+ this.guard(+ accountId,+ (provider, account) => provider.encryptionHints?.(account, email) || Promise.resolve([]),+ ),+ )+ }private log(event: string, state?: string) {this.logs.push({ at: new Date().toISOString(), event, state })this.logs = this.logs.slice(-200)}async init() {await this.store.init()+ await this.encryption.init()this.settings = await this.store.read('settings', defaultSettings)this.connections = await this.store.read<Connection[]>('connections', [], {version: CONNECTIONS_VERSION,@@ -263,6 +278,118 @@ export class MailService {void Promise.allSettled(this.connections.map((c) => this.reconnect(c.id)))this.timer = setInterval(() => void this.refresh(), 60_000)}+ encryptionStatus = () => this.encryption.status()+ private async sendingIdentity(accountId: string, identityId: string) {+ const identity = (await this.identities(accountId)).find((i) => i.id === identityId)+ if (!identity) throw new Error('Choose a valid sending identity.')+ return identity+ }+ setupEncryption = async (input: {+ accountId: string+ identityId: string+ action: 'create' | 'import' | 'replace' | 'historical'+ importReplacement?: boolean+ password?: string+ keyPassword?: string+ }) =>+ this.encryption.setup(+ await this.sendingIdentity(input.accountId, input.identityId),+ input.action,+ input.password,+ input.keyPassword,+ input.importReplacement,+ )+ setEncryptionPreference = (+ accountId: string,+ identityId: string,+ enabled: boolean,+ prefer: boolean,+ ) => this.encryption.preference(accountId, identityId, enabled, prefer)+ exportEncryptionKey = (fingerprint: string, kind: 'public' | 'backup', password?: string) =>+ this.encryption.exportKey(fingerprint, kind, password)+ revokeEncryptionKey = (fingerprint: string) => this.encryption.revoke(fingerprint)+ postponeEncryptionBackup = (fingerprint: string) => this.encryption.postpone(fingerprint)+ discoverEncryptionKeys = (email: string, refresh?: boolean) =>+ this.encryption.discover(email, refresh)+ acceptEncryptionKey = (email: string, fingerprint: string, confirmed: boolean) =>+ this.encryption.accept(email, fingerprint, confirmed)+ encryptionReadiness = (accountId: string, identityId: string, recipients: string[]) =>+ this.encryption.readiness(accountId, identityId, recipients)+ unlockEncryption = async (password?: string) => {+ const status = await this.encryption.unlock(password)+ for (const id of this.encryption.vault.ids('attachment-meta:')) {+ const attachment = this.encryption.vault.json<StagedAttachment>(id)!+ if (this.staging.get(attachment.id)?.blobId?.startsWith('vault:'))+ this.staging.set(attachment.id, attachment)+ }+ for (const id of this.encryption.vault.ids('draft:')) {+ const draft = this.encryption.vault.json<Draft>(id)!+ // Submission reconciliation is authoritative after a crash.+ const stub = this.localDrafts.get(draft.id)+ const journal = this.journals.get(draft.id)+ if (+ stub &&+ stub.encryption !== 'encrypt' &&+ (stub.status === 'sent' || stub.updatedAt >= draft.updatedAt)+ )+ continue+ if (+ stub?.status === 'sent' &&+ (stub.encryption !== 'encrypt' || journal?.state === 'sent' || journal?.dismissed)+ )+ continue+ this.localDrafts.set(draft.id, { ...draft, ...(stub ? { status: stub.status } : {}) })+ this.protectedLoaded.add(draft.id)+ }+ this.emit({ type: 'encryption', locked: false })+ return status+ }+ lockEncryption = async () => {+ if (this.protectionTransition) throw new Error('The vault is already locking.')+ this.protectionTransition = true+ try {+ await this.draftWrites+ if (this.busyDrafts.size)+ throw new Error('Wait for drafts and sends to finish before locking.')+ await this.persistDrafts()+ await this.encryption.lock()+ this.localDrafts = new Map(+ (await this.store.read<Draft[]>('drafts', [])).map((d) => [d.id, d]),+ )+ this.staging = new Map(+ (await this.store.read<StagedAttachment[]>('staging', [])).map((a) => [a.id, a]),+ )+ this.protectedLoaded.clear()+ this.emit({ type: 'encryption', locked: true })+ } finally {+ this.protectionTransition = false+ }+ }+ transferEncryption = async (input: {+ accountId: string+ identityId: string+ action: 'export' | 'import'+ code?: string+ password?: string+ }) =>+ this.encryption.transfer(+ await this.sendingIdentity(input.accountId, input.identityId),+ input.action,+ input.code,+ input.password,+ )+ private async protectedMime(draft: Draft, messageId: string, serverDraft = false) {+ const { provider } = this.provider(draft.accountId)+ if (!provider.rawMessage) throw new Error('This provider cannot safely support encrypted mail.')+ const identity = await this.sendingIdentity(draft.accountId, draft.identityId)+ const attachments = await Promise.all(+ draft.attachments.map(async (a) => ({+ ...a,+ content: await this.readStagedAttachment(a.id),+ })),+ )+ return this.encryption.compose(draft, identity, messageId, attachments, serverDraft)+ }bootstrap = async () => ({accounts: this.accounts,settings: this.settings,@@ -276,8 +403,23 @@ export class MailService {private saveConnections() {return this.store.write('connections', this.connections, CONNECTIONS_VERSION)}- private persistDrafts() {- return this.store.write('drafts', [...this.localDrafts.values()])+ private async persistDrafts() {+ const records: [string, Uint8Array | undefined][] = []+ const saved = [...this.localDrafts.values()].map((draft) => {+ if (draft.encryption !== 'encrypt') return draft+ if (this.encryption.vault.unlocked && this.protectedLoaded.has(draft.id))+ records.push(['draft:' + draft.id, Buffer.from(JSON.stringify(draft))])+ return {+ ...draft,+ html: '',+ text: '',+ attachments: [],+ serverFingerprint: draft.serverFingerprint?.match(/^[a-f0-9]{64}$/)?.[0],+ error: 'Unlock the encryption vault to resume this draft.',+ }+ })+ if (records.length) await this.encryption.vault.putMany(records)+ await this.store.write('drafts', saved)}private async persistJournal() {await this.store.write('submissions', [...this.journals.values()])@@ -671,8 +813,46 @@ export class MailService {}mailboxes = (id: string) => this.guard(id, (p, a) => p.mailboxes(a))identities = (id: string) => this.guard(id, (p, a) => p.identities(a))+ private async serverMessages(+ provider: MailProvider,+ account: Account,+ ids: string[],+ bodies = true,+ protectedMessage = false,+ ) {+ const messages = await provider.messages(account, ids, bodies)+ if (!provider.rawMessage) return messages+ return Promise.all(+ messages.map(async (message) => {+ if (+ !protectedMessage &&+ !message.security?.encrypted &&+ !/-----BEGIN PGP MESSAGE-----/.test(message.text || '')+ )+ return message+ const raw = await provider.rawMessage!(account, message.id, maxMessageBytes)+ if (securityKind(raw))+ return {+ ...message,+ html: '',+ text: '',+ preview: '',+ protectedRevision: createHash('sha256').update(raw).digest('hex'),+ }+ return message+ }),+ )+ }conversation = (id: string, threadId: string) =>- this.guard(id, (p, a) => p.conversation(a, threadId))+ this.guard(id, async (p, a) => {+ const messages = await p.conversation(a, threadId)+ if (!p.rawMessage) return messages+ return Promise.all(+ messages.map(async (message) =>+ this.encryption.read(message, await p.rawMessage!(a, message.id, maxMessageBytes)),+ ),+ )+ })query = async (query: MailQuery, cursor?: Record<string, number>): Promise<QueryPage> => {const accounts = this.accounts.filter((a) => (!query.accountId || query.accountId === a.id) && (!cursor || a.id in cursor),@@ -843,12 +1023,14 @@ export class MailService {stageRemoteAttachments = async (accountId: string,attachments: Attachment[],+ protectedDraft = false,): Promise<StagedAttachment[]> => {+ if (this.protectionTransition) throw new Error('The vault is locking.')const directory = join(this.store.directory, 'attachments')await mkdir(directory, { recursive: true, mode: 0o700 })const staged: StagedAttachment[] = []for (const attachment of attachments) {- const bytes = await this.guard(accountId, (p, a) => p.download(a, attachment))+ const bytes = await this.attachmentBytes(accountId, attachment)const item: StagedAttachment = {id: randomUUID(),name: attachment.name,@@ -856,17 +1038,48 @@ export class MailService {size: bytes.length,cid: attachment.cid,}- await writeFile(join(directory, item.id), bytes, { mode: 0o600 })+ if (protectedDraft) {+ await this.protectStagedAttachment(item, bytes)+ } else await writeFile(join(directory, item.id), bytes, { mode: 0o600 })this.staging.set(item.id, item)staged.push(item)- await this.store.write('staging', [...this.staging.values()])+ await this.persistStaging()}return staged}/** Reads a staged attachment. Only IDs recorded by this service resolve to files. */+ private async protectStagedAttachment(attachment: StagedAttachment, bytes: Uint8Array) {+ const protectedAttachment = { ...attachment, blobId: 'vault:' + attachment.id }+ await this.encryption.vault.putMany([+ ['attachment:' + attachment.id, bytes],+ ['attachment-meta:' + attachment.id, Buffer.from(JSON.stringify(protectedAttachment))],+ ])+ Object.assign(attachment, protectedAttachment)+ }+ private persistStaging() {+ return this.store.write(+ 'staging',+ [...this.staging.values()].map((attachment) =>+ attachment.blobId?.startsWith('vault:')+ ? {+ id: attachment.id,+ size: attachment.size,+ name: 'Protected attachment',+ type: 'application/octet-stream',+ blobId: attachment.blobId,+ }+ : attachment,+ ),+ )+ }readStagedAttachment = async (id: string): Promise<Uint8Array> => {if (!this.staging.has(id))throw new Error('An attachment is missing. Remove it and attach the file again.')+ if (this.staging.get(id)?.blobId?.startsWith('vault:')) {+ const bytes = this.encryption.vault.read('attachment:' + id)+ if (!bytes) throw new Error('The protected attachment is missing.')+ return bytes+ }return readFile(join(this.store.directory, 'attachments', id))}resumeDraft = async (accountId: string, messageId: string): Promise<Draft> => {@@ -874,15 +1087,26 @@ export class MailService {(d) => d.accountId === accountId && d.serverId === messageId,)if (existing) return existing- const [message] = await this.guard(accountId, (p, a) => p.messages(a, [messageId], true))+ const [message] = await this.guard(accountId, async (p, a) => {+ const [m] = await p.messages(a, [messageId], true)+ return m && p.rawMessage+ ? [await this.encryption.read(m, await p.rawMessage(a, messageId, maxMessageBytes))]+ : [m]+ })if (!message?.keywords.$draft) throw new Error('This message is no longer a draft.')+ if (message.security && !['decrypted', 'signed'].includes(message.security.state))+ throw new Error(message.security.detail)const identities = await this.identities(accountId)const identity =identities.find((i) =>message.from.some((f) => f.email.toLowerCase() === i.email.toLowerCase()),) || identities[0]if (!identity) throw new Error('No sending identity is available for this account.')- const attachments = await this.stageRemoteAttachments(accountId, message.attachments || [])+ const attachments = await this.stageRemoteAttachments(+ accountId,+ message.attachments || [],+ !!message.security?.encrypted,+ )const draft: Draft = {id: randomUUID(),accountId,@@ -896,6 +1120,8 @@ export class MailService {attachments,updatedAt: new Date().toISOString(),status: 'synced',+ encryption: message.security?.encrypted ? 'encrypt' : undefined,+ encryptionRequired: !!message.security?.encrypted,serverId: message.id,serverFingerprint: draftFingerprint(message),references: message.references,@@ -903,14 +1129,54 @@ export class MailService {}return this.saveDraft(draft)}- saveDraft = async (draft: Draft): Promise<Draft> => {+ saveDraft = (draft: Draft): Promise<Draft> => {+ const operation = this.draftWrites.then(() => this.saveDraftNow(draft))+ this.draftWrites = operation.catch(() => {})+ return operation+ }+ private async saveDraftNow(draft: Draft): Promise<Draft> {+ if (this.protectionTransition) throw new Error('Wait for the vault to finish locking.')this.account(draft.accountId)const old = this.localDrafts.get(draft.id)if (this.busyDrafts.has(draft.id) || old?.status === 'uncertain' || old?.status === 'sent')return old || draftif (old && old.updatedAt > draft.updatedAt) return old+ if (+ draft.encryption !== 'encrypt' &&+ (old?.encryption === 'encrypt' || draft.encryptionRequired) &&+ !draft.downgradeConfirmed+ )+ throw new Error('Confirm sending or saving this decrypted content without encryption first.')+ if (old?.encryption === 'encrypt' && draft.encryption !== 'encrypt')+ this.requireProtectedDraft(old)+ if (draft.encryption === 'encrypt') {+ if (!this.encryption.vault.unlocked)+ throw new Error('Unlock the encryption vault to save this protected draft.')+ draft = {+ ...draft,+ earlierPlaintext:+ draft.earlierPlaintext ||+ (!!old && old.encryption !== 'encrypt') ||+ (!!draft.serverId && old?.encryption !== 'encrypt'),+ }+ for (const attachment of draft.attachments) {+ const staged = this.staging.get(attachment.id)+ if (!staged) throw new Error('An attachment is missing.')+ if (!staged.blobId?.startsWith('vault:')) {+ const bytes = await this.readStagedAttachment(attachment.id)+ await this.protectStagedAttachment(staged, bytes)+ await this.persistStaging()+ await rm(join(this.store.directory, 'attachments', attachment.id), { force: true })+ }+ }+ this.protectedLoaded.add(draft.id)+ }this.localDrafts.set(draft.id, draft)await this.persistDrafts()+ if (old?.encryption === 'encrypt' && draft.encryption !== 'encrypt') {+ await this.encryption.vault.put('draft:' + draft.id, undefined)+ this.protectedLoaded.delete(draft.id)+ }return draft}/** Uploads attachments for providers that reference server blobs. Others read staged files. */@@ -924,14 +1190,16 @@ export class MailService {attachments.push({ ...staged, cid: attachment.cid ?? staged.cid })continue}- const data = await readFile(join(this.store.directory, 'attachments', attachment.id))+ const data = await this.readStagedAttachment(attachment.id)const blobId = await provider.upload(account, data, staged.type)attachments.push({ ...staged, blobId })}return { ...draft, attachments }}syncDraft = async (input: Draft): Promise<Draft> => {+ if (this.protectionTransition) throw new Error('The vault is locking.')if (this.busyDrafts.has(input.id)) return this.localDrafts.get(input.id) || input+ input = await this.saveDraft(input)this.busyDrafts.add(input.id)let committed: Draft | undefinedtry {@@ -940,7 +1208,13 @@ export class MailService {if (current && current.updatedAt > input.updatedAt) return currentif (current && ['uncertain', 'sent'].includes(current.status)) return currentif (input.serverId) {- const [remote] = await provider.messages(account, [input.serverId], true)+ const [remote] = await this.serverMessages(+ provider,+ account,+ [input.serverId],+ true,+ input.encryption === 'encrypt',+ )if (!remote || !remote.keywords.$draft)throw new ProviderError('conflict',@@ -956,9 +1230,19 @@ export class MailService {'This draft changed in another client. Your local copy is safe; save it as a new draft to keep both versions.',)}- const draft = await this.uploadDraft(input)- const serverId = await provider.createDraft(account, draft)- const [remote] = await provider.messages(account, [serverId], true)+ const protectedMime =+ input.encryption === 'encrypt'+ ? await this.protectedMime(input, randomUUID() + '@inlark.local', true)+ : undefined+ const draft = protectedMime ? input : await this.uploadDraft(input)+ const serverId = await provider.createDraft(account, draft, undefined, protectedMime)+ const [remote] = await this.serverMessages(+ provider,+ account,+ [serverId],+ true,+ input.encryption === 'encrypt',+ )const saved: Draft = {...draft,serverId,@@ -990,7 +1274,13 @@ export class MailService {}/** Removes a replaced server draft only if nobody else changed it since it was read. */private async removePreviousDraft(provider: MailProvider, account: Account, draft: Draft) {- const [remote] = await provider.messages(account, [draft.serverId!], true)+ const [remote] = await this.serverMessages(+ provider,+ account,+ [draft.serverId!],+ true,+ draft.encryption === 'encrypt',+ )const state = provider.getStateToken(account)if (!remote) returnif (@@ -1023,6 +1313,9 @@ export class MailService {status: 'sent',})await this.persistDrafts()+ if (draft.encryption === 'encrypt' && this.encryption.vault.unlocked)+ await this.encryption.vault.put('draft:' + draft.id, undefined)+ this.protectedLoaded.delete(draft.id)await this.releaseAttachments(draft)}private async releaseAttachments(draft: Draft) {@@ -1033,24 +1326,42 @@ export class MailService {)) {await rm(join(this.store.directory, 'attachments', attachment.id), { force: true })+ if (this.staging.get(attachment.id)?.blobId?.startsWith('vault:'))+ await this.encryption.vault.putMany([+ ['attachment:' + attachment.id, undefined],+ ['attachment-meta:' + attachment.id, undefined],+ ])this.staging.delete(attachment.id)}}- if (draft.attachments.length) await this.store.write('staging', [...this.staging.values()])+ if (draft.attachments.length) await this.persistStaging()}private async deleteDraftLocal(id: string) {const draft = this.localDrafts.get(id)+ if (draft?.encryption === 'encrypt') {+ if (!this.encryption.vault.unlocked)+ throw new Error('Unlock the vault before deleting this draft.')+ await this.encryption.vault.put('draft:' + id, undefined)+ this.protectedLoaded.delete(id)+ }this.localDrafts.delete(id)if (draft) await this.releaseAttachments(draft)}deleteDraft = async (id: string) => {if (this.busyDrafts.has(id)) throw new Error('Wait for this draft to finish saving.')const draft = this.localDrafts.get(id)+ if (draft?.encryption === 'encrypt') this.requireProtectedDraft(draft)if (draft?.status === 'uncertain')throw new Error('Check this message’s delivery status before deleting the draft.')if (draft?.serverId) {const result = await this.guard(draft.accountId, async (p, a) => {- const [remote] = await p.messages(a, [draft.serverId!], true)+ const [remote] = await this.serverMessages(+ p,+ a,+ [draft.serverId!],+ true,+ draft.encryption === 'encrypt',+ )const state = p.getStateToken(a)// Discarding a local copy must never remove mail already sent or changed elsewhere.if (@@ -1148,6 +1459,7 @@ export class MailService {}}send = async (input: Draft): Promise<SendResult> => {+ if (this.protectionTransition) throw new Error('The vault is locking.')const draft = sendDraftSchema.parse(input)if (!draft.to.length && !draft.cc.length && !draft.bcc.length)throw new Error('Add at least one recipient.')@@ -1177,7 +1489,13 @@ export class MailService {try {await this.persistJournal()if (draft.serverId) {- const [remote] = await provider.messages(account, [draft.serverId], true)+ const [remote] = await this.serverMessages(+ provider,+ account,+ [draft.serverId],+ true,+ draft.encryption === 'encrypt',+ )if (!remote || !remote.keywords.$draft)throw new ProviderError('conflict',@@ -1189,8 +1507,18 @@ export class MailService {'This draft changed in another client. Save a separate copy before sending.',)}- uploaded = await this.uploadDraft(draft)- const outgoing = await provider.prepareSubmission(account, uploaded, journal.messageId!)+ const protectedMime =+ (draft.encryption && draft.encryption !== 'none') ||+ this.encryption.identity(draft.accountId, draft.identityId)?.enabled+ ? await this.protectedMime(draft, journal.messageId!)+ : undefined+ uploaded = protectedMime ? draft : await this.uploadDraft(draft)+ const outgoing = await provider.prepareSubmission(+ account,+ uploaded,+ journal.messageId!,+ protectedMime,+ )journal.emailId = outgoing.emailIdjournal.envelope = outgoing.envelopeif (outgoing.mime) {@@ -1397,55 +1725,82 @@ export class MailService {...patch,}}+ private requireProtectedDraft(draft: Draft) {+ if (+ draft.encryption === 'encrypt' &&+ (this.protectionTransition ||+ !this.encryption.vault.unlocked ||+ !this.protectedLoaded.has(draft.id))+ )+ throw new Error('Unlock the vault before recovering or changing this protected draft.')+ }recoverRejected = async (id: string): Promise<Draft> => {const journal = this.journals.get(id)const draft = this.localDrafts.get(id)if (journal?.state !== 'partial' || journal.dismissed || !draft)throw new Error('There are no refused recipients to recover for this message.')- const refused = new Set(- this.rejectedAddresses(draft, journal).map((a) => a.email.toLowerCase()),- )- const only = (list: Address[]) => list.filter((a) => refused.has(a.email.toLowerCase()))- const recovery = this.copyDraft(draft, {- to: only(draft.to),- cc: only(draft.cc),- bcc: only(draft.bcc),- })- this.localDrafts.set(recovery.id, recovery)- journal.dismissed = true- await this.completeDraft(draft)- await this.persistJournal()- return recovery+ this.requireProtectedDraft(draft)+ if (this.busyDrafts.has(id)) throw new Error('Wait for this draft to finish saving.')+ this.busyDrafts.add(id)+ try {+ const refused = new Set(+ this.rejectedAddresses(draft, journal).map((a) => a.email.toLowerCase()),+ )+ const only = (list: Address[]) => list.filter((a) => refused.has(a.email.toLowerCase()))+ const recovery = this.copyDraft(draft, {+ to: only(draft.to),+ cc: only(draft.cc),+ bcc: only(draft.bcc),+ })+ this.localDrafts.set(recovery.id, recovery)+ if (recovery.encryption === 'encrypt') this.protectedLoaded.add(recovery.id)+ journal.dismissed = true+ await this.completeDraft(draft)+ await this.persistJournal()+ return recovery+ } finally {+ this.busyDrafts.delete(id)+ }}replaceUncertain = async (id: string): Promise<Draft> => {const journal = this.journals.get(id)const draft = this.localDrafts.get(id)if (journal?.state !== 'uncertain' || !draft)throw new Error('Only an unconfirmed message can be replaced.')- // The unconfirmed record stays, so its evidence remains available for later checks.- const replacement = this.copyDraft(draft, {})- this.localDrafts.set(replacement.id, replacement)- await this.persistDrafts()- return replacement+ this.requireProtectedDraft(draft)+ if (this.busyDrafts.has(id)) throw new Error('Wait for this draft to finish saving.')+ this.busyDrafts.add(id)+ try {+ // The unconfirmed record stays, so its evidence remains available for later checks.+ const replacement = this.copyDraft(draft, {})+ this.localDrafts.set(replacement.id, replacement)+ if (replacement.encryption === 'encrypt') this.protectedLoaded.add(replacement.id)+ await this.persistDrafts()+ return replacement+ } finally {+ this.busyDrafts.delete(id)+ }}dismissSubmission = async (id: string): Promise<void> => {const journal = this.journals.get(id)if (!journal) return+ const draft = this.localDrafts.get(id)+ if (draft && ['partial', 'uncertain'].includes(journal.state)) this.requireProtectedDraft(draft)journal.dismissed = trueif (journal.sentCopy && journal.sentCopy !== 'filed' && journal.sentCopy !== 'server')journal.sentCopy = 'dismissed'- const draft = this.localDrafts.get(id)if (draft && ['partial', 'uncertain'].includes(journal.state)) await this.completeDraft(draft)await this.removeMime(id)journal.mime = undefinedawait this.persistJournal()}- stageAttachments = async (): Promise<StagedAttachment[]> => {+ stageAttachments = async (protectedDraft = false): Promise<StagedAttachment[]> => {const result = await dialog.showOpenDialog({title: 'Attach files',properties: ['openFile', 'multiSelections'],})if (result.canceled) return []+ if (this.protectionTransition) throw new Error('The vault is locking.')const directory = join(this.store.directory, 'attachments')await mkdir(directory, { recursive: true, mode: 0o700 })const attachments: StagedAttachment[] = []@@ -1470,21 +1825,34 @@ export class MailService {size,type: types[extname(path).toLowerCase()] || 'application/octet-stream',}- await copyFile(path, join(directory, a.id))- await chmod(join(directory, a.id), 0o600)+ if (protectedDraft) {+ await this.protectStagedAttachment(a, await readFile(path))+ } else {+ await copyFile(path, join(directory, a.id))+ await chmod(join(directory, a.id), 0o600)+ }this.staging.set(a.id, a)attachments.push(a)}- await this.store.write('staging', [...this.staging.values()])+ await this.persistStaging()return attachments}+ private async attachmentBytes(accountId: string, attachment: Attachment): Promise<Uint8Array> {+ if (attachment.blobId.startsWith('decrypted:')) {+ const data = this.encryption.attachments.get(attachment.blobId)+ if (!this.encryption.vault.unlocked || data?.accountId !== accountId)+ throw new Error('Unlock and reopen this message to access its attachment.')+ return data.content+ }+ return this.guard(accountId, (p, a) => p.download(a, attachment))+ }attachment = async (accountId: string, attachment: Attachment, open: boolean): Promise<void> => {const result = await dialog.showSaveDialog({title: open ? 'Save and open attachment' : 'Save attachment',defaultPath: basename(attachment.name),})if (result.canceled || !result.filePath) return- const bytes = await this.guard(accountId, (p, a) => p.download(a, attachment))+ const bytes = await this.attachmentBytes(accountId, attachment)await writeFile(result.filePath, bytes, { mode: 0o600 })if (open) {const error = await shell.openPath(result.filePath)@@ -1494,17 +1862,24 @@ export class MailService {inlineImage = async (accountId: string, attachment: Attachment): Promise<string> => {if (!/^image\/(png|jpeg|gif|webp|avif)$/i.test(attachment.type) || attachment.size > 10_000_000)throw new Error('Unsupported inline image.')- const bytes = await this.guard(accountId, (p, a) => p.download(a, attachment))+ const bytes = await this.attachmentBytes(accountId, attachment)return 'data:' + attachment.type + ';base64,' + Buffer.from(bytes).toString('base64')}- remoteImage = async (value: string): Promise<string | null> =>- this.settings.remoteImages ? remoteImageData(value) : null+ remoteImage = async (value: string, userInitiated = false): Promise<string | null> =>+ this.settings.remoteImages || (userInitiated && this.encryption.vault.unlocked)+ ? remoteImageData(value)+ : nullsenderAvatar = async (email: string): Promise<string | null> => {if (!this.settings.remoteImages) return nullreturn this.senderAvatars.get(email)}unsubscribe = async (accountId: string, messageId: string) => {- const [message] = await this.guard(accountId, (p, a) => p.messages(a, [messageId], true))+ const [message] = await this.guard(accountId, async (p, a) => {+ const [m] = await p.messages(a, [messageId], true)+ return m && p.rawMessage+ ? [await this.encryption.read(m, await p.rawMessage(a, messageId, maxMessageBytes))]+ : [m]+ })const info = message?.unsubscribeif (!info) throw new Error('This message has no supported unsubscribe method.')if (info.url.startsWith('mailto:')) return { kind: 'mailto' as const, url: info.url }@@ -1657,6 +2032,7 @@ export class MailService {await this.syncPendingDrafts()}dispose() {+ void this.encryption.lock()if (this.timer) clearInterval(this.timer)if (this.indexingEmit) clearTimeout(this.indexingEmit)for (const provider of this.providers.values()) {diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 8e96b0c..18d96a2 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -1,6 +1,18 @@import { contextBridge, ipcRenderer } from 'electron'import type { DesktopMailAPI, AppEvent } from '@inlark/core'const methods = [+ 'encryptionStatus',+ 'setupEncryption',+ 'setEncryptionPreference',+ 'exportEncryptionKey',+ 'revokeEncryptionKey',+ 'postponeEncryptionBackup',+ 'discoverEncryptionKeys',+ 'acceptEncryptionKey',+ 'encryptionReadiness',+ 'unlockEncryption',+ 'lockEncryption',+ 'transferEncryption','bootstrap','updateStatus','ready',diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 4763b9c..7842f0b 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -1,3 +1,4 @@+import { clearDecryptedCache } from './cache'import { cn } from '@inlark/ui'import { useEffect, useMemo, useRef, useState, lazy, Suspense } from 'react'import { useInfiniteQuery, useQueries, useQuery } from '@tanstack/react-query'@@ -42,6 +43,9 @@ import {PanelLeftClose,UserRound,Info,+ Lock,+ LockOpen,+ LockKeyhole,} from '@inlark/ui/icons'import { Button, Checkbox, Dropdown, MenuItem, IconButton, EmptyState, Spinner } from '@inlark/ui'import {@@ -97,6 +101,8 @@ import { selectConversation } from './selection'import { ShortcutHint, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'import { emptyListState } from './empty-states'import { AccountMark } from './AccountMark'+import { lockVault, useEncryption } from './encryption-ui'+import { useUnlock } from './encryption-actions'import { HintIconButton } from './HintIconButton'import { targetAccounts, targetLimit } from './account-limits'import { newMessageAccount } from './compose-account'@@ -144,6 +150,8 @@ export function App() {const [density, setDensity] = useState<'compact' | 'comfortable'>(() =>localStorage.getItem('mail-density') === 'comfortable' ? 'comfortable' : 'compact',)+ const encryption = useEncryption()+ const [unlock, unlockDialog] = useUnlock()const [settingsOpen, setSettingsOpen] = useState(false),[settingsTab, setSettingsTab] = useState('general')const [composer, setComposer] = useState<Draft>(),@@ -269,11 +277,16 @@ export function App() {queryFn: async () => {const values = await Promise.all([api.drafts(), localDrafts()])const merged = new Map<string, Draft>()+ for (const draft of values[0])+ if (draft.encryption === 'encrypt') await localDeleteDraft(draft.id)for (const draft of values.flat()) {const old = merged.get(draft.id)if (!old ||- (old.status !== 'sent' && old.status !== 'uncertain' && old.updatedAt < draft.updatedAt)+ (old.encryption !== 'encrypt' &&+ old.status !== 'sent' &&+ old.status !== 'uncertain' &&+ old.updatedAt < draft.updatedAt))merged.set(draft.id, draft)}@@ -583,6 +596,9 @@ export function App() {attachments: [],updatedAt: new Date().toISOString(),status: 'local',+ ...(message?.security?.encrypted+ ? { encryption: 'encrypt' as const, encryptionRequired: true }+ : {}),...(message && kind !== 'forward'? {inReplyTo: message.messageId,@@ -595,9 +611,9 @@ export function App() {text,}if (kind === 'forward' && message?.attachments?.length)- draft.attachments = (await api.stageRemoteAttachments(id, message.attachments)).map(- (a) => ({ ...a, cid: undefined }),- )+ draft.attachments = (+ await api.stageRemoteAttachments(id, message.attachments, draft.encryption === 'encrypt')+ ).map((a) => ({ ...a, cid: undefined }))setComposer(draft)} catch (e) {fail(e)@@ -805,6 +821,12 @@ export function App() {}, [route.thread, route.threadAccount, thread.data, readerAccount?.status])useEffect(() => {const unsubscribe = api.onEvent((event) => {+ if (event.type === 'encryption') {+ if (event.locked) setComposer(undefined)+ void clearDecryptedCache().then(() => refresh())+ void queryClient.invalidateQueries({ queryKey: ['drafts'] })+ void queryClient.invalidateQueries({ queryKey: ['encryption'] })+ }if (event.type === 'changed') void refresh()if (event.type === 'accounts') {queryClient.setQueryData<Bootstrap>(@@ -1377,6 +1399,40 @@ export function App() {keywords: 'sign-off',run: () => openSettings('signatures'),},+ {+ id: 'encryption',+ group: 'Preferences',+ label: 'Encryption settings',+ icon: LockKeyhole,+ keywords: 'openpgp pgp gpg keys security privacy backup',+ run: () => openSettings('encryption'),+ },+ ...(encryption.data?.vault === 'unlocked'+ ? [+ {+ id: 'lock-keys',+ group: 'Preferences',+ label: 'Lock encryption keys',+ icon: Lock,+ keywords: 'vault openpgp security',+ run: () =>+ void lockVault()+ .then(() => notify('Encryption keys locked.'))+ .catch((e) => notify(friendlyError(e), 'error')),+ },+ ]+ : encryption.data?.vault === 'locked'+ ? [+ {+ id: 'unlock-keys',+ group: 'Preferences',+ label: 'Unlock encryption keys',+ icon: LockOpen,+ keywords: 'vault openpgp security',+ run: () => void unlock(),+ },+ ]+ : []),{id: 'shortcuts',group: 'Help',@@ -1555,6 +1611,8 @@ export function App() {onMailto={onMailto}unsubscribe={unsubscribeState}onUnsubscribe={() => void unsubscribe()}+ onUnlock={() => void unlock()}+ onOpenEncryption={() => openSettings('encryption')}/>) : (<EmptyState@@ -2369,6 +2427,7 @@ export function App() {settings={settings}onClose={() => setComposer(undefined)}onOpenAccounts={() => openSettings('accounts')}+ onOpenEncryption={() => openSettings('encryption')}notify={notify}onSaved={() => void queryClient.invalidateQueries({ queryKey: ['drafts'] })}/>@@ -2396,6 +2455,7 @@ export function App() {commands={commands}/><ShortcutDialog open={help} onClose={() => setHelp(false)} />+ {unlockDialog}<FilterDialogkey={filterOpen ? 'filter-open' : 'filter-closed'}open={filterOpen}diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxindex 50963b3..599fb55 100644--- a/apps/desktop/src/renderer/src/Composer.tsx+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -1,6 +1,6 @@import { cn } from '@inlark/ui'import { useEffect, useRef, useState } from 'react'-import { useQueries } from '@tanstack/react-query'+import { useQueries, useQuery } from '@tanstack/react-query'import { useForm } from '@tanstack/react-form'import { Dialog } from '@base-ui/react/dialog'import { useEditor, useEditorState, EditorContent } from '@tiptap/react'@@ -19,6 +19,7 @@ import {AlertCircle,ArrowUpRight,FileText,+ Lock,} from '@inlark/ui/icons'import { Modal, Button, IconButton, Select, Spinner } from '@inlark/ui'import {@@ -33,7 +34,10 @@ import {} from '@inlark/core'import { api, isDemo } from './api'import { localSaveDraft, localDeleteDraft } from './cache'-import { RecipientField } from './RecipientField'+import { RecipientField, type ChipSecurity } from './RecipientField'+import { recipientProblems, useEncryption } from './encryption-ui'+import { ContactKeyDialog, keysChanged, useUnlock } from './encryption-actions'+import { ProtectionBar, ProtectionMenu, type Protection } from './ComposerProtection'import { formatBytes } from './mail-date'import { bindingText, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'import { SignatureNode } from './signature'@@ -103,6 +107,7 @@ export function Composer({suggestions,onClose,onOpenAccounts,+ onOpenEncryption,notify,onSaved,}: {@@ -113,9 +118,16 @@ export function Composer({onClose: () => void/** Opens Settings → Accounts, e.g. to sign in to the outgoing server again. */onOpenAccounts: () => void+ /** Opens Settings → Encryption, to set up or fix this address's key. */+ onOpenEncryption: () => voidnotify: (message: string, tone?: 'error' | 'info') => voidonSaved: () => void}) {+ const [downgradeMode, setDowngradeMode] = useState<'none' | 'sign' | undefined>()+ // Once someone picks a protection mode, the recommendation never overrides it.+ const encryptionChoice = useRef(initial.encryption !== undefined)+ const [unlock, unlockDialog] = useUnlock()+ const [reviewKey, setReviewKey] = useState<string>()const shortcuts = useShortcuts()const keys = useShortcutText()const sendShortcut = shortcuts.bindings.send[0]@@ -177,7 +189,40 @@ export function Composer({disabled: true,})const signature = identity ? identitySignature(settings, identity) : undefined- const locked = sending || changingFrom || draft.status === 'uncertain' || draft.status === 'sent'+ const vault = useEncryption()+ const recipientEmails = [...draft.to, ...draft.cc, ...draft.bcc].map((a) => a.email)+ const encryptionReady = useQuery({+ queryKey: ['recipient-encryption', draft.accountId, draft.identityId, recipientEmails],+ queryFn: () => api.encryptionReadiness(draft.accountId, draft.identityId, recipientEmails),+ enabled: !!draft.identityId && recipientEmails.every(validAddress),+ staleTime: 10000,+ retry: false,+ })+ const own = vault.data?.identities.find(+ (i) => i.accountId === draft.accountId && i.identityId === draft.identityId,+ )+ const ownKey = own && vault.data?.keys.find((k) => k.fingerprint === own.fingerprint)+ const protection: Protection = draft.encryption || 'none'+ const blocked =+ protection === 'encrypt'+ ? encryptionReady.data?.recipients.filter((r) => r.status !== 'ready') || []+ : []+ const chipSecurity = (address: Address): ChipSecurity | undefined => {+ if (protection !== 'encrypt' || !own?.enabled) return+ const recipient = encryptionReady.data?.recipients.find(+ (r) => r.email === address.email.trim().toLowerCase(),+ )+ if (!recipient) return+ return recipient.status === 'ready'+ ? { ready: true, label: recipient.confirmed ? 'Encrypted · verified key' : 'Encrypted' }+ : { ready: false, label: 'Can’t encrypt · ' + recipientProblems[recipient.status] }+ }+ const locked =+ sending ||+ changingFrom ||+ draft.status === 'uncertain' ||+ draft.status === 'sent' ||+ (draft.encryption === 'encrypt' && vault.data?.vault !== 'unlocked')const lockedRef = useRef(locked)lockedRef.current = locked// A failed send is kept apart from the draft, so a later autosave can't clear the explanation.@@ -243,6 +288,30 @@ export function Composer({link: editor?.isActive('link') || false,}),})+ useEffect(() => {+ if (+ encryptionReady.data?.recommend &&+ !encryptionChoice.current &&+ latest.current.encryption !== 'encrypt'+ )+ update({ encryption: 'encrypt', earlierPlaintext: persisted.current })+ }, [encryptionReady.data?.recommend])+ useEffect(() => {+ const save = (event: Event) => {+ const tasks = (event as CustomEvent<Promise<unknown>[]>).detail+ tasks.push(+ (async () => {+ await sync.current+ if (shouldSave()) {+ await localSaveDraft(latest.current)+ await api.saveDraft(latest.current)+ }+ })(),+ )+ }+ window.addEventListener('inlark-before-lock', save)+ return () => window.removeEventListener('inlark-before-lock', save)+ }, [editor])useEffect(() => {// Locking for a send is not an edit, so it must not reset the draft or its error.editor?.setEditable(!locked, false)@@ -335,8 +404,21 @@ export function Composer({notify('Your draft could not be saved. ' + friendlyError(e), 'error')}}+ /** Changes how the message is protected; dropping encryption from decrypted content is confirmed. */+ const setProtection = (mode: Protection) => {+ encryptionChoice.current = true+ if (mode === protection) return+ if (mode !== 'encrypt' && (protection === 'encrypt' || draft.encryptionRequired))+ setDowngradeMode(mode)+ else+ update({+ encryption: mode,+ downgradeConfirmed: false,+ earlierPlaintext: mode === 'encrypt' && persisted.current,+ })+ }const send = async () => {- if (sending || changingFrom || account.status !== 'connected') return+ if (locked || account.status !== 'connected') returnconst fields = ['to', 'cc', 'bcc'] as constif (!fields.some((field) => latest.current[field].length)) {notify('Add a recipient before sending.', 'error')@@ -357,6 +439,22 @@ export function Composer({document.getElementById('compose-from')?.focus()return}+ // Encryption is never dropped to send; the bar above the message explains what to fix.+ if (latest.current.encryption === 'encrypt' && encryptionReady.data) {+ if (!encryptionReady.data.senderReady) {+ notify('Encryption isn’t ready for this address. Fix it, or stop encrypting.', 'error')+ return+ }+ if (blocked.length) {+ notify(+ 'Can’t encrypt to ' ++ (blocked.length === 1 ? blocked[0].email : blocked.length + ' recipients') ++ '. Review their keys, or stop encrypting.',+ 'error',+ )+ return+ }+ }setSending(true)setSendError(undefined)try {@@ -438,7 +536,7 @@ export function Composer({}const attachFiles = async () => {try {- const attachments = await api.stageAttachments()+ const attachments = await api.stageAttachments(latest.current.encryption === 'encrypt')// The file picker can outlive the composer or a send. Never change a locked draft.if (!alive.current || lockedRef.current) returnupdate({ attachments: [...latest.current.attachments, ...attachments] })@@ -488,6 +586,10 @@ export function Composer({enabled: !linkOpen && !discardOpen && !sending && !changingFrom,},discardDraft: { run: () => setDiscardOpen(true), enabled: canEdit },+ toggleEncryption: {+ run: () => setProtection(protection === 'encrypt' ? 'none' : 'encrypt'),+ enabled: canEdit && !!own,+ },})const addressField = (name: 'to' | 'cc' | 'bcc', label: string) => (<RecipientField@@ -499,6 +601,7 @@ export function Composer({autoFocus={name === 'to' && !initial.to.length}placeholder={name === 'to' ? 'Name or email address' : ''}onChange={(addresses) => update({ [name]: addresses })}+ security={chipSecurity}>{name === 'to' && !showCc && (<button@@ -531,7 +634,8 @@ export function Composer({'composer fixed right-6 bottom-6 w-[min(660px,_calc(100vw_-_48px))]','h-[min(700px,_calc(100vh_-_48px_-_var(--titlebar-height)))]','bg-surface border border-solid border-border-strong rounded-2xl shadow-popup z-71 flex flex-col overflow-hidden',- 'transition-[opacity,transform] duration-160 ease-[ease] data-starting-style:opacity-0',+ 'transition-[opacity,transform,filter] duration-160 ease-[ease] data-starting-style:opacity-0',+ 'data-nested-dialog-open:brightness-[0.62]','data-starting-style:transform-[translateY(10px)_scale(0.99)] data-ending-style:opacity-0','data-ending-style:transform-[translateY(10px)_scale(0.99)]',expanded &&@@ -677,6 +781,63 @@ export function Composer({)}</form.Field></div>+ <ProtectionBar+ mode={protection}+ vault={vault.data?.vault}+ own={own}+ ownKeyProblem={ownKey && !ownKey.usable ? ownKey.problem || 'unusable' : undefined}+ email={identity?.email || account.email}+ recipients={recipientEmails.length}+ readiness={encryptionReady}+ blocked={blocked}+ nameOf={(email) =>+ [...draft.to, ...draft.cc, ...draft.bcc].find(+ (a) => a.email.trim().toLowerCase() === email,+ )?.name || email+ }+ earlierPlaintext={!!draft.earlierPlaintext}+ onUnlock={() => void unlock()}+ onSetUp={onOpenEncryption}+ onTurnOn={() =>+ own &&+ void api+ .setEncryptionPreference(own.accountId, own.identityId, true, own.prefer)+ .then(keysChanged)+ .catch((e) => notify(friendlyError(e), 'error'))+ }+ onReview={setReviewKey}+ onStop={() => setProtection('none')}+ />+ <Modal+ open={!!downgradeMode}+ onOpenChange={(open) => {+ if (!open) setDowngradeMode(undefined)+ }}+ title={downgradeMode === 'sign' ? 'Sign without encrypting?' : 'Stop encrypting?'}+ description={+ (draft.encryptionRequired+ ? 'This message includes content from encrypted mail. '+ : '') ++ 'Its text and attachments will be saved and sent as readable mail that mail servers can read. Encrypted copies already saved are kept.'+ }+ >+ <div className="modal-actions flex justify-end gap-2 mt-6">+ <Button onClick={() => setDowngradeMode(undefined)}>Keep encrypting</Button>+ <Button+ variant="danger"+ onClick={() => {+ update({+ encryption: downgradeMode!,+ encryptionRequired: true,+ downgradeConfirmed: true,+ })+ setDowngradeMode(undefined)+ }}+ >+ {downgradeMode === 'sign' ? 'Sign only' : 'Don’t encrypt'}+ </Button>+ </div>+ </Modal><div className="compose-body flex-1 overflow-auto py-5 px-6 min-h-0"><EditorContent editor={editor} />{draft.attachments.length > 0 && (@@ -810,6 +971,14 @@ export function Composer({><Paperclip size={15} /></IconButton>+ {(own || protection !== 'none') && (+ <ProtectionMenu+ mode={protection}+ shortcut={own ? keys('toggleEncryption') : undefined}+ onChange={setProtection}+ onSettings={onOpenEncryption}+ />+ )}</fieldset><div className="compose-footer flex items-center gap-2.5 py-3.25 px-5 border-t border-solid border-t-border"><Button@@ -817,7 +986,13 @@ export function Composer({onClick={() => void send()}disabled={sending || changingFrom || account.status !== 'connected'}>- {sending ? <Spinner size={14} /> : <Send size={13} />}{' '}+ {sending ? (+ <Spinner size={14} />+ ) : protection === 'encrypt' && draft.status !== 'uncertain' ? (+ <Lock size={13} />+ ) : (+ <Send size={13} />+ )}{' '}{sending? draft.status === 'uncertain'? 'Checking delivery…'@@ -826,7 +1001,11 @@ export function Composer({? 'Check delivery': isDemo? 'Simulate send'- : 'Send message'}+ : protection === 'encrypt'+ ? 'Send encrypted'+ : protection === 'sign'+ ? 'Send signed'+ : 'Send message'}{sendShortcut && (<span className="send-shortcut text-[11px] opacity-60 ml-2.5">{bindingText(sendShortcut)}@@ -847,6 +1026,8 @@ export function Composer({</div></Dialog.Popup></Dialog.Portal>+ <ContactKeyDialog email={reviewKey} onClose={() => setReviewKey(undefined)} />+ {unlockDialog}<Modalopen={discardOpen}onOpenChange={setDiscardOpen}diff --git a/apps/desktop/src/renderer/src/ComposerProtection.tsx b/apps/desktop/src/renderer/src/ComposerProtection.tsxnew file mode 100644index 0000000..e9760a0--- /dev/null+++ b/apps/desktop/src/renderer/src/ComposerProtection.tsx@@ -0,0 +1,306 @@+import { cn } from '@inlark/ui'+import type { ReactNode } from 'react'+import type { UseQueryResult } from '@tanstack/react-query'+import {+ AlertCircle,+ Check,+ ChevronDown,+ Lock,+ LockKeyhole,+ LockOpen,+ Signature,+ type IconComponent,+} from '@inlark/ui/icons'+import { Button, Dropdown, MenuItem, Spinner } from '@inlark/ui'+import {+ friendlyError,+ type EncryptionIdentity,+ type EncryptionReadiness,+ type EncryptionStatus,+ type RecipientReadiness,+} from '@inlark/core'+import { recipientProblems } from './encryption-ui'++export type Protection = 'none' | 'encrypt' | 'sign'++const modes: Record<+ Protection,+ { icon: IconComponent; label: string; current: string; detail: string }+> = {+ encrypt: {+ icon: Lock,+ label: 'Encrypt',+ current: 'Encrypted',+ detail: 'Only recipients can read it',+ },+ sign: {+ icon: Signature,+ label: 'Sign only',+ current: 'Signed',+ detail: 'Proves it’s from you; anyone can read it',+ },+ none: {+ icon: LockOpen,+ label: 'Don’t encrypt',+ current: 'Not encrypted',+ detail: 'Send as regular email',+ },+}++/** The composer toolbar's choice of encrypting, signing or neither. */+export function ProtectionMenu({+ mode,+ shortcut,+ onChange,+ onSettings,+}: {+ mode: Protection+ shortcut?: string+ onChange: (mode: Protection) => void+ onSettings: () => void+}) {+ const current = modes[mode]+ const Icon = current.icon+ return (+ <Dropdown+ className="compose-protection-menu w-66 [&_.menu-item]:py-1.5"+ trigger={+ <Button+ size="small"+ variant="ghost"+ className={cn(+ 'compose-protection-trigger ml-auto h-7.25 gap-1.5 px-2.25 data-popup-open:bg-hover',+ '[&[data-popup-open]_.chevron]:transform-[rotate(180deg)]',+ mode === 'encrypt' &&+ 'text-primary bg-primary-tint [&:hover:not(:disabled)]:text-primary [&:hover:not(:disabled)]:bg-primary-tint',+ )}+ aria-label={'Protection: ' + current.current}+ title={shortcut ? 'Encrypt or stop encrypting · ' + shortcut : undefined}+ >+ <Icon size={14} />+ {current.current}+ <ChevronDown+ size={12}+ className="chevron opacity-70 transition-[transform] duration-120"+ />+ </Button>+ }+ >+ {(Object.keys(modes) as Protection[]).map((value) => {+ const option = modes[value]+ const OptionIcon = option.icon+ return (+ <MenuItem key={value} onClick={() => onChange(value)}>+ <OptionIcon size={15} className={cn(value === mode && 'text-primary')} />+ <span className="flex flex-col min-w-0">+ <span>{option.label}</span>+ <span className="text-[11px] text-muted">{option.detail}</span>+ </span>+ {value === mode && <Check size={13} className="ml-auto text-primary" />}+ </MenuItem>+ )+ })}+ <div className="h-[1px] m-1.25 bg-border" />+ <MenuItem onClick={onSettings}>+ <LockKeyhole size={14} />+ Encryption settings…+ </MenuItem>+ </Dropdown>+ )+}++/**+ * One line between the addresses and the message that says how it will be protected, and+ * what to do when it can't be.+ */+export function ProtectionBar({+ mode,+ vault,+ own,+ ownKeyProblem,+ email,+ recipients,+ readiness,+ blocked,+ nameOf,+ earlierPlaintext,+ onUnlock,+ onSetUp,+ onTurnOn,+ onReview,+ onStop,+}: {+ mode: Protection+ vault?: EncryptionStatus['vault']+ own?: EncryptionIdentity+ ownKeyProblem?: string+ email: string+ recipients: number+ readiness: UseQueryResult<EncryptionReadiness>+ blocked: RecipientReadiness[]+ nameOf: (email: string) => string+ earlierPlaintext: boolean+ onUnlock: () => void+ onSetUp: () => void+ onTurnOn: () => void+ onReview: (email: string) => void+ onStop: () => void+}) {+ if (mode === 'none') return null+ const stop = (+ <Button size="small" variant="ghost" onClick={onStop}>+ {mode === 'encrypt' ? 'Don’t encrypt' : 'Don’t sign'}+ </Button>+ )+ let tone: 'calm' | 'neutral' | 'warning' | 'danger' = 'calm'+ let icon: IconComponent | 'spinner' = mode === 'encrypt' ? Lock : Signature+ let text: ReactNode+ let action: ReactNode+ let detail: ReactNode+ if (!vault) {+ icon = 'spinner'+ text = 'Checking encryption…'+ } else if (vault === 'locked') {+ tone = 'warning'+ icon = LockKeyhole+ text =+ mode === 'encrypt'+ ? 'Your keys are locked. Unlock them to keep writing this encrypted message.'+ : 'Your keys are locked. Unlock them to sign this message.'+ action = (+ <Button size="small" onClick={onUnlock}>+ Unlock+ </Button>+ )+ } else if (!own) {+ tone = 'warning'+ icon = AlertCircle+ text = 'Encryption isn’t set up for ' + email + ' yet.'+ action = (+ <>+ {stop}+ <Button size="small" onClick={onSetUp}>+ Set up…+ </Button>+ </>+ )+ } else if (!own.enabled) {+ tone = 'warning'+ icon = AlertCircle+ text = 'Encryption is turned off for ' + email + '.'+ action = (+ <>+ {stop}+ <Button size="small" onClick={onTurnOn}>+ Turn on+ </Button>+ </>+ )+ } else if (ownKeyProblem) {+ tone = 'danger'+ icon = AlertCircle+ text =+ 'Your key for ' ++ email ++ (ownKeyProblem === 'revoked'+ ? ' was revoked.'+ : ownKeyProblem === 'expired'+ ? ' has expired.'+ : ' can’t be used.') ++ ' Replace it in Settings.'+ action = (+ <>+ {stop}+ <Button size="small" onClick={onSetUp}>+ Settings…+ </Button>+ </>+ )+ } else if (mode === 'sign') {+ tone = 'neutral'+ text =+ 'Signed, not encrypted. Recipients can check it’s from you, but anyone handling it can read it.'+ } else if (readiness.isError) {+ tone = 'danger'+ icon = AlertCircle+ text = 'Couldn’t check recipients’ keys. ' + friendlyError(readiness.error)+ action = (+ <Button size="small" onClick={() => void readiness.refetch()}>+ Try again+ </Button>+ )+ } else if (recipients && !readiness.data) {+ icon = 'spinner'+ text = 'Checking recipients’ keys…'+ } else if (blocked.length) {+ tone = 'danger'+ icon = AlertCircle+ text =+ 'Can’t encrypt to ' ++ (blocked.length === 1 ? nameOf(blocked[0].email) : blocked.length + ' recipients') ++ '. Review ' ++ (blocked.length === 1 ? 'their key' : 'their keys') ++ ', or send without encryption.'+ detail = (+ <span className="flex flex-wrap gap-1.5 mt-1.5">+ {blocked.map((recipient) => (+ <button+ type="button"+ key={recipient.email}+ className={cn(+ 'inline-flex items-center gap-1.25 h-5.5 px-2 rounded-xl border border-solid border-danger/35 bg-transparent',+ 'text-[11px] text-danger whitespace-nowrap transition-[background] duration-120 hover:bg-danger/10',+ )}+ title={'Review the key for ' + recipient.email}+ onClick={() => onReview(recipient.email)}+ >+ <LockOpen size={11} />+ {nameOf(recipient.email)}+ <span className="text-danger/75">+ · {recipientProblems[recipient.status as keyof typeof recipientProblems]}+ </span>+ </button>+ ))}+ </span>+ )+ action = stop+ } else {+ const count = readiness.data?.recipients.length || 0+ text = count+ ? 'Encrypted for ' ++ (count === 1+ ? nameOf(readiness.data!.recipients[0].email)+ : 'all ' + count + ' recipients') ++ '. The subject line isn’t encrypted.'+ : 'Encrypted. Add recipients to check their keys. The subject line isn’t encrypted.'+ }+ const Icon = icon === 'spinner' ? undefined : icon+ return (+ <div+ role="status"+ className={cn(+ 'compose-protection flex items-start gap-2.5 py-2.25 px-6 text-[11px] leading-[1.55] shrink-0',+ 'border-b border-solid border-b-border',+ tone === 'calm' && 'bg-primary-tint text-secondary [&>.protection-icon]:text-primary',+ tone === 'neutral' &&+ 'bg-[color-mix(in_srgb,_var(--hover)_50%,_transparent)] text-secondary [&>.protection-icon]:text-muted',+ tone === 'warning' && 'bg-star/8 text-foreground [&>.protection-icon]:text-star',+ tone === 'danger' && 'bg-danger/7 text-foreground [&>.protection-icon]:text-danger',+ )}+ >+ <span className="protection-icon flex shrink-0 mt-[2px]">+ {Icon ? <Icon size={13} /> : <Spinner size={13} />}+ </span>+ <div className="flex-1 min-w-0">+ <span>{text}</span>+ {detail}+ {earlierPlaintext && mode === 'encrypt' && (+ <span className="block text-muted mt-0.5">+ An earlier copy of this draft was saved unencrypted and may remain on the server.+ </span>+ )}+ </div>+ {action && <div className="flex shrink-0 gap-1.5 -my-[3px]">{action}</div>}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/ConversationRow.tsx b/apps/desktop/src/renderer/src/ConversationRow.tsxindex 7aaf335..bdfa14e 100644--- a/apps/desktop/src/renderer/src/ConversationRow.tsx+++ b/apps/desktop/src/renderer/src/ConversationRow.tsx@@ -1,5 +1,5 @@import { cn } from '@inlark/ui'-import { Archive, Mail, MailOpen, Paperclip, Star, Trash2 } from '@inlark/ui/icons'+import { Archive, Lock, Mail, MailOpen, Paperclip, Star, Trash2 } from '@inlark/ui/icons'import { Checkbox, IconButton } from '@inlark/ui'import { isDraft, type Account, type Conversation } from '@inlark/core'import { shortDate } from './mail-date'@@ -149,7 +149,14 @@ export function ConversationRow({{subject}</span><span className="row-preview overflow-hidden text-ellipsis text-muted text-[12px] leading-[18px] @max-[900px]/mail:[.density-compact_&]:hidden @max-[440px]/mail:[.density-comfortable_&]:hidden">- {c.preview}+ {c.preview ||+ // Encrypted mail has no readable preview; say why the line is empty.+ (c.messages.some((m) => m.security?.encrypted) && (+ <span className="row-encrypted inline-flex items-center gap-1 text-faint">+ <Lock size={11} />+ Encrypted message+ </span>+ ))}</span></div><divdiff --git a/apps/desktop/src/renderer/src/EncryptionSettings.tsx b/apps/desktop/src/renderer/src/EncryptionSettings.tsxnew file mode 100644index 0000000..39108d3--- /dev/null+++ b/apps/desktop/src/renderer/src/EncryptionSettings.tsx@@ -0,0 +1,1594 @@+import { cn } from '@inlark/ui'+import { useState, type ReactNode, type RefObject } from 'react'+import { useQueries } from '@tanstack/react-query'+import {+ AlertCircle,+ BadgeCheck,+ Check,+ ChevronDown,+ ChevronRight,+ Copy,+ DeviceSync,+ FileImport,+ Key,+ Lock,+ LockOpen,+ RefreshCw,+ Search,+ Share,+ ShieldX,+} from '@inlark/ui/icons'+import { Button, Checkbox, Dropdown, MenuItem, Modal, Spinner, Switch } from '@inlark/ui'+import {+ friendlyError,+ type Account,+ type EncryptionIdentity,+ type EncryptionKeySummary,+ type Identity,+} from '@inlark/core'+import { api } from './api'+import { AccountMark } from './AccountMark'+import {+ Callout,+ FingerprintBlock,+ FormError,+ KeyBadge,+ NewPasswordFields,+ PasswordField,+ StateIcon,+ dialogLead,+ formatFingerprint,+ keyFileError,+ keySources,+ lockVault,+ modalActions,+ newPasswordProblem,+ shortFingerprint,+ useEncryption,+} from './encryption-ui'+import { ContactKeyDialog, keysChanged, useUnlock } from './encryption-actions'++const section = cn(+ 'setting-section my-6.25 mx-0 [&_h4]:text-[11px] [&_h4]:font-medium [&_h4]:mt-0 [&_h4]:mb-3 [&_h4]:mx-0',+ '[&_h4]:text-secondary [&+.setting-section]:border-t [&+.setting-section]:border-solid',+ '[&+.setting-section]:border-t-border [&+.setting-section]:pt-5.5',+)+const settingRow = cn(+ 'setting-row flex items-center justify-between my-3.5 mx-0 gap-6 [&_strong]:font-normal [&_p]:text-muted',+ '[&_p]:my-[3px] [&_p]:mx-0 [&_input]:shrink-0 [&>.button]:shrink-0 [&_p]:text-[12px] [&_p]:leading-[1.6]',+ '[&_strong]:text-[13px] max-[700px]:gap-3.5',+)+const dialogWidth = 'w-[min(490px,_calc(100vw_-_40px))]'+const backupHint =+ 'At least 10 characters. Inlark can’t recover it, so keep it apart from the backup file, for example in a password manager.'++type Notify = (message: string, tone?: 'error' | 'info') => void+/** One sending address, with its key when it has one. */+interface Target {+ account: Account+ identity: Identity+ own?: EncryptionIdentity+ key?: EncryptionKeySummary+ /** The account's addresses are still being fetched. */+ loading?: boolean+}+type Dialog =+ | { kind: 'setup' | 'transfer' | 'replace' | 'older'; target: Target }+ | { kind: 'backup' | 'postpone' | 'revoke'; key: EncryptionKeySummary }++const isOwn = (key: EncryptionKeySummary) =>+ key.sources.includes('own') || key.sources.includes('import')+const ownedBy = (identity: Identity) => (i: EncryptionIdentity) =>+ i.accountId === identity.accountId && i.identityId === identity.id++/** Settings → Encryption: key storage, each sending address, and contacts’ keys. */+export function EncryptionPanel({+ accounts,+ secureStorage,+ notify,+ portalContainer,+}: {+ accounts: Account[]+ secureStorage: boolean+ notify: Notify+ portalContainer: RefObject<HTMLDivElement | null>+}) {+ const status = useEncryption()+ const [unlock, unlockDialog] = useUnlock()+ const [dialog, setDialog] = useState<Dialog>()+ const [contact, setContact] = useState<string>()+ const [busy, setBusy] = useState(false)+ const identityLists = useQueries({+ queries: accounts.map((a) => ({+ queryKey: ['identities', a.id],+ queryFn: () => api.identities(a.id),+ enabled: a.status === 'connected',+ })),+ })+ const data = status.data+ const targets: Target[] = accounts.flatMap((account, index) => {+ // Without its identities an account still gets a row, so it doesn't silently disappear.+ const identities: Identity[] = identityLists[index]?.data || [+ { id: '', accountId: account.id, name: account.name, email: account.email },+ ]+ return identities.map((identity) => {+ const own = data?.identities.find(ownedBy(identity))+ const key =+ own && data?.keys.find((k) => k.fingerprint === own.fingerprint && k.email === own.email)+ const loading = account.status === 'connected' && !!identityLists[index]?.isPending+ return { account, identity, own, key, loading }+ })+ })+ const current = new Set(targets.map((t) => t.own?.fingerprint).filter(Boolean))+ const olderKeys = (data?.keys || []).filter((k) => isOwn(k) && !current.has(k.fingerprint))+ const run = async (task: () => Promise<unknown>, done?: string) => {+ setBusy(true)+ try {+ await task()+ if (done) notify(done)+ } catch (e) {+ notify(friendlyError(e), 'error')+ } finally {+ setBusy(false)+ }+ }+ const setPreference = (own: EncryptionIdentity, enabled: boolean, prefer: boolean) =>+ void run(async () =>+ keysChanged(+ await api.setEncryptionPreference(own.accountId, own.identityId, enabled, prefer),+ ),+ )+ const unlocked = data?.vault === 'unlocked'+ const close = () => setDialog(undefined)+ return (+ <>+ <h3 className="m-0 text-[20px] font-[550] tracking-[-0.5px]">Encryption</h3>+ <p className="settings-lead text-muted mt-1.5 mb-6 mx-0 text-[12px] leading-[1.6]">+ Encrypted mail can only be read by you and the people you send it to. Inlark uses OpenPGP,+ so it works with Thunderbird, Proton Mail and other apps that support it. Subjects and+ addresses aren’t encrypted.+ </p>+ {data && data.vault !== 'absent' && (+ <div className={section}>+ <h4>Key storage</h4>+ <div className={settingRow}>+ <div className="flex items-center gap-3 min-w-0">+ <StateIcon+ icon={unlocked ? LockOpen : Lock}+ tone={unlocked ? 'neutral' : 'warning'}+ size={34}+ />+ <div>+ <strong>{unlocked ? 'Your keys are unlocked' : 'Your keys are locked'}</strong>+ <p>+ {!unlocked+ ? 'Unlock them to read encrypted mail and keep writing encrypted drafts.'+ : data.protection === 'password'+ ? 'Protected by your vault password. Lock them when you step away.'+ : 'Protected by your system keyring. Locking hides encrypted mail until you unlock again.'}+ </p>+ </div>+ </div>+ <Button+ disabled={busy}+ variant={unlocked ? 'default' : 'primary'}+ onClick={() =>+ void run(+ async () => {+ if (unlocked) await lockVault()+ else await unlock()+ },+ unlocked ? 'Encryption keys locked.' : undefined,+ )+ }+ >+ {unlocked ? <Lock size={14} /> : <LockOpen size={14} />}+ {unlocked ? 'Lock' : 'Unlock'}+ </Button>+ </div>+ </div>+ )}+ <div className={section}>+ <h4>Your addresses</h4>+ {status.isPending ? (+ <div className="flex items-center gap-2 py-4 text-muted text-[12px]">+ <Spinner size={14} /> Loading…+ </div>+ ) : (+ <div className="encryption-identities">+ {targets.map((target) => (+ <IdentityRow+ key={target.account.id + '\n' + (target.identity.id || target.identity.email)}+ target={target}+ showAccount={accounts.length > 1}+ busy={busy}+ portalContainer={portalContainer}+ onDialog={(kind) => setDialog({ kind, target })}+ onKeyDialog={(kind) => target.key && setDialog({ kind, key: target.key })}+ onPreference={setPreference}+ onExport={() =>+ void run(() => api.exportEncryptionKey(target.own!.fingerprint, 'public'))+ }+ notify={notify}+ />+ ))}+ </div>+ )}+ </div>+ <ContactKeys keys={data?.keys || []} onOpen={setContact} />+ {olderKeys.length > 0 && (+ <div className={section}>+ <h4>Older keys</h4>+ <p className="mt-0 mb-1 text-[12px] leading-[1.6] text-muted">+ Kept so you can still read mail encrypted to them. They aren’t used for new mail.+ </p>+ {olderKeys.map((key) => (+ <div+ key={key.fingerprint}+ className="older-key flex items-center gap-3 py-3 border-b border-solid border-b-border last:border-b-0"+ >+ <StateIcon icon={Key} tone="neutral" size={30} />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap text-[13px]">+ <span className="[overflow-wrap:anywhere]">{key.email}</span>+ {key.problem === 'revoked' && <KeyBadge tone="danger">Revoked</KeyBadge>}+ {key.backup && key.backup !== 'done' && (+ <KeyBadge tone="warning">Not backed up</KeyBadge>+ )}+ </div>+ <span className="block text-[11px] text-muted font-mono mt-0.5">+ {shortFingerprint(key.fingerprint)}+ </span>+ </div>+ <Dropdown+ container={portalContainer}+ className="[&_.menu-item]:min-h-7.75 w-52"+ trigger={+ <Button+ size="small"+ aria-label={'Manage older key ' + shortFingerprint(key.fingerprint)}+ >+ Manage+ <ChevronDown size={13} />+ </Button>+ }+ >+ <MenuItem onClick={() => setDialog({ kind: 'backup', key })}>+ <Key size={14} />+ Back up key…+ </MenuItem>+ <MenuItem+ onClick={() => void run(() => api.exportEncryptionKey(key.fingerprint, 'public'))}+ >+ <Share size={14} />+ Export public key…+ </MenuItem>+ {key.problem !== 'revoked' && (+ <>+ <div className="h-[1px] m-1.25 bg-border" />+ <MenuItem danger onClick={() => setDialog({ kind: 'revoke', key })}>+ <ShieldX size={14} />+ Revoke key…+ </MenuItem>+ </>+ )}+ </Dropdown>+ </div>+ ))}+ </div>+ )}+ {dialog?.kind === 'setup' && (+ <SetupDialog+ target={dialog.target}+ secureStorage={secureStorage}+ unlock={unlock}+ notify={notify}+ onClose={close}+ />+ )}+ {dialog?.kind === 'backup' && (+ <Modal+ open+ onOpenChange={(open) => !open && close()}+ title="Back up your key"+ description={'Key ' + shortFingerprint(dialog.key.fingerprint) + ' · ' + dialog.key.email}+ className={dialogWidth}+ >+ <BackupForm+ fingerprint={dialog.key.fingerprint}+ unlock={unlock}+ onSaved={() => {+ notify('Backup saved. Keep its password somewhere safe.')+ close()+ }}+ secondary={<Button onClick={close}>Cancel</Button>}+ />+ </Modal>+ )}+ {dialog?.kind === 'postpone' && (+ <Modal+ open+ onOpenChange={(open) => !open && close()}+ title="Back up later?"+ className={dialogWidth}+ >+ <PostponeForm+ fingerprint={dialog.key.fingerprint}+ onBackUp={() => setDialog({ kind: 'backup', key: dialog.key })}+ onDone={close}+ />+ </Modal>+ )}+ {dialog?.kind === 'transfer' && (+ <TransferDialog target={dialog.target} unlock={unlock} onClose={close} />+ )}+ {dialog?.kind === 'replace' && (+ <ReplaceDialog+ target={dialog.target}+ unlock={unlock}+ onClose={close}+ onReplaced={(key) => {+ notify('Your new key is ready. Contacts will be asked to review it.')+ setDialog(key ? { kind: 'backup', key } : undefined)+ }}+ />+ )}+ {dialog?.kind === 'revoke' && (+ <RevokeDialog keySummary={dialog.key} unlock={unlock} onClose={close} />+ )}+ {dialog?.kind === 'older' && (+ <OlderKeyDialog target={dialog.target} unlock={unlock} notify={notify} onClose={close} />+ )}+ <ContactKeyDialog email={contact} onClose={() => setContact(undefined)} />+ {unlockDialog}+ </>+ )+}++function IdentityRow({+ target,+ showAccount,+ busy,+ portalContainer,+ onDialog,+ onKeyDialog,+ onPreference,+ onExport,+ notify,+}: {+ target: Target+ showAccount: boolean+ busy: boolean+ portalContainer: RefObject<HTMLDivElement | null>+ onDialog: (kind: 'setup' | 'transfer' | 'replace' | 'older') => void+ onKeyDialog: (kind: 'backup' | 'postpone' | 'revoke') => void+ onPreference: (own: EncryptionIdentity, enabled: boolean, prefer: boolean) => void+ onExport: () => void+ notify: Notify+}) {+ const { account, identity, own, key } = target+ const unavailable = !identity.id+ const broken = !!key && !key.usable+ return (+ <div className="encryption-identity border-b border-solid border-b-border last:border-b-0 py-4 first:pt-1">+ <div className="flex items-center gap-3">+ <AccountMark account={account} size={30} />+ <div className="flex-1 min-w-0">+ <div className="text-[13px] font-medium text-strong [overflow-wrap:anywhere]">+ {identity.email}+ {showAccount && (+ <span className="font-normal text-[11px] text-muted ml-2">{account.name}</span>+ )}+ </div>+ <div className="text-[11px] mt-0.5">+ {!own ? (+ <span className="text-muted">+ {!unavailable+ ? 'Not set up'+ : target.loading+ ? 'Loading addresses…'+ : 'Connect this account to set up encryption'}+ </span>+ ) : broken ? (+ <span className="text-danger">+ {key.problem === 'revoked'+ ? 'Key revoked'+ : key.problem === 'expired'+ ? 'Key expired'+ : 'Key can’t be used'}+ {' · Replace it to encrypt again'}+ </span>+ ) : (+ <span className={own.enabled ? 'text-success' : 'text-muted'}>+ <span+ className={cn(+ 'inline-block w-1.25 h-1.25 rounded-full mr-1.5 align-[2px]',+ own.enabled ? 'bg-success' : 'bg-faint',+ )}+ />+ {own.enabled ? 'On' : 'Off'}+ <span className="text-muted">+ {' · Key '}+ <span className="font-mono">{shortFingerprint(own.fingerprint)}</span>+ </span>+ </span>+ )}+ </div>+ </div>+ {!own ? (+ <Button size="small" disabled={busy || unavailable} onClick={() => onDialog('setup')}>+ Set up…+ </Button>+ ) : (+ <div className="flex items-center gap-3">+ {broken ? (+ <Button size="small" disabled={busy} onClick={() => onDialog('replace')}>+ Replace key…+ </Button>+ ) : (+ <Switch+ aria-label={'Encrypt mail from ' + identity.email}+ checked={own.enabled}+ disabled={busy}+ onCheckedChange={(enabled) => onPreference(own, enabled, own.prefer)}+ />+ )}+ <Dropdown+ container={portalContainer}+ className="[&_.menu-item]:min-h-7.75 w-56"+ trigger={+ <Button+ size="small"+ className="data-popup-open:bg-hover data-popup-open:text-strong [&[data-popup-open]_svg]:transform-[rotate(180deg)]"+ aria-label={'Manage key for ' + identity.email}+ >+ Manage+ <ChevronDown size={13} />+ </Button>+ }+ >+ <MenuItem onClick={() => onKeyDialog('backup')} disabled={!key}>+ <Key size={14} />+ Back up key…+ </MenuItem>+ <MenuItem onClick={onExport}>+ <Share size={14} />+ Export public key…+ </MenuItem>+ <MenuItem+ onClick={() =>+ void navigator.clipboard+ .writeText(formatFingerprint(own.fingerprint))+ .then(() => notify('Fingerprint copied.'))+ }+ >+ <Copy size={14} />+ Copy fingerprint+ </MenuItem>+ <MenuItem onClick={() => onDialog('transfer')} disabled={broken}>+ <DeviceSync size={14} />+ Move to another device…+ </MenuItem>+ <MenuItem onClick={() => onDialog('older')}>+ <FileImport size={14} />+ Import an older key…+ </MenuItem>+ <div className="h-[1px] m-1.25 bg-border" />+ <MenuItem onClick={() => onDialog('replace')}>+ <RefreshCw size={14} />+ Replace key…+ </MenuItem>+ {key?.problem !== 'revoked' && (+ <MenuItem danger onClick={() => onKeyDialog('revoke')} disabled={!key}>+ <ShieldX size={14} />+ Revoke key…+ </MenuItem>+ )}+ </Dropdown>+ </div>+ )}+ </div>+ {own?.enabled && !broken && (+ <div className={cn(settingRow, 'mb-0 mt-3 pl-10.5')}>+ <div>+ <strong>Prefer encrypted mail</strong>+ <p>+ Let contacts know you’d like encrypted mail. New conversations are encrypted+ automatically when every recipient prefers it too.+ </p>+ </div>+ <Switch+ aria-label={'Prefer encrypted mail for ' + identity.email}+ checked={own.prefer}+ disabled={busy}+ onCheckedChange={(prefer) => onPreference(own, true, prefer)}+ />+ </div>+ )}+ {key?.backup && key.backup !== 'done' && (+ <Callout+ tone="warning"+ icon={AlertCircle}+ className="mt-3.5 ml-10.5"+ title={key.backup === 'postponed' ? 'Your key isn’t backed up' : 'Back up your key'}+ action={+ <>+ {key.backup === 'needed' && (+ <Button size="small" variant="ghost" onClick={() => onKeyDialog('postpone')}>+ Later+ </Button>+ )}+ <Button size="small" onClick={() => onKeyDialog('backup')}>+ Back up…+ </Button>+ </>+ }+ >+ <p>+ If this computer is lost, your encrypted mail is lost with it. Resetting your email+ password can’t bring it back.+ </p>+ </Callout>+ )}+ </div>+ )+}++/** Contacts’ keys found so far, filtered as you type, with a lookup for anyone else. */+function ContactKeys({+ keys,+ onOpen,+}: {+ keys: EncryptionKeySummary[]+ onOpen: (email: string) => void+}) {+ const [query, setQuery] = useState('')+ const [showAll, setShowAll] = useState(false)+ const contacts = new Map<string, EncryptionKeySummary[]>()+ for (const key of keys)+ if (!isOwn(key)) contacts.set(key.email, [...(contacts.get(key.email) || []), key])+ const text = query.trim().toLowerCase()+ const list = [...contacts.entries()]+ .filter(([email]) => !text || email.includes(text))+ .sort(([a], [b]) => a.localeCompare(b))+ const shown = showAll || text ? list : list.slice(0, 6)+ const lookup = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text) ? text : ''+ return (+ <div className={section}>+ <h4>Contacts’ keys</h4>+ <p className="mt-0 mb-3.5 text-[12px] leading-[1.6] text-muted">+ Found automatically, from your contacts’ mail providers and from mail they send you. Look+ someone up to check or verify their key.+ </p>+ <form+ className="contact-lookup flex gap-2"+ onSubmit={(e) => {+ e.preventDefault()+ if (lookup) onOpen(lookup)+ }}+ >+ <div className="relative flex-1">+ <Search+ size={14}+ className="absolute left-2.75 top-1/2 -translate-y-1/2 text-muted pointer-events-none"+ />+ <input+ className="h-8 py-0 pl-8 pr-2.5 text-[12px]"+ type="search"+ aria-label="Find or look up a contact’s key"+ placeholder="Find or look up an email address"+ value={query}+ spellCheck={false}+ onChange={(e) => setQuery(e.target.value)}+ />+ </div>+ <Button size="small" type="submit" className="shrink-0 h-8" disabled={!lookup}>+ Look up+ </Button>+ </form>+ {shown.length > 0 && (+ <div className="contact-keys mt-2">+ {shown.map(([email, list]) => {+ const current = list.find((k) => k.accepted && !k.retired)+ const active = list.filter((k) => !k.retired && k.usable)+ const changed = !!current && active.some((k) => k !== current)+ const conflict = !current && active.length > 1+ const shownKey = current || active[0] || list[0]+ return (+ <button+ key={email}+ type="button"+ className={cn(+ 'contact-key flex items-center gap-3 w-[calc(100%_+_16px)] py-2.5 px-2 -mx-2 rounded-md border-0',+ 'bg-transparent text-left transition-[background] duration-120 ease-[ease] hover:bg-hover',+ )}+ onClick={() => onOpen(email)}+ >+ <span className="flex-1 min-w-0">+ <span className="block text-[13px] [overflow-wrap:anywhere]">{email}</span>+ <span className="block text-[11px] text-muted mt-0.5 overflow-hidden text-ellipsis whitespace-nowrap">+ <span className="font-mono">{shortFingerprint(shownKey.fingerprint)}</span>+ {' · from '}+ {keySources(shownKey)}+ </span>+ </span>+ {changed ? (+ <KeyBadge tone="warning">Key changed</KeyBadge>+ ) : conflict ? (+ <KeyBadge tone="warning">Choose a key</KeyBadge>+ ) : !shownKey.usable ? (+ <KeyBadge tone="danger">Can’t be used</KeyBadge>+ ) : shownKey.confirmed ? (+ <KeyBadge tone="good" icon={BadgeCheck}>+ Verified+ </KeyBadge>+ ) : (+ <KeyBadge>Not verified</KeyBadge>+ )}+ <ChevronRight size={14} className="text-faint shrink-0" />+ </button>+ )+ })}+ </div>+ )}+ {!text && list.length > shown.length && (+ <Button+ size="small"+ variant="ghost"+ className="mt-1 -ml-2"+ onClick={() => setShowAll(true)}+ >+ Show all {list.length} contacts+ </Button>+ )}+ {text && !list.length && (+ <p className="mt-3 mb-0 text-[12px] text-muted">+ {lookup+ ? 'No saved key for this address yet. Look it up to search for one.'+ : 'No saved keys match.'}+ </p>+ )}+ </div>+ )+}++/** Choose a backup password, then where to save the file. */+function BackupForm({+ fingerprint,+ unlock,+ onSaved,+ secondary,+ lead = 'Save a password-protected copy of your private key. You’ll need it to read encrypted mail on a new computer, or if something happens to this one.',+}: {+ fingerprint: string+ unlock: () => Promise<boolean>+ onSaved: () => void+ secondary?: ReactNode+ lead?: ReactNode+}) {+ const [password, setPassword] = useState('')+ const [confirm, setConfirm] = useState('')+ const [submitted, setSubmitted] = useState(false)+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ return (+ <form+ onSubmit={async (e) => {+ e.preventDefault()+ setSubmitted(true)+ setError('')+ if (newPasswordProblem(password, confirm)) return+ setBusy(true)+ try {+ if (!(await unlock())) return+ await api.exportEncryptionKey(fingerprint, 'backup', password)+ const status = await api.encryptionStatus()+ keysChanged(status)+ // The save dialog can be cancelled, which leaves the key without a backup.+ if (status.keys.some((k) => k.fingerprint === fingerprint && k.backup === 'done'))+ onSaved()+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setBusy(false)+ }+ }}+ >+ <p className={dialogLead}>{lead}</p>+ <NewPasswordFields+ label="Backup password"+ password={password}+ confirm={confirm}+ autoFocus+ showProblems={submitted}+ hint={backupHint}+ onChange={(p, c) => {+ setPassword(p)+ setConfirm(c)+ }}+ />+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ {secondary}+ <Button type="submit" variant="primary" disabled={busy}>+ {busy && <Spinner size={14} />}+ Save backup…+ </Button>+ </div>+ </form>+ )+}++/** Postponing a backup is allowed, but only after saying plainly what's at stake. */+function PostponeForm({+ fingerprint,+ onBackUp,+ onDone,+}: {+ fingerprint: string+ onBackUp: () => void+ onDone: () => void+}) {+ const [understood, setUnderstood] = useState(false)+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ return (+ <>+ <Callout tone="warning" icon={AlertCircle} title="A lost key can’t be recovered">+ <p>+ If this computer is lost or damaged, or you forget your vault password, you won’t be able+ to read your encrypted mail again. Resetting your email password doesn’t help.+ </p>+ </Callout>+ <label className="checkbox-label flex items-center gap-2.25 text-[12px] mt-4.5">+ <Checkbox checked={understood} onCheckedChange={setUnderstood} />I understand I could lose+ access to my encrypted mail+ </label>+ <p className="mt-1.5 mb-0 ml-6 text-[11px] text-muted">+ A reminder stays in Settings until you back up.+ </p>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button+ variant="danger"+ className="modal-action-start ml-0"+ disabled={!understood || busy}+ onClick={async () => {+ setBusy(true)+ try {+ keysChanged(await api.postponeEncryptionBackup(fingerprint))+ onDone()+ } catch (e) {+ setError(friendlyError(e))+ setBusy(false)+ }+ }}+ >+ Back up later+ </Button>+ <Button variant="primary" onClick={onBackUp}>+ Back up now+ </Button>+ </div>+ </>+ )+}++/** A choice shown as a card; native radios keep arrow-key navigation. */+function Choice({+ name,+ checked,+ onSelect,+ icon,+ title,+ children,+}: {+ name: string+ checked: boolean+ onSelect: () => void+ icon: typeof Key+ title: string+ children: ReactNode+}) {+ return (+ <label+ className={cn(+ 'choice flex gap-3.5 items-center py-3 px-3.5 rounded-lg border border-solid cursor-pointer',+ 'transition-[background,border-color] duration-120 ease-[ease] [&+.choice]:mt-2',+ 'has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-primary',+ 'has-[:focus-visible]:outline-offset-2',+ checked+ ? 'border-primary-solid/70 bg-primary-tint'+ : 'border-border-strong hover:bg-hover hover:border-foreground/20',+ )}+ >+ <input type="radio" className="sr-only" name={name} checked={checked} onChange={onSelect} />+ <StateIcon icon={icon} tone={checked ? 'accent' : 'neutral'} size={34} />+ <span className="flex-1 min-w-0">+ <span className="block text-[13px] font-medium text-strong">{title}</span>+ <span className="block text-[12px] leading-[1.5] text-muted mt-0.5">{children}</span>+ </span>+ <span+ className={cn(+ 'w-3.75 h-3.75 shrink-0 rounded-full transition-[box-shadow] duration-120',+ checked+ ? 'shadow-[inset_0_0_0_4.5px_var(--accent-solid)]'+ : 'shadow-[inset_0_0_0_1px_var(--faint)]',+ )}+ aria-hidden="true"+ />+ </label>+ )+}++const formatCode = (digits: string) => digits.match(/.{1,4}/g)?.join('-') || ''+const transferError = (error: unknown) =>+ /decrypt|session key|passphrase/i.test(friendlyError(error))+ ? 'That setup code didn’t open the Setup Message. Check the code and try again.'+ : friendlyError(error)++type SetupStep =+ | 'choose'+ | 'vault'+ | 'creating'+ | 'existing'+ | 'replace'+ | 'import'+ | 'transfer'+ | 'backup'+ | 'postpone'++/**+ * Guides one address from nothing to a working, backed-up key: choose how, protect the vault+ * if the system keyring can't, then save a backup straight away.+ */+function SetupDialog({+ target,+ secureStorage,+ unlock,+ notify,+ onClose,+}: {+ target: Target+ secureStorage: boolean+ unlock: () => Promise<boolean>+ notify: Notify+ onClose: () => void+}) {+ const { identity } = target+ const status = useEncryption()+ const [step, setStep] = useState<SetupStep>('choose')+ const [method, setMethod] = useState<'create' | 'import' | 'transfer'>('create')+ const [vaultPassword, setVaultPassword] = useState('')+ const [vaultConfirm, setVaultConfirm] = useState('')+ const [submitted, setSubmitted] = useState(false)+ const [keyPassword, setKeyPassword] = useState('')+ const [code, setCode] = useState('')+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ const found = (status.data?.keys || []).filter(+ (k) => k.email.toLowerCase() === identity.email.toLowerCase(),+ )+ const needsVaultPassword = status.data?.vault === 'absent' && !secureStorage+ const own = status.data?.identities.find(ownedBy(identity))+ const ids = { accountId: identity.accountId, identityId: identity.id }+ const password = vaultPassword || undefined+ /** Whether this address has a key now; file pickers can be cancelled without an error. */+ const installed = async () => {+ const next = await api.encryptionStatus()+ keysChanged(next)+ return next.identities.some(ownedBy(identity))+ }+ const go = (to: SetupStep) => {+ setError('')+ setStep(to)+ }+ const create = async (replace = false) => {+ setError('')+ if (!replace && found.length) return setStep('existing')+ setStep('creating')+ try {+ keysChanged(+ await api.setupEncryption({ ...ids, action: replace ? 'replace' : 'create', password }),+ )+ setStep('backup')+ } catch (e) {+ if (!replace && /existing key|already exists/i.test(friendlyError(e))) {+ await status.refetch()+ setStep('existing')+ } else {+ setError(friendlyError(e))+ setStep(replace ? 'replace' : 'choose')+ }+ }+ }+ const next = () => (method === 'create' ? void create() : go(method))+ const start = async () => {+ setError('')+ if (status.data?.vault === 'locked' && !(await unlock())) return+ if (needsVaultPassword) go('vault')+ else next()+ }+ const importKey = async () => {+ setBusy(true)+ setError('')+ try {+ await api.setupEncryption({+ ...ids,+ action: 'import',+ password,+ keyPassword: keyPassword || undefined,+ })+ if (await installed()) setStep('backup')+ } catch (e) {+ setError(keyFileError(e, keyPassword))+ } finally {+ setBusy(false)+ }+ }+ const transfer = async () => {+ const digits = code.replace(/\D/g, '')+ if (digits.length !== 36) {+ setError('Enter all 36 digits of the setup code.')+ return+ }+ setBusy(true)+ setError('')+ try {+ await api.transferEncryption({ ...ids, action: 'import', code: formatCode(digits), password })+ if (await installed()) setStep('backup')+ } catch (e) {+ setError(transferError(e))+ } finally {+ setBusy(false)+ }+ }+ const finish = (message: string) => {+ notify(message)+ onClose()+ }+ const back = (to: SetupStep) => (+ <Button className="modal-action-start" variant="ghost" disabled={busy} onClick={() => go(to)}>+ Back+ </Button>+ )+ const titles: Record<SetupStep, string> = {+ choose: 'Set up encryption',+ vault: 'Choose a vault password',+ creating: 'Creating your key…',+ existing: 'This address already has a key',+ replace: 'Create a new key instead?',+ import: 'Import your key',+ transfer: 'Transfer from another device',+ backup: 'Your key is ready',+ postpone: 'Back up later?',+ }+ const firstFound = found.find(isOwn) || found[0]+ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open && !busy && step !== 'creating') onClose()+ }}+ title={titles[step]}+ description={+ ['choose', 'import', 'transfer'].includes(step) ? 'For ' + identity.email : undefined+ }+ className={dialogWidth}+ >+ {step === 'choose' && (+ <form+ onSubmit={(e) => {+ e.preventDefault()+ void start()+ }}+ >+ <Choice+ name="setup-method"+ icon={Key}+ title="Create a new key"+ checked={method === 'create'}+ onSelect={() => setMethod('create')}+ >+ Start here if you haven’t used encrypted mail with this address before.+ </Choice>+ <Choice+ name="setup-method"+ icon={FileImport}+ title="Import an existing key"+ checked={method === 'import'}+ onSelect={() => setMethod('import')}+ >+ Use a key file or backup from Thunderbird, GnuPG or another app.+ </Choice>+ <Choice+ name="setup-method"+ icon={DeviceSync}+ title="Transfer from another device"+ checked={method === 'transfer'}+ onSelect={() => setMethod('transfer')}+ >+ Use a Setup Message and the code shown on your other device.+ </Choice>+ <div+ className={cn(+ 'key-explainer grid grid-cols-2 gap-4 mt-5 py-3.5 px-4 rounded-lg text-[11px] leading-[1.55] text-muted',+ 'bg-[color-mix(in_srgb,_var(--hover)_55%,_transparent)] [&_strong]:block [&_strong]:text-[12px]',+ '[&_strong]:font-medium [&_strong]:text-secondary [&_strong]:mb-0.5',+ )}+ >+ <span>+ <strong>Public key</strong>+ Shared with your contacts automatically, so they can encrypt mail to you.+ </span>+ <span>+ <strong>Private key</strong>+ Opens your encrypted mail. It stays on this device,{' '}+ {secureStorage ? 'protected by your system keyring' : 'protected by a password'}.+ </span>+ </div>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button onClick={onClose}>Cancel</Button>+ <Button type="submit" variant="primary">+ Continue+ </Button>+ </div>+ </form>+ )}+ {step === 'vault' && (+ <form+ onSubmit={(e) => {+ e.preventDefault()+ setSubmitted(true)+ if (!newPasswordProblem(vaultPassword, vaultConfirm)) next()+ }}+ >+ <p className={dialogLead}>+ Your system keyring isn’t available, so Inlark protects your keys with a password of+ their own. You’ll enter it whenever you unlock them.+ </p>+ <NewPasswordFields+ label="Vault password"+ password={vaultPassword}+ confirm={vaultConfirm}+ autoFocus+ showProblems={submitted}+ hint="At least 10 characters. If you forget it, only a key backup can restore access."+ onChange={(p, c) => {+ setVaultPassword(p)+ setVaultConfirm(c)+ }}+ />+ <div className={modalActions}>+ {back('choose')}+ <Button type="submit" variant="primary">+ Continue+ </Button>+ </div>+ </form>+ )}+ {step === 'creating' && (+ <div className="flex flex-col items-center text-center pt-3 pb-5 gap-3" role="status">+ <Spinner size={20} />+ <p className="m-0 text-[12px] text-muted">+ Checking that this address has no key yet, then creating yours.+ </p>+ </div>+ )}+ {step === 'existing' && (+ <>+ <p className={dialogLead}>+ {firstFound && isOwn(firstFound)+ ? 'A key for ' + identity.email + ' is already on this device.'+ : 'A key for ' ++ identity.email ++ ' was found in ' ++ (firstFound ? keySources(firstFound) : 'a key directory') ++ '.'}{' '}+ To keep reading mail encrypted to it, import its private key, for example from a backup+ or the app you created it in.+ </p>+ {firstFound && <FingerprintBlock value={firstFound.fingerprint} />}+ <div className={modalActions}>+ <Button className="modal-action-start" variant="ghost" onClick={() => go('replace')}>+ Create a new key instead+ </Button>+ <Button+ variant="primary"+ onClick={() => {+ setMethod('import')+ go('import')+ }}+ >+ Import existing key+ </Button>+ </div>+ </>+ )}+ {step === 'replace' && (+ <>+ <Callout tone="warning" icon={AlertCircle}>+ <p>+ Contacts who have your current key will see a new one and may need to review it. Mail+ encrypted to the old key can’t be read here unless you import that key later.+ </p>+ </Callout>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ {back('existing')}+ <Button variant="primary" onClick={() => void create(true)}>+ Create new key+ </Button>+ </div>+ </>+ )}+ {step === 'import' && (+ <form+ onSubmit={(e) => {+ e.preventDefault()+ void importKey()+ }}+ >+ <p className={dialogLead}>+ Choose a file containing your private key, such as an exported <code>.asc</code> file or+ a backup. A public key alone isn’t enough.+ </p>+ <PasswordField+ label="Key file password"+ value={keyPassword}+ autoFocus+ onChange={(value) => {+ setKeyPassword(value)+ setError('')+ }}+ hint="The password you chose when exporting the key. Leave empty if it has none."+ />+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ {back('choose')}+ <Button type="submit" variant="primary" disabled={busy}>+ {busy ? <Spinner size={14} /> : <FileImport size={14} />}+ Choose key file…+ </Button>+ </div>+ </form>+ )}+ {step === 'transfer' && (+ <form+ onSubmit={(e) => {+ e.preventDefault()+ void transfer()+ }}+ >+ <p className={dialogLead}>+ On your other device, choose to move your key. Then pick the Setup Message file it saves+ and enter the code it shows.+ </p>+ <label className="form-field block [&_input]:mt-1.5">+ Setup code+ <input+ autoFocus+ inputMode="numeric"+ autoComplete="off"+ spellCheck={false}+ className="font-mono text-[13px] tracking-[0.5px]"+ placeholder="1234-5678-…"+ value={code}+ aria-invalid={!!error || undefined}+ onChange={(e) => {+ setCode(formatCode(e.target.value.replace(/\D/g, '').slice(0, 36)))+ setError('')+ }}+ />+ <span className="field-hint text-muted text-[11px] block mt-1.25">+ 36 digits. Dashes are added for you.+ </span>+ </label>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ {back('choose')}+ <Button type="submit" variant="primary" disabled={busy}>+ {busy ? <Spinner size={14} /> : <DeviceSync size={14} />}+ Choose Setup Message…+ </Button>+ </div>+ </form>+ )}+ {step === 'backup' && own && (+ <>+ <Callout tone="success" icon={Check} className="mb-5">+ <p>+ Encryption is on for {identity.email}. Your key is{' '}+ <span className="font-mono text-foreground">{shortFingerprint(own.fingerprint)}</span>+ .+ </p>+ </Callout>+ <h4 className="mt-0 mb-1.5 text-[13px] font-medium text-strong">+ Next, back up your key+ </h4>+ <BackupForm+ fingerprint={own.fingerprint}+ unlock={unlock}+ lead={+ method === 'create'+ ? 'Without a backup, losing this computer means losing your encrypted mail. Resetting your email password can’t bring it back.'+ : 'If your original key file isn’t stored safely, save a backup now.'+ }+ onSaved={() => finish('Encryption is ready, and your key is backed up.')}+ secondary={+ <Button className="modal-action-start" variant="ghost" onClick={() => go('postpone')}>+ Back up later+ </Button>+ }+ />+ </>+ )}+ {step === 'postpone' && own && (+ <PostponeForm+ fingerprint={own.fingerprint}+ onBackUp={() => go('backup')}+ onDone={() => finish('Encryption is ready. Remember to back up your key.')}+ />+ )}+ </Modal>+ )+}++/** Exports an Autocrypt Setup Message and shows the code that opens it. */+function TransferDialog({+ target,+ unlock,+ onClose,+}: {+ target: Target+ unlock: () => Promise<boolean>+ onClose: () => void+}) {+ const [code, setCode] = useState('')+ const [copied, setCopied] = useState(false)+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ return (+ <Modal+ open+ onOpenChange={(open) => !open && !busy && onClose()}+ title={code ? 'Enter this code on your other device' : 'Move your key to another device'}+ className={dialogWidth}+ >+ {!code ? (+ <>+ <p className={dialogLead}>+ Inlark saves a Setup Message: an encrypted file containing your key for{' '}+ {target.identity.email}. Copy it to your other device, open it in Inlark or another app+ that supports Autocrypt, and enter the code shown next.+ </p>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ <Button+ variant="primary"+ disabled={busy}+ onClick={async () => {+ setBusy(true)+ setError('')+ try {+ if (!(await unlock())) return+ const result = await api.transferEncryption({+ accountId: target.identity.accountId,+ identityId: target.identity.id,+ action: 'export',+ })+ if (result.code) setCode(result.code)+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setBusy(false)+ }+ }}+ >+ {busy && <Spinner size={14} />}+ Save Setup Message…+ </Button>+ </div>+ </>+ ) : (+ <>+ <div+ className={cn(+ 'setup-code grid grid-cols-3 gap-x-4 gap-y-2 py-4.5 px-5 rounded-lg bg-field border border-solid',+ 'border-border font-mono text-[17px] tracking-[1px] text-strong text-center select-text tabular-nums',+ )}+ aria-label={'Setup code ' + code.replace(/-/g, ' ')}+ >+ {code.split('-').map((group, index) => (+ <span key={index}>{group}</span>+ ))}+ </div>+ <Callout tone="warning" icon={AlertCircle} className="mt-4">+ <p>+ Don’t send this code by email. Anyone with both the file and the code can use your+ key. It won’t be shown again.+ </p>+ </Callout>+ <div className={modalActions}>+ <Button+ className="modal-action-start"+ variant="ghost"+ onClick={() => void navigator.clipboard.writeText(code).then(() => setCopied(true))}+ >+ {copied ? <Check size={14} /> : <Copy size={14} />}+ {copied ? 'Copied' : 'Copy code'}+ </Button>+ <Button variant="primary" onClick={onClose}>+ Done+ </Button>+ </div>+ </>+ )}+ </Modal>+ )+}++/** Swaps the key for an address. The old one stays, so older mail remains readable. */+function ReplaceDialog({+ target,+ unlock,+ onClose,+ onReplaced,+}: {+ target: Target+ unlock: () => Promise<boolean>+ onClose: () => void+ onReplaced: (key?: EncryptionKeySummary) => void+}) {+ const [method, setMethod] = useState<'create' | 'import'>('create')+ const [keyPassword, setKeyPassword] = useState('')+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ const { identity, own } = target+ return (+ <Modal+ open+ onOpenChange={(open) => !open && !busy && onClose()}+ title="Replace your key?"+ description={'For ' + identity.email}+ className={dialogWidth}+ >+ <form+ onSubmit={async (e) => {+ e.preventDefault()+ setBusy(true)+ setError('')+ try {+ if (!(await unlock())) return+ const next = await api.setupEncryption({+ accountId: identity.accountId,+ identityId: identity.id,+ action: 'replace',+ importReplacement: method === 'import',+ keyPassword: keyPassword || undefined,+ })+ keysChanged(next)+ const mine = next.identities.find(ownedBy(identity))+ // An unchanged fingerprint means the file picker was cancelled.+ if (mine && mine.fingerprint !== own?.fingerprint)+ onReplaced(+ next.keys.find((k) => k.fingerprint === mine.fingerprint && k.email === mine.email),+ )+ } catch (e) {+ setError(method === 'import' ? keyFileError(e, keyPassword) : friendlyError(e))+ } finally {+ setBusy(false)+ }+ }}+ >+ <p className={dialogLead}>+ Contacts will see a new key for this address and may need to review it. Your current key+ is kept, so you can still read mail encrypted to it.+ </p>+ <Choice+ name="replace-method"+ icon={Key}+ title="Create a new key"+ checked={method === 'create'}+ onSelect={() => setMethod('create')}+ >+ Generate a fresh key on this device.+ </Choice>+ <Choice+ name="replace-method"+ icon={FileImport}+ title="Import a key file"+ checked={method === 'import'}+ onSelect={() => setMethod('import')}+ >+ Use a private key you already have.+ </Choice>+ {method === 'import' && (+ <div className="mt-4">+ <PasswordField+ label="Key file password"+ value={keyPassword}+ onChange={setKeyPassword}+ hint="Leave empty if the file has none."+ />+ </div>+ )}+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ <Button type="submit" variant="primary" disabled={busy}>+ {busy && <Spinner size={14} />}+ {method === 'import' ? 'Choose key file…' : 'Replace key'}+ </Button>+ </div>+ </form>+ </Modal>+ )+}++/** Revokes a key, then offers the revoked key to share so contacts stop using it. */+function RevokeDialog({+ keySummary,+ unlock,+ onClose,+}: {+ keySummary: EncryptionKeySummary+ unlock: () => Promise<boolean>+ onClose: () => void+}) {+ const [revoked, setRevoked] = useState(false)+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ return (+ <Modal+ open+ onOpenChange={(open) => !open && !busy && onClose()}+ title={revoked ? 'Key revoked' : 'Revoke this key?'}+ description={'Key ' + shortFingerprint(keySummary.fingerprint) + ' · ' + keySummary.email}+ className={dialogWidth}+ >+ {!revoked ? (+ <>+ <p className={dialogLead}>+ Revoke a key if it may have been copied, or if you’ll never use it again. Contacts who+ receive the revocation stop encrypting to it. You can still read mail already encrypted+ to it. Encryption stays off for this address until you set up a new key.+ </p>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button onClick={onClose} disabled={busy}>+ Keep key+ </Button>+ <Button+ variant="danger"+ disabled={busy}+ onClick={async () => {+ setBusy(true)+ setError('')+ try {+ if (!(await unlock())) return+ keysChanged(await api.revokeEncryptionKey(keySummary.fingerprint))+ setRevoked(true)+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setBusy(false)+ }+ }}+ >+ {busy && <Spinner size={14} />}+ Revoke key+ </Button>+ </div>+ </>+ ) : (+ <>+ <p className={dialogLead}>+ Share the revoked public key with your contacts, and with whoever runs your domain’s key+ directory, so they know to stop using it.+ </p>+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button+ className="modal-action-start"+ variant="ghost"+ onClick={() =>+ void api+ .exportEncryptionKey(keySummary.fingerprint, 'public')+ .catch((e) => setError(friendlyError(e)))+ }+ >+ <Share size={14} />+ Export revoked key…+ </Button>+ <Button variant="primary" onClick={onClose}>+ Done+ </Button>+ </div>+ </>+ )}+ </Modal>+ )+}++/** Adds a key used in the past, only to read older mail. */+function OlderKeyDialog({+ target,+ unlock,+ notify,+ onClose,+}: {+ target: Target+ unlock: () => Promise<boolean>+ notify: Notify+ onClose: () => void+}) {+ const [keyPassword, setKeyPassword] = useState('')+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ return (+ <Modal+ open+ onOpenChange={(open) => !open && !busy && onClose()}+ title="Import an older key"+ description={'For ' + target.identity.email}+ className={dialogWidth}+ >+ <form+ onSubmit={async (e) => {+ e.preventDefault()+ setBusy(true)+ setError('')+ try {+ if (!(await unlock())) return+ const before = await api.encryptionStatus()+ const next = await api.setupEncryption({+ accountId: target.identity.accountId,+ identityId: target.identity.id,+ action: 'historical',+ keyPassword: keyPassword || undefined,+ })+ keysChanged(next)+ // An unchanged list of private keys means the file picker was cancelled.+ if (next.keys.filter(isOwn).length !== before.keys.filter(isOwn).length) {+ notify('Older key imported. Mail encrypted to it can be read again.')+ onClose()+ }+ } catch (e) {+ setError(keyFileError(e, keyPassword))+ } finally {+ setBusy(false)+ }+ }}+ >+ <p className={dialogLead}>+ Import a private key you used before, so Inlark can open older mail encrypted to it. It+ won’t be used for new mail.+ </p>+ <PasswordField+ label="Key file password"+ value={keyPassword}+ autoFocus+ onChange={setKeyPassword}+ hint="Leave empty if the file has none."+ />+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ <Button type="submit" variant="primary" disabled={busy}>+ {busy ? <Spinner size={14} /> : <FileImport size={14} />}+ Choose key file…+ </Button>+ </div>+ </form>+ </Modal>+ )+}diff --git a/apps/desktop/src/renderer/src/MessageSecurity.tsx b/apps/desktop/src/renderer/src/MessageSecurity.tsxnew file mode 100644index 0000000..8e038ae--- /dev/null+++ b/apps/desktop/src/renderer/src/MessageSecurity.tsx@@ -0,0 +1,290 @@+import { cn } from '@inlark/ui'+import { useState, type ReactNode } from 'react'+import { useQueryClient } from '@tanstack/react-query'+import {+ BadgeCheck,+ ChevronDown,+ Key,+ Lock,+ LockKeyhole,+ ShieldCheck,+ ShieldX,+ Signature,+ type IconComponent,+} from '@inlark/ui/icons'+import { Button, Spinner } from '@inlark/ui'+import { friendlyError, type MailSecurity, type Message } from '@inlark/core'+import { api } from './api'+import { Callout, FingerprintBlock, StateIcon, useEncryption } from './encryption-ui'++/** Whether a message's content was withheld, and so the body can't be shown at all. */+export const withheld = (security?: MailSecurity) =>+ !!security && ['locked', 'missingKey', 'integrityFailure'].includes(security.state)++function Pill({+ tone,+ icon: Icon,+ children,+}: {+ tone: 'accent' | 'good' | 'neutral' | 'danger'+ icon?: IconComponent+ children: ReactNode+}) {+ return (+ <span+ className={cn(+ 'security-pill inline-flex items-center gap-1 h-5.5 px-2 rounded-md text-[11px] font-medium whitespace-nowrap',+ tone === 'accent' && 'bg-primary-tint text-primary',+ tone === 'good' && 'bg-success/10 text-success',+ tone === 'neutral' && 'bg-hover text-muted',+ tone === 'danger' && 'bg-danger/10 text-danger',+ )}+ >+ {Icon && <Icon size={12} />}+ {children}+ </span>+ )+}++function Detail({+ icon,+ tone,+ title,+ children,+}: {+ icon: IconComponent+ tone: 'accent' | 'good' | 'neutral' | 'danger'+ title: string+ children: ReactNode+}) {+ return (+ <div className="security-detail flex gap-3 [&+.security-detail]:mt-3.5">+ <StateIcon icon={icon} tone={tone} size={28} />+ <div className="flex-1 min-w-0 text-[12px] leading-[1.6] text-muted [&_strong]:block [&_strong]:text-foreground [&_strong]:font-medium">+ <strong>{title}</strong>+ {children}+ </div>+ </div>+ )+}++/**+ * How a readable message was protected: encryption, signature, and whether the sender's key was+ * verified are separate things, so each is named on its own. Details explain what each means.+ */+export function SecuritySummary({ message }: { message: Message }) {+ const security = message.security!+ const [open, setOpen] = useState(false)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState('')+ const client = useQueryClient()+ const sender = message.from[0]+ const senderName = sender?.name || sender?.email || 'the sender'+ const signed = security.signature === 'valid'+ const verify = async () => {+ if (!sender || !security.fingerprint) return+ setBusy(true)+ setError('')+ try {+ client.setQueryData(+ ['encryption'],+ await api.acceptEncryptionKey(sender.email, security.fingerprint, true),+ )+ await Promise.all([+ client.invalidateQueries({ queryKey: ['thread'] }),+ client.invalidateQueries({ queryKey: ['contact-keys'] }),+ client.invalidateQueries({ queryKey: ['recipient-encryption'] }),+ ])+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setBusy(false)+ }+ }+ return (+ <div className="message-security mb-4.5">+ {security.signature === 'invalid' && (+ <Callout tone="danger" icon={ShieldX} title="This signature doesn’t match" className="mb-3">+ <p>+ The message may have been changed after it was sent, or it wasn’t signed by {senderName}+ . Be careful with its links, attachments and requests.+ </p>+ </Callout>+ )}+ <button+ type="button"+ className={cn(+ 'security-summary inline-flex items-center gap-1.5 flex-wrap py-1 pr-1.5 pl-1 -ml-1 rounded-lg border-0',+ 'bg-transparent text-left transition-[background] duration-120 ease-[ease] hover:bg-hover',+ )}+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ >+ {security.encrypted && (+ <Pill tone="accent" icon={Lock}>+ Encrypted+ </Pill>+ )}+ {security.signature === 'valid' ? (+ <Pill tone="good" icon={ShieldCheck}>+ Signed+ </Pill>+ ) : security.signature === 'invalid' ? (+ <Pill tone="danger" icon={ShieldX}>+ Signature invalid+ </Pill>+ ) : security.signature === 'unknown' ? (+ <Pill tone="neutral" icon={Signature}>+ Signature not checked+ </Pill>+ ) : (+ <Pill tone="neutral">Not signed</Pill>+ )}+ {signed &&+ (security.confirmed ? (+ <Pill tone="good" icon={BadgeCheck}>+ Verified sender+ </Pill>+ ) : (+ <span className="text-[11px] text-muted px-1">Sender not verified</span>+ ))}+ <ChevronDown+ size={13}+ className={cn(+ 'text-muted transition-[transform] duration-140 ease-[ease]',+ open && 'transform-[rotate(180deg)]',+ )}+ />+ </button>+ {open && (+ <div className="security-details mt-2.5 py-4 px-4.5 rounded-xl border border-solid border-border-strong bg-surface">+ {security.encrypted && (+ <Detail icon={Lock} tone="accent" title="Encrypted">+ Only you and the other recipients could read this message and its attachments. Its+ subject, addresses and date weren’t encrypted.+ </Detail>+ )}+ {security.signature === 'valid' ? (+ <Detail icon={ShieldCheck} tone="good" title="Signed">+ It hasn’t changed since it was signed with the key below.+ </Detail>+ ) : security.signature === 'invalid' ? (+ <Detail icon={ShieldX} tone="danger" title="Signature invalid">+ The signature doesn’t match the content or the sender’s key.+ </Detail>+ ) : security.signature === 'unknown' ? (+ <Detail icon={Signature} tone="neutral" title="Signature not checked">+ The sender’s key isn’t available here, so the signature couldn’t be checked.+ </Detail>+ ) : (+ <Detail icon={Signature} tone="neutral" title="Not signed">+ Nothing proves who sent it.{' '}+ {security.encrypted && 'Encryption alone doesn’t confirm the sender.'}+ </Detail>+ )}+ {signed && (+ <Detail+ icon={BadgeCheck}+ tone={security.confirmed ? 'good' : 'neutral'}+ title={security.confirmed ? 'Verified sender' : 'Sender not verified'}+ >+ {security.confirmed+ ? 'You confirmed that this key belongs to ' + senderName + '.'+ : 'A valid signature shows which key signed it, not who owns that key. To be sure it’s ' ++ senderName ++ ', compare this fingerprint with them in person or on a call.'}+ {security.fingerprint && (+ <FingerprintBlock value={security.fingerprint} className="mt-2.5" />+ )}+ {!security.confirmed && security.fingerprint && (+ <Button+ size="small"+ className="mt-2.5"+ disabled={busy}+ onClick={() => void verify()}+ >+ {busy ? <Spinner size={12} /> : <BadgeCheck size={13} />}+ It matches, mark as verified+ </Button>+ )}+ {error && <span className="block mt-2 text-[11px] text-danger">{error}</span>}+ </Detail>+ )}+ </div>+ )}+ </div>+ )+}++/** Stands in for a body that can't be shown, saying why and what would open it. */+export function WithheldBody({+ security,+ onUnlock,+ onOpenEncryption,+}: {+ security: MailSecurity+ onUnlock?: () => void+ onOpenEncryption?: () => void+}) {+ const status = useEncryption()+ const unset = status.data?.vault === 'absent'+ const content =+ security.state === 'integrityFailure'+ ? {+ icon: ShieldX,+ tone: 'danger' as const,+ title: 'This message may have been tampered with',+ text: 'Inlark couldn’t confirm it arrived intact, so its content and attachments are hidden.',+ }+ : security.state === 'missingKey'+ ? {+ icon: Key,+ tone: 'neutral' as const,+ title: 'No key here can open this message',+ text: 'It was encrypted to a key that isn’t on this device. Import that private key, including older ones, to read it.',+ action: onOpenEncryption && (+ <Button onClick={onOpenEncryption}>Encryption settings…</Button>+ ),+ }+ : unset+ ? {+ icon: LockKeyhole,+ tone: 'accent' as const,+ title: 'This message is encrypted',+ text: 'Set up encryption with the key it was sent to, then you can read it here.',+ action: onOpenEncryption && (+ <Button variant="primary" onClick={onOpenEncryption}>+ Set up encryption…+ </Button>+ ),+ }+ : {+ icon: LockKeyhole,+ tone: 'accent' as const,+ title: 'This message is encrypted',+ text: 'Unlock your keys to read it.',+ action: onUnlock && (+ <Button variant="primary" onClick={onUnlock}>+ Unlock+ </Button>+ ),+ }+ return (+ <div+ className={cn(+ 'withheld-body flex flex-col items-center text-center py-9 px-6 rounded-xl border border-dashed',+ content.tone === 'danger' ? 'border-danger/35' : 'border-border-strong',+ )}+ role="status"+ >+ <StateIcon icon={content.icon} tone={content.tone} size={44} />+ <h3 className="mt-3.5 mb-1 text-[14px] font-[550] text-strong tracking-[-0.2px]">+ {content.title}+ </h3>+ <p className="m-0 max-w-90 text-[12px] leading-[1.6] text-muted text-balance">+ {content.text}+ </p>+ {'action' in content && content.action && <div className="mt-4.5">{content.action}</div>}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/Reader.tsx b/apps/desktop/src/renderer/src/Reader.tsxindex 9506245..14d8dca 100644--- a/apps/desktop/src/renderer/src/Reader.tsx+++ b/apps/desktop/src/renderer/src/Reader.tsx@@ -29,6 +29,7 @@ import {Check,MailMinus,PencilEdit,+ Lock,} from '@inlark/ui/icons'import { Tooltip } from '@base-ui/react/tooltip'import { Button, IconButton, Dropdown, MenuItem, Spinner } from '@inlark/ui'@@ -51,6 +52,7 @@ import { actionLimit } from './account-limits'import { ShortcutHint, useShortcutText } from './shortcuts'import { emailSanitizeOptions } from './email-html'import { offersAction } from './view-actions'+import { SecuritySummary, WithheldBody, withheld } from './MessageSecurity'const formatAddress = (a: { name: string; email: string }) =>a.name ? a.name + ' <' + a.email + '>' : a.email@@ -137,6 +139,8 @@ export function EmailBody({loading = false,onLinkHover,onMailto,+ onUnlock,+ onOpenEncryption,}: {message: MessageremoteImages: boolean@@ -144,6 +148,9 @@ export function EmailBody({loading?: booleanonLinkHover?: (href: string | null) => voidonMailto?: (url: string) => void+ /** Unlocks encryption keys, so an encrypted message can be read. */+ onUnlock?: () => void+ onOpenEncryption?: () => void}) {const frame = useRef<HTMLIFrameElement>(null)const observer = useRef<ResizeObserver | null>(null)@@ -152,6 +159,10 @@ export function EmailBody({const [source, setSource] = useState('')const [adaptive, setAdaptive] = useState(false)const adaptiveFrame = useRef(false)+ const [remoteConsentMessage, setRemoteConsentMessage] = useState<string | null>(null)+ const consentScope = JSON.stringify([message.accountId, message.id])+ const permitDecryptedRemote = remoteConsentMessage === consentScope+ const effectiveRemoteImages = message.security?.encrypted ? permitDecryptedRemote : remoteImagesconst [blocked, setBlocked] = useState(false)const [frameReady, setFrameReady] = useState(false)const [renderIssue, setRenderIssue] = useState<string | null>(null)@@ -162,43 +173,49 @@ export function EmailBody({const mailto = useRef(onMailto)mailto.current = onMailtoconst describeIssue = (stage: string, error: string, currentSource = source) =>- JSON.stringify(- {- stage,- error,- htmlChars: message.html?.length ?? 0,- textChars: message.text?.length ?? 0,- sourceChars: currentSource.length,- sourceWritten: writtenSource.current === currentSource,- frame: (() => {- try {- const doc = frame.current?.contentDocument- return {- present: !!frame.current,- documentAccessible: !!doc,- documentKind: doc?.URL.startsWith('blob:')- ? 'blob'- : doc?.URL.startsWith('about:')- ? doc.URL- : doc- ? 'other'- : null,- readyState: doc?.readyState ?? null,- bodyPresent: !!doc?.body,- bodyTextChars: doc?.body?.textContent?.length ?? null,- bodyHtmlChars: doc?.body?.innerHTML.length ?? null,- }- } catch (cause) {- return {- inspectionError:- cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause),- }- }- })(),- },- null,- 2,- )+ message.security?.encrypted+ ? JSON.stringify({+ stage,+ encrypted: true,+ error: 'Encrypted message rendering failed. Content is excluded from diagnostics.',+ })+ : JSON.stringify(+ {+ stage,+ error,+ htmlChars: message.html?.length ?? 0,+ textChars: message.text?.length ?? 0,+ sourceChars: currentSource.length,+ sourceWritten: writtenSource.current === currentSource,+ frame: (() => {+ try {+ const doc = frame.current?.contentDocument+ return {+ present: !!frame.current,+ documentAccessible: !!doc,+ documentKind: doc?.URL.startsWith('blob:')+ ? 'blob'+ : doc?.URL.startsWith('about:')+ ? doc.URL+ : doc+ ? 'other'+ : null,+ readyState: doc?.readyState ?? null,+ bodyPresent: !!doc?.body,+ bodyTextChars: doc?.body?.textContent?.length ?? null,+ bodyHtmlChars: doc?.body?.innerHTML.length ?? null,+ }+ } catch (cause) {+ return {+ inspectionError:+ cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause),+ }+ }+ })(),+ },+ null,+ 2,+ )useEffect(() => {let active = trueconst run = async () => {@@ -238,8 +255,11 @@ export function EmailBody({)if (attachment) image.src = await api.inlineImage(message.accountId, attachment)else image.replaceWith(document.createTextNode(image.alt || ''))- } else if (/^https?:/.test(original) && remoteImages) {- const source = await api.remoteImage(original)+ } else if (/^https?:/.test(original) && effectiveRemoteImages) {+ const source = await api.remoteImage(+ original,+ !!message.security?.encrypted && permitDecryptedRemote,+ )if (source) image.src = sourceelse image.replaceWith(document.createTextNode(image.alt || ''))} else if (/^https?:/.test(original) && active) setBlocked(true)@@ -291,7 +311,7 @@ export function EmailBody({return () => {active = false}- }, [message.id, message.html, message.text, remoteImages, theme, loading])+ }, [message.id, message.html, message.text, effectiveRemoteImages, theme, loading])useEffect(() => {if (!source || frameReady || renderIssue) returnconst timeout = window.setTimeout(() => {@@ -419,12 +439,38 @@ export function EmailBody({if (frameReady) resizeFrame()}, [frameReady, source])useEffect(() => () => observer.current?.disconnect(), [])+ if (message.security && withheld(message.security) && !loading)+ return (+ <WithheldBody+ security={message.security}+ onUnlock={onUnlock}+ onOpenEncryption={onOpenEncryption}+ />+ )return (<>+ {message.security && !withheld(message.security) && <SecuritySummary message={message} />}{blocked && (<div className="image-notice flex gap-1.75 items-center text-muted text-[11px] pt-2 pb-4.25 px-0"><ImageOff size={13} />- Remote images are off. You can enable them in Settings.+ {message.security?.encrypted ? (+ <>+ <span>+ Remote images are blocked in encrypted mail, since loading them can show the sender+ when you read it.+ </span>+ <Button+ size="small"+ variant="ghost"+ className="ml-auto -my-1"+ onClick={() => setRemoteConsentMessage(consentScope)}+ >+ Load images+ </Button>+ </>+ ) : (+ 'Remote images are off. You can enable them in Settings.'+ )}</div>)}{source && (@@ -530,6 +576,8 @@ interface ReaderProps {onUnsubscribe: () => void/** Messages are list summaries while the full conversation loads. */loading?: boolean+ onUnlock?: () => void+ onOpenEncryption?: () => void}export type UnsubscribeState = 'available' | 'pending' | 'done'const unsubscribeLabels = {@@ -615,6 +663,8 @@ export function Reader({unsubscribe,onUnsubscribe,loading = false,+ onUnlock,+ onOpenEncryption,}: ReaderProps) {const keys = useShortcutText()// Unsent drafts sit below the conversation they would continue, never among what was said.@@ -936,6 +986,13 @@ export function Reader({className="message-attachment-hint text-muted shrink-0"/>)}+ {message.security?.encrypted && (+ <Lock+ size={12}+ className="message-encrypted text-muted shrink-0"+ aria-label="Encrypted"+ />+ )}<time dateTime={message.receivedAt} title={longDate(message.receivedAt)}>{draft && 'Saved '}{when.date}@@ -999,6 +1056,8 @@ export function Reader({loading={loading && !message.html && !message.text}onLinkHover={setLink}onMailto={onMailto}+ onUnlock={onUnlock}+ onOpenEncryption={onOpenEncryption}/>{attachments.length > 0 && (<div className="attachment-list flex gap-2.5 flex-wrap mt-5">diff --git a/apps/desktop/src/renderer/src/RecipientField.tsx b/apps/desktop/src/renderer/src/RecipientField.tsxindex 073065d..9760717 100644--- a/apps/desktop/src/renderer/src/RecipientField.tsx+++ b/apps/desktop/src/renderer/src/RecipientField.tsx@@ -1,12 +1,17 @@import { cn } from '@inlark/ui'import { useId, useRef, useState, type ReactNode } from 'react'-import { X } from '@inlark/ui/icons'+import { Lock, LockOpen, X } from '@inlark/ui/icons'import { parseAddresses, type Address } from '@inlark/core'import { Avatar } from '@inlark/ui'const valid = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)const same = (a: Address, b: Address) => a.email.toLowerCase() === b.email.toLowerCase()const format = (a: Address) => (a.name ? a.name + ' <' + a.email + '>' : a.email)+/** Whether mail to a recipient can be encrypted, shown on their chip while encrypting. */+export interface ChipSecurity {+ ready: boolean+ label: string+}/*** Recipients as removable chips with keyboard autocomplete. Text that has been typed but not yet@@ -21,6 +26,7 @@ export function RecipientField({autoFocus,placeholder,onChange,+ security,children,}: {id: string@@ -31,6 +37,7 @@ export function RecipientField({autoFocus?: booleanplaceholder?: stringonChange: (addresses: Address[]) => void+ security?: (address: Address) => ChipSecurity | undefinedchildren?: ReactNode}) {const [chips, setChips] = useState(defaultValue)@@ -95,47 +102,62 @@ export function RecipientField({><label htmlFor={id}>{label}</label><div className="recipient-chips [&_input]:flex-1 [&_input]:min-w-30 [&_input]:py-1.25 [&_input]:px-0 flex-1 min-w-0 flex flex-wrap items-center gap-1">- {chips.map((chip, i) => (- <span- key={chip.email + i}- className={cn(- 'recipient-chip inline-flex items-center gap-[3px] h-6 max-w-65 py-0 pr-1 pl-2 overflow-hidden text-[12px]',- 'whitespace-nowrap text-ellipsis text-foreground bg-hover border border-solid border-border-strong rounded-2xl',- 'cursor-default [&.invalid]:text-danger [&.invalid]:border-danger/45 [&.invalid]:bg-danger/8 [&_button]:grid',- '[&_button]:place-items-center [&_button]:w-4 [&_button]:h-4 [&_button]:p-0 [&_button]:border-0',- '[&_button]:rounded-full [&_button]:bg-none [&_button]:bg-transparent [&_button]:text-muted',- '[&_button:hover]:text-strong [&_button:hover]:bg-border-strong',- valid(chip.email) ? '' : ' invalid',- )}- title={valid(chip.email) ? chip.email : chip.email + ' is not a valid address'}- onDoubleClick={() => {- if (disabled) return- set(- chips.filter((_, index) => index !== i),- format(chip),- )- input.current?.focus()- }}- >- {chip.name || chip.email}- {!disabled && (- <button- type="button"- tabIndex={-1}- aria-label={'Remove ' + (chip.name || chip.email)}- onClick={(event) => {- event.stopPropagation()- set(- chips.filter((_, index) => index !== i),- text,- )- }}- >- <X size={11} />- </button>- )}- </span>- ))}+ {chips.map((chip, i) => {+ const secure = valid(chip.email) ? security?.(chip) : undefined+ return (+ <span+ key={chip.email + i}+ className={cn(+ 'recipient-chip inline-flex items-center gap-[3px] h-6 max-w-65 py-0 pr-1 pl-2 overflow-hidden text-[12px]',+ 'whitespace-nowrap text-ellipsis text-foreground bg-hover border border-solid border-border-strong rounded-2xl',+ 'cursor-default [&.invalid]:text-danger [&.invalid]:border-danger/45 [&.invalid]:bg-danger/8 [&_button]:grid',+ '[&_button]:place-items-center [&_button]:w-4 [&_button]:h-4 [&_button]:p-0 [&_button]:border-0',+ '[&_button]:rounded-full [&_button]:bg-none [&_button]:bg-transparent [&_button]:text-muted',+ '[&_button:hover]:text-strong [&_button:hover]:bg-border-strong',+ valid(chip.email) ? '' : ' invalid',+ secure && !secure.ready && 'invalid',+ secure && '[&>svg]:shrink-0 pl-1.75',+ )}+ title={+ valid(chip.email)+ ? chip.email + (secure ? ' · ' + secure.label : '')+ : chip.email + ' is not a valid address'+ }+ onDoubleClick={() => {+ if (disabled) return+ set(+ chips.filter((_, index) => index !== i),+ format(chip),+ )+ input.current?.focus()+ }}+ >+ {secure &&+ (secure.ready ? (+ <Lock size={11} className="text-primary" aria-label={secure.label} />+ ) : (+ <LockOpen size={11} aria-label={secure.label} />+ ))}+ {chip.name || chip.email}+ {!disabled && (+ <button+ type="button"+ tabIndex={-1}+ aria-label={'Remove ' + (chip.name || chip.email)}+ onClick={(event) => {+ event.stopPropagation()+ set(+ chips.filter((_, index) => index !== i),+ text,+ )+ }}+ >+ <X size={11} />+ </button>+ )}+ </span>+ )+ })}<inputref={input}id={id}diff --git a/apps/desktop/src/renderer/src/Settings.tsx b/apps/desktop/src/renderer/src/Settings.tsxindex 71c08e9..1216f35 100644--- a/apps/desktop/src/renderer/src/Settings.tsx+++ b/apps/desktop/src/renderer/src/Settings.tsx@@ -18,6 +18,7 @@ import {Send,SquarePen,Keyboard,+ LockKeyhole,} from '@inlark/ui/icons'import { Button, Dropdown, EmptyState, MenuItem, Modal, Select, Switch } from '@inlark/ui'import {@@ -36,6 +37,7 @@ import { FolderMappingsDialog } from './FolderMappings'import { AliasesDialog } from './Aliases'import { IndexingMeter } from './IndexingMeter'import { ShortcutEditor } from './ShortcutEditor'+import { EncryptionPanel } from './EncryptionSettings'import { newMessageAccount } from './compose-account'/** A miniature of the app window in one theme. */@@ -252,6 +254,7 @@ export function SettingsPanel({['general', 'General', SlidersHorizontal],['accounts', 'Accounts', Mail],['signatures', 'Signatures', PenLine],+ ['encryption', 'Encryption', LockKeyhole],['shortcuts', 'Shortcuts', Keyboard],['about', 'About', Info],].map(([id, name, Icon]) => {@@ -751,6 +754,37 @@ export function SettingsPanel({)}</>)}+ {tab === 'encryption' &&+ (bootstrap.accounts.length ? (+ <EncryptionPanel+ accounts={bootstrap.accounts}+ secureStorage={bootstrap.secureStorage}+ notify={notify}+ portalContainer={modalRef}+ />+ ) : (+ <>+ <h3 className="m-0 text-[20px] font-[550] tracking-[-0.5px]">Encryption</h3>+ <div className="no-accounts [&_.empty-state]:pb-12 flex min-h-90">+ <EmptyState+ icon={LockKeyhole}+ title="Nothing to encrypt yet"+ description="Encryption is set up for each address you send from. Connect an account first."+ >+ <Button+ onClick={() => {+ setTab('accounts')+ setSetup({ mode: 'add' })+ }}+ variant="primary"+ >+ <Plus size={13} />+ Connect an account+ </Button>+ </EmptyState>+ </div>+ </>+ ))}{tab === 'shortcuts' && (<><h3 className="m-0 text-[20px] font-[550] tracking-[-0.5px]">Keyboard shortcuts</h3>diff --git a/apps/desktop/src/renderer/src/Sidebar.tsx b/apps/desktop/src/renderer/src/Sidebar.tsxindex 00c5c63..69ff1de 100644--- a/apps/desktop/src/renderer/src/Sidebar.tsx+++ b/apps/desktop/src/renderer/src/Sidebar.tsx@@ -17,6 +17,7 @@ import {Star,Trash2,FileText,+ Key,WifiOff,} from '@inlark/ui/icons'import { Button, Dropdown, IconButton, MenuItem, Spinner } from '@inlark/ui'@@ -25,6 +26,7 @@ import type { Account, Mailbox, View } from '@inlark/core'import appIcon from '../../../resources/icon-mark.svg?no-inline'import { AccountMark } from './AccountMark'import { ShortcutHint, useShortcutText, type ShortcutId } from './shortcuts'+import { useEncryption } from './encryption-ui'export const views: { id: View; title: string; icon: typeof Inbox; shortcut?: ShortcutId }[] = [{ id: 'inbox', title: 'Inbox', icon: Inbox, shortcut: 'goInbox' },@@ -75,7 +77,7 @@ export function Sidebar({onSearch: () => voidonCompose: () => voidonNavigate: (next: { view: View; account?: string; folder?: string }) => void- onSettings: (tab: 'accounts' | 'general') => void+ onSettings: (tab: 'accounts' | 'general' | 'encryption') => voidonFolderAction: (operation: 'create' | 'rename' | 'delete',accountId: string,@@ -84,6 +86,14 @@ export function Sidebar({}) {const keys = useShortcutText()const go = onNavigate+ // A private key without a backup stays visible here until it is backed up, even if postponed.+ const encryption = useEncryption()+ const needsBackup = encryption.data?.keys.some(+ (key) =>+ (key.sources.includes('own') || key.sources.includes('import')) &&+ key.backup !== undefined &&+ key.backup !== 'done',+ )// Transient connecting states already show a spinner on the account row.const unavailable = accounts.filter((a) => a.status !== 'connected' && a.status !== 'connecting')const statusText =@@ -429,6 +439,23 @@ export function Sidebar({'before:pointer-events-none [@media(max-height:700px)]:pt-2',)}>+ {needsBackup && (+ <button+ className={cn(+ 'nav-item flex gap-2.5 items-center w-full h-8.5 py-0 px-2.5 border-0 bg-none bg-transparent rounded-md',+ 'text-[13px] text-left my-[2px] mx-0 transition-[color,background] duration-120 ease-[ease]',+ 'focus-visible:outline-offset-[-2px] [&>span]:flex-1 [&>span]:overflow-hidden [&>span]:text-ellipsis',+ '[&>span]:whitespace-nowrap [&>span]:relative [&>span]:top-[1px] [.sidebar-collapsed_&]:justify-center',+ '[.sidebar-collapsed_&]:p-1.75 sidebar-backup text-star [&>svg]:text-star hover:bg-star/10',+ )}+ title="Your encryption key isn’t backed up · back it up in Settings"+ aria-label="Your encryption key isn’t backed up. Back it up in Settings."+ onClick={() => onSettings('encryption')}+ >+ <Key size={15} strokeWidth={1.65} />+ {!collapsed && <span>Back up your key</span>}+ </button>+ )}{sendingIssues > 0 && (<buttonclassName={cn(diff --git a/apps/desktop/src/renderer/src/cache.ts b/apps/desktop/src/renderer/src/cache.tsindex 2e39870..4e87f1c 100644--- a/apps/desktop/src/renderer/src/cache.ts+++ b/apps/desktop/src/renderer/src/cache.ts@@ -1,7 +1,7 @@import { openDB } from 'idb'import { QueryClient, dehydrate, hydrate } from '@tanstack/react-query'import type { Draft } from '@inlark/core'-import { isDemo } from './api'+import { isDemo, api } from './api'const database = openDB('inlark-' +@@ -42,7 +42,11 @@ export function resumePersistence() {export async function restoreCache() {try {const value = await (await database).get('cache', 'queries-v1')- if (value && Date.now() - value.at < 7 * 86400_000) hydrate(queryClient, value.state)+ if (value && Date.now() - value.at < 7 * 86400_000) {+ for (const query of value.state.queries || [])+ query.state.data = redactEncrypted(query.state.data)+ hydrate(queryClient, value.state)+ }} catch {/* A cache failure must not prevent the mail client starting. */}@@ -63,6 +67,7 @@ export async function restoreCache() {['mail', 'thread', 'mailboxes', 'identities'].includes(String(q.queryKey[0])) &&q.state.status === 'success',})+ for (const query of state.queries) query.state.data = redactEncrypted(query.state.data)// Keep recent windows, not an ever-growing mailbox snapshot.state.queries.sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)state.queries = state.queries.slice(0, 80)@@ -85,8 +90,32 @@ export async function restoreCache() {}, 500)})}+export function redactEncrypted(value: unknown): any {+ if (Array.isArray(value)) return value.map(redactEncrypted)+ if (!value || typeof value !== 'object') return value+ const record = value as Record<string, any>+ if (record.security?.encrypted)+ return {+ ...record,+ html: undefined,+ text: undefined,+ preview: '',+ attachments: [],+ security: { ...record.security, state: 'locked' },+ }+ return Object.fromEntries(+ Object.entries(record).map(([key, data]) => [key, redactEncrypted(data)]),+ )+}export async function localSaveDraft(draft: Draft) {- await (await database).put('drafts', draft)+ const db = await database+ if (draft.encryption === 'encrypt') {+ // Main-process durable protection must succeed before removing an earlier plaintext save.+ await api.saveDraft(draft)+ await db.delete('drafts', draft.id)+ return+ }+ await db.put('drafts', draft)}export async function localDrafts(): Promise<Draft[]> {return (await database).getAll('drafts')@@ -101,3 +130,16 @@ export async function purgeAccountCache(ids: string[]) {for (const draft of await db.getAll('drafts'))if (ids.includes(draft.accountId)) await db.delete('drafts', draft.id)}++export async function clearDecryptedCache() {+ if (timer) clearTimeout(timer)+ await queryClient.cancelQueries({+ predicate: (q) =>+ ['thread', 'mail', 'drafts', 'recipient-encryption'].includes(String(q.queryKey[0])),+ })+ queryClient.removeQueries({+ predicate: (q) =>+ ['thread', 'mail', 'drafts', 'recipient-encryption'].includes(String(q.queryKey[0])),+ })+ await (await database).clear('cache')+}diff --git a/apps/desktop/src/renderer/src/demo.ts b/apps/desktop/src/renderer/src/demo.tsindex 5cbe755..d58fb1f 100644--- a/apps/desktop/src/renderer/src/demo.ts+++ b/apps/desktop/src/renderer/src/demo.ts@@ -15,6 +15,10 @@ import {type DesktopMailAPI,type DiscoveryCandidate,type Draft,+ type EncryptionKeySummary,+ type EncryptionReadiness,+ type EncryptionStatus,+ type RecipientReadiness,type FolderMappingReview,type FolderMappings,type Mailbox,@@ -553,7 +557,8 @@ const threadDrafts = (accountId: string, threadId: string) =>.filter((m) => m.accountId === accountId && m.threadId === threadId).sort((a, b) => a.receivedAt.localeCompare(b.receivedAt))/** A list entry for a sample message, with any drafts filed in its conversation. */-function listed(accountId: string, m: Message) {+function listed(accountId: string, original: Message) {+ const m = secured(original)const messages = [m, ...threadDrafts(accountId, m.threadId)]// Display the matching message, as the providers do, even when a draft is newer.return {@@ -630,6 +635,198 @@ const unfileDraft = (draft: Draft | undefined) => {})drafts.set(draft.id, draft)}+/* ——— Encryption: sample keys and states only; nothing is encrypted in the browser ——— */+const sampleFingerprint = (seed: string) => {+ let hash = 2166136261+ let hex = ''+ for (let round = 0; hex.length < 40; round++)+ for (const char of seed + round) {+ hash = Math.imul(hash ^ char.charCodeAt(0), 16777619) >>> 0+ hex += (hash & 15).toString(16)+ }+ return hex.slice(0, 40)+}+const sampleKey = (+ email: string,+ seed: string,+ patch: Partial<EncryptionKeySummary> = {},+): EncryptionKeySummary => ({+ email,+ fingerprint: sampleFingerprint(seed),+ sources: ['autocrypt'],+ confirmed: false,+ accepted: true,+ usable: true,+ publicKey: '',+ ...patch,+})+const encryption: EncryptionStatus = {+ vault: 'unlocked',+ protection: 'os',+ identities: [+ {+ accountId: demoAccounts[0].id,+ identityId: 'identity',+ email: demoAccounts[0].email,+ fingerprint: sampleFingerprint('personal'),+ enabled: true,+ prefer: true,+ },+ ],+ keys: [+ sampleKey(demoAccounts[0].email, 'personal', {+ sources: ['own'],+ confirmed: true,+ backup: 'needed',+ }),+ sampleKey('[email protected]', 'maya', { sources: ['wkd', 'autocrypt'] }),+ sampleKey('[email protected]', 'lena', { confirmed: true }),+ sampleKey('[email protected]', 'daniel', { confirmed: true }),+ sampleKey('[email protected]', 'daniel-new', { accepted: false }),+ ],+}+/** Contacts whose sample mail says they prefer encryption. */+const prefersEncryption = new Set(['[email protected]'])+const encryptionState = (): EncryptionStatus => structuredClone(encryption)+const emitEncryption = (locked: boolean) =>+ listeners.forEach((fn) => fn({ type: 'encryption', locked }))+const identityEmail = (accountId: string, identityId: string) => {+ const account = demoAccounts.find((a) => a.id === accountId)!+ return (+ identityId === 'identity'+ ? account.email+ : account.aliases?.find((alias) => alias.id === identityId)?.email || account.email+ ).toLowerCase()+}+const installKey = (accountId: string, identityId: string, source: 'own' | 'import') => {+ const email = identityEmail(accountId, identityId)+ const current = encryption.identities.find(+ (i) => i.accountId === accountId && i.identityId === identityId,+ )+ for (const key of encryption.keys)+ if (key.email === email) {+ key.accepted = false+ key.retired = true+ }+ const key = sampleKey(email, email + Date.now(), {+ sources: [source],+ confirmed: true,+ backup: 'needed',+ })+ encryption.keys.push(key)+ encryption.identities = encryption.identities.filter((i) => i !== current)+ encryption.identities.push({+ accountId,+ identityId,+ email,+ fingerprint: key.fingerprint,+ enabled: true,+ prefer: current?.prefer ?? false,+ })+ if (encryption.vault === 'absent') {+ encryption.vault = 'unlocked'+ encryption.protection = 'password'+ }+}+const requireUnlocked = () => {+ if (encryption.vault !== 'unlocked') throw new Error('Unlock the encryption vault first.')+}+function readiness(+ accountId: string,+ identityId: string,+ addresses: string[],+): EncryptionReadiness {+ const own = encryption.identities.find(+ (i) => i.accountId === accountId && i.identityId === identityId,+ )+ const emails = [...new Set(addresses.map((a) => a.trim().toLowerCase()))]+ if (!own?.enabled)+ return {+ senderReady: false,+ recommend: false,+ recipients: emails.map((email) => ({+ email,+ status: 'missing',+ confirmed: false,+ prefers: false,+ })),+ }+ const ownKey = encryption.keys.find((k) => k.fingerprint === own.fingerprint)+ const senderReady = !!ownKey?.usable && encryption.vault === 'unlocked'+ const recipients = emails.map((email): RecipientReadiness => {+ const keys = encryption.keys.filter((k) => k.email === email && !k.retired)+ const usable = keys.filter((k) => k.usable)+ let key = keys.find((k) => k.accepted)+ let status: RecipientReadiness['status'] = 'missing'+ if (key)+ status = usable.some((k) => k !== key)+ ? 'changed'+ : key.usable+ ? 'ready'+ : (key.problem as 'revoked') || 'unusable'+ else if (usable.length > 1) status = 'conflict'+ else if (usable.length === 1) {+ key = usable[0]+ key.accepted = true+ status = 'ready'+ }+ return {+ email,+ status,+ fingerprint: key?.fingerprint,+ confirmed: !!key?.confirmed,+ prefers: email === own.email ? own.prefer : prefersEncryption.has(email),+ }+ })+ return {+ senderReady,+ recipients,+ recommend:+ senderReady &&+ own.prefer &&+ !!recipients.length &&+ recipients.every((r) => r.status === 'ready' && r.prefers),+ }+}+/** Sample mail from Maya is encrypted and Lena's is signed, so the reader can show both. */+function secured(m: Message): Message {+ const sender = m.from[0]?.email+ const key = encryption.keys.find((k) => k.email === sender && k.accepted)+ if (sender === '[email protected]') {+ if (encryption.vault !== 'unlocked')+ return {+ ...m,+ html: '',+ text: '',+ preview: '',+ attachments: [],+ security: { encrypted: true, state: 'locked', signature: 'unknown', confirmed: false },+ }+ return {+ ...m,+ preview: '',+ security: {+ encrypted: true,+ state: 'decrypted',+ signature: 'valid',+ fingerprint: key?.fingerprint,+ confirmed: !!key?.confirmed,+ },+ }+ }+ if (sender === '[email protected]')+ return {+ ...m,+ security: {+ encrypted: false,+ state: 'signed',+ signature: 'valid',+ fingerprint: key?.fingerprint,+ confirmed: !!key?.confirmed,+ },+ }+ return m+}const copyOf = (source: Draft, patch: Partial<Draft>): Draft => ({...source,id: crypto.randomUUID(),@@ -639,6 +836,106 @@ const copyOf = (source: Draft, patch: Partial<Draft>): Draft => ({})export const demoAPI: DesktopMailAPI = {updateStatus: async () => ({ phase: 'idle' }),+ encryptionStatus: async () => encryptionState(),+ setupEncryption: async ({ accountId, identityId, action, password }) => {+ await pause(action === 'create' || action === 'replace' ? 1200 : 500)+ const email = identityEmail(accountId, identityId)+ if (encryption.vault === 'absent' && (!password || password.length < 10))+ throw new Error(+ 'Use a vault password of at least 10 characters when secure OS storage is unavailable.',+ )+ if (action === 'create' && encryption.keys.some((k) => k.email === email))+ throw new Error(+ 'An existing key was discovered for this address. Import its private key instead of generating a replacement.',+ )+ // The desktop app asks for a key file here; the demo imports a sample key instead.+ if (action === 'historical')+ encryption.keys.push(+ sampleKey(email, email + 'older' + Date.now(), {+ sources: ['import'],+ accepted: false,+ retired: true,+ backup: 'needed',+ }),+ )+ else installKey(accountId, identityId, action === 'create' ? 'own' : 'import')+ return encryptionState()+ },+ setEncryptionPreference: async (accountId, identityId, enabled, prefer) => {+ const own = encryption.identities.find(+ (i) => i.accountId === accountId && i.identityId === identityId,+ )+ if (!own) throw new Error('Create or import a key for this identity first.')+ own.enabled = enabled+ own.prefer = enabled && prefer+ return encryptionState()+ },+ exportEncryptionKey: async (fingerprint, kind, password) => {+ if (kind === 'public') return+ requireUnlocked()+ if ((password || '').length < 10)+ throw new Error('Use a backup password of at least 10 characters.')+ await pause(500)+ for (const key of encryption.keys) if (key.fingerprint === fingerprint) key.backup = 'done'+ },+ revokeEncryptionKey: async (fingerprint) => {+ requireUnlocked()+ for (const key of encryption.keys)+ if (key.fingerprint === fingerprint)+ Object.assign(key, { usable: false, problem: 'revoked', retired: true })+ for (const own of encryption.identities)+ if (own.fingerprint === fingerprint) Object.assign(own, { enabled: false, prefer: false })+ return encryptionState()+ },+ postponeEncryptionBackup: async (fingerprint) => {+ for (const key of encryption.keys) if (key.fingerprint === fingerprint) key.backup = 'postponed'+ return encryptionState()+ },+ discoverEncryptionKeys: async (email) => {+ await pause(450)+ return structuredClone(encryption.keys.filter((k) => k.email === email.toLowerCase()))+ },+ acceptEncryptionKey: async (email, fingerprint, confirmed) => {+ const keys = encryption.keys.filter((k) => k.email === email.toLowerCase())+ const selected = keys.find((k) => k.fingerprint === fingerprint)+ if (!selected) throw new Error('Choose a discovered key for this address.')+ for (const key of keys) {+ key.accepted = key === selected+ if (key !== selected) key.retired = true+ }+ selected.confirmed = confirmed+ selected.retired = false+ return encryptionState()+ },+ encryptionReadiness: async (accountId, identityId, recipients) => {+ await pause(300)+ return readiness(accountId, identityId, recipients)+ },+ unlockEncryption: async (password) => {+ await pause(300)+ if (encryption.protection === 'password' && !password)+ throw new Error('Enter the vault password.')+ encryption.vault = 'unlocked'+ emitEncryption(false)+ return encryptionState()+ },+ lockEncryption: async () => {+ encryption.vault = 'locked'+ emitEncryption(true)+ },+ transferEncryption: async ({ accountId, identityId, action }) => {+ await pause(500)+ if (action === 'export') {+ requireUnlocked()+ return {+ code: Array.from({ length: 9 }, () =>+ String(Math.floor(Math.random() * 10000)).padStart(4, '0'),+ ).join('-'),+ }+ }+ installKey(accountId, identityId, 'import')+ return {}+ },bootstrap: async () => ({accounts: demoAccounts,settings,@@ -878,7 +1175,7 @@ export const demoAPI: DesktopMailAPI = {const accountIndex = demoAccounts.findIndex((a) => a.id === accountId)const m = get(accountIndex, Number(threadId.replace('thread-', '')))if (!m) throw new Error('Conversation not found.')- return [m, ...threadDrafts(accountId, threadId)]+ return [secured(m), ...threadDrafts(accountId, threadId)]},mutate: async (input) => {const saved: [string, Message | null | undefined][] = []diff --git a/apps/desktop/src/renderer/src/encryption-actions.tsx b/apps/desktop/src/renderer/src/encryption-actions.tsxnew file mode 100644index 0000000..ec06920--- /dev/null+++ b/apps/desktop/src/renderer/src/encryption-actions.tsx@@ -0,0 +1,339 @@+import { cn } from '@inlark/ui'+import { useState } from 'react'+import { useQuery } from '@tanstack/react-query'+import { AlertCircle, BadgeCheck, Key, RefreshCw } from '@inlark/ui/icons'+import { Button, Modal, Spinner } from '@inlark/ui'+import { friendlyError, type EncryptionKeySummary, type EncryptionStatus } from '@inlark/core'+import { api } from './api'+import { queryClient } from './cache'+import {+ Callout,+ FingerprintBlock,+ FormError,+ KeyBadge,+ PasswordField,+ keySources,+ modalActions,+ shortFingerprint,+ useEncryption,+} from './encryption-ui'++const keyProblems: Record<string, string> = {+ expired: 'Expired',+ revoked: 'Revoked',+}++function UnlockDialog({+ open,+ initialError,+ onDone,+}: {+ open: boolean+ initialError?: string+ onDone: (unlocked: boolean) => void+}) {+ const status = useEncryption()+ const [password, setPassword] = useState('')+ const [error, setError] = useState(initialError || '')+ const [busy, setBusy] = useState(false)+ const passwordMode = status.data?.protection === 'password'+ return (+ <Modal+ open={open}+ onOpenChange={(value) => {+ if (!value && !busy) onDone(false)+ }}+ title="Unlock your encryption keys"+ description={+ passwordMode+ ? 'Enter your vault password to read encrypted mail and keep writing encrypted drafts.'+ : 'Inlark couldn’t open your keys with the system keyring. Make sure it’s unlocked, then try again.'+ }+ className="w-[min(440px,_calc(100vw_-_40px))]"+ >+ <form+ onSubmit={async (e) => {+ e.preventDefault()+ if (passwordMode && !password) {+ setError('Enter your vault password.')+ return+ }+ setBusy(true)+ setError('')+ try {+ queryClient.setQueryData(+ ['encryption'],+ await api.unlockEncryption(passwordMode ? password : undefined),+ )+ onDone(true)+ } catch (e) {+ setError(+ passwordMode && /authenticat|decrypt|password/i.test(friendlyError(e))+ ? 'That password didn’t work. Check it and try again.'+ : friendlyError(e),+ )+ } finally {+ setBusy(false)+ }+ }}+ >+ {passwordMode && (+ <PasswordField+ label="Vault password"+ value={password}+ autoFocus+ autoComplete="current-password"+ onChange={(value) => {+ setPassword(value)+ setError('')+ }}+ />+ )}+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button onClick={() => onDone(false)} disabled={busy}>+ Cancel+ </Button>+ <Button type="submit" variant="primary" disabled={busy}>+ {busy && <Spinner size={14} />}+ {busy ? 'Unlocking…' : passwordMode ? 'Unlock' : 'Try again'}+ </Button>+ </div>+ </form>+ </Modal>+ )+}++/**+ * Unlocks the vault when needed. Keyring-protected vaults open without asking; a vault password+ * is asked for in a dialog. Resolves whether the keys are unlocked afterwards.+ */+export function useUnlock() {+ const [request, setRequest] = useState<{+ id: number+ error?: string+ resolve: (unlocked: boolean) => void+ }>()+ const unlock = async (): Promise<boolean> => {+ const status = await queryClient.fetchQuery<EncryptionStatus>({+ queryKey: ['encryption'],+ queryFn: () => api.encryptionStatus(),+ staleTime: 0,+ })+ if (status.vault !== 'locked') return status.vault === 'unlocked'+ let error: string | undefined+ if (status.protection !== 'password') {+ try {+ queryClient.setQueryData(['encryption'], await api.unlockEncryption())+ return true+ } catch (e) {+ error = friendlyError(e)+ }+ }+ return new Promise((resolve) => setRequest({ id: Date.now(), error, resolve }))+ }+ const dialog = (+ <UnlockDialog+ key={request?.id ?? 'closed'}+ open={!!request}+ initialError={request?.error}+ onDone={(unlocked) => {+ request?.resolve(unlocked)+ setRequest(undefined)+ }}+ />+ )+ return [unlock, dialog] as const+}++/** Refreshes everything that shows which keys are trusted. */+export function keysChanged(status?: EncryptionStatus) {+ if (status) queryClient.setQueryData(['encryption'], status)+ void queryClient.invalidateQueries({ queryKey: ['encryption'] })+ void queryClient.invalidateQueries({ queryKey: ['contact-keys'] })+ void queryClient.invalidateQueries({ queryKey: ['recipient-encryption'] })+}++/**+ * The keys known for one contact: which one Inlark uses, where each came from, and whether it+ * was verified. A changed or conflicting key is explained before anything else.+ */+export function ContactKeyDialog({ email, onClose }: { email?: string; onClose: () => void }) {+ const keys = useQuery({+ queryKey: ['contact-keys', email],+ queryFn: () => api.discoverEncryptionKeys(email!),+ enabled: !!email,+ retry: false,+ })+ const [busy, setBusy] = useState<string>()+ const [error, setError] = useState('')+ const refresh = async () => {+ setBusy('refresh')+ setError('')+ try {+ queryClient.setQueryData(+ ['contact-keys', email],+ await api.discoverEncryptionKeys(email!, true),+ )+ void queryClient.invalidateQueries({ queryKey: ['recipient-encryption'] })+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setBusy(undefined)+ }+ }+ const accept = async (fingerprint: string, confirmed: boolean) => {+ setBusy(fingerprint)+ setError('')+ try {+ keysChanged(await api.acceptEncryptionKey(email!, fingerprint, confirmed))+ await keys.refetch()+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setBusy(undefined)+ }+ }+ const list = keys.data || []+ const current = list.find((k) => k.accepted && !k.retired)+ const active = list.filter((k) => !k.retired)+ const previous = list.filter((k) => k.retired)+ const changed = !!current && active.some((k) => k !== current && k.usable)+ const conflict = !current && active.filter((k) => k.usable).length > 1+ const card = (key: EncryptionKeySummary, old = false) => {+ const inUse = key === current+ return (+ <div+ key={key.fingerprint}+ className={cn(+ 'key-card rounded-lg border border-solid p-3.5 [&+.key-card]:mt-2.5',+ inUse && !changed ? 'border-primary-solid/45' : 'border-border-strong',+ old && 'opacity-70',+ )}+ >+ <div className="key-card-heading flex items-center gap-2 flex-wrap mb-1">+ <strong className="text-[12px] font-medium text-strong">+ {old+ ? 'Previous key'+ : inUse+ ? 'Key in use'+ : changed+ ? 'New key'+ : 'Key ' + shortFingerprint(key.fingerprint).slice(-9)}+ </strong>+ {!old &&+ (key.confirmed ? (+ <KeyBadge tone="good" icon={BadgeCheck}>+ Verified+ </KeyBadge>+ ) : (+ <KeyBadge>Not verified</KeyBadge>+ ))}+ {key.problem && (+ <KeyBadge tone="danger">{keyProblems[key.problem] || 'Can’t be used'}</KeyBadge>+ )}+ </div>+ <p className="mt-0 mb-2.5 text-[11px] text-muted">Found in {keySources(key)}</p>+ <FingerprintBlock value={key.fingerprint} />+ {!old && key.usable && (!inUse || !key.confirmed) && (+ <div className="key-card-actions flex gap-2 mt-3">+ {!inUse && (+ <Button+ size="small"+ variant={conflict || changed ? 'default' : 'primary'}+ disabled={!!busy}+ onClick={() => void accept(key.fingerprint, false)}+ >+ {busy === key.fingerprint && <Spinner size={12} />}+ {changed ? 'Use the new key' : 'Use this key'}+ </Button>+ )}+ <Button+ size="small"+ variant={inUse ? 'primary' : 'default'}+ disabled={!!busy}+ onClick={() => void accept(key.fingerprint, true)}+ >+ <BadgeCheck size={13} />+ {inUse ? 'Mark as verified' : 'Use and mark verified'}+ </Button>+ </div>+ )}+ </div>+ )+ }+ return (+ <Modal+ open={!!email}+ onOpenChange={(open) => {+ if (!open && !busy) onClose()+ }}+ title={'Keys for ' + (email || 'this contact')}+ description={'Inlark encrypts mail to ' + (email || 'them') + ' with the key in use.'}+ className="w-[min(520px,_calc(100vw_-_40px))]"+ >+ {keys.isPending && (+ <div className="flex items-center gap-2 py-6 justify-center text-muted text-[12px]">+ <Spinner size={14} /> Looking for keys…+ </div>+ )}+ {keys.isError && (+ <Callout tone="danger" icon={AlertCircle} title="Couldn’t look up keys">+ {friendlyError(keys.error)}+ </Callout>+ )}+ {keys.isSuccess && !list.length && (+ <Callout icon={Key} title="No key found">+ <p>+ {email} hasn’t published a key, and none came with their mail. Ask them to send you a+ message from an app with OpenPGP encryption, then check again.+ </p>+ </Callout>+ )}+ {changed && (+ <Callout+ tone="warning"+ icon={AlertCircle}+ title="This contact’s key changed"+ className="mb-4"+ >+ <p>+ This is normal after someone sets up a new device or app, but it can also mean someone+ is pretending to be them. Check the new fingerprint with {email} before using it.+ </p>+ </Callout>+ )}+ {conflict && (+ <Callout tone="warning" icon={AlertCircle} title="Choose the right key" className="mb-4">+ <p>Several keys were found for {email}. Ask them which fingerprint is theirs.</p>+ </Callout>+ )}+ {current && card(current)}+ {active.filter((k) => k !== current).map((k) => card(k))}+ {previous.length > 0 && (+ <div className="previous-keys mt-4">{previous.map((k) => card(k, true))}</div>+ )}+ {list.some((k) => !k.confirmed && !k.retired) && (+ <p className="mt-4 mb-0 text-[11px] leading-[1.6] text-muted">+ To verify a key, compare its fingerprint with {email} in person or on a call. If every+ group matches, only they can read what you encrypt to it.+ </p>+ )}+ {error && <FormError>{error}</FormError>}+ <div className={modalActions}>+ <Button+ variant="ghost"+ className="modal-action-start"+ disabled={!!busy || keys.isPending}+ onClick={() => void refresh()}+ >+ {busy === 'refresh' ? <Spinner size={14} /> : <RefreshCw size={14} />}+ Check again+ </Button>+ <Button onClick={onClose} disabled={!!busy}>+ Done+ </Button>+ </div>+ </Modal>+ )+}diff --git a/apps/desktop/src/renderer/src/encryption-ui.tsx b/apps/desktop/src/renderer/src/encryption-ui.tsxnew file mode 100644index 0000000..783cbb3--- /dev/null+++ b/apps/desktop/src/renderer/src/encryption-ui.tsx@@ -0,0 +1,299 @@+import { cn } from '@inlark/ui'+import { useEffect, useState, type ReactNode } from 'react'+import { useQuery } from '@tanstack/react-query'+import { AlertCircle, Check, Copy, Info, type IconComponent } from '@inlark/ui/icons'+import { IconButton } from '@inlark/ui'+import { friendlyError, type EncryptionKeySummary, type RecipientReadiness } from '@inlark/core'+import { api } from './api'++export const useEncryption = () =>+ useQuery({ queryKey: ['encryption'], queryFn: () => api.encryptionStatus() })++/** Gives open composers a chance to save, then locks the vault. */+export async function lockVault() {+ const tasks: Promise<unknown>[] = []+ window.dispatchEvent(new CustomEvent('inlark-before-lock', { detail: tasks }))+ await Promise.all(tasks)+ await api.lockEncryption()+}++/** Groups a fingerprint in fours, as other OpenPGP apps show it, so it can be read aloud. */+export const formatFingerprint = (fingerprint: string) =>+ fingerprint+ .toUpperCase()+ .match(/.{1,4}/g)+ ?.join(' ') || ''+/** The last 16 digits, enough to tell keys apart at a glance. */+export const shortFingerprint = (fingerprint: string) => formatFingerprint(fingerprint.slice(-16))++export const recipientProblems: Record<Exclude<RecipientReadiness['status'], 'ready'>, string> = {+ missing: 'No key found',+ expired: 'Key expired',+ revoked: 'Key revoked',+ unusable: 'Key can’t be used',+ changed: 'Key changed',+ conflict: 'Several keys found',+}+const sourceLabels: Record<EncryptionKeySummary['sources'][number], string> = {+ own: 'created in Inlark',+ import: 'imported',+ wkd: 'their provider’s key directory',+ autocrypt: 'mail they sent you',+ gossip: 'a message to several people',+}+export const keySources = (key: EncryptionKeySummary) =>+ key.sources.map((source) => sourceLabels[source]).join(', ')++/** Explains failures from importing a key file in terms of what to try next. */+export function keyFileError(error: unknown, password: string) {+ const text = friendlyError(error)+ if (/passphrase/i.test(text))+ return password+ ? 'That password didn’t unlock the key file. Check it and try again.'+ : 'This key file is password protected. Enter its password, then choose the file again.'+ if (/armor|packet|misformed|no key/i.test(text))+ return 'This file doesn’t contain a private key Inlark can read. Choose an exported private key or a backup.'+ return text+}++/** Why a new password can't be used, if it can't. */+export const newPasswordProblem = (password: string, confirm: string) =>+ password.length < 10+ ? 'Use at least 10 characters.'+ : password !== confirm+ ? 'The passwords don’t match.'+ : ''++const formField =+ "form-field block [&+.form-field]:mt-3.5 [&_input]:mt-1.5 [&_input]:text-[12px] [&_input[aria-invalid='true']]:border-danger/70"+export const dialogLead = 'mt-0 mb-4.5 text-[12px] leading-[1.6] text-secondary'+export const formError =+ 'form-error flex gap-2 text-[11px] leading-[1.6] mt-3.5 mb-0 mx-0 text-danger [&_svg]:shrink-0 [&_svg]:mt-[3px]'+export const modalActions =+ 'modal-actions flex justify-end gap-2 mt-6 [&>.modal-action-start]:mr-auto [&>.modal-action-start]:-ml-2.5'++export function PasswordField({+ label,+ value,+ onChange,+ hint,+ error,+ autoFocus,+ autoComplete = 'off',+}: {+ label: string+ value: string+ onChange: (value: string) => void+ hint?: ReactNode+ error?: string+ autoFocus?: boolean+ autoComplete?: string+}) {+ return (+ <label className={formField}>+ {label}+ <input+ type="password"+ autoFocus={autoFocus}+ autoComplete={autoComplete}+ spellCheck={false}+ value={value}+ aria-invalid={!!error || undefined}+ onChange={(e) => onChange(e.target.value)}+ />+ {error ? (+ <span className="field-error block mt-1.25 text-[11px] text-danger">{error}</span>+ ) : (+ hint && <span className="field-hint text-muted text-[11px] block mt-1.25">{hint}</span>+ )}+ </label>+ )+}++/** A password chosen now and typed again, with the mismatch shown once the form was submitted. */+export function NewPasswordFields({+ label,+ password,+ confirm,+ onChange,+ hint,+ showProblems,+ autoFocus,+}: {+ label: string+ password: string+ confirm: string+ onChange: (password: string, confirm: string) => void+ hint: ReactNode+ showProblems: boolean+ autoFocus?: boolean+}) {+ const problem = showProblems ? newPasswordProblem(password, confirm) : ''+ return (+ <>+ <PasswordField+ label={label}+ value={password}+ autoFocus={autoFocus}+ autoComplete="new-password"+ onChange={(value) => onChange(value, confirm)}+ error={problem && password.length < 10 ? problem : undefined}+ hint={hint}+ />+ <PasswordField+ label="Confirm password"+ value={confirm}+ autoComplete="new-password"+ onChange={(value) => onChange(password, value)}+ error={problem && password.length >= 10 ? problem : undefined}+ />+ </>+ )+}++export function FormError({ children }: { children: ReactNode }) {+ return (+ <div role="alert" className={formError}>+ <AlertCircle size={14} />+ <span>{children}</span>+ </div>+ )+}++/** A short boxed note: what happened or what to know, and optionally what to do about it. */+export function Callout({+ tone = 'info',+ icon: Icon = Info,+ title,+ children,+ action,+ className,+}: {+ tone?: 'info' | 'warning' | 'danger' | 'success'+ icon?: IconComponent+ title?: ReactNode+ children?: ReactNode+ action?: ReactNode+ className?: string+}) {+ return (+ <div+ className={cn(+ 'callout flex gap-3 items-start rounded-lg border border-solid py-3 px-3.5 text-[12px] leading-[1.6]',+ tone === 'info' &&+ 'border-border-strong bg-[color-mix(in_srgb,_var(--hover)_55%,_transparent)]',+ tone === 'warning' && 'border-star/28 bg-star/7',+ tone === 'danger' && 'border-danger/30 bg-danger/7',+ tone === 'success' && 'border-success/28 bg-success/7',+ className,+ )}+ >+ <Icon+ size={16}+ className={cn(+ 'shrink-0 mt-[1px]',+ tone === 'info' && 'text-muted',+ tone === 'warning' && 'text-star',+ tone === 'danger' && 'text-danger',+ tone === 'success' && 'text-success',+ )}+ />+ <div className="callout-copy flex-1 min-w-0 text-secondary [&_strong]:block [&_strong]:text-strong [&_strong]:font-medium [&_p]:m-0">+ {title && <strong>{title}</strong>}+ {children}+ </div>+ {action && <div className="callout-action shrink-0 self-center flex gap-1.5">{action}</div>}+ </div>+ )+}++/** A small label for a key's state. */+export function KeyBadge({+ tone = 'neutral',+ icon: Icon,+ children,+}: {+ tone?: 'neutral' | 'good' | 'warning' | 'danger' | 'accent'+ icon?: IconComponent+ children: ReactNode+}) {+ return (+ <span+ className={cn(+ 'key-badge inline-flex items-center gap-1 h-5 px-1.75 rounded-sm text-[11px] font-medium whitespace-nowrap',+ tone === 'neutral' && 'bg-hover text-muted',+ tone === 'good' && 'bg-success/12 text-success',+ tone === 'warning' && 'bg-star/12 text-star',+ tone === 'danger' && 'bg-danger/12 text-danger',+ tone === 'accent' && 'bg-primary-tint text-primary',+ )}+ >+ {Icon && <Icon size={12} />}+ {children}+ </span>+ )+}++/** The whole fingerprint, in rows of five groups, with a way to copy it for comparison. */+export function FingerprintBlock({ value, className }: { value: string; className?: string }) {+ const [copied, setCopied] = useState(false)+ useEffect(() => {+ if (!copied) return+ const timer = setTimeout(() => setCopied(false), 1600)+ return () => clearTimeout(timer)+ }, [copied])+ const groups = value.toUpperCase().match(/.{1,4}/g) || []+ return (+ <div+ className={cn(+ 'fingerprint flex items-center gap-3 py-2.5 pr-1.5 pl-3.5 rounded-md bg-field border border-solid border-border',+ className,+ )}+ >+ <span+ className="fingerprint-groups flex-1 grid grid-cols-[repeat(5,_max-content)] gap-x-2.5 gap-y-0.5 font-mono text-[12px] tracking-[0.4px] text-foreground select-text"+ aria-label={'Fingerprint ' + groups.join(' ')}+ >+ {groups.map((group, index) => (+ <span key={index}>{group}</span>+ ))}+ </span>+ <IconButton+ label={copied ? 'Copied' : 'Copy fingerprint'}+ onClick={() =>+ void navigator.clipboard.writeText(groups.join(' ')).then(() => setCopied(true))+ }+ >+ {copied ? <Check size={14} className="text-success" /> : <Copy size={14} />}+ </IconButton>+ </div>+ )+}++/** A tile for a dialog or empty state, so each state reads at a glance. */+export function StateIcon({+ icon: Icon,+ tone = 'accent',+ size = 40,+}: {+ icon: IconComponent+ tone?: 'accent' | 'good' | 'warning' | 'danger' | 'neutral'+ size?: number+}) {+ return (+ <span+ className={cn(+ 'state-icon grid place-items-center shrink-0 rounded-xl',+ tone === 'accent' && 'bg-primary-tint text-primary',+ tone === 'good' && 'bg-success/10 text-success',+ tone === 'warning' && 'bg-star/10 text-star',+ tone === 'danger' && 'bg-danger/10 text-danger',+ tone === 'neutral' && 'bg-hover text-muted',+ )}+ style={{ width: size, height: size }}+ aria-hidden="true"+ >+ <Icon size={Math.round(size * 0.48)} strokeWidth={1.6} />+ </span>+ )+}diff --git a/apps/desktop/src/renderer/src/shortcuts.tsx b/apps/desktop/src/renderer/src/shortcuts.tsxindex 8776ca4..2d701b4 100644--- a/apps/desktop/src/renderer/src/shortcuts.tsx+++ b/apps/desktop/src/renderer/src/shortcuts.tsx@@ -91,6 +91,13 @@ export const shortcutDefinitions = [description: 'While composing a message.',defaults: [['Mod+Shift+A']],},+ {+ id: 'toggleEncryption',+ section: 'Write',+ label: 'Encrypt or stop encrypting',+ description: 'While composing, from an address with encryption set up.',+ defaults: [['Mod+Shift+E']],+ },{ id: 'showCc', section: 'Write', label: 'Show and focus Cc', defaults: [['Mod+Shift+C']] },{ id: 'showBcc', section: 'Write', label: 'Show and focus Bcc', defaults: [['Mod+Shift+B']] },{diff --git a/docs/encryption-validation.md b/docs/encryption-validation.mdnew file mode 100644index 0000000..10e98bb--- /dev/null+++ b/docs/encryption-validation.md@@ -0,0 +1,23 @@+# Encryption validation record++Validated in this workspace on 2026-10-07 with Node 24.21.0, OpenPGP.js 6.3.2, GnuPG 2.4.9 and Stalwart 0.16.23.++| Check | Result |+| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Repository formatting, type checks, unit tests and production build (`pnpm check`) | Passed; 312 tests passed. The five container tests are intentionally gated in this command. |+| Bundled crypto worker | Passed generation, signed encryption, decryption and locking. |+| Independent GnuPG interoperability | Passed fixture decryption and signature verification, plus GnuPG decryption/verification of Inlark output, hidden recipient packets, detached signatures and protected backup import. |+| Protected draft and staging storage | Tests inspected vault, draft stubs, staging metadata and outgoing bytes for body/attachment markers. Selected file contents and filenames stay encrypted; original user files remain unchanged. |+| Crash/lock recovery | Automated service tests passed selected draft restoration, encrypted server revisions, tombstones, partial-delivery recovery, uncertain-send replacement and explicit ordinary-draft transition. |+| Browser IndexedDB inspection | A synthetic encrypted message retained its content in memory while its saved query record had no body or attachment marker and was marked locked. Clearing decrypted caches removed the memory record. |+| WKD and Autocrypt | Passed advanced/direct fallback conditions, TLS failure handling, wrong-address rejection, same-fingerprint refresh, stale/malformed headers, changed-key blocking, bounded unopened-message header discovery, cache refresh, disabled-identity privacy and Setup Message transfer. |+| Real server encrypted workflows | Passed IMAP APPEND/raw source retrieval/SMTP/Sent and JMAP upload/import/raw blob/envelope submission tests. |+| Complete Stalwart integration suite | All five tests passed together, including two further runs with temporary server diagnostics. Earlier runs intermittently failed the existing wrong-password SMTP assertion: the server connection closed with `outgoingNetwork` instead of returning `outgoingAuthentication`. Subsequent SMTP flows also failed in some runs. The JMAP custom-header field mismatch was fixed, and both transports' encrypted workflows and unopened-header discovery passed. The diagnostic runs did not reproduce the SMTP failure; its cause remains unresolved and needs investigation before release. |+| Linux unpacked packaging | Built successfully; the packaged `app.asar` worker passed generation, encryption, signing, decryption, locking and independent GnuPG checks under its bundled Electron 44.4.5 runtime. A full desktop/keyring run is still required. |+| Nix dependency packaging | Updated dependency hash and verified the fixed-output derivation. A complete Nix desktop smoke run remains required. |+| Thunderbird fixtures and round trips | Not yet verified. |+| Complete protected recovery workflows on real servers | Native end-to-end draft resume, conflict resolution and deliberate lost-response/partial-delivery/Sent-copy fault injection remain required against both transports. The service recovery tests use controlled provider fixtures. |+| Packaged OS keyring, password fallback and backup restoration on Linux, Windows and macOS | Not yet verified on real secure storage across all three platforms. Mocked OS wrapping and actual password-vault restoration tests passed. |+| Packaged end-to-end plaintext audit | Not yet complete across IndexedDB, notifications, diagnostics, IMAP index, attachments and all network requests on each platform. |++Do not release the feature until the outstanding interoperability, packaged privacy, keyring and server checks pass. The user guide is [encryption.md](encryption.md); fixture provenance is [the OpenPGP fixture README](../tests/fixtures/openpgp/README.md).diff --git a/docs/encryption.md b/docs/encryption.mdnew file mode 100644index 0000000..203d132--- /dev/null+++ b/docs/encryption.md@@ -0,0 +1,68 @@+# Email encryption++Encryption is optional for each sending identity. Open **Settings → Encryption** and choose **Set up…** next to an address, then **Create a new key**, **Import an existing key** or **Transfer from another device**. Inlark checks for published keys for your address before creating one; if it finds one, it suggests importing the original private key instead. Public keys let other people encrypt mail to you. Private keys unlock that mail and must stay protected. Each address has its own switch to turn encryption on or off, and a **Manage** menu for its key.++## Protect and recover your keys++Inlark uses secure OS key storage to protect its local vault when available. Otherwise you must choose a vault password. Private keys are never saved unprotected, even if ordinary account credentials use the existing insecure-storage fallback. If secure storage becomes unavailable, Inlark preserves the vault and asks you to restore access; it never creates a replacement automatically.++Setup ends by asking for a backup: a password-protected key file whose password you keep separately. **Back up later** requires acknowledging that losing the key can make encrypted mail permanently unreadable; a reminder remains in Settings and the sidebar until you back up. Resetting your email password cannot recover your private key or vault password. Import a backup using **Import an existing key**. An address's **Manage** menu offers **Back up key…**, **Export public key…**, **Move to another device…**, **Import an older key…** for historical mail, **Replace key…** (create or import) and **Revoke key…**. Replaced keys appear under **Older keys**, where they can still be backed up, exported or revoked. Replacing or revoking a key retains the original private key for historical decryption.++**Lock** under **Key storage**, or **Lock encryption keys** in the command menu, saves open drafts before locking. It clears decrypted messages, attachments and key state. Encrypted messages then show an **Unlock** button; keyring-protected keys unlock without a prompt, and password-protected vaults ask for the vault password. Encryption cannot protect content on an already compromised or unlocked device.++## Compose and read mail++For addresses with encryption set up, the composer toolbar offers **Encrypt** (which also signs), **Sign only** and **Don’t encrypt**; `Ctrl+Shift+E` (`⌘⇧E` on macOS) switches encryption on or off. While encrypting, a bar above the message says who it is encrypted for, recipient chips show a lock, and the send button reads **Send encrypted**. New conversations automatically select encryption only when your identity and every recipient prefer it and usable keys are available. Replies and forwards containing decrypted content start protected before their first autosave.++An encrypted send is blocked if any recipient's key is missing, expired, revoked, changed or conflicting. The bar names each affected recipient and the reason; select one to review their keys. Inlark never silently switches to ordinary mail. Sending a previously protected draft or reply unencrypted requires an explicit change and confirmation.++Bodies, HTML, attachments and inline images are encrypted. Subjects, addresses, dates, message sizes and delivery information remain visible. Encrypted mail search uses visible metadata; decrypted bodies are not indexed. Sign-only messages remain readable by the mail server and recipients.++The reader labels encryption, signature validity and verified sender separately above the message; select the labels for an explanation of each and the signing key's fingerprint. A valid signature establishes that a key signed the content; it does not by itself establish who owns the key. Compare fingerprints through another channel and choose **It matches, mark as verified** when you have done so. Messages that can't be shown explain why: locked keys, a key missing from this device, or failed integrity. An integrity failure blocks content and attachments. Invalid signatures produce a warning. Decrypted HTML uses the normal reader sanitation, and remote content stays blocked until you explicitly permit it for that message.++## Drafts and sending++Only drafts with encryption selected are protected locally. Their bodies and staged attachments are saved in the main-process encrypted vault; their server copies are PGP/MIME encrypted to your own key. Ordinary drafts and sign-only drafts retain their existing storage behavior. The server draft's encrypted revision is compared without replacing ciphertext with an ordinary body.++If an earlier autosave was unencrypted, the composer warns you. Encrypting a replacement cannot erase server backups, revision history, other clients' caches or earlier deliveries. Original files you choose as attachments remain in their original location; Inlark protects its staged copies. Explicitly saving a decrypted attachment exports ordinary content to the location you choose.++Inlark encrypts outgoing mail to every recipient and your own key and signs it by default. Bcc addresses are removed from delivered headers and gossip, and recipient key IDs are anonymized when Bcc is used. SMTP and JMAP delivery use an explicit envelope. Prepared messages are persisted before submission. Existing partial-delivery, unconfirmed-send and Sent-copy recovery continue without automatic retransmission.++## Discovery and device transfer++Inlark prefers your accepted key. Without one it checks the recipient's WKD directory, then available Autocrypt information. A first usable key can be used while labeled unconfirmed. Multiple candidates require a choice. A changed fingerprint always requires review; old keys are preserved. Refreshing the same fingerprint updates its certifications and revocations without treating it as a replacement.++For enabled identities, recipient checks can read Autocrypt headers from up to 40 recent matching messages, including unopened mail, without downloading their bodies. These lookups are cached for two minutes. **Settings → Encryption → Contacts’ keys** lists the keys found so far and looks up any address; a contact's key dialog shows where each key came from, lets you choose between changed or conflicting keys, mark a key as verified, and **Check again**. Disabled identities do not trigger automatic discovery.++Autocrypt advertises no encryption preference until you explicitly select **Prefer encrypted mail**. Peer state follows message chronology, ignores malformed or wrong-address headers and stops recommending stale preferences. Gossip is included only inside encrypted mail and only for visible recipients. Inlark deliberately requires review for changed fingerprints, which is stricter than ordinary automatic Autocrypt key replacement.++**Move to another device…** exports an Autocrypt Setup Message only when you initiate it. Keep the generated numeric code separate from the message. On the other device, choose **Transfer from another device**, enter that code and choose the message to restore the key and its encryption preference. Inlark never distributes private keys automatically.++WKD discovers public keys; Inlark does not publish a directory. Domain administrators can use **Export public key…** and publish a binary key under the advanced or direct WKD path, together with the domain's policy file. Follow the [WKD discovery specification](https://www.ietf.org/archive/id/draft-koch-openpgp-webkey-service-20.html) for address hashing, directory layout and HTTPS requirements. Key exports are ASCII armored; convert to binary before publishing.++## Implementation and release checks++The shared `@inlark/crypto` package runs OpenPGP.js in a dedicated desktop worker. Private keys never enter the renderer. The versioned vault uses Node AES-256-GCM with a random 32-byte key, fresh 12-byte nonces, 16-byte authentication tags and authenticated vault/record identity and version. Password fallback uses asynchronous scrypt with a random 32-byte salt, `N=131072`, `r=8`, `p=1` and a 256 MiB memory allowance. Atomic writes authenticate all records before exposing plaintext.++MIME input and decompressed messages are bounded to 64 MiB, individual key input and WKD responses to 1 MiB, Autocrypt headers to 10 KiB, and the serialized local vault to 256 MiB. Content beyond these limits requires a smaller message or another client. No hosted service or telemetry is involved. S/MIME, hardware tokens, system GnuPG integration, subject encryption and encrypted-body search are outside this implementation.++Run:++```sh+pnpm check+pnpm test:packaged-crypto+pnpm test:crypto-interop # requires GnuPG+pnpm test:stalwart # disposable server; requires Podman or Docker+```++After building a Linux unpacked distribution, verify its ASAR worker with its own runtime:++```sh+INLARK_CRYPTO_WORKER_DIRECTORY=apps/desktop/release/linux-unpacked/resources/app.asar/out/main \+ELECTRON_RUN_AS_NODE=1 apps/desktop/release/linux-unpacked/inlark \+ scripts/test-crypto-worker.mjs --gnupg+```++Automated coverage includes GnuPG fixtures, hidden recipients, integrity and signature failures, retired keys, vault tampering and restoration, protected draft crash recovery and tombstones, WKD fallback and address matching, key-change blocking, stale Autocrypt state, and Setup Message restoration. Stalwart tests exercise raw encrypted MIME through IMAP APPEND/SMTP and JMAP upload/import/submission. Tests inspect protected draft uploads and persisted vault/stub files for plaintext markers.++Release remains gated on Thunderbird interoperability, packaged keyring/password/backup tests on Linux, Windows and macOS, and an end-to-end plaintext inspection of IndexedDB, notifications, diagnostics, attachment staging and network uploads in those packaged environments. The browser demo does not perform cryptography and cannot validate secure OS storage. Do not publish this feature as release-ready until those checks pass.diff --git a/nix/package.nix b/nix/package.nixindex efc2df8..4de2886 100644--- a/nix/package.nix+++ b/nix/package.nix@@ -12,7 +12,7 @@ stdenv.mkDerivation (finalAttrs: {pnpm = pnpm_12;fetcherVersion = 4;postPatch = "sed -i /storeDir:/d pnpm-workspace.yaml";- hash = "sha256-E9aHE/vWKOG4O5BzkvqmmkHF/emZ6yDfhlA8+OGd4Ek=";+ hash = "sha256-VKMs8tV1e+e2cvebQT8vptqqg56P4NOj0gaqW9xxFrw=";};postPatch = "sed -i /storeDir:/d pnpm-workspace.yaml";ELECTRON_SKIP_BINARY_DOWNLOAD = "1";diff --git a/package.json b/package.jsonindex 55a957c..4df1fdb 100644--- a/package.json+++ b/package.json@@ -16,7 +16,9 @@"test:stalwart": "node scripts/stalwart-test.mjs","format": "prettier --write .","format:check": "prettier --check .",- "test:deb": "bash scripts/test-deb.sh"+ "test:deb": "bash scripts/test-deb.sh",+ "test:packaged-crypto": "pnpm build && node scripts/test-crypto-worker.mjs",+ "test:crypto-interop": "pnpm build && node scripts/test-crypto-worker.mjs --gnupg"},"devDependencies": {"@types/node": "^24.0.0",diff --git a/packages/core/src/mail.ts b/packages/core/src/mail.tsindex 943a614..02bd11d 100644--- a/packages/core/src/mail.ts+++ b/packages/core/src/mail.ts@@ -86,6 +86,7 @@ export function mergePages(}/** Identifies a server draft's content, to detect edits made by another client. */export function draftFingerprint(message: Message): string {+ if (message.protectedRevision) return message.protectedRevisionreturn JSON.stringify([message.subject,message.to,diff --git a/packages/core/src/model.ts b/packages/core/src/model.tsindex 56237f6..f868afd 100644--- a/packages/core/src/model.ts+++ b/packages/core/src/model.ts@@ -108,6 +108,14 @@ export interface Attachment {cid?: stringdisposition?: string}+export interface MailSecurity {+ encrypted: boolean+ state: 'decrypted' | 'locked' | 'missingKey' | 'integrityFailure' | 'signed'+ signature: 'valid' | 'invalid' | 'unknown' | 'unsigned'+ fingerprint?: string+ confirmed: boolean+ detail?: string+}export interface Message {id: stringaccountId: string@@ -132,6 +140,10 @@ export interface Message {inReplyTo?: string[]references?: string[]unsubscribe?: { url: string; oneClick: boolean }+ security?: MailSecurity+ /** Revision of ciphertext, never a decrypted-body fingerprint. */+ protectedRevision?: string+ encryptionIntent?: boolean}export interface Conversation {id: string@@ -202,6 +214,10 @@ export interface Draft {replyThreadId?: stringserverId?: stringserverFingerprint?: string+ encryption?: 'none' | 'encrypt' | 'sign'+ encryptionRequired?: boolean+ downgradeConfirmed?: boolean+ earlierPlaintext?: booleanstatus: 'local' | 'saving' | 'synced' | 'error' | 'sending' | 'uncertain' | 'sent'error?: string/** What kind of problem `error` describes, so the composer can offer the right recovery. */@@ -468,9 +484,25 @@ export interface MailProvider {): Promise<void>upload(account: Account, data: Uint8Array, type: string): Promise<string>download(account: Account, attachment: Attachment): Promise<Uint8Array>- createDraft(account: Account, draft: Draft, messageId?: string): Promise<string>+ rawMessage?(account: Account, messageId: string, maxBytes: number): Promise<Uint8Array>+ /** Bounded recent header-only samples for Autocrypt, including messages without a key header. */+ encryptionHints?(+ account: Account,+ email: string,+ ): Promise<{ message: Message; headers: Uint8Array }[]>+ createDraft(+ account: Account,+ draft: Draft,+ messageId?: string,+ mime?: Uint8Array,+ ): Promise<string>/** Builds or stores the message to send. Must not transmit anything to recipients. */- prepareSubmission(account: Account, draft: Draft, messageId: string): Promise<OutgoingMessage>+ prepareSubmission(+ account: Account,+ draft: Draft,+ messageId: string,+ mime?: Uint8Array,+ ): Promise<OutgoingMessage>/*** Sends a prepared message once. Throws `submissionRejected` when nothing was accepted,* `submissionUncertain` when the outcome is unknown, and other codes when sending never began.@@ -490,6 +522,7 @@ export interface MailProvider {dispose(): void}export type AppEvent =+ | { type: 'encryption'; locked: boolean }| { type: 'unread'; count: number }| { type: 'changed'; accountId?: string }| { type: 'accounts'; accounts: Account[] }@@ -529,7 +562,88 @@ export interface Bootstrap {demo: booleanversion: string}+export interface EncryptionKeySummary {+ fingerprint: string+ email: string+ sources: ('own' | 'import' | 'wkd' | 'autocrypt' | 'gossip')[]+ confirmed: boolean+ accepted: boolean+ usable: boolean+ problem?: string+ publicKey: string+ retired?: boolean+ backup?: 'needed' | 'postponed' | 'done'+}+export interface EncryptionIdentity {+ accountId: string+ identityId: string+ email: string+ fingerprint: string+ enabled: boolean+ prefer: boolean+}+export interface EncryptionStatus {+ vault: 'absent' | 'locked' | 'unlocked'+ protection?: 'os' | 'password'+ identities: EncryptionIdentity[]+ keys: EncryptionKeySummary[]+}+export interface RecipientReadiness {+ email: string+ status: 'ready' | 'missing' | 'expired' | 'revoked' | 'unusable' | 'changed' | 'conflict'+ fingerprint?: string+ confirmed: boolean+ prefers: boolean+}+export interface EncryptionReadiness {+ senderReady: boolean+ recipients: RecipientReadiness[]+ recommend: boolean+}export interface DesktopMailAPI {+ encryptionStatus(): Promise<EncryptionStatus>+ setupEncryption(input: {+ accountId: string+ identityId: string+ action: 'create' | 'import' | 'replace' | 'historical'+ password?: string+ keyPassword?: string+ importReplacement?: boolean+ }): Promise<EncryptionStatus>+ setEncryptionPreference(+ accountId: string,+ identityId: string,+ enabled: boolean,+ prefer: boolean,+ ): Promise<EncryptionStatus>+ exportEncryptionKey(+ fingerprint: string,+ kind: 'public' | 'backup',+ password?: string,+ ): Promise<void>+ revokeEncryptionKey(fingerprint: string): Promise<EncryptionStatus>+ postponeEncryptionBackup(fingerprint: string): Promise<EncryptionStatus>+ discoverEncryptionKeys(email: string, refresh?: boolean): Promise<EncryptionKeySummary[]>+ acceptEncryptionKey(+ email: string,+ fingerprint: string,+ confirmed: boolean,+ ): Promise<EncryptionStatus>+ encryptionReadiness(+ accountId: string,+ identityId: string,+ recipients: string[],+ ): Promise<EncryptionReadiness>+ unlockEncryption(password?: string): Promise<EncryptionStatus>+ lockEncryption(): Promise<void>+ transferEncryption(input: {+ accountId: string+ identityId: string+ action: 'export' | 'import'+ code?: string+ password?: string+ }): Promise<{ code?: string }>+bootstrap(): Promise<Bootstrap>updateStatus(): Promise<UpdateStatus>ready(): Promise<void>@@ -562,7 +676,11 @@ export interface DesktopMailAPI {}): Promise<void>drafts(): Promise<Draft[]>resumeDraft(accountId: string, messageId: string): Promise<Draft>- stageRemoteAttachments(accountId: string, attachments: Attachment[]): Promise<StagedAttachment[]>+ stageRemoteAttachments(+ accountId: string,+ attachments: Attachment[],+ protectedDraft?: boolean,+ ): Promise<StagedAttachment[]>saveDraft(draft: Draft): Promise<Draft>syncDraft(draft: Draft): Promise<Draft>deleteDraft(id: string): Promise<void>@@ -578,10 +696,10 @@ export interface DesktopMailAPI {/** Starts a new draft from an unconfirmed send; the unconfirmed record is kept. */replaceUncertain(draftId: string): Promise<Draft>dismissSubmission(draftId: string): Promise<void>- stageAttachments(): Promise<StagedAttachment[]>+ stageAttachments(protectedDraft?: boolean): Promise<StagedAttachment[]>attachment(accountId: string, attachment: Attachment, open: boolean): Promise<void>inlineImage(accountId: string, attachment: Attachment): Promise<string>- remoteImage(url: string): Promise<string | null>+ remoteImage(url: string, userInitiated?: boolean): Promise<string | null>senderAvatar(email: string): Promise<string | null>unsubscribe(accountId: string,diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.tsindex c8f98bd..7d29e53 100644--- a/packages/core/src/schemas.ts+++ b/packages/core/src/schemas.ts@@ -170,6 +170,10 @@ export const draftSchema = z.object({replyThreadId: id.optional(),serverId: id.optional(),serverFingerprint: z.string().optional(),+ encryption: z.enum(['none', 'encrypt', 'sign']).optional(),+ encryptionRequired: z.boolean().optional(),+ downgradeConfirmed: z.boolean().optional(),+ earlierPlaintext: z.boolean().optional(),status: z.enum(['local', 'saving', 'synced', 'error', 'sending', 'uncertain', 'sent']),error: z.string().optional(),errorKind: z@@ -201,6 +205,43 @@ export const settingsSchema = z.object({.optional(),})export const ipcSchemas = {+ encryptionStatus: z.tuple([]),+ setupEncryption: z.tuple([+ z.object({+ accountId: id,+ identityId: id,+ action: z.enum(['create', 'import', 'replace', 'historical']),+ importReplacement: z.boolean().optional(),+ password: z.string().max(4096).optional(),+ keyPassword: z.string().max(4096).optional(),+ }),+ ]),+ setEncryptionPreference: z.tuple([id, id, z.boolean(), z.boolean()]),+ exportEncryptionKey: z.tuple([+ z.string().regex(/^[a-f0-9]{40,64}$/),+ z.enum(['public', 'backup']),+ z.string().max(4096).optional(),+ ]),+ revokeEncryptionKey: z.tuple([z.string().regex(/^[a-f0-9]{40,64}$/)]),+ postponeEncryptionBackup: z.tuple([z.string().regex(/^[a-f0-9]{40,64}$/)]),+ discoverEncryptionKeys: z.tuple([z.email().max(320), z.boolean().optional()]),+ acceptEncryptionKey: z.tuple([+ z.email().max(320),+ z.string().regex(/^[a-f0-9]{40,64}$/),+ z.boolean(),+ ]),+ encryptionReadiness: z.tuple([id, id, z.array(z.email().max(320)).max(600)]),+ unlockEncryption: z.tuple([z.string().max(4096).optional()]),+ lockEncryption: z.tuple([]),+ transferEncryption: z.tuple([+ z.object({+ accountId: id,+ identityId: id,+ action: z.enum(['export', 'import']),+ code: z.string().max(4096).optional(),+ password: z.string().max(4096).optional(),+ }),+ ]),bootstrap: z.tuple([]),updateStatus: z.tuple([]),ready: z.tuple([]),@@ -232,7 +273,7 @@ export const ipcSchemas = {}),]),resumeDraft: z.tuple([id, id]),- stageRemoteAttachments: z.tuple([id, z.array(attachmentSchema).max(100)]),+ stageRemoteAttachments: z.tuple([id, z.array(attachmentSchema).max(100), z.boolean().optional()]),drafts: z.tuple([]),saveDraft: z.tuple([draftSchema]),syncDraft: z.tuple([draftSchema]),@@ -245,10 +286,10 @@ export const ipcSchemas = {recoverRejected: z.tuple([z.string().uuid()]),replaceUncertain: z.tuple([z.string().uuid()]),dismissSubmission: z.tuple([z.string().uuid()]),- stageAttachments: z.tuple([]),+ stageAttachments: z.tuple([z.boolean().optional()]),attachment: z.tuple([id, attachmentSchema, z.boolean()]),inlineImage: z.tuple([id, attachmentSchema]),- remoteImage: z.tuple([z.string().url().max(8192)]),+ remoteImage: z.tuple([z.string().url().max(8192), z.boolean().optional()]),senderAvatar: z.tuple([z.string().trim().email().max(320)]),unsubscribe: z.tuple([id, id]),openExternal: z.tuple([z.string().max(8192)]),diff --git a/packages/crypto/package.json b/packages/crypto/package.jsonnew file mode 100644index 0000000..fcbc11e--- /dev/null+++ b/packages/crypto/package.json@@ -0,0 +1,18 @@+{+ "name": "@inlark/crypto",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "typecheck": "tsc -p tsconfig.json"+ },+ "dependencies": {+ "@inlark/mime": "workspace:*",+ "openpgp": "^6.3.0",+ "zod": "^4.0.0"+ }+}diff --git a/packages/crypto/src/discovery.ts b/packages/crypto/src/discovery.tsnew file mode 100644index 0000000..3be3798--- /dev/null+++ b/packages/crypto/src/discovery.ts@@ -0,0 +1,119 @@+import { createHash, randomInt } from 'node:crypto'+import { domainToASCII } from 'node:url'+export const canonicalEmail = (email: string) =>+ email.trim().replace(/[A-Z]/g, (c) => c.toLowerCase())+export function wkdUrls(email: string) {+ const at = email.lastIndexOf('@'),+ local = email.slice(0, at),+ domain = domainToASCII(email.slice(at + 1)).toLowerCase()+ if (at < 1 || !/^(?!-)[a-z0-9-]+(?:\.(?!-)[a-z0-9-]+)+$/.test(domain) || /[\s\r\n]/.test(local))+ throw new Error('Enter a valid email address for key discovery.')+ const digest = createHash('sha1').update(canonicalEmail(local), 'utf8').digest(),+ alphabet = 'ybndrfg8ejkmcpqxot1uwisza345h769'+ let hash = '',+ value = 0,+ bits = 0+ for (const byte of digest) {+ value = (value << 8) | byte+ bits += 8+ while (bits >= 5) {+ bits -= 5+ hash += alphabet[(value >>> bits) & 31]+ }+ }+ const tail = hash + '?l=' + encodeURIComponent(local)+ return {+ advanced: `https://openpgpkey.${domain}/.well-known/openpgpkey/${domain}/hu/${tail}`,+ direct: `https://${domain}/.well-known/openpgpkey/hu/${tail}`,+ host: 'openpgpkey.' + domain,+ }+}+export interface AutocryptHeader {+ email: string+ mutual: boolean+ data: Uint8Array+}+export function parseAutocrypt(value: string, sender?: string): AutocryptHeader | undefined {+ if (value.length + 12 > 10240 || /\r(?!\n)|\n(?![ \t])/.test(value)) return+ const fields = new Map<string, string>(),+ entries = value+ .replace(/\r?\n[ \t]+/g, ' ')+ .split(';')+ .map((s) => s.trim())+ .filter(Boolean)+ for (let i = 0; i < entries.length; i++) {+ const entry = entries[i],+ equal = entry.indexOf('=')+ if (equal < 1) return+ const name = entry.slice(0, equal).trim().toLowerCase(),+ data = entry.slice(equal + 1).trim()+ if (+ fields.has(name) ||+ (!['addr', 'prefer-encrypt', 'keydata'].includes(name) && !name.startsWith('_')) ||+ (name === 'keydata' && i !== entries.length - 1)+ )+ return+ fields.set(name, data)+ }+ const email = canonicalEmail(fields.get('addr') || ''),+ encoded = (fields.get('keydata') || '').replace(/\s/g, '')+ if (+ !/^[^\s<>@]+@[^\s<>@]+$/.test(email) ||+ (sender && email !== canonicalEmail(sender)) ||+ !encoded ||+ !/^[a-z\d+/]+={0,2}$/i.test(encoded)+ )+ return+ const data = Buffer.from(encoded, 'base64')+ if (data.toString('base64') !== encoded) return+ return { email, mutual: fields.get('prefer-encrypt') === 'mutual', data }+}+export function autocryptHeader(+ email: string,+ binary: Uint8Array,+ mutual: boolean,+ gossip = false,+): string {+ if (!/^[^\s<>;@]+@[^\s<>;@]+$/.test(email)) throw new Error('Invalid Autocrypt address.')+ const value = `${gossip ? 'Autocrypt-Gossip' : 'Autocrypt'}: addr=${email}; ${mutual && !gossip ? 'prefer-encrypt=mutual; ' : ''}keydata=${Buffer.from(binary).toString('base64')}`+ if (value.length > 9000) throw new Error('This key is too large to advertise through Autocrypt.')+ // Header lines below RFC 5322's hard limit, folding only inside base64 keydata.+ const split = value.indexOf('keydata=') + 8+ return value.slice(0, split) + (value.slice(split).match(/.{1,72}/g) || []).join('\r\n ')+}+export interface PeerState {+ lastSeen?: string+ autocryptAt?: string+ gossipAt?: string+ fingerprint?: string+ gossipFingerprint?: string+ mutual?: boolean+}+export function peerUpdate(+ old: PeerState,+ receivedAt: string,+ sentAt: string | undefined,+ valid?: { fingerprint: string; mutual: boolean },+): PeerState {+ const received = Date.parse(receivedAt),+ sent = Date.parse(sentAt || ''),+ date = new Date(Number.isFinite(sent) ? Math.min(sent, received) : received).toISOString()+ if (old.autocryptAt && date < old.autocryptAt) return old+ return {+ ...old,+ lastSeen: old.lastSeen && old.lastSeen > date ? old.lastSeen : date,+ ...(valid && (!old.autocryptAt || date > old.autocryptAt)+ ? { autocryptAt: date, fingerprint: valid.fingerprint, mutual: valid.mutual }+ : {}),+ }+}+export function peerPrefersEncryption(peer?: PeerState) {+ return !!(+ peer?.mutual &&+ peer.autocryptAt &&+ peer.lastSeen &&+ Date.parse(peer.lastSeen) - Date.parse(peer.autocryptAt) <= 35 * 86400_000+ )+}+export const setupCode = () =>+ Array.from({ length: 9 }, () => String(randomInt(10000)).padStart(4, '0')).join('-')diff --git a/packages/crypto/src/engine.ts b/packages/crypto/src/engine.tsnew file mode 100644index 0000000..6e4e9da--- /dev/null+++ b/packages/crypto/src/engine.ts@@ -0,0 +1,297 @@+import * as pgp from 'openpgp'++export interface KeyInfo {+ fingerprint: string+ emails: string[]+ publicKey: string+ binary: Uint8Array+ usable: boolean+ problem?: 'expired' | 'revoked' | 'unusable'+}+export interface PrivateRecord {+ privateKey: string+ publicKey: string+ fingerprint: string+ revocationCertificate?: string+ transferPreference?: boolean+}+const config: pgp.PartialConfig = {+ v6Keys: false,+ allowUnauthenticatedMessages: false,+ allowUnauthenticatedStream: false,+ maxDecompressedMessageSize: 64 * 1024 * 1024,+ aeadProtect: false,+ s2kType: pgp.enums.s2k.iterated,+ preferredSymmetricAlgorithm: pgp.enums.symmetric.aes256,+}+const normalize = (email: string) => email.trim().toLowerCase()++/** Runs only in the desktop's dedicated worker. Private key objects never leave it. */+export class CryptoEngine {+ private keys: pgp.PrivateKey[] = []+ async load(records: PrivateRecord[]) {+ const keys = await Promise.all(+ records.map((r) => pgp.readPrivateKey({ armoredKey: r.privateKey })),+ )+ if (keys.some((k) => !k.isDecrypted()))+ throw new Error('An imported private key is still locked.')+ this.keys = keys+ }+ lock() {+ this.keys = []+ }+ async inspect(data: string | Uint8Array, email?: string): Promise<KeyInfo[]> {+ if ((typeof data === 'string' ? data.length : data.byteLength) > 1024 * 1024)+ throw new Error('Key data is too large.')+ const keys = await (typeof data === 'string'+ ? pgp.readKeys({ armoredKeys: data })+ : pgp.readKeys({ binaryKeys: data }))+ if (!keys.length || keys.length > 20) throw new Error('No supported public key was found.')+ return Promise.all(+ keys.map(async (key) => {+ const emails: string[] = []+ // Only self-certified user IDs, not untrusted user-id packet text, establish an address.+ for (const user of key.users) {+ const address = user.userID?.email+ if (address) {+ try {+ await user.verify()+ emails.push(normalize(address))+ } catch {+ for (const certificate of user.selfCertifications) {+ try {+ await user.verify(+ new Date((certificate.created || key.getCreationTime()).getTime() + 1000),+ )+ emails.push(normalize(address))+ break+ } catch {+ /* Ignore uncertified IDs. */+ }+ }+ }+ }+ }+ if (email && !emails.includes(normalize(email)))+ throw new Error('This key does not match the email address.')+ let problem: KeyInfo['problem']+ if (await key.isRevoked()) problem = 'revoked'+ else {+ const expires = await key.getExpirationTime()+ if (expires !== Infinity && (!expires || expires <= new Date())) problem = 'expired'+ else+ try {+ await key.getEncryptionKey(+ undefined,+ new Date(),+ email ? { email: normalize(email) } : undefined,+ )+ } catch {+ problem = 'unusable'+ }+ }+ const publicKey = key.toPublic()+ return {+ fingerprint: key.getFingerprint(),+ emails: [...new Set(emails)],+ publicKey: publicKey.armor(),+ binary: publicKey.write(),+ usable: !problem,+ ...(problem ? { problem } : {}),+ }+ }),+ )+ }+ async autocryptKey(armoredKey: string, email: string): Promise<Uint8Array> {+ const key = await pgp.readKey({ armoredKey }),+ primary = await key.getPrimaryUser(undefined, { email: normalize(email) }),+ encryption = await key.getEncryptionKey(undefined, new Date(), { email: normalize(email) })+ if (!(encryption instanceof pgp.Subkey) || !primary.user.userID)+ throw new Error('Autocrypt requires an encryption subkey and an email user ID.')+ const packets = new pgp.PacketList<pgp.AnyPacket>()+ packets.push(+ key.toPublic().keyPacket,+ primary.user.userID,+ primary.selfCertification,+ encryption.keyPacket,+ await encryption.verify(),+ )+ return packets.write()+ }+ async mergePublic(old: string, incoming: string): Promise<string> {+ const key = await pgp.readKey({ armoredKey: old }),+ next = await pgp.readKey({ armoredKey: incoming })+ if (key.getFingerprint() !== next.getFingerprint())+ throw new Error('Different key fingerprints cannot be merged.')+ return (await key.update(next)).toPublic().armor()+ }+ async generate(name: string, email: string): Promise<PrivateRecord> {+ const result = await pgp.generateKey({+ type: 'ecc',+ curve: 'ed25519Legacy',+ userIDs: [{ name, email: normalize(email) }],+ subkeys: [{ curve: 'curve25519Legacy' }],+ format: 'armored',+ config,+ })+ const key = await pgp.readPrivateKey({ armoredKey: result.privateKey })+ return { ...result, fingerprint: key.getFingerprint() }+ }+ async importPrivate(+ armored: string,+ email: string,+ password?: string,+ historical = false,+ ): Promise<PrivateRecord> {+ if (armored.length > 1024 * 1024) throw new Error('Key data is too large.')+ let key = await pgp.readPrivateKey({ armoredKey: armored })+ if (!key.isDecrypted())+ key = await pgp.decryptKey({ privateKey: key, passphrase: password || '' })+ await this.inspect(key.toPublic().armor(), email)+ if (!historical) await key.getSigningKey(undefined, new Date(), { email: normalize(email) })+ return {+ privateKey: key.armor(),+ publicKey: key.toPublic().armor(),+ fingerprint: key.getFingerprint(),+ }+ }+ async backup(fingerprint: string, password: string): Promise<string> {+ if (password.length < 10) throw new Error('Use a backup password of at least 10 characters.')+ const key = this.keys.find((k) => k.getFingerprint() === fingerprint)+ if (!key) throw new Error('Unlock the vault containing this key.')+ return (await pgp.encryptKey({ privateKey: key, passphrase: password })).armor()+ }+ async revoke(fingerprint: string): Promise<string> {+ const key = this.keys.find((k) => k.getFingerprint() === fingerprint)+ if (!key) throw new Error('Unlock the vault containing this key.')+ return (await pgp.revokeKey({ key, format: 'armored' })).publicKey+ }+ async encrypt(+ data: Uint8Array,+ publicKeys: string[],+ signer?: string,+ hidden = false,+ ): Promise<string> {+ const encryptionKeys = await Promise.all(+ publicKeys.map((armoredKey) => pgp.readKey({ armoredKey })),+ )+ if (!encryptionKeys.length) throw new Error('No encryption keys are available.')+ const signingKey = signer ? this.keys.find((k) => k.getFingerprint() === signer) : undefined+ if (signer && !signingKey) throw new Error('Unlock the sender’s private key.')+ return pgp.encrypt({+ message: await pgp.createMessage({ binary: data }),+ encryptionKeys,+ ...(signingKey ? { signingKeys: signingKey } : {}),+ wildcard: hidden,+ format: 'armored',+ config,+ })+ }+ async sign(data: Uint8Array, fingerprint: string): Promise<string> {+ const key = this.keys.find((k) => k.getFingerprint() === fingerprint)+ if (!key) throw new Error('Unlock the sender’s private key.')+ return pgp.sign({+ message: await pgp.createMessage({ binary: data }),+ signingKeys: key,+ detached: true,+ format: 'armored',+ config: { ...config, preferredHashAlgorithm: pgp.enums.hash.sha256 },+ })+ }+ async verify(data: Uint8Array, signature: string, publicKeys: string[]) {+ const verificationKeys = await Promise.all(+ publicKeys.map((armoredKey) => pgp.readKey({ armoredKey })),+ )+ const result = await pgp.verify({+ message: await pgp.createMessage({ binary: data }),+ signature: await pgp.readSignature({ armoredSignature: signature }),+ verificationKeys,+ format: 'binary',+ config,+ })+ return this.signatures(result.signatures, verificationKeys)+ }+ private async signatures(signatures: pgp.VerifyMessageResult['signatures'], keys: pgp.Key[]) {+ return Promise.all(+ signatures.map(async (signature) => {+ const key = keys.find((k) =>+ k.getKeys().some((sub) => sub.getKeyID().equals(signature.keyID)),+ )+ let valid = false+ try {+ await signature.verified+ valid = true+ } catch {+ /* Signature warnings do not bypass message integrity. */+ }+ return { valid, fingerprint: key?.getFingerprint(), keyId: signature.keyID.toHex() }+ }),+ )+ }+ async decrypt(armored: string, publicKeys: string[]) {+ if (!this.keys.length)+ throw new Error(+ 'No private key for this message is available. Import the original key or unlock the vault.',+ )+ const verificationKeys = await Promise.all(+ publicKeys.map((armoredKey) => pgp.readKey({ armoredKey })),+ )+ const result = await pgp.decrypt({+ message: await pgp.readMessage({ armoredMessage: armored }),+ decryptionKeys: this.keys,+ verificationKeys,+ format: 'binary',+ config,+ })+ return {+ data: result.data,+ signatures: await this.signatures(result.signatures, verificationKeys),+ }+ }+ async verifyInline(armored: string, publicKeys: string[]) {+ const verificationKeys = await Promise.all(+ publicKeys.map((armoredKey) => pgp.readKey({ armoredKey })),+ )+ const result = await pgp.verify({+ message: await pgp.readCleartextMessage({ cleartextMessage: armored }),+ verificationKeys,+ config,+ })+ return {+ text: result.data,+ signatures: await this.signatures(result.signatures, verificationKeys),+ }+ }+ async setupExport(fingerprint: string, code: string, prefer = false) {+ const key = this.keys.find((k) => k.getFingerprint() === fingerprint)+ if (!key) throw new Error('Unlock the key before transferring it.')+ const backup = key+ .armor()+ .replace(+ '-----BEGIN PGP PRIVATE KEY BLOCK-----\n',+ '-----BEGIN PGP PRIVATE KEY BLOCK-----\nAutocrypt-Prefer-Encrypt: ' ++ (prefer ? 'mutual' : 'nopreference') ++ '\n',+ )+ return pgp.encrypt({+ message: await pgp.createMessage({ text: backup }),+ passwords: [code],+ format: 'armored',+ config,+ })+ }+ async setupImport(armored: string, code: string, email: string) {+ const result = await pgp.decrypt({+ message: await pgp.readMessage({ armoredMessage: armored }),+ passwords: [code],+ format: 'utf8',+ config,+ })+ const record = await this.importPrivate(result.data, email, code)+ return {+ ...record,+ transferPreference: /^Autocrypt-Prefer-Encrypt:\s*mutual\s*$/m.test(result.data),+ }+ }+}+export type CryptoMethods = { [K in keyof CryptoEngine]: CryptoEngine[K] }diff --git a/packages/crypto/src/index.ts b/packages/crypto/src/index.tsnew file mode 100644index 0000000..e9cb872--- /dev/null+++ b/packages/crypto/src/index.ts@@ -0,0 +1,4 @@+export * from './vault'+export * from './engine'+export * from './mime'+export * from './discovery'diff --git a/packages/crypto/src/mime.ts b/packages/crypto/src/mime.tsnew file mode 100644index 0000000..5c002bc--- /dev/null+++ b/packages/crypto/src/mime.ts@@ -0,0 +1,145 @@+import { randomBytes } from 'node:crypto'++export const maxMessageBytes = 64 * 1024 * 1024+export interface MimeEntity {+ headers: Map<string, string[]>+ headerBytes: Buffer+ body: Buffer+}+/** Structural parsing only: signed bytes are never decoded, flattened, or reserialized. */+export function splitEntity(source: Uint8Array): MimeEntity {+ if (source.byteLength > maxMessageBytes) throw new Error('This message is too large to decrypt.')+ const raw = Buffer.from(source),+ end = raw.indexOf('\r\n\r\n')+ if (end < 0 || end > 128 * 1024) throw new Error('Invalid MIME headers.')+ const headerBytes = raw.subarray(0, end),+ headers = new Map<string, string[]>()+ for (const line of headerBytes+ .toString('latin1')+ .replace(/\r\n[ \t]+/g, ' ')+ .split('\r\n')) {+ const colon = line.indexOf(':')+ if (colon < 1) throw new Error('Invalid MIME header.')+ const name = line.slice(0, colon).toLowerCase(),+ values = headers.get(name) || []+ values.push(line.slice(colon + 1).trim())+ headers.set(name, values)+ }+ return { headers, headerBytes, body: raw.subarray(end + 4) }+}+export function header(entity: MimeEntity, name: string) {+ const values = entity.headers.get(name.toLowerCase()) || []+ if (values.length > 1) throw new Error('Ambiguous MIME security headers.')+ return values[0] || ''+}+export function securityKind(source: Uint8Array): 'encrypted' | 'signed' | undefined {+ const entity = splitEntity(source),+ type = header(entity, 'content-type')+ if (/^multipart\/encrypted\b/i.test(type)) return 'encrypted'+ if (/^multipart\/signed\b/i.test(type)) return 'signed'+ const body = /^text\/|^$/i.test(type) ? decodedBody(source) : entity.body+ if (body.includes(Buffer.from('-----BEGIN PGP MESSAGE-----'))) return 'encrypted'+ if (body.includes(Buffer.from('-----BEGIN PGP SIGNED MESSAGE-----'))) return 'signed'+}+export function multipart(source: Uint8Array): Buffer[] {+ const entity = splitEntity(source),+ type = header(entity, 'content-type')+ const boundary = type.match(/\bboundary\s*=\s*(?:"([^"\r\n]+)"|([^;\s]+))/i)+ const name = boundary?.[1] || boundary?.[2]+ if (!name || name.length > 70) throw new Error('Invalid MIME boundary.')+ const body = entity.body.toString('latin1'),+ marker = '--' + name,+ parts: Buffer[] = []+ const escaped = marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+ const matches = [+ ...body.matchAll(new RegExp('(?:^|\\r\\n)' + escaped + '(--)?[ \\t]*(?:\\r\\n|$)', 'g')),+ ]+ if (matches.length < 3 || !matches.at(-1)?.[1]) throw new Error('Incomplete MIME multipart.')+ for (let i = 0; i < matches.length - 1; i++) {+ if (matches[i][1]) throw new Error('Invalid MIME multipart.')+ // The CRLF introducing the next delimiter belongs to the boundary, not the signed part.+ const start = matches[i].index! + matches[i][0].length,+ end = matches[i + 1].index!+ parts.push(Buffer.from(body.slice(start, end), 'latin1'))+ }+ return parts+}+export function decodedBody(source: Uint8Array): Buffer {+ const entity = splitEntity(source),+ encoding = header(entity, 'content-transfer-encoding').toLowerCase()+ if (encoding === 'base64')+ return Buffer.from(entity.body.toString('ascii').replace(/\s/g, ''), 'base64')+ if (encoding === 'quoted-printable')+ return Buffer.from(+ entity.body+ .toString('latin1')+ .replace(/=\r\n/g, '')+ .replace(/=([\da-f]{2})/gi, (_, code) => String.fromCharCode(parseInt(code, 16))),+ 'latin1',+ )+ if (encoding && !['7bit', '8bit', 'binary'].includes(encoding))+ throw new Error('Unsupported MIME encoding.')+ return entity.body+}+export function armoredPayload(source: Uint8Array): string {+ const entity = splitEntity(source)+ if (/^multipart\/encrypted\b/i.test(header(entity, 'content-type'))) {+ if (!/\bprotocol\s*=\s*"?application\/pgp-encrypted"?/i.test(header(entity, 'content-type')))+ throw new Error('Unsupported encrypted message format.')+ const parts = multipart(source)+ if (+ parts.length !== 2 ||+ !/^application\/pgp-encrypted\b/i.test(header(splitEntity(parts[0]), 'content-type')) ||+ !/^application\/octet-stream\b/i.test(header(splitEntity(parts[1]), 'content-type')) ||+ !/^Version: 1\s*$/i.test(decodedBody(parts[0]).toString().trim())+ )+ throw new Error('Invalid PGP/MIME envelope.')+ return decodedBody(parts[1]).toString('utf8').trim()+ }+ const text = decodedBody(source).toString('utf8')+ const armor = text.match(/-----BEGIN PGP MESSAGE-----[\s\S]*?-----END PGP MESSAGE-----/)+ if (!armor) throw new Error('No encrypted content was found.')+ return armor[0]+}+export function mimeContent(source: Uint8Array): Buffer {+ const entity = splitEntity(source)+ const headers = entity.headerBytes+ .toString('latin1')+ .split(/\r\n(?=[^ \t])/)+ .filter((line) => /^content-/i.test(line))+ return Buffer.concat([Buffer.from(headers.join('\r\n') + '\r\n\r\n', 'latin1'), entity.body])+}+export function replaceContent(+ source: Uint8Array,+ content: Uint8Array,+ extra: string[] = [],+): Buffer {+ const entity = splitEntity(source)+ const headers = entity.headerBytes+ .toString('latin1')+ .split(/\r\n(?=[^ \t])/)+ .filter((line) => !/^(content-|mime-version:|bcc:)/i.test(line))+ return Buffer.concat([+ Buffer.from([...headers, 'MIME-Version: 1.0', ...extra].join('\r\n') + '\r\n', 'latin1'),+ Buffer.from(content),+ ])+}+const boundary = () => 'inlark-' + randomBytes(18).toString('hex')+export function encryptedMime(armor: string): Buffer {+ const b = boundary()+ return Buffer.from(+ `Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${b}"\r\n\r\n--${b}\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--${b}\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\nContent-Disposition: inline; filename="encrypted.asc"\r\n\r\n${armor.trim().replace(/\r?\n/g, '\r\n')}\r\n--${b}--\r\n`,+ )+}+export function signedMime(content: Uint8Array, signature: string): Buffer {+ const b = boundary()+ return Buffer.concat([+ Buffer.from(+ `Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${b}"\r\n\r\n--${b}\r\n`,+ ),+ Buffer.from(content),+ Buffer.from(+ `\r\n--${b}\r\nContent-Type: application/pgp-signature; name="signature.asc"\r\n\r\n${signature.trim().replace(/\r?\n/g, '\r\n')}\r\n--${b}--\r\n`,+ ),+ ])+}diff --git a/packages/crypto/src/vault.ts b/packages/crypto/src/vault.tsnew file mode 100644index 0000000..445e1ff--- /dev/null+++ b/packages/crypto/src/vault.ts@@ -0,0 +1,273 @@+import { createCipheriv, createDecipheriv, randomBytes, randomUUID, scrypt } from 'node:crypto'+import { mkdir, open, rename, rm, link } from 'node:fs/promises'+import { dirname } from 'node:path'+import { z } from 'zod'++const encoded = z+ .string()+ .max(180_000_000)+ .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)+const boxSchema = z.object({ nonce: encoded, tag: encoded, data: encoded }).strict()+type Box = z.infer<typeof boxSchema>+const headerSchema = z.discriminatedUnion('mode', [+ z.object({ mode: z.literal('password'), salt: encoded, key: boxSchema }).strict(),+ z.object({ mode: z.literal('os'), key: encoded }).strict(),+])+const schema = z+ .object({+ version: z.literal(1),+ id: z.string().uuid(),+ protection: headerSchema,+ records: z.record(z.string().min(1).max(4096), boxSchema),+ })+ .strict()+type Document = z.infer<typeof schema>+export interface SecureStorage {+ available(): boolean+ wrap(value: string): string+ unwrap(value: string): string+}+const aad = (vaultId: string, record: string) =>+ Buffer.from(JSON.stringify(['inlark-vault', 1, vaultId, record]))+const bytes = (text: string, size?: number) => {+ const value = Buffer.from(text, 'base64')+ if (value.toString('base64') !== text || (size !== undefined && value.length !== size))+ throw new Error('Invalid vault data. Your files have been preserved.')+ return value+}+export function seal(key: Uint8Array, plaintext: Uint8Array, identity: Uint8Array): Box {+ const nonce = randomBytes(12)+ const cipher = createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 })+ cipher.setAAD(identity)+ return {+ nonce: nonce.toString('base64'),+ data: Buffer.concat([cipher.update(plaintext), cipher.final()]).toString('base64'),+ tag: cipher.getAuthTag().toString('base64'),+ }+}+export function unseal(key: Uint8Array, box: Box, identity: Uint8Array): Buffer {+ const decipher = createDecipheriv('aes-256-gcm', key, bytes(box.nonce, 12), { authTagLength: 16 })+ decipher.setAAD(identity)+ decipher.setAuthTag(bytes(box.tag, 16))+ // No plaintext is returned until final() authenticates the complete record.+ const partial = decipher.update(bytes(box.data))+ try {+ return Buffer.concat([partial, decipher.final()])+ } finally {+ partial.fill(0)+ }+}+async function derive(password: string, salt: Buffer): Promise<Buffer> {+ if (!password || password.length > 4096) throw new Error('Enter a vault password.')+ return new Promise((resolve, reject) =>+ scrypt(+ password,+ salt,+ 32,+ { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 },+ (error, key) => (error ? reject(error) : resolve(key)),+ ),+ )+}++/** One atomically replaced, authenticated snapshot. Missing or unreadable storage never recreates it. */+export class Vault {+ private document?: Document+ private key?: Buffer+ private queue = Promise.resolve()+ constructor(+ readonly path: string,+ private secure?: SecureStorage,+ ) {}+ get exists() {+ return !!this.document+ }+ get unlocked() {+ return !!this.key+ }+ get mode() {+ return this.document?.protection.mode+ }+ async init() {+ try {+ const file = await open(this.path, 'r')+ try {+ if ((await file.stat()).size > 256 * 1024 * 1024)+ throw new Error('Vault exceeds the supported size.')+ this.document = schema.parse(JSON.parse(await file.readFile('utf8')))+ } finally {+ await file.close()+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw new Error('Could not read the encryption vault. Your files have been preserved.')+ }+ }+ async create(password?: string) {+ // Explicit creation only. Exclusive file creation prevents racing an existing vault.+ if (this.exists) throw new Error('An encryption vault already exists. Unlock it instead.')+ const key = randomBytes(32),+ id = randomUUID()+ let protection: Document['protection']+ try {+ if (this.secure?.available())+ protection = { mode: 'os', key: this.secure.wrap(key.toString('base64')) }+ else {+ if (!password || password.length < 10)+ throw new Error(+ 'Use a vault password of at least 10 characters when secure OS storage is unavailable.',+ )+ const salt = randomBytes(32),+ wrapping = await derive(password, salt)+ try {+ protection = {+ mode: 'password',+ salt: salt.toString('base64'),+ key: seal(wrapping, key, aad(id, 'vault-key')),+ }+ } finally {+ wrapping.fill(0)+ }+ }+ const doc: Document = {+ version: 1,+ id,+ protection,+ records: { check: seal(key, Buffer.from('Inlark vault'), aad(id, 'check')) },+ }+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 })+ const temporary = this.path + '.' + randomUUID() + '.tmp'+ try {+ const file = await open(temporary, 'wx', 0o600)+ try {+ await file.writeFile(JSON.stringify(doc))+ await file.sync()+ } finally {+ await file.close()+ }+ await link(temporary, this.path)+ if (process.platform !== 'win32') {+ const directory = await open(dirname(this.path), 'r')+ try {+ await directory.sync()+ } finally {+ await directory.close()+ }+ }+ } finally {+ await rm(temporary, { force: true })+ }+ this.document = doc+ this.key = key+ } catch (error) {+ key.fill(0)+ throw error+ }+ }+ async unlock(password?: string) {+ if (!this.document) throw new Error('Set up encryption first.')+ if (this.key) return+ const doc = this.document+ let key: Buffer | undefined+ try {+ if (doc.protection.mode === 'os') {+ if (!this.secure?.available())+ throw new Error('Unlock your OS keyring. The existing vault cannot be replaced.')+ key = bytes(this.secure.unwrap(doc.protection.key), 32)+ } else {+ const wrapping = await derive(password || '', bytes(doc.protection.salt, 32))+ try {+ key = unseal(wrapping, doc.protection.key, aad(doc.id, 'vault-key'))+ } finally {+ wrapping.fill(0)+ }+ }+ if (+ key.length !== 32 ||+ !doc.records.check ||+ unseal(key, doc.records.check, aad(doc.id, 'check')).toString() !== 'Inlark vault'+ )+ throw new Error('Invalid vault.')+ // Authenticate every record before accepting an unlock, including historical private keys.+ for (const [id, box] of Object.entries(doc.records)) unseal(key, box, aad(doc.id, id)).fill(0)+ this.key = key+ } catch (error) {+ key?.fill(0)+ if (doc.protection.mode === 'os') throw error+ throw new Error(+ 'The password is incorrect or the vault was damaged. Your files have been preserved.',+ )+ }+ }+ async lock() {+ await this.queue+ this.key?.fill(0)+ this.key = undefined+ }+ ids(prefix: string) {+ return Object.keys(this.document?.records ?? {}).filter((id) => id.startsWith(prefix))+ }+ read(id: string): Buffer | undefined {+ if (!this.key || !this.document) throw new Error('Unlock the encryption vault first.')+ const box = this.document.records[id]+ return box ? unseal(this.key, box, aad(this.document.id, id)) : undefined+ }+ json<T>(id: string): T | undefined {+ const data = this.read(id)+ if (!data) return+ try {+ return JSON.parse(data.toString()) as T+ } finally {+ data.fill(0)+ }+ }+ put(id: string, value: Uint8Array | undefined) {+ return this.putMany([[id, value]])+ }+ putJSON(id: string, value: unknown) {+ return this.put(id, Buffer.from(JSON.stringify(value)))+ }+ putMany(values: [string, Uint8Array | undefined][]): Promise<void> {+ if (!this.key || !this.document)+ return Promise.reject(new Error('Unlock the encryption vault first.'))+ const encrypted = values.map(([id, data]) => {+ if (!id || id === 'check' || id.length > 4096) throw new Error('Invalid vault record.')+ return [id, data ? seal(this.key!, data, aad(this.document!.id, id)) : undefined] as const+ })+ const operation = this.queue.then(async () => {+ if (!this.document || !this.key) throw new Error('The vault is locked.')+ const doc = structuredClone(this.document)+ for (const [id, box] of encrypted) {+ if (box) doc.records[id] = box+ else delete doc.records[id]+ }+ const serialized = JSON.stringify(doc)+ if (Buffer.byteLength(serialized) > 256 * 1024 * 1024)+ throw new Error('The encryption vault is full. Your existing data has been preserved.')+ const temporary = this.path + '.' + randomUUID() + '.tmp'+ try {+ const file = await open(temporary, 'wx', 0o600)+ try {+ await file.writeFile(serialized)+ await file.sync()+ } finally {+ await file.close()+ }+ await rename(temporary, this.path)+ this.document = doc+ if (process.platform !== 'win32') {+ const directory = await open(dirname(this.path), 'r')+ try {+ await directory.sync()+ } finally {+ await directory.close()+ }+ }+ } finally {+ await rm(temporary, { force: true })+ }+ })+ this.queue = operation.catch(() => {})+ return operation+ }+}diff --git a/packages/crypto/tsconfig.json b/packages/crypto/tsconfig.jsonnew file mode 100644index 0000000..4b7d0d2--- /dev/null+++ b/packages/crypto/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../tsconfig.json", "include": ["src"], "compilerOptions": { "types": ["node"] } }diff --git a/packages/imap/package.json b/packages/imap/package.jsonindex a4b8598..1e6b4f8 100644--- a/packages/imap/package.json+++ b/packages/imap/package.json@@ -14,7 +14,8 @@"@inlark/core": "workspace:*","imapflow": "^2.0.6","mailparser": "^3.9.28",- "nodemailer": "^10.0.10"+ "nodemailer": "^10.0.10",+ "@inlark/mime": "workspace:*"},"devDependencies": {"@types/mailparser": "^3.4.6",diff --git a/packages/imap/src/convert.ts b/packages/imap/src/convert.tsindex 9f4f6aa..068fe95 100644--- a/packages/imap/src/convert.ts+++ b/packages/imap/src/convert.ts@@ -92,6 +92,7 @@ export function attachmentsOf(message: IndexedMessage): Attachment[] {}/** The body parts to render, preferring those not marked as attachments. */export function textParts(structure?: BodyPart): { html?: BodyPart; text?: BodyPart } {+ if (structure?.type.toLowerCase() === 'multipart/encrypted') return {}const candidates = leaves(structure).filter((p) => isText(p) && p.disposition !== 'attachment')return {html: candidates.find((p) => p.type === 'text/html'),@@ -133,6 +134,7 @@ export function previewText(value: string, html = false): string {// Opening a message supplies the full body. Bound work here for every caller,// before any HTML processing, entity decoding, or line splitting.value = value.slice(0, previewInputLimit)+ if (value.includes('-----BEGIN PGP MESSAGE-----')) return ''const text = html? withoutHiddenBlocks(value).replace(/<[^<>]*>/g, ' ')@@ -196,6 +198,9 @@ export function toNewMessage(}export function toMessage(accountId: string, m: IndexedMessage): Message {+ const encrypted =+ m.bodyStructure?.type.toLowerCase() === 'multipart/encrypted' ||+ m.preview.includes('-----BEGIN PGP MESSAGE-----')return {id: m.id,accountId,@@ -208,7 +213,17 @@ export function toMessage(accountId: string, m: IndexedMessage): Message {replyTo: m.replyTo,receivedAt: m.receivedAt,sentAt: m.sentAt,- preview: m.preview,+ preview: encrypted ? '' : m.preview,+ ...(encrypted+ ? {+ security: {+ encrypted: true,+ state: 'locked' as const,+ signature: 'unknown' as const,+ confirmed: false,+ },+ }+ : {}),keywords: keywordsFromFlags(m.flags),mailboxIds: { [m.mailboxId]: true },size: m.size,diff --git a/packages/imap/src/imapflow-port.ts b/packages/imap/src/imapflow-port.tsindex bfb7c3a..ed74195 100644--- a/packages/imap/src/imapflow-port.ts+++ b/packages/imap/src/imapflow-port.ts@@ -293,8 +293,13 @@ export class ImapFlowPort implements ImapPort {return this.wrap(async () => {const [size] = await this.fetch(String(uid), { size: true })if (!size || (size.size ?? 0) > maxBytes) return undefined- const message = await this.client.fetchOne(String(uid), { source: true }, { uid: true })- return message && message.source ? new Uint8Array(message.source) : undefined+ // Omit the part to stream the exact RFC822 source, and consume one extra byte+ // so a truncated download can never be mistaken for a complete signed message.+ const { content } = await this.client.download(String(uid), undefined, {+ uid: true,+ maxBytes: maxBytes + 1,+ })+ return bytes(content, maxBytes, false)})}download(uid: number, part: string, maxBytes: number, truncate = false): Promise<Uint8Array> {diff --git a/packages/imap/src/mime.ts b/packages/imap/src/mime.tsindex e975a99..fe0d658 100644--- a/packages/imap/src/mime.ts+++ b/packages/imap/src/mime.ts@@ -1,150 +1,2 @@-import MailComposer from 'nodemailer/lib/mail-composer'-import { simpleParser, type AddressObject } from 'mailparser'-import { parseUnsubscribe, ProviderError, type Address } from '@inlark/core'--export interface ComposeInput {- from: Address- to: Address[]- cc: Address[]- bcc: Address[]- subject: string- html: string- text: string- /** Without angle brackets. */- messageId: string- inReplyTo?: string[]- references?: string[]- date?: Date- attachments: { name: string; type: string; cid?: string; content: Uint8Array }[]- /** Drafts keep Bcc so another client resuming the draft sees it; transmitted/Sent copies never do. */- keepBcc?: boolean-}--export interface ParsedMime {- subject: string- from: Address[]- to: Address[]- cc: Address[]- bcc: Address[]- replyTo: Address[]- date?: string- /** Message ids are returned without angle brackets. */- messageId?: string- inReplyTo: string[]- references: string[]- /** '' when the message has no HTML part; never generated from the text. */- html: string- text: string- attachments: {- name: string- type: string- size: number- cid?: string- disposition?: string- content: Uint8Array- }[]- unsubscribe?: { url: string; oneClick: boolean }-}--export const defaultMaxMimeBytes = 64 * 1024 * 1024--const bracketed = (id: string) => `<${id.trim().replace(/^<|>$/g, '')}>`-const addresses = (list: Address[]) =>- list.length ? list.map((a) => ({ name: a.name, address: a.email })) : undefined-// A copy, so the result never shares a pooled ArrayBuffer with unrelated memory.-const plain = (bytes: Uint8Array) => new Uint8Array(bytes)--export async function composeMime(input: ComposeInput): Promise<Uint8Array> {- const node = new MailComposer({- from: { name: input.from.name, address: input.from.email },- to: addresses(input.to),- cc: addresses(input.cc),- bcc: addresses(input.bcc),- subject: input.subject,- text: input.text || undefined,- html: input.html || undefined,- messageId: bracketed(input.messageId),- inReplyTo: input.inReplyTo?.length ? input.inReplyTo.map(bracketed).join(' ') : undefined,- references: input.references?.length ? input.references.map(bracketed) : undefined,- date: input.date ?? new Date(),- attachments: input.attachments.map((a) => ({- filename: a.name,- contentType: a.type || 'application/octet-stream',- content: Buffer.from(a.content.buffer, a.content.byteOffset, a.content.byteLength),- contentDisposition: a.cid ? 'inline' : 'attachment',- ...(a.cid ? { cid: a.cid } : {}),- })),- // Content is always supplied in memory; never let a value be read as a path or URL.- disableFileAccess: true,- disableUrlAccess: true,- // The default prefix names the library; boundaries should not identify the client.- boundaryPrefix: '--',- // Canonical CRLF, so the bytes stored as a Sent copy are exactly the bytes transmitted.- newline: 'windows',- }).compile()- node.keepBcc = !!input.keepBcc- return plain(await node.build())-}--const ids = (value: unknown): string[] =>- [value ?? []]- .flat()- .flatMap((v) => String(v).match(/<[^<>]+>/g) ?? (String(v).trim() ? [String(v).trim()] : []))- .map((id) => id.replace(/^<|>$/g, '').trim())- .filter(Boolean)--const addressList = (value?: AddressObject | AddressObject[]): Address[] =>- [value ?? []].flat().flatMap((object) =>- object.value- .flatMap((a) => (a.group ? a.group : [a]))- .filter((a) => a.address)- .map((a) => ({ name: a.name || '', email: a.address! })),- )--/** Mirrors the JMAP provider: https or mailto only, never credentials in the URL. */--export async function parseMime(- source: Uint8Array,- options: { maxBytes?: number } = {},-): Promise<ParsedMime> {- const maxBytes = options.maxBytes ?? defaultMaxMimeBytes- if (source.byteLength > maxBytes)- throw new ProviderError('tooLarge', 'This message is too large to open.')- const mail = await simpleParser(- Buffer.from(source.buffer, source.byteOffset, source.byteLength),- { skipTextToHtml: true, skipTextLinks: true, skipImageLinks: true, keepCidLinks: true },- )- const header = (key: string) => {- const line = mail.headerLines?.find((h) => h.key === key)?.line- return line- ?.slice(line.indexOf(':') + 1)- .replace(/\r?\n[ \t]+/g, ' ')- .trim()- }- const date = mail.date && !Number.isNaN(mail.date.getTime()) ? mail.date.toISOString() : undefined- const messageId = ids(mail.messageId)[0]- const unsubscribe = parseUnsubscribe(header('list-unsubscribe'), header('list-unsubscribe-post'))- return {- subject: mail.subject ?? '',- from: addressList(mail.from),- to: addressList(mail.to),- cc: addressList(mail.cc),- bcc: addressList(mail.bcc),- replyTo: addressList(mail.replyTo),- ...(date ? { date } : {}),- ...(messageId ? { messageId } : {}),- inReplyTo: ids(mail.inReplyTo),- references: ids(mail.references),- html: typeof mail.html === 'string' ? mail.html : '',- text: mail.text ?? '',- attachments: mail.attachments.map((a) => ({- name: a.filename || 'attachment',- type: a.contentType || 'application/octet-stream',- size: a.content.byteLength,- ...(a.cid ? { cid: a.cid.replace(/^<|>$/g, '') } : {}),- ...(a.contentDisposition ? { disposition: a.contentDisposition } : {}),- content: plain(a.content),- })),- ...(unsubscribe ? { unsubscribe } : {}),- }-}+// Kept as a compatibility entry point for existing consumers.+export * from '@inlark/mime'diff --git a/packages/imap/src/provider.ts b/packages/imap/src/provider.tsindex c503fab..33ec98d 100644--- a/packages/imap/src/provider.ts+++ b/packages/imap/src/provider.ts@@ -762,7 +762,7 @@ export class ImapProvider implements MailProvider {// Display the matching representative, even if the thread has newer mail elsewhere.c.receivedAt = row.latest.receivedAtc.subject = row.latest.subject || '(No subject)'- c.preview = row.latest.preview+ c.preview = toMessage(account.id, row.latest).previewc.count = row.countreturn c})@@ -1188,6 +1188,64 @@ export class ImapProvider implements MailProvider {if (lost.length) await this.index.removeMessages(this.accountId, lost)}+ async rawMessage(_account: Account, messageId: string, maxBytes: number): Promise<Uint8Array> {+ const rows = await this.index.messages(this.accountId, [messageId])+ const boxes = await this.index.listMailboxes(this.accountId)+ for (const row of rows) {+ const box = boxes.find((b) => b.id === row.mailboxId)+ if (!box || row.size > maxBytes) continue+ const raw = await this.run(async (port) => {+ const selected = await port.select(box.path)+ if (selected.uidValidity !== row.uidValidity) return+ return port.source(row.uid, Math.min(maxBytes, 64 * 1024 * 1024))+ })+ if (raw) return raw+ }+ throw new ProviderError(+ 'rawMessage',+ 'The original message is unavailable or too large to open securely.',+ )+ }++ async encryptionHints(account: Account, email: string) {+ const page = await this.query(account, { view: 'all', from: email }, 0, 20)+ const rows = (+ await this.index.threadMessages(+ this.accountId,+ page.items.map((m) => m.id),+ )+ )+ .filter(+ (row) => row.from.length === 1 && row.from[0].email.toLowerCase() === email.toLowerCase(),+ )+ .sort((a, b) => b.receivedAt.localeCompare(a.receivedAt))+ .slice(0, 40)+ const boxes = await this.index.listMailboxes(this.accountId)+ const hints: { message: Message; headers: Uint8Array }[] = []+ for (const [mailboxId, items] of byMailbox(rows)) {+ const box = boxes.find((b) => b.id === mailboxId)+ if (!box) continue+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ const valid = items.filter((row) => row.uidValidity === selected.uidValidity)+ if (!valid.length) return+ const fetched = await port.fetch(uidSet(valid.map((row) => row.uid)), {+ headers: ['autocrypt'],+ })+ for (const row of valid) {+ const headers =+ fetched.find((m) => m.uid === row.uid)?.headers || 'Content-Type: text/plain'+ if (Buffer.byteLength(headers) <= 20 * 1024)+ hints.push({+ message: toMessage(account.id, row),+ headers: Buffer.from(headers.trimEnd() + '\r\n\r\n'),+ })+ }+ })+ }+ return hints+ }+// Drafts and sendingprivate async compose(account: Account, draft: Draft, messageId: string, keepBcc: boolean) {@@ -1223,7 +1281,12 @@ export class ImapProvider implements MailProvider {.replace(/[^a-z0-9.-]/g, '')return randomUUID() + '@' + (domain || 'inlark.invalid')}- async createDraft(account: Account, draft: Draft, messageId?: string): Promise<string> {+ async createDraft(+ account: Account,+ draft: Draft,+ messageId?: string,+ precomposed?: Uint8Array,+ ): Promise<string> {const drafts = await this.roleBox('drafts')if (!drafts)throw new ProviderError(@@ -1232,7 +1295,7 @@ export class ImapProvider implements MailProvider {)// Every saved revision gets its own Message-ID so it can be found unambiguously.const id = messageId || this.messageId(this.sender(account, draft.identityId).email)- const mime = await this.compose(account, draft, id, true)+ const mime = precomposed ?? (await this.compose(account, draft, id, true))return this.run(async (port) => {// APPEND flags are checked against the selected folder's permanent flags.const selected = await port.select(drafts.path)@@ -1259,10 +1322,11 @@ export class ImapProvider implements MailProvider {account: Account,draft: Draft,messageId: string,+ precomposed?: Uint8Array,): Promise<OutgoingMessage> {const recipients = [...new Set([...draft.to, ...draft.cc, ...draft.bcc].map((a) => a.email))]// Bcc recipients are only in the envelope, never in the transmitted headers.- const mime = await this.compose(account, draft, messageId, false)+ const mime = precomposed ?? (await this.compose(account, draft, messageId, false))// Bounces go to the address the message is from, as recipients would expect.const from = this.sender(account, draft.identityId).emailreturn { messageId, mime, envelope: { from, to: recipients } }diff --git a/packages/jmap/package.json b/packages/jmap/package.jsonindex c05220b..d13b87d 100644--- a/packages/jmap/package.json+++ b/packages/jmap/package.json@@ -11,6 +11,7 @@"typecheck": "tsc -p tsconfig.json"},"dependencies": {- "@inlark/core": "workspace:*"+ "@inlark/core": "workspace:*",+ "@inlark/mime": "workspace:*"}}diff --git a/packages/jmap/src/index.ts b/packages/jmap/src/index.tsindex 1f88657..f877b9c 100644--- a/packages/jmap/src/index.ts+++ b/packages/jmap/src/index.ts@@ -85,6 +85,7 @@ const summaryProperties = ['messageId','inReplyTo','references',+ 'bodyStructure',]function batches<T>(items: T[], size: number): T[][] {const result: T[][] = []@@ -182,6 +183,16 @@ function asMessage(account: Account, raw: Json, bodies: boolean): Message {raw['header:List-Unsubscribe-Post:asText'],)}+ if (+ raw.bodyStructure?.type?.toLowerCase() === 'multipart/encrypted' ||+ /-----BEGIN PGP MESSAGE-----/.test(result.preview)+ ) {+ result.preview = ''+ result.html = ''+ result.text = ''+ result.attachments = []+ result.security = { encrypted: true, state: 'locked', signature: 'unknown', confirmed: false }+ }return result}export class JmapProvider implements MailProvider {@@ -633,7 +644,11 @@ export class JmapProvider implements MailProvider {throw new JmapError('upload', 'The upload could not be verified.')return result.blobId}- async download(account: Account, attachment: Attachment): Promise<Uint8Array> {+ async download(+ account: Account,+ attachment: Attachment,+ maxBytes = 100_000_000,+ ): Promise<Uint8Array> {if (!this.session) throw new JmapError('session', 'Reconnect the account.')let url = this.session.downloadUrlfor (const [key, value] of Object.entries({@@ -652,7 +667,7 @@ export class JmapProvider implements MailProvider {const part = await reader.read()if (part.done) breaksize += part.value.byteLength- if (size > 100_000_000) {+ if (size > maxBytes) {await reader.cancel()throw new JmapError('tooLarge',@@ -669,13 +684,113 @@ export class JmapProvider implements MailProvider {}return bytes}- async createDraft(account: Account, draft: Draft, messageId?: string): Promise<string> {+ async rawMessage(account: Account, messageId: string, maxBytes: number): Promise<Uint8Array> {+ const [result] = await this.call([+ [+ 'Email/get',+ { accountId: account.remoteId, ids: [messageId], properties: ['id', 'blobId', 'size'] },+ 'raw',+ ],+ ])+ const message = result.list?.find((m: Json) => m.id === messageId)+ const limit = Math.min(maxBytes, 64 * 1024 * 1024)+ if (!message?.blobId || message.size > limit)+ throw new JmapError(+ 'rawMessage',+ 'The complete message is unavailable or too large to open securely.',+ )+ return this.download(+ account,+ { blobId: message.blobId, name: 'message.eml', type: 'message/rfc822', size: message.size },+ limit,+ )+ }+ async encryptionHints(account: Account, email: string) {+ const mailboxes = await this.mailboxes(account)+ const [, result] = await this.call([+ [+ 'Email/query',+ {+ accountId: account.remoteId,+ filter: jmapFilter({ view: 'all', from: email }, mailboxes),+ sort: [{ property: 'receivedAt', isAscending: false }],+ limit: Math.min(40, this.capabilities.maxObjectsInGet),+ },+ 'hints',+ ],+ [+ 'Email/get',+ {+ accountId: account.remoteId,+ '#ids': { resultOf: 'hints', name: 'Email/query', path: '/ids' },+ properties: [+ 'id',+ 'threadId',+ 'from',+ 'to',+ 'cc',+ 'receivedAt',+ 'sentAt',+ 'keywords',+ 'mailboxIds',+ 'header:Autocrypt:all',+ ],+ },+ 'headers',+ ],+ ])+ return (result.list || [])+ .filter(+ (raw: Json) =>+ raw.from?.length === 1 && raw.from[0].email.toLowerCase() === email.toLowerCase(),+ )+ .map((raw: Json) => {+ const values: string[] =+ raw['header:Autocrypt:all'] || raw['header:Autocrypt:asRaw:all'] || []+ const headers = values.length+ ? values.map((v) => 'Autocrypt: ' + v).join('\r\n')+ : 'Content-Type: text/plain'+ return {+ message: asMessage(account, raw, false),+ headers: new TextEncoder().encode(headers.trimEnd() + '\r\n\r\n'),+ }+ })+ .filter((hint: { headers: Uint8Array }) => hint.headers.byteLength <= 20 * 1024)+ }+ async createDraft(+ account: Account,+ draft: Draft,+ messageId?: string,+ precomposed?: Uint8Array,+ ): Promise<string> {const boxes = await this.mailboxes(account)const drafts = boxes.find((b) => b.role === 'drafts')if (!drafts?.rights.mayAddItems)throw new JmapError('drafts', 'A writable Drafts folder is required.')const identity = (await this.identities(account)).find((i) => i.id === draft.identityId)if (!identity) throw new JmapError('identity', 'Choose a valid sending identity.')+ if (precomposed) {+ const blobId = await this.upload(account, precomposed, 'message/rfc822')+ const [result] = await this.call([+ [+ 'Email/import',+ {+ accountId: account.remoteId,+ emails: {+ protected: {+ blobId,+ mailboxIds: { [drafts.id]: true },+ keywords: { $draft: true, $seen: true },+ },+ },+ },+ 'import',+ ],+ ])+ if (!result.created?.protected?.id)+ throw new JmapError('draft', 'The server could not import the protected draft.')+ return result.created.protected.id+ }const [result] = await this.call([['Email/set',@@ -722,8 +837,9 @@ export class JmapProvider implements MailProvider {account: Account,draft: Draft,messageId: string,+ precomposed?: Uint8Array,): Promise<OutgoingMessage> {- const emailId = await this.createDraft(account, draft, messageId)+ const emailId = await this.createDraft(account, draft, messageId, precomposed)const identity = (await this.identities(account)).find((i) => i.id === draft.identityId)return {messageId,@@ -760,7 +876,16 @@ export class JmapProvider implements MailProvider {'EmailSubmission/set',{accountId: account.remoteId,- create: { send: { emailId: message.emailId, identityId } },+ create: {+ send: {+ emailId: message.emailId,+ identityId,+ envelope: {+ mailFrom: { email: message.envelope.from },+ rcptTo: message.envelope.to.map((email) => ({ email })),+ },+ },+ },onSuccessUpdateEmail: { '#send': patch },},'s',diff --git a/packages/mime/package.json b/packages/mime/package.jsonnew file mode 100644index 0000000..00e3713--- /dev/null+++ b/packages/mime/package.json@@ -0,0 +1,22 @@+{+ "name": "@inlark/mime",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "typecheck": "tsc -p tsconfig.json"+ },+ "dependencies": {+ "@inlark/core": "workspace:*",+ "mailparser": "^3.9.28",+ "nodemailer": "^10.0.10"+ },+ "devDependencies": {+ "@types/mailparser": "^3.4.6",+ "@types/nodemailer": "^8.0.2"+ }+}diff --git a/packages/mime/src/index.ts b/packages/mime/src/index.tsnew file mode 100644index 0000000..e975a99--- /dev/null+++ b/packages/mime/src/index.ts@@ -0,0 +1,150 @@+import MailComposer from 'nodemailer/lib/mail-composer'+import { simpleParser, type AddressObject } from 'mailparser'+import { parseUnsubscribe, ProviderError, type Address } from '@inlark/core'++export interface ComposeInput {+ from: Address+ to: Address[]+ cc: Address[]+ bcc: Address[]+ subject: string+ html: string+ text: string+ /** Without angle brackets. */+ messageId: string+ inReplyTo?: string[]+ references?: string[]+ date?: Date+ attachments: { name: string; type: string; cid?: string; content: Uint8Array }[]+ /** Drafts keep Bcc so another client resuming the draft sees it; transmitted/Sent copies never do. */+ keepBcc?: boolean+}++export interface ParsedMime {+ subject: string+ from: Address[]+ to: Address[]+ cc: Address[]+ bcc: Address[]+ replyTo: Address[]+ date?: string+ /** Message ids are returned without angle brackets. */+ messageId?: string+ inReplyTo: string[]+ references: string[]+ /** '' when the message has no HTML part; never generated from the text. */+ html: string+ text: string+ attachments: {+ name: string+ type: string+ size: number+ cid?: string+ disposition?: string+ content: Uint8Array+ }[]+ unsubscribe?: { url: string; oneClick: boolean }+}++export const defaultMaxMimeBytes = 64 * 1024 * 1024++const bracketed = (id: string) => `<${id.trim().replace(/^<|>$/g, '')}>`+const addresses = (list: Address[]) =>+ list.length ? list.map((a) => ({ name: a.name, address: a.email })) : undefined+// A copy, so the result never shares a pooled ArrayBuffer with unrelated memory.+const plain = (bytes: Uint8Array) => new Uint8Array(bytes)++export async function composeMime(input: ComposeInput): Promise<Uint8Array> {+ const node = new MailComposer({+ from: { name: input.from.name, address: input.from.email },+ to: addresses(input.to),+ cc: addresses(input.cc),+ bcc: addresses(input.bcc),+ subject: input.subject,+ text: input.text || undefined,+ html: input.html || undefined,+ messageId: bracketed(input.messageId),+ inReplyTo: input.inReplyTo?.length ? input.inReplyTo.map(bracketed).join(' ') : undefined,+ references: input.references?.length ? input.references.map(bracketed) : undefined,+ date: input.date ?? new Date(),+ attachments: input.attachments.map((a) => ({+ filename: a.name,+ contentType: a.type || 'application/octet-stream',+ content: Buffer.from(a.content.buffer, a.content.byteOffset, a.content.byteLength),+ contentDisposition: a.cid ? 'inline' : 'attachment',+ ...(a.cid ? { cid: a.cid } : {}),+ })),+ // Content is always supplied in memory; never let a value be read as a path or URL.+ disableFileAccess: true,+ disableUrlAccess: true,+ // The default prefix names the library; boundaries should not identify the client.+ boundaryPrefix: '--',+ // Canonical CRLF, so the bytes stored as a Sent copy are exactly the bytes transmitted.+ newline: 'windows',+ }).compile()+ node.keepBcc = !!input.keepBcc+ return plain(await node.build())+}++const ids = (value: unknown): string[] =>+ [value ?? []]+ .flat()+ .flatMap((v) => String(v).match(/<[^<>]+>/g) ?? (String(v).trim() ? [String(v).trim()] : []))+ .map((id) => id.replace(/^<|>$/g, '').trim())+ .filter(Boolean)++const addressList = (value?: AddressObject | AddressObject[]): Address[] =>+ [value ?? []].flat().flatMap((object) =>+ object.value+ .flatMap((a) => (a.group ? a.group : [a]))+ .filter((a) => a.address)+ .map((a) => ({ name: a.name || '', email: a.address! })),+ )++/** Mirrors the JMAP provider: https or mailto only, never credentials in the URL. */++export async function parseMime(+ source: Uint8Array,+ options: { maxBytes?: number } = {},+): Promise<ParsedMime> {+ const maxBytes = options.maxBytes ?? defaultMaxMimeBytes+ if (source.byteLength > maxBytes)+ throw new ProviderError('tooLarge', 'This message is too large to open.')+ const mail = await simpleParser(+ Buffer.from(source.buffer, source.byteOffset, source.byteLength),+ { skipTextToHtml: true, skipTextLinks: true, skipImageLinks: true, keepCidLinks: true },+ )+ const header = (key: string) => {+ const line = mail.headerLines?.find((h) => h.key === key)?.line+ return line+ ?.slice(line.indexOf(':') + 1)+ .replace(/\r?\n[ \t]+/g, ' ')+ .trim()+ }+ const date = mail.date && !Number.isNaN(mail.date.getTime()) ? mail.date.toISOString() : undefined+ const messageId = ids(mail.messageId)[0]+ const unsubscribe = parseUnsubscribe(header('list-unsubscribe'), header('list-unsubscribe-post'))+ return {+ subject: mail.subject ?? '',+ from: addressList(mail.from),+ to: addressList(mail.to),+ cc: addressList(mail.cc),+ bcc: addressList(mail.bcc),+ replyTo: addressList(mail.replyTo),+ ...(date ? { date } : {}),+ ...(messageId ? { messageId } : {}),+ inReplyTo: ids(mail.inReplyTo),+ references: ids(mail.references),+ html: typeof mail.html === 'string' ? mail.html : '',+ text: mail.text ?? '',+ attachments: mail.attachments.map((a) => ({+ name: a.filename || 'attachment',+ type: a.contentType || 'application/octet-stream',+ size: a.content.byteLength,+ ...(a.cid ? { cid: a.cid.replace(/^<|>$/g, '') } : {}),+ ...(a.contentDisposition ? { disposition: a.contentDisposition } : {}),+ content: plain(a.content),+ })),+ ...(unsubscribe ? { unsubscribe } : {}),+ }+}diff --git a/packages/mime/tsconfig.json b/packages/mime/tsconfig.jsonnew file mode 100644index 0000000..4b7d0d2--- /dev/null+++ b/packages/mime/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../tsconfig.json", "include": ["src"], "compilerOptions": { "types": ["node"] } }diff --git a/packages/ui/src/icons.tsx b/packages/ui/src/icons.tsxindex 1957958..d902691 100644--- a/packages/ui/src/icons.tsx+++ b/packages/ui/src/icons.tsx@@ -10,6 +10,7 @@ import {ArrowUpRight as ArrowUpRightGlyph,AtIcon as AtSignGlyph,Bold as BoldGlyph,+ CheckmarkBadge01Icon as BadgeCheckGlyph,Calendar as CalendarGlyph,CalendarAdd02Icon as CalendarAddGlyph,Check as CheckGlyph,@@ -24,9 +25,11 @@ import {File as FileGlyph,FileArchive as FileArchiveGlyph,FileImage as FileImageGlyph,+ FileImportIcon as FileImportGlyph,FileSpreadsheetIcon as FileSpreadsheetIconGlyph,FileText as FileTextGlyph,Folder as FolderGlyph,+ FingerPrintIcon as FingerprintGlyph,FolderInputIcon as FolderInputIconGlyph,FolderPlus as FolderPlusGlyph,Forward as ForwardGlyph,@@ -37,11 +40,15 @@ import {Info as InfoGlyph,Italic as ItalicGlyph,Keyboard as KeyboardGlyph,+ Key01Icon as KeyGlyph,LaptopIcon as LaptopGlyph,+ LaptopPhoneSyncIcon as DeviceSyncGlyph,Link2 as Link2Glyph,List as ListGlyph,LoaderCircle as LoaderCircleGlyph,LockKeyhole as LockKeyholeGlyph,+ LockKeyholeOpenIcon as LockOpenGlyph,+ LockKeyholeIcon as LockGlyph,Mail as MailGlyph,MailMinus01Icon as MailMinusGlyph,MailOpen as MailOpenGlyph,@@ -66,8 +73,10 @@ import {Share08Icon as ShareGlyph,SettingsIcon as SettingsIconGlyph,ShieldCheck as ShieldCheckGlyph,+ ShieldKeyIcon as ShieldKeyGlyph,ShieldX as ShieldXGlyph,Shuffle as ShuffleGlyph,+ SignatureIcon as SignatureGlyph,SlidersHorizontal as SlidersHorizontalGlyph,SquarePenIcon as SquarePenGlyph,Star as StarGlyph,@@ -96,6 +105,7 @@ export const ArrowUp = icon(ArrowUpGlyph)export const ArrowUpRight = icon(ArrowUpRightGlyph)export const AtSign = icon(AtSignGlyph)export const Bold = icon(BoldGlyph)+export const BadgeCheck = icon(BadgeCheckGlyph)export const Calendar = icon(CalendarGlyph)export const CalendarAdd = icon(CalendarAddGlyph)export const Check = icon(CheckGlyph)@@ -110,9 +120,11 @@ export const ExternalLink = icon(ExternalLinkGlyph)export const File = icon(FileGlyph)export const FileArchive = icon(FileArchiveGlyph)export const FileImage = icon(FileImageGlyph)+export const FileImport = icon(FileImportGlyph)export const FileSpreadsheet = icon(FileSpreadsheetIconGlyph)export const FileText = icon(FileTextGlyph)export const Folder = icon(FolderGlyph)+export const Fingerprint = icon(FingerprintGlyph)export const FolderInput = icon(FolderInputIconGlyph)export const FolderPlus = icon(FolderPlusGlyph)export const Forward = icon(ForwardGlyph)@@ -123,11 +135,15 @@ export const Inbox = icon(InboxGlyph)export const Info = icon(InfoGlyph)export const Italic = icon(ItalicGlyph)export const Keyboard = icon(KeyboardGlyph)+export const Key = icon(KeyGlyph)export const Laptop = icon(LaptopGlyph)+export const DeviceSync = icon(DeviceSyncGlyph)export const Link2 = icon(Link2Glyph)export const List = icon(ListGlyph)export const LoaderCircle = icon(LoaderCircleGlyph)export const LockKeyhole = icon(LockKeyholeGlyph)+export const Lock = icon(LockGlyph)+export const LockOpen = icon(LockOpenGlyph)export const Mail = icon(MailGlyph)export const MailMinus = icon(MailMinusGlyph)export const MailOpen = icon(MailOpenGlyph)@@ -152,8 +168,10 @@ export const Settings = icon(SettingsGlyph)export const Share = icon(ShareGlyph)export const SettingsIcon = icon(SettingsIconGlyph)export const ShieldCheck = icon(ShieldCheckGlyph)+export const ShieldKey = icon(ShieldKeyGlyph)export const ShieldX = icon(ShieldXGlyph)export const Shuffle = icon(ShuffleGlyph)+export const Signature = icon(SignatureGlyph)export const SlidersHorizontal = icon(SlidersHorizontalGlyph)export const SquarePen = icon(SquarePenGlyph)export const Star = icon(StarGlyph)diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsxindex 8e828a5..80c4bb0 100644--- a/packages/ui/src/index.tsx+++ b/packages/ui/src/index.tsx@@ -96,7 +96,9 @@ export function Modal({'modal fixed top-[calc(50%_+_var(--titlebar-height,0px)_/_2)] left-[50%] transform-[translate(-50%,_-50%)]','w-[min(560px,_calc(100vw_-_40px))] max-h-[calc(100vh_-_70px_-_var(--titlebar-height,0px))] overflow-y-auto','bg-surface border border-solid border-border-strong rounded-2xl',- 'shadow-popup p-5.75 z-101 max-w-[calc(100vw_-_40px)] transition-[opacity,transform] duration-160 ease-[ease]',+ 'shadow-popup p-5.75 z-101 max-w-[calc(100vw_-_40px)] transition-[opacity,transform,filter] duration-160 ease-[ease]',+ // A dialog opened from this one has no backdrop of its own, so this one recedes instead.+ 'data-nested-dialog-open:brightness-[0.62]','data-starting-style:opacity-0 data-starting-style:transform-[translate(-50%,_-48%)_scale(0.98)]','data-ending-style:opacity-0 data-ending-style:transform-[translate(-50%,_-48%)_scale(0.98)]',className,@@ -138,7 +140,8 @@ export function Dropdown({<Menu.Root><Menu.Trigger render={trigger} /><Menu.Portal container={container}>- <Menu.Positioner sideOffset={6} align="end">+ {/* Above dialogs such as the composer; the popup's own z-index can't escape this. */}+ <Menu.Positioner className="dropdown-positioner z-120" sideOffset={6} align="end"><Menu.PopupclassName={cn('dropdown min-w-45 bg-raised border border-solid border-border-strong rounded-lg shadow-popup p-1.25 z-120',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dcf2b65..b8b3e07 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -142,12 +142,18 @@ importers:'@inlark/core':specifier: workspace:*version: link:../../packages/core+ '@inlark/crypto':+ specifier: workspace:*+ version: link:../../packages/crypto'@inlark/imap':specifier: workspace:*version: link:../../packages/imap'@inlark/jmap':specifier: workspace:*version: link:../../packages/jmap+ '@inlark/mime':+ specifier: workspace:*+ version: link:../../packages/mime'@inlark/ui':specifier: workspace:*version: link:../../packages/ui@@ -286,11 +292,26 @@ importers:specifier: ^4.0.0version: 4.6.5+ packages/crypto:+ dependencies:+ '@inlark/mime':+ specifier: workspace:*+ version: link:../mime+ openpgp:+ specifier: ^6.3.0+ version: 6.3.2+ zod:+ specifier: ^4.0.0+ version: 4.6.5+packages/imap:dependencies:'@inlark/core':specifier: workspace:*version: link:../core+ '@inlark/mime':+ specifier: workspace:*+ version: link:../mimeimapflow:specifier: ^2.0.6version: 2.0.6@@ -313,6 +334,28 @@ importers:'@inlark/core':specifier: workspace:*version: link:../core+ '@inlark/mime':+ specifier: workspace:*+ version: link:../mime++ packages/mime:+ dependencies:+ '@inlark/core':+ specifier: workspace:*+ version: link:../core+ mailparser:+ specifier: ^3.9.28+ version: 3.9.28+ nodemailer:+ specifier: ^10.0.10+ version: 10.0.10+ devDependencies:+ '@types/mailparser':+ specifier: ^3.4.6+ version: 3.4.6+ '@types/nodemailer':+ specifier: ^8.0.2+ version: 8.0.2packages/ui:dependencies:@@ -3930,6 +3973,15 @@ packages:resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}+ resolution: {integrity: sha512-wcZTzHz41LV8Y48zH/JlD1JT8YdNmpWOuMAjQ/podvvCwsjBEU37K3znJh4UQcj3hksE5z9TzvhbUbwzsGvlLQ==}+ engines: {node: '>= 18.0.0', typescript: '>= 5.0.0'}+ peerDependencies:+ '@openpgp/web-stream-tools': ~0.3.0+ peerDependenciesMeta:+ '@openpgp/web-stream-tools':+ optional: true+resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==}@@ -8524,6 +8576,8 @@ snapshots:regex: 6.1.0regex-recursion: 6.0.2+ [email protected]: {}+diff --git a/scripts/test-crypto-worker.mjs b/scripts/test-crypto-worker.mjsnew file mode 100644index 0000000..517fc7e--- /dev/null+++ b/scripts/test-crypto-worker.mjs@@ -0,0 +1,122 @@+import assert from 'node:assert/strict'+import { Worker } from 'node:worker_threads'+import { readdir, readFile, writeFile, mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join, resolve, sep } from 'node:path'+import { pathToFileURL } from 'node:url'+import { spawnSync } from 'node:child_process'+// Electron's Node mode also accepts a directory inside a packaged app.asar.+const directory = process.env.INLARK_CRYPTO_WORKER_DIRECTORY+ ? pathToFileURL(resolve(process.env.INLARK_CRYPTO_WORKER_DIRECTORY) + sep)+ : new URL('../apps/desktop/out/main/', import.meta.url)+const entry = (await readdir(directory)).find((name) => /^crypto-worker-.*\.js$/.test(name))+assert.ok(entry, 'Build the desktop before checking the packaged crypto worker.')+const worker = new Worker(new URL(entry, directory)),+ pending = new Map()+let next = 1+worker.on('message', ({ id, result, error }) => {+ const call = pending.get(id)+ if (!call) return+ pending.delete(id)+ clearTimeout(call.timer)+ if (error) call.reject(new Error(error))+ else call.resolve(result)+})+worker.on('error', (error) => {+ for (const call of pending.values()) {+ clearTimeout(call.timer)+ call.reject(error)+ }+ pending.clear()+})+const request = (method, ...args) =>+ new Promise((resolve, reject) => {+ const id = next++,+ timer = setTimeout(() => {+ pending.delete(id)+ reject(new Error('Crypto worker timed out.'))+ }, 30000)+ pending.set(id, { resolve, reject, timer })+ worker.postMessage({ id, method, args })+ })+try {+ const key = await request('generate', 'Packaged fixture', '[email protected]')+ await request('load', [key])+ const encrypted = await request(+ 'encrypt',+ new TextEncoder().encode('Packaged private content'),+ [key.publicKey],+ key.fingerprint,+ )+ const result = await request('decrypt', encrypted, [key.publicKey])+ assert.equal(Buffer.from(result.data).toString(), 'Packaged private content')+ assert.equal(result.signatures[0].valid, true)+ if (process.argv.includes('--gnupg')) {+ const home = await mkdtemp(join(tmpdir(), 'inlark-interop-'))+ const fixture = (name) =>+ readFile(new URL('../tests/fixtures/openpgp/' + name, import.meta.url))+ const gpg = (args, input) => {+ const result = spawnSync(+ 'gpg',+ ['--homedir', home, '--batch', '--yes', '--no-tty', '--pinentry-mode', 'loopback', ...args],+ { input, maxBuffer: 16 * 1024 * 1024 },+ )+ assert.equal(result.status, 0, result.stderr?.toString() || result.error?.message)+ return result+ }+ try {+ const alice = await request(+ 'importPrivate',+ (await fixture('alice-private.asc')).toString(),+ '[email protected]',+ )+ const bob = await request(+ 'importPrivate',+ (await fixture('bob-private.asc')).toString(),+ '[email protected]',+ )+ await request('load', [alice, bob])+ gpg(['--import'], await fixture('bob-private.asc'))+ gpg(['--import'], await fixture('alice-public.asc'))+ const entity = await fixture('entity.mime')+ for (const hidden of [false, true]) {+ const output = await request(+ 'encrypt',+ entity,+ [alice.publicKey, bob.publicKey],+ alice.fingerprint,+ hidden,+ )+ const decrypted = gpg(['--status-fd', '2', '--decrypt'], output)+ assert.deepEqual(decrypted.stdout, entity)+ assert.match(decrypted.stderr.toString(), new RegExp('VALIDSIG ' + alice.fingerprint, 'i'))+ }+ const signature = await request('sign', entity, alice.fingerprint)+ await writeFile(join(home, 'message.mime'), entity)+ await writeFile(join(home, 'signature.asc'), signature)+ const verified = gpg([+ '--status-fd',+ '2',+ '--verify',+ join(home, 'signature.asc'),+ join(home, 'message.mime'),+ ])+ assert.match(verified.stderr.toString(), new RegExp('VALIDSIG ' + alice.fingerprint, 'i'))+ const backup = await request('backup', alice.fingerprint, 'synthetic-backup-password')+ gpg(['--passphrase', 'synthetic-backup-password', '--import'], backup)+ console.log(+ 'Independent GnuPG: signed encryption, hidden recipients, detached signatures and protected key import passed.',+ )+ } finally {+ spawnSync('gpgconf', ['--homedir', home, '--kill', 'gpg-agent'])+ await rm(home, { recursive: true, force: true })+ }+ }+ await request('lock')+ await assert.rejects(request('decrypt', encrypted, [key.publicKey]), /No private key/)+ console.log(+ 'Packaged crypto worker: generation, encryption, signing, decryption and locking passed.',+ )+} finally {+ await worker.terminate()+}diff --git a/tests/crypto.test.ts b/tests/crypto.test.tsnew file mode 100644index 0000000..aa09ee3--- /dev/null+++ b/tests/crypto.test.ts@@ -0,0 +1,348 @@+import { beforeAll, afterEach, describe, expect, it } from 'vitest'+import { mkdtemp, readFile, writeFile, rm, stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { randomBytes } from 'node:crypto'+import * as pgp from '../packages/crypto/node_modules/openpgp/dist/node/openpgp.mjs'+import {+ CryptoEngine,+ Vault,+ seal,+ unseal,+ wkdUrls,+ parseAutocrypt,+ peerUpdate,+ peerPrefersEncryption,+ mimeContent,+ multipart,+ splitEntity,+ header,+ armoredPayload,+ signedMime,+ encryptedMime,+ type PrivateRecord,+} from '../packages/crypto/src'+import { composeMime, parseMime } from '../packages/mime/src'+const fixture = (name: string) => readFile(new URL('./fixtures/openpgp/' + name, import.meta.url))+let directories: string[] = []+const directory = async () => {+ const path = await mkdtemp(join(tmpdir(), 'inlark-crypto-'))+ directories.push(path)+ return path+}+afterEach(async () => {+ await Promise.all(directories.map((path) => rm(path, { recursive: true, force: true })))+ directories = []+})++describe('authenticated vault', () => {+ it('authenticates ciphertext, record identity, nonce and tag before returning plaintext', () => {+ const key = randomBytes(32),+ context = Buffer.from('private:key:v1'),+ box = seal(key, Buffer.from('PRIVATE SECRET'), context)+ expect(unseal(key, box, context).toString()).toBe('PRIVATE SECRET')+ for (const change of [+ { tag: randomBytes(16).toString('base64') },+ { nonce: randomBytes(12).toString('base64') },+ { data: randomBytes(14).toString('base64') },+ ])+ expect(() => unseal(key, { ...box, ...change }, context)).toThrow()+ expect(() => unseal(key, box, Buffer.from('other-key:v1'))).toThrow()+ expect(() =>+ unseal(key, { ...box, tag: Buffer.alloc(15).toString('base64') }, context),+ ).toThrow()+ })+ it('requires password fallback, survives restart, and never writes plaintext keys or drafts', async () => {+ const path = join(await directory(), 'vault.json'),+ vault = new Vault(path)+ await vault.init()+ await expect(vault.create()).rejects.toThrow('password')+ await vault.create('portable-password')+ await vault.putJSON('private:original', { secret: 'PRIVATE KEY MARKER' })+ await vault.put('draft:draft-id', Buffer.from('BODY MARKER'))+ await vault.put('attachment:1', Buffer.from('ATTACHMENT MARKER'))+ const text = await readFile(path, 'utf8')+ expect(text).not.toContain('MARKER')+ expect((await stat(path)).mode & 0o777).toBe(0o600)+ const encrypted = JSON.parse(text)+ expect(encrypted.protection.mode).toBe('password')+ expect(Buffer.from(encrypted.protection.salt, 'base64')).toHaveLength(32)+ await vault.lock()+ expect(() => vault.read('private:original')).toThrow('Unlock')+ const restored = new Vault(path)+ await restored.init()+ await expect(restored.unlock('wrong password')).rejects.toThrow('incorrect')+ expect(await readFile(path, 'utf8')).toBe(text)+ await restored.unlock('portable-password')+ expect(restored.json('private:original')).toEqual({ secret: 'PRIVATE KEY MARKER' })+ await restored.put('draft:draft-id', Buffer.from('REVISED BODY'))+ await restored.lock()+ await restored.unlock('portable-password')+ expect(restored.read('draft:draft-id')?.toString()).toBe('REVISED BODY')+ })+ it('uses OS protection only when available and refuses recreation, corruption and unknown versions', async () => {+ const path = join(await directory(), 'vault.json'),+ storage = {+ available: () => true,+ wrap: (s: string) => Buffer.from('wrapped:' + s).toString('base64'),+ unwrap: (s: string) => Buffer.from(s, 'base64').toString().slice(8),+ }+ const vault = new Vault(path, storage)+ await vault.init()+ await vault.create()+ await vault.putJSON('key:first', { secret: 'one' })+ await vault.lock()+ storage.available = () => false+ await expect(vault.unlock()).rejects.toThrow('keyring')+ await expect(vault.create('new-password')).rejects.toThrow('already exists')+ storage.available = () => true+ await vault.unlock()+ expect(vault.json('key:first')).toEqual({ secret: 'one' })+ const data = JSON.parse(await readFile(path, 'utf8'))+ data.records['key:other'] = data.records['key:first']+ delete data.records['key:first']+ await writeFile(path, JSON.stringify(data))+ const damaged = new Vault(path, storage)+ await damaged.init()+ await expect(damaged.unlock()).rejects.toThrow()+ data.version = 2+ await writeFile(path, JSON.stringify(data))+ const newer = new Vault(path, storage)+ await expect(newer.init()).rejects.toThrow('preserved')+ expect(JSON.parse(await readFile(path, 'utf8')).version).toBe(2)+ })+ it('uses fresh nonces and serializes concurrent snapshots without dropping records', async () => {+ const path = join(await directory(), 'vault.json'),+ vault = new Vault(path, {+ available: () => true,+ wrap: (s) => Buffer.from(s).toString('base64'),+ unwrap: (s) => Buffer.from(s, 'base64').toString(),+ })+ await vault.init()+ await vault.create()+ await Promise.all(+ Array.from({ length: 20 }, (_, i) => vault.put('record:' + i, Buffer.from('same content'))),+ )+ const doc = JSON.parse(await readFile(path, 'utf8'))+ expect(new Set(Object.values(doc.records).map((b: any) => b.nonce)).size).toBe(21)+ await vault.lock()+ await vault.unlock()+ expect(vault.ids('record:')).toHaveLength(20)+ })+})++describe('OpenPGP interoperability and byte preserving MIME', () => {+ let engine: CryptoEngine, alice: PrivateRecord, bob: PrivateRecord, publicKeys: string[]+ beforeAll(async () => {+ engine = new CryptoEngine()+ alice = await engine.importPrivate(+ (await fixture('alice-private.asc')).toString(),+ '[email protected]',+ )+ bob = await engine.importPrivate(+ (await fixture('bob-private.asc')).toString(),+ '[email protected]',+ )+ publicKeys = [alice.publicKey, bob.publicKey]+ await engine.load([alice, bob])+ })+ it('generates v4 Ed25519 signing and Curve25519 encryption keys and protected backups', async () => {+ const generated = await engine.generate('User', '[email protected]'),+ key = await pgp.readPrivateKey({ armoredKey: generated.privateKey })+ expect(key.keyPacket.version).toBe(4)+ expect(key.getAlgorithmInfo().algorithm).toBe('eddsaLegacy')+ expect(key.subkeys[0].getAlgorithmInfo().algorithm).toBe('ecdh')+ const [info] = await engine.inspect(generated.publicKey, '[email protected]')+ expect(info.usable).toBe(true)+ await engine.load([generated, alice, bob])+ const backup = await engine.backup(generated.fingerprint, 'separate-backup-password'),+ protectedKey = await pgp.readPrivateKey({ armoredKey: backup })+ expect(protectedKey.isDecrypted()).toBe(false)+ const restored = await engine.importPrivate(+ backup,+ '[email protected]',+ 'separate-backup-password',+ )+ expect(restored.fingerprint).toBe(generated.fingerprint)+ await expect(+ engine.importPrivate(backup, '[email protected]', 'separate-backup-password'),+ ).rejects.toThrow('match')+ })+ for (const file of ['encrypted-signed.eml', 'encrypted-unsigned.eml', 'encrypted-bcc.eml'])+ it('decrypts independent GnuPG ' + file + ' with HTML and attachment', async () => {+ const result = await engine.decrypt(armoredPayload(await fixture(file)), publicKeys),+ mime = await parseMime(result.data)+ expect(mime.text.trim()).toBe('Secret fixture body.')+ expect(mime.html).toContain('<p>Secret fixture body.</p>')+ expect(Buffer.from(mime.attachments[0].content).toString()).toBe('Secret fixture attachment.')+ expect(result.signatures.every((s) => s.valid)).toBe(true)+ if (file === 'encrypted-signed.eml')+ expect(result.signatures[0].fingerprint).toBe(alice.fingerprint)+ })+ it('preserves exact signed bytes and identifies invalid signatures without discarding readable data', async () => {+ const source = await fixture('signed.eml'),+ parts = multipart(source)+ expect(parts[0]).toEqual(await fixture('entity.mime'))+ expect(+ (await engine.verify(parts[0], splitEntity(parts[1]).body.toString(), publicKeys))[0].valid,+ ).toBe(true)+ const invalid = multipart(await fixture('invalid-signature.eml'))+ expect(+ (await engine.verify(invalid[0], splitEntity(invalid[1]).body.toString(), publicKeys))[0]+ .valid,+ ).toBe(false)+ })+ it('hides every recipient key ID for Bcc and preserves sender decryption', async () => {+ const armored = await engine.encrypt(+ await fixture('entity.mime'),+ publicKeys,+ alice.fingerprint,+ true,+ ),+ message = await pgp.readMessage({ armoredMessage: armored })+ expect(message.getEncryptionKeyIDs().every((id) => id.toHex() === '0000000000000000')).toBe(+ true,+ )+ expect((await engine.decrypt(armored, publicKeys)).signatures[0].valid).toBe(true)+ })+ it('minimizes Autocrypt advertisements to one certified address and encryption subkey', async () => {+ const advertised = await engine.autocryptKey(alice.publicKey, '[email protected]'),+ key = await pgp.readKey({ binaryKey: advertised })+ expect(key.toPacketList()).toHaveLength(5)+ expect(key.users).toHaveLength(1)+ expect(key.subkeys).toHaveLength(1)+ expect((await engine.inspect(advertised, '[email protected]'))[0].usable).toBe(true)+ })+ it('rejects expired encryption keys while allowing their private key import for historical mail', async () => {+ const expired = await pgp.generateKey({+ type: 'ecc',+ curve: 'ed25519Legacy',+ subkeys: [{ curve: 'curve25519Legacy' }],+ userIDs: [{ email: '[email protected]' }],+ date: new Date(Date.now() - 86400_000),+ keyExpirationTime: 60,+ format: 'armored',+ })+ expect((await engine.inspect(expired.publicKey, '[email protected]'))[0].problem).toBe(+ 'expired',+ )+ await expect(+ engine.importPrivate(expired.privateKey, '[email protected]'),+ ).rejects.toThrow()+ expect(+ (await engine.importPrivate(expired.privateKey, '[email protected]', undefined, true))+ .fingerprint,+ ).toMatch(/^[a-f0-9]{40}$/)+ })+ it('retains revoked key state across refresh and decrypts history with a retired private key', async () => {+ const ciphertext = await engine.encrypt(await fixture('entity.mime'), [bob.publicKey]),+ revoked = await engine.revoke(bob.fingerprint),+ refreshed = await engine.mergePublic(revoked, bob.publicKey)+ expect((await engine.inspect(refreshed, '[email protected]'))[0].problem).toBe('revoked')+ const replacement = await engine.generate('Bob', '[email protected]'),+ retired = await engine.importPrivate(bob.privateKey, '[email protected]', undefined, true),+ otherDevice = new CryptoEngine()+ await otherDevice.load([replacement, retired])+ expect(Buffer.from((await otherDevice.decrypt(ciphertext, publicKeys)).data)).toEqual(+ await fixture('entity.mime'),+ )+ await expect(otherDevice.encrypt(await fixture('entity.mime'), [refreshed])).rejects.toThrow()+ otherDevice.lock()+ })+ it('blocks corrupt ciphertext and clears private state on lock', async () => {+ const armored = armoredPayload(await fixture('encrypted-unsigned.eml'))+ const binary = Buffer.from(+ armored+ .split(/\r?\n/)+ .filter((line) => /^[A-Za-z0-9+/]{4,}={0,2}$/.test(line))+ .join(''),+ 'base64',+ )+ binary[binary.length - 8] ^= 1+ const corrupt = (await pgp.readMessage({ binaryMessage: binary })).armor()+ await expect(engine.decrypt(corrupt, publicKeys)).rejects.toThrow()+ engine.lock()+ await expect(engine.decrypt(armored, publicKeys)).rejects.toThrow('No private key')+ await engine.load([alice, bob])+ })+ it('accepts inline encrypted and cleartext signed messages', async () => {+ expect(+ Buffer.from(+ (await engine.decrypt(armoredPayload(await fixture('inline-encrypted.eml')), publicKeys))+ .data,+ ).toString(),+ ).toContain('Secret inline fixture body.')+ const source = splitEntity(await fixture('inline-signed.eml'))+ expect(+ (await engine.verifyInline(source.body.toString(), publicKeys)).signatures[0].valid,+ ).toBe(true)+ })+ it('emits canonical MIME and verifies its own detached signature without flattening alternatives', async () => {+ const mime = await composeMime({+ from: { name: 'Alice', email: '[email protected]' },+ to: [{ name: 'Bob', email: '[email protected]' }],+ cc: [],+ bcc: [],+ subject: 'Visible',+ text: 'Secret unicode café',+ html: '<p>Secret unicode café</p>',+ messageId: '[email protected]',+ attachments: [],+ })+ const content = mimeContent(mime),+ sig = await engine.sign(content, alice.fingerprint),+ signed = signedMime(content, sig),+ parts = multipart(signed)+ expect(parts[0]).toEqual(content)+ expect(+ (await engine.verify(parts[0], splitEntity(parts[1]).body.toString(), publicKeys))[0].valid,+ ).toBe(true)+ expect(+ header(splitEntity(encryptedMime(await engine.encrypt(signed, publicKeys))), 'content-type'),+ ).toContain('multipart/encrypted')+ })+})++describe('discovery and Autocrypt state', () => {+ it('uses the specified WKD hash, original local-part query, and advanced/direct paths', () => {+ const urls = wkdUrls('[email protected]')+ expect(urls.advanced).toBe(+ 'https://openpgpkey.example.org/.well-known/openpgpkey/example.org/hu/iy9q119eutrkn8s1mk4r39qejnbu3n5q?l=Joe.Doe',+ )+ expect(urls.direct).toContain('/.well-known/openpgpkey/hu/iy9q119eutrkn8s1mk4r39qejnbu3n5q')+ })+ it('rejects wrong sender, duplicate attributes, invalid base64, unsupported critical attributes and oversized headers', () => {+ const valid = '[email protected]; prefer-encrypt=mutual; keydata=YWJj'+ expect(parseAutocrypt(valid, '[email protected]')?.mutual).toBe(true)+ for (const value of [+ valid.replace('alice', 'other'),+ valid + '; keydata=YWJj',+ valid.replace('keydata=', 'critical=1; keydata='),+ valid.replace('YWJj', '!!'),+ valid + ' '.repeat(10240),+ ])+ expect(parseAutocrypt(value, '[email protected]')).toBeUndefined()+ expect(parseAutocrypt(valid.replace('keydata=', '_extra=1; keydata='))?.data).toEqual(+ Buffer.from('abc'),+ )+ })+ it('ignores older headers, clamps future timestamps and discourages stale encryption preferences', () => {+ const peer = peerUpdate({}, '2026-10-07T12:00:00Z', '2026-10-07T10:00:00Z', {+ fingerprint: 'first',+ mutual: true,+ })+ expect(peerPrefersEncryption(peer)).toBe(true)+ expect(+ peerUpdate(peer, '2026-10-07T12:00:00Z', '2026-10-06T10:00:00Z', {+ fingerprint: 'old',+ mutual: false,+ }),+ ).toEqual(peer)+ const future = peerUpdate(peer, '2026-10-07T12:00:00Z', '2099-01-01T00:00:00Z', {+ fingerprint: 'new',+ mutual: true,+ })+ expect(future.autocryptAt).toBe('2026-10-07T12:00:00.000Z')+ expect(peerPrefersEncryption({ ...peer, lastSeen: '2026-12-07T12:00:00.000Z' })).toBe(false)+ })+})diff --git a/tests/encryption-service.test.ts b/tests/encryption-service.test.tsnew file mode 100644index 0000000..8fb67cd--- /dev/null+++ b/tests/encryption-service.test.ts@@ -0,0 +1,619 @@+import { publicFetch } from '../apps/desktop/src/main/public-fetch'+import { lookup } from 'node:dns/promises'+import { dialog } from 'electron'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { randomUUID } from 'node:crypto'+import { CryptoEngine, Vault } from '../packages/crypto/src'+import { identityKey, type Draft, type Identity, type Message } from '../packages/core/src'+import { JsonStore } from '../apps/desktop/src/main/storage'+import { EncryptionService, type CryptoTransport } from '../apps/desktop/src/main/encryption'+import { MailService } from '../apps/desktop/src/main/service'+import { ImapProvider } from '../packages/imap/src'+import { openInProcessIndex } from '../apps/desktop/src/main/imap-index/sqlite-index'+import { FakeImapServer } from './support/fake-imap'+import { parseMime } from '../packages/mime/src'+import {+ armoredPayload,+ encryptedMime,+ splitEntity,+ header,+ autocryptHeader,+} from '../packages/crypto/src'+vi.mock('electron', () => ({+ app: { getVersion: () => 'test' },+ safeStorage: {+ isEncryptionAvailable: () => false,+ getSelectedStorageBackend: () => 'basic_text',+ },+ dialog: { showOpenDialog: vi.fn(), showSaveDialog: vi.fn() },+ shell: {},+ Notification: { isSupported: () => false },+}))+vi.mock('../apps/desktop/src/main/public-fetch', () => ({+ publicFetch: vi.fn(async () => ({ status: 404, type: '', bytes: Buffer.alloc(0) })),+}))+vi.mock('node:dns/promises', () => ({+ lookup: vi.fn(async () => [{ address: '1.1.1.1', family: 4 }]),+}))+const file = (name: string) => readFile(new URL('./fixtures/openpgp/' + name, import.meta.url))+let directory: string, store: JsonStore, service: EncryptionService, engine: CryptoEngine+const own: Identity = {+ id: 'default',+ accountId: JSON.stringify(['crypto-test', 'imap']),+ name: 'Bob',+ email: '[email protected]',+}+const message: Message = {+ id: 'fixture',+ accountId: own.accountId,+ threadId: 'thread',+ subject: 'Visible fixture subject',+ from: [{ name: 'Alice', email: '[email protected]' }],+ to: [{ name: 'Bob', email: own.email }],+ cc: [],+ bcc: [],+ replyTo: [],+ receivedAt: '2026-10-07T12:00:00.000Z',+ sentAt: '2026-10-07T10:00:00.000Z',+ preview: '',+ size: 1,+ hasAttachment: true,+ keywords: { $seen: true },+ mailboxIds: { inbox: true },+}+const draft = (): Draft => ({+ id: randomUUID(),+ accountId: own.accountId,+ identityId: own.id,+ to: [{ name: 'Alice', email: '[email protected]' }],+ cc: [],+ bcc: [{ name: 'Carol', email: '[email protected]' }],+ subject: 'VISIBLE',+ text: 'PRIVATE BODY MARKER',+ html: '<p>PRIVATE BODY MARKER</p>',+ attachments: [],+ updatedAt: new Date().toISOString(),+ status: 'local',+ encryption: 'encrypt',+})+const factory = (): CryptoTransport =>+ ({+ call: async (method, ...args) => (engine[method] as Function).apply(engine, args),+ close: async () => {+ engine.lock()+ },+ }) as CryptoTransport+async function seed() {+ const privateRecord = await engine.importPrivate(+ (await file('bob-private.asc')).toString(),+ own.email,+ )+ const vault = new Vault(join(directory, 'encryption-vault.json'))+ await vault.init()+ await vault.create('vault-password')+ await vault.putJSON('private:' + privateRecord.fingerprint, privateRecord)+ await vault.lock()+ const keys = [] as any[]+ for (const name of ['alice', 'bob', 'carol']) {+ const email = name + '@encryption.test',+ [info] = await engine.inspect((await file(name + '-public.asc')).toString(), email)+ keys.push({+ ...info,+ email,+ binary: Buffer.from(info.binary).toString('base64'),+ sources: [name === 'bob' ? 'own' : 'autocrypt'],+ confirmed: name === 'bob',+ accepted: true,+ backup: name === 'bob' ? 'needed' : undefined,+ })+ }+ await store.write('encryption-state', {+ identities: {+ [identityKey(own.accountId, own.id)]: {+ accountId: own.accountId,+ identityId: own.id,+ email: own.email,+ fingerprint: privateRecord.fingerprint,+ enabled: true,+ prefer: false,+ },+ },+ keys,+ accepted: Object.fromEntries(keys.map((k) => [k.email, k.fingerprint])),+ peers: {},+ refreshed: {},+ })+}+beforeEach(async () => {+ vi.mocked(dialog.showOpenDialog).mockReset()+ vi.mocked(dialog.showSaveDialog).mockReset()+ vi.mocked(publicFetch)+ .mockReset()+ .mockResolvedValue({ status: 404, type: '', bytes: Buffer.alloc(0) })+ vi.mocked(lookup)+ .mockReset()+ .mockResolvedValue([{ address: '1.1.1.1', family: 4 }] as any)+ directory = await mkdtemp(join(tmpdir(), 'inlark-encryption-'))+ store = new JsonStore(directory)+ await store.init()+ engine = new CryptoEngine()+ await seed()+ service = new EncryptionService(store, factory)+ await service.init()+ await service.unlock('vault-password')+})+afterEach(async () => {+ await service.lock()+ await rm(directory, { recursive: true, force: true })+ vi.clearAllMocks()+})++it('separates encryption, signature validity and confirmed sender identity, including inline and unsigned mail', async () => {+ for (const name of [+ 'encrypted-signed.eml',+ 'encrypted-unsigned.eml',+ 'signed.eml',+ 'invalid-signature.eml',+ 'inline-encrypted.eml',+ 'inline-signed.eml',+ ]) {+ const result = await service.read(message, await file(name))+ expect(['decrypted', 'signed']).toContain(result.security?.state)+ expect(result.text).toContain('fixture')+ expect(result.security?.confirmed).toBe(false)+ if (name === 'invalid-signature.eml') expect(result.security?.signature).toBe('invalid')+ if (name === 'encrypted-unsigned.eml') expect(result.security?.signature).toBe('unsigned')+ if (name === 'encrypted-signed.eml') expect(result.security?.signature).toBe('valid')+ }+ const status = await service.status(),+ key = status.keys.find((k) => k.email === '[email protected]')!+ await service.accept(key.email, key.fingerprint, true)+ expect(+ (await service.read(message, await file('encrypted-signed.eml'))).security?.confirmed,+ ).toBe(true)+ const inline = splitEntity(await file('inline-encrypted.eml'))+ const encoded = Buffer.from(+ 'Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n' ++ inline.body.toString('base64') ++ '\r\n',+ )+ expect((await service.read(message, encoded)).text).toContain('Secret inline fixture body.')+ const state: any = await store.read('encryption-state', {})+ state.keys = state.keys.filter((key: any) => key.email !== '[email protected]')+ await store.write('encryption-state', state)+ const withoutSigner = new EncryptionService(store, factory)+ await withoutSigner.init()+ await withoutSigner.unlock('vault-password')+ const unverified = await withoutSigner.read(message, await file('encrypted-signed.eml'))+ expect(unverified.security).toMatchObject({+ state: 'decrypted',+ signature: 'unknown',+ confirmed: false,+ })+ expect(unverified.text).toContain('fixture')+ await withoutSigner.lock()+})+it('locks decrypted attachments and views, and never exposes content on locked or missing-key reads', async () => {+ const read = await service.read(message, await file('encrypted-signed.eml'))+ expect(service.attachments.size).toBeGreaterThan(0)+ const attachment = service.attachments.get(read.attachments![0].blobId)!.content+ await service.lock()+ expect(service.attachments.size).toBe(0)+ expect(attachment.every((byte) => byte === 0)).toBe(true)+ const locked = await service.read(message, await file('encrypted-signed.eml'))+ expect(locked.security?.state).toBe('locked')+ expect(locked.text).toBe('')+ expect(locked.attachments).toEqual([])+})+it('blocks corrupted ciphertext and missing-key reads before releasing bodies or attachment handles', async () => {+ const armor = armoredPayload(await file('encrypted-unsigned.eml')),+ line = armor+ .split(/\r?\n/)+ .filter((value) => /^[A-Za-z0-9+/]{4,}={0,2}$/.test(value))+ .at(-1)!,+ corrupt = armor.replace(line, (line[0] === 'A' ? 'B' : 'A') + line.slice(1))+ const blocked = await service.read(message, encryptedMime(corrupt))+ expect(blocked.security?.state).toBe('integrityFailure')+ expect(blocked.text).toBe('')+ expect(blocked.attachments).toEqual([])+ expect(service.attachments.size).toBe(0)+ await engine.load([+ await engine.importPrivate(+ (await file('alice-private.asc')).toString(),+ '[email protected]',+ ),+ ])+ const missing = await service.read(message, await file('inline-encrypted.eml'))+ expect(missing.security?.state).toBe('missingKey')+ expect(missing.text).toBe('')+ expect(service.attachments.size).toBe(0)+})+it('allows explicit ordinary mail with an unusable sender key while blocking protected sends', async () => {+ const state: any = await store.read('encryption-state', {}),+ key = state.keys.find((k: any) => k.email === own.email)+ key.publicKey = await engine.revoke(key.fingerprint)+ await store.write('encryption-state', state)+ const changed = new EncryptionService(store, factory)+ await changed.init()+ await changed.unlock('vault-password')+ await expect(changed.compose(draft(), own, '[email protected]', [])).rejects.toThrow(+ 'sender’s key',+ )+ const ordinary = await changed.compose(+ { ...draft(), encryption: 'none', downgradeConfirmed: true },+ own,+ '[email protected]',+ [],+ )+ expect((await parseMime(ordinary)).text).toContain('PRIVATE BODY MARKER')+ expect(header(splitEntity(ordinary), 'autocrypt')).toBe('')+ await changed.lock()+})+it('encrypts Bcc content to all recipients and sender, omits Bcc headers and gossip, and encrypts drafts only to self', async () => {+ const input = draft(),+ mime = await service.compose(input, own, '[email protected]', [+ {+ name: 'private.txt',+ type: 'text/plain',+ content: Buffer.from('PRIVATE ATTACHMENT MARKER'),+ },+ ])+ expect(mime.toString()).not.toContain('MARKER')+ expect(mime.toString()).not.toContain('[email protected]')+ expect(header(splitEntity(mime), 'bcc')).toBe('')+ const record = await engine.importPrivate(+ (await file('alice-private.asc')).toString(),+ '[email protected]',+ )+ await engine.load([record])+ const decrypted = await engine.decrypt(+ armoredPayload(mime),+ (await service.status()).keys.map((k) => k.publicKey),+ )+ expect(Buffer.from(decrypted.data).toString()).not.toContain('[email protected]')+ expect((await parseMime(decrypted.data)).text).toContain('PRIVATE BODY MARKER')+ await engine.load([+ await engine.importPrivate((await file('bob-private.asc')).toString(), own.email),+ ])+ const self = await service.compose(input, own, '[email protected]', [], true)+ expect(header(splitEntity(self), 'autocrypt-draft-state')).toContain('encrypt=yes')+ await engine.load([record])+ await expect(engine.decrypt(armoredPayload(self), [record.publicKey])).rejects.toThrow()+})+it('blocks changed, conflicting and unusable recipient keys without downgrading', async () => {+ const state: any = await store.read('encryption-state', {})+ const replacement = await engine.generate('Alice replacement', '[email protected]'),+ [info] = await engine.inspect(replacement.publicKey, '[email protected]')+ state.keys.push({+ ...info,+ email: '[email protected]',+ binary: Buffer.from(info.binary).toString('base64'),+ sources: ['wkd'],+ confirmed: false,+ accepted: false,+ })+ await store.write('encryption-state', state)+ const changed = new EncryptionService(store, factory)+ await changed.init()+ await changed.unlock('vault-password')+ const ready = await changed.readiness(own.accountId, own.id, ['[email protected]'])+ expect(ready.recipients[0].status).toBe('changed')+ expect(ready.recommend).toBe(false)+ await expect(changed.compose(draft(), own, '[email protected]', [])).rejects.toThrow(+ '[email protected] (changed)',+ )+ await changed.accept('[email protected]', info.fingerprint, false)+ expect(+ (await changed.readiness(own.accountId, own.id, ['[email protected]'])).recipients[0]+ .status,+ ).toBe('ready')+ await changed.lock()+})+it('imports an explicitly chosen replacement while retaining, decrypting and backing up the original private key', async () => {+ const old = (await service.status()).identities[0].fingerprint,+ replacement = await engine.generate('Bob replacement', own.email),+ input = join(directory, 'replacement.asc')+ await writeFile(input, replacement.privateKey)+ vi.mocked(dialog.showOpenDialog).mockResolvedValueOnce({ canceled: false, filePaths: [input] })+ const status = await service.setup(own, 'replace', undefined, undefined, true)+ expect(status.identities[0].fingerprint).toBe(replacement.fingerprint)+ expect(status.keys.find((k) => k.fingerprint === old)).toMatchObject({+ retired: true,+ accepted: false,+ })+ expect(status.keys.find((k) => k.fingerprint === replacement.fingerprint)).toMatchObject({+ retired: false,+ accepted: true,+ })+ expect(service.vault.ids('private:')).toContain('private:' + old)+ expect((await service.read(message, await file('encrypted-signed.eml'))).text).toContain(+ 'Secret fixture body.',+ )+ const path = join(directory, 'retired-backup.asc')+ vi.mocked(dialog.showSaveDialog).mockResolvedValueOnce({ canceled: false, filePath: path })+ await service.exportKey(old, 'backup', 'separate-backup-password')+ expect(+ (+ await engine.importPrivate(+ await readFile(path, 'utf8'),+ own.email,+ 'separate-backup-password',+ true,+ )+ ).fingerprint,+ ).toBe(old)+ expect(JSON.stringify(await service.status())).not.toContain('PGP PRIVATE KEY')+})+it('keeps protected main-process drafts and attachments encrypted through crash recovery, lock and tombstones', async () => {+ const server = new FakeImapServer(),+ submit = vi.fn(async () => ({+ accepted: ['[email protected]', '[email protected]'],+ rejected: [],+ }))+ const main = new MailService(store, () => {}, {+ crypto: factory,+ providers: (options) =>+ new ImapProvider({+ connectionId: options.connectionId,+ name: options.name,+ config: options.config as any,+ password: options.secrets.password,+ index: openInProcessIndex(':memory:'),+ readAttachment: options.readAttachment,+ background: false,+ ports: server.port,+ smtp: { submit, verify: async () => {} },+ timing: { sentCopyGraceMs: 0, previews: 0 },+ }),+ })+ await main.init()+ await main.connect({+ connectionId: 'crypto-test',+ name: 'Encrypted',+ password: 'disposable',+ remember: false,+ config: {+ protocol: 'imap',+ email: own.email,+ incoming: { host: 'imap.encryption.test', port: 993, security: 'tls', username: 'bob' },+ outgoing: { host: 'smtp.encryption.test', port: 587, security: 'starttls', username: 'bob' },+ outgoingSameCredentials: true,+ },+ })+ await main.unlockEncryption('vault-password')+ const input = draft()+ const original = join(directory, 'selected-private.txt')+ await writeFile(original, 'PRIVATE ATTACHMENT MARKER')+ vi.mocked(dialog.showOpenDialog).mockResolvedValueOnce({ canceled: false, filePaths: [original] })+ input.attachments = await main.stageAttachments(true)+ expect(await readFile(join(directory, 'staging.json'), 'utf8')).not.toContain(+ 'selected-private.txt',+ )+ expect(main.encryption.vault.ids('attachment:')).toContain(+ 'attachment:' + input.attachments[0].id,+ )+ await expect(+ readFile(join(directory, 'attachments', input.attachments[0].id)),+ ).rejects.toMatchObject({ code: 'ENOENT' })+ await main.saveDraft(input)+ expect(await readFile(join(directory, 'drafts.json'), 'utf8')).not.toContain('MARKER')+ expect(await readFile(join(directory, 'encryption-vault.json'), 'utf8')).not.toContain('MARKER')+ await main.lockEncryption()+ expect((await main.drafts())[0].text).toBe('')+ await main.unlockEncryption('vault-password')+ expect((await main.drafts())[0].text).toBe('PRIVATE BODY MARKER')+ await expect(main.saveDraft({ ...input, encryption: 'none' })).rejects.toThrow('Confirm')+ const saved = await main.syncDraft(input)+ expect(saved.status).toBe('synced')+ expect(saved.serverFingerprint).toMatch(/^[a-f0-9]{64}$/)+ const sent = await main.send(saved)+ expect(sent.status).toBe('sent')+ expect(Buffer.from(submit.mock.calls[0][2]).toString()).not.toContain('MARKER')+ const tombstone = (await main.drafts()).find((d) => d.id === input.id)!+ expect(tombstone.status).toBe('sent')+ expect(tombstone.text).toBe('')+ expect(main.encryption.vault.ids('draft:')).not.toContain('draft:' + input.id)+ expect(main.encryption.vault.ids('attachment:')).not.toContain(+ 'attachment:' + input.attachments[0].id,+ )+ const partial = draft()+ submit.mockImplementationOnce(+ async () =>+ ({+ accepted: ['[email protected]'],+ rejected: [{ email: '[email protected]', reason: '550 Refused' }],+ }) as any,+ )+ expect((await main.send(partial)).status).toBe('partial')+ await main.lockEncryption()+ await expect(main.recoverRejected(partial.id)).rejects.toThrow('Unlock')+ await main.unlockEncryption('vault-password')+ const recovered = await main.recoverRejected(partial.id)+ expect(recovered.text).toBe('PRIVATE BODY MARKER')+ expect([...recovered.to, ...recovered.cc, ...recovered.bcc].map((a) => a.email)).toEqual([+ '[email protected]',+ ])+ expect(main.encryption.vault.ids('draft:')).toContain('draft:' + recovered.id)+ expect(await readFile(join(directory, 'drafts.json'), 'utf8')).not.toContain('MARKER')+ await main.lockEncryption()+ await main.unlockEncryption('vault-password')+ expect((await main.drafts()).find((d) => d.id === recovered.id)?.text).toBe('PRIVATE BODY MARKER')+ const uncertain = draft()+ submit.mockRejectedValueOnce(new Error('Lost final response'))+ expect((await main.send(uncertain)).status).toBe('uncertain')+ await main.lockEncryption()+ await expect(main.replaceUncertain(uncertain.id)).rejects.toThrow('Unlock')+ await main.unlockEncryption('vault-password')+ const replacement = await main.replaceUncertain(uncertain.id)+ await main.lockEncryption()+ await main.unlockEncryption('vault-password')+ expect((await main.drafts()).find((d) => d.id === replacement.id)?.text).toBe(+ 'PRIVATE BODY MARKER',+ )+ expect(main.encryption.vault.ids('draft:')).toContain('draft:' + uncertain.id)+ const downgrade = draft()+ await main.saveDraft(downgrade)+ await main.saveDraft({+ ...downgrade,+ encryption: 'none',+ downgradeConfirmed: true,+ text: 'Explicitly ordinary revised content',+ updatedAt: new Date(Date.now() + 1000).toISOString(),+ })+ expect(main.encryption.vault.ids('draft:')).not.toContain('draft:' + downgrade.id)+ await main.lockEncryption()+ await main.unlockEncryption('vault-password')+ expect((await main.drafts()).find((d) => d.id === downgrade.id)?.text).toBe(+ 'Explicitly ordinary revised content',+ )+ main.dispose()+ await new Promise((resolve) => setTimeout(resolve, 30))+})++it('uses advanced WKD first, falls back to direct only for absent DNS, and keeps the same fingerprint accepted', async () => {+ const [info] = await engine.inspect(+ (await file('alice-public.asc')).toString(),+ '[email protected]',+ )+ vi.mocked(publicFetch).mockResolvedValue({+ status: 200,+ type: 'application/octet-stream',+ bytes: Buffer.from(info.binary),+ })+ const initial = (await service.status()).keys.find((k) => k.email === '[email protected]')!+ await service.discover(initial.email, true)+ expect(vi.mocked(publicFetch).mock.calls[0][0]).toContain('https://openpgpkey.encryption.test/')+ expect((await service.status()).keys.find((k) => k.email === initial.email)?.accepted).toBe(true)+ expect(+ (await service.readiness(own.accountId, own.id, [initial.email])).recipients[0].status,+ ).toBe('ready')+ vi.mocked(publicFetch).mockClear()+ vi.mocked(lookup).mockRejectedValueOnce(+ Object.assign(new Error('Absent DNS'), { code: 'ENOTFOUND' }),+ )+ await service.discover(initial.email, true)+ expect(vi.mocked(publicFetch).mock.calls[0][0]).toContain(+ 'https://encryption.test/.well-known/openpgpkey/hu/',+ )+ vi.mocked(publicFetch).mockClear().mockRejectedValueOnce(new Error('TLS failed'))+ await service.discover(initial.email, true)+ expect(vi.mocked(publicFetch).mock.calls).toHaveLength(1)+ expect(vi.mocked(publicFetch).mock.calls[0][0]).toContain('https://openpgpkey.')+})+it('discovers keys and preference from bounded unopened-message headers after WKD and refreshes stale peer state', async () => {+ const dave = await engine.generate('Dave', '[email protected]'),+ advertisement = autocryptHeader(+ '[email protected]',+ await engine.autocryptKey(dave.publicKey, '[email protected]'),+ true,+ ),+ oldDate = new Date(Date.now() - 40 * 86400_000).toISOString(),+ recentDate = new Date().toISOString(),+ hintMessage = {+ ...message,+ from: [{ name: 'Dave', email: '[email protected]' }],+ sentAt: oldDate,+ receivedAt: oldDate,+ },+ hints = vi.fn(async () => [+ { message: hintMessage, headers: Buffer.from(advertisement + '\r\n\r\n') },+ ]),+ automatic = new EncryptionService(store, factory, hints)+ await automatic.init()+ await automatic.unlock('vault-password')+ await automatic.preference(own.accountId, own.id, true, true)+ const ready = await automatic.readiness(own.accountId, own.id, ['[email protected]'])+ expect(vi.mocked(publicFetch)).toHaveBeenCalled()+ expect(ready).toMatchObject({+ recommend: true,+ recipients: [{ status: 'ready', confirmed: false, prefers: true }],+ })+ await automatic.readiness(own.accountId, own.id, ['[email protected]'])+ expect(hints).toHaveBeenCalledTimes(1)+ hints.mockResolvedValueOnce([+ {+ message: { ...hintMessage, receivedAt: recentDate, sentAt: recentDate },+ headers: Buffer.from('Content-Type: text/plain\r\n\r\n'),+ },+ ])+ await automatic.discover('[email protected]', true)+ expect(+ (await automatic.readiness(own.accountId, own.id, ['[email protected]'])).recommend,+ ).toBe(false)+ await automatic.preference(own.accountId, own.id, false, false)+ vi.mocked(publicFetch).mockClear()+ await automatic.readiness(own.accountId, own.id, ['[email protected]'])+ expect(vi.mocked(publicFetch)).not.toHaveBeenCalled()+ expect(hints).toHaveBeenCalledTimes(2)+ await automatic.lock()+})+it('rejects wrong-address WKD keys and stale or malformed Autocrypt headers without replacing accepted keys', async () => {+ const [info] = await engine.inspect((await file('alice-public.asc')).toString())+ vi.mocked(publicFetch).mockResolvedValueOnce({+ status: 200,+ type: '',+ bytes: Buffer.from(info.binary),+ })+ await expect(service.discover('[email protected]', true)).rejects.toThrow('match')+ const replacement = await engine.generate('Alice replacement', '[email protected]'),+ [replacementInfo] = await engine.inspect(replacement.publicKey)+ const raw = await file('unsigned.eml'),+ header = Buffer.from(+ 'Autocrypt: [email protected]; prefer-encrypt=mutual; keydata=' ++ Buffer.from(info.binary).toString('base64') ++ '\r\n',+ )+ await service.observe(message, Buffer.concat([header, raw]))+ const old = Buffer.from(+ 'Autocrypt: [email protected]; keydata=' ++ Buffer.from(replacementInfo.binary).toString('base64') ++ '\r\n',+ )+ await service.observe({ ...message, sentAt: '2026-10-06T10:00:00Z' }, Buffer.concat([old, raw]))+ const keys = (await service.status()).keys.filter((k) => k.email === '[email protected]')+ expect(keys).toHaveLength(1)+ expect(keys[0].fingerprint).toBe(info.fingerprint)+ await service.preference(own.accountId, own.id, true, true)+ expect(+ (await service.readiness(own.accountId, own.id, ['[email protected]'])).recommend,+ ).toBe(true)+ await service.observe(+ { ...message, receivedAt: '2026-12-07T12:00:00Z', sentAt: '2026-12-07T10:00:00Z' },+ raw,+ )+ expect(+ (await service.readiness(own.accountId, own.id, ['[email protected]'])).recommend,+ ).toBe(false)+})+it('exports and restores a Setup Message using a separate generated code and transfers encryption preference', async () => {+ await service.preference(own.accountId, own.id, true, true)+ const path = join(directory, 'setup.eml')+ vi.mocked(dialog.showSaveDialog).mockResolvedValue({ canceled: false, filePath: path })+ const exported = await service.transfer(own, 'export')+ expect(exported.code).toMatch(/^(\d{4}-){8}\d{4}$/)+ const mime = await readFile(path, 'utf8')+ expect(mime).not.toContain(exported.code!)+ expect(mime).not.toContain('BEGIN PGP PRIVATE KEY')+ const destination = join(directory, 'other-device'),+ otherStore = new JsonStore(destination)+ await otherStore.init()+ const other = new EncryptionService(otherStore, factory)+ await other.init()+ vi.mocked(dialog.showOpenDialog).mockResolvedValue({ canceled: false, filePaths: [path] })+ await expect(+ other.transfer(own, 'import', 'wrong code', 'other-vault-password'),+ ).rejects.toThrow()+ await other.transfer(own, 'import', exported.code, 'other-vault-password')+ const restored = await other.status()+ expect(restored.identities[0].fingerprint).toBe(+ (await service.status()).identities[0].fingerprint,+ )+ expect(restored.identities[0].prefer).toBe(true)+ expect((await other.read(message, await file('encrypted-signed.eml'))).text).toContain(+ 'Secret fixture body.',+ )+ await other.lock()+})diff --git a/tests/fixtures/openpgp/README.md b/tests/fixtures/openpgp/README.mdnew file mode 100644index 0000000..5563808--- /dev/null+++ b/tests/fixtures/openpgp/README.md@@ -0,0 +1,9 @@+# Independent OpenPGP fixtures++`generate.py` uses GnuPG to produce synthetic v4 Ed25519/Curve25519 keys and messages, independently of OpenPGP.js. Generated with GnuPG 2.4.9 on Linux. The Alice, Bob and Carol addresses use the reserved `.test` domain. The checked-in private keys are deliberately public test fixtures and must never be used for real mail.++Fixtures cover signed and unsigned PGP/MIME encryption, hidden recipients, exact-byte detached signatures, invalid signatures, inline encryption, inline cleartext signatures, HTML alternatives and attachments. Regeneration changes key fingerprints and ciphertext; tests derive fingerprints from the keys rather than hard-coding them.++Run `python3 tests/fixtures/openpgp/generate.py` with GnuPG installed to regenerate. Run `pnpm test:crypto-interop` to check the reverse direction: GnuPG decrypts and verifies output from the bundled Inlark worker and imports a password-protected backup. It uses a disposable keyring and kills its test agent on completion.++Thunderbird interoperability is a separate release requirement; these fixtures do not stand in for a Thunderbird test.diff --git a/tests/fixtures/openpgp/alice-private.asc b/tests/fixtures/openpgp/alice-private.ascnew file mode 100644index 0000000..5cef5e0--- /dev/null+++ b/tests/fixtures/openpgp/alice-private.asc@@ -0,0 +1,15 @@+-----BEGIN PGP PRIVATE KEY BLOCK-----++lFgEasZ61xYJKwYBBAHaRw8BAQdABu5bIqXHj6bocVrIznYWjiVWrEa2u2cW1UNV+4/uoGakAAQCBz2tYwDBlpdvKOYsOOXXYvmRkHEQXJUY0n7EKq9kuag4dtCVBbGlj+ZSBGaXh0dXJlIDxhbGljZUBlbmNyeXB0aW9uLnRlc3Q+iJAEExYKADgWIQTpp44K+Ykr9f+EQIXDmV3Mx8NenbAUCasZ61wIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIX+gAAKCRDmV3Mx8NenbMULAP0b/XbXZYH8iw35pPN2g4nwsJWure8AHv6WBRMNe7xX+NQD+KonzQ/NoMWxvyPYZtAFsH15fJbWf0ygvYoBc4NufYAacXQRqxnrXEgorBgEE+AZdVAQUBAQdALuWv7SNpjvEHpjbgfxwhvR4m/+RTjm2LNjroVbKiM0ADAQgHAAD/+WEnsrMu3TNUxi7mH6VK3d9n0LsFH7Nlz7xz8nsQ23fgU74h4BBgWCgAgFiEE6aeO+CmJK/X/hECFw5ldzMfDXp2wFAmrGetcCGwwACgkQ5ldzMfDXp2zjJgEArqyq8zbV+PPQTAMerE2GsIuQkxkzO9kkl8jbguunmr3ABANHfKmd0EVHllbIt+tEZxNZL+jCu+4dkGLmwuhX1yg/4G+=Ye+B+-----END PGP PRIVATE KEY BLOCK-----diff --git a/tests/fixtures/openpgp/alice-public.asc b/tests/fixtures/openpgp/alice-public.ascnew file mode 100644index 0000000..60e3192--- /dev/null+++ b/tests/fixtures/openpgp/alice-public.asc@@ -0,0 +1,13 @@+-----BEGIN PGP PUBLIC KEY BLOCK-----++mDMEasZ61xYJKwYBBAHaRw8BAQdABu5bIqXHj6bocVrIznYWjiVWrEa2u2cW1UNV+4/uoGam0JUFsaWNlIEZpeHR1cmUgPGFsaWNlQGVuY3J5cHRpb24udGVzdD6IkAQT+FgoAOBYhBOmnjgpiSv1/4RAhcOZXczHw16dsBQJqxnrXAhsDBQsJCAcCBhUKCQgL+AgQWAgMBAh4BAheAAAoJEOZXczHw16dsxQsA/Rv9dtdlgfyLDfmk83aDifCwla6t+7wAe/pYFEw17vFc1AP4qifND82gxbG/I9hm0AWwfXl8ltZ/TKC9igFzg259gBrg4+BGrGetcSCisGAQQBl1UBBQEBB0Au5a/tI2mO8QemNuB/HCG9Hib/5FOObYs2OuhV+sqIzQAMBCAeIeAQYFgoAIBYhBOmnjgpiSv1/4RAhcOZXczHw16dsBQJqxnrXAhsM+AAoJEOZXczHw16ds4yYBAK6sqvM21Tz0EwDHqxNhrCLkJMZMzvZJJfI24Lrp5q9w+AQDR3ypndBFR5ZWyLfrRGcTWS/owruHZBi5sLoV9coP+Bg==+=pAlq+-----END PGP PUBLIC KEY BLOCK-----diff --git a/tests/fixtures/openpgp/bob-private.asc b/tests/fixtures/openpgp/bob-private.ascnew file mode 100644index 0000000..1474aa5--- /dev/null+++ b/tests/fixtures/openpgp/bob-private.asc@@ -0,0 +1,15 @@+-----BEGIN PGP PRIVATE KEY BLOCK-----++lFgEasZ61xYJKwYBBAHaRw8BAQdA7a+cOkY1i68WtVsviLQsVpwWil5c3qobaIMl+kLWiZKsAAP4+kDToQXjadLYhT4BVzelQwxtTI6kaUTcDO7YdfxP/ig67tCFCb2Ig+Rml4dHVyZSA8Ym9iQGVuY3J5cHRpb24udGVzdD6IkAQTFgoAOBYhBIluQ2HEn9bX+TsA0oCh5dTF1OFGBBQJqxnrXAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAAAoJ+ECh5dTF1OFGBb+MA/il7iGRRP/0TX7pnbbTTuLiTIlG5kh4WUJ4hKx4CQqmYAQCd+PtddUoQ8FmC4AsDl5sxTgWNPAJLrIROfPRIhl9/eBZxdBGrGetcSCisGAQQBl1UB+BQEBB0BtSaiVHrs+XeKkGG7xsYcH5exeDxhAfTnEoC5dmyimIgMBCAcAAP9q8pei+GG8UOvcIsWTBetF71+UUMOZthLXjxxToUfDfABJWiHgEGBYKACAWIQSJbkNhxJ/W+107ANKAoeXUxdThRgQUCasZ61wIbDAAKCRAoeXUxdThRgZIwAQCCpypJ4Bfv/H1Q+84+BY7M0uSjV3Wqiuk/4DanKMWvhhAD9GhhO+5xrJIbaj/WOGGAdQxtBohxVzrbf+3hleipteKwk=+=givt+-----END PGP PRIVATE KEY BLOCK-----diff --git a/tests/fixtures/openpgp/bob-public.asc b/tests/fixtures/openpgp/bob-public.ascnew file mode 100644index 0000000..e10f62e--- /dev/null+++ b/tests/fixtures/openpgp/bob-public.asc@@ -0,0 +1,13 @@+-----BEGIN PGP PUBLIC KEY BLOCK-----++mDMEasZ61xYJKwYBBAHaRw8BAQdA7a+cOkY1i68WtVsviLQsVpwWil5c3qobaIMl+kLWiZKu0IUJvYiBGaXh0dXJlIDxib2JAZW5jcnlwdGlvbi50ZXN0PoiQBBMWCgA4+FiEEiW5DYcSf1tdOwDSgKHl1MXU4UYEFAmrGetcCGwMFCwkIBwIGFQoJCAsCBBYC+AwECHgECF4AACgkQKHl1MXU4UYFv4wD+KXuIZFE//RNfumdttNO4uJMiUbmSHhZQ+niErHgJCqZgBAJ0+111ShDwWYLgCwOXmzFOBY08AkushE589EiGX394FuDgEasZ6+1xIKKwYBBAGXVQEFAQEHQG1JqJUeuz5d4qQYbvGxhwfl7F4PGEB9OcSgLl2bKKYi+AwEIB4h4BBgWCgAgFiEEiW5DYcSf1tdOwDSgKHl1MXU4UYEFAmrGetcCGwwACgkQ+KHl1MXU4UYGSMAEAgqcqSeAX7/x9UPOPgWOzNLko1d1qorpP+A2pyjFr4YQA/RoY+TvucaySG2o/1jhhgHUMbQaIcVc62394ZXoqbXisJ+=XQt3+-----END PGP PUBLIC KEY BLOCK-----diff --git a/tests/fixtures/openpgp/carol-private.asc b/tests/fixtures/openpgp/carol-private.ascnew file mode 100644index 0000000..8225d0c--- /dev/null+++ b/tests/fixtures/openpgp/carol-private.asc@@ -0,0 +1,15 @@+-----BEGIN PGP PRIVATE KEY BLOCK-----++lFgEasZ61xYJKwYBBAHaRw8BAQdAl45RxD20I/vRVznYqsMnI1HqpiaUYHd2rQUg+SffNsXoAAQD5fqsRigyRLmkBhCQ5JY+V2MjT3VuXdbMsmUASRYGu5w75tCVDYXJv+bCBGaXh0dXJlIDxjYXJvbEBlbmNyeXB0aW9uLnRlc3Q+iJAEExYKADgWIQSAGdNt+CqE8O5TRncD4l6okvp8+4gUCasZ61wIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIX+gAAKCRD4l6okvp8+4pRLAQCfmERIBpq+63mg+gpgt2DhN54usEAW76ML2vU8BLqe+zwD/X6yTmLMOrlA+RPiO/nk9SPoWVzA4bmQk3AWs2En87wWcXQRqxnrXEgorBgEE+AZdVAQUBAQdAAd819Q4iTd+tR3iT3UfqpP3c+iOO5ra3NVrHT6XH3CsDAQgHAAD/+fNsls8BchBRp7W6HLsY38v158yXeBaWctd5iak9/HrAR94h4BBgWCgAgFiEEgBnT+bQqhPDuU0Z3A+JeqJL6fPuIFAmrGetcCGwwACgkQ+JeqJL6fPuLTswEAns3BgZDu+SlMTnrEEMYBbkUxlbmhxX6lZmszJX6b0W6ABAJNIrGbJOImZQX2Vt5K+nVYPq3GM+E0JSZxuaTaXbCx0J+=ce98+-----END PGP PRIVATE KEY BLOCK-----diff --git a/tests/fixtures/openpgp/carol-public.asc b/tests/fixtures/openpgp/carol-public.ascnew file mode 100644index 0000000..28ad47d--- /dev/null+++ b/tests/fixtures/openpgp/carol-public.asc@@ -0,0 +1,13 @@+-----BEGIN PGP PUBLIC KEY BLOCK-----++mDMEasZ61xYJKwYBBAHaRw8BAQdAl45RxD20I/vRVznYqsMnI1HqpiaUYHd2rQUg+SffNsXq0JUNhcm9sIEZpeHR1cmUgPGNhcm9sQGVuY3J5cHRpb24udGVzdD6IkAQT+FgoAOBYhBIAZ020KoTw7lNGdwPiXqiS+nz7iBQJqxnrXAhsDBQsJCAcCBhUKCQgL+AgQWAgMBAh4BAheAAAoJEPiXqiS+nz7ilEsBAJ+YREgGmr7reaD6CmC3YOE3ni6w+QBbvowva9TwEup7PAP9frJOYsw6uUD5E+I7+eT1I+hZXMDhuZCTcBazYSfzvBbg4+BGrGetcSCisGAQQBl1UBBQEBB0AB3zX1DiJN361HeJPdR+qk/dz6I47mtrc1WsdP+pcfcKwMBCAeIeAQYFgoAIBYhBIAZ020KoTw7lNGdwPiXqiS+nz7iBQJqxnrXAhsM+AAoJEPiXqiS+nz7i07MBAJ7NwYGQ7kpTE56xBDGAW5FMZW5ocV+pWZrMyV+m9Fug+AQCTSKxmyTiJmUF9lbeSvp1WD6txjBNCUmcbmk2l2wsdCQ==+=PK5J+-----END PGP PUBLIC KEY BLOCK-----diff --git a/tests/fixtures/openpgp/encrypted-bcc.eml b/tests/fixtures/openpgp/encrypted-bcc.emlnew file mode 100644index 0000000..d4fce6b--- /dev/null+++ b/tests/fixtures/openpgp/encrypted-bcc.eml@@ -0,0 +1,34 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="fixture-pgp"++--fixture-pgp+Content-Type: application/pgp-encrypted++Version: 1++--fixture-pgp+Content-Type: application/octet-stream++-----BEGIN PGP MESSAGE-----++hF4DPybE4lg1cQsSAQdALzSH/uzAvKeyxqt8wY3qmKuFx5hIuvhT++qrS8JPjTsw+v2j9Eu8yxEiQYVtrkhaJa3MoaIz7ZPDBPbp1EN/feFTplPx0/9QZQyHc1ovvFTFF+hF4DpmEGRpxqMycSAQdAJj2/YQ64U1A0W8BzZfrFAv8KxXUW4AqVAVJyWf5jchow+bDza+YHpsXwBgQr1Eig7OAiE7+DpOjsSZdGeOj+k0sEXzvJm5AyRn0Oga66oyV4l+hF4DAAAAAAAAAAASAQdAfXNV1EM41NmT1cyJODlkZcE027AVWa6guLm+2l6lWkMw+2Xu4Y/h69m2Zymp4yOaubl25EJN9Ch6yCnPbB4CuF7BGsLPFPxjGQAtJ7OXmAXyn+0sB+AZNo/CxrTqbtQxGQ7LIR9IvyWBRaT44hUsZ3eat9mrTuzeOijPETyjP/rKuB+rSP1ckcUeqkN7Fq070nLQ2ahN3zD8NBgI33GIv88KM7dLaquXXl8mOJ6J0s6JAuJ+6QU9DBBEQJx1sKeOMPoPHpVVh4VCJ77KT1e+CrBzefuQlku7KPj5GeMHnq4FGiuK+C2MBtDYs9/oZyIAzpDP4pQhrdedf2M0Wx0l8Iniz3rE5Ro3pSAk/FBCbydjrs8Jd+eQr0FQZUy4I9KCLi3LrbKtIKNYQqpWdcdI6vviohHqwRc8YxZ32xRgrpPCzuxXgx+bcYDN5yHaXNZIYoEYi50ltRn1yQcGnzvKoJallgLDxMFL3n40sHWDg2dIkG1YSIm+GRQ3yAjGTH2TiZ0qAgjI3y7/x+KTZxcaUV6pLPSMjCtQ+=NGHg+-----END PGP MESSAGE-----++--fixture-pgp--diff --git a/tests/fixtures/openpgp/encrypted-signed.eml b/tests/fixtures/openpgp/encrypted-signed.emlnew file mode 100644index 0000000..4b20299--- /dev/null+++ b/tests/fixtures/openpgp/encrypted-signed.eml@@ -0,0 +1,35 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="fixture-pgp"++--fixture-pgp+Content-Type: application/pgp-encrypted++Version: 1++--fixture-pgp+Content-Type: application/octet-stream++-----BEGIN PGP MESSAGE-----++hF4DPybE4lg1cQsSAQdANtMh9amz06ca0eZYn0ZsGF8SO1ftDQcP8pYv3lYPlVww+32X1NQH6b2J5qIAFKyVDxeeAHvhD8VynkXDkmBVtZZSXQIz40QjXase0A1gbgnvE+hF4DpmEGRpxqMycSAQdA56WcnMiVMak3lx+yNhw3+BRd/28HtJfSTWvDmYDZ0iIw+Vge/LgiYPZFI+0TNZ9wP+ZUje/djokO8cg8HtU7QB+fDi8q+6lKYaFo75bx/QJXg+0sEHAV2zp2PMi73rB2dcZPHAXp8tXUknPEQR+DoLjhRn+K/rt0NEWVg/g1eS/lnZ+Os0cGewwwxdIxw+25XaIM24K34ZOb4f8e/jjporhpi8iMzosyjyHQ/d2os5xHxB2+3e2iH3XoEjD7ZJl9KbvLzyFzpyZAE5/QLE/l9sTDMp8Lbs0+asMNIGugXpGsod+G+Vw+0YUdHIoWINHdGz82/CL2KqDtMLqo9bzdPU2XRsp82rh/ob23NXZa2y1VnbKi8+ZcMf/bFlJHffbmQy+u7C5pCeoCFSgEUd2yy4sJIsEo5jW/bylH931QyMpRCXWaAx+ZWDyf6QFbDdodcNmUuU7goQH7tMqteCzbqrHs13ZdOf6Rf8xEmAJ48b2/LdY7zRM+JPYcfOm69cVQhMtgrxiKD3Umc7RR42wJWN/qa3dw43Y2Q+nNKLmDvg6Hjuzq/yE8+guQyOj6liTbF4NnOdtO20+tnLV0t2kJcfl5JHy4OVf4jqLxdg6nNBBMi0v4vhpCT+aPgyrNU2KKi+OX7mtzTr8SibKB1c0Sg589PkAiivWU+6Pnegs+bwVbFOvHrYLhan+MwyEY3iGfZG9ofsM+fnS7V67vWkQwi90yME=+=JeAw+-----END PGP MESSAGE-----++--fixture-pgp--diff --git a/tests/fixtures/openpgp/encrypted-unsigned.eml b/tests/fixtures/openpgp/encrypted-unsigned.emlnew file mode 100644index 0000000..30485b5--- /dev/null+++ b/tests/fixtures/openpgp/encrypted-unsigned.eml@@ -0,0 +1,32 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="fixture-pgp"++--fixture-pgp+Content-Type: application/pgp-encrypted++Version: 1++--fixture-pgp+Content-Type: application/octet-stream++-----BEGIN PGP MESSAGE-----++hF4DPybE4lg1cQsSAQdAkcRGrljE3UEdJQL8sf0/h2o0uJkbe8aRY56H11OKfEAw+oOtyzbMPFIX/lER8Jqc5HJRwNsZYNNs5EHOWIXXNGpj8rilryLcay2BISaUrMQ/5+hF4DpmEGRpxqMycSAQdAMk96vIGF1BJXYrZFIs95Er6+OnRLF2ZZB3LU3VC5wDsw++ur0JAfV4FS+Tnlzhju9dh5C/qWBXiFWWIra/qvQ9miCZzqftyZ2fqVakqLz4bhE+0sB+Act+b0ZeUJoJha2J0u/sy8wxYhCUABjyIqJX3aw7xwRovu3uvuQkGMaIYAXX+xQHC6gULF3i+nJmJTEB/S7J8z86Ox8yfbT1pTIGv0xn119TuUcqmA1XINFg+ILEV+ST+vVWS04g1QB5vB3YTLxXwSTZ0TPAZBYiZmzrGOkX81qeatLWRnTJtgMiaUFJfN+HwQcY+t+fHg7Um1bUVHIBo9dbYnEFc/esTcrWmdQzbuLFCpLT67LSSn5o6QXt7EO+NiPNP0yx0LeFX/vgesXl75FZ0R5zcBKtCyM72WwSltTDAcupRYp7V+jCstOEGYY4+uLVLw/M/YkiFot7L/zayhoeU8VS53SX9mI0lAOfSuu+Lgv9N6cKL4QctSfW3cPRc+PD5byAkEjGI35ecmgZLasHY8vUMX3EQ5m+JULzHN9xoM+=wx16+-----END PGP MESSAGE-----++--fixture-pgp--diff --git a/tests/fixtures/openpgp/entity.mime b/tests/fixtures/openpgp/entity.mimenew file mode 100644index 0000000..ec458b8--- /dev/null+++ b/tests/fixtures/openpgp/entity.mime@@ -0,0 +1,24 @@+Content-Type: multipart/mixed; boundary="fixture-mixed"++--fixture-mixed+Content-Type: multipart/alternative; boundary="fixture-alt"++--fixture-alt+Content-Type: text/plain; charset=utf-8+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYm9keS4=+--fixture-alt+Content-Type: text/html; charset=utf-8+Content-Transfer-Encoding: base64++PHA+U2VjcmV0IGZpeHR1cmUgYm9keS48L3A++--fixture-alt--++--fixture-mixed+Content-Type: text/plain; name="secret.txt"+Content-Disposition: attachment; filename="secret.txt"+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYXR0YWNobWVudC4=+--fixture-mixed--diff --git a/tests/fixtures/openpgp/generate.py b/tests/fixtures/openpgp/generate.pynew file mode 100644index 0000000..ce8622c--- /dev/null+++ b/tests/fixtures/openpgp/generate.py@@ -0,0 +1,50 @@+#!/usr/bin/env python3+"""Generate synthetic interoperability fixtures with GnuPG, independent of OpenPGP.js."""+from pathlib import Path+import subprocess+import tempfile+import sys++out = Path(__file__).resolve().parent+with tempfile.TemporaryDirectory(prefix='inlark-gpg-') as home:+ base = ['gpg', '--homedir', home, '--batch', '--yes', '--no-tty', '--pinentry-mode', 'loopback', '--passphrase', '']+ def run(args, data=None):+ result = subprocess.run(base + args, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ if result.returncode:+ sys.stderr.write(result.stderr.decode())+ result.check_returncode()+ return result.stdout+ keys = {}+ for name in ['alice', 'bob', 'carol']:+ address = f'{name}@encryption.test'+ run(['--quick-generate-key', f'{name.title()} Fixture <{address}>', 'ed25519', 'sign', '0'])+ fingerprint = next(line.split(':')[9] for line in run(['--with-colons', '--list-keys', address]).decode().splitlines() if line.startswith('fpr:'))+ run(['--quick-add-key', fingerprint, 'cv25519', 'encr', '0'])+ keys[name] = fingerprint+ (out / f'{name}-public.asc').write_bytes(run(['--armor', '--export', fingerprint]))+ (out / f'{name}-private.asc').write_bytes(run(['--armor', '--export-secret-keys', fingerprint]))+ entity = ('Content-Type: multipart/mixed; boundary="fixture-mixed"\r\n\r\n'+ '--fixture-mixed\r\nContent-Type: multipart/alternative; boundary="fixture-alt"\r\n\r\n'+ '--fixture-alt\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n'+ 'U2VjcmV0IGZpeHR1cmUgYm9keS4=\r\n--fixture-alt\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n'+ 'PHA+U2VjcmV0IGZpeHR1cmUgYm9keS48L3A+\r\n--fixture-alt--\r\n'+ '\r\n--fixture-mixed\r\nContent-Type: text/plain; name="secret.txt"\r\nContent-Disposition: attachment; filename="secret.txt"\r\nContent-Transfer-Encoding: base64\r\n\r\n'+ 'U2VjcmV0IGZpeHR1cmUgYXR0YWNobWVudC4=\r\n--fixture-mixed--\r\n').encode()+ (out / 'entity.mime').write_bytes(entity)+ headers = b'From: Alice Fixture <[email protected]>\r\nTo: Bob Fixture <[email protected]>\r\nSubject: Visible fixture subject\r\nDate: Wed, 7 Oct 2026 10:00:00 +0000\r\nMIME-Version: 1.0\r\n'+ def encrypted(armor):+ return headers + b'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="fixture-pgp"\r\n\r\n--fixture-pgp\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--fixture-pgp\r\nContent-Type: application/octet-stream\r\n\r\n' + armor.replace(b'\n', b'\r\n') + b'\r\n--fixture-pgp--\r\n'+ for name, flags in [('encrypted-unsigned', []), ('encrypted-signed', ['--sign']), ('encrypted-bcc', ['--hidden-recipient', keys['carol']])]:+ armor = run(['--armor', '--trust-model', 'always', '--local-user', keys['alice'], '--recipient', keys['alice'], '--recipient', keys['bob']] + flags + ['--encrypt'], entity)+ (out / f'{name}.eml').write_bytes(encrypted(armor))+ signature = run(['--armor', '--local-user', keys['alice'], '--detach-sign'], entity).replace(b'\n', b'\r\n')+ signed = headers + b'Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="fixture-sig"\r\n\r\n--fixture-sig\r\n' + entity + b'\r\n--fixture-sig\r\nContent-Type: application/pgp-signature\r\n\r\n' + signature + b'\r\n--fixture-sig--\r\n'+ (out / 'signed.eml').write_bytes(signed)+ (out / 'invalid-signature.eml').write_bytes(signed.replace(b'U2VjcmV0IGZpeHR1cmUgYm9keS4=', b'QWx0ZXJlZCBmaXh0dXJlIGJvZHk='))+ text = b'Secret inline fixture body.\n'+ inline = run(['--armor', '--trust-model', 'always', '--recipient', keys['bob'], '--encrypt'], text)+ (out / 'inline-encrypted.eml').write_bytes(headers + b'Content-Type: text/plain; charset=utf-8\r\n\r\n' + inline.replace(b'\n', b'\r\n'))+ clear = run(['--armor', '--local-user', keys['alice'], '--clearsign'], text)+ (out / 'inline-signed.eml').write_bytes(headers + b'Content-Type: text/plain; charset=utf-8\r\n\r\n' + clear.replace(b'\n', b'\r\n'))+ (out / 'unsigned.eml').write_bytes(headers + entity)+ subprocess.run(['gpgconf', '--homedir', home, '--kill', 'gpg-agent'], check=False)diff --git a/tests/fixtures/openpgp/inline-encrypted.eml b/tests/fixtures/openpgp/inline-encrypted.emlnew file mode 100644index 0000000..a08e8a0--- /dev/null+++ b/tests/fixtures/openpgp/inline-encrypted.eml@@ -0,0 +1,15 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: text/plain; charset=utf-8++-----BEGIN PGP MESSAGE-----++hF4DpmEGRpxqMycSAQdAdx7xQEcQN85Drb3Pt0RNY1IRaiy1xCfTd6FOHV1HSXww+A/dPDWB52SDKKHva/UzGlkuLGyqRLZD00qz6xkJcMAg3H8oD58d+SZGxry/Xl9/e+0lcBIWXXrJnSDsM4aKbggI6CzyYszgRAYIFKfL8gM+8Wo3+d+D3hPq5GXOelJJ97+6FvU2i0oVMNpcJAILM1ieh00WxfFTPIc7F8a8Cz1G4HPOT+A2CsXwwI=+=FZZ0+-----END PGP MESSAGE-----diff --git a/tests/fixtures/openpgp/inline-signed.eml b/tests/fixtures/openpgp/inline-signed.emlnew file mode 100644index 0000000..96f5a48--- /dev/null+++ b/tests/fixtures/openpgp/inline-signed.eml@@ -0,0 +1,19 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: text/plain; charset=utf-8++-----BEGIN PGP SIGNED MESSAGE-----+Hash: SHA512++Secret inline fixture body.++-----BEGIN PGP SIGNATURE-----++iHUEARYKAB0WIQTpp44KYkr9f+EQIXDmV3Mx8NenbAUCasZ61wAKCRDmV3Mx8Nen+bJpqAP4sieOMhFiX09hTadcSQ8UpQvADuXEYkpLjrrfax4MfhAD/U0gmI6ObChS1+fBCX6YoLvhbKubZFa6xbKutZQnuTugo=+=PsA4+-----END PGP SIGNATURE-----diff --git a/tests/fixtures/openpgp/invalid-signature.eml b/tests/fixtures/openpgp/invalid-signature.emlnew file mode 100644index 0000000..5f0da3d--- /dev/null+++ b/tests/fixtures/openpgp/invalid-signature.eml@@ -0,0 +1,45 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="fixture-sig"++--fixture-sig+Content-Type: multipart/mixed; boundary="fixture-mixed"++--fixture-mixed+Content-Type: multipart/alternative; boundary="fixture-alt"++--fixture-alt+Content-Type: text/plain; charset=utf-8+Content-Transfer-Encoding: base64++QWx0ZXJlZCBmaXh0dXJlIGJvZHk=+--fixture-alt+Content-Type: text/html; charset=utf-8+Content-Transfer-Encoding: base64++PHA+U2VjcmV0IGZpeHR1cmUgYm9keS48L3A++--fixture-alt--++--fixture-mixed+Content-Type: text/plain; name="secret.txt"+Content-Disposition: attachment; filename="secret.txt"+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYXR0YWNobWVudC4=+--fixture-mixed--++--fixture-sig+Content-Type: application/pgp-signature++-----BEGIN PGP SIGNATURE-----++iHUEABYKAB0WIQTpp44KYkr9f+EQIXDmV3Mx8NenbAUCasZ61wAKCRDmV3Mx8Nen+bKIjAP42UQHn4WW6EmXeVzOdqeZR+FpOIuZ8hK5hSc5QCnp39gEArr2x8xWcySUe+EVqGH27Z+3ug8/LmRJtmr3Su1G05iAM=+=C+Qm+-----END PGP SIGNATURE-----++--fixture-sig--diff --git a/tests/fixtures/openpgp/signed.eml b/tests/fixtures/openpgp/signed.emlnew file mode 100644index 0000000..ff53090--- /dev/null+++ b/tests/fixtures/openpgp/signed.eml@@ -0,0 +1,45 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="fixture-sig"++--fixture-sig+Content-Type: multipart/mixed; boundary="fixture-mixed"++--fixture-mixed+Content-Type: multipart/alternative; boundary="fixture-alt"++--fixture-alt+Content-Type: text/plain; charset=utf-8+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYm9keS4=+--fixture-alt+Content-Type: text/html; charset=utf-8+Content-Transfer-Encoding: base64++PHA+U2VjcmV0IGZpeHR1cmUgYm9keS48L3A++--fixture-alt--++--fixture-mixed+Content-Type: text/plain; name="secret.txt"+Content-Disposition: attachment; filename="secret.txt"+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYXR0YWNobWVudC4=+--fixture-mixed--++--fixture-sig+Content-Type: application/pgp-signature++-----BEGIN PGP SIGNATURE-----++iHUEABYKAB0WIQTpp44KYkr9f+EQIXDmV3Mx8NenbAUCasZ61wAKCRDmV3Mx8Nen+bKIjAP42UQHn4WW6EmXeVzOdqeZR+FpOIuZ8hK5hSc5QCnp39gEArr2x8xWcySUe+EVqGH27Z+3ug8/LmRJtmr3Su1G05iAM=+=C+Qm+-----END PGP SIGNATURE-----++--fixture-sig--diff --git a/tests/fixtures/openpgp/unsigned.eml b/tests/fixtures/openpgp/unsigned.emlnew file mode 100644index 0000000..4ed1db9--- /dev/null+++ b/tests/fixtures/openpgp/unsigned.eml@@ -0,0 +1,29 @@+From: Alice Fixture <[email protected]>+To: Bob Fixture <[email protected]>+Subject: Visible fixture subject+Date: Wed, 7 Oct 2026 10:00:00 +0000+MIME-Version: 1.0+Content-Type: multipart/mixed; boundary="fixture-mixed"++--fixture-mixed+Content-Type: multipart/alternative; boundary="fixture-alt"++--fixture-alt+Content-Type: text/plain; charset=utf-8+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYm9keS4=+--fixture-alt+Content-Type: text/html; charset=utf-8+Content-Transfer-Encoding: base64++PHA+U2VjcmV0IGZpeHR1cmUgYm9keS48L3A++--fixture-alt--++--fixture-mixed+Content-Type: text/plain; name="secret.txt"+Content-Disposition: attachment; filename="secret.txt"+Content-Transfer-Encoding: base64++U2VjcmV0IGZpeHR1cmUgYXR0YWNobWVudC4=+--fixture-mixed--diff --git a/tests/imap-convert.test.ts b/tests/imap-convert.test.tsindex fa75f22..d9a2278 100644--- a/tests/imap-convert.test.ts+++ b/tests/imap-convert.test.ts@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest'import { previewText } from '../packages/imap/src/convert'describe('IMAP previews', () => {+ it('excludes armored encrypted content from previews and the metadata index', () => {+ expect(previewText('-----BEGIN PGP MESSAGE-----\r\n\r\nEncrypted packet bytes')).toBe('')+ })it('normalizes whitespace and leaves quoted reply lines out', () => {expect(previewText(' Hello\tthere\r\n > Old reply\n\nNew text ')).toBe('Hello there New text')expect(previewText('x'.repeat(300))).toHaveLength(256)diff --git a/tests/jmap.test.ts b/tests/jmap.test.tsindex 866b0fa..96c0541 100644--- a/tests/jmap.test.ts+++ b/tests/jmap.test.ts@@ -349,4 +349,30 @@ describe('JMAP provider', () => {).toEqual({ url: 'https://list.example/unsubscribe', oneClick: true })expect(parseUnsubscribe('<javascript:alert(1)>')).toBeUndefined()})+ it('discovers bounded Autocrypt headers without requesting bodies or message blobs', async () => {+ const { provider, calls } = fixture({+ 'Email/get': () => ({+ list: [+ {+ ...raw('key'),+ 'header:Autocrypt:all': [+ '[email protected]; prefer-encrypt=mutual; keydata=YWJj',+ ],+ },+ { ...raw('wrong'), from: [{ email: '[email protected]' }] },+ ],+ }),+ })+ const [account] = await provider.connect()+ const hints = await provider.encryptionHints(account, '[email protected]')+ expect(hints).toHaveLength(1)+ expect(Buffer.from(hints[0].headers).toString()).toContain('prefer-encrypt=mutual')+ const query = calls.find((call) => call.name === 'Email/query')!+ expect(query.args.limit).toBeLessThanOrEqual(40)+ const get = calls.find((call) => call.name === 'Email/get')!+ expect(get.args.properties).not.toContain('blobId')+ expect(get.args.properties).not.toContain('bodyValues')+ expect(get.args.fetchAllBodyValues).toBeUndefined()+ provider.dispose()+ })})diff --git a/tests/stalwart-imap.integration.test.ts b/tests/stalwart-imap.integration.test.tsindex 9857dd9..fdcccb9 100644--- a/tests/stalwart-imap.integration.test.ts+++ b/tests/stalwart-imap.integration.test.ts@@ -1,3 +1,12 @@+import {+ CryptoEngine,+ mimeContent,+ replaceContent,+ encryptedMime,+ armoredPayload,+ autocryptHeader,+} from '../packages/crypto/src'+import { composeMime, parseMime } from '../packages/mime/src'import { describe, it, expect } from 'vitest'import { randomUUID } from 'node:crypto'import { readFileSync } from 'node:fs'@@ -264,4 +273,87 @@ describe.skipIf(!ready)('disposable Stalwart IMAP/SMTP integration', () => {jmap.dispose()}}, 120000)+ it('APPENDs encrypted drafts, retrieves byte-preserving sources and sends the same protected bytes through SMTP', async () => {+ const provider = imap(),+ [account] = await provider.connect(),+ [identity] = await provider.identities(account),+ engine = new CryptoEngine(),+ key = await engine.generate('Integration', identity.email)+ await engine.load([key])+ const draft: Draft = {+ id: randomUUID(),+ accountId: account.id,+ identityId: identity.id,+ to: [{ name: 'Self', email: identity.email }],+ cc: [],+ bcc: [],+ subject: 'Encrypted IMAP ' + randomUUID(),+ html: '<p>SECRET IMAP MARKER</p>',+ text: 'SECRET IMAP MARKER',+ attachments: [],+ updatedAt: new Date().toISOString(),+ status: 'local',+ encryption: 'encrypt',+ }+ const id = draft.id + '@inlark.test',+ plain = await composeMime({+ from: identity,+ to: draft.to,+ cc: [],+ bcc: [],+ subject: draft.subject,+ text: draft.text,+ html: draft.html,+ messageId: id,+ attachments: [+ {+ name: 'secret.txt',+ type: 'text/plain',+ content: Buffer.from('SECRET ATTACHMENT MARKER'),+ },+ ],+ })+ const encrypted = replaceContent(+ plain,+ encryptedMime(await engine.encrypt(mimeContent(plain), [key.publicKey], key.fingerprint)),+ ['Autocrypt-Draft-State: encrypt=yes'],+ )+ let serverId: string | undefined+ try {+ serverId = await provider.createDraft(account, draft, id, encrypted)+ const raw = await provider.rawMessage(account, serverId, 64 * 1024 * 1024)+ expect(Buffer.from(raw)).toEqual(encrypted)+ expect(Buffer.from(raw).toString()).not.toContain('MARKER')+ const content = await engine.decrypt(armoredPayload(raw), [key.publicKey])+ expect((await parseMime(content.data)).text).toContain('SECRET IMAP MARKER')+ expect(content.signatures[0].valid).toBe(true)+ const outgoing = await provider.prepareSubmission(+ account,+ draft,+ id,+ replaceContent(+ plain,+ encryptedMime(await engine.encrypt(mimeContent(plain), [key.publicKey], key.fingerprint)),+ [+ autocryptHeader(+ identity.email,+ await engine.autocryptKey(key.publicKey, identity.email),+ true,+ ),+ ],+ ),+ )+ expect((await provider.submit(account, outgoing)).accepted).toEqual([identity.email])+ await provider.fileSentCopy(account, outgoing)+ await sync(provider)+ expect(+ (await provider.encryptionHints(account, identity.email)).some((hint) =>+ Buffer.from(hint.headers).toString().includes('prefer-encrypt=mutual'),+ ),+ ).toBe(true)+ } finally {+ if (serverId) await provider.update(account, {}, [serverId])+ await provider.close()+ }+ }, 60000)})diff --git a/tests/stalwart.integration.test.ts b/tests/stalwart.integration.test.tsindex 52e8b4e..bf838f9 100644--- a/tests/stalwart.integration.test.ts+++ b/tests/stalwart.integration.test.ts@@ -1,3 +1,12 @@+import {+ CryptoEngine,+ mimeContent,+ replaceContent,+ encryptedMime,+ armoredPayload,+ autocryptHeader,+} from '../packages/crypto/src'+import { composeMime, parseMime } from '../packages/mime/src'import { describe, it, expect } from 'vitest'import { JmapProvider } from '../packages/jmap/src'import { randomUUID } from 'node:crypto'@@ -114,7 +123,7 @@ describe.skipIf(!serverUrl || !username || !password)('disposable Stalwart integconst outgoing = {messageId: draft.id + '@inlark.test',emailId,- envelope: { from: '', to: [] },+ envelope: { from: identities[0].email, to: [identities[0].email] },}expect((await provider.submit(account, outgoing, draft.identityId)).rejected).toEqual([])expect(await provider.submissionExists(account, outgoing)).toBe(true)@@ -156,4 +165,112 @@ describe.skipIf(!serverUrl || !username || !password)('disposable Stalwart integprovider.dispose()}}, 60000)+ it('imports complete encrypted MIME, resumes ciphertext drafts and submits with an explicit Bcc envelope', async () => {+ const provider = new JmapProvider({+ serverUrl: serverUrl!,+ authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64'),+ connectionId: 'encrypted-integration',+ name: 'Encrypted integration',+ })+ const [account] = await provider.connect(),+ [identity] = await provider.identities(account),+ engine = new CryptoEngine(),+ key = await engine.generate('Integration', identity.email)+ await engine.load([key])+ const draft: Draft = {+ id: randomUUID(),+ accountId: account.id,+ identityId: identity.id,+ to: [],+ cc: [],+ bcc: [{ name: 'Self', email: identity.email }],+ subject: 'Encrypted integration ' + randomUUID(),+ html: '<p>SECRET JMAP MARKER</p>',+ text: 'SECRET JMAP MARKER',+ attachments: [],+ updatedAt: new Date().toISOString(),+ status: 'local',+ encryption: 'encrypt',+ }+ const id = draft.id + '@inlark.test',+ plain = await composeMime({+ from: identity,+ to: [],+ cc: [],+ bcc: [],+ subject: draft.subject,+ text: draft.text,+ html: draft.html,+ messageId: id,+ attachments: [+ {+ name: 'secret.txt',+ type: 'text/plain',+ content: Buffer.from('SECRET ATTACHMENT MARKER'),+ },+ ],+ })+ const encrypted = replaceContent(+ plain,+ encryptedMime(+ await engine.encrypt(mimeContent(plain), [key.publicKey], key.fingerprint, true),+ ),+ ['Autocrypt-Draft-State: encrypt=yes; _by-choice=yes'],+ )+ const created: string[] = []+ try {+ const draftId = await provider.createDraft(account, draft, undefined, encrypted)+ created.push(draftId)+ const raw = await provider.rawMessage(account, draftId, 64 * 1024 * 1024)+ expect(Buffer.from(raw)).toEqual(encrypted)+ expect(Buffer.from(raw).toString()).not.toContain('MARKER')+ expect(+ (await parseMime((await engine.decrypt(armoredPayload(raw), [key.publicKey])).data))+ .attachments,+ ).toHaveLength(1)+ const outgoingMime = replaceContent(+ plain,+ encryptedMime(+ await engine.encrypt(mimeContent(plain), [key.publicKey], key.fingerprint, true),+ ),+ [+ autocryptHeader(+ identity.email,+ await engine.autocryptKey(key.publicKey, identity.email),+ true,+ ),+ ],+ )+ const outgoing = await provider.prepareSubmission(account, draft, id, outgoingMime)+ created.push(outgoing.emailId!)+ expect(outgoing.envelope.to).toEqual([identity.email])+ expect(+ Buffer.from(+ await provider.rawMessage(account, outgoing.emailId!, 64 * 1024 * 1024),+ ).toString(),+ ).toContain('prefer-encrypt=mutual')+ expect((await provider.submit(account, outgoing, identity.id)).accepted).toEqual([+ identity.email,+ ])+ expect(await provider.submissionExists(account, outgoing)).toBe(true)+ await expect+ .poll(+ async () =>+ (await provider.encryptionHints(account, identity.email))+ .map((hint) => Buffer.from(hint.headers).toString())+ .join('\n'),+ { timeout: 10000, interval: 250 },+ )+ .toContain('prefer-encrypt=mutual')+ expect(+ Buffer.from(+ await provider.rawMessage(account, outgoing.emailId!, 64 * 1024 * 1024),+ ).toString(),+ ).not.toContain('MARKER')+ } finally {+ await provider.messages(account, created)+ await provider.update(account, {}, created)+ provider.dispose()+ }+ }, 60000)})diff --git a/vitest.config.ts b/vitest.config.tsindex af7c9cf..dbef765 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -4,6 +4,8 @@ export default defineConfig({resolve: {alias: {electron: fileURLToPath(new URL('./tests/electron.stub.ts', import.meta.url)),+ '@inlark/crypto': fileURLToPath(new URL('./packages/crypto/src/index.ts', import.meta.url)),+ '@inlark/mime': fileURLToPath(new URL('./packages/mime/src/index.ts', import.meta.url)),'@inlark/core': fileURLToPath(new URL('./packages/core/src/index.ts', import.meta.url)),'@inlark/jmap': fileURLToPath(new URL('./packages/jmap/src/index.ts', import.meta.url)),'@inlark/imap': fileURLToPath(new URL('./packages/imap/src/index.ts', import.meta.url)),