Documentation
¶
Index ¶
- func AdaptiveMFA(service *Service) func(func(forge.Context) error) func(forge.Context) error
- func CalculateDeviceFingerprint(userAgent, ipAddress string, additionalData map[string]string) string
- func OptionalMFA(service *Service) func(func(forge.Context) error) func(forge.Context) error
- func RegisterRoutes(router forge.Router, handler *Handler)
- func RequireFactorType(service *Service, factorType FactorType) func(func(forge.Context) error) func(forge.Context) error
- func RequireMFA(service *Service) func(func(forge.Context) error) func(forge.Context) error
- func StepUpAuth(service *Service, maxAge time.Duration) func(func(forge.Context) error) func(forge.Context) error
- type AdaptiveMFAConfig
- type AdminBypassRequest
- type AdminPolicyRequest
- type BackupCodeFactorAdapter
- func (a *BackupCodeFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
- func (a *BackupCodeFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
- func (a *BackupCodeFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, ...) (bool, error)
- func (a *BackupCodeFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
- type BackupCodesConfig
- type BaseFactorAdapter
- type Challenge
- type ChallengeRequest
- type ChallengeResponse
- type ChallengeStatus
- type ChallengeStatusResponse
- type Config
- type DeleteFactorRequest
- type DeviceInfo
- type DevicesResponse
- type EmailConfig
- type EmailFactorAdapter
- func (a *EmailFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
- func (a *EmailFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
- func (a *EmailFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, ...) (bool, error)
- func (a *EmailFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
- type EnrollFactorRequest
- type ErrorResponse
- type Factor
- type FactorAdapter
- type FactorAdapterRegistry
- type FactorEnrollmentRequest
- type FactorEnrollmentResponse
- type FactorInfo
- type FactorPriority
- type FactorStatus
- type FactorType
- type FactorVerificationRequest
- type FactorsResponse
- type GetChallengeStatusRequest
- type GetChallengeStatusResponse
- type GetFactorRequest
- type GetStatusRequest
- type Handler
- func (h *Handler) AdminGetPolicy(c forge.Context) error
- func (h *Handler) AdminGrantBypass(c forge.Context) error
- func (h *Handler) AdminResetUserMFA(c forge.Context) error
- func (h *Handler) AdminUpdatePolicy(c forge.Context) error
- func (h *Handler) DeleteFactor(c forge.Context) error
- func (h *Handler) EnrollFactor(c forge.Context) error
- func (h *Handler) GetChallengeStatus(c forge.Context) error
- func (h *Handler) GetFactor(c forge.Context) error
- func (h *Handler) GetPolicy(c forge.Context) error
- func (h *Handler) GetStatus(c forge.Context) error
- func (h *Handler) InitiateChallenge(c forge.Context) error
- func (h *Handler) ListFactors(c forge.Context) error
- func (h *Handler) ListTrustedDevices(c forge.Context) error
- func (h *Handler) RevokeTrustedDevice(c forge.Context) error
- func (h *Handler) TrustDevice(c forge.Context) error
- func (h *Handler) UpdateFactor(c forge.Context) error
- func (h *Handler) VerifyChallenge(c forge.Context) error
- func (h *Handler) VerifyFactor(c forge.Context) error
- type InitiateChallengeRequest
- type LimitResult
- type ListFactorsRequest
- type ListFactorsResponse
- type ListTrustedDevicesResponse
- type MFABypassResponse
- type MFAConfigResponse
- type MFAPolicy
- type MFAPolicyResponse
- type MFASession
- type MFAStatus
- type MessageResponse
- type Plugin
- func (p *Plugin) Config() *Config
- func (p *Plugin) ID() string
- func (p *Plugin) Init(authInstance core.Authsome) error
- func (p *Plugin) Migrate() error
- func (p *Plugin) RegisterHooks(_ *hooks.HookRegistry) error
- func (p *Plugin) RegisterRoutes(router forge.Router) error
- func (p *Plugin) RegisterServiceDecorators(_ *registry.ServiceRegistry) error
- func (p *Plugin) Service() *Service
- func (p *Plugin) WithConfig(config *Config) *Plugin
- type PluginOption
- func WithAdaptiveMFA(enabled bool, threshold float64) PluginOption
- func WithBackupCodes(enabled bool, count, length int) PluginOption
- func WithDefaultConfig(cfg *Config) PluginOption
- func WithEmail(enabled bool, codeLength, expiryMinutes int) PluginOption
- func WithEnabled(enabled bool) PluginOption
- func WithGracePeriodDays(days int) PluginOption
- func WithRequireForAllUsers(required bool) PluginOption
- func WithSMS(enabled bool, codeLength, expiryMinutes int) PluginOption
- func WithTOTP(enabled bool, issuer string) PluginOption
- type RateLimitConfig
- type RateLimiter
- func (r *RateLimiter) CheckFactorLimit(ctx context.Context, userID xid.ID, factorType FactorType) (*LimitResult, error)
- func (r *RateLimiter) CheckUserLimit(ctx context.Context, userID xid.ID) (*LimitResult, error)
- func (r *RateLimiter) ClearLockout(ctx context.Context, userID xid.ID) error
- func (r *RateLimiter) GetExponentialBackoff(attemptNumber int) time.Duration
- func (r *RateLimiter) IsLockedOut(ctx context.Context, userID xid.ID) (bool, *time.Time, error)
- func (r *RateLimiter) RecordAttempt(ctx context.Context, userID xid.ID, factorID *xid.ID, factorType FactorType, ...) error
- type ResetUserMFARequest
- type ResetUserMFAResponse
- type RevokeTrustedDeviceRequest
- type RiskAssessment
- type RiskContext
- type RiskEngine
- type RiskFactor
- type RiskLevel
- type SMSConfig
- type SMSFactorAdapter
- func (a *SMSFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
- func (a *SMSFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
- func (a *SMSFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, ...) (bool, error)
- func (a *SMSFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
- type Service
- func (s *Service) DeleteFactor(ctx context.Context, factorID xid.ID) error
- func (s *Service) EnrollFactor(ctx context.Context, userID xid.ID, req *FactorEnrollmentRequest) (*FactorEnrollmentResponse, error)
- func (s *Service) GetChallengeStatus(ctx context.Context, sessionID xid.ID, userID xid.ID) (*ChallengeStatusResponse, error)
- func (s *Service) GetFactor(ctx context.Context, factorID xid.ID) (*Factor, error)
- func (s *Service) GetMFAStatus(ctx context.Context, userID xid.ID, deviceID string) (*MFAStatus, error)
- func (s *Service) GrantBypass(ctx context.Context, appID, userID, grantedBy xid.ID, durationSeconds int, ...) (*MFABypassResponse, error)
- func (s *Service) InitiateChallenge(ctx context.Context, req *ChallengeRequest) (*ChallengeResponse, error)
- func (s *Service) IsTrustedDevice(ctx context.Context, userID xid.ID, deviceID string) (bool, error)
- func (s *Service) ListFactors(ctx context.Context, userID xid.ID, activeOnly bool) ([]*Factor, error)
- func (s *Service) ListTrustedDevices(ctx context.Context, userID xid.ID) ([]*TrustedDevice, error)
- func (s *Service) ResetUserMFA(ctx context.Context, appID, userID, adminID xid.ID) error
- func (s *Service) RevokeTrustedDevice(ctx context.Context, deviceID xid.ID) error
- func (s *Service) TrustDevice(ctx context.Context, userID xid.ID, deviceInfo *DeviceInfo) error
- func (s *Service) UpdateFactor(ctx context.Context, factorID xid.ID, updates map[string]any) error
- func (s *Service) UpdatePolicy(ctx context.Context, appID xid.ID, orgID *xid.ID, updatedBy xid.ID, ...) (*MFAPolicyResponse, error)
- func (s *Service) VerifyChallenge(ctx context.Context, req *VerificationRequest) (*VerificationResponse, error)
- func (s *Service) VerifyEnrollment(ctx context.Context, factorID xid.ID, proof string) error
- type SuccessResponse
- type TOTPConfig
- type TOTPFactorAdapter
- func (a *TOTPFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
- func (a *TOTPFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
- func (a *TOTPFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, ...) (bool, error)
- func (a *TOTPFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
- type TrustDeviceRequest
- type TrustedDevice
- type TrustedDevicesConfig
- type UpdateFactorRequest
- type UpdatePolicyRequest
- type VerificationRequest
- type VerificationResponse
- type VerifyChallengeRequest
- type VerifyEnrolledFactorRequest
- type WebAuthnConfig
- type WebAuthnFactorAdapter
- func (a *WebAuthnFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
- func (a *WebAuthnFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
- func (a *WebAuthnFactorAdapter) IsAvailable() bool
- func (a *WebAuthnFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, ...) (bool, error)
- func (a *WebAuthnFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AdaptiveMFA ¶
AdaptiveMFA applies risk-based MFA requirements.
func CalculateDeviceFingerprint ¶
func CalculateDeviceFingerprint(userAgent, ipAddress string, additionalData map[string]string) string
CalculateDeviceFingerprint generates a device fingerprint from user agent and other data.
func OptionalMFA ¶
OptionalMFA suggests MFA but doesn't require it.
func RegisterRoutes ¶
RegisterRoutes registers all MFA routes with OpenAPI documentation.
func RequireFactorType ¶
func RequireFactorType(service *Service, factorType FactorType) func(func(forge.Context) error) func(forge.Context) error
RequireFactorType ensures the user has a specific factor type enrolled.
func RequireMFA ¶
RequireMFA ensures the user has completed MFA verification.
Types ¶
type AdaptiveMFAConfig ¶
type AdaptiveMFAConfig struct {
Enabled bool `default:"false" json:"enabled"`
RiskThreshold float64 `default:"50.0" json:"risk_threshold"` // 0-100
FactorLocationChange bool `default:"true" json:"factor_location_change"`
FactorNewDevice bool `default:"true" json:"factor_new_device"`
FactorVelocity bool `default:"true" json:"factor_velocity"`
FactorIPReputation bool `default:"false" json:"factor_ip_reputation"`
RequireStepUpThreshold float64 `default:"75.0" json:"require_step_up_threshold"`
LocationChangeRisk float64 `default:"30.0" json:"location_change_risk"`
NewDeviceRisk float64 `default:"40.0" json:"new_device_risk"`
VelocityRisk float64 `default:"50.0" json:"velocity_risk"`
}
AdaptiveMFAConfig configures risk-based authentication.
type AdminBypassRequest ¶
type AdminBypassRequest struct {
UserID xid.ID `json:"userId"`
Duration int `json:"duration"` // Bypass duration in seconds
Reason string `json:"reason"` // Reason for bypass
}
AdminBypassRequest represents a request to grant temporary MFA bypass.
type AdminPolicyRequest ¶
type AdminPolicyRequest struct {
RequiredFactors int `json:"requiredFactors"` // Number of factors required
AllowedTypes []string `json:"allowedTypes"` // e.g., ["totp", "sms", "email", "webauthn", "backup"]
GracePeriod int `json:"gracePeriod"` // Grace period in seconds for new users
Enabled bool `json:"enabled"` // Enable/disable MFA requirement
}
AdminPolicyRequest represents a request to update MFA policy.
type BackupCodeFactorAdapter ¶
type BackupCodeFactorAdapter struct {
BaseFactorAdapter
// contains filtered or unexported fields
}
BackupCodeFactorAdapter integrates twofa plugin's backup codes as an MFA factor.
func NewBackupCodeFactorAdapter ¶
func NewBackupCodeFactorAdapter(twofaService *twofa.Service, enabled bool) *BackupCodeFactorAdapter
NewBackupCodeFactorAdapter creates a new backup code factor adapter.
func (*BackupCodeFactorAdapter) Challenge ¶
func (a *BackupCodeFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
Challenge creates a backup code verification challenge.
func (*BackupCodeFactorAdapter) Enroll ¶
func (a *BackupCodeFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
Enroll generates backup codes for a user.
func (*BackupCodeFactorAdapter) Verify ¶
func (a *BackupCodeFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, data map[string]any) (bool, error)
Verify verifies a backup code.
func (*BackupCodeFactorAdapter) VerifyEnrollment ¶
func (a *BackupCodeFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
VerifyEnrollment is not needed for backup codes (immediately active).
type BackupCodesConfig ¶
type BackupCodesConfig struct {
Enabled bool `default:"true" json:"enabled"`
Count int `default:"10" json:"count"`
Length int `default:"8" json:"length"`
Format string `default:"XXXX-XXXX" json:"format"` // Code format
AllowReuse bool `default:"false" json:"allow_reuse"`
}
BackupCodesConfig configures backup recovery codes.
type BaseFactorAdapter ¶
type BaseFactorAdapter struct {
// contains filtered or unexported fields
}
BaseFactorAdapter provides common functionality for adapters.
func (*BaseFactorAdapter) IsAvailable ¶
func (b *BaseFactorAdapter) IsAvailable() bool
IsAvailable checks if the factor is available.
func (*BaseFactorAdapter) Type ¶
func (b *BaseFactorAdapter) Type() FactorType
Type returns the factor type.
type Challenge ¶
type Challenge struct {
ID xid.ID `json:"id"`
UserID xid.ID `json:"userId"`
FactorID xid.ID `json:"factorId"`
Type FactorType `json:"type"`
Status ChallengeStatus `json:"status"`
Code string `json:"-"` // Hashed verification code
Metadata map[string]any `json:"metadata"`
Attempts int `json:"attempts"`
MaxAttempts int `json:"maxAttempts"`
IPAddress string `json:"ipAddress"`
UserAgent string `json:"userAgent"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
VerifiedAt *time.Time `json:"verifiedAt,omitempty"`
}
Challenge represents an active MFA challenge.
type ChallengeRequest ¶
type ChallengeRequest struct {
UserID xid.ID `json:"userId"`
FactorTypes []FactorType `json:"factorTypes,omitempty"` // Specific factor types to use
Context string `json:"context,omitempty"` // "login", "transaction", "step-up"
Metadata map[string]any `json:"metadata,omitempty"`
}
ChallengeRequest initiates an MFA challenge.
type ChallengeResponse ¶
type ChallengeResponse struct {
ChallengeID xid.ID `json:"challengeId"`
SessionID xid.ID `json:"sessionId"`
FactorsRequired int `json:"factorsRequired"`
AvailableFactors []FactorInfo `json:"availableFactors"`
ExpiresAt time.Time `json:"expiresAt"`
}
ChallengeResponse contains challenge details.
type ChallengeStatus ¶
type ChallengeStatus string
ChallengeStatus represents the state of an MFA challenge.
const ( ChallengeStatusPending ChallengeStatus = "pending" ChallengeStatusVerified ChallengeStatus = "verified" ChallengeStatusFailed ChallengeStatus = "failed" ChallengeStatusExpired ChallengeStatus = "expired" ChallengeStatusCancelled ChallengeStatus = "cancelled" )
type ChallengeStatusResponse ¶
type ChallengeStatusResponse struct {
SessionID xid.ID `json:"sessionId"`
Status string `json:"status"` // pending, completed, expired
FactorsRequired int `json:"factorsRequired"`
FactorsVerified int `json:"factorsVerified"`
FactorsRemaining int `json:"factorsRemaining"`
ExpiresAt time.Time `json:"expiresAt"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
}
ChallengeStatusResponse contains the current status of an MFA challenge.
type Config ¶
type Config struct {
// Global settings
Enabled bool `default:"true" json:"enabled"`
RequireForAllUsers bool `default:"false" json:"require_for_all_users"`
GracePeriodDays int `default:"7" json:"grace_period_days"`
// Factor settings
AllowedFactorTypes []FactorType `json:"allowed_factor_types"`
RequiredFactorCount int `default:"1" json:"required_factor_count"`
// TOTP settings
TOTP TOTPConfig `json:"totp"`
// SMS settings
SMS SMSConfig `json:"sms"`
// Email settings
Email EmailConfig `json:"email"`
// WebAuthn settings
WebAuthn WebAuthnConfig `json:"webauthn"`
// Backup codes settings
BackupCodes BackupCodesConfig `json:"backup_codes"`
// Trusted device settings
TrustedDevices TrustedDevicesConfig `json:"trusted_devices"`
// Challenge settings
ChallengeExpiryMinutes int `default:"5" json:"challenge_expiry_minutes"`
MaxAttempts int `default:"3" json:"max_attempts"`
// Rate limiting
RateLimit RateLimitConfig `json:"rate_limit"`
// Adaptive MFA
AdaptiveMFA AdaptiveMFAConfig `json:"adaptive_mfa"`
// Session settings
SessionExpiryMinutes int `default:"15" json:"session_expiry_minutes"`
}
Config holds MFA plugin configuration.
func (*Config) GetFactorConfig ¶
func (c *Config) GetFactorConfig(factorType FactorType) any
GetFactorConfig returns configuration for a specific factor type.
func (*Config) IsFactorAllowed ¶
func (c *Config) IsFactorAllowed(factorType FactorType) bool
IsFactorAllowed checks if a factor type is allowed.
type DeleteFactorRequest ¶
type DeleteFactorRequest struct {
// Path parameters
ID string `description:"Factor ID to delete" path:"id" validate:"required"`
}
DeleteFactorRequest represents the request to delete a factor.
type DeviceInfo ¶
type DeviceInfo struct {
DeviceID string `json:"deviceId"`
Name string `json:"name,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
DeviceInfo contains device identification data.
type DevicesResponse ¶
type EmailConfig ¶
type EmailConfig struct {
Enabled bool `default:"true" json:"enabled"`
Provider string `json:"provider"` // Email provider
CodeLength int `default:"6" json:"code_length"`
CodeExpiryMinutes int `default:"10" json:"code_expiry_minutes"`
TemplateID string `json:"template_id"`
RateLimit *RateLimitConfig `json:"rate_limit,omitempty"`
}
EmailConfig configures email verification settings.
type EmailFactorAdapter ¶
type EmailFactorAdapter struct {
BaseFactorAdapter
// contains filtered or unexported fields
}
EmailFactorAdapter integrates emailotp plugin as an MFA factor (not primary auth).
func NewEmailFactorAdapter ¶
func NewEmailFactorAdapter(emailOTPService *emailotp.Service, notifAdapter *notificationPlugin.Adapter, enabled bool) *EmailFactorAdapter
NewEmailFactorAdapter creates a new email factor adapter.
func (*EmailFactorAdapter) Challenge ¶
func (a *EmailFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
Challenge sends an email OTP code for MFA verification.
func (*EmailFactorAdapter) Enroll ¶
func (a *EmailFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
Enroll registers an email address for MFA.
func (*EmailFactorAdapter) Verify ¶
func (a *EmailFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, data map[string]any) (bool, error)
Verify verifies an email OTP code.
func (*EmailFactorAdapter) VerifyEnrollment ¶
func (a *EmailFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
VerifyEnrollment sends a test code to verify email works.
type EnrollFactorRequest ¶
type EnrollFactorRequest struct {
// Body fields
Type FactorType `` /* 160-byte string literal not displayed */
Priority FactorPriority `` /* 130-byte string literal not displayed */
Name string `description:"User-friendly name for the factor" json:"name,omitempty" validate:"omitempty,min=1,max=100"`
Metadata map[string]any `description:"Additional factor-specific metadata" json:"metadata,omitempty"`
}
EnrollFactorRequest represents the request to enroll a new MFA factor.
type ErrorResponse ¶
type ErrorResponse struct {
Error string `description:"Error message" json:"error"`
Code string `description:"Error code for programmatic handling" json:"code,omitempty"`
Details map[string]any `description:"Additional error details" json:"details,omitempty"`
}
ErrorResponse represents a standard error response.
type Factor ¶
type Factor struct {
ID xid.ID `json:"id"`
UserID xid.ID `json:"userId"`
Type FactorType `json:"type"`
Status FactorStatus `json:"status"`
Priority FactorPriority `json:"priority"`
Name string `json:"name"` // User-friendly name
Secret string `json:"-"` // Encrypted secret data
Metadata map[string]any `json:"metadata"` // Factor-specific metadata
LastUsedAt *time.Time `json:"lastUsedAt"`
VerifiedAt *time.Time `json:"verifiedAt"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
}
Factor represents an enrolled authentication factor.
type FactorAdapter ¶
type FactorAdapter interface {
// Type returns the factor type this adapter handles
Type() FactorType
// Enroll initiates factor enrollment for a user
// Returns provisioning data needed to complete enrollment
Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
// VerifyEnrollment verifies the enrollment (e.g., user scanned QR code and provides first TOTP)
VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
// Challenge initiates a verification challenge (sends code, displays options, etc.)
Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
// Verify verifies the challenge response
Verify(ctx context.Context, challenge *Challenge, response string, data map[string]any) (bool, error)
// IsAvailable checks if this factor type is available/configured
IsAvailable() bool
}
FactorAdapter defines the interface for integrating authentication factors Each adapter wraps an existing plugin (twofa, emailotp, phone, passkey).
type FactorAdapterRegistry ¶
type FactorAdapterRegistry struct {
// contains filtered or unexported fields
}
FactorAdapterRegistry manages available factor adapters.
func NewFactorAdapterRegistry ¶
func NewFactorAdapterRegistry() *FactorAdapterRegistry
NewFactorAdapterRegistry creates a new adapter registry.
func (*FactorAdapterRegistry) Get ¶
func (r *FactorAdapterRegistry) Get(factorType FactorType) (FactorAdapter, error)
Get retrieves a factor adapter by type.
func (*FactorAdapterRegistry) GetAvailable ¶
func (r *FactorAdapterRegistry) GetAvailable() []FactorType
GetAvailable returns only available factor types.
func (*FactorAdapterRegistry) List ¶
func (r *FactorAdapterRegistry) List() []FactorType
List returns all available factor types.
func (*FactorAdapterRegistry) Register ¶
func (r *FactorAdapterRegistry) Register(adapter FactorAdapter)
Register registers a factor adapter.
type FactorEnrollmentRequest ¶
type FactorEnrollmentRequest struct {
Type FactorType `json:"type"`
Priority FactorPriority `json:"priority,omitempty"`
Name string `json:"name,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
FactorEnrollmentRequest represents a request to enroll a new factor.
type FactorEnrollmentResponse ¶
type FactorEnrollmentResponse struct {
FactorID xid.ID `json:"factorId"`
Type FactorType `json:"type"`
Status FactorStatus `json:"status"`
ProvisioningData map[string]any `json:"provisioningData"` // Type-specific setup data
}
FactorEnrollmentResponse contains data needed to complete enrollment.
type FactorInfo ¶
type FactorInfo struct {
FactorID xid.ID `json:"factorId"`
Type FactorType `json:"type"`
Name string `json:"name"`
Metadata map[string]any `json:"metadata,omitempty"` // Masked phone, email, etc.
}
FactorInfo provides minimal factor information for challenge selection.
type FactorPriority ¶
type FactorPriority string
FactorPriority defines the priority of a factor.
const ( FactorPriorityPrimary FactorPriority = "primary" // Primary authentication factor FactorPriorityBackup FactorPriority = "backup" // Backup/fallback factor FactorPriorityOptional FactorPriority = "optional" // Optional additional security )
type FactorStatus ¶
type FactorStatus string
FactorStatus represents the state of an authentication factor.
const ( FactorStatusPending FactorStatus = "pending" // Enrolled but not verified FactorStatusActive FactorStatus = "active" // Verified and active FactorStatusDisabled FactorStatus = "disabled" // Temporarily disabled FactorStatusRevoked FactorStatus = "revoked" // Permanently revoked )
type FactorType ¶
type FactorType string
FactorType represents different authentication factor types.
const ( FactorTypeTOTP FactorType = "totp" // Time-based One-Time Password (Google Authenticator) FactorTypeSMS FactorType = "sms" // SMS verification code FactorTypeEmail FactorType = "email" // Email verification code FactorTypeWebAuthn FactorType = "webauthn" // FIDO2/WebAuthn (security keys, biometrics) FactorTypePush FactorType = "push" // Push notification approval FactorTypeBackup FactorType = "backup" // Backup recovery codes FactorTypeQuestion FactorType = "question" // Security questions FactorTypeBiometric FactorType = "biometric" // Biometric authentication )
type FactorVerificationRequest ¶
type FactorVerificationRequest struct {
FactorID xid.ID `json:"factorId"`
Code string `json:"code,omitempty"` // For OTP-based factors
Data map[string]any `json:"data,omitempty"` // For complex factors (WebAuthn, etc.)
}
FactorVerificationRequest verifies an enrolled factor.
type FactorsResponse ¶
type GetChallengeStatusRequest ¶
type GetChallengeStatusRequest struct {
// Path parameters
ID string `description:"Challenge ID" path:"id" validate:"required"`
}
GetChallengeStatusRequest represents the request to get challenge status.
type GetChallengeStatusResponse ¶
type GetChallengeStatusResponse struct {
ChallengeID xid.ID `description:"Unique challenge identifier" json:"challengeId"`
Status ChallengeStatus `description:"Current status of the challenge" json:"status"`
FactorsRequired int `description:"Number of factors required" json:"factorsRequired"`
FactorsVerified int `description:"Number of factors verified" json:"factorsVerified"`
Attempts int `description:"Number of verification attempts" json:"attempts"`
MaxAttempts int `description:"Maximum allowed attempts" json:"maxAttempts"`
AvailableFactors []FactorInfo `description:"Available factors for this challenge" json:"availableFactors"`
}
GetChallengeStatusResponse represents the challenge status response.
type GetFactorRequest ¶
type GetFactorRequest struct {
// Path parameters
ID string `description:"Factor ID" path:"id" validate:"required"`
}
GetFactorRequest represents the request to get a specific factor.
type GetStatusRequest ¶
type GetStatusRequest struct {
// Query parameters
DeviceID string `description:"Device ID to check trust status" query:"deviceId"`
}
GetStatusRequest represents the request to get MFA status.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler provides HTTP endpoints for MFA operations.
func (*Handler) AdminGetPolicy ¶
AdminGetPolicy handles GET /mfa/admin/policy AdminGetPolicy the current MFA policy for an app.
func (*Handler) AdminGrantBypass ¶
AdminGrantBypass handles POST /mfa/admin/bypass AdminGrantBypass temporary MFA bypass for a user (admin only).
func (*Handler) AdminResetUserMFA ¶
AdminResetUserMFA handles POST /mfa/admin/users/:id/reset AdminResetUserMFA all MFA factors for a user (admin only).
func (*Handler) AdminUpdatePolicy ¶
AdminUpdatePolicy handles PUT /mfa/admin/policy AdminUpdatePolicy the MFA policy for an app (admin only).
func (*Handler) DeleteFactor ¶
DeleteFactor handles DELETE /mfa/factors/:id.
func (*Handler) EnrollFactor ¶
EnrollFactor handles POST /mfa/factors/enroll.
func (*Handler) GetChallengeStatus ¶
GetChallengeStatus handles GET /mfa/challenge/:id.
func (*Handler) InitiateChallenge ¶
InitiateChallenge handles POST /mfa/challenge.
func (*Handler) ListFactors ¶
ListFactors handles GET /mfa/factors.
func (*Handler) ListTrustedDevices ¶
ListTrustedDevices handles GET /mfa/devices.
func (*Handler) RevokeTrustedDevice ¶
RevokeTrustedDevice handles DELETE /mfa/devices/:id.
func (*Handler) TrustDevice ¶
TrustDevice handles POST /mfa/devices/trust.
func (*Handler) UpdateFactor ¶
UpdateFactor handles PUT /mfa/factors/:id.
func (*Handler) VerifyChallenge ¶
VerifyChallenge handles POST /mfa/verify.
type InitiateChallengeRequest ¶
type InitiateChallengeRequest struct {
// Body fields
FactorTypes []FactorType `description:"Specific factor types to use for this challenge" json:"factorTypes,omitempty"`
Context string `` /* 148-byte string literal not displayed */
Metadata map[string]any `description:"Additional context metadata" json:"metadata,omitempty"`
}
InitiateChallengeRequest represents the request to start an MFA challenge.
type LimitResult ¶
type LimitResult struct {
Allowed bool
RetryAfter *time.Duration
AttemptsLeft int
LockoutEnds *time.Time
}
LimitResult represents the result of a rate limit check.
type ListFactorsRequest ¶
type ListFactorsRequest struct {
// Query parameters
ActiveOnly bool `description:"Return only active factors" query:"activeOnly"`
}
ListFactorsRequest represents the request to list factors.
type ListFactorsResponse ¶
type ListFactorsResponse struct {
Factors []Factor `description:"List of enrolled factors" json:"factors"`
Count int `description:"Total number of factors" json:"count"`
}
ListFactorsResponse represents the response containing factors list.
type ListTrustedDevicesResponse ¶
type ListTrustedDevicesResponse struct {
Devices []TrustedDevice `description:"List of trusted devices" json:"devices"`
Count int `description:"Total number of trusted devices" json:"count"`
}
ListTrustedDevicesResponse represents the response containing trusted devices.
type MFABypassResponse ¶
type MFABypassResponse struct {
ID xid.ID `json:"id"`
UserID xid.ID `json:"userId"`
ExpiresAt time.Time `json:"expiresAt"`
Reason string `json:"reason"`
}
MFABypassResponse contains MFA bypass details.
type MFAConfigResponse ¶
type MFAPolicy ¶
type MFAPolicy struct {
ID xid.ID `json:"id"`
OrganizationID xid.ID `json:"organizationId"`
RequiredFactorCount int `json:"requiredFactorCount"` // Number of factors required
AllowedFactorTypes []FactorType `json:"allowedFactorTypes"` // Permitted factor types
RequiredFactorTypes []FactorType `json:"requiredFactorTypes"` // Mandatory factor types
GracePeriodDays int `json:"gracePeriodDays"` // Days before MFA is enforced
TrustedDeviceDays int `json:"trustedDeviceDays"` // Days device is trusted
StepUpRequired bool `json:"stepUpRequired"` // Require step-up for sensitive ops
AdaptiveMFAEnabled bool `json:"adaptiveMfaEnabled"` // Enable risk-based MFA
MaxFailedAttempts int `json:"maxFailedAttempts"`
LockoutDurationMinutes int `json:"lockoutDurationMinutes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
MFAPolicy defines organization-level MFA requirements.
type MFAPolicyResponse ¶
type MFAPolicyResponse struct {
ID xid.ID `json:"id"`
AppID xid.ID `json:"appId"`
OrganizationID *xid.ID `json:"organizationId,omitempty"`
Enabled bool `json:"enabled"`
RequiredFactorCount int `json:"requiredFactorCount"`
AllowedFactorTypes []string `json:"allowedFactorTypes"`
GracePeriodDays int `json:"gracePeriodDays"`
}
MFAPolicyResponse contains MFA policy details.
type MFASession ¶
type MFASession struct {
ID xid.ID `json:"id"`
UserID xid.ID `json:"userId"`
SessionToken string `json:"sessionToken"`
FactorsRequired int `json:"factorsRequired"`
FactorsVerified int `json:"factorsVerified"`
VerifiedFactors []xid.ID `json:"verifiedFactors"`
RiskLevel RiskLevel `json:"riskLevel"`
IPAddress string `json:"ipAddress"`
UserAgent string `json:"userAgent"`
Metadata map[string]any `json:"metadata"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
}
MFASession represents an MFA verification session.
type MFAStatus ¶
type MFAStatus struct {
Enabled bool `json:"enabled"`
EnrolledFactors []FactorInfo `json:"enrolledFactors"`
RequiredCount int `json:"requiredCount"`
PolicyActive bool `json:"policyActive"`
GracePeriod *time.Time `json:"gracePeriod,omitempty"`
TrustedDevice bool `json:"trustedDevice"`
}
MFAStatus represents overall MFA status for a user.
type MessageResponse ¶
type MessageResponse = responses.MessageResponse
MessageResponse types - use shared responses from core.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements the plugins.Plugin interface for Multi-Factor Authentication.
func NewPlugin ¶
func NewPlugin(opts ...PluginOption) *Plugin
NewPlugin creates a new MFA plugin with optional configuration.
func (*Plugin) RegisterHooks ¶
func (p *Plugin) RegisterHooks(_ *hooks.HookRegistry) error
RegisterHooks registers MFA-related hooks.
func (*Plugin) RegisterRoutes ¶
RegisterRoutes registers MFA endpoints.
func (*Plugin) RegisterServiceDecorators ¶
func (p *Plugin) RegisterServiceDecorators(_ *registry.ServiceRegistry) error
RegisterServiceDecorators allows MFA to enhance core services.
func (*Plugin) Service ¶
Service returns the MFA service (for use by middleware and other components).
func (*Plugin) WithConfig ¶
WithConfig sets custom configuration.
type PluginOption ¶
type PluginOption func(*Plugin)
PluginOption is a functional option for configuring the MFA plugin.
func WithAdaptiveMFA ¶
func WithAdaptiveMFA(enabled bool, threshold float64) PluginOption
WithAdaptiveMFA sets the adaptive MFA configuration.
func WithBackupCodes ¶
func WithBackupCodes(enabled bool, count, length int) PluginOption
WithBackupCodes sets the backup codes configuration.
func WithDefaultConfig ¶
func WithDefaultConfig(cfg *Config) PluginOption
WithDefaultConfig sets the default configuration for the plugin.
func WithEmail ¶
func WithEmail(enabled bool, codeLength, expiryMinutes int) PluginOption
WithEmail sets the email configuration.
func WithEnabled ¶
func WithEnabled(enabled bool) PluginOption
WithEnabled sets whether MFA is enabled.
func WithGracePeriodDays ¶
func WithGracePeriodDays(days int) PluginOption
WithGracePeriodDays sets the grace period in days.
func WithRequireForAllUsers ¶
func WithRequireForAllUsers(required bool) PluginOption
WithRequireForAllUsers sets whether MFA is required for all users.
func WithSMS ¶
func WithSMS(enabled bool, codeLength, expiryMinutes int) PluginOption
WithSMS sets the SMS configuration.
func WithTOTP ¶
func WithTOTP(enabled bool, issuer string) PluginOption
WithTOTP sets the TOTP configuration.
type RateLimitConfig ¶
type RateLimitConfig struct {
Enabled bool `default:"true" json:"enabled"`
MaxAttempts int `default:"5" json:"max_attempts"`
WindowMinutes int `default:"15" json:"window_minutes"`
LockoutMinutes int `default:"30" json:"lockout_minutes"`
}
RateLimitConfig configures rate limiting.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides rate limiting for MFA operations.
func NewRateLimiter ¶
func NewRateLimiter(config *RateLimitConfig, repo *repository.MFARepository) *RateLimiter
NewRateLimiter creates a new rate limiter.
func (*RateLimiter) CheckFactorLimit ¶
func (r *RateLimiter) CheckFactorLimit(ctx context.Context, userID xid.ID, factorType FactorType) (*LimitResult, error)
CheckFactorLimit checks if a specific factor has exceeded rate limits.
func (*RateLimiter) CheckUserLimit ¶
func (r *RateLimiter) CheckUserLimit(ctx context.Context, userID xid.ID) (*LimitResult, error)
CheckUserLimit checks if a user has exceeded rate limits.
func (*RateLimiter) ClearLockout ¶
ClearLockout clears the lockout for a user (admin function).
func (*RateLimiter) GetExponentialBackoff ¶
func (r *RateLimiter) GetExponentialBackoff(attemptNumber int) time.Duration
GetExponentialBackoff calculates exponential backoff duration.
func (*RateLimiter) IsLockedOut ¶
IsLockedOut checks if a user is currently locked out.
func (*RateLimiter) RecordAttempt ¶
func (r *RateLimiter) RecordAttempt(ctx context.Context, userID xid.ID, factorID *xid.ID, factorType FactorType, success bool, metadata map[string]string) error
RecordAttempt records a verification attempt.
type ResetUserMFARequest ¶
type ResetUserMFARequest struct {
// Path parameters
ID string `description:"User ID whose MFA should be reset" path:"id" validate:"required"`
// Body fields
Reason string `description:"Reason for MFA reset (for audit trail)" json:"reason,omitempty" validate:"omitempty,min=1,max=500"`
}
ResetUserMFARequest represents the request to reset user's MFA (admin only).
type ResetUserMFAResponse ¶
type ResetUserMFAResponse struct {
Success bool `description:"Whether the reset was successful" json:"success"`
Message string `description:"Human-readable message" json:"message"`
FactorsReset int `description:"Number of factors that were reset" json:"factorsReset"`
DevicesRevoked int `description:"Number of trusted devices revoked" json:"devicesRevoked"`
}
ResetUserMFAResponse represents the response after resetting user's MFA.
type RevokeTrustedDeviceRequest ¶
type RevokeTrustedDeviceRequest struct {
// Path parameters
ID string `description:"Trusted device ID to revoke" path:"id" validate:"required"`
}
RevokeTrustedDeviceRequest represents the request to revoke a trusted device.
type RiskAssessment ¶
type RiskAssessment struct {
Level RiskLevel `json:"level"`
Score float64 `json:"score"` // 0-100
Factors []string `json:"factors"` // Risk factors identified
Recommended []FactorType `json:"recommended"` // Recommended factor types
Metadata map[string]any `json:"metadata"`
}
RiskAssessment represents authentication risk evaluation.
type RiskContext ¶
type RiskContext struct {
UserID xid.ID
IPAddress string
UserAgent string
Location string
DeviceID string
Timestamp time.Time
}
RiskContext contains contextual information for risk assessment.
type RiskEngine ¶
type RiskEngine struct {
// contains filtered or unexported fields
}
RiskEngine assesses authentication risk and recommends factors.
func NewRiskEngine ¶
func NewRiskEngine(config *AdaptiveMFAConfig, repo *repository.MFARepository) *RiskEngine
NewRiskEngine creates a new risk assessment engine.
func (*RiskEngine) AssessRisk ¶
func (e *RiskEngine) AssessRisk(ctx context.Context, riskCtx *RiskContext) (*RiskAssessment, error)
AssessRisk performs a comprehensive risk assessment.
func (*RiskEngine) GetRequiredFactorCount ¶
func (e *RiskEngine) GetRequiredFactorCount(level RiskLevel) int
GetRequiredFactorCount returns the number of factors required based on risk.
func (*RiskEngine) RequiresStepUp ¶
func (e *RiskEngine) RequiresStepUp(score float64) bool
RequiresStepUp determines if step-up authentication is needed.
type RiskFactor ¶
type RiskFactor struct {
Name string
Description string
Score float64 // 0-100
Weight float64 // 0-1
}
RiskFactor represents an identified risk factor.
type SMSConfig ¶
type SMSConfig struct {
Enabled bool `default:"true" json:"enabled"`
Provider string `json:"provider"` // "twilio", "vonage", etc.
CodeLength int `default:"6" json:"code_length"`
CodeExpiryMinutes int `default:"5" json:"code_expiry_minutes"`
TemplateID string `json:"template_id"`
RateLimit *RateLimitConfig `json:"rate_limit,omitempty"`
}
SMSConfig configures SMS verification settings.
type SMSFactorAdapter ¶
type SMSFactorAdapter struct {
BaseFactorAdapter
// contains filtered or unexported fields
}
SMSFactorAdapter integrates phone plugin as an MFA factor (not primary auth).
func NewSMSFactorAdapter ¶
func NewSMSFactorAdapter(phoneService *phone.Service, notifAdapter *notificationPlugin.Adapter, enabled bool) *SMSFactorAdapter
NewSMSFactorAdapter creates a new SMS factor adapter.
func (*SMSFactorAdapter) Challenge ¶
func (a *SMSFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
Challenge sends an SMS OTP code for MFA verification.
func (*SMSFactorAdapter) Enroll ¶
func (a *SMSFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
Enroll registers a phone number for MFA.
func (*SMSFactorAdapter) Verify ¶
func (a *SMSFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, data map[string]any) (bool, error)
Verify verifies an SMS OTP code.
func (*SMSFactorAdapter) VerifyEnrollment ¶
func (a *SMSFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
VerifyEnrollment sends a test code to verify phone works.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides MFA orchestration and management.
func NewService ¶
func NewService( repo *repository.MFARepository, adapterRegistry *FactorAdapterRegistry, notifAdapter *notificationPlugin.Adapter, config *Config, ) *Service
NewService creates a new MFA service.
func (*Service) DeleteFactor ¶
DeleteFactor removes a factor.
func (*Service) EnrollFactor ¶
func (s *Service) EnrollFactor(ctx context.Context, userID xid.ID, req *FactorEnrollmentRequest) (*FactorEnrollmentResponse, error)
EnrollFactor initiates factor enrollment for a user.
func (*Service) GetChallengeStatus ¶
func (s *Service) GetChallengeStatus(ctx context.Context, sessionID xid.ID, userID xid.ID) (*ChallengeStatusResponse, error)
GetChallengeStatus retrieves the current status of an MFA challenge/session.
func (*Service) GetMFAStatus ¶
func (s *Service) GetMFAStatus(ctx context.Context, userID xid.ID, deviceID string) (*MFAStatus, error)
GetMFAStatus returns the MFA status for a user.
func (*Service) GrantBypass ¶
func (s *Service) GrantBypass(ctx context.Context, appID, userID, grantedBy xid.ID, durationSeconds int, reason string) (*MFABypassResponse, error)
GrantBypass grants temporary MFA bypass for a user.
func (*Service) InitiateChallenge ¶
func (s *Service) InitiateChallenge(ctx context.Context, req *ChallengeRequest) (*ChallengeResponse, error)
InitiateChallenge starts an MFA verification challenge.
func (*Service) IsTrustedDevice ¶
func (s *Service) IsTrustedDevice(ctx context.Context, userID xid.ID, deviceID string) (bool, error)
IsTrustedDevice checks if a device is trusted.
func (*Service) ListFactors ¶
func (s *Service) ListFactors(ctx context.Context, userID xid.ID, activeOnly bool) ([]*Factor, error)
ListFactors lists all factors for a user.
func (*Service) ListTrustedDevices ¶
ListTrustedDevices lists all trusted devices for a user.
func (*Service) ResetUserMFA ¶
ResetUserMFA resets all MFA factors and devices for a user.
func (*Service) RevokeTrustedDevice ¶
RevokeTrustedDevice removes trust from a device.
func (*Service) TrustDevice ¶
TrustDevice marks a device as trusted.
func (*Service) UpdateFactor ¶
UpdateFactor updates factor settings.
func (*Service) UpdatePolicy ¶
func (s *Service) UpdatePolicy(ctx context.Context, appID xid.ID, orgID *xid.ID, updatedBy xid.ID, req *AdminPolicyRequest) (*MFAPolicyResponse, error)
UpdatePolicy updates the MFA policy for an app/organization.
func (*Service) VerifyChallenge ¶
func (s *Service) VerifyChallenge(ctx context.Context, req *VerificationRequest) (*VerificationResponse, error)
VerifyChallenge verifies a challenge response.
type SuccessResponse ¶
type SuccessResponse struct {
Message string `description:"Success message" json:"message"`
Data map[string]any `description:"Additional response data" json:"data,omitempty"`
}
SuccessResponse represents a standard success response.
type TOTPConfig ¶
type TOTPConfig struct {
Enabled bool `default:"true" json:"enabled"`
Issuer string `default:"AuthSome" json:"issuer"`
Period int `default:"30" json:"period"` // Seconds
Digits int `default:"6" json:"digits"`
Algorithm string `default:"SHA1" json:"algorithm"` // SHA1, SHA256, SHA512
WindowSize int `default:"1" json:"window_size"` // Past/future periods to accept
}
TOTPConfig configures TOTP (Google Authenticator) settings.
type TOTPFactorAdapter ¶
type TOTPFactorAdapter struct {
BaseFactorAdapter
// contains filtered or unexported fields
}
TOTPFactorAdapter integrates twofa plugin's TOTP functionality as an MFA factor.
func NewTOTPFactorAdapter ¶
func NewTOTPFactorAdapter(twofaService *twofa.Service, enabled bool) *TOTPFactorAdapter
NewTOTPFactorAdapter creates a new TOTP factor adapter.
func (*TOTPFactorAdapter) Challenge ¶
func (a *TOTPFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
Challenge initiates a TOTP verification challenge For TOTP, there's no async challenge - user provides code directly.
func (*TOTPFactorAdapter) Enroll ¶
func (a *TOTPFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
Enroll initiates TOTP enrollment.
func (*TOTPFactorAdapter) Verify ¶
func (a *TOTPFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, data map[string]any) (bool, error)
Verify verifies a TOTP code.
func (*TOTPFactorAdapter) VerifyEnrollment ¶
func (a *TOTPFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
VerifyEnrollment verifies TOTP enrollment by checking first code.
type TrustDeviceRequest ¶
type TrustDeviceRequest struct {
// Body fields
DeviceID string `description:"Unique device identifier" json:"deviceId" validate:"required"`
Name string `description:"User-friendly device name" json:"name,omitempty" validate:"omitempty,min=1,max=100"`
Metadata map[string]any `description:"Device metadata (OS, browser, etc.)" json:"metadata,omitempty"`
}
TrustDeviceRequest represents the request to trust a device.
type TrustedDevice ¶
type TrustedDevice struct {
ID xid.ID `json:"id"`
UserID xid.ID `json:"userId"`
DeviceID string `json:"deviceId"` // Fingerprint/identifier
Name string `json:"name"` // User-friendly name
Metadata map[string]any `json:"metadata"` // Device info
IPAddress string `json:"ipAddress"`
UserAgent string `json:"userAgent"`
LastUsedAt *time.Time `json:"lastUsedAt"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
}
TrustedDevice represents a device that can skip MFA.
type TrustedDevicesConfig ¶
type TrustedDevicesConfig struct {
Enabled bool `default:"true" json:"enabled"`
DefaultExpiryDays int `default:"30" json:"default_expiry_days"`
MaxExpiryDays int `default:"90" json:"max_expiry_days"`
MaxDevicesPerUser int `default:"5" json:"max_devices_per_user"`
}
TrustedDevicesConfig configures trusted device settings.
type UpdateFactorRequest ¶
type UpdateFactorRequest struct {
// Path parameters
ID string `description:"Factor ID" path:"id" validate:"required"`
// Body fields
Name *string `description:"New name for the factor" json:"name,omitempty" validate:"omitempty,min=1,max=100"`
Priority *FactorPriority `` /* 136-byte string literal not displayed */
Status *FactorStatus `` /* 128-byte string literal not displayed */
Metadata map[string]any `description:"Updated metadata" json:"metadata,omitempty"`
}
UpdateFactorRequest represents the request to update a factor.
type UpdatePolicyRequest ¶
type UpdatePolicyRequest struct {
// Body fields
RequiredFactorCount *int `` /* 142-byte string literal not displayed */
AllowedFactorTypes []FactorType `description:"Permitted factor types" json:"allowedFactorTypes,omitempty"`
RequiredFactorTypes []FactorType `description:"Mandatory factor types" json:"requiredFactorTypes,omitempty"`
GracePeriodDays *int `` /* 144-byte string literal not displayed */
TrustedDeviceDays *int `` /* 144-byte string literal not displayed */
StepUpRequired *bool `description:"Require step-up authentication for sensitive operations" json:"stepUpRequired,omitempty"`
AdaptiveMFAEnabled *bool `description:"Enable risk-based MFA" json:"adaptiveMfaEnabled,omitempty"`
MaxFailedAttempts *int `` /* 143-byte string literal not displayed */
LockoutDurationMinutes *int `` /* 145-byte string literal not displayed */
}
UpdatePolicyRequest represents the request to update MFA policy (admin only).
type VerificationRequest ¶
type VerificationRequest struct {
ChallengeID xid.ID `json:"challengeId"`
FactorID xid.ID `json:"factorId"`
Code string `json:"code,omitempty"`
Data map[string]any `json:"data,omitempty"`
RememberDevice bool `json:"rememberDevice,omitempty"`
DeviceInfo *DeviceInfo `json:"deviceInfo,omitempty"`
}
VerificationRequest verifies a challenge.
type VerificationResponse ¶
type VerificationResponse struct {
Success bool `json:"success"`
SessionComplete bool `json:"sessionComplete"`
FactorsRemaining int `json:"factorsRemaining,omitempty"`
Token string `json:"token,omitempty"` // MFA completion token
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
}
VerificationResponse indicates verification result.
type VerifyChallengeRequest ¶
type VerifyChallengeRequest struct {
// Body fields
ChallengeID xid.ID `description:"ID of the challenge to verify" json:"challengeId" validate:"required"`
FactorID xid.ID `description:"ID of the factor being used" json:"factorId" validate:"required"`
Code string `description:"Verification code for OTP-based factors" json:"code,omitempty" validate:"required_without=Data"`
Data map[string]any `description:"Verification data for complex factors" json:"data,omitempty"`
RememberDevice bool `description:"Whether to trust this device" json:"rememberDevice,omitempty"`
DeviceInfo *DeviceInfo `description:"Device identification information" json:"deviceInfo,omitempty"`
}
VerifyChallengeRequest represents the request to verify an MFA challenge.
type VerifyEnrolledFactorRequest ¶
type VerifyEnrolledFactorRequest struct {
// Path parameters
ID string `description:"Factor ID to verify" path:"id" validate:"required"`
// Body fields
Code string `description:"Verification code for OTP-based factors" json:"code,omitempty" validate:"required_without=Data"`
Data map[string]any `description:"Verification data for complex factors (WebAuthn, etc.)" json:"data,omitempty"`
}
VerifyEnrolledFactorRequest represents the request to verify an enrolled factor.
type WebAuthnConfig ¶
type WebAuthnConfig struct {
Enabled bool `default:"true" json:"enabled"`
RPDisplayName string `default:"AuthSome" json:"rp_display_name"`
RPID string `json:"rp_id"` // e.g., "example.com"
RPOrigins []string `json:"rp_origins"` // Allowed origins
AttestationPreference string `default:"none" json:"attestation_preference"` // none, indirect, direct
AuthenticatorSelection struct {
RequireResidentKey bool `default:"false" json:"require_resident_key"`
ResidentKeyRequirement string `default:"preferred" json:"resident_key_requirement"` // discouraged, preferred, required
UserVerification string `default:"preferred" json:"user_verification"` // discouraged, preferred, required
} `json:"authenticator_selection"`
Timeout int `default:"60000" json:"timeout"` // Milliseconds
}
WebAuthnConfig configures WebAuthn/FIDO2 settings.
type WebAuthnFactorAdapter ¶
type WebAuthnFactorAdapter struct {
BaseFactorAdapter
// contains filtered or unexported fields
}
WebAuthnFactorAdapter integrates passkey plugin as an MFA factor This adapter enables passkeys to be used as a second authentication factor while maintaining support for standalone passwordless authentication.
func NewWebAuthnFactorAdapter ¶
func NewWebAuthnFactorAdapter(passkeyService *passkey.Service, enabled bool) *WebAuthnFactorAdapter
NewWebAuthnFactorAdapter creates a new WebAuthn factor adapter.
func (*WebAuthnFactorAdapter) Challenge ¶
func (a *WebAuthnFactorAdapter) Challenge(ctx context.Context, factor *Factor, metadata map[string]any) (*Challenge, error)
Challenge initiates a WebAuthn authentication challenge for MFA verification.
func (*WebAuthnFactorAdapter) Enroll ¶
func (a *WebAuthnFactorAdapter) Enroll(ctx context.Context, userID xid.ID, metadata map[string]any) (*FactorEnrollmentResponse, error)
Enroll initiates WebAuthn credential registration for MFA.
func (*WebAuthnFactorAdapter) IsAvailable ¶
func (a *WebAuthnFactorAdapter) IsAvailable() bool
IsAvailable checks if WebAuthn factor is available.
func (*WebAuthnFactorAdapter) Verify ¶
func (a *WebAuthnFactorAdapter) Verify(ctx context.Context, challenge *Challenge, response string, data map[string]any) (bool, error)
Verify verifies the WebAuthn challenge response.
func (*WebAuthnFactorAdapter) VerifyEnrollment ¶
func (a *WebAuthnFactorAdapter) VerifyEnrollment(ctx context.Context, enrollmentID xid.ID, proof string) error
VerifyEnrollment completes WebAuthn credential registration.