Expand description
§Alibi
Authentication for Rust, compatible with Better Auth’s TypeScript client.
§Quick Start
ⓘ
use alibi::{AuthConfig, AuthSchema, Alibi};
use alibi::plugins::EmailPasswordPlugin;
use alibi::seaorm::{Database, SeaOrmStore};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = AuthConfig::new("your-secret-key-that-is-at-least-32-chars");
let database = Database::connect("sqlite::memory:").await?;
let store = SeaOrmStore::<AppAuthSchema>::new(config.clone(), database);
let auth = Alibi::<AppAuthSchema>::new(config)
.store(store)
.plugin(EmailPasswordPlugin::new())
.build()
.await?;
Ok(())
}Modules§
- adapter_
record - Retained adapter output alongside immutable, typed storage authority.
- authenticated_
user - Authenticated identity without inventing an application-owned storage model.
- background_
tasks - Application observation of already running background work.
- config
- Configuration types beyond the root
AuthConfigentrypoint. - core_
paths - Well-known core route paths.
- Email provider interfaces and development helpers.
- endpoint
- Trusted endpoint calls keep logical input separate from an optional HTTP request.
- entity
- Entity traits for the Alibi framework.
- error
- Error types and result aliases for Alibi.
- field_
policy - Application and plugin field policies at the session input boundary.
- hooks
- Request-hook utilities shared across Alibi integrations.
- integrations
- Framework integrations.
- middleware
- Middleware traits and configuration types.
- openapi
- plugin
- Plugin authoring interfaces and shared runtime types.
- plugins
- Built-in plugins and their configuration.
- prelude
- Common traits and data types used by handlers, tests, hooks, and direct dispatch.
- schema
- Schema traits and derive macros for app-owned auth models.
- seaorm
SeaORMintegration re-exports, gated behind theseaormfeature.- session
- Session issuance and signed cookies for custom sign-in flows.
- sqlx
SQLxintegration re-exports, gated behind the defaultsqlxfeature or one of its engines,sqlx-sqliteandsqlx-postgres.- store
- Storage traits and cache adapters used by Alibi.
- telemetry
- Explicit application-owned telemetry. No endpoint, environment discovery or process fingerprinting is enabled by the library. Install a sink on the auth builder to opt in; the application owns its transport and retention policy.
- types
- user_
validation - Application identity policy at the endpoint’s actual admission boundary.
- utils
- Shared utility modules for
alibi-core. - uuid
- Generate and parse universally unique identifiers (UUIDs).
- verification
- Initialized verification policy, raw snapshots and adapter publication phases.
- wire
- Wire-facing response view models.
Macros§
- impl_
auth_ plugin - Generates the
AuthPluginimpl for a plugin with static route dispatch.
Structs§
- Account
Config - Account-level configuration: linking, token encryption, sign-in behavior.
- Account
Linking Config - Settings that control how OAuth accounts are linked to existing users.
- Account
View - Public account response shape.
- Adapter
Output - Declared adapter values retain JavaScript undefined presence for trusted observers. Serialization omits undefined values, as public JSON does.
- Adapter
Record - One actual adapter result. Output transforms may change additional values or omit them, while identity, ownership and credential accessors retain the physical model. Public response filtering is a separate operation.
- Advanced
Config - Advanced configuration options (mirrors TS
advancedblock). - Advanced
Database Config - Database-related advanced options.
- Alibi
- ApiKey
- API key response shape.
- ApiKey
Starting Characters - UTF-16 code units selected from the beginning of a generated API key.
- ApiKey
View - Public API key response shape.
- Auth
Builder - Initial builder for configuring
Alibi. - Auth
Config - Main configuration for
Alibi - Auth
Context - Context passed to plugin methods.
- Auth
Init Context - Initialization context passed to plugin setup.
- Auth
Request - Authentication request wrapper
- Auth
Response - Authentication response wrapper
- Auth
Route - Route definition for plugins.
- Body
Limit Config - Configuration for body size limit middleware.
- Body
Limit Middleware - Body size limit middleware.
- Cache
Rate Limit Storage - Shared fixed-window counter backed by the application’s existing cache. Every attempt increments, including blocked attempts; retries report the full window.
- Cache
Version Context - Immutable inputs to the cache version policy.
- Callback
Context - Owned native context for application callbacks, including background delivery. The schema accessor exposes the live instance and its hook-aware store; the request and hook data retain the actual transport and admitted endpoint input.
- Code
Message Response - Middleware error response
{ code: String, message: String }. - Console
Email Provider - Development email provider that logs emails to stderr.
- Context
Extensions - Typed settings and callbacks published during plugin initialization.
- Cookie
Attributes - Overridable cookie attributes.
- Cookie
Cache Config - Configuration for cookie-based session caching.
- Cookie
Override - Per-cookie override entry.
- Cors
Config - Configuration for CORS middleware.
- Cors
Middleware - CORS middleware.
- Create
Account - Account creation data
- Create
ApiKey - API key creation data.
- Create
Device Code - Input for creating a new device authorization code.
- Create
Invitation - Invitation creation data
- Create
Jwk - Create
Member - Member creation data
- Create
Organization - Organization creation data
- Create
Passkey - Input for creating a new passkey.
- Create
Session - Session creation data
- Create
Team - Create
TwoFactor - Two-factor authentication creation data.
- Create
User - User creation data
- Create
Verification - Verification token creation data
- Create
Wallet Address - Cross
SubDomain Config - Configuration for sharing cookies across sub-domains.
- Csrf
Config - Configuration for Better Auth request-origin and CSRF protection.
- Csrf
Middleware - Better Auth request protection middleware.
- Device
Code - Device authorization code storage shape.
- Endpoint
Rate Limit - Rate limit parameters for a single endpoint.
- Error
Code Message Response - Error body
{ code: String, message: String }matching the TS better-auth error response shape. - Error
Message Response - Error body
{ message: String }. - Headers
- Response headers preserving repeated header names such as
Set-Cookie. - Health
Check Response - Health-check response for
/health. - Invitation
- Organization invitation
- Invitation
View - Public invitation response shape.
- IpAddress
Config - IP-address extraction configuration.
- Jwk
- Private keyring persistence. Public JWKS responses must select public material explicitly.
- JwtConfig
- JWT configuration
- List
Users Params - Parameters for listing users through the configured adapter.
- Managed
Secrets - Versioned persistence keys. New ciphertext uses the current version; retained versions read existing ciphertext without rewriting it. Removing a retained version retires it immediately. Signed cookies use only the current key and are invalidated when that key changes.
- Member
- Organization member
- Member
User View - Minimal user info for member-related API responses.
- Memory
Cache Adapter - In-memory cache adapter for testing and development
- Memory
Rate Limit Storage - Bounded rolling in-memory storage. Share an
Arcbetween auth instances when they must consume the same client/path quotas. - OkResponse
- Generic
{ ok: bool }response used by/okand/errorendpoints. - Open
ApiBuilder - Embedded builder, also used by the HTTP
OpenAPIplugin. - Open
ApiEndpoint - Rich metadata for one route; dispatch still comes exclusively from
AuthRoute. - Open
ApiField - A model field’s wire schema and input/output policy.
- Open
ApiInfo - Open
ApiModel - An ordered model definition. Repeated registrations merge fields by wire name.
- Open
ApiOperation - Open
ApiRegistry - Immutable snapshot of the routes and model projections registered on one auth instance.
- Open
ApiResponse - Open
ApiSpec - Organization
- Organization entity - matches
OpenAPIschema - Organization
View - Public organization response shape.
- Passkey
- Passkey response shape.
- Passkey
View - Public passkey response shape.
- Password
Config - Password strength rules. Length limits belong to the email/password plugin
(
password_min_length,password_max_length). Built-in hashing uses pinned scrypt parameters. - Password
Hash Context - Logical identity of an actual endpoint call, independently of whether it came from HTTP. Trusted server APIs have a path and may have no request.
- Plugin
Open ApiMetadata - A plugin’s endpoint annotations and schema additions.
- Plugin
Rate Limit - Plugin rules are evaluated in installation order, before application overrides.
- Rate
Limit Config - Configuration for the rate limiting middleware.
- Rate
Limit Error Response - Rate-limit error response with
retryAfterfield. - Rate
Limit Middleware - Request policies with atomic rolling or fixed-window storage.
- Request
Hook Context - Request-derived data available to middleware, stores, and other hooks during request handling.
- Request
Meta - Metadata extracted from an incoming request for session creation.
- Scrypt
Hasher - The pinned Better Auth password format: hexadecimal salt and scrypt key.
- Session
Config - Session-specific configuration
- Session
Manager - Session manager handles session creation, validation, and cleanup
- Session
View - Public session response shape.
- Status
Message Response { status: bool, message: String }response (e.g. change-email).- Status
Response - Generic
{ status: bool }response. - Success
Message Response { success: bool, message: String }response (e.g. delete-user).- Success
Response - Generic
{ success: bool }response (e.g. sign-out). - Team
- A team within one organization. The durable capacity counter is private to storage.
- Team
Member - A user membership in a team. The uniqueness key is never returned on the wire.
- TwoFactor
- Two-factor authentication response shape.
- Update
Account - Account update data (for refreshing OAuth tokens)
- Update
ApiKey - API key update data.
- Update
Device Code - Input for updating an existing device authorization code.
- Update
Organization - Organization update data
- Update
Passkey - Input for updating a passkey.
- Update
Team - Update
TwoFactor - Mutate one exact factor generation without resetting its lockout state.
- Update
User - User update data
- Update
User Request - Update
User Response - Update
Verification - User
Config - User
View - Public user response shape.
- Validation
Error Response - Validation error response
{ code, message, errors }. - Verification
Email Override Handle - Verification
View - Public verification response shape.
- Wallet
Address - An address linked to a SIWE identity on one chain.
Enums§
- ApiKey
Start Text - How API-key starting characters are persisted.
- Auth
Error - Authentication framework error types.
- Authenticated
User - The identity established by a cache-aware session read.
- Awaited
Notification Error Policy - Response policy for awaited lifecycle notifications. Explicit verification delivery retains its direct error contract; deferred work logs its errors.
- Before
Request Action - Action returned by
AuthPlugin::before_request. - Cache
Version Source - Which actual snapshot a version callback receives.
- Consume
ApiKey Result - Outcome of an atomic API key usage consumption.
- Cookie
Cache Strategy - Strategy for signing / encrypting the cookie cache.
- Cookie
Cache Version - Immutable configured cache version; empty literals use the source default.
- Cookie
Refresh Cache - Stateless cache renewal policy, corresponding to
cookieCache.refreshCache. - Database
Error - Http
Endpoint Response - Endpoint output distinguishing a logical value from a native raw response.
Raw responses bypass completed endpoint hooks, while HTTP response hooks
still observe them, matching a Source endpoint returning a
Response. - Http
Method - HTTP method enumeration
- Http
Request Action - Physical HTTP hook control flow, before route selection and endpoint hooks.
- Invitation
Status - Invitation status
- OAuth
State Strategy - Strategy for persisting OAuth state between the sign-in and callback steps.
- Rate
Limit Decision - Rate
Limit Rule - Same
Site - User
Filter Value - String operands for admin user-list filtering.
Traits§
- Auth
Account - Trait representing an account entity (OAuth provider linking).
- Auth
ApiKey - Trait representing an API key entity.
- Auth
Invitation - Trait representing an invitation entity.
- Auth
Member - Trait representing an organization member entity.
- Auth
Organization - Trait representing an organization entity.
- Auth
Passkey - Trait representing a passkey entity.
- Auth
Plugin - Plugin trait that all authentication plugins must implement.
- Auth
Schema - App-owned auth schema declaration.
- Auth
Session - Trait representing a session entity.
- Auth
Store - Auth
Transaction - Auth
TwoFactor - Trait representing a two-factor authentication entity.
- Auth
User - Trait representing a user entity.
- Auth
Verification - Trait representing a verification token entity.
- Background
Task Handler - Application integration for deferred operations, such as platform waitUntil.
- Cache
Adapter - Cache adapter trait for session caching
- Cookie
Cache Version Resolver - Application-owned asynchronous cache version policy.
- Email
Provider - Trait for sending emails. Implement this to integrate with your
email service (SMTP,
SendGrid, SES, etc.). - Middleware
- Middleware trait for request/response processing.
- Password
Hash Hook - An initialized policy applied at actual password hashing, after endpoint admission and before the selected original hasher. Verification is unchanged.
- Password
Hasher - Custom password hasher trait for pluggable password hashing strategies.
- Rate
Limit Resolver - Application-owned request policy; returning
Nonedisables this request’s limit. - Rate
Limit Storage - A rate-limit backend must atomically decide and consume before returning.
- Verification
Email Override - A plugin override for delivery of the core email-verification challenge.
- Wallet
Address Store
Functions§
- extract_
origin - Extract the origin (scheme + host + port) from a URL string.
- hash_
password - Hash
passwordusing the customhasher(if provided) or the default scrypt algorithm and NFKC normalization. - start_
background_ task - Start owned work immediately and retain the initiating request/tracing context. The returned observation may be dropped without cancelling pending work.
- transaction
- Errors
- validate_
request_ body - Validate a request body, returning a parsed + validated value or an error response.
- validation_
error_ response - Convert
validator::ValidationErrorsinto a standardized error response body. - verify_
password - Verify
passwordagainsthashusing the customhasher(if provided) or the default scrypt algorithm. ReturnsOk(())on match, orErr(AuthError::InvalidCredentials)on mismatch. - with_
request_ hook_ context - Run a future with request context available to downstream integrations.
- with_
request_ hook_ context_ value - Run a future with an explicit request hook context.
Type Aliases§
- Auth
Result - Background
Task Completion - Completion of an already started owned task. Dropping this observation does not cancel its underlying work. Applications may retain and await it to keep their executor alive until work completes.
- Organization
Permissions - Preserve insertion order because upstream stores permission JSON as a string.