Skip to content

Conversation

cy948
Copy link
Contributor

@cy948 cy948 commented Jun 15, 2025

💻 变更类型 | Change Type

  • ✨ feat
  • 🐛 fix
  • ♻️ refactor
  • 💄 style
  • 👷 build
  • ⚡️ perf
  • 📝 docs
  • 🔨 chore

🔀 变更说明 | Description of Change

Main Changes:

  • src/libs/next-auth/adapter/index.ts: 改为call后端api endpoint完成 database 调用。
  • src/app/(backend)/api/auth/adapter/route.ts: 调用 service。
  • src/server/services/nextAuthUser/index.ts: 放置原 adapter 的 ORM 操作。

Cascade Changes:

  • src/libs/next-auth/edge.ts

📝 补充信息 | Additional Information

Summary by Sourcery

Refactor NextAuth database adapter to be edge-compatible by routing all ORM operations through a secured backend API endpoint and update related configurations and initializations

Enhancements:

  • Migrate LobeNextAuthDbAdapter to invoke a new /api/auth/adapter HTTP endpoint instead of direct ORM calls
  • Introduce a backend API route and NextAuthUserService to centralize and secure all adapter database operations
  • Revise NextAuth initialization and auth.config to use JWT sessions, environment-driven adapter setup, and remove the legacy edge adapter
  • Update trpc contexts, middleware, and server auth utilities to import and use the consolidated NextAuth module instead of the edge-specific variant
  • Add NEXT_AUTH_SSO_SESSION_STRATEGY environment variable and integrate it into the auth configuration for session strategy control

Copy link

vercel bot commented Jun 15, 2025

@cy948 is attempting to deploy a commit to the LobeHub Community Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

sourcery-ai bot commented Jun 15, 2025

Reviewer's Guide

Refactors the NextAuth DB adapter to be edge runtime compatible by moving ORM operations behind a secure backend API endpoint, centralizing database logic in NextAuthUserService, and updating NextAuth initialization, contexts, and configuration to use the new fetch-based adapter.

Sequence diagram for NextAuth adapter DB operation via backend API

sequenceDiagram
    participant NextAuthAdapter as NextAuth Adapter (Edge)
    participant BackendAPI as /api/auth/adapter (Backend API)
    participant NextAuthUserService as NextAuthUserService
    participant DB as Database

    NextAuthAdapter->>BackendAPI: POST /api/auth/adapter {action, data}
    BackendAPI->>NextAuthUserService: Call method based on action
    NextAuthUserService->>DB: Perform ORM/database operation
    DB-->>NextAuthUserService: Return result
    NextAuthUserService-->>BackendAPI: Return result
    BackendAPI-->>NextAuthAdapter: {success, data}
Loading

Class diagram for NextAuthUserService and Adapter refactor

classDiagram
    class NextAuthUserService {
      +safeUpdateUser()
      +createAuthenticator()
      +createSession()
      +createUser()
      +createVerificationToken()
      +deleteSession()
      +deleteUser()
      +getAccount()
      +getAuthenticator()
      +getSessionAndUser()
      +getUser()
      +getUserByAccount()
      +getUserByEmail()
      +linkAccount()
      +listAuthenticatorsByUserId()
      +unlinkAccount()
      +updateAuthenticatorCounter()
      +updateSession()
      +updateUser()
      +useVerificationToken()
    }

    class LobeNextAuthDbAdapter {
      +createAuthenticator()
      +createSession()
      +createUser()
      +createVerificationToken()
      +deleteSession()
      +deleteUser()
      +getAccount()
      +getAuthenticator()
      +getSessionAndUser()
      +getUser()
      +getUserByAccount()
      +getUserByEmail()
      +linkAccount()
      +listAuthenticatorsByUserId()
      +unlinkAccount()
      +updateAuthenticatorCounter()
      +updateSession()
      +updateUser()
      +useVerificationToken()
      -fetcher()
      -postProcessor()
    }

    LobeNextAuthDbAdapter <.. NextAuthUserService : fetches via API
    NextAuthUserService --> "1" Database : uses
    NextAuthUserService --> "1" UserModel : uses
    NextAuthUserService --> "1" AgentService : uses
Loading

File-Level Changes

Change Details Files
Offload adapter DB operations to a protected backend API endpoint
  • Remove direct ORM imports and serverDB usage
  • Introduce fetcher and postProcessor for POSTing actions
  • Validate APP_URL and KEY_VAULTS_SECRET env variables
  • Replace each adapter method with fetch calls
src/libs/next-auth/adapter/index.ts
Add /api/auth/adapter endpoint to handle adapter actions
  • Create POST route parsing action and data
  • Authenticate requests via KEY_VAULTS_SECRET header
  • Dispatch actions through NextAuthUserService switch-case
  • Return standardized success/data/error responses
src/app/(backend)/api/auth/adapter/route.ts
Centralize original ORM adapter logic into NextAuthUserService
  • Extract all adapter methods into service class
  • Retain original Drizzle ORM operations and mappings
  • Import model, schema, and utility mappers
  • Provide safeUpdateUser webhook handler
src/server/services/nextAuthUser/index.ts
Simplify NextAuth initialization and remove edge-specific adapter
  • Update libs/next-auth/index.ts to use auth.config
  • Remove conditional adapter initialization and edge import
  • Configure JWT session strategy directly in auth.config
  • Delete obsolete edge.ts adapter file
src/libs/next-auth/index.ts
src/libs/next-auth/auth.config.ts
src/libs/next-auth/edge.ts
Update TRPC contexts and auth utilities to use new adapter imports
  • Replace imports from @/libs/next-auth/edge with main next-auth
  • Call NextAuth.auth() instead of edge handler
  • Adjust middleware to use NextAuth.auth
  • Update server auth util to import new adapter
src/libs/trpc/edge/context.ts
src/libs/trpc/lambda/context.ts
src/utils/server/auth.ts
src/middleware.ts
Extend auth config schema to include session strategy
  • Add NEXT_AUTH_SSO_SESSION_STRATEGY env var in zod schema
  • Default session strategy to 'jwt'
  • Expose strategy in getAuthConfig
src/config/auth.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@lobehubbot
Copy link
Member

👍 @cy948

Thank you for raising your pull request and contributing to our Community
Please make sure you have followed our contributing guidelines. We will review it as soon as possible.
If you encounter any problems, please feel free to connect with us.
非常感谢您提出拉取请求并为我们的社区做出贡献,请确保您已经遵循了我们的贡献指南,我们会尽快审查它。
如果您遇到任何问题,请随时与我们联系。

@cy948 cy948 force-pushed the refactor/next-auth-db branch 2 times, most recently from 349e47c to d39361f Compare June 15, 2025 12:56
@cy948 cy948 force-pushed the refactor/next-auth-db branch from d39361f to d42fd6c Compare July 22, 2025 03:18
@cy948 cy948 marked this pull request as ready for review July 28, 2025 06:40
Copy link
Contributor

gru-agent bot commented Jul 28, 2025

TestGru Assignment

Summary

Link CommitId Status Reason
Detail d42fd6c ✅ Finished

History Assignment

Files

File Pull Request
src/utils/server/auth.ts ❌ Failed (I failed to setup the environment.)
src/server/services/nextAuthUser/utils.ts ❌ Failed (I failed to setup the environment.)
src/server/services/nextAuthUser/index.ts ❌ Failed (I failed to setup the environment.)
src/server/routers/lambda/user.ts ❌ Failed (I failed to setup the environment.)

Tip

You can @gru-agent and leave your feedback. TestGru will make adjustments based on your input

@dosubot dosubot bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 28, 2025
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cy948 - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Unresolved merge conflict markers present in code. (link)

General comments:

  • There are unresolved Git conflict markers in AuthSignInBox.tsx (<<<<<<< HEAD / >>>>>>>); please remove them and finalize the intended callbackUrl logic.
  • Enhance the fetcher in LobeNextAuthDbAdapter to check response.ok and throw or handle HTTP errors before parsing JSON to avoid unexpected failures.
  • Add request validation (e.g. with Zod) in the /api/auth/adapter route to enforce correct action names and payload shapes and prevent malformed requests.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- There are unresolved Git conflict markers in AuthSignInBox.tsx (<<<<<<< HEAD / >>>>>>>); please remove them and finalize the intended callbackUrl logic.
- Enhance the fetcher in LobeNextAuthDbAdapter to check response.ok and throw or handle HTTP errors before parsing JSON to avoid unexpected failures.
- Add request validation (e.g. with Zod) in the /api/auth/adapter route to enforce correct action names and payload shapes and prevent malformed requests.

## Individual Comments

### Comment 1
<location> `src/libs/next-auth/adapter/index.ts:42` </location>
<code_context>
+    throw new Error('LobeNextAuthDbAdapter: KEY_VAULTS_SECRET is not set in environment variables');
+  }
+
+  const fetcher = (action: string, data: any) => fetch(interactionUrl, {
+    method: 'POST',
+    headers: {
</code_context>

<issue_to_address>
No retry or error handling for network failures in fetcher.

Add try/catch and handle network errors, timeouts, and non-JSON responses to prevent unhandled promise rejections and improve error clarity.
</issue_to_address>

### Comment 2
<location> `src/libs/next-auth/adapter/index.ts:79` </location>
<code_context>
-        .delete(nextauthSessions)
-        .where(eq(nextauthSessions.sessionToken, sessionToken));
+      const result = await fetcher('deleteSession', sessionToken);
+      await postProcessor(result);
       return;
     },
</code_context>

<issue_to_address>
deleteSession and deleteUser do not return deleted objects as per Adapter contract.

The current implementation always returns undefined, which may break consumers relying on the deleted object. Please return the deleted object or null if not found, as required by the Adapter contract.
</issue_to_address>

### Comment 3
<location> `src/libs/next-auth/adapter/index.ts:145` </location>
<code_context>
-            eq(nextauthAccounts.providerAccountId, account.providerAccountId),
-          ),
-        );
+      const result = await fetcher('unlinkAccount', account);
+      await postProcessor(result);
+      return
</code_context>

<issue_to_address>
unlinkAccount does not return AdapterAccount as per Adapter contract.

Currently, unlinkAccount always returns undefined. To align with the Adapter contract and avoid issues for consumers expecting the deleted AdapterAccount, return the deleted account when available.
</issue_to_address>

### Comment 4
<location> `src/app/(backend)/api/auth/adapter/route.ts:93` </location>
<code_context>
+        }
+        return NextResponse.json({ success: true, data: result });
+    } catch (error) {
+        return NextResponse.json({ success: false, error }, { status: 400 });
+    }
+}
</code_context>

<issue_to_address>
Error responses may leak internal error objects.

Avoid returning raw error objects; instead, return sanitized error messages to prevent exposing sensitive information.
</issue_to_address>

### Comment 5
<location> `src/app/[variants]/(auth)/next-auth/signin/AuthSignInBox.tsx:78` </location>
<code_context>

   const searchParams = useSearchParams();

+<<<<<<< HEAD
   // Redirect back to the page url, fallback to '/' if failed
+=======
+  // Redirect back to the page url
+>>>>>>> ecf695d9b (:bug: fix: default callbackUrl)
   const callbackUrl = searchParams.get('callbackUrl') ?? '/';

</code_context>

<issue_to_address>
Unresolved merge conflict markers present in code.

Please resolve the merge conflict markers (<<<<<<<, =======, >>>>>>>) to prevent syntax errors before merging.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

throw new Error('LobeNextAuthDbAdapter: KEY_VAULTS_SECRET is not set in environment variables');
}

const fetcher = (action: string, data: any) => fetch(interactionUrl, {
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): No retry or error handling for network failures in fetcher.

Add try/catch and handle network errors, timeouts, and non-JSON responses to prevent unhandled promise rejections and improve error clarity.

.delete(nextauthSessions)
.where(eq(nextauthSessions.sessionToken, sessionToken));
const result = await fetcher('deleteSession', sessionToken);
await postProcessor(result);
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): deleteSession and deleteUser do not return deleted objects as per Adapter contract.

The current implementation always returns undefined, which may break consumers relying on the deleted object. Please return the deleted object or null if not found, as required by the Adapter contract.

eq(nextauthAccounts.providerAccountId, account.providerAccountId),
),
);
const result = await fetcher('unlinkAccount', account);
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): unlinkAccount does not return AdapterAccount as per Adapter contract.

Currently, unlinkAccount always returns undefined. To align with the Adapter contract and avoid issues for consumers expecting the deleted AdapterAccount, return the deleted account when available.

}
return NextResponse.json({ success: true, data: result });
} catch (error) {
return NextResponse.json({ success: false, error }, { status: 400 });
Copy link
Contributor

Choose a reason for hiding this comment

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

🚨 issue (security): Error responses may leak internal error objects.

Avoid returning raw error objects; instead, return sanitized error messages to prevent exposing sensitive information.

Comment on lines 78 to 82
<<<<<<< HEAD
// Redirect back to the page url, fallback to '/' if failed
=======
// Redirect back to the page url
>>>>>>> ecf695d9b (:bug: fix: default callbackUrl)
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Unresolved merge conflict markers present in code.

Please resolve the merge conflict markers (<<<<<<<, =======, >>>>>>>) to prevent syntax errors before merging.

Comment on lines 155 to 156
const data = await postProcessor(result);
return data;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const data = await postProcessor(result);
return data;
return await postProcessor(result);


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines 161 to 162
const session = await postProcessor(result);
return session;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const session = await postProcessor(result);
return session;
return await postProcessor(result);


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines 167 to 168
const data = await postProcessor(result);
return data;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const data = await postProcessor(result);
return data;
return await postProcessor(result);


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines 173 to 174
const data = await postProcessor(result);
return data;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const data = await postProcessor(result);
return data;
return await postProcessor(result);


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines +89 to +91
const adapterUser = mapLobeUserToAdapterUser(existingUser);
return adapterUser;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const adapterUser = mapLobeUserToAdapterUser(existingUser);
return adapterUser;
return mapLobeUserToAdapterUser(existingUser);


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Copy link

vercel bot commented Jul 29, 2025

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

Project Deployment Preview Comments Updated (UTC)
lobe-chat-database Ready Ready Preview Comment Aug 29, 2025 3:41pm

@cy948 cy948 force-pushed the refactor/next-auth-db branch from d3424a9 to 5ce892b Compare July 29, 2025 09:13
@cy948 cy948 force-pushed the refactor/next-auth-db branch from ac1ab0b to 8b51ea6 Compare August 7, 2025 05:08
@dosubot dosubot bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Aug 7, 2025
Copy link

codecov bot commented Aug 7, 2025

Codecov Report

❌ Patch coverage is 3.82979% with 226 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.95%. Comparing base (85f9ca5) to head (1a01cf0).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8188      +/-   ##
==========================================
- Coverage   84.04%   83.95%   -0.09%     
==========================================
  Files         870      869       -1     
  Lines       70571    70590      +19     
  Branches     4889     6261    +1372     
==========================================
- Hits        59309    59264      -45     
- Misses      11256    11320      +64     
  Partials        6        6              
Flag Coverage Δ
app 85.88% <3.00%> (-0.12%) ⬇️
database 96.26% <ø> (ø)
packages/electron-server-ipc 74.61% <ø> (ø)
packages/file-loaders 83.59% <ø> (ø)
packages/model-runtime 74.21% <ø> (+<0.01%) ⬆️
packages/prompts 100.00% <ø> (ø)
packages/utils 61.07% <100.00%> (ø)
packages/web-crawler 59.57% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
Store 68.86% <ø> (ø)
Services 61.95% <ø> (ø)
Server 63.36% <2.20%> (-3.00%) ⬇️
Libs 53.11% <0.00%> (+7.00%) ⬆️
Utils 70.63% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@arvinxx arvinxx changed the base branch from main-archived to main August 29, 2025 08:28
@cy948 cy948 force-pushed the refactor/next-auth-db branch from ef87b70 to 1d22501 Compare August 29, 2025 10:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size:XXL This PR changes 1000+ lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants