Files
tern-server/migrations/0002_accounts_sync.sql
Mateusz PstruchaandClaude Opus 5 4c1a6457c5 Initial sync server: IMAP engine, schema, and read API
Covers phases 1-2 of the build order in the architecture spec: the IMAP
sync engine (IDLE + UIDVALIDITY tracking + jittered reconnect, headers
first with lazy body fetch), the full data model, and a minimal REST API
for auth, accounts, folders, messages and delta polling.

Credentials are encrypted at rest with ChaCha20-Poly1305 rather than
libsodium secretbox, to avoid a system dependency for the same
construction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 19:00:59 +02:00

33 lines
1.5 KiB
SQL

-- 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()
);