Authsome

Architecture

How Authsome packages fit together.

Authsome is organized around a central Engine type that orchestrates authentication across a composable set of plugins, store backends, and bridge interfaces. Understanding this structure helps you make informed decisions about which components to use and how to extend the system.

High-level diagram

┌─────────────────────────────────────────────────────────────────────────────┐
│                           Engine (authsome.Engine)                          │
│                                                                             │
│  SignUp / SignIn / SignOut / Refresh / GetMe / UpdateMe                     │
│  ForgotPassword / ResetPassword / ChangePassword / VerifyEmail              │
│  Impersonate / RBAC / Webhooks / Devices / Environments                     │
├──────────────────────────┬──────────────────────────────────────────────────┤
│        Plugin System     │        Strategy Registry                         │
│                          │                                                  │
│  plugin.Registry         │  strategy.Registry                               │
│  BeforeSignUp            │    password strategy (priority 10)               │
│  AfterSignUp             │    social strategy (priority 20)                 │
│  BeforeSignIn            │    passkey strategy (priority 30)                │
│  AfterSignIn             │    sso strategy (priority 40)                   │
│  BeforeSessionCreate     │    magiclink strategy (priority 50)              │
│  AfterUserDelete         │    phone strategy (priority 60)                  │
│  RouteProvider           │    (priority determines fallback order)          │
│  MigrationProvider       │                                                  │
├──────────────────────────┴──────────────────────────────────────────────────┤
│                          Hook Bus (hook.Bus)                                 │
│  40+ action types: ActionSignUp, ActionSignIn, ActionSignOut,               │
│  ActionRefresh, ActionUserUpdate, ActionSessionRevoke, ActionImpersonate,   │
│  ActionAdminBanUser, ActionRoleCreate, ActionEnvironmentCreate, ...         │
├─────────────────────────────────────────────────────────────────────────────┤
│                         Bridge Interfaces                                    │
│  Chronicle (audit) · Relay (webhooks) · Mailer · SMSSender · Herald        │
│  Warden (authz) · Keysmith (API keys) · Vault (secrets) · Dispatch (jobs)  │
│  Ledger (billing) · MetricsCollector                                        │
├──────────────────────────┬──────────────────────────────────────────────────┤
│       store.Store        │     Token Formats                                │
│  (composite interface)   │                                                  │
│  UserStore               │  tokenformat.Format interface                   │
│  SessionStore            │    Opaque (64-char hex, default)                 │
│  DeviceStore             │    JWT (OIDC claims, per-app)                    │
│  WebhookStore            │                                                  │
│  OrganizationStore       │                                                  │
│  EnvironmentStore        │                                                  │
│  RBACStore               │                                                  │
│  FormConfigStore         │                                                  │
├──────┬───────────────────┴──────────────────────────────────────────────────┤
│memory│  postgres  │  sqlite  │  mongo                                       │
└──────┴────────────┴──────────┴──────────────────────────────────────────────┘

Engine

The Engine is the top-level orchestrator. It holds references to the store, plugin registry, strategy registry, hook bus, and all bridge interfaces. All authentication logic flows through the engine.

import "github.com/xraph/authsome"

eng, err := authsome.New(
    authsome.WithStore(myStore),
    authsome.WithPlugin(passwordPlugin),
    authsome.WithWarden(wardenEngine),    // optional: Warden for RBAC
    authsome.WithChronicle(chronicle),    // optional: audit trail
    authsome.WithMailer(mailer),          // optional: transactional email
)

The engine is constructed with authsome.New(opts...) and activated with eng.Start(ctx). It exposes the full service API as methods on *Engine.

Store abstraction

All persistence goes through the store.Store composite interface. Swap the backend at construction time with no other changes.

// Development: no external dependencies
store := memory.New()

// Production: PostgreSQL
store, err := postgres.New(ctx, "postgres://user:pass@host:5432/db")

// Alternative: SQLite for embedded applications
store, err := sqlite.New(ctx, "./auth.db")

// Alternative: MongoDB for document-oriented workloads
store, err := mongo.New(ctx, "mongodb://localhost:27017", "authdb")

The composite interface covers:

Sub-interfaceResponsibility
UserStoreUser CRUD, lookup by email/username/phone
SessionStoreSession CRUD, lookup by token/refresh token
DeviceStoreDevice fingerprinting and trusted device management
WebhookStoreWebhook endpoint registration and delivery records
OrganizationStoreOrgs, members, teams, invitations
EnvironmentStoreEnvironment isolation per app
RBACStoreRoles, permissions, user role assignments
FormConfigStoreDynamic form field definitions
AppSessionConfigStorePer-app session configuration overrides
PasswordResetStorePassword reset tokens
VerificationStoreEmail/phone verification tokens
PasswordHistoryStoreHistoric password hashes for reuse prevention

Plugin system

Plugins are the primary extension point. Each plugin implements the plugin.Plugin base interface and any combination of optional lifecycle interfaces.

// Base interface — all plugins must implement this.
type Plugin interface {
    Name() string
}

// Optional lifecycle interfaces a plugin may implement:
type OnInit interface {
    OnInit(ctx context.Context, e PluginEngine) error
}
type RouteProvider interface {
    RegisterRoutes(r forge.Router, e PluginEngine)
}
type MigrationProvider interface {
    Migrations(driver string) []migrate.Migration
}
type BeforeSignUp interface {
    OnBeforeSignUp(ctx context.Context, req *account.SignUpRequest) error
}
type AfterSignUp interface {
    OnAfterSignUp(ctx context.Context, u *user.User, sess *session.Session)
}
type BeforeSignIn interface {
    OnBeforeSignIn(ctx context.Context, req *account.SignInRequest) error
}
type AfterSignIn interface {
    OnAfterSignIn(ctx context.Context, u *user.User, sess *session.Session)
}
type AuthMethodContributor interface {
    AuthMethods() []AuthMethod
}

The engine's plugin registry discovers capabilities at registration time using type assertions.

Built-in plugins

PluginImportContributes
passwordgithub.com/xraph/authsome/plugins/passwordPassword strategy, signup/signin/reset routes
magiclinkgithub.com/xraph/authsome/plugins/magiclinkPasswordless email strategy, magic link routes
socialgithub.com/xraph/authsome/plugins/socialOAuth2 strategies for Google, GitHub, Microsoft, Apple
ssogithub.com/xraph/authsome/plugins/ssoOIDC/SAML enterprise SSO strategy and connection management
passkeygithub.com/xraph/authsome/plugins/passkeyWebAuthn/FIDO2 strategy, registration/authentication ceremonies
mfagithub.com/xraph/authsome/plugins/mfaTOTP and SMS OTP second-factor challenges
phonegithub.com/xraph/authsome/plugins/phonePhone number sign-in via OTP
oauth2providergithub.com/xraph/authsome/plugins/oauth2providerBecome an OAuth2 authorization server
organizationgithub.com/xraph/authsome/plugins/organizationOrg/team/invitation management routes
apikeygithub.com/xraph/authsome/plugins/apikeyAPI key issuance and verification
consentgithub.com/xraph/authsome/plugins/consentUser consent management for OAuth2 flows
emailgithub.com/xraph/authsome/plugins/emailEmail template management
notificationgithub.com/xraph/authsome/plugins/notificationMulti-channel notification delivery

Hook bus

The hook bus emits structured events for every significant operation. Listeners can react to events for metrics, audit, downstream notifications, or custom business logic.

import "github.com/xraph/authsome/hook"

// Subscribe to sign-up events.
eng.Hooks().Subscribe(hook.ActionSignUp, func(ctx context.Context, event *hook.Event) {
    log.Printf("new signup: user=%s app=%s", event.ResourceID, event.Tenant)
})

Action types

The hook bus defines 40+ named action constants:

CategoryActions
AuthActionSignUp, ActionSignIn, ActionSignOut, ActionRefresh, ActionAccountLocked
UserActionUserUpdate, ActionUserDelete, ActionDataExport, ActionAccountDeletion
SessionActionSessionRevoke, ActionImpersonate
AdminActionAdminBanUser, ActionAdminUnbanUser, ActionAdminDeleteUser
RBACActionRoleCreate, ActionRoleUpdate, ActionRoleDelete, ActionRoleAssign, ActionRoleUnassign
WebhookActionWebhookCreate, ActionWebhookUpdate, ActionWebhookDelete
EnvironmentActionEnvironmentCreate, ActionEnvironmentUpdate, ActionEnvironmentDelete, ActionEnvironmentClone
DeviceActionDeviceTrust, ActionDeviceRegister
MFAActionMFAEnroll, ActionMFAChallenge, ActionMFAVerify

Strategy registry

Authentication strategies are registered with a priority. When a sign-in request arrives, the engine selects the highest-priority strategy that accepts the request.

import "github.com/xraph/authsome/strategy"

// Plugins register strategies through the plugin.AuthMethodContributor interface.
// You can also register strategies directly:
eng.RegisterStrategy(myStrategy, 5)

Lower priority values are evaluated first (priority 1 runs before priority 10). This allows you to insert custom strategies that intercept before built-in ones.

Bridges

Bridges are optional integration interfaces. When a bridge is not configured, the corresponding functionality is silently skipped (fail-open).

BridgeInterfaceUsed for
Chroniclebridge.ChronicleAudit trail — records every auth event with severity and outcome
Relaybridge.EventRelayWebhook delivery — forwards hook events to registered endpoints
Mailerbridge.MailerTransactional email for magic links, verifications, password resets
SMSSenderbridge.SMSSenderSMS delivery for phone OTP and MFA SMS codes
Heraldbridge.HeraldUnified multi-channel notification system (replaces Mailer + SMS)
Wardenbridge.AuthorizerAuthorization engine for RBAC/ReBAC/ABAC policy evaluation
Keysmithbridge.KeyManagerAPI key management with rotation, scopes, and usage tracking
Vaultbridge.VaultSecrets management and feature flag access
Dispatchbridge.DispatcherBackground job queue for async tasks
Ledgerbridge.LedgerBilling/metering integration
Metricsbridge.MetricsCollectorCounter and histogram metrics for observability

Bridge adapters

Each bridge ships with one or more pre-built adapters:

import (
    "github.com/xraph/authsome/bridge/chronicleadapter"
    "github.com/xraph/authsome/bridge/maileradapter"
    "github.com/xraph/authsome/bridge/smsadapter"
    "github.com/xraph/authsome/bridge/relayadapter"
)

// Chronicle: wrap a Chronicle engine
authsome.WithChronicle(chronicleadapter.New(chronicleEngine))

// Mailer: SMTP or Resend
authsome.WithMailer(maileradapter.NewSMTP(smtpConfig))
authsome.WithMailer(maileradapter.NewResend(resendAPIKey))

// SMS: Twilio
authsome.WithSMSSender(smsadapter.NewTwilio(twilioConfig))

// Relay: wrap a Relay engine
authsome.WithEventRelay(relayadapter.New(relayEngine))

API layer and middleware

The engine integrates with Forge-based HTTP applications through the extension system.

import "github.com/xraph/authsome/extension"

// Register as a Forge extension (auto-wires store from DI container).
app.Register(extension.New(
    extension.WithPlugin(password.New()),
    extension.WithPlugin(social.New(socialCfg)),
))

Standalone middleware is available for non-Forge applications:

import "github.com/xraph/authsome/middleware"

// Extract and validate Bearer token, inject user into context.
mux.Handle("/api/", middleware.RequireAuth(eng)(apiHandler))

// Require a specific permission (delegates to Warden if configured).
mux.Handle("/api/admin/", middleware.RequirePermission(eng, "admin", "users")(adminHandler))

// Apply per-endpoint rate limiting.
mux.Handle("/api/", middleware.RateLimit(eng)(apiHandler))

Token formats

Access tokens are opaque 64-character hex strings by default. Switch to signed JWTs per app for use cases that require client-side validation or OIDC compatibility.

import "github.com/xraph/authsome/tokenformat"

// JWT format with RSA-256 signing key.
jwtFmt, err := tokenformat.NewJWT(tokenformat.JWTConfig{
    Algorithm:  "RS256",
    PrivateKey: rsaPrivateKey,
    PublicKey:  rsaPublicKey,
    Issuer:     "https://auth.myapp.com",
    Audience:   []string{"https://api.myapp.com"},
})

// Register JWT format for a specific app.
authsome.WithJWTFormat("myapp", jwtFmt)

When JWT is configured for an app, all sessions created for that app receive a signed JWT as the access token. The refresh token remains opaque.

Package index

PackageImport pathPurpose
authsomegithub.com/xraph/authsomeRoot — Engine, Config, Option, entity type aliases
idgithub.com/xraph/authsome/idTypeID-based identifiers with 27 prefixes
accountgithub.com/xraph/authsome/accountSignUpRequest, SignInRequest, session creation, password hashing
usergithub.com/xraph/authsome/userUser entity and UserQuery/UserList pagination types
sessiongithub.com/xraph/authsome/sessionSession entity
devicegithub.com/xraph/authsome/deviceDevice entity and fingerprinting
hookgithub.com/xraph/authsome/hookHook bus, Event, 40+ action constants
plugingithub.com/xraph/authsome/pluginPlugin interfaces (base + 15 capability interfaces)
strategygithub.com/xraph/authsome/strategyStrategy interface and priority registry
bridgegithub.com/xraph/authsome/bridge11 bridge interfaces and their adapters
tokenformatgithub.com/xraph/authsome/tokenformatOpaque and JWT token format implementations
ceremonygithub.com/xraph/authsome/ceremonyShort-lived auth ceremony state store
rbacgithub.com/xraph/authsome/rbacRole, Permission, UserRole, RBAC store interface
organizationgithub.com/xraph/authsome/organizationOrg, Member, Team, Invitation entity types
environmentgithub.com/xraph/authsome/environmentEnvironment entity and clone operations
formconfiggithub.com/xraph/authsome/formconfigDynamic form field definitions and submission validation
webhookgithub.com/xraph/authsome/webhookWebhook entity and delivery records
middlewaregithub.com/xraph/authsome/middlewareHTTP middleware: auth extraction, RBAC, rate limiting, IP access
storegithub.com/xraph/authsome/storeComposite Store interface and sentinel errors
store/memorygithub.com/xraph/authsome/store/memoryIn-memory store (testing and development)
store/postgresgithub.com/xraph/authsome/store/postgresPostgreSQL store
store/sqlitegithub.com/xraph/authsome/store/sqliteSQLite store
store/mongogithub.com/xraph/authsome/store/mongoMongoDB store
extensiongithub.com/xraph/authsome/extensionForge extension adapter

On this page