Skip to content
bymaxonePublic

About

Full-stack authentication library for Rust (Axum 0.8), React 19 & Next.js 16 — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready. Pure-Rust crypto with WebAssembly edge verification.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

342 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

bymax-auth / @bymax-one/rust-auth

bymax-auth · @bymax-one/rust-auth

Full-stack authentication for Rust (Axum), React & Next.js
JWT · MFA · OAuth · Sessions · Multi-Tenant · Pure-Rust Crypto · WebAssembly Edge Verification

crates.io version crates.io downloads npm version docs.rs CI status coverage mutation gate OpenSSF Scorecard RustSec audit build provenance license Rust edition 2024

GitHub · Issues · Quick Start · docs.rs · API Reference · Examples


Important

🚧 Early development. This repository is under active construction. The crates are not yet published to crates.io or npm, and the API described below is the target surface the project is building toward — not all of it exists yet. Badges, version numbers, and install commands reflect the intended 1.0 release. See the development plan for current status.

✨ Overview

bymax-auth is a complete authentication and authorization solution shipped as a lean Cargo workspace (crates.io) plus a matching npm package — covering everything from an Axum backend to React hooks, Next.js route handlers, and an edge JWT verifier compiled to WebAssembly.

Instead of stitching together a dozen crates and packages for JWT, MFA, OAuth, sessions, password reset, and brute-force protection, you add one library and get a production-ready auth system that spans your entire stack — with the frontend types generated from the Rust source, so the server and the client can never drift.

Why bymax-auth?

  • 🎯 One workspace, full stack — A backend crate (bymax-auth) and an npm package (@bymax-one/rust-auth) in lockstep. Shared types and constants are generated from Rust via ts-rs and re-checked in CI — zero manual synchronization, zero drift.
  • 🔌 Your database, your rules — The library defines async traits (UserRepository, EmailProvider). You implement them with sqlx, SeaORM, Diesel, or anything else. No ORM dependency, no driver baked in.
  • 🦀 Pure-Rust crypto only — Password hashing, MFA encryption, TOTP, and token generation run entirely on RustCrypto (scrypt, argon2, aes-gcm, hmac, sha2, subtle). No ring, no OpenSSL, no C bindings, and #![forbid(unsafe_code)] on every first-party crate.
  • ⚡ Pay for what you use — A tiny always-compiled core; every heavy integration (Redis, Axum, reqwest, MFA) is a Cargo feature or a trait you plug. A per-feature dependency budget is enforced in CI, so a minimal build pulls a minimal tree.
  • 🏢 Multi-tenant ready — Every operation is scoped by tenant_id, taken from a resolver and never the request body. A separate platform-admin identity domain is isolated from tenant users from day one.
  • 🌐 Edge-native — The same HS256 verifier that runs on the server compiles to wasm32-unknown-unknown and runs in the Next.js proxy (on the Node.js runtime) with no network call — one crypto implementation, server and edge, proven by tests. The edge is a fast reject, not the authority: with no network it cannot read the revocation list or the token epoch, so a revoked token still verifies there until it expires. Anything that must not outlive a revocation has to reach the backend.
cargo add bymax-auth --features "argon2,sessions,mfa,oauth,oauth-reqwest,redis,axum"
pnpm add @bymax-one/rust-auth

Note

Production status. Bymax Live — a Rust-backend + React/Next.js application — is the project's first production consumer (the dogfood target). It will run the library as its authentication and authorization layer (sessions, MFA, OAuth, platform admin, Redis), so the wire contract, the security invariants, and server/edge JWT parity are validated against real traffic rather than synthetic tests alone.


🔥 Features

🔐 Core Authentication

  • ✅ Registration & Login — Email/password hashed with scrypt and Argon2id (configurable, rehash-on-verify, self-describing PHC strings)
  • ✅ HS256 Access + Opaque Refresh Tokens — Atomic rotation with a grace window for concurrent requests; refresh tokens are opaque and never JWTs
  • ✅ Multi-Factor Authentication — TOTP with otpauth:// URI + QR, hashed recovery codes, and a temp-token challenge flow
  • ✅ OAuth 2.0 — Google built-in, PKCE + single-use state, account create/link/reject decisioning, MFA branch
  • ✅ Password Reset — Token-link or OTP, configurable per deployment, uniformly anti-enumerating
  • ✅ Email Verification — OTP-based with atomic resend cooldown

🛡️ Security

  • ✅ Pure-Rust Crypto — RustCrypto only (scrypt/Argon2id, AES-256-GCM, HMAC-SHA1 TOTP, HS256); no ring/OpenSSL/C on any path
  • ✅ Brute-Force Protection — Fixed-window Redis counters keyed on HMAC(tenant:email) — no PII in keys
  • ✅ Session Management — Active-session tracking with FIFO eviction, device/IP metadata, and new-session alerts
  • ✅ HttpOnly Cookies — Secure-by-default, refresh cookie path-scoped with SameSite=Strict, plus a non-HttpOnly has_session signal
  • ✅ Constant-Time Comparisons — Every secret/token/OTP/recovery-code compare goes through subtle — never == on secret bytes
  • ✅ JWT Revocation — Instant access-token revocation via a Redis jti blacklist
  • ✅ Anti-Enumeration — Identical status, body, and timing for known vs. unknown accounts, with an always-run sentinel hash
  • ✅ Refresh-Token Reuse Detection — Replaying a consumed token revokes that login's whole lineage, and only that lineage
  • ✅ Bulk Access-Token Revocation — A password reset advances a per-user token epoch, invalidating every outstanding access token in one write
  • ✅ Absolute Session Lifetime — Optional hard cap on how long one login can be extended by rotation
  • ✅ Cross-Site Request Refusal — Cookie-authenticated writes from an untrusted origin are rejected (matters under SameSite=None)
  • ✅ Breached-Password Refusal — Optional Have I Been Pwned check by k-anonymity range, over the crate's own HttpClient seam
  • ✅ Per-Route Rate Limiting — A per-route limit counted in the engine's shared Redis counter (one budget across instances), with an in-process governor layer as the fallback when no shared counter is configured; values pinned to the shared cross-implementation contract

🏢 Multi-Tenant & Platform

  • ✅ Tenant Isolation — All operations scoped by tenant_id via a configurable TenantIdResolver (anti-spoofing: a body that names a tenant is refused)
  • ✅ Platform Admin Auth — A separate identity domain with its own claims, sessions, and role hierarchy — fully isolated from tenant users
  • ✅ User Invitations — Single-use tokenized invites with role + tenant assignment and re-validation on accept
  • ✅ Role-Based Access Control — Hierarchical roles enforced by the RequireRole<R> extractor
  • ✅ Service API Keys (opt-in) — Scoped keys for machine callers: only an HMAC digest is stored, one answer for every bad credential, a route that declares no scopes opens for no one, rotation with overlap, an audit event per request

🧩 Developer Experience

  • ✅ Full-Stack Typed — Rust domain types → TypeScript via ts-rs, drift-gated in CI
  • ✅ Two Artifacts — bymax-auth for crates.io, @bymax-one/rust-auth for npm, versioned in lockstep (neither is published yet)
  • ✅ Builder + Validated Config — Assemble the engine with AuthEngineBuilder; build() fails fast with a typed ConfigError
  • ✅ Trait-Pluggable — Bring your own database, email transport, HTTP client, and stores
  • ✅ Axum-Native Extractors — FromRequestParts guards (AuthUser, RequireRole<R>, …) — no middleware soup, no Passport equivalent

📦 Two Packages, One Workspace

The backend ships on crates.io; the frontend ships on npm. The WebAssembly edge verifier is bundled inside the npm package (never published as a standalone crate).

Backend — bymax-auth (crates.io)

A thin facade over a set of focused internal crates. You enable only the capabilities you need; the always-compiled core stays tiny.

Feature Enables
scrypt (default) Default password KDF (parity baseline) — drop-in scrypt
argon2 Argon2id KDF + the hardened AuthConfig::secure_defaults() profile
sessions Redis-backed session tracking + FIFO eviction
mfa TOTP setup/verify/challenge, recovery codes (AES-256-GCM secret at rest)
oauth OAuth 2.0 + PKCE orchestration (transport injected — zero HTTP deps)
oauth-reqwest Bundled reqwest-backed HttpClient (opt-in; omit to supply your own)
platform Platform-admin identity domain (login/MFA/sessions)
invitations Tokenized user invitations
api-keys Scoped service API keys (repository port, issuing, the require_api_key_scopes axum layer)
redis Canonical Redis stores (redis + deadpool-redis) with atomic Lua
axum HTTP router, extractors, DTO validation, cookie delivery, per-route rate limiting, WebSocket tickets
breach Opt-in breached-password check (HibpBreachChecker, HIBP k-anonymity)
openapi OpenAPI request-body schemas of the auth routes (with axum)
client Native Rust typed auth client (needs a backend with bearer or both token delivery; the default cookie delivery returns no tokens to it)
full Every backend feature above

Note

There is no core feature — the engine is always compiled and individual flows are runtime toggles. When a feature is disabled, its crates and dependencies are never linked (a no-MFA build pulls in none of aes-gcm/sha1).

Frontend — @bymax-one/rust-auth (npm)

One package, four entry points — import only what your app needs:

Subpath Import Purpose Peer deps
Shared @bymax-one/rust-auth/shared Types, constants, error codes — generated from Rust None
Client @bymax-one/rust-auth/client Native-fetch client with single-flight refresh None
React @bymax-one/rust-auth/react AuthProvider + hooks React 19
Next.js @bymax-one/rust-auth/nextjs Proxy, route handlers, WASM-backed edge JWT verify Next.js 16
shared (generated, zero deps)
   ↗        ↖
client      (Rust crate: bymax-auth-client)
   ↑
 react
   ↑
nextjs ──→ bymax-auth-wasm (edge HS256 verifier)

Tip

Prefer to learn from working code? The examples/ directory ships runnable apps — axum-minimal, axum-mfa, axum-oauth-google, react-vite, and nextjs — each built and linted in CI so they never rot.

🚀 Quick Start

1. Add the crate

# Cargo.toml
[dependencies]
bymax-auth = { version = "<first release>", features = ["argon2", "sessions", "mfa", "oauth", "oauth-reqwest", "redis", "axum"] }

2. Implement the repository trait

The library defines what it needs — your app provides how. Map the abstract AuthUser contract onto your own schema; the only invariant is that password_hash is persisted exactly as the library produced it (a self-describing PHC string).

use async_trait::async_trait;
use bymax_auth::core::RepositoryError;
use bymax_auth::core::traits::UserRepository;
use bymax_auth::types::{AuthUser, CreateUserData, CreateWithOAuthData, UpdateMfaData};

pub struct PgUserRepository {
    pool: sqlx::PgPool,
}

#[async_trait]
impl UserRepository for PgUserRepository {
    async fn find_by_email(
        &self,
        email: &str,
        tenant_id: &str,
    ) -> Result<Option<AuthUser>, RepositoryError> {
        // `UserRow` is your own `#[derive(sqlx::FromRow)]` struct with an
        // `impl From<UserRow> for AuthUser`: `AuthUser` does not implement `sqlx::FromRow`.
        sqlx::query_as::<_, UserRow>(
            "SELECT * FROM users WHERE email = $1 AND tenant_id = $2",
        )
        .bind(email.to_lowercase())
        .bind(tenant_id)
        .fetch_optional(&self.pool)
        .await
        .map(|row| row.map(AuthUser::from))
        .map_err(|e| RepositoryError::Backend(Box::new(e)))
    }

    async fn create(&self, data: CreateUserData) -> Result<AuthUser, RepositoryError> {
        // INSERT … RETURNING *, storing data.password_hash verbatim.
        todo!()
    }

    // Every write takes the tenant the account lives in and MUST restrict itself to it:
    // `WHERE id = $1 AND tenant_id = $2`.
    async fn update_password(
        &self,
        id: &str,
        tenant_id: &str,
        password_hash: &str,
    ) -> Result<(), RepositoryError> {
        todo!()
    }

    async fn update_mfa(
        &self,
        id: &str,
        tenant_id: &str,
        data: UpdateMfaData,
    ) -> Result<(), RepositoryError> {
        todo!()
    }

    async fn find_by_oauth_id(
        &self,
        provider: &str,
        provider_id: &str,
        tenant_id: &str,
    ) -> Result<Option<AuthUser>, RepositoryError> {
        todo!()
    }

    async fn create_with_oauth(
        &self,
        data: CreateWithOAuthData,
    ) -> Result<AuthUser, RepositoryError> {
        todo!()
    }

    // … link_oauth, update_status, update_email_verified, etc.
}

3. Implement the email provider trait

Email delivery is fully delegated — the library never imports a mailer SDK. It passes structured data (token, OTP, session info, invite data), never rendered HTML.

Most deployments should not write this trait by hand. DefaultAuthEmailProvider already implements every method over a one-method delivery port, with the escaping, header sanitization and failure policy described below:

use std::sync::Arc;
use bymax_auth::core::traits::{
    AuthEmailSink, DefaultAuthEmailProvider, EmailError, OutgoingEmail,
};

pub struct ResendSink { /* client, from */ }

#[async_trait::async_trait]
impl AuthEmailSink for ResendSink {
    async fn send(&self, message: OutgoingEmail<'_>) -> Result<(), EmailError> {
        // One call, whatever your transport is (Resend/SES/SMTP). `message.tenant_id` is the
        // tenant the account belongs to, for a multi-tenant channel's attribution and routing.
        Ok(())
    }
}

let email = Arc::new(DefaultAuthEmailProvider::new(Arc::new(ResendSink { /* … */ })));

Override any subset of the copy by implementing AuthEmailCatalogue (every method has a secure default) and passing it to .with_catalogue(…). Every renderer receives an AuthEmailContext { tenant_id, email, locale } as its first argument, so a link can be built under a tenant-specific host; email is the delivery address, which for email_change_verification is the NEW address and for email_changed the PREVIOUS one. By default a delivery failure is logged and swallowed, so a down channel never turns "enable MFA" into a failed request — .with_delivery_error_policy(DeliveryErrorPolicy::Rethrow) restores the error for the flows that react to one (the reset path deletes an undelivered token early; the email-change path refuses to report "sent"; the invitation path answers 500 auth.internal).

Warning

A renderer that returns html owns its own escaping. The provider escapes what it renders — a message that leaves html unset has its text turned into escaped paragraphs — but a returned html value is used verbatim. That is what makes a real <a> link possible, and it means an override interpolating a display name, a tenant name or an address must escape those itself. The subject sanitization and the failure policy do apply to overrides; escaping is the one that does not.

To bridge the port onto something the sink shape does not fit, implement EmailProvider directly. Every method takes the account's tenant_id first; a cross-tenant platform admin carries none, so those notices arrive under the reserved PLATFORM_EMAIL_TENANT ("platform").

use async_trait::async_trait;
use bymax_auth::core::traits::{EmailError, EmailProvider, InviteData, SessionInfo};

pub struct ResendEmailProvider { /* client, from, app_url */ }

#[async_trait]
impl EmailProvider for ResendEmailProvider {
    async fn send_password_reset_token(
        &self, tenant_id: &str, email: &str, token: &str, locale: Option<&str>,
    ) -> Result<(), EmailError> {
        // Render and send with your transport of choice (Resend/SES/SMTP).
        Ok(())
    }

    async fn send_email_verification_otp(
        &self, tenant_id: &str, email: &str, otp: &str, locale: Option<&str>,
    ) -> Result<(), EmailError> {
        // …
        Ok(())
    }

    async fn send_new_session_alert(
        &self, tenant_id: &str, email: &str, info: &SessionInfo, locale: Option<&str>,
    ) -> Result<(), EmailError> {
        // …
        Ok(())
    }

    async fn send_invitation(
        &self, tenant_id: &str, email: &str, data: &InviteData, locale: Option<&str>,
    ) -> Result<(), EmailError> {
        // …
        Ok(())
    }

    // … password-reset OTP, MFA enabled/disabled notifications, etc.
}

Warning

Any consumer-supplied value (display name, tenant name, inviter name, device string) interpolated into an HTML email body MUST be escaped to prevent stored XSS, and a subject line must carry no CR/LF or a channel that builds headers by concatenation will read the rest of it as extra headers. DefaultAuthEmailProvider does both for you; a hand-written provider owns them itself. Tokens and OTPs are library-generated and safe; the placeholders you fill in are not.

4. Build the engine and mount the router

build() runs full startup validation and returns Result<AuthEngine, ConfigError> — a misconfiguration fails fast at boot, never at the first request.

use std::sync::Arc;
use bymax_auth::axum::{auth_router, AxumAuthConfig, ClientIpSource};
use bymax_auth::core::providers::{GoogleOAuthProvider, ReqwestHttpClient};
use bymax_auth::core::{AuthConfig, AuthEngine, Environment};
use bymax_auth::redis::RedisStores;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let http = Arc::new(ReqwestHttpClient::new()?);
    let google_config = /* GoogleOAuthConfig { client id, secret, redirect URI, … } */;
    let stores = Arc::new(RedisStores::connect("redis://127.0.0.1", "auth")?);

    let mut config = AuthConfig::secure_defaults(); // or AuthConfig::nest_compat_defaults()
    // The OAuth routes mount only when this toggle is on (it is off by default).
    config.controllers.oauth = true;

    let engine = AuthEngine::builder()
        .config(config)
        .environment(Environment::Production)   // resolves Secure cookies + prod redirect checks
        .user_repository(Arc::new(PgUserRepository { pool }))
        .email_provider(Arc::new(ResendEmailProvider { /* … */ }))
        .redis_stores(stores.clone())
        .http_client(http.clone())
        .oauth_provider(Arc::new(GoogleOAuthProvider::new(google_config, http)))
        // `redis_stores` does not wire the single-use OAuth `state` store: with
        // `controllers.oauth` on, `build()` fails with `ConfigError::OAuthStateStoreMissing` without it.
        .oauth_state_store(stores)
        .build()?;

    // `ClientIpSource` states how the caller's address is learned, for the per-route rate limiter
    // and for the session, lockout and hook context alike. Behind a proxy, name it:
    //   AxumAuthConfig::new(ClientIpSource::TrustedForwardedFor)
    //       .is_trusted_proxy(|peer| peer.is_loopback()) // true only for YOUR proxies
    // `X-Forwarded-For` is then believed only from those peers; without the predicate the
    // router refuses to build, because a directly reachable caller would pick its own address.
    let app = auth_router(engine, AxumAuthConfig::new(ClientIpSource::PeerAddr))?;

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    // The rate limiter reads the peer address, so serve with connect info.
    axum::serve(
        listener,
        app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
    )
    .await?;
    Ok(())
}

5. Protect your own routes with extractors

Guards are Axum FromRequestParts extractors — compose them straight into a handler signature. They read the token from a cookie or Authorization: Bearer header — never from the query string.

use axum::Json;
use bymax_auth::axum::{AdminRole, AuthUser, RequireRole, Role, SelfOrAdmin};
use bymax_auth::types::DashboardClaims;

// A role is a marker type whose NAME is a key of `roles.hierarchy`.
struct Admin;
impl Role for Admin { const NAME: &'static str = "ADMIN"; }
impl AdminRole for Admin { const NAME: &'static str = "ADMIN"; }

// Any authenticated dashboard user; `.0` carries the verified claims.
async fn profile(user: AuthUser) -> Json<DashboardClaims> {
    Json(user.0)
}

// Admins (and anything above them in the hierarchy) only.
async fn list_users(_: RequireRole<Admin>) -> &'static str {
    "ok"
}

// The resource owner (the `{user_id}` path segment), or an admin.
async fn update_user(_: SelfOrAdmin<Admin>) -> &'static str {
    "ok"
}

Machine callers: scoped service API keys (feature api-keys)

For a service that calls yours without a user session, enable api_keys (a strong pepper, a closed scopes vocabulary), implement ApiKeyRepository over your database, and guard routes with the layer. A key must hold every scope the route declares; a layer built with an empty list refuses everything.

use bymax_auth::axum::{CurrentApiKey, require_api_key_scopes, spawn_api_key_flush};

// Mint a key once (the plaintext is returned only here) from your own admin tooling:
//   let issued = engine.issue_api_key(IssueApiKeyInput::new("billing", vec!["reports:read".into()])).await?;

async fn report(CurrentApiKey(key): CurrentApiKey) -> String {
    format!("hello {}", key.label)
}

let guard = require_api_key_scopes(&state, &["reports:read"])?;
let app = Router::new().route("/reports/{id}", get(report)).route_layer(guard);

// Writes the coalesced last-used timestamps; call `shutdown().await` before the process exits.
let flush = spawn_api_key_flush(engine.clone())?;

The key travels in the x-api-key header (configurable), never the query string. Every bad credential answers the same 401 auth.api_key_invalid; a valid key missing a scope answers 403 auth.api_key_scope_insufficient. Rotate with rotate_api_key (an overlap keeps the old key valid for a while), and receive one audit event per request through AuthHooks::on_api_key_request.

6. Frontend integration (React)

Build an AuthClient once, hand it to AuthProvider; the hooks read the context it populates — exactly as in @bymax-one/nest-auth, so existing consumers change only the import specifier.

// app/providers.tsx
'use client'
import { AuthProvider } from '@bymax-one/rust-auth/react'
import { createAuthClient } from '@bymax-one/rust-auth/client'

const authClient = createAuthClient({
  // The origin every endpoint is resolved against. An empty string keeps calls same-origin,
  // through the Next.js route handlers.
  baseUrl: '',
})

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <AuthProvider client={authClient} onSessionExpired={() => (location.href = '/login')}>
      {children}
    </AuthProvider>
  )
}
// app/(dashboard)/profile.tsx
'use client'
import { useAuth, useSession } from '@bymax-one/rust-auth/react'

export function Profile() {
  const { user, status } = useSession()
  const { logout } = useAuth()

  if (status === 'loading') return <div>Loading…</div>
  if (status === 'unauthenticated' || user === null) return <div>Please log in</div>

  return (
    <div>
      <p>Welcome, {user.name}!</p>
      <button onClick={() => logout()}>Sign out</button>
    </div>
  )
}

7. Frontend integration (Next.js 16, edge JWT via WASM)

Mount the auth proxy at the project root and expose the route handlers below. The proxy verifies the access token in the Next.js middleware layer using the WebAssembly build of the same HS256 verifier the backend uses — no network round-trip. The WebAssembly glue needs the Node.js runtime; the lighter Edge runtime does not initialize it.

// proxy.ts — Next.js 16 proxy (Node.js runtime)
import { createAuthProxy } from '@bymax-one/rust-auth/nextjs'

export const { proxy } = createAuthProxy({
  accessTokenSecret: process.env.AUTH_ACCESS_TOKEN_SECRET ?? null, // verified locally via WASM
  // Set these whenever the backend configures `jwt.issuer` / `jwt.audience`. Left unset, the
  // proxy also accepts a token minted for another issuer or audience under the same secret.
  expectedIssuer: process.env.AUTH_JWT_ISSUER ?? null,
  expectedAudience: process.env.AUTH_JWT_AUDIENCE ?? null,
  loginPath: '/login',
  // Prefixes at a segment boundary: never list '/', which would make every route public.
  // `/auth` is the same-origin forwarding route to the backend (login, register, ...) and
  // `/api/auth` holds the client-refresh and logout handlers; both must be reachable while
  // the caller is unauthenticated, or an expired access token can never be refreshed.
  // The refresh cookie is sent only to paths under `cookies.refresh_cookie_path` (default
  // `/auth`), so a handler that must read it has to be mounted under that path. These
  // handlers are under `/api/auth`, so the backend sets `cookies.refresh_cookie_path` to
  // `/api/auth` (see "Proxy topology" below).
  publicPaths: ['/login', '/auth', '/api/auth'],
  silentRefreshPath: '/api/auth/silent-refresh',
  roleRules: [{ pathPrefix: '/admin', roles: ['ADMIN'] }],
  blockedStatuses: ['BANNED', 'INACTIVE', 'SUSPENDED'],
})

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}

Proxy topology. The browser sends the refresh cookie only to URLs under its Path, which is cookies.refresh_cookie_path on the backend and defaults to /auth. The Next route handlers (client-refresh, silent-refresh, logout) sit at /api/auth/*, so with the default the browser never sends them the refresh cookie and every refresh answers 401. Set cookies.refresh_cookie_path to /api/auth on the backend, and pass the same value as refreshCookiePath to the handlers so a clear names the cookie at the path it was planted with. The library default is unchanged and matches @bymax-one/nest-auth.

publicPaths entries are prefixes that end at a segment boundary, and '/' is a prefix of every path: '/' makes every route public. List each public prefix instead.

Important

The WASM module and verifyJwtToken are server/edge only — never import them into a Client Component. The HS256 secret must never reach the browser; an accidental client import is a security defect (a server-only guard catches it at build time).

// app/api/auth/logout/route.ts
import { createLogoutHandler } from '@bymax-one/rust-auth/nextjs'

export const POST = createLogoutHandler({
  backendUrl: process.env.API_BASE_URL!,
  loginPath: '/login',
  refreshCookiePath: '/api/auth', // the backend's cookies.refresh_cookie_path
})
// app/api/auth/silent-refresh/route.ts — the proxy redirects here when the access token has
// expired but a `has_session` signal is present
import { createSilentRefreshHandler } from '@bymax-one/rust-auth/nextjs'

export const GET = createSilentRefreshHandler({
  backendUrl: process.env.API_BASE_URL!,
  loginPath: '/login',
  refreshCookiePath: '/api/auth', // the backend's cookies.refresh_cookie_path
})

⚙️ Configuration

Everything is configured through AuthConfig. Two ready-made profiles bundle sensible choices; Default equals nest_compat_defaults().

Profile Posture
AuthConfig::nest_compat_defaults() Behavioral parity with @bymax-one/nest-auth out of the box (scrypt, email verification required, brute-force max_attempts = 5) — the Default
AuthConfig::secure_defaults() Hardened opt-in profile (Argon2id as the password KDF) — available under the argon2 feature
Group Key options nest-compat default
jwt secret (required, ≥ 32 chars), previous_secrets (and the top-level identifier_key), access_expires_in, refresh_expires_in_days, refresh_grace_window, absolute_session_lifetime_days, issuer, audience 15m, 7d, 30 s (at most 300 s), 30 (0 disables the cap), HS256 (pinned), both off
password active_algorithm, scrypt cost_factor / Argon2id memory_kib, min_length, blocklist scrypt N=2¹⁷, r=8, p=1; min_length = 15 (8..=128, applied only when a password is set, never on login or rehash); blocklist = []
token_delivery Cookie | Bearer | Both Cookie
cookies names, refresh_cookie_path, same_site, trusted_origins, resolve_domains HttpOnly, Secure, Lax (the refresh cookie is Strict), []
mfa encryption_key (32 bytes), previous_encryption_keys, issuer, totp_window, recovery_code_count —
sessions enabled, default_max_sessions, max_sessions_resolver false, 5
brute_force max_attempts, window 5, 900
rate limiting AxumAuthConfig::rate_limits — per-route limits counted in the shared store, pinned to the shared contract on, per-route
password_reset method (Token | Otp), otp_length, token_ttl Token, 600 s
email_verification required, otp_ttl true, 600 s
email_change token_ttl (the routes mount only with controllers.email_change) 3600 s
platform enabled (requires roles.platform_hierarchy) false
invitations enabled, token_ttl false, 48 h
api_keys enabled, pepper, scopes, header, prefix, last_used_flush, audit_mode false, —, —, x-api-key, bak, 60 s, best-effort
roles hierarchy (required), platform_hierarchy —
oauth google, redirect_allowlist, *_redirect_url —
controllers per-group route toggles (auth, password_reset, mfa, sessions, platform, oauth, invitations, email_change, workspaces); sessions, platform and invitations follow their enabled flag auth and password_reset on, the rest off
workspaces enabled (needs WorkspaceRepository, MembershipRepository and a membership cache store on the builder), roles (hierarchy, owner_role), permissions, membership_cache_ttl_seconds, allow_create, max_workspaces_per_user, deletion_grace_days, invitation_ttl_seconds, max_pending_invitations_per_workspace false, —, owner-only except view_members, 60, true, 0 (no limit), 14, 604800 (60 to 2592000), 100 (1 to 10000)
route_prefix the mount segment of every route; a value other than auth requires an explicit cookies.refresh_cookie_path (RefreshPathMismatch) auth
tenancy tenant_id_resolver, enforce_tenant_binding (refuses a token minted for another tenant than the resolver names; requires a resolver, else TenantBindingWithoutResolver) none, false
account status blocked_statuses, user_status_cache_ttl (how long a status change takes to reach a live token) BANNED, INACTIVE, SUSPENDED; 60 s

Numeric bounds. build() refuses a numeric option outside the range below.

Option Accepted
sessions.default_max_sessions 1 to 1000
jwt.refresh_expires_in_days 1 to 3650
jwt.absolute_session_lifetime_days 0 (off) or 1 to 3650
jwt.access_cookie_max_age 1 to 315 360 000 s
brute_force.window 1 to 604 800 s
password_reset.token_ttl, password_reset.otp_ttl, email_verification.otp_ttl, email_change.token_ttl, invitations.token_ttl 1 to 315 360 000 s (ten years)
scrypt parallelization, Argon2id parallelism 1 to 16

user_status_cache_ttl = 0 means "no cache" here, where nest-auth refuses 0. The access cookie lifetime is a Duration, so its ceiling reads 315 360 000 s where nest-auth's option is in milliseconds (315 360 000 000 ms); the limit is the same ten years. A sub-second Duration counts as 0.

Note

build() validates every cross-field invariant (secret length/entropy, role referential integrity, parameter floors, SameSite=None ⇒ Secure, trusted_origins reachable under the cookie posture, OAuth redirect allow-listing, required stores) and rejects an invalid config with a precise ConfigError.

Tip

Binding tokens to an issuer and an audience. jwt.issuer and jwt.audience are None by default. Set either and its value is stamped on every token this backend mints — dashboard, platform and MFA challenge alike — and required on every token it verifies: one carrying a different value, or none at all, is rejected. That matters with HS256, where the verifier can also sign: every service holding the secret to check a token can mint one, so audience binding is what stops a token minted for one service being replayed at another that trusts the same secret. The check sits at the single verification chokepoint, so a retired signing key does not waive it.

Two things to know before switching it on. Both backends of a shared deployment must carry the same pair, or they stop accepting each other's tokens. And enabling it invalidates the access tokens already in flight — a window of one access-token lifetime, which clients close by refreshing. An empty string reads as unconfigured rather than as "require the empty issuer".

Rotating the signing secret. jwt.previous_secrets lists secrets retired by a rotation, accepted for verification only. Without it, changing jwt.secret signs every user out the moment the new configuration rolls out and invalidates every stored recovery-code digest — those are keyed by an HMAC derived from the secret, so users lose the codes they printed and filed. With it, both keep working while tokens issued under the old secret drain, and a rotation becomes a rollout. Remove the entry once the longest-lived token signed under it has expired: every entry is a key that still opens the door. mfa.encryption_key rotates the same way, through its own list — see below.

Pin identifier_key before you rotate. Every Redis name that identifies an account — the session index, the token epoch, the MFA keys, the recent-authentication marker, and the OTP and rate-limit identifiers — is an HMAC under a key derived from jwt.secret unless you set identifier_key, and so are the stored MFA recovery-code digests. Rotate jwt.secret alone and all of them are renamed: live sessions lose their index, every token epoch reads zero, so a token that a password reset or a revoke-all had refused is accepted again until it expires, and recovery codes stop verifying unless the old secret is listed in jwt.previous_secrets. identifier_key is a secret of its own for those names and digests; it is validated like jwt.secret and never signs or verifies a token. The value is simply the secret you want them to keep deriving from — there is nothing to compute.

Routine rotation — keep sessions, epochs and recovery codes Rotation after a compromise — cut the link
Before rotating Once, set identifier_key to the value jwt.secret has now and deploy. Nothing moves: the derivation is unchanged. Later rotations leave it as it is. Revoke what has to be revoked while the session index can still find it; afterwards nothing can be revoked through it, and refresh tokens, which are looked up by their own hash, keep working. Do not list the compromised secret in jwt.previous_secrets.
Rotating Put the new secret in jwt.secret and the old one in jwt.previous_secrets; keep identifier_key as it is. Put the new secret in jwt.secret and choose a new identifier_key.
Names Unchanged. Moved: sessions lose their index until they next refresh (meanwhile they are missing from the session list and cannot be revoked through it, and their refresh tokens still work until they expire), every epoch reads zero, MFA set-up state and lockout counters start empty, and stored recovery-code digests stop verifying.
Revoked tokens Stay revoked. Tokens signed under the old secret no longer verify. A token signed under a secret that stays in previous_secrets and had been refused by an epoch is accepted again, because the epoch is renamed with the rest and revoking first does not carry it across: remove retired secrets from previous_secrets or wait out jwt.access_expires_in.
Afterwards Drop the old secret from previous_secrets once its last token has expired. Users with MFA need new recovery codes: an old code is refused like any wrong code, and sign-in with the authenticator app is unaffected. A signed-in user replaces them with POST /auth/mfa/recovery-codes (POST /auth/platform/mfa/recovery-codes for an admin, both under the default route_prefix), proving a current TOTP code; the library does not regenerate them at the next sign-in or notify anyone, so your application prompts for it. Listing the secret the digests were keyed from (the old identifier_key, or the old jwt.secret if it was never set) in previous_secrets would keep the old codes working, and would keep tokens signed with it verifying if it was also a signing secret: that is the trade-off.

Pinning to the old secret leaves the derived Redis names computable by anyone who knows that secret. They are names, not signing material, and using one still needs access to your Redis; if cutting that link matters more than keeping sessions, take the second column. Without identifier_key a rotation moves the names as the second column does, whether or not you wanted them to.

Tip

Rotating the MFA encryption key. mfa.previous_encryption_keys lists AES-256 keys retired by a rotation of mfa.encryption_key. The stored ciphertext carries no key identifier, so without the list a change of key makes every enrolled user's TOTP secret undecryptable at once, with no way back — their authenticator simply stops matching. With it, a stored secret that opened under a retired key is re-encrypted under the current one on the next successful challenge, so the rotation drains on its own instead of requiring the retired key to stay configured forever. The rewrite is best-effort after a TOTP challenge: the user is already authenticated and the retired key still opens the secret, so a store that cannot answer the rewrite is logged and costs only the migration (the next challenge retries it); it never fails the challenge. build() holds each entry to the same bar as the current key (base64, exactly 32 bytes, and never equal to the current key or to another entry), because a malformed one would otherwise surface at a user's first challenge rather than at boot. Drop the entry once your enrolled users have had time to authenticate at least once. nest-auth exposes the identical option as mfa.previousEncryptionKeys.

Important

The parameters that carry a control's strength are bounded by build(). mfa.totp_window must be 0..=2 (TotpWindowRange): the window counts 30-second steps on either side of now, so 2n + 1 codes are valid at once — three at 1, five at the maximum — and a wider window would make a six-digit code proportionally easier to guess while the configuration still reads as "MFA enabled". mfa.recovery_code_count must be 1..=50 (RecoveryCodeCountRange), because zero enrols an account with no way back if the authenticator is lost. password.scrypt.block_size must be at least 8 (ScryptBlockSize) and password.scrypt.parallelization at least 1 (ScryptParallelization): the memory cost is 128 * N * r, so a smaller block size divides the hardness that the cost-factor floor exists to guarantee — invisibly, since the bounded parameter is still intact. jwt.refresh_grace_window must stay below the refresh lifetime (RefreshGraceTooLarge) and at or under 300 seconds (RefreshGraceCeiling): it is the span in which an already-consumed refresh token still buys a session, so it is the replay window for a stolen one and exists to cover a single network retry.

Important

jwt.access_expires_in must not exceed 30 days, the window a store keeps a bumped token epoch readable. The epoch is what makes a stateless access token revocable: a password reset advances it and every token stamped below it stops verifying — but only while the bumped value is still there. A longer-lived access token would outlive it, current_epoch would fall back to 0, and a token the reset revoked would verify again. build() refuses the configuration (ConfigError::AccessLifetimeExceedsEpochRetention) rather than letting it fail open, and nest-auth enforces the identical bound.

cookies.trusted_origins is required, and must be non-empty, as soon as same_site is None: that is the setting where the browser sends the session cookie cross-site, so an origin has to be authorized. Every entry must be a bare origin (scheme, host and an optional port), or build() refuses it. Under Lax/Strict the list may stay empty, but a deployment serving app.example.com and api.example.com from one .example.com cookie (cookies.resolve_domains) is same-site, so the browser does send the cookie between them; list those origins too.

The breached-password check is opt-in for a different reason: it is the only part of the credential path that reaches the network, and a library should not start talking to a third party because it was upgraded. It rides the crate's own HttpClient seam, so a deployment supplies the transport it already has:

// Cargo.toml: bymax-auth = { version = "…", features = ["breach"] }
use bymax_auth::core::traits::HibpBreachChecker;

let engine = AuthEngine::builder()
    .config(config)
    .user_repository(users)
    .redis_stores(stores)
    .breach_checker(Arc::new(HibpBreachChecker::new(http_client)))
    .build()?;

The checker fails open by contract: an unreachable corpus must never stop someone changing their password — least of all during an incident, when changing it is the urgent thing.


🏗️ Architecture

The library is a set of crates you embed in your Axum service — a framework-agnostic core wrapped by thin adapters.

┌──────────────────────────────────────────────────────────┐
│                  Your Axum Application                     │
│                                                            │
│   bymax-auth-axum   →  router · extractors · rate-limit    │
│        │                                                   │
│   bymax-auth-core   →  AuthEngine · services · 21 hooks    │
│      ╱   │   ╲                                             │
│  -crypto -jwt -types     (pure-Rust, wasm-safe)            │
│        │                                                   │
│   ┌────▼─────┐   ┌──────────────┐   ┌──────────────┐       │
│   │ User     │   │ Email        │   │ SessionStore │       │
│   │ Repository│  │ Provider     │   │ (bymax-auth- │       │
│   │ (yours)  │   │ (yours)      │   │  redis)      │       │
│   └──────────┘   └──────────────┘   └──────────────┘       │
└──────────────────────────────────────────────────────────┘
         bindings/bymax-auth-wasm  →  edge HS256 verifier (npm)

Design Principles

Principle Description
🔌 Trait-Driven Define contracts, inject implementations — works with sqlx, SeaORM, Diesel, or any store
🔒 Secure by Default scrypt/Argon2id, HttpOnly cookies, jti blacklist, brute-force, anti-enumeration — all on out of the box
🪶 Tiny Mandatory Tree A small always-compiled core; Redis, Axum, reqwest, and MFA are feature-gated, with a CI dependency budget
🦀 One Crypto, Everywhere A single pure-Rust HS256 primitive runs on the server and at the edge (WASM) — never two implementations
🌳 wasm-clean boundary bymax-auth-wasm depends only on -crypto/-jwt/-types; a CI job builds wasm32 to prove it
⚡ Fast & measured No GC and no FFI boundary; hot paths run in ns–µs while memory-hard KDFs stay tunable — tracked with Criterion benches (details)

🔐 Security Model

The security architecture is codified as a set of inviolable invariants that the quality gates exist to protect — relaxing one is treated as a vulnerability, not a feature.

JWT Token Type Discrimination

Every token carries a type claim that extractors validate before acceptance:

Token type Issued when Accepted by
dashboard Successful login or MFA challenge AuthUser
platform Platform-admin login or MFA challenge PlatformUser
mfa_challenge Login with MFA enabled (pre-verification) MFA challenge endpoint

This prevents token-type-confusion attacks. A dashboard token presented to a platform route is rejected with PlatformAuthRequired (not the generic TokenInvalid), so clients can distinguish wrong-context from expired.

Algorithm Pinning & Opaque Refresh

Verification pins header.alg == "HS256" before any signature math — none, RS256, ES256, and every asymmetric algorithm are rejected, and only a symmetric key exists. Refresh tokens are opaque CSPRNG strings, inert without their server-side Redis record, persisted only as sha256(token) — never signed or parsed as JWTs.

Separate Auth Contexts for Multi-Tenant SaaS

Platform admins and tenant users are fully isolated — separate repositories, claims, extractors, and routes. When a TenantIdResolver is configured it is authoritative on every tenant-scoped flow (login, register, both email-verification steps, all four password-reset steps, and the OAuth initiate), and a request that names a tenantId of its own is refused with auth.validation rather than having it silently discarded — preventing tenant spoofing at the architecture level, and saying so instead of answering success while the account lands under a different tenant.

Because a configured resolver makes the body's value dead weight, tenantId is optional on every DTO that carries it and a client may omit it entirely. With no resolver configured the body is the only thing that can name a tenant, and a request naming none is refused with auth.validation rather than defaulted — the deployment has to choose one of the two, and neither choice is guessed on its behalf.

Atomic State on Shared Redis

Every read→decide→write on contended state — refresh rotation + grace, ownership-checked revoke, brute-force increment, OTP verify+consume, single-use WebSocket ticket — runs as a single atomic Lua script, closing the concurrency races those flows would otherwise expose.

Note

Redis Cluster is not supported, because the scripts that write a session touch keys that hash to different slots.

Security Checklist

When integrating bymax-auth in production, verify each of the following:

  • cookies.resolve_domains validates against an allow-list — the Host header is never used to derive a parent domain
  • oauth.redirect_allowlist is set so no redirect/callback URL is request-derived (no open redirect)
  • The MFA encryption_key is 32 bytes from a secret manager; the JWT secret is 32 random bytes, high-entropy
  • HS256 pinning, constant-time comparisons (subtle), and CSPRNG (OsRng) are never bypassed
  • HttpOnly + Secure (outside development); refresh cookie path-scoped with SameSite=Strict

Log events

Every operational tracing event the crates emit carries an event field naming a closed code, so an operator can filter, count and alert on a code instead of matching message text. The messages stay as they are for a human reading a log.

The fields on these events are closed or numeric: a closed cause (store_unavailable, internal, ...), a plane or flow name, a status code or a count. No event carries an account, an email address, a token, an IP address or the text of an error: an identifier in a log line is the first thing a log-shipping pipeline copies to a third party, and a store's own error text names its backend. Repository, store and host-hook failures are told apart by the code and cause, never by their message.

A test (crates/bymax-auth-core/tests/log_events.rs) reads every crate's sources and this table: each production tracing call must carry event = "RUST_AUTH_..." and no forbidden field, and the codes in the sources and in this table must be the same set, with the same level, in both directions.

Code Level Emitted when
RUST_AUTH_ACCOUNT_REMOVAL_COUNTERS_NOT_BUMPED warn An account removal committed but some workspace membership counters were not bumped
RUST_AUTH_ACCOUNT_STATUS_CACHE_INVALIDATION_FAILED error Invalidating the account-status cache failed
RUST_AUTH_API_KEY_AUDIT_HOOK_FAILED error The API-key audit hook returned an error
RUST_AUTH_API_KEY_AUDIT_HOOK_TIMEOUT error The API-key audit hook exceeded its timeout ceiling
RUST_AUTH_API_KEY_LAST_USED_FLUSH_FAILED warn The background flush of API-key last-used timestamps failed; the next round retries
RUST_AUTH_API_KEY_ROUTE_WITHOUT_SCOPES error An API-key guarded route declares no scopes and was refused
RUST_AUTH_API_KEY_STORE_UNAVAILABLE error The API-key store could not answer
RUST_AUTH_BREACH_CHECK_BAD_BODY warn The breach-check service answered a non-UTF-8 body; the password was allowed
RUST_AUTH_BREACH_CHECK_UNAVAILABLE warn The breach-check service answered with a failure status; the password was allowed
RUST_AUTH_BREACH_CHECK_UNREACHABLE warn The breach-check service was unreachable; the password was allowed
RUST_AUTH_BRUTE_FORCE_IDENTIFIER_REJECTED error A brute-force identifier was rejected by the key-injection guard
RUST_AUTH_EMAIL_CHANGE_ACCOUNT_LOCKED warn An email change was refused: the account is locked
RUST_AUTH_EMAIL_CHANGE_COMPLETED info An account's email address was changed
RUST_AUTH_EMAIL_CHANGE_DELIVERY_FAILED error The email-change verification message could not be delivered
RUST_AUTH_EMAIL_CHANGE_NOTICE_FAILED error The notice to the previous address failed after the change
RUST_AUTH_EMAIL_CHANGE_PASSWORD_REJECTED warn An email change was refused: the current password was wrong
RUST_AUTH_EMAIL_CHANGE_TOKEN_STALE warn An email-change token was refused: it is no longer bound to the account password
RUST_AUTH_EMAIL_CHANGE_VERIFICATION_SENT info An email-change verification was sent
RUST_AUTH_EMAIL_DELIVERY_FAILED error An email could not be delivered by the configured sender
RUST_AUTH_EMAIL_NOOP debug The no-op email sender received a message
RUST_AUTH_EMAIL_NOOP_OTP_REDACTED debug The no-op email sender received a message and redacted its one-time code
RUST_AUTH_EMAIL_NOOP_TOKEN_REDACTED debug The no-op email sender received a message and redacted its token
RUST_AUTH_EMAIL_VERIFICATION_CODE_NOT_STORED warn The verification code could not be stored; a resend recovers
RUST_AUTH_EMAIL_VERIFIED info An email address was verified
RUST_AUTH_INTERNAL_ERROR error A request failed with an internal error (the response body stays generic)
RUST_AUTH_INVITATION_ACCEPTED info An invitation was accepted
RUST_AUTH_INVITATION_CREATED info An invitation was created
RUST_AUTH_INVITATION_DELIVERY_FAILED error An invitation message could not be delivered (the invitation stands)
RUST_AUTH_INVITATION_INVITER_CANNOT_GRANT warn An invitation was refused: its inviter can no longer grant it
RUST_AUTH_INVITATION_RECORD_REJECTED warn A stored invitation record was rejected as empty or carrying an undeclared role
RUST_AUTH_INVITATION_REVOKE_OUTRANKED warn An invitation revocation was refused: the revoker is outranked
RUST_AUTH_INVITATION_SUPERSEDE_CONTENDED warn A superseding invitation was refused: the pending one kept changing under the rank check
RUST_AUTH_INVITATION_SUPERSEDE_OUTRANKED warn A superseding invitation was refused: it is outranked by the pending one
RUST_AUTH_INVITATION_WITHDRAWN info An invitation was withdrawn
RUST_AUTH_LOGIN_ACCOUNT_LOCKED warn A login was refused: the account is locked
RUST_AUTH_LOGIN_INVALID_CREDENTIALS warn A login was refused: invalid credentials
RUST_AUTH_LOGIN_LOCKOUT_CLEARED info An account's lockout was cleared
RUST_AUTH_LOGIN_LOCKOUT_REMAINING_UNREADABLE error The remaining lockout time could not be read; the configured window is reported
RUST_AUTH_LOGIN_LOCKOUT_STATE_UNREADABLE error The lockout state could not be read for the hook
RUST_AUTH_LOGIN_MFA_CHALLENGE_ISSUED info A login succeeded and an MFA challenge was issued
RUST_AUTH_LOGIN_SUCCEEDED info A login succeeded
RUST_AUTH_LOGIN_TENANT_MISMATCH warn The user repository returned an account outside the requested tenant
RUST_AUTH_LOGOUT_PENDING_LOOKUP_FAILED warn The pending-owner lookup of a logout failed
RUST_AUTH_LOGOUT_PENDING_NOT_CLAIMED warn The pending owner of a logout could not be claimed
RUST_AUTH_LOGOUT_PENDING_NOT_RECORDED warn The pending owner of a logout could not be recorded
RUST_AUTH_LOGOUT_PENDING_STALE_NOT_REMOVED warn A stale pending owner could not be removed
RUST_AUTH_LOGOUT_REVOCATION_WRITE_FAILED warn A logout revocation write failed (the step is named in the message)
RUST_AUTH_LOGOUT_SESSION_CLOSED info A session was closed by a logout
RUST_AUTH_LOGOUT_SESSION_LOOKUP_FAILED warn A logout could not look up the session
RUST_AUTH_MEMBERSHIP_CACHE_UNAVAILABLE warn The workspace membership cache could not answer and the call proceeded
RUST_AUTH_MFA_ACCOUNT_LOCKED warn An MFA call was refused: the account is locked
RUST_AUTH_MFA_CHALLENGE_PASSED info An MFA challenge was passed
RUST_AUTH_MFA_CHALLENGE_REFUSED warn An MFA challenge was refused at issuance
RUST_AUTH_MFA_CHALLENGE_TENANT_MISMATCH warn The user repository returned an account outside the MFA token's tenant
RUST_AUTH_MFA_DISABLED info MFA was disabled
RUST_AUTH_MFA_DISABLE_INVALID_CODE warn Disabling MFA was refused: invalid code
RUST_AUTH_MFA_ENABLED info MFA was enabled
RUST_AUTH_MFA_INVALID_CODE warn An MFA challenge was refused: invalid code
RUST_AUTH_MFA_PLATFORM_CHALLENGE_PASSED info A platform MFA challenge was passed
RUST_AUTH_MFA_RESET_ADMINISTRATIVE warn MFA was removed administratively
RUST_AUTH_MFA_RESET_NOTHING_TO_REMOVE info An administrative MFA reset found no second factor to remove
RUST_AUTH_MFA_SECRET_NOT_MIGRATED warn Re-encrypting an MFA secret under the current key failed; the next challenge retries
RUST_AUTH_MFA_SETUP_INITIATED info MFA setup was initiated
RUST_AUTH_MFA_SETUP_INVALID_CODE warn MFA setup was refused: invalid TOTP code
RUST_AUTH_MFA_SETUP_PENDING_CONSUMED warn MFA setup was refused: the pending record was consumed by a concurrent request
RUST_AUTH_MFA_SURFACE_MISSING error An MFA challenge was requested but this build has no MFA surface
RUST_AUTH_MFA_TENANT_PLANE_MISMATCH warn An MFA call was refused: the tenant does not match the plane
RUST_AUTH_OAUTH_CALLBACK_PROVIDER_ERROR warn The OAuth callback carried an error from the provider
RUST_AUTH_OAUTH_HOOKS_MISSING warn The OAuth controller was enabled without custom hooks, so every OAuth sign-in is denied
RUST_AUTH_OAUTH_PROVIDER_ERROR_MAPPED warn An OAuth provider error was mapped to oauth_failed
RUST_AUTH_PASSWORD_CHANGED info A password was changed and the other sessions revoked
RUST_AUTH_PASSWORD_CHANGE_ACCOUNT_LOCKED warn A password change was refused: the account is locked
RUST_AUTH_PASSWORD_CHANGE_PASSWORD_REJECTED warn A password change was refused: the current password was wrong
RUST_AUTH_PASSWORD_RESET_COMPLETED info A password was reset and every session revoked
RUST_AUTH_PASSWORD_RESET_COOLDOWN_NOT_RELEASED warn The password-reset resend cooldown could not be released
RUST_AUTH_PASSWORD_RESET_PROOF_NOT_ISSUED warn A password-reset proof could not be issued
RUST_AUTH_PASSWORD_RESET_PROOF_STALE warn A password reset was refused: the proof was issued against a password that has since changed
RUST_AUTH_PASSWORD_RESET_ROLLBACK_FAILED error The rollback of a stored password-reset token failed
RUST_AUTH_PLATFORM_LOGIN_ACCOUNT_LOCKED warn A platform login was refused: the account is locked
RUST_AUTH_PLATFORM_LOGIN_INVALID_CREDENTIALS warn A platform login was refused: invalid credentials
RUST_AUTH_PLATFORM_LOGIN_MFA_CHALLENGE_ISSUED info A platform login succeeded and an MFA challenge was issued
RUST_AUTH_PLATFORM_LOGIN_SUCCEEDED info A platform login succeeded
RUST_AUTH_PLATFORM_LOGOUT_SESSION_LOOKUP_FAILED warn A platform logout could not look up the session
RUST_AUTH_PLATFORM_REFRESH_FAMILY_REVOKED warn A platform refresh-token family was revoked after reuse detection
RUST_AUTH_PLATFORM_REFRESH_NO_SESSION warn A platform refresh found no live session or grace window
RUST_AUTH_PLATFORM_REFRESH_REUSE_DETECTED warn Reuse of a consumed platform refresh token was detected
RUST_AUTH_RATE_LIMITER_OUTSIDE_RUNTIME warn A rate limiter was built outside a Tokio runtime, so its key map is never swept
RUST_AUTH_REAUTH_ACCOUNT_LOCKED warn A re-authentication was refused: the account is locked
RUST_AUTH_REAUTH_NOT_RECENT warn A re-authentication check was refused: no recent authentication
RUST_AUTH_REFRESH_ABSOLUTE_LIFETIME_EXCEEDED warn A rotation was refused: the session outlived the absolute lifetime cap
RUST_AUTH_REFRESH_FAMILY_REVOKED warn A refresh-token family was revoked after reuse detection
RUST_AUTH_REFRESH_NO_SESSION warn A refresh found no live session or grace window
RUST_AUTH_REFRESH_RECOVERED_WITHOUT_TENANT warn A grace recovery was refused: the dashboard session names no tenant
RUST_AUTH_REFRESH_REUSE_DETECTED warn Reuse of a consumed refresh token was detected
RUST_AUTH_REFRESH_SESSION_WITHOUT_TENANT warn A refresh was refused: the dashboard session record names no tenant
RUST_AUTH_REGISTERED info A user registered
RUST_AUTH_SESSIONS_OTHER_DEVICES_REVOKED info Every other device was signed out and the token epoch advanced
RUST_AUTH_SESSION_CAP_NOT_ENFORCED warn The session cap could not be enforced
RUST_AUTH_SESSION_EVICTION_FAILED warn Evicting an over-cap session failed
RUST_AUTH_SIDE_EFFECT_FAILED warn A detached side effect returned an error, which is ignored
RUST_AUTH_SIDE_EFFECT_TIMEOUT warn A detached side effect exceeded its timeout ceiling and is ignored
RUST_AUTH_STORE_UNAVAILABLE error A request failed because a store could not answer (answered 503)
RUST_AUTH_TENANT_BINDING_NOT_APPLIED warn Tenant binding is on but no request was supplied, so it was not applied
RUST_AUTH_WORKSPACE_INVITATIONS_UNCONFIGURED warn Workspaces are enabled with no invitation store, so workspace invitations are unavailable
RUST_AUTH_WORKSPACE_INVITATION_DELIVERY_FAILED warn A workspace invitation message could not be delivered (the invitation stands)
RUST_AUTH_WORKSPACE_INVITATION_EMAIL_UNSUPPORTED error The email provider does not implement workspace invitations
RUST_AUTH_WS_TICKET_REFUSED_MFA_PENDING warn A WebSocket ticket was refused: the session has not satisfied its second factor
RUST_AUTH_WS_TICKET_REFUSED_NO_TENANT warn A WebSocket ticket was refused: the snapshot names no tenant
RUST_AUTH_WS_TICKET_REFUSED_TOKEN_REVOKED warn A WebSocket ticket was refused: the token it was minted from is revoked
RUST_AUTH_WS_TICKET_REFUSED_EXPIRED warn A WebSocket ticket was refused: the token it was minted from has expired
RUST_AUTH_WS_TICKET_REFUSED_TENANT_MISMATCH warn A WebSocket ticket was refused: the snapshot names another tenant than the expected one
RUST_AUTH_WS_TICKET_REFUSED_ACCOUNT_GONE warn A WebSocket ticket was refused: the account no longer exists
RUST_AUTH_WS_TICKET_REFUSED_ACCOUNT_BLOCKED warn A WebSocket ticket was refused: the account is blocked

🛡️ Security Table

Layer Implementation
Password Hashing RustCrypto scrypt (N=2¹⁷, r=8, p=1 — OWASP's recommended minimum) or argon2 Argon2id (PHC)
MFA Encryption aes-gcm AES-256-GCM with a fresh 12-byte CSPRNG IV per call
TOTP hmac + sha1 per RFC 4226/6238, ±1 step window, anti-replay marked
Recovery Codes Keyed HMAC-SHA-256 digests (never plaintext, never reversible)
Token Generation getrandom/OsRng CSPRNG — 256 bits of entropy
Secret Comparison subtle constant-time — never == on secret bytes
JWT Hand-rolled HS256 (hmac + sha2), jti blacklist via Redis
Cookies HttpOnly, Secure-by-default, SameSite=Lax (refresh cookie Strict), path-scoped refresh
Brute-Force Redis atomic fixed-window counters per HMAC(tenant:email)
CSRF (OAuth) 64-hex single-use state (GETDEL) + PKCE code_verifier (S256)
Refresh Rotation Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage
Cross-Site Writes Origin / Sec-Fetch-Site check on cookie-authenticated writes — the gap SameSite=None leaves open
Breached Passwords Optional Have I Been Pwned range check by k-anonymity; only a 5-char SHA-1 prefix leaves the process
Rate Limiting Per-route fixed window in the shared Redis counter, with a tower_governor layer in process as the fallback; the limits themselves are pinned to the shared contract
Session Lifetime Optional absolute cap on how long one login can be extended by rotation
Edge Verify Same HS256 primitive compiled to WebAssembly — no network call

Important

All cryptography uses RustCrypto — no ring, no OpenSSL, no C/C++ bindings on any target — and every first-party crate is #![forbid(unsafe_code)] (the sole exception being the wasm-bindgen glue in the edge binding).


🧱 Tech Stack

Rust Axum RustCrypto WebAssembly Redis React Next.js TypeScript


⚡ Performance & Footprint

Rust's advantage over a managed runtime (Node, the JVM) is per-operation cost with no garbage collector and no FFI marshalling. bymax-auth is built to spend that advantage deliberately — and to prove it with benchmarks rather than assert it.

Built to be cheap where it should be

Lever What it buys
No runtime, no GC Auth work is synchronous CPU over owned bytes — no allocator pauses, no event-loop hops, predictable tail latency under load
Pure-Rust RustCrypto Every primitive is inlined Rust — no C bindings and no per-call FFI boundary to cross (the cost a native Node addon pays on every call)
Static where it's hot Internal services are monomorphized; dynamic dispatch (Arc<dyn _>) is paid only at the host-pluggable trait boundary, never in the inner loop
Allocation-aware Digests return a stack [u8; 32]; fixed-size randomness uses a stack [u8; N] instead of a Vec; transient key material lives in Zeroizing buffers wiped on drop
Pay for what you use A bare build is a tiny core — Redis, Axum, OAuth, and MFA are feature-gated behind a CI dependency budget, so unused capabilities cost zero binary and zero attack surface
Tiny edge The Next.js middleware verifies JWTs through a wasm-bindgen module — the same HS256 code as the server, with no network round-trip

Memory-hard by design — not by accident

Password hashing is deliberately expensive: scrypt and Argon2id are memory-hard so an attacker who exfiltrates the hash store cannot brute-force it cheaply. Their cost is a security knob (cost_factor / memory_kib), not a bottleneck — and it is the one operation the engine hands to tokio::task::spawn_blocking, so a burst of logins never stalls the async runtime. Everything around the KDF stays in the nanosecond–microsecond range.

Measured, not asserted

Tracked with Criterion so a regression surfaces as a number — the same discipline applied to the coverage gate.

Primitive (per call) Median Role
SHA-256 (mac::sha256) ~110 ns high-entropy token → Redis key suffix
Keyed HMAC-SHA-256 ~430 ns low-entropy identifier / recovery-code hashing
Secure token (32 B → hex) ~870 ns dominated by the OS CSPRNG syscall, not allocation
AES-256-GCM encrypt / decrypt ~2.1 µs / ~1.3 µs TOTP secret encrypted at rest
TOTP generate / verify (±1 window) ~200 ns / ~710 ns RFC 6238, constant-time
scrypt hash / verify (N=2¹⁷) ~150 ms memory-hard — tunable security cost, at OWASP's recommended minimum
Argon2id hash / verify (19 MiB) ~10 ms memory-hard — tunable security cost

Indicative medians on an Apple M4 Max, release profile, Rust 1.96. Reproduce with cargo bench -p bymax-auth-crypto --bench crypto --all-features. Absolute figures are hardware-dependent — the point is the order of magnitude and that the numbers are tracked, not hand-waved.

Note

The cheap operations cost nanoseconds to microseconds; the only deliberately slow step is the memory-hard KDF, which is a security control you dial in — not a hot loop. Optimisation is a standing project premise, but it never outranks a constant-time, zeroize, or no-oracle guarantee.


🧪 Testing & Quality

Authentication is critical infrastructure, so the suite is held to a bar beyond "it compiles" — every behavior is pinned so a regression fails a test.

  • ✅ 100% line and function coverage — 19,598 lines and 2,309 functions, enforced as a release gate via cargo-llvm-cov --fail-under-lines 100 across the full cargo-hack feature matrix. Regions — finer than lines, one per branch inside an expression — sit at 96.71% and are deliberately not a gate
  • ✅ Mutation gate — cargo-mutants seeds faults into the source and the suite must catch them. The last full sweep (9 h, 2026-07-28): 1,652 mutants — 1,269 caught, 89 detected by timeout, 293 unviable, 1 survivor, which is closed on the branch that follows it. The timeouts are all container-backed Redis stores, where a mutation is detected by the test hanging rather than failing: real detection, but weaker than an assertion, so the two are reported apart rather than summed into one number. Mutants no test can kill are recorded in .cargo/mutants.toml with the reason each is equivalent. The sweep runs post-merge on main, never on a PR — it takes ~9 hours
  • ✅ Property tests + fuzzing — proptest round-trips and cargo-fuzz smoke runs over the trust-boundary parsers (JWT, PHC, base32)
  • ✅ Real-Redis E2E — atomic Lua, rotation/grace, and revocation proven against redis:8 via testcontainers
  • ✅ Edge parity — wasm-bindgen-test confirms the WASM verifier accepts a token signed by the backend
  • ✅ Supply chain — cargo-deny (advisories/licenses/bans/sources), cargo-vet, a dependency budget, and cargo-public-api + cargo-semver-checks on every PR
cargo test --workspace --all-features      # unit + integration
cargo llvm-cov --workspace --all-features  # 100% line/function gate
cargo mutants                              # mutation testing
cargo deny check                           # supply-chain policy
wasm-pack test --node bindings/bymax-auth-wasm

Note

Line coverage proves a line executed; mutation testing proves a test would fail if that line were wrong. Both run in CI, alongside a wasm32-unknown-unknown build that guarantees the edge crate stays free of server dependencies.


📖 API Reference

HTTP Endpoints

Route groups mount only when their feature and runtime toggle are enabled, so an unconfigured group contributes zero routes. Paths are shown under the default auth prefix. POST /auth/logout and POST /auth/platform/logout are public on purpose: the refresh token authorizes them, so a caller whose access token has expired can still sign out.

Method Path Guard / Auth Description
POST /auth/register Public Register a dashboard user and issue tokens
POST /auth/login Public Authenticate (may return an MFA challenge)
POST /auth/logout Public (refresh token, cookie or body) Revoke the access jti and the refresh session
POST /auth/refresh Public (refresh cookie) Rotate the refresh token, issue a new access token
GET /auth/me AuthUser Current dashboard user
POST /auth/verify-email Public Verify email with an OTP
POST /auth/resend-verification Public Resend the email-verification OTP
POST /auth/password/forgot-password Public Request a password reset (token or OTP)
POST /auth/password/reset-password Public Submit a new password
POST /auth/password/verify-otp Public Verify a password-reset OTP
POST /auth/password/resend-otp Public Resend the password-reset OTP
POST /auth/password/change AuthUser + UserStatus Change the password, proving the current one
POST /auth/mfa/setup AuthUser + VerifiedUser Generate the TOTP secret + recovery codes
POST /auth/mfa/verify-enable AuthUser + VerifiedUser Confirm setup and enable MFA
POST /auth/mfa/challenge Public (MFA temp token) Submit a TOTP / recovery code after login
POST /auth/mfa/disable AuthUser + VerifiedUser Disable MFA
POST /auth/mfa/recovery-codes AuthUser + VerifiedUser Regenerate recovery codes (TOTP-gated)
GET /auth/sessions AuthUser, UserStatus List active sessions
POST /auth/sessions/revoke-all AuthUser, UserStatus Revoke every session except the caller's own
DELETE /auth/sessions/:id AuthUser, UserStatus Revoke a specific session (ownership-checked)
POST /auth/invitations AuthUser + UserStatus Create a tenant invitation
POST /auth/invitations/accept Public Accept an invitation and create the user
POST /auth/invitations/revoke AuthUser + UserStatus Withdraw a pending invitation
POST /auth/email/change AuthUser + UserStatus Request an address change (re-proves the password)
POST /auth/email/change/confirm Public Confirm it with the token sent to the new address
POST /auth/platform/login Public Platform-admin login (separate context)
POST /auth/platform/mfa/challenge Public Platform-admin MFA challenge
GET /auth/platform/me PlatformUser Current platform admin
POST /auth/platform/mfa/setup PlatformUser Generate the platform admin's TOTP secret + recovery codes
POST /auth/platform/mfa/verify-enable PlatformUser Confirm setup and enable MFA
POST /auth/platform/mfa/disable PlatformUser Disable MFA
POST /auth/platform/mfa/recovery-codes PlatformUser Regenerate recovery codes (TOTP-gated)
POST /auth/platform/logout Public (refresh token in the body) Revoke platform tokens
POST /auth/platform/refresh Public (platform refresh cookie) Rotate the platform refresh token
DELETE /auth/platform/sessions PlatformUser Revoke all platform sessions
GET /auth/oauth/:provider Public Initiate the OAuth authorize redirect
GET /auth/oauth/:provider/callback Public Handle the callback, exchange the code, issue tokens
POST /auth/ws-ticket AuthUser, UserStatus, MfaSatisfied Mint a single-use WebSocket upgrade ticket
GET /auth/workspaces UserStatus List the caller's workspaces (cursor-paged)
POST /auth/workspaces UserStatus Create a workspace owned by the caller
PATCH /auth/workspaces/:workspaceId RequireWorkspace (workspaces.permissions.manage_workspace) Rename a workspace
GET /auth/workspaces/:workspaceId/access RequireWorkspace<AnyWorkspaceMember> The workspace and the caller's role in it
GET /auth/workspaces/:workspaceId/members RequireWorkspace (workspaces.permissions.view_members) List the members (cursor-paged)
POST /auth/workspaces/:workspaceId/switch RequireWorkspace<AnyWorkspaceMember> Record the workspace as the caller's last active one
POST /auth/workspaces/:workspaceId/schedule-deletion RequireWorkspace (workspaces.permissions.delete_workspace) Schedule deletion, re-proving the password
POST /auth/workspaces/:workspaceId/restore RequireWorkspace (workspaces.permissions.delete_workspace) Undo a scheduled deletion within its grace period
PATCH /auth/workspaces/:workspaceId/members/:userId RequireWorkspace (workspaces.permissions.manage_members) Change a member's role
DELETE /auth/workspaces/:workspaceId/members/:userId RequireWorkspace (workspaces.permissions.manage_members) Remove a member
POST /auth/workspaces/:workspaceId/leave RequireWorkspace<AnyWorkspaceMember> Leave the workspace
POST /auth/workspaces/:workspaceId/transfer-ownership RequireWorkspace<AnyWorkspaceMember> (the engine requires the owner) Hand ownership to another member
GET /auth/workspaces/:workspaceId/invitations RequireWorkspace (workspaces.permissions.manage_members) List the pending invitations (cursor-paged)
POST /auth/workspaces/:workspaceId/invitations RequireWorkspace (workspaces.permissions.manage_members) Invite an address with a role
POST /auth/workspaces/:workspaceId/invitations/resend RequireWorkspace (workspaces.permissions.manage_members) Send a pending invitation again
POST /auth/workspaces/:workspaceId/invitations/revoke RequireWorkspace (workspaces.permissions.manage_members) Withdraw a pending invitation
POST /auth/workspaces/invitations/preview Public Say what an invitation token is for

GET /auth/oauth/:provider plants an HttpOnly oauth_state cookie carrying the flow's state, and the callback refuses any request that does not send it back — the binding RFC 6749 §10.12 requires, without which an attacker can hand a victim a callback URL and have the victim's browser complete the attacker's login. The router's cookie layer handles this; a custom mount must keep CookieManagerLayer in place.

Extractors (Axum FromRequestParts)

Extractor Purpose
AuthUser Validates the dashboard JWT (cookie or Authorization header)
OptionalAuthUser Routes that differ for anonymous vs. authenticated users
RequireRole<R> Hierarchical role check
PlatformUser Platform-admin JWT validation
RequirePlatformRole<R> Platform role hierarchy enforcement
CurrentUser Extracts the validated claims
SelfOrAdmin Ownership-or-admin access
UserStatus Blocks accounts in a blocked status (Redis-cached status), and an unverified address when email_verification.required
VerifiedUser The same rule as UserStatus, named for routes that must never be reachable from an unproven address (MFA management)
RequireWorkspace<P> Resolves the {workspaceId} path segment to the caller's membership and checks the policy P (AnyWorkspaceMember accepts any active member)
WsAuthUser WebSocket upgrade authenticated by a single-use ticket (ticket query parameter)
WsAuthUserFromHeader WebSocket upgrade authenticated by the access JWT in the Authorization: Bearer header
CurrentApiKey The service API key a request was admitted with; only behind require_api_key_scopes
MfaSatisfied Enforces a completed MFA verification on the request

Client (@bymax-one/rust-auth/client)

Export Purpose
createAuthClient() Typed AuthClient: login, register, logout, refresh, getMe, mfaChallenge(tempToken, code), forgotPassword, resetPassword. baseUrl is required; routePrefix rebases the paths; authFetch reuses an existing wrapper
createAuthFetch() A fetch wrapper with credentials, a timeout and a single-flight refresh-and-retry on a 401 (refreshEndpoint, default /api/auth/client-refresh; onSessionExpired)
AuthClientError The error thrown for a non-2xx answer: the backend's auth.* code, the HTTP status and any details

The client has a typed method only for the endpoints above. Call every other route through authFetch.

A login can need a second factor. login() resolves a LoginResult, which is either an AuthResult or an MfaChallengeResult ({ mfaRequired: true, mfaTempToken }). Complete it through the client, since no hook wraps it:

const result = await client.login({ email, password })
if ('mfaRequired' in result) {
  await client.mfaChallenge(result.mfaTempToken, totpCode)
}

React Hooks

AuthProvider takes client (an AuthClient), onSessionExpired and revalidateInterval (milliseconds, default 300000, 0 disables the background check).

Hook Returns
useSession() { user, status, isLoading, refresh(), lastValidation } — session state + revalidate; user is null while loading or unauthenticated
useAuth() { login(), logout(), register(), forgotPassword(), resetPassword() } — auth actions
useAuthStatus() { isAuthenticated, isLoading } — derived state

Next.js Factories

Factory Type Purpose
createAuthProxy() Proxy config Auth-aware proxy for proxy.ts. Config: accessTokenSecret, expectedIssuer, expectedAudience, loginPath, publicPaths, silentRefreshPath, roleRules, blockedStatuses, maxRedirects, routePrefix
createSilentRefreshHandler() GET handler Refreshes cookie-to-cookie through the backend, relays the rotated cookies, then redirects to redirectTo (open-redirect-guarded)
createClientRefreshHandler() POST handler Client-triggered token refresh
createLogoutHandler() POST handler Clear tokens and session
verifyJwtToken(token, secret, binding?, expectedType?) Edge helper WASM-backed HS256 verification (server only). Pass expectedType (for example 'dashboard'), or a valid mfa_challenge token also verifies

The /nextjs subpath also exports decodeJwtToken (reads a token without checking its signature), getUserId, getUserRole, getTenantId, isTokenExpired, buildSilentRefreshUrl, resolveSafeDestination, the cookie helpers getSetCookieHeaders, dedupeSetCookieHeaders and parseSetCookieHeader, isBackgroundRequest, and the route constants SILENT_REFRESH_ROUTE, CLIENT_REFRESH_ROUTE and LOGOUT_ROUTE.

Shared (@bymax-one/rust-auth/shared)

Generated from the Rust source: the wire types (AuthResult, LoginResult, MfaChallengeResult, the user and claims types, the error envelope), the error codes, AUTH_ROUTES and AUTH_ROUTE_PREFIX, the cookie names and path constants, and AuthClientError.


🗺️ Roadmap

The items below are on deck for future releases. None ship today — the list exists so contributors can see where the workspace is headed and where help is most useful. Open an issue to discuss priorities or propose a design.

Area Item Status
Registry publishing OIDC trusted publishing, the release workflow, SBOM/attestation publishing, and the tag ↔ version gate (P12's second half) Deferred
OAuth providers A provider trait implementation set beyond Google — GitHub, Microsoft, Apple — behind the existing OAuthProvider seam Planned
Error-message i18n Locale presets for AuthError's user-facing messages (defaults are English) Planned
Passwordless / magic link Single-use link flow reusing generate_secure_token and the EmailProvider seam Exploring
Passkeys / WebAuthn WebAuthn as an MFA method, and eventually a first factor, behind its own feature Exploring
Per-tenant configuration Per-tenant overrides for session limits, MFA enforcement, and password policy, resolved per request Exploring
Pluggable password policy A PasswordPolicy seam for complexity classes and per-tenant rules (the breach check already ships as PasswordBreachChecker) Planned
Additional adapters An actix-web adapter alongside bymax-auth-axum, sharing the same engine and wire contract Exploring

Track progress and discuss proposals on the issues board. Phase-level status for the work already delivered lives in docs/development_plan.md.


🤝 Contributing

Contributions are welcome! Please read the contributing guidelines before opening a pull request.

# Clone the repository
git clone https://github.com/bymaxone/rust-auth.git
cd rust-auth

# Build the workspace
cargo build --workspace --all-features

# Run the test suite
cargo test --workspace --all-features

# Lint + format
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo fmt --all -- --check

# Frontend package
cd packages/rust-auth && npm ci && npm run build:wasm && npm run build

Runnable apps live under examples/ (three Axum services, a React + Vite SPA, a Next.js edge app, and a dogfood integration). The release and publishing process — and the one-time OIDC / protected-environment setup it requires — is documented in docs/RELEASE.md.


🔒 Security Policy

If you discover a security vulnerability, please do not open a public issue. Email support@bymax.one with the details. We take security seriously and will respond promptly. See SECURITY.md.


📄 License

MIT © Bymax One


Built with ❤️ and 🦀 by Bymax One

About

Full-stack authentication library for Rust (Axum 0.8), React 19 & Next.js 16 — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready. Pure-Rust crypto with WebAssembly edge verification.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages