auth

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 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 provides storage-neutral authentication use cases, provider adapters, guarded HTTP routes, a credential-free Kernel session action, and an opt-in Flow bundle. It is not a complete login server or user database; production safety depends on the host's adapters and deployment configuration.

Included

  • Password registration, login, password reset, and optional email verification. Passwords use bcrypt-compatible hashes and a 12–72 byte policy.
  • Digest-only, one-use reset and verification tokens, with atomic consume-and-apply guarantees delegated to host stores.
  • Host-managed browser sessions, separate from native desktop PKCE handoff codes and opaque bearer credentials.
  • Google, GitHub, Apple, and Facebook provider adapters. Facebook uses a manually built OIDC/PKCE flow that Meta currently labels as testing; see provider limitations.
  • Explicit account linking: matching email alone never links a provider identity.
  • Guarded net/http routes, the auth.current_session Kernel action, Transport route bindings, and an explicitly registered nexssflow bundle.
  • Eight importable Flow routes in nexssflow/nflows/auth.nflow. Flow hosts supply per-request auth dependencies, trusted identity, and the HTTP request/response exchange; the raw HTTPHandler attaches its exchange automatically. See the Flow integration guide.

Host responsibilities

The host must supply 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-limit thresholds and trusted caller-key derivation (the package provides a reusable rate-limited RequestBoundary decorator); OAuth provider configuration and fixed callback URLs; and application authorization. The library does not grant tenant, workspace, project, or resource permissions. Hosts must authorize each such access from trusted server-side identity and policy. See host integration.

For public browser-facing auth, use the Turnstile-protected constructor and configure a server-side verifier. NewHTTPHandler and the Flow bundle's lower-level boundary constructors remain available when the host intentionally supplies an equivalent anti-abuse check itself; omitting both is not a secure public deployment.

Cloudflare Turnstile setup

Configure these values in the deployment's secret manager or host environment. The site key is public and belongs in the browser app; the secret key must remain server-side. This library does not load .env files or read environment variables automatically.

TURNSTILE_SITE_KEY=<public Cloudflare site key>
TURNSTILE_SECRET_KEY=<server-only Cloudflare secret key>
TURNSTILE_EXPECTED_HOSTNAME=auth.example.com

Build the verifier and secure HTTP handler after the host has loaded its secrets:

verifier, err := auth.NewCloudflareTurnstileVerifier(auth.CloudflareTurnstileConfig{
    SecretKey:        os.Getenv("TURNSTILE_SECRET_KEY"),
    ExpectedHostname: os.Getenv("TURNSTILE_EXPECTED_HOSTNAME"),
})
if err != nil {
    return err
}

handler, err := auth.NewSecureHTTPHandler(auth.HTTPConfig{
    Service:  service,
    Boundary: hostRequestBoundary,
}, verifier)
if err != nil {
    return err
}

The secure constructor requires action-bound responses for login, registration, password reset/forgot-password, email verification and resend, OAuth begin, and desktop authorization start. The browser must render the widget with the matching action (login, register, password_reset, email_verify, oauth_begin, or desktop_start) and send the response as turnstile_token; email resend uses the same email_verify action. OAuth callbacks, authenticated linking/logout, and PKCE code exchange are protected by their separate state/session controls. Siteverify outages fail closed with a retryable 503; rejected or missing responses are denied.

For Flow, wrap the host ActionBoundary with nexssflow.NewTurnstileActionBoundary and auth.DefaultTurnstileOperations(); see Flow Turnstile setup. Use Cloudflare's server-side Siteverify API and their test keys only in non-production tests. A successful test key is not evidence that production keys, hostnames, browser widgets, or application middleware are correctly configured.

Legacy API

The old auth.New(Config) plugin is deprecated and now refuses to initialize unless Config.Env is explicitly dev, development, or test. Production hosts must use NewService with host-owned adapters. The legacy middleware no longer reads JWTs from query strings; use the Authorization: Bearer header where bearer credentials are appropriate.

Install and verify

go get github.com/nexssp/auth@latest
go test -count=1 ./...
go test -race -count=1 ./...
go vet ./...
go mod tidy -diff
go mod verify

These checks validate code and fixtures, not a consuming application's database transactions, cookies, middleware, browser widget, or live identity-provider configuration. 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. The legacy Plugin, Store, GORMStore, and NewMemoryStore APIs do not implement the modern Service contracts or its transactional guarantees.

nexss/plugins/auth/memorystore.go

Legacy identity, tenancy, token, and provider models retained for compatibility.

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")
	// ErrOneTimeTokenRevokerRequired indicates that email-backed token delivery
	// needs a store capable of revoking credentials when notification fails.
	ErrOneTimeTokenRevokerRequired = errors.New("email-backed one-time token store must support revocation")
)
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")
)
View Source
var (
	ErrTurnstileConfiguration = errors.New("turnstile is not configured correctly")
	ErrTurnstileRequired      = errors.New("a Turnstile response is required")
	ErrTurnstileRejected      = errors.New("turnstile response was rejected")
	ErrTurnstileUnavailable   = errors.New("turnstile verification is unavailable")
)
View Source
var ErrRateLimiterUnavailable = errors.New("authentication rate limiter is unavailable")

ErrRateLimiterUnavailable indicates that caller-key derivation or the limiter backend failed; callers must treat the request as unavailable, not as allowed.

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

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

func InitOrLoadPersistentKeys(privPath, pubPath string) error

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

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

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

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

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

BrowserSessionLifetime lets the host preserve per-account session settings.

type CloudflareTurnstileConfig added in v0.2.0

type CloudflareTurnstileConfig struct {
	SecretKey        string
	ExpectedHostname string
}

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

GORMStore implements the legacy Store interface. It is not a Service adapter.

func NewGORMStore

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

NewGORMStore migrates the legacy Store schema and returns its adapter.

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 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 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 removes a token when its email notification fails. A store paired with an EmailSender in Service must 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 deprecated

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

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.

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 RateLimitConfig added in v0.3.0

type RateLimitConfig struct {
	Default    ratelimit.Limiter
	Operations map[BoundaryOperation]ratelimit.Limiter
	Key        RateLimitKeyFunc
}

RateLimitConfig composes a host request boundary with the package's shared limiter contract. Default applies to every auth operation; Operations may override individual operations to use different thresholds or backends. The adapter prefixes keys with the operation so buckets stay independent.

type RateLimitKeyFunc added in v0.3.0

type RateLimitKeyFunc func(ctx context.Context, operation BoundaryOperation, request *http.Request) (string, error)

RateLimitKeyFunc derives a stable per-caller key from trusted host state. Hosts must not trust raw forwarded-IP headers; configure trusted-proxy handling before deriving an address. Return a keyed digest instead of raw personal data when the limiter backend would otherwise retain identifiers.

type RateLimitedRequestBoundary added in v0.3.0

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

RateLimitedRequestBoundary applies a rate limit before delegating to the host boundary. Limiter errors fail closed and are reported as service unavailable.

func NewRateLimitedRequestBoundary added in v0.3.0

func NewRateLimitedRequestBoundary(next RequestBoundary, config RateLimitConfig) (*RateLimitedRequestBoundary, error)

NewRateLimitedRequestBoundary wraps next with a shared rate limit and optional operation-specific overrides. The caller retains ownership of all supplied limiters and the trusted caller-key derivation policy.

func (*RateLimitedRequestBoundary) AuthorizeAuthRequest added in v0.3.0

func (boundary *RateLimitedRequestBoundary) AuthorizeAuthRequest(ctx context.Context, operation BoundaryOperation, request *http.Request, turnstileToken string) error

AuthorizeAuthRequest rate-limits a caller before invoking the host's remaining anti-abuse, CSRF, origin, and registration-policy checks.

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 deprecated

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 the persistence surface for the legacy Plugin. It combines identity, token, provider, role, feature, and tenancy operations; it is not the storage contract used by Service and does not provide its atomicity guarantees.

Deprecated: Implement the storage interfaces needed by Service for new hosts.

func NewMemoryStore

func NewMemoryStore() Store

NewMemoryStore returns an in-memory implementation of the legacy Store API. It does not implement the storage interfaces required by Service.

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

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