Documentation
¶
Overview ¶
Package auth provides storage-neutral authentication services, provider adapters, token utilities, guarded HTTP handlers, and credential interfaces.
Hosts supply account policy, persistence, browser cookies, CSRF and abuse controls, email delivery, and deployment-specific wiring.
nexss/plugins/auth/memorystore.go
Replace the top part of auth/middleware.go with this:
Package auth provides highly scalable authentication, authorisation, and multi-tenancy.
Path: nexss/plugins/auth/oauth.go
Index ¶
- Constants
- Variables
- func BrowserSessionBinding(ctx context.Context) (string, bool)
- func CookieToken(cookieName string) func(r *http.Request) string
- func HashPassword(password string) (string, error)
- func InitKeys(privPEM, pubPEM []byte) error
- func InitOrLoadPersistentKeys(privPath, pubPath string) error
- func InitTempKeys() error
- func JWTMiddleware(cfg JWTConfig) func(http.Handler) http.Handler
- func NewCurrentSessionAction(service *Service) *action.BuiltAction[CurrentSessionRequest, CurrentSessionResponse]
- func NewPKCEVerifier() (string, error)
- func NewStateToken() (string, error)
- func PKCEChallenge(verifier string) (string, error)
- func QueryToken(param string) func(r *http.Request) string
- func TokenDigest(value string) string
- func TurnstileActionForOperation(operation BoundaryOperation) (string, bool)
- func ValidateProviderRedirectURL(value string) error
- func ValidateTurnstileOperations(operations ...BoundaryOperation) error
- func VerifyPassword(password, encodedHash string) error
- func VerifyToken(tokenString string) (*jwt.Token, error)
- func WithBrowserSessionBinding(ctx context.Context, sessionIDDigest string) context.Context
- func WithHTTPExchange(ctx context.Context, request *http.Request, response http.ResponseWriter) context.Context
- type Account
- type AccountStore
- type ActionTokenModel
- type AppleProviderConfig
- type AuthEmail
- type BoundaryOperation
- type BrowserSession
- type BrowserSessionHost
- type BrowserSessionLifetime
- type CloudflareTurnstileConfig
- type CloudflareTurnstileVerifier
- type Configdeprecated
- type CurrentSessionRequest
- type CurrentSessionResponse
- type DesktopAuthCode
- type DesktopAuthRequest
- type DesktopAuthStore
- type DesktopBearer
- type DesktopBearerStore
- type EmailMFAProvider
- type EmailSender
- type EmailVerificationMode
- type Emailer
- type FacebookProviderConfig
- type FeatureModel
- type FeatureSet
- type GORMStore
- func (s *GORMStore) CreateRefreshToken(ctx context.Context, userID, tokenID string, expiry time.Time) error
- func (s *GORMStore) CreateResetToken(ctx context.Context, userID, token string, expiry time.Time) error
- func (s *GORMStore) CreateUser(ctx context.Context, u *User) error
- func (s *GORMStore) CreateVerificationToken(ctx context.Context, userID, token string, expiry time.Time) error
- func (s *GORMStore) DeleteResetToken(ctx context.Context, token string) error
- func (s *GORMStore) DeleteUser(ctx context.Context, id string) error
- func (s *GORMStore) DeleteVerificationToken(ctx context.Context, token string) error
- func (s *GORMStore) GetOAuthAccount(ctx context.Context, provider, providerUserID string) (string, error)
- func (s *GORMStore) GetResetToken(ctx context.Context, token string) (string, error)
- func (s *GORMStore) GetRolePermissions(ctx context.Context, role string) ([]string, error)
- func (s *GORMStore) GetTenantFeatures(ctx context.Context, tenantID string) ([]string, error)
- func (s *GORMStore) GetTenantRole(ctx context.Context, userID, tenantID string) (string, error)
- func (s *GORMStore) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (s *GORMStore) GetUserByID(ctx context.Context, id string) (*User, error)
- func (s *GORMStore) GetUserFeatures(ctx context.Context, userID string) ([]string, error)
- func (s *GORMStore) GetUserRoles(ctx context.Context, userID string) ([]string, error)
- func (s *GORMStore) GetUserTenants(ctx context.Context, userID string) ([]TenantAccess, error)
- func (s *GORMStore) GetVerificationToken(ctx context.Context, token string) (string, error)
- func (s *GORMStore) LinkOAuthAccount(ctx context.Context, userID, provider, providerUserID string) error
- func (s *GORMStore) PruneExpiredTokens(ctx context.Context) error
- func (s *GORMStore) RevokeAllUserTokens(ctx context.Context, userID string) error
- func (s *GORMStore) RevokeRefreshToken(ctx context.Context, tokenID string) error
- func (s *GORMStore) UpdateUser(ctx context.Context, u *User) error
- func (s *GORMStore) ValidateRefreshToken(ctx context.Context, tokenID string) (string, error)
- type GitHubProviderConfig
- type GoogleProviderConfig
- type HTTPConfig
- type HTTPExchange
- type HTTPHandler
- type HostPolicy
- type JWTConfig
- type MFAProvider
- type NewPasswordAccount
- type NoopEmailer
- type OAuthAccountModel
- type OAuthCallbackOutcome
- type OAuthCallbackRedirector
- type OAuthConfig
- type OAuthProvider
- func NewAppleProvider(ctx context.Context, config AppleProviderConfig) (OAuthProvider, error)
- func NewFacebookProvider(config FacebookProviderConfig) (OAuthProvider, error)
- func NewGitHubProvider(config GitHubProviderConfig) (OAuthProvider, error)
- func NewGoogleProvider(ctx context.Context, config GoogleProviderConfig) (OAuthProvider, error)
- type OAuthProviderDTO
- type OAuthStateStore
- type OneTimeTokenRevoker
- type OneTimeTokenStore
- type OneTimeTokens
- type OpaqueToken
- type PendingOAuthLinkStore
- type PendingOAuthState
- type PermissionModel
- type Plugin
- func New(cfg Config) (*Plugin, error)deprecated
- type ProviderCallbackResult
- type ProviderIdentity
- type RBACStore
- type RefreshTokenModel
- type RegistrationAttempt
- type RequestBoundary
- type RoleModel
- type Service
- func (s *Service) AuthenticatePassword(ctx context.Context, identifier, password string) (Account, error)
- func (s *Service) BeginProviderLogin(ctx context.Context, providerName, redirectURL string, linkCurrentAccount bool, ...) (string, error)
- func (s *Service) CompleteProviderCallback(ctx context.Context, providerName, state, code string) (ProviderCallbackResult, error)
- func (s *Service) CompleteProviderLogin(ctx context.Context, providerName, state, code string) (Account, error)
- func (s *Service) CurrentBrowserAccount(ctx context.Context) (Account, bool, error)
- func (s *Service) EmailVerificationMode(ctx context.Context) (EmailVerificationMode, error)
- func (s *Service) EndBrowserSession(ctx context.Context) error
- func (s *Service) ExchangeDesktopAuthCode(ctx context.Context, code, verifier string) (string, time.Time, error)
- func (s *Service) IssueDesktopAuthCode(ctx context.Context, state string, account Account) (string, error)
- func (s *Service) LinkPendingProviderIdentity(ctx context.Context) error
- func (s *Service) RegisterPassword(ctx context.Context, attempt RegistrationAttempt, ...) (Account, error)
- func (s *Service) RequestEmailVerification(ctx context.Context, email string) error
- func (s *Service) RequestPasswordReset(ctx context.Context, email string) error
- func (s *Service) ResetPassword(ctx context.Context, token, password, confirmation string) error
- func (s *Service) ResolveDesktopBearer(ctx context.Context, token string) (Account, bool, error)
- func (s *Service) StartBrowserSession(ctx context.Context, account Account) error
- func (s *Service) StartDesktopAuth(ctx context.Context, state, challenge, redirectURI string) error
- func (s *Service) VerifyEmail(ctx context.Context, token string) error
- type ServiceConfig
- type Store
- type TenantAccess
- type TenantFeatureModel
- type TenantMemberModel
- type Token
- type Tokens
- type TurnstileRequestBoundary
- type TurnstileVerifier
- type User
- type UserModel
Constants ¶
const ( PasswordMinBytes = 12 PasswordMaxBytes = 72 PasswordResetTTL = time.Hour EmailVerificationTTL = 24 * time.Hour OAuthStateTTL = 10 * time.Minute DesktopAuthRequestTTL = 10 * time.Minute DesktopAuthCodeTTL = 2 * time.Minute DesktopBearerTTL = 30 * 24 * time.Hour )
const ( EmailPasswordReset = "password_reset" EmailVerifyAddress = "email_verification" )
Variables ¶
var ( ErrRequestDenied = errors.New("authentication request denied by host boundary") ErrRateLimited = errors.New("authentication request rate limited by host boundary") )
var ( // ErrInvalidOneTimeToken covers an unknown, expired, or already-consumed token. ErrInvalidOneTimeToken = errors.New("invalid, expired, or consumed one-time token") ErrOneTimeTokenStoreUnavailable = errors.New("one-time token store is unavailable") )
var ( // ErrPasswordMismatch means the supplied password does not match the stored hash. ErrPasswordMismatch = errors.New("password does not match") // ErrUnsupportedPasswordHash means the stored hash algorithm is not supported here. ErrUnsupportedPasswordHash = errors.New("unsupported password hash") // ErrInvalidPasswordHash means a recognized bcrypt hash is malformed or invalid. ErrInvalidPasswordHash = errors.New("invalid password hash") )
var ( ErrAccountNotFound = errors.New("account not found") ErrInvalidCredentials = errors.New("invalid email or password") ErrEmailNotVerified = errors.New("email verification is required") ErrInvalidInput = errors.New("invalid authentication input") ErrAccountLinkRequired = errors.New("sign in to the existing account to link this provider") ErrInvalidDesktopAuth = errors.New("invalid or expired desktop authorization") ErrVerificationModeUnset = errors.New("host email verification mode must be explicitly configured") )
var ( ErrInvalidOAuthResponse = errors.New("invalid or expired OAuth response") ErrOAuthEmailMismatch = errors.New("provider-verified email does not match the existing account") )
Functions ¶
func BrowserSessionBinding ¶
BrowserSessionBinding returns the opaque-cookie digest attached by the host session middleware. Callers must never put the raw cookie value in context.
func HashPassword ¶
HashPassword creates a bcrypt hash. Length and account policy belong to the caller.
func InitKeys ¶
InitKeys validates and installs a matching RSA key pair with at least 2048 bits. Parsed keys are swapped together so signing and verification cannot see a partially initialized or mismatched pair.
func InitOrLoadPersistentKeys ¶
InitOrLoadPersistentKeys loads a complete key pair, or creates one only when both files are absent. A partial or unreadable pair is an error, not a reason to silently replace credentials.
func InitTempKeys ¶
func InitTempKeys() error
InitTempKeys generates one process-local 2048-bit RSA key pair if keys have not already been installed. The generated key is unsuitable for persistent production sessions because it changes when the process restarts.
func NewCurrentSessionAction ¶
func NewCurrentSessionAction(service *Service) *action.BuiltAction[CurrentSessionRequest, CurrentSessionResponse]
NewCurrentSessionAction returns the read-only Kernel action surface for auth. It verifies both Kernel's trusted user scope and the host's current browser session; credential entry and exchange operations remain on HTTP routes.
func NewPKCEVerifier ¶
NewPKCEVerifier creates a 32-byte verifier using the unpadded URL-safe base64url alphabet for OAuth and desktop handoffs.
func NewStateToken ¶
NewStateToken creates a 256-bit lowercase-hex OAuth or desktop state value.
func PKCEChallenge ¶
PKCEChallenge returns the S256 challenge for a verifier valid under the RFC 7636 43-128 character verifier syntax.
func TokenDigest ¶
TokenDigest returns the lowercase SHA-256 hex digest of the exact token bytes.
func TurnstileActionForOperation ¶ added in v0.2.0
func TurnstileActionForOperation(operation BoundaryOperation) (string, bool)
TurnstileActionForOperation returns the exact action string expected in the Siteverify response for operations that accept a client-supplied response token.
func ValidateProviderRedirectURL ¶
ValidateProviderRedirectURL is exposed for host config checks. OAuth redirect URLs must be canonical HTTPS URLs; HTTP is permitted only for localhost or loopback development endpoints.
func ValidateTurnstileOperations ¶ added in v0.2.0
func ValidateTurnstileOperations(operations ...BoundaryOperation) error
ValidateTurnstileOperations rejects operations that have no client-supplied Turnstile token in their request contract.
func VerifyPassword ¶
VerifyPassword compares a candidate against a supported bcrypt hash. It accepts $2y$ and $2a$ encodings, and does not create hashes or apply account policy.
func WithBrowserSessionBinding ¶
WithBrowserSessionBinding attaches the SHA-256 digest of the current opaque browser-cookie ID to a request context. Durable OAuth stores use it to bind one-use state to the same browser session without storing the cookie value.
func WithHTTPExchange ¶
func WithHTTPExchange(ctx context.Context, request *http.Request, response http.ResponseWriter) context.Context
WithHTTPExchange attaches the active HTTP exchange to ctx. A nil ctx is returned unchanged; callers should supply a request context.
Types ¶
type Account ¶
type Account struct {
ID string
Email string
Username string
PasswordHash string
EmailVerified bool
AuthVersion uint64
}
Account contains only generic authentication state. Organization membership, roles, platform-admin status, and invitation state remain application-owned.
type AccountStore ¶
type AccountStore interface {
FindByIdentifier(ctx context.Context, identifier string) (Account, error)
FindByEmail(ctx context.Context, email string) (Account, error)
FindByID(ctx context.Context, id string) (Account, error)
UpdatePasswordAndRevokeAuth(ctx context.Context, subject, passwordHash string) error
MarkEmailVerified(ctx context.Context, subject string) error
FindByProviderIdentity(ctx context.Context, provider, subject string) (Account, error)
LinkProviderIdentity(ctx context.Context, userID, provider, subject, emailAtLink string) error
}
AccountStore is the application persistence seam. UpdatePasswordAndRevokeAuth must atomically update the password, increment its session version, revoke desktop credentials, and invalidate outstanding desktop exchanges/reset links.
type ActionTokenModel ¶
type ActionTokenModel struct {
Token string `gorm:"primaryKey;type:varchar(64)"`
Type string `gorm:"index;type:varchar(16)"` // "verify" or "reset"
UserID string `gorm:"index;type:varchar(36);not null"`
ExpiresAt time.Time `gorm:"index"`
}
func (ActionTokenModel) TableName ¶
func (ActionTokenModel) TableName() string
type AppleProviderConfig ¶
type AppleProviderConfig struct {
ClientID string
TeamID string
KeyID string
PrivateKeyPEM []byte
RedirectURL string
HTTPClient *http.Client
}
AppleProviderConfig contains host-owned Apple Sign in with Apple credentials.
type AuthEmail ¶
AuthEmail is a notification event, not a rendered message. The host owns its email templates, canonical links, sender identity, and delivery provider.
type BoundaryOperation ¶
type BoundaryOperation string
BoundaryOperation names the public operation for the host's Turnstile, terms, CSRF, registration eligibility, and rate-limit adapter.
const ( BoundaryLogin BoundaryOperation = "login" BoundaryRegister BoundaryOperation = "register" BoundaryPasswordReset BoundaryOperation = "password_reset" BoundaryEmailVerify BoundaryOperation = "email_verify" BoundaryOAuthBegin BoundaryOperation = "oauth_begin" BoundaryOAuthCallback BoundaryOperation = "oauth_callback" BoundaryOAuthLink BoundaryOperation = "oauth_link" BoundaryDesktopStart BoundaryOperation = "desktop_start" BoundaryDesktopExchange BoundaryOperation = "desktop_exchange" BoundaryLogout BoundaryOperation = "logout" )
func DefaultTurnstileOperations ¶ added in v0.2.0
func DefaultTurnstileOperations() []BoundaryOperation
DefaultTurnstileOperations returns operations that should receive a challenge by default in public browser-facing deployments. OAuth callbacks, authenticated account linking, logout, and PKCE code exchange use separate state/session protections and are intentionally not included.
type BrowserSession ¶
type BrowserSession struct {
Subject string
AuthVersion uint64
StartedAt time.Time
ExpiresAt time.Time
}
BrowserSession is the policy-neutral identity/time data a host may place in its browser-session mechanism. AuthVersion corresponds to a host's account session version; it is not an organization role or authorization policy.
type BrowserSessionHost ¶
type BrowserSessionHost interface {
EstablishBrowserSession(ctx context.Context, session BrowserSession) error
CurrentBrowserSession(ctx context.Context) (BrowserSession, bool, error)
EndBrowserSession(ctx context.Context) error
}
BrowserSessionHost is the explicit seam for browser cookie/session behavior. The host owns cookie attributes, session-ID rotation, CSRF state, absolute expiry enforcement, database identity binding, and session invalidation. This is deliberately distinct from DesktopBearerStore; browser cookies are not desktop bearer credentials.
type BrowserSessionLifetime ¶
BrowserSessionLifetime lets the host preserve per-account session settings.
type CloudflareTurnstileConfig ¶ added in v0.2.0
CloudflareTurnstileConfig contains server-only Siteverify settings. SecretKey must never be sent to a browser or stored in Flow source. ExpectedHostname is compared to Cloudflare's verified hostname response.
type CloudflareTurnstileVerifier ¶ added in v0.2.0
type CloudflareTurnstileVerifier struct {
// contains filtered or unexported fields
}
CloudflareTurnstileVerifier verifies responses with Cloudflare Siteverify. Siteverify is called once per token; this client does not retry single-use tokens.
func NewCloudflareTurnstileVerifier ¶ added in v0.2.0
func NewCloudflareTurnstileVerifier(config CloudflareTurnstileConfig) (*CloudflareTurnstileVerifier, error)
NewCloudflareTurnstileVerifier constructs a verifier with a fixed HTTPS endpoint, bounded response size, a five-second maximum timeout, and redirects disabled. No environment variables are read automatically.
func (*CloudflareTurnstileVerifier) Verify ¶ added in v0.2.0
func (verifier *CloudflareTurnstileVerifier) Verify(ctx context.Context, responseToken, expectedAction string) error
Verify sends the response token to Cloudflare and requires success, the configured hostname, and an exact action match. The optional remoteip field is deliberately omitted because this package cannot know whether proxy IP headers were validated by the host.
type Config
deprecated
type Config struct {
Store Store
Emailer Emailer
JWTPublicKey []byte
JWTPrivateKey []byte
BaseURL string // e.g., "https://app.example.com"
Env string // "development", "production", etc.
// Token Lifecycles
AccessTTL time.Duration // Default: 15m
RefreshTTL time.Duration // Default: 30d
ResetTokenTTL time.Duration // Default: 1h
VerifyTokenTTL time.Duration // Default: 24h
// Brute-force & DDoS Protection (Login Endpoint)
LoginRateLimitRPS float64 // Default: 5.0
LoginRateLimitBurst int // Default: 2
LoginConcurrency int32 // Default: 20 (Prevents bcrypt CPU starvation)
LoginTimeout time.Duration // Default: 3s
// Semantic Brute-Force Protection (Fail2Ban)
LoginMaxFailures int // e.g., 5 failed attempts
LoginFailWindow time.Duration // e.g., within 15 minutes
LoginLockout time.Duration // e.g., ban for 30 minutes
// DesktopMode enables legacy local-development behavior. It does not make the
// legacy plugin suitable for production or public network exposure.
DesktopMode bool
// PublicPaths bypasses JWT validation for specified prefixes.
PublicPaths []string
OAuthProviders []OAuthConfig
MFAProviders map[string]MFAProvider
ActionCodeTTL time.Duration
}
Config controls the legacy authentication plugin.
Deprecated: Config is for development/test compatibility. Production hosts must supply adapters through Service and use the guarded HTTP or Flow APIs.
type CurrentSessionRequest ¶
type CurrentSessionRequest struct{}
CurrentSessionRequest contains no caller-supplied identity or credentials.
type CurrentSessionResponse ¶
type CurrentSessionResponse struct {
AccountID string `json:"account_id"`
EmailVerified bool `json:"email_verified"`
}
CurrentSessionResponse contains only the public identity fields needed by a caller. Password hashes, bearer credentials, and auth-version state are never returned by this action.
type DesktopAuthCode ¶
type DesktopAuthRequest ¶
DesktopAuthRequest and DesktopAuthCode are short-lived records required for the PHP-compatible browser-to-native PKCE handoff.
type DesktopAuthStore ¶
type DesktopAuthStore interface {
CreateDesktopAuthRequest(ctx context.Context, stateDigest string, request DesktopAuthRequest) error
HasDesktopAuthRequest(ctx context.Context, stateDigest string, now time.Time) (bool, error)
ConsumeDesktopAuthRequest(ctx context.Context, stateDigest string, now time.Time, apply func(context.Context, DesktopAuthRequest) error) error
CreateDesktopAuthCode(ctx context.Context, codeDigest string, code DesktopAuthCode) error
ConsumeDesktopAuthCode(ctx context.Context, codeDigest string, now time.Time, apply func(context.Context, DesktopAuthCode) error) error
}
DesktopAuthStore must implement atomic consume-and-apply operations. In particular, consuming a code and storing the bearer credential must share a transaction when the host database supports transactions.
type DesktopBearer ¶
DesktopBearer is the neutral server-side record for a desktop bearer token. Store the token digest, not the plaintext value.
type DesktopBearerStore ¶
type DesktopBearerStore interface {
StoreDesktopBearer(ctx context.Context, digest string, bearer DesktopBearer) error
ResolveDesktopBearer(ctx context.Context, digest string, now time.Time) (DesktopBearer, bool, error)
RevokeDesktopBearer(ctx context.Context, digest string, at time.Time) (bool, error)
}
DesktopBearerStore is a distinct host seam for server-side opaque bearer records. Implementations own persistence, revocation, expiry comparisons, and any last-used bookkeeping; the module supplies token generation and digesting. Resolve must reject revoked, expired, or stale-AuthVersion credentials.
type EmailMFAProvider ¶
type EmailMFAProvider struct {
// contains filtered or unexported fields
}
EmailMFAProvider to domyślna implementacja 2FA wysyłająca kod na e-mail.
func NewEmailMFAProvider ¶
func NewEmailMFAProvider(store Store, emailer Emailer) *EmailMFAProvider
func (*EmailMFAProvider) ID ¶
func (p *EmailMFAProvider) ID() string
func (*EmailMFAProvider) Name ¶
func (p *EmailMFAProvider) Name() string
func (*EmailMFAProvider) Type ¶
func (p *EmailMFAProvider) Type() string
type EmailSender ¶
EmailSender is implemented by the host's mailer/template adapter.
type EmailVerificationMode ¶
type EmailVerificationMode string
EmailVerificationMode is a host-selected policy. There is intentionally no default. Each host must explicitly choose its deployment behavior.
const ( VerificationDisabled EmailVerificationMode = "disabled" VerificationOptional EmailVerificationMode = "optional" VerificationRequired EmailVerificationMode = "required" )
type FacebookProviderConfig ¶
FacebookProviderConfig contains host-supplied Facebook Login settings. The adapter uses PKCE and deliberately does not send an app secret in the token-exchange URL.
type FeatureModel ¶
type FeatureModel struct {
UserID string `gorm:"primaryKey;type:varchar(36)"`
Feature string `gorm:"primaryKey;type:varchar(64)"`
}
func (FeatureModel) TableName ¶
func (FeatureModel) TableName() string
type FeatureSet ¶
type FeatureSet map[string]struct{}
FeatureSet provides O(1) feature flag lookups.
func NewFeatureSet ¶
func NewFeatureSet(features []string) FeatureSet
func (FeatureSet) Has ¶
func (fs FeatureSet) Has(feature string) bool
type GORMStore ¶
type GORMStore struct {
// contains filtered or unexported fields
}
func (*GORMStore) CreateRefreshToken ¶
func (*GORMStore) CreateResetToken ¶
func (*GORMStore) CreateVerificationToken ¶
func (*GORMStore) DeleteResetToken ¶
func (*GORMStore) DeleteVerificationToken ¶
func (*GORMStore) GetOAuthAccount ¶
func (*GORMStore) GetResetToken ¶
func (*GORMStore) GetRolePermissions ¶
func (*GORMStore) GetTenantFeatures ¶
func (*GORMStore) GetTenantRole ¶
func (*GORMStore) GetUserByEmail ¶
func (*GORMStore) GetUserByID ¶
func (*GORMStore) GetUserFeatures ¶
func (*GORMStore) GetUserRoles ¶
func (*GORMStore) GetUserTenants ¶
func (*GORMStore) GetVerificationToken ¶
func (*GORMStore) LinkOAuthAccount ¶
func (*GORMStore) PruneExpiredTokens ¶
func (*GORMStore) RevokeAllUserTokens ¶
func (*GORMStore) RevokeRefreshToken ¶
type GitHubProviderConfig ¶
type GitHubProviderConfig struct {
ClientID string
ClientSecret string
RedirectURL string
HTTPClient *http.Client
}
GitHubProviderConfig contains only host-supplied GitHub OAuth settings.
type GoogleProviderConfig ¶
type GoogleProviderConfig struct {
ClientID string
ClientSecret string
RedirectURL string
HTTPClient *http.Client
}
GoogleProviderConfig contains only host-supplied Google OAuth settings. The redirect URI must be the exact canonical callback registered with Google.
type HTTPConfig ¶
type HTTPConfig struct {
Service *Service
Boundary RequestBoundary
OAuthCallbackRedirector OAuthCallbackRedirector
}
HTTPConfig contains an auth service and the mandatory untrusted-boundary guard.
type HTTPExchange ¶
type HTTPExchange struct {
Request *http.Request
Response http.ResponseWriter
}
HTTPExchange carries the live HTTP request and response writer for one request. It is intentionally request-scoped: host-owned BrowserSessionHost implementations can read the validated request and write/clear session cookies before the response is committed. Never log or serialize it.
func HTTPExchangeFromContext ¶
func HTTPExchangeFromContext(ctx context.Context) (HTTPExchange, bool)
HTTPExchangeFromContext returns the request-scoped exchange, if one was attached by the HTTP host.
type HTTPHandler ¶
type HTTPHandler struct {
// contains filtered or unexported fields
}
func NewHTTPHandler ¶
func NewHTTPHandler(config HTTPConfig) (*HTTPHandler, error)
NewHTTPHandler refuses to expose auth routes without the host security boundary that preserves Turnstile, terms, CSRF, and rate limiting.
func NewSecureHTTPHandler ¶ added in v0.2.0
func NewSecureHTTPHandler(config HTTPConfig, verifier TurnstileVerifier) (*HTTPHandler, error)
NewSecureHTTPHandler composes the default Turnstile gate with the host boundary before mounting public auth routes. Use NewHTTPHandler directly only when the host intentionally provides equivalent anti-abuse verification itself.
func (*HTTPHandler) ServeHTTP ¶
func (handler *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type HostPolicy ¶
type HostPolicy interface {
EmailVerificationMode(ctx context.Context) (EmailVerificationMode, error)
CreatePasswordAccount(ctx context.Context, attempt RegistrationAttempt, account NewPasswordAccount) (Account, error)
ProvisionProviderAccount(ctx context.Context, identity ProviderIdentity, attempt RegistrationAttempt) (Account, error)
}
HostPolicy owns registration decisions, the explicit verification mode, and provider-backed account creation. CreatePasswordAccount must perform all eligibility/invite/first-admin/terms checks and persist the account in one host transaction. ProvisionProviderAccount must apply those same rules and create the account plus linked identity atomically. It must not mark an unverified provider email verified unless the host independently verified it.
type MFAProvider ¶
type MFAProvider interface {
ID() string
Name() string
Type() string // Zwraca typ interfejsu UI: "code", "webauthn", "push"
Challenge(ctx context.Context, user *User) (hint string, err error)
Verify(ctx context.Context, user *User, input string) error
}
MFAProvider definiuje kontrakt dla strategii autoryzacji dwuetapowej (Strategy Pattern). Umożliwia łatwe dodawanie SMS, TOTP, WebAuthn itp. bez zmiany rdzenia.
type NewPasswordAccount ¶
type NewPasswordAccount struct {
Email string
Username string
PasswordHash string
EmailVerified bool
}
NewPasswordAccount is passed to the host persistence adapter. PasswordHash is a bcrypt-compatible hash; the host owns uniqueness and bootstrap transactions.
type NoopEmailer ¶
type NoopEmailer struct{}
NoopEmailer acts as a null-sink for testing/local setups. Logs outputs directly.
type OAuthAccountModel ¶
type OAuthAccountModel struct {
Provider string `gorm:"primaryKey;type:varchar(64)"`
ProviderUserID string `gorm:"primaryKey;type:varchar(128)"`
UserID string `gorm:"type:varchar(36);index;not null"`
}
OAuthAccountModel stores links between OAuth providers and local users.
func (OAuthAccountModel) TableName ¶
func (OAuthAccountModel) TableName() string
type OAuthCallbackOutcome ¶
type OAuthCallbackOutcome struct {
Provider string
AccountID string
Registration RegistrationAttempt
DesktopState string
Err error
}
OAuthCallbackOutcome gives the trusted host enough context to restore its existing login/editor redirect behavior. The callback must use configured host destinations, never a URL supplied by the browser.
type OAuthCallbackRedirector ¶
type OAuthCallbackRedirector func(ctx context.Context, outcome OAuthCallbackOutcome) (string, error)
type OAuthConfig ¶
type OAuthConfig struct {
Provider string // e.g., "google"
ClientID string
ClientSecret string
RedirectURL string // e.g., "http://localhost:33669/auth/oauth/google/callback"
IssuerURL string // e.g., "https://accounts.google.com"
Scopes []string // e.g., []string{"openid", "profile", "email"}
}
OAuthConfig defines an external identity provider (Google, Microsoft, etc.)
type OAuthProvider ¶
type OAuthProvider interface {
Name() string
CallbackMethod() string
AuthorizationURL(ctx context.Context, state, nonce, verifier, redirectURL string) (string, error)
Complete(ctx context.Context, code, nonce, verifier, redirectURL string) (ProviderIdentity, error)
}
OAuthProvider is a verified provider adapter. Complete must exchange the code and validate provider-specific signatures/claims/email before returning.
func NewAppleProvider ¶
func NewAppleProvider(ctx context.Context, config AppleProviderConfig) (OAuthProvider, error)
NewAppleProvider creates Apple's OIDC adapter. The callback uses form_post; its browser-session cookie must therefore be configured by the host for that cross-site POST (PHP uses Secure, HttpOnly, SameSite=None).
func NewFacebookProvider ¶
func NewFacebookProvider(config FacebookProviderConfig) (OAuthProvider, error)
NewFacebookProvider creates a Facebook Login OIDC adapter. Meta currently documents this manually built OIDC/PKCE flow as testing; its signed email claim is not treated as verified unless the token explicitly says so.
func NewGitHubProvider ¶
func NewGitHubProvider(config GitHubProviderConfig) (OAuthProvider, error)
NewGitHubProvider creates the GitHub OAuth adapter with read:user and user:email scopes, state and PKCE validation handled by Service.
func NewGoogleProvider ¶
func NewGoogleProvider(ctx context.Context, config GoogleProviderConfig) (OAuthProvider, error)
NewGoogleProvider creates an OIDC adapter pinned to Google's issuer and validates issuer, audience, signature, time claims, nonce, and verified email.
type OAuthProviderDTO ¶
type OAuthProviderDTO struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
}
DTO dla frontendu
type OAuthStateStore ¶
type OAuthStateStore interface {
SaveOAuthState(ctx context.Context, stateDigest string, state PendingOAuthState) error
ConsumeOAuthState(ctx context.Context, stateDigest string, now time.Time) (PendingOAuthState, bool, error)
}
OAuthStateStore persists a digest-keyed, short-lived login attempt. Consume must atomically remove one unexpired record before returning it.
type OneTimeTokenRevoker ¶
OneTimeTokenRevoker is an optional capability for removing a token when its email notification failed. Host stores may implement it alongside the atomic consume contract.
type OneTimeTokenStore ¶
type OneTimeTokenStore interface {
InsertOneTimeToken(ctx context.Context, digest, subject string, expiresAt time.Time) error
ConsumeOneTimeToken(ctx context.Context, digest string, now time.Time, apply func(callbackCtx context.Context, subject string) error) error
}
OneTimeTokenStore is the host persistence seam. Bind each instance to a host-owned token domain (for example, reset or email verification) and persist only the digest. ConsumeOneTimeToken must, in one transaction/atomic operation, locate a token whose expiry is strictly after now, claim/delete it, call apply with its subject, and commit only if apply succeeds. The callback should make the host-side state change using the transaction represented by callbackCtx. Return ErrInvalidOneTimeToken when no eligible token exists.
This contract supports atomic reset completion and email-verification marking without deciding account policy or introducing an application database here.
type OneTimeTokens ¶
type OneTimeTokens struct {
Store OneTimeTokenStore
}
OneTimeTokens applies storage-neutral one-time-token mechanics over a host-selected store. A store instance should be scoped to one token domain.
func (OneTimeTokens) Consume ¶
func (tokens OneTimeTokens) Consume(ctx context.Context, value string, now time.Time, apply func(callbackCtx context.Context, subject string) error) error
Consume validates the 64-character lowercase-hex value and delegates its single-use consume plus apply callback to the store's atomic transaction.
type OpaqueToken ¶
OpaqueToken contains a one-time plaintext value and its lowercase SHA-256 digest. Persist Digest only; reveal Value only to the client that must use it.
func NewHexToken ¶
func NewHexToken() (OpaqueToken, error)
NewHexToken creates a 256-bit lowercase-hex token and its digest. The 64-character form can be used for password-reset links or other host-owned one-time tokens.
func NewOpaqueToken ¶
func NewOpaqueToken() (OpaqueToken, error)
NewOpaqueToken creates a 256-bit raw-URL-base64 token suitable for opaque authorization codes, bearer tokens, or other host-defined token domains.
func NewResetToken ¶
func NewResetToken() (OpaqueToken, error)
NewResetToken creates a 256-bit lowercase-hex token for password-recovery links.
type PendingOAuthLinkStore ¶
type PendingOAuthLinkStore interface {
SavePendingOAuthLink(ctx context.Context, identity ProviderIdentity, expiresAt time.Time) error
ConsumePendingOAuthLink(ctx context.Context, now time.Time, apply func(context.Context, ProviderIdentity) error) error
}
PendingOAuthLinkStore is normally bound to the browser session. A pending identity is linked only after the user authenticates to the matching local account and explicitly invokes the link route. Its consume callback must only remove the intent when apply succeeds.
type PendingOAuthState ¶
type PendingOAuthState struct {
Provider string
Nonce string
Verifier string
RedirectURL string
LinkSubject string
Registration RegistrationAttempt
DesktopState string
StartedAt time.Time
ExpiresAt time.Time
}
PendingOAuthState stores PKCE/nonce secrets server-side; never send these values back to the browser except the derived authorization URL.
type PermissionModel ¶
type PermissionModel struct {
Role string `gorm:"primaryKey;type:varchar(64)"`
Permission string `gorm:"primaryKey;type:varchar(64)"`
}
func (PermissionModel) TableName ¶
func (PermissionModel) TableName() string
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
func New
deprecated
New constructs the legacy JWT/plugin API.
Deprecated: This API is restricted to explicitly named development/test environments. Production hosts should use NewService and the guarded HTTP or Flow APIs with host-owned persistence, session, and request-boundary adapters.
type ProviderCallbackResult ¶
type ProviderCallbackResult struct {
Account Account
Registration RegistrationAttempt
DesktopState string
DesktopCallbackURL string
}
ProviderCallbackResult contains server-side callback outcome data for the HTTP handler/host redirect adapter. It must never be serialized as a response.
type ProviderIdentity ¶
ProviderIdentity is trusted only after OAuthProvider.Complete has validated it. EmailVerified is true only when that provider explicitly attests to the email; it is independent of whether the provider subject itself was authenticated.
type RBACStore ¶
type RBACStore interface {
GetUserFeatures(ctx context.Context, userID string) ([]string, error)
GetUserTenants(ctx context.Context, userID string) ([]TenantAccess, error)
HasTenantAccess(ctx context.Context, userID, tenantID string) (bool, string, error)
}
RBACStore is the interface for providing RBAC data from the master DB. Implement this in your user service layer.
type RefreshTokenModel ¶
type RefreshTokenModel struct {
TokenID string `gorm:"primaryKey;type:varchar(36)"`
UserID string `gorm:"index;type:varchar(36)"`
ExpiresAt time.Time `gorm:"index"`
}
func (RefreshTokenModel) TableName ¶
func (RefreshTokenModel) TableName() string
type RegistrationAttempt ¶
type RegistrationAttempt struct {
Email string
Username string
InviteCode string
TermsAccepted bool
}
RegistrationAttempt carries user input and optional host-defined registration context. The core passes invite and terms fields through without applying policy.
type RequestBoundary ¶
type RequestBoundary interface {
AuthorizeAuthRequest(ctx context.Context, operation BoundaryOperation, request *http.Request, turnstileToken string) error
}
RequestBoundary is mandatory for public routes. The host supplies anti-abuse, registration-policy, CSRF, and rate-limit checks here. The core deliberately does not accept or trust forwarded IP headers itself.
type RoleModel ¶
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service implements storage-neutral auth use cases. It contains no application database, invitation lifecycle, organization roles, Turnstile, rate limits, or email templates.
func NewService ¶
func NewService(config ServiceConfig) (*Service, error)
func (*Service) AuthenticatePassword ¶
func (s *Service) AuthenticatePassword(ctx context.Context, identifier, password string) (Account, error)
AuthenticatePassword verifies local credentials, including legacy username lookup delegated to the host. It does not create a browser session or desktop token; callers choose the credential type explicitly.
func (*Service) BeginProviderLogin ¶
func (s *Service) BeginProviderLogin(ctx context.Context, providerName, redirectURL string, linkCurrentAccount bool, registration RegistrationAttempt, desktopState string) (string, error)
BeginProviderLogin generates state, nonce, and PKCE values, then stores all sensitive callback state server-side. linkCurrentAccount is only for an already-authenticated browser session; otherwise an email conflict becomes a pending link requiring password login and an explicit follow-up action. The registration attempt carries app-owned invite/terms input only. A desktop state binds the provider flow to an already-started native PKCE request.
func (*Service) CompleteProviderCallback ¶
func (s *Service) CompleteProviderCallback(ctx context.Context, providerName, state, code string) (ProviderCallbackResult, error)
CompleteProviderCallback returns enough server-side context for the host to route browser success/errors and for desktop logins to finish the PKCE handoff.
func (*Service) CompleteProviderLogin ¶
func (s *Service) CompleteProviderLogin(ctx context.Context, providerName, state, code string) (Account, error)
CompleteProviderLogin consumes state once, validates the provider callback, refuses automatic email-based linking, and delegates new-account eligibility and atomic creation/linking to the host adapter.
func (*Service) CurrentBrowserAccount ¶
CurrentBrowserAccount resolves the current host session and rejects expired or stale-version sessions; the host still owns cookie/CSRF handling.
func (*Service) EmailVerificationMode ¶
func (s *Service) EmailVerificationMode(ctx context.Context) (EmailVerificationMode, error)
EmailVerificationMode returns the host-selected mode for the current request. It deliberately has no package default; callers must keep host policy as the source of truth.
func (*Service) ExchangeDesktopAuthCode ¶
func (s *Service) ExchangeDesktopAuthCode(ctx context.Context, code, verifier string) (string, time.Time, error)
ExchangeDesktopAuthCode consumes the one-time PKCE code and creates a separate opaque bearer token. Only its digest is persisted; the host store must join the bearer insertion to the code-consumption transaction.
func (*Service) IssueDesktopAuthCode ¶
func (s *Service) IssueDesktopAuthCode(ctx context.Context, state string, account Account) (string, error)
IssueDesktopAuthCode consumes one pending loopback request and redirects only to its exactly validated, ephemeral 127.0.0.1 callback.
func (*Service) LinkPendingProviderIdentity ¶
LinkPendingProviderIdentity links a previously verified email-conflict identity only to the now-authenticated account with that exact email address.
func (*Service) RegisterPassword ¶
func (s *Service) RegisterPassword(ctx context.Context, attempt RegistrationAttempt, password, confirmation string) (Account, error)
RegisterPassword creates a password account only after the host's eligibility policy permits it. disabled preserves immediate signup; optional and required send a verification event, with required enforced at login.
func (*Service) RequestEmailVerification ¶
RequestEmailVerification sends a host-rendered email only when verification is enabled. Unknown addresses and already-verified accounts are intentionally quiet.
func (*Service) RequestPasswordReset ¶
RequestPasswordReset always has the same result for known and unknown email addresses. The host performs per-IP/per-email throttling at the HTTP boundary.
func (*Service) ResetPassword ¶
ResetPassword atomically consumes the one-time token with the host's password update/revocation transaction.
func (*Service) ResolveDesktopBearer ¶
func (*Service) StartBrowserSession ¶
StartBrowserSession delegates cookie policy, session-ID rotation, CSRF, absolute expiry enforcement, and identity binding to the host.
func (*Service) StartDesktopAuth ¶
type ServiceConfig ¶
type ServiceConfig struct {
Accounts AccountStore
Policy HostPolicy
BrowserSessions BrowserSessionHost
BrowserSessionLifetime BrowserSessionLifetime
Emails EmailSender
PasswordResetTokens OneTimeTokens
EmailVerifyTokens OneTimeTokens
OAuthStates OAuthStateStore
PendingOAuthLinks PendingOAuthLinkStore
OAuthProviders map[string]OAuthProvider
DesktopAuth DesktopAuthStore
DesktopBearers DesktopBearerStore
DesktopBearerLifetime time.Duration
Now func() time.Time
}
ServiceConfig composes generic authentication with host-owned adapters. No email-verification mode is supplied here; HostPolicy must explicitly return disabled, optional, or required for each signup/login decision.
type Store ¶
type Store interface {
// User CRUD
GetUserByEmail(ctx context.Context, email string) (*User, error)
GetUserByID(ctx context.Context, id string) (*User, error)
CreateUser(ctx context.Context, user *User) error
UpdateUser(ctx context.Context, user *User) error
DeleteUser(ctx context.Context, id string) error
// RBAC & Features
GetUserRoles(ctx context.Context, userID string) ([]string, error)
GetRolePermissions(ctx context.Context, role string) ([]string, error)
GetUserFeatures(ctx context.Context, userID string) ([]string, error)
// Multi-Tenancy
GetUserTenants(ctx context.Context, userID string) ([]TenantAccess, error)
GetTenantRole(ctx context.Context, userID, tenantID string) (string, error)
GetTenantFeatures(ctx context.Context, tenantID string) ([]string, error)
// Token Management (Refresh & Revocation)
CreateRefreshToken(ctx context.Context, userID, tokenID string, expiry time.Time) error
ValidateRefreshToken(ctx context.Context, tokenID string) (userID string, err error)
RevokeRefreshToken(ctx context.Context, tokenID string) error
RevokeAllUserTokens(ctx context.Context, userID string) error
PruneExpiredTokens(ctx context.Context) error
// Email Verification & Password Reset
CreateVerificationToken(ctx context.Context, userID, token string, expiry time.Time) error
GetVerificationToken(ctx context.Context, token string) (userID string, err error)
DeleteVerificationToken(ctx context.Context, token string) error
CreateResetToken(ctx context.Context, userID, token string, expiry time.Time) error
GetResetToken(ctx context.Context, token string) (userID string, err error)
DeleteResetToken(ctx context.Context, token string) error
// OAuth 2.0
GetOAuthAccount(ctx context.Context, provider, providerUserID string) (userID string, err error)
LinkOAuthAccount(ctx context.Context, userID, provider, providerUserID string) error
}
Store defines persistence operations. Can be implemented by GORM, raw SQL, or Memory.
func NewMemoryStore ¶
func NewMemoryStore() Store
type TenantAccess ¶
type TenantFeatureModel ¶
type TenantFeatureModel struct {
TenantID string `gorm:"primaryKey;type:varchar(36)"`
Feature string `gorm:"primaryKey;type:varchar(64)"`
}
func (TenantFeatureModel) TableName ¶
func (TenantFeatureModel) TableName() string
type TenantMemberModel ¶
type TenantMemberModel struct {
TenantID string `gorm:"primaryKey;type:varchar(36)"`
UserID string `gorm:"primaryKey;type:varchar(36)"`
Role string `gorm:"type:varchar(64)"`
}
func (TenantMemberModel) TableName ¶
func (TenantMemberModel) TableName() string
type Tokens ¶
func GenerateTokens ¶
type TurnstileRequestBoundary ¶ added in v0.2.0
type TurnstileRequestBoundary struct {
// contains filtered or unexported fields
}
TurnstileRequestBoundary composes Turnstile verification with host request authorization. It must be constructed with NewTurnstileRequestBoundary.
func NewTurnstileRequestBoundary ¶ added in v0.2.0
func NewTurnstileRequestBoundary(next RequestBoundary, verifier TurnstileVerifier, operations ...BoundaryOperation) (*TurnstileRequestBoundary, error)
NewTurnstileRequestBoundary wraps an existing host policy boundary and adds server-side verification for the selected operations. The wrapped boundary should enforce trusted identity, origin/CSRF, registration rules and rate limits, but should not separately verify the same Turnstile token.
func (*TurnstileRequestBoundary) AuthorizeAuthRequest ¶ added in v0.2.0
func (boundary *TurnstileRequestBoundary) AuthorizeAuthRequest(ctx context.Context, operation BoundaryOperation, request *http.Request, responseToken string) error
AuthorizeAuthRequest applies the host's checks first, then verifies a required Turnstile response before the auth service can consume credentials.
type TurnstileVerifier ¶ added in v0.2.0
type TurnstileVerifier interface {
Verify(ctx context.Context, responseToken, expectedAction string) error
}
TurnstileVerifier verifies a client response and binds it to the auth operation. Implementations must fail closed and must never log the secret or response token.
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Password []byte `json:"-"` // Never leak the hashed password
Verified bool `json:"verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
User represents the core identity in the system.
type UserModel ¶
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package nexssflow exposes auth session and host-authorized lifecycle actions to Flow runners.
|
Package nexssflow exposes auth session and host-authorized lifecycle actions to Flow runners. |
|
examples/localapp
command
|
|
|
Package roles provides zero-boilerplate role-based service composition.
|
Package roles provides zero-boilerplate role-based service composition. |
|
Package secret wraps sensitive strings to prevent accidental logging or serialization.
|
Package secret wraps sensitive strings to prevent accidental logging or serialization. |
|
dlock
Path: nexss/auth/security/dlock/memory_mutex.go
|
Path: nexss/auth/security/dlock/memory_mutex.go |