📧✨ Beautiful email. For everyone.
feat: trust self-signed server certificates (#26)
Paul Koeck27b57a258cca
diff --git a/README.md b/README.mdindex c0217d5..c6424f5 100644--- a/README.md+++ b/README.md@@ -102,6 +102,7 @@ Open **Settings → Accounts → Add account** and type your email address. Inla- **JMAP is preferred** when your server offers it. Inlark finds it through DNS SRV or `/.well-known/jmap`.- **IMAP/SMTP** settings come from your domain's autoconfig file or DNS SRV records. Only if your domain publishes nothing does Inlark ask Thunderbird's public settings directory, and then it sends just the domain.- **Encryption is required.** Inlark uses implicit TLS or required STARTTLS, always with certificate verification and never a plaintext fallback. Your password is never tried against a server you didn't choose.+- **Self-signed certificates are trusted one at a time.** When a certificate can't be verified, such as Proton Mail Bridge's on `127.0.0.1`, the connection check shows who it's issued to, how long it's valid and its SHA-256 fingerprint before any password is sent. You can trust exactly that certificate for that server. If it ever changes, Inlark stops before signing in and asks again. Expired certificates are never accepted.- **Passwords go into your OS keyring** when one is available. Without a keyring, you decide whether to remember a login on this device. If you do, the password is stored unencrypted in an owner-only file.IMAP accounts build a local index in the background, newest Inbox mail first. Until it catches up, lists tell you that older mail may be missing, and search still runs on the server. If your server can't do an action safely, such as a move without `MOVE` or `UIDPLUS`, Inlark turns it off and tells you why rather than guessing.diff --git a/apps/desktop/src/main/service.ts b/apps/desktop/src/main/service.tsindex f9fe330..a842d97 100644--- a/apps/desktop/src/main/service.ts+++ b/apps/desktop/src/main/service.ts@@ -1,4 +1,4 @@-import { randomUUID } from 'node:crypto'+import { randomUUID, X509Certificate } 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'@@ -10,12 +10,14 @@ import {friendlyError,draftFingerprint,connectionErrorCodes,+ isProviderError,ProviderError,type Account,type AccountAppearance,type Address,type Settings,type ConnectInput,+ type ConnectionCheck,type ConnectionConfig,type ConnectionSettings,type ConnectionTest,@@ -35,6 +37,7 @@ import {type DiscoveryResult,type OutgoingMessage,type SendResult,+ type ServerSettings,type SubmissionSummary,} from '@inlark/core'import { JmapProvider } from '@inlark/jmap'@@ -117,7 +120,9 @@ const definiteSubmissionCodes = ['authentication','outgoingAuthentication','outgoingNetwork',+ 'outgoingCertificate','tls',+ 'certificate','capability','mailboxes','submission',@@ -141,17 +146,35 @@ export interface ServiceOptions {providers?: ProviderFactorydiscover?: (email: string) => Promise<DiscoveryResult>}+/** Fingerprints shown to the user are computed here from the certificate itself, never taken on trust. */+function verifiedCertificates(config: ConnectionConfig): ConnectionConfig {+ if (config.protocol !== 'imap') return config+ const verified = (server: ServerSettings): ServerSettings => {+ if (!server.certificate) return server+ try {+ const sha256 = new X509Certificate(server.certificate.pem).fingerprint256+ return { ...server, certificate: { sha256, pem: server.certificate.pem } }+ } catch {+ throw new Error(+ `The trusted certificate for ${server.host} can't be read. Remove it and check the connection again.`,+ )+ }+ }+ return { ...config, incoming: verified(config.incoming), outgoing: verified(config.outgoing) }+}const errorKind = (error: unknown): DraftErrorKind | undefined =>error instanceof ProviderError? error.code === 'outgoingAuthentication'? 'outgoingAuthentication'- : error.code === 'submissionRejected'- ? 'rejected'- : error.code === 'conflict'- ? 'conflict'- : connectionErrorCodes.includes(error.code) || error.code === 'outgoingNetwork'- ? 'connection'- : undefined+ : error.code === 'certificate' || error.code === 'outgoingCertificate'+ ? 'certificate'+ : error.code === 'submissionRejected'+ ? 'rejected'+ : error.code === 'conflict'+ ? 'conflict'+ : connectionErrorCodes.includes(error.code) || error.code === 'outgoingNetwork'+ ? 'connection'+ : undefined: error instanceof Error && error.message.includes('another client')? 'conflict': undefined@@ -300,7 +323,8 @@ export class MailService {error.code === 'authentication' ? 'authentication' : 'offline',friendlyError(error),)- if (error instanceof ProviderError && error.code === 'outgoingAuthentication')+ // Neither resolves by retrying, so sending stays marked unavailable until the user acts.+ if (isProviderError(error, 'outgoingAuthentication', 'outgoingCertificate'))this.outgoing(account.connectionId, friendlyError(error))this.log('request-failed', error instanceof ProviderError ? error.code : 'local')throw error@@ -338,8 +362,17 @@ export class MailService {}/** Signs in to each server separately and reports each result. Nothing is saved or sent. */testConnection = async (input: ConnectInput): Promise<ConnectionTest> => {+ input = { ...input, config: verifiedCertificates(input.config) }const provider = this.createProvider('test-' + randomUUID(), input, true)const result: ConnectionTest = { incoming: { ok: false } }+ /** A refused certificate is read again without signing in, so the user can review it. */+ const failed = async (server: 'incoming' | 'outgoing', error: unknown) => {+ const check: ConnectionCheck = { ok: false, error: friendlyError(error) }+ const certificate =+ isProviderError(error, 'certificate', 'outgoingCertificate') &&+ (await provider.inspectCertificate?.(server).catch(() => undefined))+ return certificate ? { ...check, certificate } : check+ }try {const [accounts] = await Promise.allSettled([provider.connect()])if (accounts.status === 'fulfilled') {@@ -348,11 +381,11 @@ export class MailService {: { ok: false, error: 'This login does not provide an accessible mail account.' }if (accounts.value[0] && provider.folderMappings)result.folders = await provider.folderMappings(accounts.value[0]).catch(() => undefined)- } else result.incoming = { ok: false, error: friendlyError(accounts.reason) }+ } else result.incoming = await failed('incoming', accounts.reason)if (provider.verifyOutgoing)result.outgoing = await provider.verifyOutgoing().then(() => ({ ok: true }),- (error) => ({ ok: false, error: friendlyError(error) }),+ (error) => failed('outgoing', error),)return result} finally {@@ -362,6 +395,7 @@ export class MailService {}/** `reconnecting` restores a saved login, so labels and names edited since then are kept. */connect = async (input: ConnectInput, reconnecting = false): Promise<Account[]> => {+ input = { ...input, config: verifiedCertificates(input.config) }const id = input.connectionId || randomUUID()const previous = this.connections.find((c) => c.id === id)if (previous && previous.config.protocol !== input.config.protocol)diff --git a/apps/desktop/src/renderer/src/AccountSetup.tsx b/apps/desktop/src/renderer/src/AccountSetup.tsxindex 49cb10f..08cdf78 100644--- a/apps/desktop/src/renderer/src/AccountSetup.tsx+++ b/apps/desktop/src/renderer/src/AccountSetup.tsx@@ -10,13 +10,24 @@ import {} from 'react'import { useQuery } from '@tanstack/react-query'import { z } from 'zod'-import { AlertCircle, ArrowLeft, Check, LockKeyhole, PenLine, X as Cross } from '@inlark/ui/icons'+import {+ AlertCircle,+ ArrowLeft,+ Check,+ LockKeyhole,+ PenLine,+ ShieldCheck,+ ShieldX,+ X as Cross,+} from '@inlark/ui/icons'import { Button, Checkbox, Spinner } from '@inlark/ui'import {accountSchema,friendlyError,type Account,type Bootstrap,+ type CertificateDetails,+ type CertificateProblem,type ConnectInput,type ConnectionCheck,type ConnectionConfig,@@ -30,6 +41,7 @@ import {type Protocol,type ServerSettings,type TransportSecurity,+ type TrustedCertificate,} from '@inlark/core'import { api, isDemo } from './api'import { queryClient } from './cache'@@ -39,7 +51,12 @@ import { FolderMappingEditor, initialFolderChoices, needsFolderReview } from './/** `signIn` repeats a saved connection's login; `edit` opens its server settings for changes. */export type SetupMode = 'add' | 'signIn' | 'edit'type ServerKind = 'incoming' | 'outgoing'-type ServerFields = { host: string; port: string; security: TransportSecurity }+type ServerFields = {+ host: string+ port: string+ security: TransportSecurity+ certificate?: TrustedCertificate+}interface Fields {protocol: ProtocolserverUrl: string@@ -104,6 +121,7 @@ function fieldsFrom(source: ConnectionConfig | DiscoveryCandidate, email: stringhost: s.host,port: String(s.port),security: s.security,+ ...(s.certificate ? { certificate: s.certificate } : {}),})const username = source.incoming.username || emailconst outgoingUsername = source.outgoing.username || username@@ -212,7 +230,10 @@ function CheckRow({{check? check.ok? 'Signed in'- : check.error || 'Sign-in failed'+ : check.certificate+ ? 'Stopped before signing in: ' ++ problemTitles[check.certificate.problem].toLowerCase()+ : check.error || 'Sign-in failed': pending? 'Checking…': 'Not checked'}@@ -221,6 +242,179 @@ function CheckRow({)}+const problemTitles: Record<CertificateProblem, string> = {+ selfSigned: 'Self-signed certificate',+ unknownIssuer: 'Certificate from an unknown authority',+ otherName: 'Certificate for another server name',+ changed: 'Certificate changed',+ expired: 'Certificate expired',+ notYetValid: 'Certificate not valid yet',+}+const certificateDate = new Intl.DateTimeFormat(undefined, {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+})+const isLocal = (host: string) => /^(localhost|127(\.\d{1,3}){3}|\[?::1\]?)$/i.test(host)+/** Long enough to recognize, short enough for one line. */+const shortFingerprint = (sha256: string) => sha256.slice(0, 11) + '…' + sha256.slice(-11)++function certificateExplanation(certificate: CertificateDetails, host: string) {+ const local = isLocal(host)+ const intercepted = 'but it could also mean someone is intercepting the connection.'+ switch (certificate.problem) {+ case 'selfSigned':+ return (+ 'No certificate authority vouches for it. ' ++ (local+ ? 'That’s normal for a bridge on this computer, such as Proton Mail Bridge.'+ : 'That’s common for self-hosted servers, ' + intercepted)+ )+ case 'unknownIssuer':+ return (+ 'It’s issued by ' ++ certificate.issuer ++ ', an authority this computer doesn’t trust. ' ++ (local+ ? 'That’s normal for a server on this computer.'+ : 'That’s common on private networks, ' + intercepted)+ )+ case 'otherName':+ return (+ 'It’s issued for ' ++ (certificate.names.join(', ') || certificate.subject) ++ ', not ' ++ host ++ '. If one of those names is your server, use it instead.'+ )+ case 'changed':+ return (+ 'It isn’t the certificate you trusted before. ' ++ (local+ ? 'That’s expected after the bridge is reinstalled or reset.'+ : 'That’s expected after the certificate is renewed, ' + intercepted)+ )+ case 'expired':+ return (+ 'It expired on ' ++ certificateDate.format(new Date(certificate.validTo)) ++ ', so it can’t be trusted. Renew it on the server, then try again.'+ )+ case 'notYetValid':+ return (+ 'It isn’t valid until ' ++ certificateDate.format(new Date(certificate.validFrom)) ++ '. Check that this computer’s date and time are correct.'+ )+ }+}++/** A certificate that stopped the connection check, with what the user needs to judge it. */+function CertificateReview({+ certificate,+ host,+ servers,+ action,+ disabled,+ onTrust,+}: {+ certificate: CertificateDetails+ host: string+ servers: ServerKind[]+ action: string+ disabled: boolean+ onTrust: () => void+}) {+ const trustable = certificate.problem !== 'expired' && certificate.problem !== 'notYetValid'+ const names = certificate.names.filter((name) => name !== certificate.subject)+ return (+ <div className="certificate-review mt-3 pt-3 pb-3.5 px-3.5 border border-solid border-border-strong rounded-lg bg-field text-[12px]">+ <div className="flex items-start gap-2.5">+ <ShieldX size={15} className="shrink-0 mt-[1px] text-danger" />+ <div className="min-w-0">+ <div className="flex flex-wrap items-baseline gap-[2px_10px]">+ <strong className="font-medium text-strong">+ {problemTitles[certificate.problem]}+ </strong>+ <span className="text-[11px] text-muted">+ {host} ·{' '}+ {servers.length > 1+ ? 'incoming and outgoing'+ : servers[0] === 'incoming'+ ? 'incoming'+ : 'outgoing'}+ </span>+ </div>+ <p className="mt-1 mb-0 mx-0 text-secondary leading-[1.6]">+ {certificateExplanation(certificate, host)}+ </p>+ </div>+ </div>+ <dl+ className={cn(+ 'certificate-details [&>div]:grid [&>div]:grid-cols-[92px_minmax(0,_1fr)] [&>div]:gap-3 [&>div]:py-1.5',+ '[&_dt]:text-muted [&_dd]:m-0 [&_dd]:min-w-0 [&_dd]:text-foreground [&_dd]:[overflow-wrap:anywhere]',+ 'mt-2.5 mb-0 ml-6.25 mr-0 text-[11px]',+ )}+ >+ <div>+ <dt>Issued to</dt>+ <dd>+ {certificate.subject}+ {names.length > 0 && <span className="text-muted"> · {names.join(', ')}</span>}+ </dd>+ </div>+ <div>+ <dt>Issued by</dt>+ <dd>{certificate.issuer}</dd>+ </div>+ <div>+ <dt>Valid</dt>+ <dd className="tabular-nums">+ {certificateDate.format(new Date(certificate.validFrom))} –{' '}+ {certificateDate.format(new Date(certificate.validTo))}+ </dd>+ </div>+ <div>+ <dt>SHA-256</dt>+ <dd className="font-mono text-[10.5px] leading-[1.7] select-all">+ {/* Breaks after 16 of the 32 pairs when it doesn't fit on one line. */}+ {certificate.sha256.slice(0, 48)}+ <wbr />+ {certificate.sha256.slice(48)}+ </dd>+ </div>+ </dl>+ {trustable && (+ <div className="flex items-center gap-3 mt-3 ml-6.25 max-[700px]:flex-col max-[700px]:items-start">+ <p className="flex-1 m-0 text-[11px] text-muted leading-[1.6]">+ Trust it only if you expect it, for example by comparing the fingerprint with the one+ your server or bridge shows. Inlark will accept exactly this certificate and stop if it+ ever changes.+ </p>+ <Button size="small" className="shrink-0" disabled={disabled} onClick={onTrust}>+ <ShieldCheck size={13} />+ {action}+ </Button>+ </div>+ )}+ </div>+ )+}++/** Each certificate that stopped a server, once, with the servers that presented it. */+function certificateReviews(test?: ConnectionTest) {+ const reviews: { certificate: CertificateDetails; servers: ServerKind[] }[] = []+ for (const kind of ['incoming', 'outgoing'] as const) {+ const certificate = test?.[kind]?.certificate+ if (!certificate) continue+ const same = reviews.find((r) => r.certificate.sha256 === certificate.sha256)+ if (same) same.servers.push(kind)+ else reviews.push({ certificate, servers: [kind] })+ }+ return reviews+}+/** The server settings of a discovered or saved configuration, shown before any password is sent. */function ServerSummary({ fields }: { fields: Fields }) {return fields.protocol === 'jmap' ? (@@ -256,6 +450,15 @@ function ServerSummary({ fields }: { fields: Fields }) {<span className="server-meta text-secondary tabular-nums">Port {fields[kind].port} · {securityLabel[fields[kind].security]}</span>+ {fields[kind].certificate && (+ <span+ className="server-certificate inline-flex items-center gap-1.25 text-secondary"+ title={'SHA-256 ' + fields[kind].certificate.sha256}+ >+ <ShieldCheck size={12} className="text-success" />+ Trusted certificate+ </span>+ )}</dd></div>))}@@ -453,33 +656,39 @@ export function AccountSetup({}/** Builds and validates the request, marking any field the schema rejects. */- const validate = (): ConnectInput | undefined => {+ const validate = (current: Fields): ConnectInput | undefined => {const address = email.trim()const config =- fields.protocol === 'jmap'+ current.protocol === 'jmap'? {protocol: 'jmap' as const,- serverUrl: fields.serverUrl.trim(),- username: fields.username.trim(),+ serverUrl: current.serverUrl.trim(),+ username: current.username.trim(),}: {protocol: 'imap' as const,email: address,incoming: {- host: fields.incoming.host,- port: Number(fields.incoming.port.trim()) || 0,- security: fields.incoming.security,- username: fields.username.trim(),+ host: current.incoming.host,+ port: Number(current.incoming.port.trim()) || 0,+ security: current.incoming.security,+ username: current.username.trim(),+ ...(current.incoming.certificate+ ? { certificate: current.incoming.certificate }+ : {}),},outgoing: {- host: fields.outgoing.host,- port: Number(fields.outgoing.port.trim()) || 0,- security: fields.outgoing.security,- username: (fields.sameLogin ? fields.username : fields.outgoingUsername).trim(),+ host: current.outgoing.host,+ port: Number(current.outgoing.port.trim()) || 0,+ security: current.outgoing.security,+ username: (current.sameLogin ? current.username : current.outgoingUsername).trim(),+ ...(current.outgoing.certificate+ ? { certificate: current.outgoing.certificate }+ : {}),},- outgoingSameCredentials: fields.sameLogin,+ outgoingSameCredentials: current.sameLogin,}- const separate = fields.protocol === 'imap' && !fields.sameLogin+ const separate = current.protocol === 'imap' && !current.sameLoginconst parsed = accountSchema.safeParse({config,password,@@ -533,10 +742,13 @@ export function AccountSetup({if (pending.current) await connect({ ...pending.current, folders: choices })return}- const input = validate()+ const input = validate(fields)if (!input) returnif (input.config.protocol === 'jmap') return connect(input)- // IMAP checks both servers first, so a failure names the server that needs attention.+ await check(input)+ }+ /** IMAP checks both servers first, so a failure names the server that needs attention. */+ const check = async (input: ConnectInput) => {setBusy('testing')setError('')setTest(undefined)@@ -573,6 +785,19 @@ export function AccountSetup({setBusy(undefined)}}+ /** Trusts a certificate for each server that presented it, then checks again. */+ const trust = (certificate: CertificateDetails, servers: ServerKind[]) => {+ if (busy) return+ const next = { ...fields }+ for (const kind of servers)+ next[kind] = {+ ...next[kind],+ certificate: { sha256: certificate.sha256, pem: certificate.pem },+ }+ setFields(next)+ const input = validate(next)+ if (input) void check(input)+ }const title =mode === 'edit' ? 'Edit connection' : mode === 'signIn' ? 'Sign in again' : 'Connect an account'@@ -598,6 +823,9 @@ export function AccountSetup({const isBusy = discovering || !!busyconst selected = origin.kind === 'candidate' ? candidates[origin.index] : undefinedconst failed = test && (!test.incoming.ok || (test.outgoing && !test.outgoing.ok))+ const reviews = certificateReviews(test)+ const trustLabel =+ mode === 'add' ? 'Trust and connect' : mode === 'edit' ? 'Trust and save' : 'Trust and sign in'return (<form className="account-form max-w-140" ref={form} onSubmit={(e) => void submit(e)} noValidate>@@ -896,6 +1124,27 @@ export function AccountSetup({/></div></div>+ {fields[kind].certificate && (+ <div className="trusted-certificate flex items-center gap-2 mt-2.5 text-[11px] text-muted">+ <ShieldCheck size={13} className="shrink-0 text-success" />+ <span+ className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap"+ title={'SHA-256 ' + fields[kind].certificate.sha256}+ >+ Trusted certificate{' '}+ <span className="font-mono text-[10.5px]">+ {shortFingerprint(fields[kind].certificate.sha256)}+ </span>+ </span>+ <button+ type="button"+ className="shrink-0 border-0 bg-none bg-transparent text-primary text-[11px] p-0 hover:underline"+ onClick={() => updateServer(kind, { certificate: undefined })}+ >+ Stop trusting+ </button>+ </div>+ )}</fieldset>)))}@@ -1070,10 +1319,22 @@ export function AccountSetup({pending={busy === 'testing'}/></ul>+ {reviews.map(({ certificate, servers }) => (+ <CertificateReview+ key={certificate.sha256}+ certificate={certificate}+ host={fields[servers[0]].host}+ servers={servers}+ action={trustLabel}+ disabled={isBusy}+ onTrust={() => trust(certificate, servers)}+ />+ ))}{failed && (<p className="connection-check-hint mt-2.5 mb-0 mx-0 text-[11px] text-muted">- Nothing was saved. Check the password or the server settings above, then try- again.+ {reviews.length+ ? 'Nothing was saved. No password is sent to a server until its certificate is accepted.'+ : 'Nothing was saved. Check the password or the server settings above, then try again.'}</p>)}</section>diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxindex 812b9af..899bc3b 100644--- a/apps/desktop/src/renderer/src/Composer.tsx+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -70,6 +70,11 @@ function draftProblem(draft: Draft): { text: string; detail?: string } | undefin}case 'outgoingAuthentication':return { text: 'The outgoing server rejected your login. Nothing was sent.', detail }+ case 'certificate':+ return {+ text: 'The server’s certificate couldn’t be verified. Nothing was sent; your draft is saved.',+ detail,+ }case 'connection':return {text: 'The server couldn’t be reached. Nothing was sent; your draft is saved.',@@ -675,7 +680,8 @@ export function Composer({Keep both versions</Button>)}- {shown.errorKind === 'outgoingAuthentication' && (+ {(shown.errorKind === 'outgoingAuthentication' ||+ shown.errorKind === 'certificate') && (<Buttonsize="small"onClick={async () => {diff --git a/apps/desktop/src/renderer/src/demo.ts b/apps/desktop/src/renderer/src/demo.tsindex 810029f..c372e95 100644--- a/apps/desktop/src/renderer/src/demo.ts+++ b/apps/desktop/src/renderer/src/demo.ts@@ -7,7 +7,9 @@ import {nextAccountColor,type Account,type AppEvent,+ type CertificateDetails,type ConnectInput,+ type ConnectionCheck,type ConnectionConfig,type ConnectionTest,type DesktopMailAPI,@@ -19,6 +21,7 @@ import {type Message,type MailQuery,type MutationInput,+ type ServerSettings,type SubmissionSummary,} from '@inlark/core'import { longDate } from './mail-date'@@ -405,16 +408,54 @@ function folderReview(choices?: FolderMappings): FolderMappingReview {return review}const loginError = 'The server rejected the username or password.'+/** A bridge on this computer, such as Proton Mail Bridge, with its own self-signed certificate. */+const bridgeCertificate: CertificateDetails = {+ problem: 'selfSigned',+ sha256:+ '23:E0:DC:41:A3:1A:2F:37:9E:B7:44:2A:84:97:04:8D:D9:14:85:65:0A:04:B8:91:6C:C0:FE:0B:25:9F:E6:AF',+ pem: `-----BEGIN CERTIFICATE-----+MIICBjCCAa2gAwIBAgIUGwUOiqnvorOa3clMVMGq9qxVuBowCgYIKoZIzj0EAwIw+SzELMAkGA1UEBhMCQ0gxEjAQBgNVBAoMCVByb3RvbiBBRzEUMBIGA1UECwwLUHJv+dG9uIE1haWwxEjAQBgNVBAMMCTEyNy4wLjAuMTAeFw0yNjEwMDUxNzMzNTNaFw00+NjA5MzAxNzMzNTNaMEsxCzAJBgNVBAYTAkNIMRIwEAYDVQQKDAlQcm90b24gQUcx+FDASBgNVBAsMC1Byb3RvbiBNYWlsMRIwEAYDVQQDDAkxMjcuMC4wLjEwWTATBgcq+hkjOPQIBBggqhkjOPQMBBwNCAASnJ9hy5EFDQvHbvnMr1RyGWIVhdeXR/jJ9aSgJ+XaUjsEKa93YrzrBmr/Ij/HV8FtYlnzK1mWECVM6iugkLfiDTo28wbTAdBgNVHQ4E+FgQUJ/Wq8taq+JxuQMQGFv1aaoiG6zEwHwYDVR0jBBgwFoAUJ/Wq8taq+JxuQMQG+Fv1aaoiG6zEwDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARggkxMjcuMC4wLjGH+BH8AAAEwCgYIKoZIzj0EAwIDRwAwRAIgPRE48rZJg/eFRQWbbTuRVOWuj+JtTFZl+Wukj+PB9ujECIGbrTLztJ8IYOx2o01W6jV1gbx5aIpiMBXiDMnZ6eJjH+-----END CERTIFICATE-----+`,+ subject: '127.0.0.1',+ issuer: 'Proton AG',+ names: ['127.0.0.1'],+ validFrom: '2026-10-05T17:33:53.000Z',+ validTo: '2046-09-30T17:33:53.000Z',+}+/** Demo only: a local server is refused until its certificate is trusted. */+function untrustedBridge(server: ServerSettings): ConnectionCheck | undefined {+ if (!/^(localhost|127\.0\.0\.1)$/.test(server.host)) return undefined+ if (server.certificate?.sha256 === bridgeCertificate.sha256) return undefined+ return {+ ok: false,+ error: `The certificate of ${server.host} couldn't be verified, so the connection was stopped before signing in.`,+ certificate: bridgeCertificate,+ }+}function demoTest(input: ConnectInput): ConnectionTest {- const incoming = input.password === 'wrong' ? { ok: false, error: loginError } : { ok: true }+ const incoming =+ (input.config.protocol === 'imap' && untrustedBridge(input.config.incoming)) ||+ (input.password === 'wrong' ? { ok: false, error: loginError } : { ok: true })if (input.config.protocol === 'jmap') return { incoming }const outgoingPassword = input.config.outgoingSameCredentials? input.password: input.outgoingPasswordconst outgoing =- outgoingPassword === 'nosmtp' || outgoingPassword === 'wrong'+ untrustedBridge(input.config.outgoing) ||+ (outgoingPassword === 'nosmtp' || outgoingPassword === 'wrong'? { ok: false, error: 'The outgoing server rejected the username or password.' }- : { ok: true }+ : { ok: true })return { incoming, outgoing, ...(incoming.ok ? { folders: folderReview() } : {}) }}diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.tsindex 09c0023..d9f0ce5 100644--- a/packages/core/src/errors.ts+++ b/packages/core/src/errors.ts@@ -1,8 +1,11 @@/*** Codes shared by every provider so the service can react without knowing the protocol.*- * - `network` / `authentication` / `tls`: the incoming connection is unavailable.- * - `outgoingNetwork` / `outgoingAuthentication`: the outgoing server is unavailable; nothing was sent.+ * - `network` / `authentication` / `tls` / `certificate`: the incoming connection is unavailable.+ * - `outgoingNetwork` / `outgoingAuthentication` / `outgoingCertificate`: the outgoing server is+ * unavailable; nothing was sent.+ * - `certificate` / `outgoingCertificate`: the server's certificate isn't trusted, so nothing was+ * signed in. The user may be able to review and trust it.* - `submissionRejected`: the server refused the message; nothing was sent.* - `submissionUncertain`: the message may have been sent. Never retry automatically.* - `filing` / `filingUncertain`: the message was sent, but its Sent copy is not confirmed.@@ -13,8 +16,10 @@ export type ProviderErrorCode =| 'network'| 'authentication'| 'tls'+ | 'certificate'| 'outgoingNetwork'| 'outgoingAuthentication'+ | 'outgoingCertificate'| 'submissionRejected'| 'submissionUncertain'| 'filing'@@ -39,7 +44,13 @@ export class ProviderError extends Error {}/** Errors meaning the incoming server cannot currently be used at all. */-export const connectionErrorCodes: readonly string[] = ['network', 'authentication', 'http', 'tls']+export const connectionErrorCodes: readonly string[] = [+ 'network',+ 'authentication',+ 'http',+ 'tls',+ 'certificate',+]export const isProviderError = (error: unknown, ...codes: string[]): error is ProviderError =>error instanceof ProviderError && (!codes.length || codes.includes(error.code))diff --git a/packages/core/src/model.ts b/packages/core/src/model.tsindex 0acf114..7d968aa 100644--- a/packages/core/src/model.ts+++ b/packages/core/src/model.ts@@ -192,7 +192,8 @@ export interface Draft {/** What kind of problem `error` describes, so the composer can offer the right recovery. */errorKind?: DraftErrorKind}-export type DraftErrorKind = 'conflict' | 'connection' | 'outgoingAuthentication' | 'rejected'+export type DraftErrorKind =+ 'conflict' | 'connection' | 'outgoingAuthentication' | 'certificate' | 'rejected'export interface Settings {theme: 'dark' | 'light' | 'system'remoteImages: boolean@@ -255,6 +256,31 @@ export interface ServerSettings {port: numbersecurity: TransportSecurityusername: string+ /** A certificate the user chose to trust for this server, in addition to public authorities. */+ certificate?: TrustedCertificate+}+/** Exactly one certificate, identified by its SHA-256 fingerprint. */+export interface TrustedCertificate {+ /** Upper-case hex pairs separated by colons, as shown to the user. */+ sha256: string+ pem: string+}+/**+ * Why a server's certificate isn't accepted. `changed` means it differs from the trusted one.+ * `expired` and `notYetValid` can't be trusted at all.+ */+export type CertificateProblem =+ 'selfSigned' | 'unknownIssuer' | 'otherName' | 'changed' | 'expired' | 'notYetValid'+/** A certificate a server presented, read without signing in, for the user to review. */+export interface CertificateDetails extends TrustedCertificate {+ problem: CertificateProblem+ /** The common name, or else the organization, of the subject and issuer. */+ subject: string+ issuer: string+ /** The host names and addresses the certificate is valid for. */+ names: string[]+ validFrom: string+ validTo: string}export interface JmapConnectionConfig {protocol: 'jmap'@@ -323,6 +349,8 @@ export interface DiscoveryResult {export interface ConnectionCheck {ok: booleanerror?: string+ /** The certificate that stopped the connection, when the user may be able to trust it. */+ certificate?: CertificateDetails}export interface ConnectionTest {incoming: ConnectionCheck@@ -388,6 +416,11 @@ export interface MailProvider {connect(): Promise<Account[]>/** Signs in to the outgoing server without sending anything (SMTP providers only). */verifyOutgoing?(): Promise<void>+ /**+ * Reads the certificate a server presents without signing in. Undefined when the certificate+ * would be accepted or can't be read.+ */+ inspectCertificate?(server: 'incoming' | 'outgoing'): Promise<CertificateDetails | undefined>/** Releases resources asynchronously, e.g. closing a local index before its files are removed. */close?(): Promise<void>mailboxes(account: Account): Promise<Mailbox[]>diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.tsindex c46c6bb..6813ac8 100644--- a/packages/core/src/schemas.ts+++ b/packages/core/src/schemas.ts@@ -30,11 +30,19 @@ export const hostSchema = z/^\[?[0-9a-f:]+(:\d{1,3}(\.\d{1,3}){3})?\]?$/.test(value),'Enter a server name such as imap.example.com, without https:// or a port.',)+export const trustedCertificateSchema = z.object({+ sha256: z.string().regex(/^[0-9A-F]{2}(:[0-9A-F]{2}){31}$/),+ pem: z+ .string()+ .max(16_384)+ .regex(/^-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+-----END CERTIFICATE-----\r?\n?$/),+})export const serverSettingsSchema = z.object({host: hostSchema,port: z.number().int().min(1, 'Enter a port.').max(65535, 'Enter a port up to 65535.'),security: z.enum(['tls', 'starttls']),username: z.string().min(1, 'Enter a username.').max(320),+ certificate: trustedCertificateSchema.optional(),})export const connectionConfigSchema = z.discriminatedUnion('protocol', [z.object({@@ -151,7 +159,9 @@ export const draftSchema = z.object({serverFingerprint: z.string().optional(),status: z.enum(['local', 'saving', 'synced', 'error', 'sending', 'uncertain', 'sent']),error: z.string().optional(),- errorKind: z.enum(['conflict', 'connection', 'outgoingAuthentication', 'rejected']).optional(),+ errorKind: z+ .enum(['conflict', 'connection', 'outgoingAuthentication', 'certificate', 'rejected'])+ .optional(),})export const sendDraftSchema = draftSchema.refine(diff --git a/packages/imap/src/certificate.ts b/packages/imap/src/certificate.tsnew file mode 100644index 0000000..fe675ed--- /dev/null+++ b/packages/imap/src/certificate.ts@@ -0,0 +1,259 @@+import { X509Certificate } from 'node:crypto'+import { connect as connectTcp, isIP, type Socket } from 'node:net'+import {+ checkServerIdentity,+ connect as connectTls,+ getCACertificates,+ type ConnectionOptions,+ type TLSSocket,+} from 'node:tls'+import {+ ProviderError,+ type CertificateDetails,+ type CertificateProblem,+ type ServerSettings,+} from '@inlark/core'++type TrustSettings = Pick<ServerSettings, 'host' | 'certificate'>++/** Verification failures that trusting the presented certificate resolves. */+const trustable: Partial<Record<string, CertificateProblem>> = {+ DEPTH_ZERO_SELF_SIGNED_CERT: 'selfSigned',+ SELF_SIGNED_CERT_IN_CHAIN: 'unknownIssuer',+ UNABLE_TO_GET_ISSUER_CERT: 'unknownIssuer',+ UNABLE_TO_GET_ISSUER_CERT_LOCALLY: 'unknownIssuer',+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'unknownIssuer',+ CERT_UNTRUSTED: 'unknownIssuer',+ ERR_TLS_CERT_ALTNAME_INVALID: 'otherName',+ HOSTNAME_MISMATCH: 'otherName',+}+/** Every certificate verification failure, as opposed to a failed TLS handshake. */+const certificateCodes = new Set([+ ...Object.keys(trustable),+ 'CERT_HAS_EXPIRED',+ 'CERT_NOT_YET_VALID',+ 'CERT_REVOKED',+ 'CERT_REJECTED',+ 'CERT_SIGNATURE_FAILURE',+ 'CERT_CHAIN_TOO_LONG',+ 'INVALID_CA',+ 'INVALID_PURPOSE',+ 'PATH_LENGTH_EXCEEDED',+ 'ERROR_IN_CERT_NOT_BEFORE_FIELD',+ 'ERROR_IN_CERT_NOT_AFTER_FIELD',+ 'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',+])+export const isCertificateFailure = (code?: string | null) => !!code && certificateCodes.has(code)++/** The name a certificate must match: an IPv6 address loses its brackets. */+const bare = (host: string) => host.replace(/^\[|\]$/g, '')+/** The name to send with SNI, which never carries an IP address. */+const serverName = (host: string) => (isIP(bare(host)) ? undefined : host)++export const certificateFingerprint = (pem: string) => new X509Certificate(pem).fingerprint256++/**+ * TLS options that require a certificate the public authorities vouch for, issued for the server's+ * name. A certificate the user trusted for this server is accepted too, but only that exact one:+ * it must match by fingerprint, whoever issued it and whatever names it's for. `ca` replaces the+ * public authorities and is for tests only.+ */+export function certificateOptions(+ server: TrustSettings,+ ca?: string | Uint8Array,+): ConnectionOptions {+ const authorities = ca && (typeof ca === 'string' ? ca : Buffer.from(ca))+ const base: ConnectionOptions = {+ rejectUnauthorized: true,+ minVersion: 'TLSv1.2',+ ...(authorities ? { ca: authorities } : {}),+ }+ const trusted = server.certificate?.pem+ if (!trusted) return base+ const sha256 = certificateFingerprint(trusted)+ return {+ ...base,+ ca: [...(authorities ? [authorities] : getCACertificates('default')), trusted],+ // Lets the trusted certificate anchor the chain even when it isn't an authority itself.+ allowPartialTrustChain: true,+ checkServerIdentity: (name, cert) =>+ cert.fingerprint256 === sha256 ? undefined : checkServerIdentity(name, cert),+ }+}++/** Explains a refused certificate. The connection stopped before any login was sent. */+export function certificateError(+ direction: 'incoming' | 'outgoing',+ server: TrustSettings,+ code?: string | null,+): ProviderError {+ const host = server.host+ const stopped = 'so the connection was stopped before signing in.'+ return new ProviderError(+ direction === 'incoming' ? 'certificate' : 'outgoingCertificate',+ code === 'CERT_HAS_EXPIRED'+ ? `The certificate of ${host} has expired, ${stopped}`+ : code === 'CERT_NOT_YET_VALID'+ ? `The certificate of ${host} isn't valid yet, ${stopped} Check this computer's date and time.`+ : server.certificate && code && trustable[code]+ ? `${host} presented a different certificate than the one you trusted, ${stopped}`+ : `The certificate of ${host} couldn't be verified, ${stopped}`,+ )+}++/**+ * Connects, secures the connection and reads the server's certificate, then hangs up without+ * signing in. Resolves to undefined when the certificate would be accepted, when trusting it+ * wouldn't help, or when the server never presents one.+ */+export async function inspectCertificate(+ server: ServerSettings,+ protocol: 'imap' | 'smtp',+ options: { ca?: string | Uint8Array; timeoutMs?: number } = {},+): Promise<CertificateDetails | undefined> {+ // Only the outermost socket is ever destroyed. A TLS socket closes the plain one beneath it,+ // and destroying that plain socket first crashes Node 24.+ let outer: Socket | undefined+ const timer = setTimeout(+ () => outer?.destroy(new Error('Timed out')),+ options.timeoutMs ?? 10_000,+ )+ const open = <T extends Socket>(socket: T, ready: 'connect' | 'secureConnect') =>+ new Promise<T>((resolve, reject) => {+ outer = socket+ socket.once(ready, () => resolve(socket))+ socket.on('error', reject)+ })+ const secure = (extra: ConnectionOptions) =>+ open(+ connectTls({+ host: bare(server.host),+ port: server.port,+ servername: serverName(server.host),+ minVersion: 'TLSv1.2',+ ...(options.ca ? { ca: Buffer.from(options.ca) } : {}),+ // Only to read the certificate, which is judged below. Nothing is sent over this connection.+ rejectUnauthorized: false,+ ...extra,+ }),+ 'secureConnect',+ )+ try {+ let socket: TLSSocket+ if (server.security === 'tls') socket = await secure({})+ else {+ const plain = await open(+ connectTcp({ host: bare(server.host), port: server.port }),+ 'connect',+ )+ if (!(await (protocol === 'imap' ? startImapTls : startSmtpTls)(plain))) return undefined+ socket = await secure({ socket: plain })+ }+ const peer = socket.getPeerX509Certificate()+ return peer && review(server, peer, socket.authorized, socket.authorizationError)+ } catch {+ return undefined+ } finally {+ clearTimeout(timer)+ outer?.destroy()+ }+}++function review(+ server: ServerSettings,+ peer: X509Certificate,+ authorized: boolean,+ reason: Error | string | null,+): CertificateDetails | undefined {+ const code = typeof reason === 'string' ? reason : (reason as { code?: string } | null)?.code+ const now = Date.now()+ const trusted = server.certificate && certificateFingerprint(server.certificate.pem)+ const problem: CertificateProblem | undefined =+ now > peer.validToDate.getTime()+ ? 'expired'+ : now < peer.validFromDate.getTime()+ ? 'notYetValid'+ : authorized || peer.fingerprint256 === trusted || !code || !trustable[code]+ ? undefined+ : trusted+ ? 'changed'+ : trustable[code]+ if (!problem) return undefined+ return {+ problem,+ sha256: peer.fingerprint256,+ pem: peer.toString(),+ subject: nameOf(peer.subject, 'CN', 'O') || 'Unnamed',+ issuer: nameOf(peer.issuer, 'O', 'CN') || 'Unnamed',+ // The same address often appears as both a DNS name and an IP address.+ names: [+ ...new Set(+ [...(peer.subjectAltName || '').matchAll(/(?:DNS|IP Address):("[^"]*"|[^,]*)/g)].map((m) =>+ m[1].replace(/^"|"$/g, ''),+ ),+ ),+ ],+ validFrom: peer.validFromDate.toISOString(),+ validTo: peer.validToDate.toISOString(),+ }+}++/** The first of these attributes in a distinguished name, such as `CN` in `O=Example\nCN=mail`. */+function nameOf(dn: string, ...attributes: string[]) {+ const fields = dn.split('\n').map((line) => line.split(/=(.*)/s))+ for (const attribute of attributes) {+ const value = fields.find(([key]) => key === attribute)?.[1]+ if (value) return value.replace(/^"|"$/g, '')+ }+}++/** Collects lines until `last` matches one, so a reply's continuation lines are included. */+function reply(socket: Socket, last: (line: string) => boolean): Promise<string[]> {+ return new Promise((resolve, reject) => {+ const lines: string[] = []+ let buffer = ''+ const received = (chunk: Buffer) => {+ buffer += chunk.toString('latin1')+ // A greeting or capability list is small; anything this large isn't a mail server.+ if (buffer.length > 65_536) return finish(new Error('Reply too long'))+ for (let end = buffer.indexOf('\n'); end >= 0; end = buffer.indexOf('\n')) {+ const line = buffer.slice(0, end).replace(/\r$/, '')+ buffer = buffer.slice(end + 1)+ lines.push(line)+ if (last(line)) return finish()+ }+ }+ const closed = () => finish(new Error('Connection closed'))+ function finish(error?: Error) {+ socket.off('data', received)+ socket.off('error', closed)+ socket.off('close', closed)+ if (error) reject(error)+ else resolve(lines)+ }+ socket.on('data', received)+ socket.once('error', closed)+ socket.once('close', closed)+ })+}++async function startImapTls(socket: Socket): Promise<boolean> {+ const greeting = await reply(socket, (line) => line.startsWith('* '))+ if (!/^\* OK\b/i.test(greeting.at(-1)!)) return false+ socket.write('A1 STARTTLS\r\n')+ const done = await reply(socket, (line) => line.startsWith('A1 '))+ return /^A1 OK\b/i.test(done.at(-1)!)+}++async function startSmtpTls(socket: Socket): Promise<boolean> {+ // The last line of a reply has a space, or nothing, after its code.+ const smtpReply = () => reply(socket, (line) => /^\d{3}(?: |$)/.test(line))+ if (!(await smtpReply()).at(-1)!.startsWith('220')) return false+ // The same neutral name as a real session, so the local hostname never reaches the server.+ socket.write('EHLO [127.0.0.1]\r\n')+ const ehlo = await smtpReply()+ if (!ehlo.at(-1)!.startsWith('250') || !ehlo.some((line) => /^250[ -]STARTTLS\s*$/i.test(line)))+ return false+ socket.write('STARTTLS\r\n')+ return (await smtpReply()).at(-1)!.startsWith('220')+}diff --git a/packages/imap/src/imapflow-port.ts b/packages/imap/src/imapflow-port.tsindex 99ae743..261f87f 100644--- a/packages/imap/src/imapflow-port.ts+++ b/packages/imap/src/imapflow-port.ts@@ -5,7 +5,8 @@ import {type ListResponse,type MessageStructureObject,} from 'imapflow'-import { ProviderError, type Address } from '@inlark/core'+import { ProviderError, type Address, type ServerSettings } from '@inlark/core'+import { certificateError, certificateOptions, isCertificateFailure } from './certificate'import type { BodyPart, FolderListing } from './metadata-index'import type {AppendResult,@@ -20,20 +21,14 @@ import type {SelectedMailbox,} from './port'-const tlsCodes = new Set([- 'CERT_HAS_EXPIRED',- 'CERT_NOT_YET_VALID',- 'DEPTH_ZERO_SELF_SIGNED_CERT',- 'SELF_SIGNED_CERT_IN_CHAIN',- 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',- 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',- 'ERR_TLS_CERT_ALTNAME_INVALID',- 'ERR_SSL_WRONG_VERSION_NUMBER',- 'EPROTO',-])+const tlsCodes = new Set(['ERR_SSL_WRONG_VERSION_NUMBER', 'EPROTO'])/** Maps a connection-phase failure to a calm, specific error. Never includes the password. */-export function connectionError(error: unknown, host: string): ProviderError {+export function connectionError(+ error: unknown,+ server: Pick<ServerSettings, 'host' | 'certificate'>,+): ProviderError {+ const host = server.hostconst e = error as {code?: stringauthenticationFailed?: boolean@@ -45,6 +40,7 @@ export function connectionError(error: unknown, host: string): ProviderError {'authentication','The incoming server rejected this login. Check the username and password, or create an app password.',)+ if (isCertificateFailure(e?.code)) return certificateError('incoming', server, e.code)if (e?.tlsFailed ||(e?.code && tlsCodes.has(e.code)) ||@@ -86,11 +82,7 @@ export function imapFlowOptions(doSTARTTLS: implicit ? undefined : true,...(isIP(options.host.replace(/^\[|\]$/g, '')) ? {} : { servername: options.host }),auth: { user: options.username, pass: options.password },- tls: {- rejectUnauthorized: true,- minVersion: 'TLSv1.2',- ...(options.tls?.ca ? { ca: Buffer.from(options.tls.ca) } : {}),- },+ tls: certificateOptions(options, options.tls?.ca),logger: false,// No client identification is sent to the server.clientInfo: { name: false },@@ -172,7 +164,7 @@ export class ImapFlowPort implements ImapPort {try {await this.client.connect()} catch (error) {- throw connectionError(error, this.options.host)+ throw connectionError(error, this.options)}}async close() {diff --git a/packages/imap/src/index.ts b/packages/imap/src/index.tsindex 67d7101..b3406b5 100644--- a/packages/imap/src/index.ts+++ b/packages/imap/src/index.ts@@ -6,3 +6,4 @@ export * from './imapflow-port'export * from './mime'export * from './smtp'export * from './provider'+export * from './certificate'diff --git a/packages/imap/src/provider.ts b/packages/imap/src/provider.tsindex 96d4e68..b91d60c 100644--- a/packages/imap/src/provider.ts+++ b/packages/imap/src/provider.ts@@ -37,6 +37,7 @@ import {toNewMessage,uidSet,} from './convert'+import { inspectCertificate } from './certificate'import { isInbox, reviewFolders, rolesByPath } from './folders'import { ImapFlowPort } from './imapflow-port'import type {@@ -72,6 +73,7 @@ export interface ImapProviderOptions {mime: Uint8Array,) => Promise<SubmissionOutcome>}+ inspect?: typeof inspectCertificate/** Tests only: trust an extra certificate authority. */tls?: { ca?: string | Uint8Array }timing?: Partial<Timing>@@ -288,6 +290,14 @@ export class ImapProvider implements MailProvider {verifyOutgoing(): Promise<void> {return (this.options.smtp?.verify || verifySmtp)(this.smtpSettings())}+ inspectCertificate(server: 'incoming' | 'outgoing') {+ const { config, tls } = this.options+ return (this.options.inspect || inspectCertificate)(+ config[server],+ server === 'incoming' ? 'imap' : 'smtp',+ { ca: tls?.ca },+ )+ }// Folders@@ -446,7 +456,8 @@ export class ImapProvider implements MailProvider {} catch (error) {if (this.disposed) breakif (isProviderError(error, 'authentication')) this.setState('authentication', error.message)- else if (isProviderError(error, 'network', 'tls')) this.setState('offline', error.message)+ else if (isProviderError(error, 'network', 'tls', 'certificate'))+ this.setState('offline', error.message)failures++await this.wait(Math.min(60_000, 1000 * 2 ** Math.min(failures, 6)))}diff --git a/packages/imap/src/smtp.ts b/packages/imap/src/smtp.tsindex 7137c66..2163365 100644--- a/packages/imap/src/smtp.ts+++ b/packages/imap/src/smtp.ts@@ -3,6 +3,7 @@ import { isIP } from 'node:net'import { Readable } from 'node:stream'import { TLSSocket } from 'node:tls'import { ProviderError, type ServerSettings, type SubmissionOutcome } from '@inlark/core'+import { certificateError, certificateOptions } from './certificate'export interface SmtpSettings extends ServerSettings {password: string@@ -39,7 +40,6 @@ interface Internals {const passwordMethods = ['PLAIN', 'LOGIN', 'CRAM-MD5']export function smtpOptions(settings: SmtpSettings): SMTPConnection.Options {- const ca = settings.tls?.caconst timeout = settings.timeoutMsreturn {host: settings.host,@@ -60,10 +60,8 @@ export function smtpOptions(settings: SmtpSettings): SMTPConnection.Options {transactionLog: false,lmtp: false,tls: {- rejectUnauthorized: true,- minVersion: 'TLSv1.2',+ ...certificateOptions(settings, settings.tls?.ca),...(isIP(settings.host) ? {} : { servername: settings.host }),- ...(ca ? { ca: typeof ca === 'string' ? ca : Buffer.from(ca) } : {}),},}}@@ -245,14 +243,10 @@ function connectionLost('outgoingNetwork',`${host} didn't offer an encrypted connection (STARTTLS), so no password was sent. ${hint}`,)- if (- (socket instanceof TLSSocket && socket.authorizationError) ||- /certificate|altnames|self[- ]signed/i.test(text)- )- return new ProviderError(- 'outgoingNetwork',- `The certificate of ${host} couldn't be verified, so the connection was stopped before signing in. Check the server name, or ask the server's administrator about its certificate.`,- )+ const refused = socket instanceof TLSSocket ? socket.authorizationError : undefined+ if (refused || /certificate|altnames|self[- ]signed/i.test(text))+ // Node reports the verification code as a string, despite its type.+ return certificateError('outgoing', settings, refused as unknown as string | undefined)if (error?.command === 'STARTTLS' && error.responseCode)return new ProviderError('outgoingNetwork',diff --git a/tests/certificate.test.ts b/tests/certificate.test.tsnew file mode 100644index 0000000..963e113--- /dev/null+++ b/tests/certificate.test.ts@@ -0,0 +1,217 @@+import { describe, it, expect, afterEach } from 'vitest'+import { X509Certificate } from 'node:crypto'+import { readFileSync } from 'node:fs'+import {+ createServer as createTcpServer,+ type AddressInfo,+ type Server,+ type Socket,+} from 'node:net'+import { createServer as createTlsServer, createSecureContext, TLSSocket } from 'node:tls'+import { SMTPServer } from 'smtp-server'+import type { ServerSettings } from '../packages/core/src'+import { certificateOptions, inspectCertificate } from '../packages/imap/src/certificate'+import { ImapFlowPort } from '../packages/imap/src/imapflow-port'++const fixture = (name: string) => readFileSync(new URL(`./fixtures/tls/${name}`, import.meta.url))+const ca = fixture('ca.crt')+const pair = (name: string) => ({ key: fixture(name + '.key'), cert: fixture(name + '.crt') })+const trust = (name: string) => {+ const pem = fixture(name + '.crt').toString()+ return { sha256: new X509Certificate(pem).fingerprint256, pem }+}+const closers: (() => Promise<void>)[] = []+afterEach(async () => {+ await Promise.all(closers.splice(0).map((close) => close()))+})+const listen = async (server: Server, sockets: Set<Socket>) => {+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ closers.push(async () => {+ sockets.forEach((s) => s.destroy())+ await new Promise<void>((resolve) => server.close(() => resolve()))+ })+ return (server.address() as AddressInfo).port+}++/**+ * Just enough IMAP to sign in: every command succeeds. With `starttls` the session starts in+ * plain text and upgrades on request. Records each command name, never its arguments.+ */+async function imapServer(certificate: string, security: 'tls' | 'starttls') {+ const commands: string[] = []+ const sockets = new Set<Socket>()+ const context = createSecureContext(pair(certificate))+ const session = (socket: Socket, plain: boolean) => {+ sockets.add(socket)+ let buffer = ''+ const received = (chunk: Buffer) => {+ buffer += chunk.toString('latin1')+ for (let end = buffer.indexOf('\r\n'); end >= 0; end = buffer.indexOf('\r\n')) {+ const [tag, name = ''] = buffer.slice(0, end).split(' ')+ buffer = buffer.slice(end + 2)+ const command = name.toUpperCase()+ commands.push(command)+ if (command === 'STARTTLS' && plain) {+ socket.write(tag + ' OK Begin TLS\r\n')+ socket.off('data', received)+ sockets.delete(socket)+ const secure = new TLSSocket(socket, { isServer: true, secureContext: context })+ // A client that refuses the certificate ends the handshake; close this side too.+ secure.on('error', () => secure.destroy())+ return session(secure, false)+ }+ if (command === 'CAPABILITY')+ socket.write('* CAPABILITY IMAP4rev1' + (plain ? ' STARTTLS' : '') + '\r\n')+ socket.write(tag + ' OK Done\r\n')+ if (command === 'LOGOUT') socket.end()+ }+ }+ socket.on('data', received)+ socket.on('error', () => socket.destroy())+ }+ const greet = (socket: Socket, plain: boolean) => {+ socket.write('* OK [CAPABILITY IMAP4rev1' + (plain ? ' STARTTLS' : '') + '] Ready\r\n')+ session(socket, plain)+ }+ const server =+ security === 'tls'+ ? createTlsServer(pair(certificate), (socket) => greet(socket, false))+ : createTcpServer((socket) => greet(socket, true))+ server.on('tlsClientError', () => undefined)+ return { port: await listen(server, sockets), commands }+}++async function smtpServer(certificate: string) {+ const auth: string[] = []+ const server = new SMTPServer({+ logger: false,+ disableReverseLookup: true,+ closeTimeout: 10,+ ...pair(certificate),+ onAuth(credentials, _session, callback) {+ auth.push(credentials.username ?? '')+ callback(null, { user: credentials.username })+ },+ })+ server.on('error', () => undefined)+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ closers.push(() => new Promise<void>((resolve) => server.close(() => resolve())))+ return { port: (server.server.address() as AddressInfo).port, auth }+}++const server = (port: number, overrides: Partial<ServerSettings> = {}): ServerSettings => ({+ host: '127.0.0.1',+ port,+ security: 'tls',+ username: 'user',+ ...overrides,+})++describe('trusted certificates', () => {+ it('verifies the normal way unless a certificate is trusted', () => {+ expect(certificateOptions({ host: 'mail.example.test' })).toEqual({+ rejectUnauthorized: true,+ minVersion: 'TLSv1.2',+ })+ const certificate = trust('untrusted')+ const options = certificateOptions({ host: '127.0.0.1', certificate }, ca)+ expect(options).toMatchObject({ rejectUnauthorized: true, allowPartialTrustChain: true })+ // The trusted certificate is added to the authorities, never in place of verification.+ expect(options.ca).toEqual([ca, certificate.pem])+ const peer = (name: string) => new X509Certificate(fixture(name + '.crt')).toLegacyObject()+ expect(options.checkServerIdentity!('127.0.0.1', peer('untrusted'))).toBeUndefined()+ expect(options.checkServerIdentity!('other.example.test', peer('untrusted'))).toBeUndefined()+ expect(options.checkServerIdentity!('other.example.test', peer('server'))).toBeInstanceOf(Error)+ })++ it('signs in to IMAP only with the certificate the user trusted', async () => {+ const { port, commands } = await imapServer('untrusted', 'tls')+ const settings = { ...server(port), password: 'secret', timeoutMs: 3000, tls: { ca } }+ const refused = new ImapFlowPort(settings, 'command')+ await expect(refused.connect()).rejects.toMatchObject({ code: 'certificate' })+ const changed = new ImapFlowPort({ ...settings, certificate: trust('server') }, 'command')+ await expect(changed.connect()).rejects.toMatchObject({+ code: 'certificate',+ message: expect.stringMatching(/different certificate than the one you trusted/),+ })+ expect(commands).toEqual([])+ const trusted = new ImapFlowPort({ ...settings, certificate: trust('untrusted') }, 'command')+ await trusted.connect()+ await trusted.close()+ expect(commands).toContain('LOGIN')+ })+})++describe('certificate inspection', () => {+ it('reads a self-signed certificate over implicit TLS', async () => {+ const { port, commands } = await imapServer('untrusted', 'tls')+ const certificate = await inspectCertificate(server(port), 'imap', { ca })+ expect(certificate).toMatchObject({+ problem: 'selfSigned',+ sha256: trust('untrusted').sha256,+ pem: trust('untrusted').pem,+ subject: 'localhost',+ issuer: 'localhost',+ names: ['localhost', '127.0.0.1'],+ })+ expect(Date.parse(certificate!.validTo)).toBeGreaterThan(Date.now())+ expect(commands).toEqual([])+ })++ it('upgrades IMAP and SMTP with STARTTLS without ever signing in', async () => {+ const imap = await imapServer('untrusted', 'starttls')+ const viaImap = await inspectCertificate(server(imap.port, { security: 'starttls' }), 'imap')+ expect(viaImap).toMatchObject({ problem: 'selfSigned', sha256: trust('untrusted').sha256 })+ expect(imap.commands).toEqual(['STARTTLS'])+ const smtp = await smtpServer('untrusted')+ const viaSmtp = await inspectCertificate(server(smtp.port, { security: 'starttls' }), 'smtp')+ expect(viaSmtp).toMatchObject({ problem: 'selfSigned', sha256: trust('untrusted').sha256 })+ expect(smtp.auth).toEqual([])+ })++ it('reports nothing for a certificate that would be accepted', async () => {+ const verified = await imapServer('server', 'tls')+ expect(await inspectCertificate(server(verified.port), 'imap', { ca })).toBeUndefined()+ const trusted = await imapServer('untrusted', 'tls')+ const settings = server(trusted.port, { certificate: trust('untrusted') })+ expect(await inspectCertificate(settings, 'imap', { ca })).toBeUndefined()+ })++ it('explains why a certificate is refused', async () => {+ const privateAuthority = await imapServer('server', 'tls')+ expect(await inspectCertificate(server(privateAuthority.port), 'imap')).toMatchObject({+ problem: 'unknownIssuer',+ subject: 'localhost',+ issuer: 'Inlark Test CA',+ })+ const replaced = await imapServer('untrusted', 'tls')+ const settings = server(replaced.port, { certificate: trust('server') })+ expect(await inspectCertificate(settings, 'imap', { ca })).toMatchObject({ problem: 'changed' })+ const expired = await imapServer('expired', 'tls')+ // Even a trusted certificate stops working once it expires.+ const trustedExpired = server(expired.port, { certificate: trust('expired') })+ expect(await inspectCertificate(trustedExpired, 'imap', { ca })).toMatchObject({+ problem: 'expired',+ validTo: '2021-01-01T00:00:00.000Z',+ })+ })++ it('gives up quietly when no certificate can be read', async () => {+ const plain = await imapServer('untrusted', 'starttls')+ // A server that only speaks plain text on the implicit TLS port.+ expect(await inspectCertificate(server(plain.port), 'imap')).toBeUndefined()+ const closed = createTcpServer()+ const port = await listen(closed, new Set())+ await new Promise<void>((resolve) => closed.close(() => resolve()))+ expect(await inspectCertificate(server(port), 'imap')).toBeUndefined()+ const silent = createTcpServer(() => undefined)+ const sockets = new Set<Socket>()+ silent.on('connection', (socket) => sockets.add(socket))+ const quiet = await listen(silent, sockets)+ const started = Date.now()+ expect(+ await inspectCertificate(server(quiet, { security: 'starttls' }), 'smtp', { timeoutMs: 200 }),+ ).toBeUndefined()+ expect(Date.now() - started).toBeLessThan(2000)+ })+})diff --git a/tests/connection-config.test.ts b/tests/connection-config.test.tsindex 86ff479..2a924c1 100644--- a/tests/connection-config.test.ts+++ b/tests/connection-config.test.ts@@ -1,4 +1,6 @@import { describe, it, expect } from 'vitest'+import { X509Certificate } from 'node:crypto'+import { readFileSync } from 'node:fs'import { accountSchema, hostSchema, ipcSchemas } from '../packages/core/src'const imap = {@@ -31,6 +33,20 @@ describe('connection configuration validation', () => {}).success,).toBe(false)})+ it('accepts a trusted certificate only as a fingerprint and a single PEM certificate', () => {+ const pem = readFileSync(new URL('./fixtures/tls/untrusted.crt', import.meta.url), 'utf8')+ const sha256 = new X509Certificate(pem).fingerprint256+ const trusting = (certificate: unknown) =>+ accountSchema.safeParse({+ ...imap,+ config: { ...imap.config, incoming: { ...imap.config.incoming, certificate } },+ }).success+ expect(trusting({ sha256, pem })).toBe(true)+ expect(trusting({ sha256: sha256.toLowerCase(), pem })).toBe(false)+ expect(trusting({ sha256: sha256.slice(3), pem })).toBe(false)+ expect(trusting({ sha256, pem: pem.replace('CERTIFICATE', 'PRIVATE KEY') })).toBe(false)+ expect(trusting({ sha256, pem: pem + pem })).toBe(false)+ })it('requires a separate outgoing password only when credentials differ', () => {const separate = { ...imap, config: { ...imap.config, outgoingSameCredentials: false } }expect(accountSchema.safeParse(separate).success).toBe(false)diff --git a/tests/fixtures/tls/README.md b/tests/fixtures/tls/README.mdindex 23fd9da..1bd4ca9 100644--- a/tests/fixtures/tls/README.md+++ b/tests/fixtures/tls/README.md@@ -4,6 +4,7 @@ These certificates and private keys exist only for the automated tests. The keys- `ca.crt` / `ca.key`: the test certificate authority.- `server.crt` / `server.key`: `localhost` and `127.0.0.1`, signed by the test CA.-- `untrusted.crt` / `untrusted.key`: a self-signed certificate for the same names that no test trusts.+- `untrusted.crt` / `untrusted.key`: a self-signed certificate for the same names. Only tests of certificates the user chose to trust accept it.+- `expired.crt` / `expired.key`: a self-signed certificate for the same names that expired in 2021.-Run `generate.sh` to recreate them (valid for 20 years).+Run `generate.sh` to recreate them (valid for 20 years, except the expired one).diff --git a/tests/fixtures/tls/expired.crt b/tests/fixtures/tls/expired.crtnew file mode 100644index 0000000..791b894--- /dev/null+++ b/tests/fixtures/tls/expired.crt@@ -0,0 +1,12 @@+-----BEGIN CERTIFICATE-----+MIIBsDCCAVagAwIBAgIUSil6lSPAqF6zWZ3VD1zywakz50AwCgYIKoZIzj0EAwIw+FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIwMDEwMTAwMDAwMFoXDTIxMDEwMTAw+MDAwMFowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D+AQcDQgAE/ab2PYoCUHrUNSJMWRSdOXou9hmNSY4KW/zsW3anL6jRNRrJsLWhs8Qd+qzbDVBKUgFsGvzg72IJQOXhIhUKqxqOBhTCBgjAdBgNVHQ4EFgQUocq6Zy4ZFDE6+YA0EscLYaRHWKwswHwYDVR0jBBgwFoAUocq6Zy4ZFDE6YA0EscLYaRHWKwswDwYD+VR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8AAAEwEwYDVR0l+BAwwCgYIKwYBBQUHAwEwCgYIKoZIzj0EAwIDSAAwRQIgUygGGeFpwqMurPqbp+KD+SftyGzSDQ15qgCQR51xSp8UCIQCbs/TXZVwAgkUTb9O6akk469K/VDF+Bxpwp2AB+egWgww==+-----END CERTIFICATE-----diff --git a/tests/fixtures/tls/expired.key b/tests/fixtures/tls/expired.keynew file mode 100644index 0000000..87dc2d5--- /dev/null+++ b/tests/fixtures/tls/expired.key@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg4MvFjJnUaev/9tRN+T+q8dq67Uh+eevwaBqiKvZoxTOKhRANCAAT9pvY9igJQetQ1IkxZFJ05ei72GY1J+jgpb/OxbdqcvqNE1GsmwtaGzxB2rNsNUEpSAWwa/ODvYglA5eEiFQqrG+-----END PRIVATE KEY-----diff --git a/tests/fixtures/tls/generate.sh b/tests/fixtures/tls/generate.shindex da3fa5f..981b376 100755--- a/tests/fixtures/tls/generate.sh+++ b/tests/fixtures/tls/generate.sh@@ -28,3 +28,9 @@ rm -f ca.srlopenssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days "$days" \-subj '/CN=localhost' -keyout untrusted.key -out untrusted.crt \-addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' -addext 'extendedKeyUsage=serverAuth'++# Self-signed certificate for the same names that expired long ago (needs OpenSSL 3.4 or later)+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \+ -not_before 20200101000000Z -not_after 20210101000000Z \+ -subj '/CN=localhost' -keyout expired.key -out expired.crt \+ -addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' -addext 'extendedKeyUsage=serverAuth'diff --git a/tests/service-imap.test.ts b/tests/service-imap.test.tsindex c1e2cd6..d46b8f4 100644--- a/tests/service-imap.test.ts+++ b/tests/service-imap.test.ts@@ -1,4 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { X509Certificate } from 'node:crypto'+import { readFileSync } from 'node:fs'import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -19,8 +21,10 @@ import { ImapProvider } from '../packages/imap/src'import { JmapProvider } from '../packages/jmap/src'import {ProviderError,+ type CertificateDetails,type ConnectInput,type Draft,+ type ImapConnectionConfig,type SubmissionOutcome,} from '../packages/core/src'import { FakeImapServer } from './support/fake-imap'@@ -38,6 +42,8 @@ const input: ConnectInput = {remember: true,connectionId: 'imap-connection',}+const pem = readFileSync(new URL('./fixtures/tls/untrusted.crt', import.meta.url), 'utf8')+const fingerprint = new X509Certificate(pem).fingerprint256const draftId = 'fb4c0a00-254f-4fb1-965e-96d56ca9ef17'const accountId = JSON.stringify(['imap-connection', 'imap'])const draft: Draft = {@@ -60,6 +66,7 @@ let service: MailServicelet store: JsonStorelet submit: ReturnType<typeof vi.fn<(...args: any[]) => Promise<SubmissionOutcome>>>let verify: ReturnType<typeof vi.fn<(...args: any[]) => Promise<void>>>+let inspect: ReturnType<typeof vi.fn<(...args: any[]) => Promise<CertificateDetails | undefined>>>const factory: ProviderFactory = (options) =>new ImapProvider({connectionId: options.connectionId,@@ -75,6 +82,7 @@ const factory: ProviderFactory = (options) =>background: false,ports: server.port,smtp: { submit, verify },+ inspect,timing: { sentCopyGraceMs: 0, previews: 0 },})async function start() {@@ -87,6 +95,7 @@ beforeEach(async () => {server = new FakeImapServer()submit = vi.fn(async () => ({ accepted: ['[email protected]', '[email protected]'], rejected: [] }))verify = vi.fn(async () => {})+ inspect = vi.fn(async () => undefined)await start()})afterEach(async () => {@@ -115,6 +124,50 @@ describe('IMAP account setup', () => {expect(submit).not.toHaveBeenCalled()await expect(stat(join(directory, 'connections.json'))).rejects.toThrow()})+ it('offers a refused certificate for review, without signing in again', async () => {+ const certificate: CertificateDetails = {+ problem: 'selfSigned',+ sha256: fingerprint,+ pem,+ subject: 'localhost',+ issuer: 'localhost',+ names: ['localhost', '127.0.0.1'],+ validFrom: '2026-01-01T00:00:00.000Z',+ validTo: '2046-01-01T00:00:00.000Z',+ }+ const refused = "The certificate of smtp.example.com couldn't be verified."+ verify.mockRejectedValueOnce(new ProviderError('outgoingCertificate', refused))+ inspect.mockResolvedValueOnce(certificate)+ const test = await service.testConnection({ ...input, connectionId: undefined })+ expect(test.incoming).toEqual({ ok: true })+ expect(test.outgoing).toEqual({ ok: false, error: refused, certificate })+ expect(inspect).toHaveBeenCalledWith(input.config.outgoing, 'smtp', { ca: undefined })+ // Only a certificate problem is worth a second look.+ verify.mockRejectedValueOnce(new ProviderError('outgoingAuthentication', 'Wrong password.'))+ const login = await service.testConnection({ ...input, connectionId: undefined })+ expect(login.outgoing).toEqual({ ok: false, error: 'Wrong password.' })+ expect(inspect).toHaveBeenCalledTimes(1)+ })+ it('saves a trusted certificate with the fingerprint computed from the certificate itself', async () => {+ const forged = { sha256: Array(32).fill('00').join(':'), pem }+ const config = input.config as ImapConnectionConfig+ await service.connect({+ ...input,+ config: { ...config, outgoing: { ...config.outgoing, certificate: forged } },+ })+ const settings = await service.connectionSettings('imap-connection')+ expect((settings.config as ImapConnectionConfig).outgoing.certificate).toEqual({+ sha256: fingerprint,+ pem,+ })+ const damaged = { ...forged, pem: pem.replace(/[A-Z]/g, 'A') }+ await expect(+ service.testConnection({+ ...input,+ config: { ...config, incoming: { ...config.incoming, certificate: damaged } },+ }),+ ).rejects.toThrow("can't be read")+ })it('requires both servers before completing setup', async () => {verify.mockRejectedValueOnce(new ProviderError('outgoingNetwork', 'The outgoing server could not be reached.'),@@ -365,6 +418,14 @@ describe('IMAP sending', () => {expect((await service.send(draft)).status).toBe('sent')expect(service.accounts[0].outgoingError).toBeUndefined()})+ it('treats a refused outgoing certificate as definitely not sent', async () => {+ const refused = 'smtp.example.com presented a different certificate than the one you trusted.'+ submit.mockRejectedValueOnce(new ProviderError('outgoingCertificate', refused))+ await expect(service.send(draft)).rejects.toThrow('different certificate')+ expect(service.accounts[0]).toMatchObject({ status: 'connected', outgoingError: refused })+ expect((await service.drafts())[0]).toMatchObject({ status: 'error', errorKind: 'certificate' })+ expect((await journal()).state).toBe('rejected')+ })})describe('IMAP drafts', () => {diff --git a/tests/smtp.test.ts b/tests/smtp.test.tsindex 7ef0766..f8ffc50 100644--- a/tests/smtp.test.ts+++ b/tests/smtp.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, afterEach } from 'vitest'+import { X509Certificate } from 'node:crypto'import { readFileSync } from 'node:fs'import { createServer, type AddressInfo, type Socket } from 'node:net'import { SMTPServer, type SMTPServerOptions } from 'smtp-server'@@ -6,6 +7,10 @@ import { composeMime } from '../packages/imap/src/mime'import { smtpOptions, submitSmtp, verifySmtp, type SmtpSettings } from '../packages/imap/src/smtp'const fixture = (name: string) => readFileSync(new URL(`./fixtures/tls/${name}`, import.meta.url))+const trust = (name: string) => {+ const pem = fixture(name).toString()+ return { sha256: new X509Certificate(pem).fingerprint256, pem }+}const ca = fixture('ca.crt')const trusted = { key: fixture('server.key'), cert: fixture('server.crt') }const untrusted = { key: fixture('untrusted.key'), cert: fixture('untrusted.crt') }@@ -29,6 +34,7 @@ async function start(options: Partial<SMTPServerOptions> = {}) {const server = new SMTPServer({logger: false,disableReverseLookup: true,+ closeTimeout: 10,...trusted,onAuth(auth, session, callback) {log.auth.push(auth.username ?? '')@@ -61,10 +67,9 @@ async function start(options: Partial<SMTPServerOptions> = {}) {server.server.on('connection', (socket: Socket) => sockets.add(socket))await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))const port = (server.server.address() as AddressInfo).port- servers.push(async () => {- sockets.forEach((s) => s.destroy())- await new Promise<void>((resolve) => server.close(() => resolve()))- })+ // The server ends what's still open itself. Destroying a raw socket under a TLS handshake the+ // client refused crashes Node 24, since smtp-server leaves the TLS socket on top of it.+ servers.push(() => new Promise<void>((resolve) => server.close(() => resolve())))return { port, log, sockets }}@@ -144,15 +149,36 @@ describe('SMTP submission', () => {it('rejects an untrusted certificate before signing in', async () => {const tls = await start({ secure: true, ...untrusted })const error = await failure(verifySmtp(settings(tls.port)))- expect(error).toMatchObject({ code: 'outgoingNetwork' })+ expect(error).toMatchObject({ code: 'outgoingCertificate' })expect(error.message).toMatch(/certificate/)const starttls = await start({ ...untrusted })const upgrade = await failure(verifySmtp(settings(starttls.port, { security: 'starttls' })))- expect(upgrade).toMatchObject({ code: 'outgoingNetwork' })+ expect(upgrade).toMatchObject({ code: 'outgoingCertificate' })expect(upgrade.message).toMatch(/certificate/)expect([...tls.log.auth, ...starttls.log.auth]).toEqual([])})+ it('accepts exactly the certificate the user trusted, in both security modes', async () => {+ const certificate = trust('untrusted.crt')+ const tls = await start({ secure: true, ...untrusted })+ await verifySmtp(settings(tls.port, { certificate }))+ const starttls = await start({ ...untrusted })+ await verifySmtp(settings(starttls.port, { security: 'starttls', certificate }))+ expect([...tls.log.auth, ...starttls.log.auth]).toEqual(['user', 'user'])+ // Trusting one certificate doesn't stop verifying others the normal way.+ const verified = await start({ secure: true })+ await verifySmtp(settings(verified.port, { certificate }))+ expect(verified.log.auth).toEqual(['user'])+ })++ it('stops before signing in when the certificate differs from the trusted one', async () => {+ const { port, log } = await start({ secure: true, ...untrusted })+ const error = await failure(verifySmtp(settings(port, { certificate: trust('server.crt') })))+ expect(error).toMatchObject({ code: 'outgoingCertificate' })+ expect(error.message).toMatch(/different certificate than the one you trusted/)+ expect(log.auth).toEqual([])+ })+it('reports a wrong password as an authentication failure', async () => {const { port, log } = await start({ secure: true })const error = await failure(verifySmtp(settings(port, { password: 'wrong' })))diff --git a/tests/stalwart-imap.integration.test.ts b/tests/stalwart-imap.integration.test.tsindex 13656bb..9857dd9 100644--- a/tests/stalwart-imap.integration.test.ts+++ b/tests/stalwart-imap.integration.test.ts@@ -57,8 +57,30 @@ describe.skipIf(!ready)('disposable Stalwart IMAP/SMTP integration', () => {it('enforces TLS verification, credentials and both security modes', async () => {const untrusted = imap('tls', { tls: undefined })- await expect(untrusted.connect()).rejects.toMatchObject({ code: 'tls' })+ await expect(untrusted.connect()).rejects.toMatchObject({ code: 'certificate' })await untrusted.close()+ // Without the test CA, the server's certificate can still be reviewed and trusted by itself.+ for (const security of ['tls', 'starttls'] as const) {+ const reviewing = imap(security, { tls: undefined })+ const certificate = await reviewing.inspectCertificate('incoming')+ expect(certificate).toMatchObject({ problem: 'unknownIssuer', issuer: 'Inlark Test CA' })+ expect(await reviewing.inspectCertificate('outgoing')).toMatchObject({+ sha256: certificate!.sha256,+ })+ const trusted = { sha256: certificate!.sha256, pem: certificate!.pem }+ const base = config(security)+ const p = imap(security, {+ tls: undefined,+ config: {+ ...base,+ incoming: { ...base.incoming, certificate: trusted },+ outgoing: { ...base.outgoing, certificate: trusted },+ },+ })+ expect(await p.connect()).toHaveLength(1)+ await p.verifyOutgoing()+ await p.close()+ }const wrong = imap('tls', { password: 'wrong-' + randomUUID() })await expect(wrong.connect()).rejects.toMatchObject({ code: 'authentication' })await wrong.close()