Skip to content

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

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

🛂 server: add better auth is an authentication framework#881
nfmelendez wants to merge 3 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: 128b4ec

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

✅ All tests passed.

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

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

@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
Comment on lines +12 to +17
if (!credentialId) {
const session = await betterAuth.api.getSession({ headers: c.req.raw.headers });
if (session) {
await next();
return;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: The auth middleware allows users authenticated via betterAuth to proceed without setting credentialId in validated data, which downstream handlers expect.
Severity: MEDIUM

Suggested Fix

Modify the middleware to ensure credentialId is set from the betterAuth session before calling next(). Alternatively, use separate routing to prevent betterAuth-authenticated users from reaching handlers that require credentialId.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.

Location: server/middleware/auth.ts#L12-L17

Potential issue: In the `auth` middleware, if a user authenticates via the
`betterAuth.api.getSession()` path, the middleware calls `next()` without adding the
`credentialId` to the validated cookie data. Downstream route handlers that use this
middleware expect `credentialId` to be present and attempt to destructure it from
`c.req.valid("cookie")`. When it's missing, `credentialId` will be `undefined`, leading
to incorrect behavior or potential cascading errors in at least six route files that
depend on it.

Did we get this right? 👍 / 👎 to inform future reviews.

Copy link
Copy Markdown

@devin-ai-integration devin-ai-integration bot left a comment

Choose a reason for hiding this comment

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

Devin Review found 2 potential issues.

View 4 additional findings in Devin Review.

Open in Devin Review

Comment on lines +12 to +17
if (!credentialId) {
const session = await betterAuth.api.getSession({ headers: c.req.raw.headers });
if (session) {
await next();
return;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Auth middleware skips setting credentialId for better-auth sessions, breaking all downstream handlers

When a user authenticates via a better-auth session (no legacy credential_id cookie), the middleware at lines 14-16 calls next() without calling c.req.addValidatedData("cookie", { credentialId }). Every downstream handler guarded by auth() immediately destructures credentialId from c.req.valid("cookie") — e.g. server/api/card.ts:199, server/api/ramp.ts:45, server/api/activity.ts:87, server/api/kyc.ts:51, server/api/pax.ts:30, server/api/passkey.ts:30 — and uses it for database lookups like where: eq(credentials.id, credentialId). With credentialId being undefined, these queries match nothing, and the handlers return 500 ("no credential") or 400 errors. The authentication appears to succeed but every protected operation silently fails.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

.route("/pax", pax)
.route("/ramp", ramp);
.route("/ramp", ramp)
.on(["POST", "GET"], "/auth/*", (c) => auth.handler(c.req.raw));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚩 Wildcard /auth/* route could shadow existing auth sub-routes

The new .on(["POST", "GET"], "/auth/*", (c) => auth.handler(c.req.raw)) at server/api/index.ts:31 is registered after .route("/auth/registration", registration) and .route("/auth/authentication", authentication) at lines 23-24. In Hono's trie-based router, more specific paths typically take precedence over wildcards, so existing registration/authentication endpoints should still work. However, if better-auth registers any routes that overlap with sub-paths of /auth/registration/* or /auth/authentication/*, there could be unexpected behavior. Additionally, all HTTP methods other than POST/GET to /auth/* sub-paths will not reach better-auth (only POST and GET are handled). This is probably fine for better-auth's API surface but worth confirming.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide 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: 128b4ece93

ℹ️ 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 on lines +14 to +16
if (session) {
await next();
return;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Block fallback auth when no credential id is available

When credential_id is missing, this branch now accepts any Better Auth session and calls next() without adding validated cookie data, but downstream handlers still assume c.req.valid("cookie").credentialId exists (for example, server/api/pax.ts and other auth()-protected routes). Requests authenticated only via the new SIWE session cookie will therefore hit protected endpoints with no credential id and fail as 500/"no credential" instead of a clean 401 or mapped identity, which breaks the newly introduced auth path for existing API routes.

Useful? React with 👍 / 👎.

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