Skip to content

Comments

show outlook sign in again message#1007

Merged
elie222 merged 1 commit intomainfrom
chore/logs
Nov 25, 2025
Merged

show outlook sign in again message#1007
elie222 merged 1 commit intomainfrom
chore/logs

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 24, 2025

Show Outlook sign-in again by throwing SafeError in apps/web/utils/outlook/client.ts:getOutlookClientWithRefresh when Microsoft identity errors (e.g., AADSTS70000, AADSTS70008, AADSTS70011, AADSTS700082, AADSTS50173, AADSTS65001, AADSTS500011, AADSTS54005, invalid_grant) require re-authentication

Propagate SafeError from emailProviderMiddleware instead of returning 500, and emit a SafeError with a reconnect message from getOutlookClientWithRefresh on specific Microsoft identity errors.

📍Where to Start

Start with the error handling branch in getOutlookClientWithRefresh in client.ts, then review the SafeError guard in middleware.ts.


📊 Macroscope summarized 977a164. 2 files reviewed, 4 issues evaluated, 4 issues filtered, 0 comments posted

🗂️ Filtered Issues

apps/web/utils/middleware.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 292: Potential null/undefined dereference of emailAccount.account when reading emailAccount.account.provider. The Prisma query includes account with only provider selected, but the relation may be null (e.g., missing linked account). In that case emailAccount.account.provider will throw at runtime with "Cannot read properties of null (reading 'provider')" before createEmailProvider is called, leading to a 500 response from the catch block. Add a guard to verify emailAccount.account and emailAccount.account.provider exist, and return a defined error (e.g., 404/400) rather than crashing. [ Out of scope ]
apps/web/utils/outlook/client.ts — 0 comments posted, 3 evaluated, 3 filtered
  • line 100: Token expiry units mismatch: expiresAt is compared against Date.now() (milliseconds) on line 100, but the function later persists expires_at as seconds via Math.floor(Date.now() / 1000 + tokens.expires_in) (line 187). On subsequent calls, a seconds-based expiresAt will be compared to milliseconds, causing premature refresh attempts (or always-refresh). Fix by normalizing units (either store/read milliseconds or divide Date.now() by 1000). [ Out of scope ]
  • line 184: Refresh token rotation is ignored. Microsoft may return a new refresh_token on refresh. The code persists only access_token and expires_at (lines 184–192) and continues using the old refreshToken. This can lead to future refresh failures once the old refresh token is invalidated. Capture and persist tokens.refresh_token when present. [ Low confidence ]
  • line 186: Missing validation of token response fields. The code uses tokens.access_token (line 194) and tokens.expires_in (line 187) without checking presence or type. If either is missing or malformed, Math.floor(Date.now() / 1000 + tokens.expires_in) yields NaN and persists an invalid expires_at, and createOutlookClient(tokens.access_token) will throw due to an undefined token after already saving broken state. Add explicit checks for access_token and expires_in before saving/returning, and fail atomically. [ Low confidence ]

Summary by CodeRabbit

Bug Fixes

  • Improved error handling for email provider authentication with enhanced user-facing messages that prompt account reconnection when Microsoft account re-authentication is required.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Nov 24, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Nov 24, 2025 9:34pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 24, 2025

Walkthrough

Error handling for Microsoft Outlook authentication has been refined. The Outlook client now detects specific Azure AD error codes and throws user-friendly SafeError exceptions for re-authentication scenarios. The middleware has been updated to propagate SafeError exceptions to higher-level handlers instead of converting them to 500 responses.

Changes

Cohort / File(s) Summary
Outlook authentication error handling
apps/web/utils/outlook/client.ts, apps/web/utils/middleware.ts
Outlook client detects Microsoft identity platform error codes (AADSTS70000, AADSTS70008, AADSTS70011, AADSTS700082, AADSTS50173, AADSTS65001, AADSTS500011, AADSTS54005, invalid_grant) in getOutlookClientWithRefresh and throws SafeError with user-facing re-authentication message. Middleware updated to re-throw SafeError instead of converting to 500 response, allowing propagation to higher-level handlers.

Sequence Diagram

sequenceDiagram
    participant Client as Client Request
    participant OutlookClient as Outlook Client
    participant Middleware as Email Middleware
    participant ErrorHandler as Error Handler

    Client->>OutlookClient: Request (with expired token)
    OutlookClient->>OutlookClient: Detect AADSTS error code
    OutlookClient->>OutlookClient: Log warning
    OutlookClient->>Middleware: Throw SafeError
    
    rect rgb(220, 240, 255)
    Note over Middleware: NEW: Check if SafeError
    Middleware->>Middleware: Identify as SafeError
    Middleware->>ErrorHandler: Re-throw SafeError
    end
    
    ErrorHandler->>Client: User-friendly re-auth message
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Verify correctness of all specific AADSTS error codes listed (AADSTS70000, AADSTS70008, AADSTS70011, AADSTS700082, AADSTS50173, AADSTS65001, AADSTS500011, AADSTS54005, invalid_grant)
  • Ensure SafeError message is appropriately formatted and user-facing
  • Confirm middleware error handling logic correctly distinguishes between SafeError and other error types

Possibly related PRs

  • Outlook auth #493: Introduces Outlook auth token-refresh logic that the current PR now enhances with specific error code detection and SafeError handling.
  • Adjust api auth #363: Modifies SafeError's constructor/signature and implements SafeError usage in API auth; current PR extends SafeError propagation through middleware and Outlook client.
  • Adjust logging #937: Previously modified Outlook client to handle Azure AD refresh/token errors; current PR refines this with SafeError-based re-authentication prompts.

Poem

🐰 Azure dreams and tokens true,
SafeErrors hop through, bright and new,
No more fives-and-zeros' sly refrain,
Users smile, re-auth again!
Hoppy errors, bugs, begone—
Our Warren's auth now marches on!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'show outlook sign in again message' accurately reflects the main change: adding user-facing messaging prompting Outlook users to reconnect when authentication errors occur.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/logs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/web/utils/outlook/client.ts (1)

146-178: Re‑auth SafeError flow is sound; consider tightening overlap with catch‑block logging

The new requiresReauth detection for specific AADSTS / invalid_grant cases looks good and, combined with throwing a SafeError, gives you a clean, user‑facing “sign in again” message that will propagate through emailProviderMiddleware and withMiddleware as intended.

One minor cleanup you could consider: since these same invalid_grant / AADSTS50173 cases now throw a SafeError with a human‑readable message, the isInvalidGrantError check in the catch block (which looks for those substrings on error.message) will no longer match for this path. Logging is already covered by the new logger.warn("Microsoft authorization expired - user needs to reconnect", ...), so you might either:

  • Narrow isInvalidGrantError to only the remaining scenarios you still expect there, or
  • Remove the overlapping substrings from the catch‑block check to avoid confusion about when that logging actually triggers.

Purely optional, since behavior is already correct.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 027f420 and 977a164.

📒 Files selected for processing (2)
  • apps/web/utils/middleware.ts (1 hunks)
  • apps/web/utils/outlook/client.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Applied to files:

  • apps/web/utils/middleware.ts
🧬 Code graph analysis (2)
apps/web/utils/middleware.ts (1)
apps/web/utils/error.ts (1)
  • SafeError (59-69)
apps/web/utils/outlook/client.ts (1)
apps/web/utils/error.ts (1)
  • SafeError (59-69)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Review for correctness
  • GitHub Check: test
🔇 Additional comments (1)
apps/web/utils/middleware.ts (1)

302-317: SafeError rethrow correctly preserves user‑friendly auth errors

Re‑throwing SafeError from emailProviderMiddleware lets the top‑level withMiddleware handler apply its dedicated SafeError logic (including the special “No refresh token” path and generic safe‑message 400s) instead of masking these as a 500 “Failed to initialize email provider”. This is a clean way to surface the new Outlook re‑auth messaging without affecting other error paths.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

@elie222 elie222 merged commit d666fb2 into main Nov 25, 2025
17 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 28, 2025
@elie222 elie222 deleted the chore/logs branch December 18, 2025 23:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant