auth

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 43 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

nexssp/auth

Nexss Flow 🌀 ready

github.com/nexssp/auth is a reusable Go authentication module for Nexss ecosystem and Go applications.

The module contains storage-neutral authentication use cases, provider adapters, guarded HTTP routes, a credential-free Kernel session action, and an opt-in Flow bundle. Applications supply account storage, registration policy, email delivery, browser-session and CSRF behavior, rate limiting, and deployment configuration.

Included

  • Password registration, login, password reset, and optional email verification. Bcrypt-compatible hashes include verification support for existing $2y$ and $2a$ hashes; the configured password policy is 12–72 bytes.
  • Digest-only, one-use reset and verification tokens, with atomic consume-and-apply contracts delegated to host stores.
  • Browser sessions through a host interface, kept separate from native desktop PKCE handoff codes and opaque bearer credentials.
  • Google, GitHub, Apple, and Facebook provider adapters. Facebook uses Meta's manually built OIDC/PKCE flow, which Meta labels as testing; see provider limitations.
  • Explicit account linking: matching email alone never links a provider identity.
  • A guarded net/http API, the auth.current_session Kernel action, Transport route bindings, and an explicitly registered nexssflow bundle.
  • The Flow bundle exports nexssflow/nflows/auth.nflow with eight route-bound pipelines. Use Transport's standard thttp.listen; the host supplies per-request auth dependencies, trusted identity, and the HTTP request/response exchange. OAuth and desktop endpoints remain available through auth.NewHTTPHandler on the host mux or as Transport raw handlers. See the Flow integration guide.

Host responsibilities

This module is not a complete login server or user database. The host must implement account persistence and transaction guarantees, registration and email-verification policy, email templates and canonical links, session and cookie issuance, CSRF/origin checks, trusted request identity, rate limits, optional Turnstile, OAuth provider configuration and registered callback URLs, and app authorization. See host integration.

The Flow bundle does not load a .env file or define standard environment-variable names for these host-owned settings. Load database, session, mail, OAuth, and optional Turnstile secrets in the host process before starting Flow. Keep the Turnstile secret server-side and perform response-token verification in the host boundary; see Flow environment and provider setup.

Never trust a callback URL from browser input. Use fixed provider callback URLs. For Apple form_post, the host's session cookie must work on a cross-site POST (SameSite=None; Secure). Ensure OAuth callback and provider token-exchange URLs are redacted from proxy and application logs.

Install

go get github.com/nexssp/auth@latest

Verify

From the module root, using Go's default workspace resolution:

go test -count=1 ./...
go test -race -count=1 ./...
go vet ./...
go mod tidy -diff
go mod verify

These checks validate local code and fixtures, not live identity-provider configuration or a consuming application's cookies, database transactions, middleware, or UI. Facebook remains unverified against a live Meta app.

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

View Source
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
)
View Source
const (
	EmailPasswordReset = "password_reset"
	EmailVerifyAddress = "email_verification"
)

Variables

View Source
var (
	ErrRequestDenied = errors.New("authentication request denied by host boundary")
	ErrRateLimited   = errors.New("authentication request rate limited by host boundary")
)
View Source
var (
	// ErrInvalidOneTimeToken covers an unknown, expired, or already-consumed token.
	ErrInvalidOneTimeToken = errors.New("invalid, expired, or consumed one-time token")
	// ErrOneTimeTokenStoreUnavailable indicates that no host store was supplied.
	ErrOneTimeTokenStoreUnavailable = errors.New("one-time token store is unavailable")
)
View Source
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")
)
View Source
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")
	ErrVerificationUnavailable  = errors.New("email verification is unavailable")
	ErrPasswordResetUnavailable = errors.New("password reset is unavailable")
	ErrOAuthUnavailable         = errors.New("OAuth provider is unavailable")
	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")
)
View Source
var (
	ErrInvalidOAuthResponse = errors.New("invalid or expired OAuth response")
	ErrOAuthEmailMismatch   = errors.New("provider-verified email does not match the existing account")
)

Functions

func BrowserSessionBinding

func BrowserSessionBinding(ctx context.Context) (string, bool)

BrowserSessionBinding returns the opaque-cookie digest attached by the host session middleware. Callers must never put the raw cookie value in context.

func CookieToken

func CookieToken(cookieName string) func(r *http.Request) string

func HashPassword

func HashPassword(password string) (string, error)

HashPassword creates a bcrypt hash. Length and account policy belong to the caller.

func InitKeys

func InitKeys(privPEM, pubPEM []byte) error

func InitOrLoadPersistentKeys

func InitOrLoadPersistentKeys(privPath, pubPath string) error

func InitTempKeys

func InitTempKeys() error

func JWTMiddleware

func JWTMiddleware(cfg JWTConfig) func(http.Handler) http.Handler

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

func NewPKCEVerifier() (string, error)

NewPKCEVerifier creates a 32-byte verifier using the unpadded URL-safe base64url alphabet for OAuth and desktop handoffs.

func NewStateToken

func NewStateToken() (string, error)

NewStateToken creates a 256-bit lowercase-hex OAuth or desktop state value.

func PKCEChallenge

func PKCEChallenge(verifier string) (string, error)

PKCEChallenge returns the S256 challenge for a verifier valid under the RFC 7636 43-128 character verifier syntax.

func QueryToken

func QueryToken(param string) func(r *http.Request) string

func TokenDigest

func TokenDigest(value string) string

TokenDigest returns the lowercase SHA-256 hex digest of the exact token bytes.

func ValidateProviderRedirectURL

func ValidateProviderRedirectURL(value string) error

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 VerifyPassword

func VerifyPassword(password, encodedHash string) error

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 VerifyToken

func VerifyToken(tokenString string) (*jwt.Token, error)

func WithBrowserSessionBinding

func WithBrowserSessionBinding(ctx context.Context, sessionIDDigest string) context.Context

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

type AuthEmail struct {
	Kind      string
	To        string
	Token     string
	ExpiresAt time.Time
}

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"
)

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

type BrowserSessionLifetime func(ctx context.Context, account Account) (time.Duration, error)

BrowserSessionLifetime lets the host preserve per-account session settings.

type Config

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 bypasses strict security checks for local offline-first apps.
	DesktopMode bool

	// PublicPaths bypasses JWT validation for specified prefixes.
	PublicPaths []string

	OAuthProviders []OAuthConfig

	MFAProviders map[string]MFAProvider

	ActionCodeTTL time.Duration
}

Config controls the authentication plugin.

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 DesktopAuthCode struct {
	Subject       string
	AuthVersion   uint64
	CodeChallenge string
	ExpiresAt     time.Time
}

type DesktopAuthRequest

type DesktopAuthRequest struct {
	CodeChallenge string
	RedirectURI   string
	ExpiresAt     time.Time
}

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

type DesktopBearer struct {
	Subject     string
	AuthVersion uint64
	ExpiresAt   time.Time
}

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) Challenge

func (p *EmailMFAProvider) Challenge(ctx context.Context, user *User) (string, error)

func (*EmailMFAProvider) ID

func (p *EmailMFAProvider) ID() string

func (*EmailMFAProvider) Name

func (p *EmailMFAProvider) Name() string

func (*EmailMFAProvider) Type

func (p *EmailMFAProvider) Type() string

func (*EmailMFAProvider) Verify

func (p *EmailMFAProvider) Verify(ctx context.Context, user *User, input string) error

type EmailSender

type EmailSender interface {
	SendAuthEmail(ctx context.Context, message AuthEmail) error
}

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 Emailer

type Emailer interface {
	Send(ctx context.Context, to, subject, body string) error
}

Emailer abstracts outbound transactional emails.

type FacebookProviderConfig

type FacebookProviderConfig struct {
	ClientID    string
	RedirectURL string
	HTTPClient  *http.Client
}

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 NewGORMStore

func NewGORMStore(db *gorm.DB) (*GORMStore, error)

func (*GORMStore) CreateRefreshToken

func (s *GORMStore) CreateRefreshToken(ctx context.Context, userID, tokenID string, expiry time.Time) error

func (*GORMStore) CreateResetToken

func (s *GORMStore) CreateResetToken(ctx context.Context, userID, token string, expiry time.Time) error

func (*GORMStore) CreateUser

func (s *GORMStore) CreateUser(ctx context.Context, u *User) error

func (*GORMStore) CreateVerificationToken

func (s *GORMStore) CreateVerificationToken(ctx context.Context, userID, token string, expiry time.Time) error

func (*GORMStore) DeleteResetToken

func (s *GORMStore) DeleteResetToken(ctx context.Context, token string) error

func (*GORMStore) DeleteUser

func (s *GORMStore) DeleteUser(ctx context.Context, id string) error

func (*GORMStore) DeleteVerificationToken

func (s *GORMStore) DeleteVerificationToken(ctx context.Context, token string) error

func (*GORMStore) GetOAuthAccount

func (s *GORMStore) GetOAuthAccount(ctx context.Context, provider, providerUserID string) (string, error)

func (*GORMStore) GetResetToken

func (s *GORMStore) GetResetToken(ctx context.Context, token string) (string, error)

func (*GORMStore) GetRolePermissions

func (s *GORMStore) GetRolePermissions(ctx context.Context, role string) ([]string, error)

func (*GORMStore) GetTenantFeatures

func (s *GORMStore) GetTenantFeatures(ctx context.Context, tenantID string) ([]string, error)

func (*GORMStore) GetTenantRole

func (s *GORMStore) GetTenantRole(ctx context.Context, userID, tenantID string) (string, error)

func (*GORMStore) GetUserByEmail

func (s *GORMStore) GetUserByEmail(ctx context.Context, email string) (*User, error)

func (*GORMStore) GetUserByID

func (s *GORMStore) GetUserByID(ctx context.Context, id string) (*User, error)

func (*GORMStore) GetUserFeatures

func (s *GORMStore) GetUserFeatures(ctx context.Context, userID string) ([]string, error)

func (*GORMStore) GetUserRoles

func (s *GORMStore) GetUserRoles(ctx context.Context, userID string) ([]string, error)

func (*GORMStore) GetUserTenants

func (s *GORMStore) GetUserTenants(ctx context.Context, userID string) ([]TenantAccess, error)

func (*GORMStore) GetVerificationToken

func (s *GORMStore) GetVerificationToken(ctx context.Context, token string) (string, error)

func (*GORMStore) LinkOAuthAccount

func (s *GORMStore) LinkOAuthAccount(ctx context.Context, userID, provider, providerUserID string) error

func (*GORMStore) PruneExpiredTokens

func (s *GORMStore) PruneExpiredTokens(ctx context.Context) error

func (*GORMStore) RevokeAllUserTokens

func (s *GORMStore) RevokeAllUserTokens(ctx context.Context, userID string) error

func (*GORMStore) RevokeRefreshToken

func (s *GORMStore) RevokeRefreshToken(ctx context.Context, tokenID string) error

func (*GORMStore) UpdateUser

func (s *GORMStore) UpdateUser(ctx context.Context, u *User) error

func (*GORMStore) ValidateRefreshToken

func (s *GORMStore) ValidateRefreshToken(ctx context.Context, tokenID string) (string, error)

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 (*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 JWTConfig

type JWTConfig struct {
	// Added context.Context to the signature!
	VerifyFn     func(ctx context.Context, token string) (jwt.MapClaims, error)
	TokenSource  func(r *http.Request) string
	ClaimsMapper func(scope *xctx.RequestScope, claims jwt.MapClaims)
	Optional     bool
	PublicPaths  []string
}

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.

func (NoopEmailer) Send

func (NoopEmailer) Send(ctx context.Context, to, subject, body string) error

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

type OneTimeTokenRevoker interface {
	RevokeOneTimeToken(ctx context.Context, digest string) error
}

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.

func (OneTimeTokens) Issue

func (tokens OneTimeTokens) Issue(ctx context.Context, subject string, expiresAt time.Time) (string, error)

Issue creates a random 64-character lowercase-hex token and stores only its digest. The host chooses the token domain, expiry, and any replacement policy.

type OpaqueToken

type OpaqueToken struct {
	Value  string
	Digest string
}

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

func New(cfg Config) (*Plugin, error)

func (*Plugin) Actions

func (p *Plugin) Actions() []action.AnyAction

func (*Plugin) Protect

func (p *Plugin) Protect() func(http.Handler) http.Handler

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

type ProviderIdentity struct {
	Provider      string
	Subject       string
	Email         string
	EmailVerified bool
}

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 RoleModel struct {
	UserID string `gorm:"primaryKey;type:varchar(36)"`
	Role   string `gorm:"primaryKey;type:varchar(64)"`
}

func (RoleModel) TableName

func (RoleModel) TableName() string

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

func (s *Service) CurrentBrowserAccount(ctx context.Context) (Account, bool, error)

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) EndBrowserSession

func (s *Service) EndBrowserSession(ctx context.Context) error

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

func (s *Service) LinkPendingProviderIdentity(ctx context.Context) error

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

func (s *Service) RequestEmailVerification(ctx context.Context, email string) error

RequestEmailVerification sends a host-rendered email only when verification is enabled. Unknown addresses and already-verified accounts are intentionally quiet.

func (*Service) RequestPasswordReset

func (s *Service) RequestPasswordReset(ctx context.Context, email string) error

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

func (s *Service) ResetPassword(ctx context.Context, token, password, confirmation string) error

ResetPassword atomically consumes the one-time token with the host's password update/revocation transaction.

func (*Service) ResolveDesktopBearer

func (s *Service) ResolveDesktopBearer(ctx context.Context, token string) (Account, bool, error)

func (*Service) StartBrowserSession

func (s *Service) StartBrowserSession(ctx context.Context, account Account) error

StartBrowserSession delegates cookie policy, session-ID rotation, CSRF, absolute expiry enforcement, and identity binding to the host.

func (*Service) StartDesktopAuth

func (s *Service) StartDesktopAuth(ctx context.Context, state, challenge, redirectURI string) error

func (*Service) VerifyEmail

func (s *Service) VerifyEmail(ctx context.Context, token string) error

VerifyEmail consumes a verification token and marks the host-owned account email verified in the same transaction as token consumption.

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 TenantAccess struct {
	TenantID string `json:"tenant_id"`
	Role     string `json:"role"` // admin, operator, viewer
}

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 Token

type Token struct {
	Access  string `json:"access_token"`
	Refresh string `json:"refresh_token"`
}

Token holds standard OAuth2/OIDC token pairs.

type Tokens

type Tokens struct {
	Access  string `json:"access_token"`
	Refresh string `json:"refresh_token"`
}

func GenerateTokens

func GenerateTokens(tenantID, userID, role string) (*Tokens, error)

func GenerateTokensWithClaims

func GenerateTokensWithClaims(claims jwt.MapClaims) (*Tokens, error)

GenerateTokensWithClaims preserves the historical 30-day refresh-token lifetime for callers that do not use the authentication plugin.

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

type UserModel struct {
	ID        string    `gorm:"primaryKey;type:varchar(36)"`
	Email     string    `gorm:"uniqueIndex;type:varchar(255);not null"`
	Password  []byte    `gorm:"not null"`
	Verified  bool      `gorm:"default:false;index"`
	CreatedAt time.Time `gorm:"autoCreateTime"`
	UpdatedAt time.Time `gorm:"autoUpdateTime"`
}

func (UserModel) TableName

func (UserModel) TableName() string

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.
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

Jump to

Keyboard shortcuts

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