authall

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 29 Imported by: 0

README

Auth-All

Auth-All is an authentication framework that runs inside a Go application.

It provides the capabilities a developer normally assembles from several libraries: users, accounts, database-backed sessions, email and password authentication, email verification, password reset, magic links, OAuth, account linking, plugins, schema tooling, an OpenAPI contract, and a generated TypeScript client.

Auth-All is not an identity server. The application keeps its database, its HTTP server, and its user interface.

Install

go get github.com/alternayte/auth-all

The TypeScript client is a separate npm package:

npm install @alternayte/auth-all-client

The operator tool is available as a prebuilt binary on the releases page. A Go user can also install it directly:

go install github.com/alternayte/auth-all/cmd/auth-all@latest

Use

auth, err := authall.New(
    authall.WithStore(postgres.New(db)),
    authall.WithBaseURL("https://app.example.com"),
    authall.WithEmailPassword(),
    authall.WithEmailSender(sender),
    authall.WithProvider(
        github.New(
            github.WithClientID(clientID),
            github.WithClientSecret(clientSecret),
        ),
    ),
    authall.WithPlugins(
        magiclink.New(),
    ),
)
if err != nil {
    log.Fatal(err)
}

mux.Handle("/api/auth/", auth.Handler())

Create the tables one time before the first start:

go run github.com/alternayte/auth-all/cmd/auth-all migrate \
    --driver postgres --dsn "$DATABASE_URL"

Properties

  • net/http native and framework agnostic.
  • The application owns the database. PostgreSQL and SQLite are supported.
  • Secure defaults. Opaque session tokens, hashed tokens at rest, Argon2id password hashing, OAuth state validation, PKCE where the provider supports it, and conservative account linking.
  • Plugins are first class. The official Magic Link plugin uses the same public plugin API that a third-party plugin uses.
  • One OpenAPI contract produces the official TypeScript client.

Documentation

Guide Content
Getting started The first integration, step by step.
Email and password Sign-up, sign-in, verification, and reset.
Sessions Session storage, cookies, and revocation.
Magic Link The official sign-in link plugin.
GitHub OAuth GitHub sign-in.
Google OAuth Google sign-in.
Account management Password change, address change, and account delete.
Account linking The linking policy and its threats.
PostgreSQL The PostgreSQL adapter.
SQLite The SQLite adapter.
Migrations and the CLI Schema operations.
Plugin authors The public extension surface.
TypeScript client The generated client.
Deployment Cookies, origins, proxies, and a troubleshooting table.
Security model Threat assumptions and defenses.

Two official examples show a complete integration:

Development

The repository exposes one command:

just verify

It formats, analyses, tests, starts the PostgreSQL test container, runs the race detector, checks the generated artifacts, tests the TypeScript client, builds the examples, and writes artifacts/v1-verification.md.

License

MIT. See LICENSE.

Documentation

Overview

Package authall is an embedded authentication framework for Go applications.

Auth-All runs inside the application, stores its data in the database the application owns, and integrates through net/http.

Index

Constants

View Source
const (
	DefaultBasePath   = "/api/auth"
	DefaultCookieName = "authall.session"
	// DefaultSessionTTL is the absolute lifetime of a session. A session ends
	// at this age, even when the person stays active.
	DefaultSessionTTL = 30 * 24 * time.Hour
	// DefaultSessionIdleTimeout ends a session that saw no request for this
	// long.
	DefaultSessionIdleTimeout = 7 * 24 * time.Hour
	// DefaultSessionTouchInterval limits how often a session read writes
	// last_seen_at.
	DefaultSessionTouchInterval = 5 * time.Minute
	DefaultVerificationTTL      = 24 * time.Hour
	DefaultPasswordResetTTL     = time.Hour
	DefaultOAuthStateTTL        = 15 * time.Minute
)

Defaults used when an option is not supplied.

View Source
const Version = "1.0.0"

Version is the Auth-All API contract version.

Variables

View Source
var (
	ErrInvalidRequest     = apierr.ErrInvalidRequest
	ErrInvalidCredentials = apierr.ErrInvalidCredentials
	ErrEmailAlreadyExists = apierr.ErrEmailAlreadyExists
	ErrWeakPassword       = apierr.ErrWeakPassword
	ErrInvalidToken       = apierr.ErrInvalidToken
	ErrUnauthorized       = apierr.ErrUnauthorized
	ErrForbidden          = apierr.ErrForbidden
	ErrNotFound           = apierr.ErrNotFound
	ErrLastAuthMethod     = apierr.ErrLastAuthMethod
	// ErrNoPasswordCredential reports that the account has no password. An
	// OAuth-only user reaches it.
	ErrNoPasswordCredential = apierr.ErrNoPasswordCredential
)

Re-exported public errors.

Functions

This section is empty.

Types

type AccountLinkingOptions

type AccountLinkingOptions struct {
	// AllowVerifiedEmailAutoLink links an external account to an existing user
	// when the provider proves the same verified email address. It is off by
	// default, because email matching alone allows account takeover through a
	// provider that does not verify addresses.
	AllowVerifiedEmailAutoLink bool
}

AccountLinkingOptions configures how an external account joins a user.

type Argon2Params

type Argon2Params = crypto.Argon2Params

Argon2Params re-exports the password hashing parameters.

func DefaultArgon2Params

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params returns the default password hashing cost.

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth is a configured Auth-All instance.

func New

func New(opts ...Option) (*Auth, error)

New builds an Auth-All instance from functional options.

func (*Auth) Accounts

func (a *Auth) Accounts(ctx context.Context, userID string) ([]store.Account, error)

Accounts returns the external accounts of one user.

func (*Auth) BasePath

func (a *Auth) BasePath() string

BasePath returns the configured base path.

func (*Auth) CheckSchema

func (a *Auth) CheckSchema(ctx context.Context) error

CheckSchema reports an actionable error when the database schema is missing or outdated. Auth-All never migrates a schema on its own.

func (*Auth) Cleanup

func (a *Auth) Cleanup(ctx context.Context) error

Cleanup removes expired sessions, tokens, and OAuth states.

func (*Auth) CreateUser

func (a *Auth) CreateUser(ctx context.Context, in CreateUserInput) (*store.User, error)

CreateUser creates a user, and a password credential when a password is supplied. It returns apierr.ErrEmailAlreadyExists for a duplicate address.

func (*Auth) GetUser

func (a *Auth) GetUser(ctx context.Context, id string) (*store.User, error)

GetUser returns one user by id.

func (*Auth) GetUserByEmail

func (a *Auth) GetUserByEmail(ctx context.Context, address string) (*store.User, error)

GetUserByEmail returns one user by the normalized form of an address.

func (*Auth) Handler

func (a *Auth) Handler() http.Handler

Handler returns the Auth-All HTTP handler. Mount it at the configured base path, for example mux.Handle("/api/auth/", auth.Handler()).

func (*Auth) Hooks

func (a *Auth) Hooks() *hook.Hooks

Hooks returns the lifecycle hook registry of the instance.

func (*Auth) Migrate

func (a *Auth) Migrate(ctx context.Context) ([]schema.Statement, error)

Migrate applies the effective schema. It runs only when the application or the command line tool calls it.

func (*Auth) MigrationPlan

func (a *Auth) MigrationPlan(ctx context.Context) ([]schema.Statement, error)

MigrationPlan returns the statements that are not applied yet.

func (*Auth) MigrationSQL

func (a *Auth) MigrationSQL(d schema.Dialect) ([]schema.Statement, error)

MigrationSQL returns the complete deterministic DDL for one dialect. It needs no database connection.

func (*Auth) OpenAPI

func (a *Auth) OpenAPI() *openapi.Document

OpenAPI returns the effective OpenAPI document of the enabled API.

func (*Auth) RevokeSession

func (a *Auth) RevokeSession(ctx context.Context, sessionID string) error

RevokeSession revokes one session by id.

func (*Auth) RevokeUserSessions

func (a *Auth) RevokeUserSessions(ctx context.Context, userID string) (int, error)

RevokeUserSessions revokes every session of one user and returns the count.

func (*Auth) Routes

func (a *Auth) Routes() []RouteInfo

Routes returns every mounted route of the enabled API.

func (*Auth) Schema

func (a *Auth) Schema() *schema.Schema

Schema returns the effective schema of core plus every registered plugin.

func (*Auth) Session

func (a *Auth) Session(ctx context.Context, r *http.Request) (*store.Session, error)

Session returns the session of a request. It returns nil when the request carries no valid session.

func (*Auth) User

func (a *Auth) User(ctx context.Context, r *http.Request) (*store.User, error)

User returns the authenticated user of a request. It returns nil when the request carries no valid session.

func (*Auth) VerifyEmailToken

func (a *Auth) VerifyEmailToken(ctx context.Context, token string) (*store.User, error)

VerifyEmailToken consumes an email verification token and records that the user controls the address. It exists so an application can verify an address from its own page without a call to the HTTP API.

type Code

type Code = apierr.Code

Code is a stable machine-readable error code.

type CookieOptions

type CookieOptions struct {
	Name     string
	Domain   string
	Path     string
	SameSite http.SameSite
	// Secure defaults to true. Set it to false only for local development
	// over plain HTTP.
	Secure *bool
}

CookieOptions configures the session cookie.

type CreateUserInput

type CreateUserInput struct {
	Email       string
	Password    string
	DisplayName string
	ImageURL    string
	// EmailVerified marks the address as already proven.
	EmailVerified bool
}

CreateUserInput describes a user created through the programmatic API.

type EmailPasswordOptions

type EmailPasswordOptions struct {
	// RequireEmailVerification blocks sign-in until the address is verified.
	RequireEmailVerification bool
	// SendVerificationOnSignUp sends a verification email after sign-up. It is
	// implied by RequireEmailVerification.
	SendVerificationOnSignUp bool
	// VerifyEmailURL is the application page that receives a verification
	// token. Auth-All appends the token query parameter. The default is
	// BaseURL + /verify-email.
	VerifyEmailURL string
	// ResetPasswordURL is the application page that receives a password reset
	// token. Auth-All appends the token query parameter. The default is
	// BaseURL + /reset-password.
	ResetPasswordURL string
	// ChangeEmailURL is the application page that receives an email change
	// token. Auth-All appends the token query parameter. The default is
	// BaseURL + /change-email.
	ChangeEmailURL string
	// DeleteAccountURL is the application page that receives an account delete
	// token. Auth-All appends the token query parameter. The default is
	// BaseURL + /delete-account.
	DeleteAccountURL string
}

EmailPasswordOptions configures email and password authentication.

type Error

type Error = apierr.Error

Error is the public Auth-All error type. Its code is part of the public API compatibility surface.

type Option

type Option func(*config)

Option configures Auth-All.

func WithAccountLinking

func WithAccountLinking(o AccountLinkingOptions) Option

WithAccountLinking configures the account linking policy.

func WithArgon2Params

func WithArgon2Params(p crypto.Argon2Params) Option

WithArgon2Params configures the password hashing cost. A sign-in rehashes a password that was stored with different parameters.

func WithBasePath

func WithBasePath(p string) Option

WithBasePath sets the mount path of the HTTP handler. The default is /api/auth.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL sets the absolute public URL of the application, for example https://app.example.com. Auth-All uses it to build links and to validate redirects. It is required when an OAuth provider is configured.

func WithClock

func WithClock(now func() time.Time) Option

WithClock replaces the clock. Tests use it for deterministic expiry.

func WithCookie

func WithCookie(o CookieOptions) Option

WithCookie configures the session cookie.

func WithCookieSameSite

func WithCookieSameSite(mode http.SameSite) Option

WithCookieSameSite sets the SameSite attribute of the session cookie.

Use http.SameSiteLaxMode when the application and the API share a registrable domain, for example app.example.com and api.example.com. Use http.SameSiteNoneMode only for a true cross-site setup. A browser refuses a cookie with SameSite=None and no Secure attribute, so that pair fails the construction. See docs/guides/deployment.md.

func WithEmailPassword

func WithEmailPassword(opts ...EmailPasswordOptions) Option

WithEmailPassword enables email and password authentication.

func WithEmailSender

func WithEmailSender(s email.Sender) Option

WithEmailSender sets the email delivery boundary of the application.

func WithEventHandler

func WithEventHandler(h events.Handler) Option

WithEventHandler registers an observability handler.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger.

func WithPasswordPolicy

func WithPasswordPolicy(p PasswordPolicy) Option

WithPasswordPolicy configures the accepted passwords.

func WithPlugins

func WithPlugins(plugins ...plugin.Plugin) Option

WithPlugins registers one or more plugins.

func WithProvider

func WithProvider(providers ...oauth.Provider) Option

WithProvider registers one or more OAuth providers.

func WithRateLimiter

func WithRateLimiter(l ratelimit.Limiter) Option

WithRateLimiter sets the rate limiter for sensitive operations.

func WithSession

func WithSession(o SessionOptions) Option

WithSession configures session lifetime.

func WithSessionLifetime

func WithSessionLifetime(idle, absolute time.Duration) Option

WithSessionLifetime sets the two session deadlines.

idle ends a session that saw no request for that long. absolute ends a session at that age, even when the person stays active. One value cannot serve both, because a stolen token that stays active would never expire.

The defaults are 7 days and 30 days.

func WithStore

func WithStore(s store.Store) Option

WithStore sets the storage adapter. It is required.

func WithStrictRateLimiting

func WithStrictRateLimiting() Option

WithStrictRateLimiting fails the construction when no rate limiter is configured.

A production deployment needs a limiter. Without one, every sensitive endpoint accepts unlimited attempts, so a brute-force attack and an enumeration attack run without a bound. The default only writes a warning, because a test and a local run do not need a limiter.

func WithTokenTTL

func WithTokenTTL(o TokenTTLOptions) Option

WithTokenTTL configures one-time token lifetimes.

func WithTrustedOrigins

func WithTrustedOrigins(origins ...string) Option

WithTrustedOrigins adds browser origins that can call state-changing endpoints. The origin of BaseURL is always trusted. A credentialed wildcard origin is never allowed.

func WithTrustedProxies

func WithTrustedProxies(cidrs ...string) Option

WithTrustedProxies declares the reverse proxies that stand in front of the application. Auth-All reads a forwarded client address only when the direct peer is inside one of these blocks.

Each value is a CIDR block, for example 10.0.0.0/8. A single IP address is also valid, and Auth-All treats it as one host. An invalid value fails the construction.

Auth-All ignores the X-Forwarded-For header when no trusted proxy is declared, because any client can set that header. Declare the proxies of the deployment. See docs/guides/deployment.md.

type PasswordPolicy

type PasswordPolicy struct {
	MinLength int
	MaxLength int
}

PasswordPolicy configures the accepted passwords. Auth-All does not require special characters, because a length requirement protects better.

func DefaultPasswordPolicy

func DefaultPasswordPolicy() PasswordPolicy

DefaultPasswordPolicy returns the default policy.

type RouteInfo

type RouteInfo struct {
	Method string
	// Path is the complete path, including the configured base path.
	Path string
	// PluginID names the contributing plugin. It is empty for a core route.
	PluginID string
	// Documented reports whether the route appears in the OpenAPI document.
	Documented bool
}

RouteInfo describes one mounted Auth-All route.

type SessionOptions

type SessionOptions struct {
	// TTL is the absolute lifetime. A session ends at this age, even when the
	// person stays active. The default is 30 days.
	TTL time.Duration
	// IdleTimeout ends a session that saw no request for this long. The
	// default is 7 days.
	IdleTimeout time.Duration
	// TouchInterval limits how often a session read updates last_seen_at.
	TouchInterval time.Duration
}

SessionOptions configures session lifetime.

type TokenTTLOptions

type TokenTTLOptions struct {
	EmailVerification time.Duration
	PasswordReset     time.Duration
	OAuthState        time.Duration
}

TokenTTLOptions configures one-time token lifetimes.

Directories

Path Synopsis
Package apierr defines the stable, machine-readable error contract of Auth-All.
Package apierr defines the stable, machine-readable error contract of Auth-All.
cmd
auth-all command
Command auth-all manages the Auth-All schema and generates the published contract artifacts.
Command auth-all manages the Auth-All schema and generates the published contract artifacts.
Package email defines the provider-independent email boundary of Auth-All.
Package email defines the provider-independent email boundary of Auth-All.
Package events defines the structured observability events of Auth-All.
Package events defines the structured observability events of Auth-All.
examples
go-app command
Command example-app shows a complete Auth-All integration in a small Go application.
Command example-app shows a complete Auth-All integration in a small Go application.
Package hook defines the typed lifecycle hooks of Auth-All.
Package hook defines the typed lifecycle hooks of Auth-All.
humaauth module
internal
clientgen
Package clientgen generates the official TypeScript client from the effective OpenAPI document.
Package clientgen generates the official TypeScript client from the effective OpenAPI document.
crypto
Package crypto holds the password hashing and token primitives of Auth-All.
Package crypto holds the password hashing and token primitives of Auth-All.
jwt
Package jwt verifies the compact RS256 identity tokens of OpenID Connect providers.
Package jwt verifies the compact RS256 identity tokens of OpenID Connect providers.
reference
Package reference builds the canonical Auth-All configuration.
Package reference builds the canonical Auth-All configuration.
sqlstore
Package sqlstore implements the Auth-All storage boundary over database/sql.
Package sqlstore implements the Auth-All storage boundary over database/sql.
testsupport
Package testsupport builds migrated databases for the Auth-All test suites.
Package testsupport builds migrated databases for the Auth-All test suites.
Package oauth defines the OAuth provider boundary of Auth-All.
Package oauth defines the OAuth provider boundary of Auth-All.
github
Package github implements the GitHub OAuth provider for Auth-All.
Package github implements the GitHub OAuth provider for Auth-All.
google
Package google implements the Google OpenID Connect provider for Auth-All.
Package google implements the Google OpenID Connect provider for Auth-All.
Package openapi holds the OpenAPI document model of Auth-All.
Package openapi holds the OpenAPI document model of Auth-All.
Package plugin is the public extension surface of Auth-All.
Package plugin is the public extension surface of Auth-All.
plugins
magiclink
Package magiclink implements sign-in through an emailed one-time link.
Package magiclink implements sign-in through an emailed one-time link.
Package ratelimit defines the rate-limit integration point of Auth-All.
Package ratelimit defines the rate-limit integration point of Auth-All.
Package schema describes the Auth-All database schema independently from a specific database engine.
Package schema describes the Auth-All database schema independently from a specific database engine.
Package store defines the storage boundary of Auth-All.
Package store defines the storage boundary of Auth-All.
postgres
Package postgres provides the PostgreSQL storage adapter for Auth-All.
Package postgres provides the PostgreSQL storage adapter for Auth-All.
sqlite
Package sqlite provides the SQLite storage adapter for Auth-All.
Package sqlite provides the SQLite storage adapter for Auth-All.
storetest
Package storetest holds the behavioral contract suite that every Auth-All storage adapter must pass.
Package storetest holds the behavioral contract suite that every Auth-All storage adapter must pass.
tools
evidence command
Command evidence writes the v1 verification evidence of Auth-All.
Command evidence writes the v1 verification evidence of Auth-All.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL