Skip to content

fix: Patch better-auth to force delete image of the session cache#727

Merged
elie222 merged 1 commit intoelie222:mainfrom
edulelis:fix-microsoft-auth-large-cookies-v3
Aug 29, 2025
Merged

fix: Patch better-auth to force delete image of the session cache#727
elie222 merged 1 commit intoelie222:mainfrom
edulelis:fix-microsoft-auth-large-cookies-v3

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Aug 28, 2025

Summary by CodeRabbit

  • Chores

    • Applied a dependency patch to the authentication library via package configuration.
  • Refactor

    • User profile images are no longer included in session data, reducing cookie size and payload.

@vercel
Copy link

vercel bot commented Aug 28, 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.

@edulelis edulelis changed the title fix:Patch better-auth to force delete image of the session cache fix: Patch better-auth to force delete image of the session cache Aug 28, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 28, 2025

Walkthrough

Adds pnpm patchedDependencies in package.json to apply a local patch to better-auth@1.3.4. The patch modifies dist/cookies/index.mjs to set session.user.image = null in setCookieCache before building sessionData.

Changes

Cohort / File(s) Summary
Package config (pnpm patch wiring)
package.json
Adds pnpm patchedDependencies mapping for better-auth@1.3.4 to patches/better-auth@1.3.4.patch. Existing overrides unchanged.
Third-party patch
patches/better-auth@1.3.4.patch
In dist/cookies/index.mjs, updates setCookieCache(ctx, session) to set session.user.image = null before constructing sessionData.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App
  participant BetterAuth as better-auth (patched)
  participant CookieStore as Cookie Store

  App->>BetterAuth: setCookieCache(ctx, session)
  Note right of BetterAuth: Clear image field<br/>session.user.image = null
  BetterAuth->>BetterAuth: Construct sessionData from session
  BetterAuth->>CookieStore: Write sessionData to cookies
  CookieStore-->>App: Ack
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I nibbled the code with a careful bite,
Patched the auth so cookies stay light.
A portrait removed, a session made neat—
Crunching dependencies like carrot treat. 🥕
Now hop along, secure and bright!

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.

✨ Finishing Touches
🧪 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 @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit 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 @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @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.

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

🧹 Nitpick comments (2)
package.json (1)

33-39: Add a brief comment near patchedDependencies explaining the rationale and removal plan.

Helps future maintainers understand why this exists and when it can be dropped after an upstream fix.

patches/better-auth@1.3.4.patch (1)

1-12: Consider upstreaming or using a library hook to exclude large fields.

Longer-term, prefer a first-class option (e.g., a transform/omit callback) over patching dist files to reduce maintenance risk on upgrades.

📜 Review details

Configuration used: Path: .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 c8df439 and 08afcaf.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • patches/better-auth@1.3.4.patch (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
!{.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:

  • patches/better-auth@1.3.4.patch
  • package.json
!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:

  • patches/better-auth@1.3.4.patch
  • package.json

Comment on lines 33 to 39
"overrides": {
"@types/react": "19.0.10",
"@types/react-dom": "19.0.4"
},
"patchedDependencies": {
"better-auth@1.3.4": "patches/better-auth@1.3.4.patch"
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Commit the updated lockfile and verify the patch is wired.

Ensure pnpm-lock.yaml captures the patch; otherwise CI or new installs may miss it.


🏁 Script executed:

#!/bin/bash
set -euo pipefail
LOCK="$(fd -H --max-depth 1 '^pnpm-lock\.yaml$' | head -n1)"
if [[ -z "${LOCK}" ]]; then
  echo "pnpm-lock.yaml not found at repo root"; exit 1
fi

echo "Checking lockfile for patched better-auth@1.3.4…"
rg -nC2 -F 'patch:better-auth@1.3.4' "$LOCK" || { echo "Patch not recorded in lockfile"; exit 2; }
rg -nC2 -F 'patchedDependencies:' "$LOCK" || echo "Note: lockfile format may differ; manually confirm patch entry."

echo "Verifying patch file path exists…"
test -f patches/better-auth@1.3.4.patch || { echo "Patch file missing"; exit 3; }
echo "OK"

Length of output: 361


Commit updated lockfile with patch entry
pnpm-lock.yaml is missing the patch:better-auth@1.3.4 entry; run pnpm install, commit the updated pnpm-lock.yaml to include it, and confirm patches/better-auth@1.3.4.patch exists so the patch is wired.

🤖 Prompt for AI Agents
In package.json around lines 33 to 39, you added a patchedDependencies entry for
better-auth@1.3.4 but did not update pnpm-lock.yaml; run `pnpm install` locally
to regenerate the lockfile so it includes the `patch:better-auth@1.3.4` entry,
verify that `patches/better-auth@1.3.4.patch` exists in the repo, then commit
the updated pnpm-lock.yaml (and the patch file if missing) so the patch is
correctly wired.

🛠️ Refactor suggestion

Pin better-auth to 1.3.4 in pnpm.overrides so the patch always applies.

Without an override, a transitive resolution to a different better-auth version will bypass the patch.

Apply:

   "pnpm": {
     "overrides": {
+      "better-auth": "1.3.4",
       "@types/react": "19.0.10",
       "@types/react-dom": "19.0.4"
     },
     "patchedDependencies": {
       "better-auth@1.3.4": "patches/better-auth@1.3.4.patch"
     }
   }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In package.json around lines 33 to 39, add an override that pins better-auth to
version 1.3.4 so the patch always applies: update the existing overrides map to
include "better-auth": "1.3.4" (alongside the @types entries) and save; this
ensures pnpm will always resolve better-auth@1.3.4 and the patchedDependencies
entry will be used.

Comment on lines +1 to +12
diff --git a/dist/cookies/index.mjs b/dist/cookies/index.mjs
index f4c53b8b90f61589ffe873e22d756bf081144f2f..993b62d63705fe3ffee1bfea69386d939b482c77 100644
--- a/dist/cookies/index.mjs
+++ b/dist/cookies/index.mjs
@@ -259,6 +259,7 @@ async function setCookieCache(ctx, session) {
},
{}
);
+ session.user.image = null;
const sessionData = { session: filteredSession, user: session.user };
const expiresAtDate = getDate(
ctx.context.authCookies.sessionData.options.maxAge || 60,
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Regenerate the patch rather than hand-editing to keep headers consistent.

After changing the hunk, use pnpm patch / patch-commit to re-create the patch so it applies cleanly across environments.


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Quick sanity check: ensure the patch reflects 'userWithoutImage' lines"
rg -nC2 'userWithoutImage' patches/better-auth@1.3.4.patch || { echo "Patch not updated"; exit 1; }

Length of output: 289


Regenerate the patch using pnpm patch / patch-commit
Hand-editing dropped the intended userWithoutImage changes and misaligned headers. Recreate the patch via the patch tool so it cleanly includes the proper hunk.

🤖 Prompt for AI Agents
In patches/better-auth@1.3.4.patch around lines 1 to 12, the hand-edited diff
replaced the intended userWithoutImage logic with a direct assignment
(session.user.image = null) and misaligned hunk headers; regenerate the patch
using the repo's patch tooling (pnpm patch or patch-commit) so the proper
transformation that creates userWithoutImage (or equivalent filtered user
object) is preserved, ensure the diff hunk headers and context lines are
correct, and commit the regenerated patch file instead of hand-editing.

Comment on lines +5 to +12
@@ -259,6 +259,7 @@ async function setCookieCache(ctx, session) {
},
{}
);
+ session.user.image = null;
const sessionData = { session: filteredSession, user: session.user };
const expiresAtDate = getDate(
ctx.context.authCookies.sessionData.options.maxAge || 60,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Avoid mutating session.user; safely omit image from the cached payload.

Current code sets session.user.image = null, which:

  • Mutates the input (possible side effects if the object is reused).
  • Retains an "image": null key, wasting bytes.
  • Can throw if session.user is undefined.

Update the patch to construct a user object without image:

@@ -259,6 +259,7 @@ async function setCookieCache(ctx, session) {
       },
       {}
     );
-+    session.user.image = null;
-+    const sessionData = { session: filteredSession, user: session.user };
++    const user = session.user ?? {};
++    const { image: _omit, ...userWithoutImage } = user;
++    const sessionData = { session: filteredSession, user: userWithoutImage };
     const expiresAtDate = getDate(
       ctx.context.authCookies.sessionData.options.maxAge || 60,

This removes the image field entirely, minimizes cookie size, and avoids side effects.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@@ -259,6 +259,7 @@ async function setCookieCache(ctx, session) {
},
{}
);
+ session.user.image = null;
const sessionData = { session: filteredSession, user: session.user };
const expiresAtDate = getDate(
ctx.context.authCookies.sessionData.options.maxAge || 60,
@@ async function setCookieCache(ctx, session) {
},
{}
);
const user = session.user ?? {};
const { image: _omit, ...userWithoutImage } = user;
const sessionData = { session: filteredSession, user: userWithoutImage };
const expiresAtDate = getDate(
ctx.context.authCookies.sessionData.options.maxAge || 60,
);
// …
}
🤖 Prompt for AI Agents
In patches/better-auth@1.3.4.patch around lines 5 to 12, the change mutates
session.user.image = null; instead construct a new user object that omits the
image property and use that in sessionData instead of mutating the original
(e.g. if session.user is defined, create a shallow copy that excludes image and
assign that to the user field; if session.user is undefined keep it undefined),
then pass { session: filteredSession, user: safeUser } to sessionData so you
avoid side effects, possible errors when user is undefined, and the extra null
field in the cookie payload.

@elie222 elie222 merged commit a03348a into elie222:main Aug 29, 2025
12 of 14 checks passed
@edulelis edulelis deleted the fix-microsoft-auth-large-cookies-v3 branch August 29, 2025 14:37
This was referenced Oct 21, 2025
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