Skip to content

🛂 server: add better auth is an authentication framework#881

Open
nfmelendez wants to merge 4 commits intomainfrom
better-auth
Open

🛂 server: add better auth is an authentication framework#881
nfmelendez wants to merge 4 commits intomainfrom
better-auth

Conversation

@nfmelendez
Copy link
Copy Markdown
Contributor

@nfmelendez nfmelendez commented Mar 12, 2026

Summary by CodeRabbit

  • New Features

    • SIWE wallet sign-in and organization management with roles and admin/member controls
    • New auth endpoints and more resilient session handling (cookie + session fallback)
  • Documentation

    • Comprehensive SIWE + organization setup guide with end-to-end examples
    • Docs sidebar reordered to surface core authentication docs first
  • Chores

    • Backend auth database and adapter provisioning; changeset entries added
  • Security

    • OpenAPI now documents cookie-based SIWE auth scheme

Open with Devin

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 12, 2026

🦋 Changeset detected

Latest commit: 80fc2a3

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@exactly/server Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a robust authentication and authorization system by integrating the 'better-auth' framework. It enables advanced features such as Sign-In with Ethereum (SIWE) and comprehensive organization management, allowing users to create organizations and manage members with distinct roles. The changes span across database schema, API endpoints, middleware, and user-facing documentation, laying the groundwork for secure and scalable user and organization interactions.

Highlights

  • Core Authentication Framework Integration: Integrated the 'better-auth' library to establish a comprehensive authentication and authorization system, supporting SIWE (Sign-In with Ethereum) and organization management.
  • Database Schema Expansion: Introduced new database tables and relations for users, sessions, authenticators, verifications, wallet addresses, organizations, members, and invitations to support the new authentication framework.
  • API and Middleware Updates: Added new API routes for authentication (/api/auth/*) and updated the existing authentication middleware to leverage the new 'better-auth' session management.
  • Documentation for New Features: Provided new documentation covering SIWE authentication flows and the process for creating and managing organizations, including code examples.
Changelog
  • .changeset/cool-snakes-reply.md
    • Added a changeset entry for setting up better auth database tables.
  • .changeset/pretty-chicken-hang.md
    • Added a changeset entry for installing better auth.
  • .changeset/rare-pears-sort.md
    • Added a changeset entry for setting up better auth.
  • docs/astro.config.ts
    • Updated the Astro configuration to include new documentation pages for 'Docs' and 'Organizations and authentication' in the sidebar.
  • docs/src/content/docs/organization-authentication.md
    • Added a new documentation page detailing SIWE authentication and organization creation, including code examples.
  • server/database/index.ts
    • Imported drizzleAdapter from better-auth.
    • Exported a new authAdapter instance, mapping better-auth schema entities to existing Drizzle ORM tables.
  • server/database/schema.ts
    • Imported boolean and timestamp types for Drizzle ORM.
    • Added new pgTable definitions for users, sessions, authenticators, verifications, walletAddresses, organizations, members, and invitations.
    • Defined relations between the newly added tables (e.g., usersRelations, sessionsRelations).
  • server/index.ts
    • Imported the new auth utility.
    • Added a new Hono route handler for /api/auth/* to delegate authentication requests to the better-auth framework.
  • server/middleware/auth.ts
    • Imported betterAuth utility.
    • Modified the authentication middleware to check for better-auth sessions if the traditional credential_id cookie is not found, allowing for dual authentication mechanisms.
  • server/package.json
    • Added better-auth as a production dependency.
    • Added better-sqlite3 as a development dependency.
  • server/script/openapi.ts
    • Imported zeroHash from viem.
    • Updated the AUTH_SECRET environment variable to zeroHash for OpenAPI generation.
    • Added a new siweAuth security scheme to the OpenAPI specifications, referencing the __Secure-better-auth.session_token cookie.
  • server/utils/auth.ts
    • Added a new file to configure and export the betterAuth instance.
    • Configured betterAuth with drizzleAdapter, base URL, trusted origins, and SIWE and organization plugins.
    • Implemented SIWE nonce generation and message verification logic using viem.
    • Defined access control roles (admin, owner, member) for organization management.
Activity
  • No specific pull request activity (comments, reviews, etc.) was provided in the context.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 12, 2026

Warning

Rate limit exceeded

@nfmelendez has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 59 minutes and 45 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 59 minutes and 45 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6ea71416-5606-40fc-8824-08d44b0473f0

📥 Commits

Reviewing files that changed from the base of the PR and between 811d11f and 80fc2a3.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (15)
  • .changeset/brisk-otter-glides.md
  • .changeset/pretty-chicken-hang.md
  • .changeset/rare-pears-sort.md
  • docs/astro.config.ts
  • docs/src/content/docs/organization-authentication.md
  • pnpm-workspace.yaml
  • server/api/index.ts
  • server/database/index.ts
  • server/database/schema.ts
  • server/index.ts
  • server/middleware/org.ts
  • server/package.json
  • server/script/openapi.ts
  • server/test/middleware/org.test.ts
  • server/utils/auth.ts

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds BetterAuth-based SIWE authentication and organization support: new Drizzle Postgres schema and relations, exported database and authAdapter, BetterAuth configuration and routes, middleware session fallback, OpenAPI security entry, docs, and three changeset files.

Changes

Cohort / File(s) Summary
Changesets
.changeset/cool-snakes-reply.md, .changeset/pretty-chicken-hang.md, .changeset/rare-pears-sort.md
Three patch changeset files added for @exactly/server noting improved auth/database setup.
Documentation
docs/astro.config.ts, docs/src/content/docs/organization-authentication.md
Prepends a "Docs" group to the OpenAPI sidebar and adds a detailed SIWE/organization authentication guide with examples.
Database schema & adapter
server/database/schema.ts, server/database/index.ts
Adds comprehensive Drizzle pg tables (users, sessions, authenticators, verifications, wallet_addresses, organizations, members, invitations), relations, indexes; exports database (default) and new authAdapter.
Auth implementation & middleware
server/utils/auth.ts, server/middleware/auth.ts, server/index.ts, server/package.json
Introduces BetterAuth configuration (SIWE + organization plugins) exported as default, middleware fallback to session via BetterAuth when credential cookie missing, registers /api/auth/* route, and adds better-auth + better-sqlite3 deps.
OpenAPI script
server/script/openapi.ts
Imports zeroHash from viem, uses it for AUTH_SECRET, and adds a cookie-based siweAuth security scheme (__Secure-better-auth.session_token) to generated OpenAPI components.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client (Browser)
    participant Auth as BetterAuth Handler
    participant Server as App Server
    participant DB as Database
    participant Sentry as Sentry

    Client->>Auth: GET /api/auth/nonce
    Auth->>DB: store nonce
    DB-->>Auth: nonce
    Auth-->>Client: nonce

    Client->>Client: sign SIWE message
    Client->>Auth: POST /api/auth/verify (signed message)
    Auth->>Auth: parse & verify chainId/address/signature
    alt valid
        Auth->>DB: create/update user & session
        DB-->>Auth: session
        Auth->>Server: set __Secure-better-auth.session_token
        Server-->>Client: success response
    else invalid
        Auth->>Sentry: capture verification error
        Sentry-->>Auth: ack
        Auth-->>Client: unauthorized
    end

    Client->>Server: POST /api/auth/create-organization (with session)
    Server->>DB: create organization & member
    DB-->>Server: organization created
    Server-->>Client: organization id/details
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • ⬆️ major upgrade #631 — Modifies server database/schema and server/package.json; closely related to the schema and auth dependency changes in this PR.

Suggested reviewers

  • cruzdanilo
  • dieguezguille
  • franm91
🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title attempts to describe adding Better Auth as an authentication framework, which aligns with the main changes (comprehensive authentication setup with Better Auth, database schema, and SIWE integration). However, the phrasing is awkward and partially unclear due to 'is an authentication framework' being imprecise description rather than action-focused language.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch better-auth

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@cruzdanilo cruzdanilo changed the title add better auth is an authentication framework 🛂 server: add better auth is an authentication framework Mar 12, 2026
gemini-code-assist[bot]

This comment was marked as resolved.

@sentry
Copy link
Copy Markdown

sentry bot commented Mar 12, 2026

Codecov Report

❌ Patch coverage is 57.69231% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.65%. Comparing base (dba36d8) to head (80fc2a3).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
server/database/schema.ts 65.62% 11 Missing ⚠️
server/utils/auth.ts 16.66% 10 Missing ⚠️
server/api/index.ts 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #881      +/-   ##
==========================================
- Coverage   71.74%   71.65%   -0.09%     
==========================================
  Files         229      231       +2     
  Lines        8292     8344      +52     
  Branches     2669     2673       +4     
==========================================
+ Hits         5949     5979      +30     
- Misses       2113     2135      +22     
  Partials      230      230              
Flag Coverage Δ
e2e 71.65% <57.69%> (-0.09%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

@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: 12


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ac66a631-8798-4e64-80e3-76561a0be138

📥 Commits

Reviewing files that changed from the base of the PR and between 641a8df and 31ba9a9.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • .changeset/cool-snakes-reply.md
  • .changeset/pretty-chicken-hang.md
  • .changeset/rare-pears-sort.md
  • docs/astro.config.ts
  • docs/src/content/docs/organization-authentication.md
  • server/database/index.ts
  • server/database/schema.ts
  • server/index.ts
  • server/middleware/auth.ts
  • server/package.json
  • server/script/openapi.ts
  • server/utils/auth.ts

Comment thread docs/src/content/docs/organization-authentication.md
Comment thread docs/src/content/docs/organization-authentication.md
Comment thread docs/src/content/docs/organization-authentication.md
Comment thread server/database/index.ts
Comment thread server/database/schema.ts
Comment thread server/database/schema.ts
Comment thread server/database/schema.ts
Comment thread server/database/schema.ts
Comment thread server/middleware/auth.ts Outdated
Comment thread server/package.json Outdated
@nfmelendez nfmelendez force-pushed the better-auth branch 2 times, most recently from c2defde to c93fb20 Compare March 12, 2026 17:33
coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@nfmelendez nfmelendez force-pushed the better-auth branch 2 times, most recently from 6d12264 to 811d11f Compare March 12, 2026 18:49
Copy link
Copy Markdown

@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.

♻️ Duplicate comments (1)
server/middleware/auth.ts (1)

10-19: ⚠️ Potential issue | 🔴 Critical

Type signature doesn't match runtime behavior—when BetterAuth session is used, credentialId is undefined, not the string promised by the middleware type.

The middleware declares { out: { cookie: { credentialId: string } } }, but the BetterAuth fallback path (lines 14–17) calls next() without setting credentialId. All nine endpoints using auth() destructure { credentialId } and will receive undefined when a BetterAuth session is used.

Per the design intent (noted in prior review), this fallback is for endpoints that don't require credentialId. However, every current endpoint using auth() does require it. Either:

  1. Make the type accurate: { credentialId?: string } and add conditional logic in endpoints to handle both auth methods
  2. Separate concerns: create distinct middleware for credential-based vs session-based authentication
  3. Confirm whether the BetterAuth path is intended to be unreachable for these endpoints

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8c01d4f7-1f82-4e51-b6b8-fe3ea4aeb76a

📥 Commits

Reviewing files that changed from the base of the PR and between c93fb20 and 811d11f.

📒 Files selected for processing (8)
  • .changeset/rare-pears-sort.md
  • docs/astro.config.ts
  • docs/src/content/docs/organization-authentication.md
  • server/database/index.ts
  • server/index.ts
  • server/middleware/auth.ts
  • server/script/openapi.ts
  • server/utils/auth.ts

coderabbitai[bot]

This comment was marked as resolved.

@nfmelendez nfmelendez force-pushed the better-auth branch 2 times, most recently from 72065d0 to 128b4ec Compare March 13, 2026 14:27
@cruzdanilo cruzdanilo marked this pull request as ready for review March 25, 2026 17:12
@cruzdanilo cruzdanilo self-requested a review as a code owner March 25, 2026 17:12
sentry[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

sentry[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

sentry[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

sentry[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@nfmelendez
Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 15, 2026

✅ 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.

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