#17

Add Gmail accounts and full-client sync

MergedstylesshOwnermerged intofrom

Summary

  • add a provider-neutral mail account model and Gmail connector while keeping Gmail as the message source of truth
  • add Google identity sign-in plus incremental Gmail mailbox authorization with encrypted OAuth tokens
  • support Gmail inbox/search, folders, drafts, sending, attachments, message state, multi-account routing, foreground sync, and Pub/Sub watch notifications
  • add custom-email and Gmail choices to onboarding and a Vercel-style connected-account list in the current settings pages
  • document isolated staging and production OAuth, Pub/Sub, Railway, Cloud Scheduler, verification, privacy, and key-rotation setup

Privacy model

  • persist account identity, encrypted OAuth grants, Gmail history cursor, subscription expiry, health, and UI revision
  • fetch Gmail message bodies and attachments on demand without storing them in Redakt
  • keep Google sign-in scopes separate from the restricted gmail.modify grant

Validation

  • focused ESLint on all changed TypeScript and TSX files
  • pnpm exec tsc --noEmit
  • pnpm test (50 tests passed)
  • pnpm build
  • desktop and 320px mobile browser verification of account settings and the deletion dialog
  • git diff --check
  • clean local merge-tree against current origin/main

Relates to #5.

Activity

7
mikey3mo ago

Code review — Gmail accounts and full-client sync

Reviewed the OAuth/token security model, multi-account authorization boundaries, Pub/Sub webhook + renewal auth, DB schema/migration, and the Gmail sync/normalize logic (with paired tests), against PR head ca004b5. This is a large, well-structured PR; the security-sensitive plumbing (OAuth CSRF state, token encryption, Pub/Sub OIDC verification, per-account DB-level ownership checks) is solid. One correctness bug causes silent data loss and should be fixed before merge; the rest are non-blocking follow-ups.

(Note: this run's token only has pulls:comment scope, not pulls:write, so I can't submit inline-anchored review comments or a formal request-changes decision — posting everything as one comment instead.)

Blocking

lib/gmail/normalize.ts:70-77 — large email bodies are silently truncated.

function bodyValue(message: GmailMessage, mimeType: "text/plain" | "text/html") {
  let value: string | undefined;
  walkParts(message.payload, (part) => {
    if (value !== undefined || part.mimeType !== mimeType || !part.body?.data) return;
    value = decodeBase64Url(part.body.data).toString("utf8");
  });
  return value;
}

This only reads part.body?.data. Per the Gmail API, a message body part larger than ~1MB comes back with body.attachmentId set and body.data omitted, requiring a separate messages.attachments.get call to fetch it. There's no fallback here, so text/html silently become undefined for such messages, and gmailMessageToMessage (normalize.ts:161) falls back to message.snippet — the full body of any sufficiently large email (long threads, HTML-heavy newsletters) is silently dropped with no error surfaced to the user. normalize.test.mjs only covers small inline body.data payloads, so this isn't caught by tests. Suggest hydrating oversized body parts via attachmentId, the same way attachment content is fetched elsewhere (e.g. lib/gmail/provider.ts's hydrateAttachments).

Non-blocking (worth follow-up)

  • No test coverage for the core sync/provider logic. lib/gmail/sync.ts and lib/gmail/provider.ts — the most complex, stateful, network-dependent code in this PR (history-cursor advancement, 404 fallback, subscription renewal, pagination) — have zero dedicated tests, unlike the adjacent pure-function mime/normalize helpers. Given the subtlety of the 404/403 handling gaps below, some unit coverage with a mocked Gmail client would catch regressions here.
  • lib/gmail/sync.ts:39 — only Gmail 404 triggers the full-resync fallback; a 410 (also used by Gmail for expired history cursors) falls through to a bare throw on line 49, permanently wedging that account's sync until manual reconnect.
  • lib/gmail/sync.ts:42-48 — 403 (insufficient scope, e.g. grant lacks gmail.modify) isn't handled like 401; the account stays status: "connected" and keeps failing silently instead of surfacing a reauthorize prompt.
  • lib/gmail/sync.ts:85-104 (ensureGmailSubscription) — unlike syncGmailAccount, a 401 here doesn't set status: "reauthorize". An account with a permanently revoked grant gets re-selected by the daily renew cron indefinitely, wasting Gmail API quota on a call that can never succeed.
  • app/api/mail/sync/renew/route.ts:12 — cron-secret check uses non-constant-time !== string comparison (request.headers.get("authorization") !== \Bearer ${secret}`). Switch to crypto.timingSafeEqual` on fixed-length buffers. Low practical exploitability over TLS, but cheap to fix given the secret has no rotation/expiry.
  • lib/db/schema.ts:81 — mail_accounts.email has no supporting index, but listStoredMailAccountsByEmail("gmail", email) filters on exactly this column on every inbound Gmail Pub/Sub push notification — an externally-triggered, potentially high-volume hot path. As the table grows this becomes a sequential scan per webhook delivery; consider an index on email or a composite (connector, email) index.
  • Pre-existing, not introduced by this PR, but now more consequential: lib/crypto/secret.ts:4 falls back to a hardcoded "redakt-dev-secret" key if BETTER_AUTH_SECRET is unset at runtime, with no startup validation enforcing its presence. This key protects mailbox-adjacent secrets encrypted outside better-auth's own (correctly-enforced) encryptOAuthTokens path. Worth a startup assertion given the new Gmail integration raises the stakes, though out of scope for this diff.

Verified clean (no action needed)

  • OAuth CSRF/state handling goes entirely through better-auth's server-side state+PKCE store — no custom callback re-implementation to attack.
  • Gmail/Google OAuth tokens are encrypted at rest via better-auth's encryptOAuthTokens (AES-256-GCM, keyed from BETTER_AUTH_SECRET); DB migration's token-adjacent columns are consistent with ciphertext storage.
  • Confused-deputy check on app/api/mail/accounts/google/complete/route.ts: session is validated before linking, and unique indexes on (auth_account_id) and (user_id, connector, external_account_id) prevent cross-user row collisions.
  • Every mail API route (accounts, sync, attachments, drafts, send, threads) resolves the account via findStoredMailAccount(user.id, accountId), a DB-level WHERE id = ? AND userId = ? — no IDOR path found for accessing or acting on another user's mailbox by ID manipulation.
  • Pub/Sub webhook (app/api/mail/sync/google-pubsub/route.ts) verifies a real Google-signed OIDC bearer JWT (issuer, audience, verified service-account email) before processing — this is a real defense, not an unauthenticated endpoint despite first appearances.
  • Migration 0002_first_wild_child.sql is purely additive (new table + constraints/indexes), safe for a rolling deploy; FK cascades from user → mail_accounts/account prevent orphaned rows on user deletion.

Verification performed

Read the full diff (90 files) against base c7daa76, plus surrounding non-diffed context needed to judge each change: lib/auth.ts, lib/env.ts, lib/data/mail-accounts.ts, lib/data/accounts.ts, lib/mail/get-provider.ts, lib/gmail/client.ts, lib/gmail/provider.ts, and the DB migration/snapshot files. Confirmed the local checkout's HEAD matches the PR's headSha (ca004b5).

stylesshOwner3mo ago

Addressed the blocking finding and the related hardening items in 944ebbf:

  • Hydrate text/plain and text/html MIME bodies backed by Gmail attachmentId before normalization, and keep those body parts out of the attachment list. Hydration failures now surface instead of silently falling back to the snippet.
  • Extracted testable provider/sync cores and added coverage for body hydration, pagination, cursor advancement, 404/410 full-refresh fallback, reauthorization classification, and watch expiration validation.
  • Treat Gmail 401/403 failures as reauthorization-required during sync and watch renewal; clear the stored subscription expiry so the renewal cron stops selecting revoked accounts.
  • Compare the cron bearer token using fixed-length SHA-256 digests with timingSafeEqual.
  • Added a (connector, email) index and generated migration 0003_nappy_machine_man.sql for Pub/Sub account lookup.
  • Removed the hardcoded mailbox encryption-key fallback; BETTER_AUTH_SECRET is now required, with a regression test.

Validation on the new head: 62 tests pass, focused ESLint passes, tsc --noEmit passes, next build passes, drizzle-kit check passes, and git diff --check is clean.

stylessh merged commit b464920 into main3mo ago

Branch stylessh/gmail-client has been merged.

Checking branch