mfa

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package mfa provides multi-factor authentication functionality.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCredentialExists is returned when a credential with the same ID already exists.
	ErrCredentialExists = errors.New("credential already exists")
	// ErrMaxCredentialsReached is returned when the maximum number of credentials is reached.
	ErrMaxCredentialsReached = errors.New("maximum credentials reached")
)
View Source
var (
	// ErrInvalidRecoveryCode is returned when a recovery code is invalid.
	ErrInvalidRecoveryCode = errors.New("invalid recovery code")
	// ErrRecoveryCodeUsed is returned when a recovery code has already been used.
	ErrRecoveryCodeUsed = errors.New("recovery code already used")
	// ErrNoRecoveryCodesLeft is returned when all recovery codes have been used.
	ErrNoRecoveryCodesLeft = errors.New("no recovery codes left")
)
View Source
var (
	// ErrInvalidCode is returned when the TOTP code is invalid.
	ErrInvalidCode = errors.New("invalid TOTP code")
	// ErrSecretTooShort is returned when the secret is too short.
	ErrSecretTooShort = errors.New("secret is too short")
)
View Source
var (
	// ErrWebAuthnNotConfigured is returned when WebAuthn is not configured.
	ErrWebAuthnNotConfigured = errors.New("webauthn not configured")
	// ErrCredentialNotFound is returned when a credential is not found.
	ErrCredentialNotFound = errors.New("credential not found")
	// ErrInvalidChallenge is returned when the challenge is invalid.
	ErrInvalidChallenge = errors.New("invalid challenge")
)

Functions

This section is empty.

Types

type Algorithm

type Algorithm int

Algorithm represents the hashing function used for OTP generation.

const (
	// AlgorithmSHA1 should be used for compatibility with Google Authenticator.
	AlgorithmSHA1 Algorithm = iota
	AlgorithmSHA256
	AlgorithmSHA512
	AlgorithmMD5
)

func (Algorithm) String

func (a Algorithm) String() string

type CredentialInfo

type CredentialInfo struct {
	ID         string    `json:"id"`
	Name       string    `json:"name"`
	CreatedAt  time.Time `json:"created_at"`
	LastUsedAt time.Time `json:"last_used_at"`
}

CredentialInfo represents public information about a credential.

type CredentialManager

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

CredentialManager manages WebAuthn credentials.

func NewCredentialManager

func NewCredentialManager(store CredentialStore, config *CredentialManagerConfig) *CredentialManager

NewCredentialManager creates a new credential manager.

func (*CredentialManager) AddCredential

func (m *CredentialManager) AddCredential(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error

AddCredential adds a new credential for a user.

func (*CredentialManager) DeleteCredential

func (m *CredentialManager) DeleteCredential(ctx context.Context, userID uuid.UUID, credID string) error

DeleteCredential deletes a credential.

func (*CredentialManager) GetCredential

func (m *CredentialManager) GetCredential(ctx context.Context, userID uuid.UUID, credID string) (*CredentialInfo, error)

GetCredential retrieves a credential by ID.

func (*CredentialManager) GetRawCredentials

func (m *CredentialManager) GetRawCredentials(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)

GetRawCredentials returns all raw WebAuthn credentials for a user. This is used internally for WebAuthn ceremonies.

func (*CredentialManager) ListCredentials

func (m *CredentialManager) ListCredentials(ctx context.Context, userID uuid.UUID) ([]CredentialInfo, error)

ListCredentials returns all credentials for a user.

func (*CredentialManager) UpdateCredentialName

func (m *CredentialManager) UpdateCredentialName(ctx context.Context, userID uuid.UUID, credID, name string) error

UpdateCredentialName updates the name of a credential.

func (*CredentialManager) UpdateLastUsed

func (m *CredentialManager) UpdateLastUsed(ctx context.Context, userID uuid.UUID, credID []byte) error

UpdateLastUsed updates the last used time of a credential.

type CredentialManagerConfig

type CredentialManagerConfig struct {
	// MaxCredentialsPerUser is the maximum number of credentials per user.
	MaxCredentialsPerUser int
}

CredentialManagerConfig holds configuration for the credential manager.

func DefaultCredentialManagerConfig

func DefaultCredentialManagerConfig() *CredentialManagerConfig

DefaultCredentialManagerConfig returns the default configuration.

type CredentialStore

type CredentialStore interface {
	// Create creates a new credential.
	Create(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
	// GetByUser retrieves all credentials for a user.
	GetByUser(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)
	// GetByID retrieves a credential by ID.
	GetByID(ctx context.Context, userID uuid.UUID, credID []byte) (*WebAuthnCredential, error)
	// Update updates a credential.
	Update(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
	// Delete deletes a credential.
	Delete(ctx context.Context, userID uuid.UUID, credID []byte) error
	// Count returns the number of credentials for a user.
	Count(ctx context.Context, userID uuid.UUID) (int, error)
}

CredentialStore defines the interface for storing WebAuthn credentials.

type DeleteCredentialRequest

type DeleteCredentialRequest struct {
	Password string `json:"password" validate:"required"`
}

DeleteCredentialRequest represents a request to delete a credential.

type Digits

type Digits int

Digits represents the number of digits in a TOTP code.

const (
	DigitsSix   Digits = 6
	DigitsEight Digits = 8
)

func (Digits) Format

func (d Digits) Format(in int32) string

Format converts an integer into the zero-filled size for this Digits.

func (Digits) Length

func (d Digits) Length() int

Length returns the number of characters for this Digits.

func (Digits) String

func (d Digits) String() string

type DisableRequest

type DisableRequest struct {
	Code     string `json:"code"`
	Password string `json:"password" validate:"required"`
}

DisableRequest represents a request to disable MFA.

type Handler

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

Handler handles HTTP requests for MFA operations.

func NewHandler

func NewHandler(totp *TOTP, recovery *Recovery) *Handler

NewHandler creates a new MFA handler.

func NewHandlerWithWebAuthn

func NewHandlerWithWebAuthn(totp *TOTP, recovery *Recovery, webauthnConfig *WebAuthnConfig, credStore CredentialStore) *Handler

NewHandlerWithWebAuthn creates a new MFA handler with custom WebAuthn configuration.

func (*Handler) Disable

func (h *Handler) Disable(c echo.Context) error

Disable handles MFA disabling.

func (*Handler) GetRecoveryCodes

func (h *Handler) GetRecoveryCodes(c echo.Context) error

GetRecoveryCodes handles getting recovery codes.

func (*Handler) RegenerateRecoveryCodes

func (h *Handler) RegenerateRecoveryCodes(c echo.Context) error

RegenerateRecoveryCodes handles regenerating recovery codes.

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers the MFA routes.

func (*Handler) Setup

func (h *Handler) Setup(c echo.Context) error

Setup handles MFA setup initiation.

func (*Handler) Status

func (h *Handler) Status(c echo.Context) error

Status handles getting MFA status.

func (*Handler) ValidateMFA

func (h *Handler) ValidateMFA(c echo.Context) error

ValidateMFA validates MFA code during login. This would be called after initial password authentication.

func (*Handler) Verify

func (h *Handler) Verify(c echo.Context) error

Verify handles MFA setup verification.

func (*Handler) WebAuthnDeleteCredential

func (h *Handler) WebAuthnDeleteCredential(c echo.Context) error

WebAuthnDeleteCredential deletes a WebAuthn credential.

func (*Handler) WebAuthnRegisterBegin

func (h *Handler) WebAuthnRegisterBegin(c echo.Context) error

WebAuthnRegisterBegin starts the WebAuthn registration ceremony.

func (*Handler) WebAuthnRegisterFinish

func (h *Handler) WebAuthnRegisterFinish(c echo.Context) error

WebAuthnRegisterFinish completes the WebAuthn registration ceremony.

func (*Handler) WebAuthnStatus

func (h *Handler) WebAuthnStatus(c echo.Context) error

WebAuthnStatus returns the WebAuthn status for the current user.

type InMemoryCredentialStore

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

InMemoryCredentialStore is an in-memory implementation of CredentialStore.

func NewInMemoryCredentialStore

func NewInMemoryCredentialStore() *InMemoryCredentialStore

NewInMemoryCredentialStore creates a new in-memory credential store.

func (*InMemoryCredentialStore) Count

func (s *InMemoryCredentialStore) Count(ctx context.Context, userID uuid.UUID) (int, error)

Count returns the number of credentials for a user.

func (*InMemoryCredentialStore) Create

Create creates a new credential.

func (*InMemoryCredentialStore) Delete

func (s *InMemoryCredentialStore) Delete(ctx context.Context, userID uuid.UUID, credID []byte) error

Delete deletes a credential.

func (*InMemoryCredentialStore) GetByID

func (s *InMemoryCredentialStore) GetByID(ctx context.Context, userID uuid.UUID, credID []byte) (*WebAuthnCredential, error)

GetByID retrieves a credential by ID.

func (*InMemoryCredentialStore) GetByUser

func (s *InMemoryCredentialStore) GetByUser(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)

GetByUser retrieves all credentials for a user.

func (*InMemoryCredentialStore) Update

Update updates a credential.

type Key

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

Key contains the provisioning data for a TOTP account.

func (*Key) AccountName

func (k *Key) AccountName() string

func (*Key) Issuer

func (k *Key) Issuer() string

func (*Key) Secret

func (k *Key) Secret() string

func (*Key) String

func (k *Key) String() string

func (*Key) URL

func (k *Key) URL() string

type ListCredentialsResponse

type ListCredentialsResponse struct {
	Credentials []CredentialInfo `json:"credentials"`
	Count       int              `json:"count"`
	MaxAllowed  int              `json:"max_allowed"`
}

ListCredentialsResponse represents the response for listing credentials.

type LoginSession

type LoginSession struct {
	UserID    uuid.UUID `json:"user_id"`
	Challenge string    `json:"challenge"`
	ExpiresAt time.Time `json:"expires_at"`
	// SessionData is the serialized webauthn.SessionData
	SessionData []byte `json:"session_data"`
}

LoginSession holds the state for a login ceremony.

type Recovery

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

Recovery provides recovery code generation and validation.

func NewRecovery

func NewRecovery(config *RecoveryConfig) *Recovery

NewRecovery creates a new Recovery instance.

func (*Recovery) FormatCodesForDisplay

func (r *Recovery) FormatCodesForDisplay(codes []string) []string

FormatCodesForDisplay formats recovery codes for display to the user. Groups codes in pairs for easier reading.

func (*Recovery) Generate

func (r *Recovery) Generate() (*RecoveryCodes, error)

Generate generates a new set of recovery codes.

func (*Recovery) GetConfig

func (r *Recovery) GetConfig() *RecoveryConfig

GetConfig returns the current recovery configuration.

func (*Recovery) RemainingCodes

func (r *Recovery) RemainingCodes(usedCodes []bool) int

RemainingCodes returns the number of unused recovery codes.

func (*Recovery) Validate

func (r *Recovery) Validate(code string, hashedCodes []string, usedCodes []bool) (int, error)

Validate validates a recovery code against the stored hashed codes. Returns the index of the matched code, or -1 if not found.

func (*Recovery) ValidateAndMark

func (r *Recovery) ValidateAndMark(code string, hashedCodes []string, usedCodes []bool) ([]bool, error)

ValidateAndMark validates a recovery code and marks it as used. Returns the updated usedCodes slice.

type RecoveryCodes

type RecoveryCodes struct {
	// Codes are the plaintext recovery codes (only available at generation time).
	Codes []string `json:"codes,omitempty"`
	// HashedCodes are the hashed recovery codes for storage.
	HashedCodes []string `json:"-"`
	// UsedCodes tracks which codes have been used (by index).
	UsedCodes []bool `json:"-"`
}

RecoveryCodes represents a set of recovery codes.

type RecoveryCodesResponse

type RecoveryCodesResponse struct {
	Codes     []string `json:"codes"`
	Remaining int      `json:"remaining"`
}

RecoveryCodesResponse represents the recovery codes response.

type RecoveryConfig

type RecoveryConfig struct {
	// Count is the number of recovery codes to generate.
	Count int
	// Length is the length of each recovery code (in characters).
	Length int
}

RecoveryConfig holds recovery code configuration.

func DefaultRecoveryConfig

func DefaultRecoveryConfig() *RecoveryConfig

DefaultRecoveryConfig returns the default recovery code configuration.

type RegistrationSession

type RegistrationSession struct {
	UserID    uuid.UUID `json:"user_id"`
	Challenge string    `json:"challenge"`
	ExpiresAt time.Time `json:"expires_at"`
	// SessionData is the serialized webauthn.SessionData
	SessionData []byte `json:"session_data"`
}

RegistrationSession holds the state for a registration ceremony.

type SetupResponse

type SetupResponse struct {
	// Secret is the TOTP secret (base32 encoded).
	Secret string `json:"secret"`
	// URI is the provisioning URI for authenticator apps.
	URI string `json:"uri"`
}

SetupResponse contains the data needed for MFA setup.

type SetupResponseDTO

type SetupResponseDTO struct {
	Secret string `json:"secret"`
	URI    string `json:"uri"`
}

SetupResponseDTO represents the response for MFA setup.

type StatusResponse

type StatusResponse struct {
	Enabled       bool `json:"enabled"`
	RecoveryCount int  `json:"recovery_codes_remaining"`
	SetupRequired bool `json:"setup_required,omitempty"`
}

StatusResponse represents the MFA status response.

type TOTP

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

TOTP provides TOTP generation and validation.

func NewTOTP

func NewTOTP(config *TOTPConfig) *TOTP

NewTOTP creates a new TOTP instance.

func (*TOTP) GenerateCode

func (t *TOTP) GenerateCode(secret string) (string, error)

GenerateCode generates a TOTP code for the current time.

func (*TOTP) GenerateKey

func (t *TOTP) GenerateKey(accountName string) (*Key, error)

GenerateKey generates a new TOTP key for a user.

func (*TOTP) GenerateSecret

func (t *TOTP) GenerateSecret() (string, error)

GenerateSecret generates a new TOTP secret.

func (*TOTP) GetConfig

func (t *TOTP) GetConfig() *TOTPConfig

GetConfig returns the current TOTP configuration.

func (*TOTP) GetProvisioningURI

func (t *TOTP) GetProvisioningURI(accountName, secret string) string

GetProvisioningURI returns the provisioning URI for authenticator apps.

func (*TOTP) Setup

func (t *TOTP) Setup(accountName string) (*SetupResponse, error)

Setup generates the provisioning secret and URI for MFA setup.

func (*TOTP) Validate

func (t *TOTP) Validate(code, secret string) bool

Validate validates a TOTP code against a secret.

func (*TOTP) ValidateWithSkew

func (t *TOTP) ValidateWithSkew(code, secret string) bool

ValidateWithSkew validates a TOTP code with clock skew tolerance.

type TOTPConfig

type TOTPConfig struct {
	// Issuer is the name shown in authenticator apps.
	Issuer string
	// Algorithm is the hash algorithm (SHA1, SHA256, SHA512).
	Algorithm Algorithm
	// Digits is the number of digits in the code.
	Digits Digits
	// Period is the time step in seconds.
	Period uint
	// SecretSize is the size of the secret in bytes.
	SecretSize uint
	// Skew is the number of periods to allow for clock drift.
	Skew uint
}

TOTPConfig holds TOTP configuration.

func DefaultTOTPConfig

func DefaultTOTPConfig() *TOTPConfig

DefaultTOTPConfig returns the default TOTP configuration.

type UpdateCredentialRequest

type UpdateCredentialRequest struct {
	Name string `json:"name" validate:"required,min=1,max=100"`
}

UpdateCredentialRequest represents a request to update a credential.

type ValidateMFARequest

type ValidateMFARequest struct {
	MFAToken     string `json:"mfa_token" validate:"required"`
	Code         string `json:"code"`
	RecoveryCode string `json:"recovery_code"`
}

ValidateMFARequest represents a request to validate MFA during login.

type VerifyRequest

type VerifyRequest struct {
	Code   string `json:"code" validate:"required"`
	Secret string `json:"secret" validate:"required"`
}

VerifyRequest represents a request to verify MFA setup.

type VerifyResponse

type VerifyResponse struct {
	Enabled       bool     `json:"enabled"`
	RecoveryCodes []string `json:"recovery_codes,omitempty"`
}

VerifyResponse represents the response for MFA verification.

type WebAuthn

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

WebAuthn provides WebAuthn registration and authentication.

func NewWebAuthn

func NewWebAuthn(config *WebAuthnConfig) (*WebAuthn, error)

NewWebAuthn creates a new WebAuthn instance.

func (*WebAuthn) BeginDiscoverableLogin

func (w *WebAuthn) BeginDiscoverableLogin() (*protocol.CredentialAssertion, *LoginSession, error)

BeginDiscoverableLogin starts a discoverable (usernameless) login ceremony.

func (*WebAuthn) BeginLogin

BeginLogin starts a WebAuthn login ceremony.

func (*WebAuthn) BeginRegistration

func (w *WebAuthn) BeginRegistration(user *WebAuthnUser) (*protocol.CredentialCreation, *RegistrationSession, error)

BeginRegistration starts a WebAuthn registration ceremony.

func (*WebAuthn) FinishLogin

func (w *WebAuthn) FinishLogin(user *WebAuthnUser, session *LoginSession, response *protocol.ParsedCredentialAssertionData) (*WebAuthnCredential, error)

FinishLogin completes a WebAuthn login ceremony.

func (*WebAuthn) FinishRegistration

func (w *WebAuthn) FinishRegistration(user *WebAuthnUser, session *RegistrationSession, response *protocol.ParsedCredentialCreationData) (*WebAuthnCredential, error)

FinishRegistration completes a WebAuthn registration ceremony.

func (*WebAuthn) GetConfig

func (w *WebAuthn) GetConfig() *WebAuthnConfig

GetConfig returns the current WebAuthn configuration.

type WebAuthnConfig

type WebAuthnConfig struct {
	// RPDisplayName is the display name of the relying party.
	RPDisplayName string
	// RPID is the relying party ID (usually the domain).
	RPID string
	// RPOrigins are the allowed origins.
	RPOrigins []string
	// Timeout is the timeout for ceremonies in milliseconds.
	Timeout int
	// AuthenticatorSelection specifies authenticator requirements.
	AuthenticatorSelection *protocol.AuthenticatorSelection
	// AttestationPreference specifies attestation conveyance preference.
	AttestationPreference protocol.ConveyancePreference
}

WebAuthnConfig holds WebAuthn configuration.

func DefaultWebAuthnConfig

func DefaultWebAuthnConfig() *WebAuthnConfig

DefaultWebAuthnConfig returns the default WebAuthn configuration.

type WebAuthnCredential

type WebAuthnCredential struct {
	ID              []byte    `json:"id"`
	PublicKey       []byte    `json:"public_key"`
	AttestationType string    `json:"attestation_type"`
	AAGUID          []byte    `json:"aaguid"`
	SignCount       uint32    `json:"sign_count"`
	CloneWarning    bool      `json:"clone_warning"`
	Name            string    `json:"name"`
	CreatedAt       time.Time `json:"created_at"`
	LastUsedAt      time.Time `json:"last_used_at"`
}

WebAuthnCredential represents a stored WebAuthn credential.

func FromWebAuthnCredential

func FromWebAuthnCredential(cred *webauthn.Credential, name string) *WebAuthnCredential

FromWebAuthnCredential creates a WebAuthnCredential from webauthn.Credential.

func (*WebAuthnCredential) ToWebAuthnCredential

func (c *WebAuthnCredential) ToWebAuthnCredential() webauthn.Credential

ToWebAuthnCredential converts to webauthn.Credential.

type WebAuthnCredentialDTO

type WebAuthnCredentialDTO struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	CreatedAt  string `json:"created_at"`
	LastUsedAt string `json:"last_used_at"`
}

WebAuthnCredentialDTO represents a WebAuthn credential for API responses.

type WebAuthnRegisterBeginRequest

type WebAuthnRegisterBeginRequest struct {
	Name string `json:"name" validate:"required"`
}

WebAuthnRegisterBeginRequest represents a request to begin WebAuthn registration.

type WebAuthnStatusResponse

type WebAuthnStatusResponse struct {
	Enabled     bool                    `json:"enabled"`
	Credentials []WebAuthnCredentialDTO `json:"credentials"`
}

WebAuthnStatusResponse represents the WebAuthn status response.

type WebAuthnUser

type WebAuthnUser struct {
	ID          uuid.UUID
	Name        string
	DisplayName string
	Credentials []WebAuthnCredential
}

WebAuthnUser represents a user for WebAuthn operations.

func (*WebAuthnUser) WebAuthnCredentials

func (u *WebAuthnUser) WebAuthnCredentials() []webauthn.Credential

WebAuthnCredentials returns the user's credentials.

func (*WebAuthnUser) WebAuthnDisplayName

func (u *WebAuthnUser) WebAuthnDisplayName() string

WebAuthnDisplayName returns the user's display name.

func (*WebAuthnUser) WebAuthnID

func (u *WebAuthnUser) WebAuthnID() []byte

WebAuthnID returns the user's WebAuthn ID.

func (*WebAuthnUser) WebAuthnName

func (u *WebAuthnUser) WebAuthnName() string

WebAuthnName returns the user's name.

Jump to

Keyboard shortcuts

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