---
type: system
title: Authentication
description: The authentication system uses Better Auth to manage user and agent sessions, handle identity providers, and integrate with the oRPC server via middleware and route handlers.
tags: [authentication, better-auth, session, oRPC]
verified:
  - by: openwiki/0.7.2
    at: 2026-10-14T20:42:32.326Z
---

# Authentication System

## Overview

The authentication system is built using [Better Auth](https://better-auth.com) to provide secure session management, support for email/password authentication, and integration with the application's API routes.

## Configuration

The auth instance is created in `packages/auth/src/index.ts` by the `createAuth` function. It configures Better Auth with:

- **Database Adapter**: Uses Drizzle ORM with a PostgreSQL provider and the schema defined in `@os/db/schema/auth`.
- **Cookies**: Sets `httpOnly`, `sameSite: "none"`, and `secure: true` for enhanced security.
- **Providers**: Enables email and password authentication.
- **Security**: Requires a secret (`BETTER_AUTH_SECRET`) and sets trusted origins based on `CORS_ORIGIN`.

## Middleware

In the server entrypoint (`apps/server/src/index.ts`), the auth middleware is applied to all incoming requests except those under `/api/auth/**`. This middleware:

- Extracts session information from cookies.
- Masks email addresses in logs for privacy.
- Makes the session available to downstream handlers via the request context.

## Route Handling

Auth-specific routes (login, logout, session management, etc.) are handled by the Better Auth handler mounted at `/api/auth/*`. This allows the authentication endpoints to be publicly accessible while protecting other routes with the middleware.

## Session Type

The auth instance exports a `Session` type that represents the shape of session data, which can be used throughout the application for type-safe session access.

## Integration with oRPC

The auth middleware runs before oRPC route handlers, ensuring that the session is available in the context when processing RPC requests. This allows procedures to access user information and enforce authorization checks.