#17
Add Gmail accounts and full-client sync
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.modifygrant
Validation
- focused ESLint on all changed TypeScript and TSX files
pnpm exec tsc --noEmitpnpm 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
7Addressed the blocking finding and the related hardening items in 944ebbf:
- Hydrate
text/plainandtext/htmlMIME bodies backed by GmailattachmentIdbefore 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 migration0003_nappy_machine_man.sqlfor Pub/Sub account lookup. - Removed the hardcoded mailbox encryption-key fallback;
BETTER_AUTH_SECRETis 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.
b464920 into main3mo 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:commentscope, notpulls: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.This only reads
part.body?.data. Per the Gmail API, a message body part larger than ~1MB comes back withbody.attachmentIdset andbody.dataomitted, requiring a separatemessages.attachments.getcall to fetch it. There's no fallback here, sotext/htmlsilently becomeundefinedfor such messages, andgmailMessageToMessage(normalize.ts:161) falls back tomessage.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.mjsonly covers small inlinebody.datapayloads, so this isn't caught by tests. Suggest hydrating oversized body parts viaattachmentId, the same way attachment content is fetched elsewhere (e.g.lib/gmail/provider.ts'shydrateAttachments).Non-blocking (worth follow-up)
lib/gmail/sync.tsandlib/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-functionmime/normalizehelpers. 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 Gmail404triggers the full-resync fallback; a410(also used by Gmail for expired history cursors) falls through to a barethrowon line 49, permanently wedging that account's sync until manual reconnect.lib/gmail/sync.ts:42-48—403(insufficient scope, e.g. grant lacksgmail.modify) isn't handled like401; the account staysstatus: "connected"and keeps failing silently instead of surfacing a reauthorize prompt.lib/gmail/sync.ts:85-104(ensureGmailSubscription) — unlikesyncGmailAccount, a401here doesn't setstatus: "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 tocrypto.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.emailhas no supporting index, butlistStoredMailAccountsByEmail("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 onemailor a composite(connector, email)index.lib/crypto/secret.ts:4falls back to a hardcoded"redakt-dev-secret"key ifBETTER_AUTH_SECRETis unset at runtime, with no startup validation enforcing its presence. This key protects mailbox-adjacent secrets encrypted outside better-auth's own (correctly-enforced)encryptOAuthTokenspath. Worth a startup assertion given the new Gmail integration raises the stakes, though out of scope for this diff.Verified clean (no action needed)
encryptOAuthTokens(AES-256-GCM, keyed fromBETTER_AUTH_SECRET); DB migration's token-adjacent columns are consistent with ciphertext storage.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.accounts,sync,attachments,drafts,send,threads) resolves the account viafindStoredMailAccount(user.id, accountId), a DB-levelWHERE id = ? AND userId = ?— no IDOR path found for accessing or acting on another user's mailbox by ID manipulation.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.0002_first_wild_child.sqlis purely additive (new table + constraints/indexes), safe for a rolling deploy; FK cascades fromuser→mail_accounts/accountprevent 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'sHEADmatches the PR'sheadSha(ca004b5).