fix: Clean refresh token only if "invalid_grant"#703
Conversation
WalkthroughAdds Changes
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
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
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 detailsConfiguration used: .coderabbit.yaml 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
@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. |
There was a problem hiding this comment.
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 addingselect_account. To reduce unnecessary re-prompts while still enabling incremental auth, considerinclude_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.
checkGmailPermissionscallstokeninfo, which typically returnsinvalid_tokenfor bad/expired access tokens.invalid_grantis usually emitted by the token refresh endpoint, not bytokeninfo. Includinginvalid_scopeandaccess_deniedhere 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_grantspecifically 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.
📒 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.tsapps/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: UsewithAuthfor user-level operations
UsewithEmailAccountfor 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 withwithAuthorwithEmailAccountmiddleware 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.tsapps/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.tsapps/web/utils/gmail/permissions.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport 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.tsapps/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).
UsewithEmailAccountmiddleware for API routes that operate on a specific email account (i.e., use or requireemailAccountId).
UsewithAuthmiddleware for API routes that operate at the user level (i.e., use or require onlyuserId).
UsewithErrormiddleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST usewithErrormiddleware and validate the cron secret usinghasCronSecret(request)orhasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts withcaptureExceptionand 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.
AllfindUniqueandfindFirstPrisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
AllfindManyPrisma 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 useelements 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.tsapps/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.tsapps/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", |
There was a problem hiding this comment.
Increased the error list for attempting to acquire a new access token.
| }; | ||
| } | ||
| } else { | ||
| logger.warn("Got no refresh token to attempt refresh", { |
There was a problem hiding this comment.
This should never happen, but added a log here to observe.
| const url = googleAuth.generateAuthUrl({ | ||
| access_type: "offline", | ||
| scope: [...new Set([...SCOPES, "openid", "email"])].join(" "), | ||
| prompt: "consent", |
There was a problem hiding this comment.
Ideally, we want the user's consent due to the added scopes.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 oninvalid_grantand add observabilityGoogle’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 inapps/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, andexpires_atin 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.
📒 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}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport 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 useelements 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.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Summary by CodeRabbit