Skip to content

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

Merged
cruzdanilo merged 4 commits intomainfrom
better-auth
May 7, 2026
Merged

🛂 server: add better auth is an authentication framework#881
cruzdanilo merged 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: f724117

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

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 66.66667% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.30%. Comparing base (8c2785c) to head (4494826).
✅ 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 61.53% 9 Missing and 1 partial ⚠️
server/api/index.ts 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #881      +/-   ##
==========================================
- Coverage   72.35%   72.30%   -0.05%     
==========================================
  Files         231      233       +2     
  Lines        8884     8966      +82     
  Branches     2874     2885      +11     
==========================================
+ Hits         6428     6483      +55     
- Misses       2199     2225      +26     
- Partials      257      258       +1     
Flag Coverage Δ
e2e 72.27% <62.12%> (+2.76%) ⬆️

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.

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

@chatgpt-codex-connector
Copy link
Copy Markdown

💡 Codex Review

exa/server/utils/auth.ts

Lines 40 to 44 in 1c80b01

return await verifyMessage({
address: parsedAddress.output,
message,
signature: parsedSignature.output,
});

P1 Badge Require SIWE nonce and domain validation

When verifyMessage only calls viem's generic signature check, any message previously signed by the wallet can be replayed after an attacker requests a fresh nonce for that wallet, because the callback never verifies that the signed SIWE payload contains Better Auth's stored nonce, expected domain/audience, or even the requested chain. In the SIWE plugin path, this callback is the place where those SIWE fields must be enforced; otherwise possession of an old signature is enough to create a new session for that address.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 37b90c6d2d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts Outdated
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d85a723a84

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts Outdated
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 992a30b8a5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts Outdated
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00179866bf

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts
@nfmelendez nfmelendez force-pushed the better-auth branch 2 times, most recently from d0de4ff to bb348e9 Compare May 7, 2026 14:52
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb348e933a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6cf1d366ba

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9e6a5b8338

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread server/utils/auth.ts
@cruzdanilo cruzdanilo merged commit f724117 into main May 7, 2026
3 of 4 checks passed
@cruzdanilo cruzdanilo deleted the better-auth branch May 7, 2026 20:28
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