-- IMAP/SMTP accounts a user has added, plus per-account sync bookkeeping. -- One-way sync: server only ever fetches from IMAP INBOX (§2.1), so -- sync_state has exactly one row per account, not per-folder. CREATE TABLE accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, provider_type TEXT NOT NULL DEFAULT 'generic_imap', -- reserved for future oauth providers (gmail, apple) imap_host TEXT NOT NULL, imap_port INTEGER NOT NULL DEFAULT 993, imap_use_tls BOOLEAN NOT NULL DEFAULT true, smtp_host TEXT NOT NULL, smtp_port INTEGER NOT NULL DEFAULT 587, smtp_use_starttls BOOLEAN NOT NULL DEFAULT true, username TEXT NOT NULL, -- credentials encrypted at rest (ChaCha20-Poly1305, server-held key) — never stored plaintext encrypted_password BYTEA NOT NULL, password_nonce BYTEA NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX accounts_user_id_idx ON accounts(user_id); CREATE TABLE sync_state ( account_id UUID PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE, uidvalidity BIGINT, last_synced_uid BIGINT NOT NULL DEFAULT 0, status TEXT NOT NULL DEFAULT 'pending', -- pending | syncing | idle | error last_error TEXT, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() );