Skip to content

fix: Clean refresh token only if "invalid_grant"#703

Merged
elie222 merged 4 commits intoelie222:mainfrom
edulelis:fix-gmail-refresh-tokens
Aug 20, 2025
Merged

fix: Clean refresh token only if "invalid_grant"#703
elie222 merged 4 commits intoelie222:mainfrom
edulelis:fix-gmail-refresh-tokens

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Aug 20, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Always prompt Google consent during account connection.
    • Improved Gmail permission checks: validate scopes before/after refresh and attempt refresh when possible.
    • Clearer messaging when access expires, advising reconnection and listing missing permissions.
    • Avoid unconditional deletion of credentials; only clean up stale tokens when refresh confirms expiration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Adds prompt: "consent" to Google OAuth URL generation. Enhances Gmail permissions check: expands refreshable error set, performs a forced refresh and re-checks scopes, conditionally clears tokens on invalid_grant via Prisma, returns explicit reconnect errors with missingScopes, and tightens refreshToken parameter to string.

Changes

Cohort / File(s) Summary of Changes
Google OAuth auth-url
apps/web/app/api/google/linking/auth-url/route.ts
Added prompt: "consent" to googleAuth.generateAuthUrl options; access_type, scope, and state unchanged.
Gmail permissions/refresh flow
apps/web/utils/gmail/permissions.ts
Broadened refreshable error set (invalid_token, invalid_grant, invalid_scope, access_denied); checks permissions before refresh; if error and refreshable, forces refresh via getGmailClientWithRefresh, re-checks scopes; on re-check invalid_grant clears access_token, refresh_token, expires_at via Prisma and returns reconnect error + missingScopes; on refresh failure returns reconnect error; removed prior unconditional token-cleanup branch; updated function signature: refreshToken: string (was `string

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant P as handleGmailPermissionsCheck
  participant G as Google API
  participant DB as Prisma

  C->>P: checkPermissions(emailAccountId, access_token, refresh_token)
  P->>G: permissionsCheck(access_token)
  alt Permissions OK
    G-->>P: hasAllPermissions = true
    P-->>C: { hasAllPermissions: true }
  else Error ∈ {invalid_token, invalid_grant, invalid_scope, access_denied}
    alt refresh_token exists
      P->>G: refreshAccessToken(refresh_token) (force)
      alt Refresh succeeds
        G-->>P: new access_token
        P->>G: permissionsCheck(new access_token)
        alt Re-check error == invalid_grant
          P->>DB: clear tokens (access_token, refresh_token, expires_at)
          DB-->>P: cleared / not found
          P-->>C: { hasAllPermissions: false, error: "Gmail access expired. Please reconnect your account.", missingScopes }
        else Other re-check result
          P-->>C: { hasAllPermissions, error, missingScopes }
        end
      else Refresh fails
        P-->>C: { hasAllPermissions: false, error: "Gmail access expired. Please reconnect your account.", missingScopes }
      end
    else No refresh_token
      P-->>C: { hasAllPermissions: false, missingScopes }
    end
  end
Loading
sequenceDiagram
  autonumber
  participant Client
  participant Route as /api/google/linking/auth-url
  participant GA as googleAuth

  Client->>Route: GET auth URL
  Route->>GA: generateAuthUrl({ access_type: "offline", scope, state, prompt: "consent" })
  GA-->>Route: auth URL
  Route-->>Client: 200 OK (URL)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A rabbit hops to OAuth's gate,
"Consent," it hums — renew our slate.
Tokens tumble, scopes align,
If grants expire, we clear the vine.
Reconnect, dear inbox—sun will shine. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fdcdbe0 and 602138d.

📒 Files selected for processing (1)
  • apps/web/utils/gmail/permissions.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/utils/gmail/permissions.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel
Copy link

vercel bot commented Aug 20, 2025

@edulelis is attempting to deploy a commit to the Inbox Zero OSS Program Team on Vercel.

A member of the Team first needs to authorize it.

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: 2

🧹 Nitpick comments (3)
apps/web/app/api/google/linking/auth-url/route.ts (1)

19-19: Consent prompt will always re-prompt users; consider UX and incremental auth.

Adding prompt: "consent" guarantees a fresh consent screen (and helps ensure a refresh_token is issued), which is often desired on linking/re-linking. If you want users to also easily switch Google accounts during linking, consider adding select_account. To reduce unnecessary re-prompts while still enabling incremental auth, consider include_granted_scopes: true.

Proposed tweak:

   const url = googleAuth.generateAuthUrl({
     access_type: "offline",
     scope: [...new Set([...SCOPES, "openid", "email"])].join(" "),
-    prompt: "consent",
+    // Re-prompt and allow account switching during linking flows
+    prompt: "consent select_account",
+    // Enable incremental auth without re-requesting already granted scopes
+    include_granted_scopes: true,
     state,
   });

Please confirm this aligns with your desired UX for the linking flow before adopting.

apps/web/utils/gmail/permissions.ts (2)

87-95: Refresh-trigger criteria include codes unlikely from tokeninfo; validate assumption.

checkGmailPermissions calls tokeninfo, which typically returns invalid_token for bad/expired access tokens. invalid_grant is usually emitted by the token refresh endpoint, not by tokeninfo. Including invalid_scope and access_denied here will trigger refresh attempts that cannot grant new scopes (refresh cannot expand scopes), though it’s harmless.

If you want to narrowly refresh only when it helps, consider:

  • Trigger refresh primarily on invalid_token (and possibly generic network failures).
  • Handle invalid_grant specifically in the refresh attempt’s catch path (see next comments).

109-114: Avoid shadowing outer variables for clarity.

Destructuring into the same identifiers (hasAllPermissions, error, missingScopes) that are already defined above reduces readability and can lead to mistakes.

Suggested rename:

-        const { hasAllPermissions, error, missingScopes } =
+        const {
+          hasAllPermissions: hasAllPermissionsAfterRefresh,
+          error: errorAfterRefresh,
+          missingScopes: missingScopesAfterRefresh,
+        } =
           await checkGmailPermissions({
             accessToken: newAccessToken,
             emailAccountId,
           });

And update the subsequent return accordingly (see next comment).

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6e673fc and 822d014.

📒 Files selected for processing (2)
  • apps/web/app/api/google/linking/auth-url/route.ts (1 hunks)
  • apps/web/utils/gmail/permissions.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
  • apps/web/utils/gmail/permissions.ts
apps/web/app/**

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit Inference Engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
  • apps/web/utils/gmail/permissions.ts
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
  • apps/web/utils/gmail/permissions.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
  • apps/web/utils/gmail/permissions.ts
**/api/**/route.ts

📄 CodeRabbit Inference Engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit Inference Engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
  • apps/web/utils/gmail/permissions.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/api/google/linking/auth-url/route.ts
  • apps/web/utils/gmail/permissions.ts
apps/web/utils/gmail/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/gmail-api.mdc)

Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Files:

  • apps/web/utils/gmail/permissions.ts
apps/web/utils/**

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/gmail/permissions.ts
apps/web/utils/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/gmail/permissions.ts
🧠 Learnings (1)
📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Applied to files:

  • apps/web/utils/gmail/permissions.ts
⏰ 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). (2)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security

if (
error &&
[
"invalid_token",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Increased the error list for attempting to acquire a new access token.

};
}
} else {
logger.warn("Got no refresh token to attempt refresh", {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This should never happen, but added a log here to observe.

@edulelis edulelis changed the title WIP: fix: Clean refresh token only if "invalid_grant" fix: Clean refresh token only if "invalid_grant" Aug 20, 2025
const url = googleAuth.generateAuthUrl({
access_type: "offline",
scope: [...new Set([...SCOPES, "openid", "email"])].join(" "),
prompt: "consent",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ideally, we want the user's consent due to the added scopes.

Copy link
Owner

Choose a reason for hiding this comment

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

I don't think it's needed. consent just means if they need to reconsent. If they hadn't given consent they'd see the consent screen anyway. But it's fine to keep this in anyway. It means the user is forced to give consent again even if they already gave consent.

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: 1

♻️ Duplicate comments (2)
apps/web/utils/gmail/permissions.ts (2)

115-144: Token cleanup on permissionsAfterRefresh.error === "invalid_grant" is unreachable in practice. Move cleanup into the refresh catch.

invalid_grant is thrown by the token refresh endpoint, not by tokeninfo. This branch will almost never run, so tokens won’t be cleaned when refresh fails with invalid_grant. This deviates from the PR objective “Clean refresh token only if invalid_grant”.

Remove this unreachable block and handle invalid_grant in the catch below:

-      if (
-        permissionsAfterRefresh.error &&
-        permissionsAfterRefresh.error === "invalid_grant"
-      ) {
-        logger.info("Cleaning up invalid Gmail tokens", { emailAccountId });
-        const emailAccount = await prisma.emailAccount.findUnique({
-          where: { id: emailAccountId },
-          select: { accountId: true },
-        });
-        if (!emailAccount)
-          return {
-            hasAllPermissions: false,
-            error: "Email account not found",
-          };
-
-        await prisma.account.update({
-          where: { id: emailAccount.accountId },
-          data: {
-            access_token: null,
-            refresh_token: null,
-            expires_at: null,
-          },
-        });
-
-        return {
-          hasAllPermissions: false,
-          error: "Gmail access expired. Please reconnect your account.",
-          missingScopes: permissionsBeforeRefresh.missingScopes,
-        };
-      }

147-153: Clean up tokens on invalid_grant and add observability

Google’s OAuth2 token endpoint returns error=invalid_grant (HTTP 400) when a refresh token is expired, revoked, or otherwise invalid (RFC 6749). Update the catch block in apps/web/utils/gmail/permissions.ts (around lines 147–153) to:

  • Inspect the caught error for "invalid_grant"
  • On "invalid_grant":
    • Log at INFO level
    • Clear the stored access_token, refresh_token, and expires_at in the database
    • Return the “please reconnect” response
  • On any other error:
    • Log a WARN with the failure reason
    • Return the same “please reconnect” response

Apply:

-    } catch (_) {
-      return {
-        hasAllPermissions: false,
-        error: "Gmail access expired. Please reconnect your account.",
-        missingScopes: permissionsBeforeRefresh.missingScopes,
-      };
-    }
+    } catch (err: unknown) {
+      const reason =
+        (err as any)?.response?.data?.error ||
+        (err as any)?.error ||
+        (err as any)?.code ||
+        (err as any)?.message ||
+        "unknown_error";
+
+      if (reason === "invalid_grant") {
+        logger.info("Cleaning up invalid Gmail tokens after refresh invalid_grant", {
+          emailAccountId,
+        });
+
+        const emailAccount = await prisma.emailAccount.findUnique({
+          where: { id: emailAccountId },
+          select: { accountId: true },
+        });
+        if (!emailAccount) {
+          return {
+            hasAllPermissions: false,
+            error: "Email account not found",
+          };
+        }
+
+        await prisma.account.update({
+          where: { id: emailAccount.accountId },
+          data: {
+            access_token: null,
+            refresh_token: null,
+            expires_at: null,
+          },
+        });
+
+        return {
+          hasAllPermissions: false,
+          error: "Gmail access expired. Please reconnect your account.",
+          missingScopes: permissionsBeforeRefresh.missingScopes,
+        };
+      }
+
+      logger.warn("Failed to refresh Gmail access token", { emailAccountId, reason });
+      return {
+        hasAllPermissions: false,
+        error: "Gmail access expired. Please reconnect your account.",
+        missingScopes: permissionsBeforeRefresh.missingScopes,
+      };
+    }
🧹 Nitpick comments (2)
apps/web/utils/gmail/permissions.ts (2)

89-97: Refresh gating looks fine, but note tokeninfo won’t emit invalid_grant.

Keeping a set of “refreshable” errors is good, but tokeninfo typically returns errors like invalid_token; invalid_grant comes from the refresh token endpoint, not tokeninfo.

Optional tidy-up to make this a bit clearer and avoid repeated .includes:

-  if (
-    permissionsBeforeRefresh.error &&
-    [
-      "invalid_token",
-      "invalid_grant",
-      "invalid_scope",
-      "access_denied",
-    ].includes(permissionsBeforeRefresh.error)
-  ) {
+  const refreshableErrors = new Set([
+    "invalid_token",
+    "invalid_grant",
+    "invalid_scope",
+    "access_denied",
+  ]);
+  if (permissionsBeforeRefresh.error && refreshableErrors.has(permissionsBeforeRefresh.error)) {

108-114: Avoid shadowing the accessToken parameter.

Rename to clarify intent and reduce confusion when reading logs and traces.

Apply:

-      // re-check permissions with the new access token
-      const accessToken = getAccessTokenFromClient(gmailClient);
-      const permissionsAfterRefresh = await checkGmailPermissions({
-        accessToken,
-        emailAccountId,
-      });
+      // re-check permissions with the new access token
+      const refreshedAccessToken = getAccessTokenFromClient(gmailClient);
+      const permissionsAfterRefresh = await checkGmailPermissions({
+        accessToken: refreshedAccessToken,
+        emailAccountId,
+      });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 203c566 and fdcdbe0.

📒 Files selected for processing (1)
  • apps/web/utils/gmail/permissions.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/gmail/permissions.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit Inference Engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/gmail/permissions.ts
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/gmail/permissions.ts
apps/web/utils/gmail/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/gmail-api.mdc)

Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Files:

  • apps/web/utils/gmail/permissions.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/gmail/permissions.ts
apps/web/utils/**

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/gmail/permissions.ts
apps/web/utils/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/gmail/permissions.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/gmail/permissions.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/gmail/permissions.ts
🧠 Learnings (1)
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/utils/gmail/permissions.ts
🧬 Code Graph Analysis (1)
apps/web/utils/gmail/permissions.ts (1)
apps/web/utils/gmail/client.ts (2)
  • getGmailClientWithRefresh (49-103)
  • getAccessTokenFromClient (117-122)
⏰ 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). (2)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (2)
apps/web/utils/gmail/permissions.ts (2)

84-87: LGTM: Pre-check permissions before attempting a refresh.

The early, lightweight tokeninfo check before a refresh is sensible and avoids unnecessary refresh calls.


99-107: LGTM: Forced refresh path is correct.

Passing accessToken: null and expiresAt: null to force a refresh aligns with getGmailClientWithRefresh’s behavior and intent.

@edulelis
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@elie222 elie222 merged commit 1995501 into elie222:main Aug 20, 2025
9 of 10 checks passed
nnennajohn pushed a commit to slimui/inbox-zero that referenced this pull request Aug 26, 2025
@edulelis edulelis deleted the fix-gmail-refresh-tokens branch August 27, 2025 20:32
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.

2 participants

Comments