Skip to main content

Crate alibi

Crate alibi 

Source
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 AuthConfig entrypoint.
core_paths
Well-known core route paths.
email
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
SeaORM integration re-exports, gated behind the seaorm feature.
session
Session issuance and signed cookies for custom sign-in flows.
sqlx
SQLx integration re-exports, gated behind the default sqlx feature or one of its engines, sqlx-sqlite and sqlx-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 AuthPlugin impl for a plugin with static route dispatch.

Structs§

AccountConfig
Account-level configuration: linking, token encryption, sign-in behavior.
AccountLinkingConfig
Settings that control how OAuth accounts are linked to existing users.
AccountView
Public account response shape.
AdapterOutput
Declared adapter values retain JavaScript undefined presence for trusted observers. Serialization omits undefined values, as public JSON does.
AdapterRecord
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.
AdvancedConfig
Advanced configuration options (mirrors TS advanced block).
AdvancedDatabaseConfig
Database-related advanced options.
Alibi
ApiKey
API key response shape.
ApiKeyStartingCharacters
UTF-16 code units selected from the beginning of a generated API key.
ApiKeyView
Public API key response shape.
AuthBuilder
Initial builder for configuring Alibi.
AuthConfig
Main configuration for Alibi
AuthContext
Context passed to plugin methods.
AuthInitContext
Initialization context passed to plugin setup.
AuthRequest
Authentication request wrapper
AuthResponse
Authentication response wrapper
AuthRoute
Route definition for plugins.
BodyLimitConfig
Configuration for body size limit middleware.
BodyLimitMiddleware
Body size limit middleware.
CacheRateLimitStorage
Shared fixed-window counter backed by the application’s existing cache. Every attempt increments, including blocked attempts; retries report the full window.
CacheVersionContext
Immutable inputs to the cache version policy.
CallbackContext
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.
CodeMessageResponse
Middleware error response { code: String, message: String }.
ConsoleEmailProvider
Development email provider that logs emails to stderr.
ContextExtensions
Typed settings and callbacks published during plugin initialization.
CookieAttributes
Overridable cookie attributes.
CookieCacheConfig
Configuration for cookie-based session caching.
CookieOverride
Per-cookie override entry.
CorsConfig
Configuration for CORS middleware.
CorsMiddleware
CORS middleware.
CreateAccount
Account creation data
CreateApiKey
API key creation data.
CreateDeviceCode
Input for creating a new device authorization code.
CreateInvitation
Invitation creation data
CreateJwk
CreateMember
Member creation data
CreateOrganization
Organization creation data
CreatePasskey
Input for creating a new passkey.
CreateSession
Session creation data
CreateTeam
CreateTwoFactor
Two-factor authentication creation data.
CreateUser
User creation data
CreateVerification
Verification token creation data
CreateWalletAddress
CrossSubDomainConfig
Configuration for sharing cookies across sub-domains.
CsrfConfig
Configuration for Better Auth request-origin and CSRF protection.
CsrfMiddleware
Better Auth request protection middleware.
DeviceCode
Device authorization code storage shape.
EndpointRateLimit
Rate limit parameters for a single endpoint.
ErrorCodeMessageResponse
Error body { code: String, message: String } matching the TS better-auth error response shape.
ErrorMessageResponse
Error body { message: String }.
Headers
Response headers preserving repeated header names such as Set-Cookie.
HealthCheckResponse
Health-check response for /health.
Invitation
Organization invitation
InvitationView
Public invitation response shape.
IpAddressConfig
IP-address extraction configuration.
Jwk
Private keyring persistence. Public JWKS responses must select public material explicitly.
JwtConfig
JWT configuration
ListUsersParams
Parameters for listing users through the configured adapter.
ManagedSecrets
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
MemberUserView
Minimal user info for member-related API responses.
MemoryCacheAdapter
In-memory cache adapter for testing and development
MemoryRateLimitStorage
Bounded rolling in-memory storage. Share an Arc between auth instances when they must consume the same client/path quotas.
OkResponse
Generic { ok: bool } response used by /ok and /error endpoints.
OpenApiBuilder
Embedded builder, also used by the HTTP OpenAPI plugin.
OpenApiEndpoint
Rich metadata for one route; dispatch still comes exclusively from AuthRoute.
OpenApiField
A model field’s wire schema and input/output policy.
OpenApiInfo
OpenApiModel
An ordered model definition. Repeated registrations merge fields by wire name.
OpenApiOperation
OpenApiRegistry
Immutable snapshot of the routes and model projections registered on one auth instance.
OpenApiResponse
OpenApiSpec
Organization
Organization entity - matches OpenAPI schema
OrganizationView
Public organization response shape.
Passkey
Passkey response shape.
PasskeyView
Public passkey response shape.
PasswordConfig
Password strength rules. Length limits belong to the email/password plugin (password_min_length, password_max_length). Built-in hashing uses pinned scrypt parameters.
PasswordHashContext
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.
PluginOpenApiMetadata
A plugin’s endpoint annotations and schema additions.
PluginRateLimit
Plugin rules are evaluated in installation order, before application overrides.
RateLimitConfig
Configuration for the rate limiting middleware.
RateLimitErrorResponse
Rate-limit error response with retryAfter field.
RateLimitMiddleware
Request policies with atomic rolling or fixed-window storage.
RequestHookContext
Request-derived data available to middleware, stores, and other hooks during request handling.
RequestMeta
Metadata extracted from an incoming request for session creation.
ScryptHasher
The pinned Better Auth password format: hexadecimal salt and scrypt key.
SessionConfig
Session-specific configuration
SessionManager
Session manager handles session creation, validation, and cleanup
SessionView
Public session response shape.
StatusMessageResponse
{ status: bool, message: String } response (e.g. change-email).
StatusResponse
Generic { status: bool } response.
SuccessMessageResponse
{ success: bool, message: String } response (e.g. delete-user).
SuccessResponse
Generic { success: bool } response (e.g. sign-out).
Team
A team within one organization. The durable capacity counter is private to storage.
TeamMember
A user membership in a team. The uniqueness key is never returned on the wire.
TwoFactor
Two-factor authentication response shape.
UpdateAccount
Account update data (for refreshing OAuth tokens)
UpdateApiKey
API key update data.
UpdateDeviceCode
Input for updating an existing device authorization code.
UpdateOrganization
Organization update data
UpdatePasskey
Input for updating a passkey.
UpdateTeam
UpdateTwoFactor
Mutate one exact factor generation without resetting its lockout state.
UpdateUser
User update data
UpdateUserRequest
UpdateUserResponse
UpdateVerification
UserConfig
UserView
Public user response shape.
ValidationErrorResponse
Validation error response { code, message, errors }.
VerificationEmailOverrideHandle
VerificationView
Public verification response shape.
WalletAddress
An address linked to a SIWE identity on one chain.

Enums§

ApiKeyStartText
How API-key starting characters are persisted.
AuthError
Authentication framework error types.
AuthenticatedUser
The identity established by a cache-aware session read.
AwaitedNotificationErrorPolicy
Response policy for awaited lifecycle notifications. Explicit verification delivery retains its direct error contract; deferred work logs its errors.
BeforeRequestAction
Action returned by AuthPlugin::before_request.
CacheVersionSource
Which actual snapshot a version callback receives.
ConsumeApiKeyResult
Outcome of an atomic API key usage consumption.
CookieCacheStrategy
Strategy for signing / encrypting the cookie cache.
CookieCacheVersion
Immutable configured cache version; empty literals use the source default.
CookieRefreshCache
Stateless cache renewal policy, corresponding to cookieCache.refreshCache.
DatabaseError
HttpEndpointResponse
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.
HttpMethod
HTTP method enumeration
HttpRequestAction
Physical HTTP hook control flow, before route selection and endpoint hooks.
InvitationStatus
Invitation status
OAuthStateStrategy
Strategy for persisting OAuth state between the sign-in and callback steps.
RateLimitDecision
RateLimitRule
SameSite
UserFilterValue
String operands for admin user-list filtering.

Traits§

AuthAccount
Trait representing an account entity (OAuth provider linking).
AuthApiKey
Trait representing an API key entity.
AuthInvitation
Trait representing an invitation entity.
AuthMember
Trait representing an organization member entity.
AuthOrganization
Trait representing an organization entity.
AuthPasskey
Trait representing a passkey entity.
AuthPlugin
Plugin trait that all authentication plugins must implement.
AuthSchema
App-owned auth schema declaration.
AuthSession
Trait representing a session entity.
AuthStore
AuthTransaction
AuthTwoFactor
Trait representing a two-factor authentication entity.
AuthUser
Trait representing a user entity.
AuthVerification
Trait representing a verification token entity.
BackgroundTaskHandler
Application integration for deferred operations, such as platform waitUntil.
CacheAdapter
Cache adapter trait for session caching
CookieCacheVersionResolver
Application-owned asynchronous cache version policy.
EmailProvider
Trait for sending emails. Implement this to integrate with your email service (SMTP, SendGrid, SES, etc.).
Middleware
Middleware trait for request/response processing.
PasswordHashHook
An initialized policy applied at actual password hashing, after endpoint admission and before the selected original hasher. Verification is unchanged.
PasswordHasher
Custom password hasher trait for pluggable password hashing strategies.
RateLimitResolver
Application-owned request policy; returning None disables this request’s limit.
RateLimitStorage
A rate-limit backend must atomically decide and consume before returning.
VerificationEmailOverride
A plugin override for delivery of the core email-verification challenge.
WalletAddressStore

Functions§

extract_origin
Extract the origin (scheme + host + port) from a URL string.
hash_password
Hash password using the custom hasher (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::ValidationErrors into a standardized error response body.
verify_password
Verify password against hash using the custom hasher (if provided) or the default scrypt algorithm. Returns Ok(()) on match, or Err(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§

AuthResult
BackgroundTaskCompletion
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.
OrganizationPermissions
Preserve insertion order because upstream stores permission JSON as a string.

Derive Macros§

AuthSchema
PluginConfig