#30

Add opt-in AI Focus inbox

MergedstylesshOwnermerged intofrom

Summary

  • Add Focus as an opt-in AI-assisted inbox view with explainable categories, confidence, deadlines, inline and bulk mail actions, and smart folder-routing suggestions.
  • Add BYOK settings for OpenAI, Anthropic, and Google Gemini with explicit processing consent, encrypted key storage, model selectors, provider logos, and first-run navigation discovery.
  • Add provider-safe Focus and thread routes, token-free sample data, responsive empty and loading states, legal documentation, and database migrations.
  • Protect provider quota with a database-backed per-user throttle, and move mailbox and AI credentials to a separate versioned encryption keyring with transparent legacy rotation.

Testing

  • pnpm exec eslint <changed TypeScript and JavaScript files>
  • pnpm exec tsc --noEmit
  • pnpm test (136 tests passed)
  • pnpm build
  • pnpm exec drizzle-kit check
  • docker compose config --quiet
  • git diff --check origin/main...HEAD
  • Browser smoke test: Focus list, sample sections, Focus thread navigation, and visible reply composer for ?reply=1

Notes

  • Focus remains opt-in and only analyzes mail after the user accepts AI processing and configures a provider.
  • Sample data can be toggled on for UI testing without calling an AI provider or consuming tokens.
  • Live environments must define REDAKT_ENCRYPTION_KEYS with a key distinct from BETTER_AUTH_SECRET before deploying this revision.

Activity

7
mikeyreviewed2mo ago
mikey2mo ago

Review summary

Reviewed the full diff (49 files, +6807/-46), focusing on the security-sensitive surface: BYOK API key storage/encryption, the new AI settings and Focus API routes, prompt construction sent to third-party LLM providers, and the two additive DB migrations.

No blocking issues found. Specifics I verified:

  • API key handling (lib/crypto/secret.ts, lib/data/ai-settings.ts, app/api/settings/ai/route.ts): keys are AES-256-GCM encrypted at rest, never returned to the client (only a 4-char apiKeyHint), and saveAiSettings correctly nulls the stored key when the provider changes so a key never gets reused against the wrong provider's API.
  • Auth on new routes: GET/PUT/PATCH/DELETE /api/settings/ai and POST /api/mail/focus all call getSessionUser() and 401 if absent. getMailProvider → resolveMailAccount (unchanged) scopes account lookup to user.id, so there's no cross-account IDOR via the account query param in the Focus route.
  • Prompt-injection / output-validation (lib/ai/focus.ts, lib/ai/provider.ts): the system prompt explicitly instructs the model to treat email content and collection names as untrusted data and never follow embedded instructions. Provider output is passed through a strict JSON schema (additionalProperties: false, enums, maxLength) and normalizeFocusResponse re-validates every field server-side (thread IDs must be in the requested set, deadlines must match a strict ISO-8601 regex and are only kept for category === "deadline", collectionId must be in the requested set). Unclassified threads are backfilled with a safe default rather than dropped.
  • Rendering: the AI-generated reason text is rendered via JSX text interpolation (components/focus/focus-view.tsx:1890), not dangerouslySetInnerHTML, so no injected HTML/script risk from provider output.
  • Migrations (0006_unique_emma_frost.sql, 0007_glossy_dormammu.sql): purely additive (new table, new nullable column) — no backfill or rollout hazard.
  • Input validation (lib/ai/settings.ts parseAiSettingsInput): rejects unknown body keys, validates provider against an allow-list, model against a conservative regex, and API key length (8–512 chars) before it ever reaches encryption or a provider call.

Nothing here rises to a blocking finding. Two things worth a human glance but not blockers:

  • No app-wide rate limiting exists on /api/mail/focus, so a compromised session (via some other vuln) could be used to repeatedly burn the victim's own configured AI provider quota — this matches the existing lack of rate limiting elsewhere in the app, so it's not a regression introduced by this PR specifically.
  • The AES key for encryptSecret/decryptSecret is still derived from BETTER_AUTH_SECRET (pre-existing pattern, just relabeled from "mailbox secrets" to "stored secrets" here) — reusing the auth-session secret as an encryption key is a minor crypto-hygiene smell but not new to this change.

Verification performed: read the full diff via try pr diff, cross-checked unchanged dependencies (resolveMailAccount, getMailProvider) against the local checkout at the PR head commit, and traced the API-key value from input validation through storage, retrieval, and UI display to confirm it's never leaked to the client.

stylesshOwner2mo ago

Addressed both review follow-ups in 883ef19:

  • Added an atomic, database-backed per-user limit of 10 Focus analyses per 10-minute window. Rejected requests return 429, Retry-After, and quota headers. Demo mode uses the same policy without provider calls.
  • Added the separate, versioned REDAKT_ENCRYPTION_KEYS keyring for mailbox credentials and AI provider keys. Existing auth-secret ciphertext remains readable and is transparently re-encrypted with the current dedicated key on access.

Also added the additive rate-limit migration, Railway/self-hosting configuration, independent local secret generation, and regression coverage for throttling, key separation, legacy migration, and key rotation.

Validation on this head: focused ESLint, TypeScript, all 136 tests, production build, migration consistency, Compose configuration, and diff checks pass.

stylessh merged commit 6386c47 into main2mo ago

Branch stylessh/ai-focus has been merged.

Checking branch