Skip to content

Migrate to better auth#637

Merged
elie222 merged 102 commits intoelie222:mainfrom
edulelis:migrate-to-better-auth
Aug 11, 2025
Merged

Migrate to better auth#637
elie222 merged 102 commits intoelie222:mainfrom
edulelis:migrate-to-better-auth

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Aug 5, 2025

Summary by CodeRabbit

  • New Features

    • Migrated to Better Auth and updated Google/Microsoft sign-in flows with new async handlers.
  • Bug Fixes

    • Unified Microsoft provider identifier to "microsoft".
    • Made token expiration values consistently numeric to improve refresh and client behavior.
  • Refactor

    • Replaced external auth hooks/providers with local utilities and simplified token/session handling.
    • Updated sign-out flow to perform explicit redirects.
  • Chores

    • Updated dependencies and applied database migrations for the new auth system.
  • Documentation

    • Added an OAuth redirect URI to README.

edulelis and others added 30 commits July 31, 2025 18:01
…unt-prompt

Add consent and account_select to Microsoft Entra
…unt-prompt

Set logger, update error page
…unt-prompt

Separate google/microsoft-entra-id logic on jwt
…unt-prompt

Add missing authorization url
@elie222
Copy link
Owner

elie222 commented Aug 11, 2025

@claude review

@claude
Copy link

claude bot commented Aug 11, 2025

Claude encountered an error —— View job

Failed with exit code 128

I'll analyze this and get back to you.

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

🧹 Nitpick comments (3)
apps/web/app/api/google/linking/callback/route.ts (2)

76-77: Use structured logger context for errors

Pass errors as structured context for consistency with the rest of the file.

-      logger.error("ID token verification failed using googleAuth:", err);
+      logger.error("ID token verification failed using googleAuth", { error: err });

172-174: Unreachable mapping branch (“Missing access_token”)

This code path never throws a “Missing access_token” error. Consider pruning or mapping to realistic googleAuth.getToken failures instead.

apps/web/app/api/outlook/linking/callback/route.ts (1)

136-139: Consider including source user id in “Merging…” log

You include sourceUserId in the post-transaction log. Including it here improves traceability if the transaction fails.

-    logger.info("Merging Microsoft account linked to user.", {
-      email: providerEmail,
-      targetUserId,
-    });
+    logger.info("Merging Microsoft account linked to user.", {
+      email: providerEmail,
+      targetUserId,
+      sourceUserId: existingAccount.userId,
+    });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6eb4fd5 and 5e7efc6.

📒 Files selected for processing (2)
  • apps/web/app/api/google/linking/callback/route.ts (3 hunks)
  • apps/web/app/api/outlook/linking/callback/route.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.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/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
🧠 Learnings (3)
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
PR: elie222/inbox-zero#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/app/api/google/linking/callback/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operations

Applied to files:

  • apps/web/app/api/outlook/linking/callback/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withEmailAccount` middleware for API routes that operate on a specific email account (i.e., use or require `emailAccountId`).

Applied to files:

  • apps/web/app/api/outlook/linking/callback/route.ts
🧬 Code Graph Analysis (2)
apps/web/app/api/google/linking/callback/route.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
apps/web/app/api/outlook/linking/callback/route.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
⏰ 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 (8)
apps/web/app/api/google/linking/callback/route.ts (4)

102-107: Structured warning with contextual fields — good

Consistent message and structured context will make log search far easier. No concerns.


114-119: “Already linked to self” log refactor looks good

Clear, stable message with context. Matches the pattern used elsewhere.


128-135: Merge log now uses stable message + useful context

Includes email, providerAccountId, existingUserId, targetUserId — sufficient for traceability.


154-158: Post-merge reassignment log is clear and actionable

Context includes providerAccountId, targetUserId, originalUserId. Looks good.

apps/web/app/api/outlook/linking/callback/route.ts (4)

98-100: Good explicit failure when profile email is absent

Clear error that’s later mapped to “incomplete_profile”. No issues.


118-120: Merge-failed log matches the agreed structured format

Stable string with { email }. Matches prior guidance. LGTM.


127-129: Already-linked log refactor is consistent

Stable message; context includes email and targetUserId. Good.


158-162: Reassignment log includes the right context

Email, targetUserId, sourceUserId present. Looks good.

Comment on lines +325 to +330
if (provider === "microsoft") {
providerOptions.push({
label: "Move to folder",
value: ActionType.MOVE_FOLDER,
});
}
Copy link
Owner

Choose a reason for hiding this comment

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

i would just inline as anyway if things will be added in the future it's unlikely in the next spot after move to folder

cc: z.string().nullish(),
bcc: z.string().nullish(),
subject: z.string().nullish(),
folderName: z.string().nullish(),
Copy link
Owner

Choose a reason for hiding this comment

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

ya folder shouldn't be an option for google. will confuse the ai and can't be used anyway

case ActionType.DIGEST:
actions.push("add to digest");
break;
case ActionType.MOVE_FOLDER:
Copy link
Owner

Choose a reason for hiding this comment

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

can't be used in google

.nullish()
.transform((v) => v ?? null)
.describe("The webhook URL to call"),
folderName: z
Copy link
Owner

Choose a reason for hiding this comment

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

can't be used in google

ownerEmail: string,
folderName: string,
): Promise<void> {
await outlookArchiveThread({
Copy link
Owner

Choose a reason for hiding this comment

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

should this be archive? seems like a bad function name?

return folderIdCache;
}

export async function getOrCreateFolderByName(
Copy link
Owner

Choose a reason for hiding this comment

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

worth adding a test. ai can generate it quickly

@elie222 elie222 merged commit 4dc9cdd into elie222:main Aug 11, 2025
21 of 23 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 18, 2025
@edulelis edulelis deleted the migrate-to-better-auth branch August 27, 2025 20:32
This was referenced Sep 2, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 25, 2025
This was referenced Oct 21, 2025
This was referenced Jan 5, 2026
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.

3 participants