auth

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 21 Imported by: 0 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.

Documentation

Index

Constants

View Source
const (
	SessionCookieName = "ky_session"
	CSRFCookieName    = "ky_csrf"
	HeaderCSRF        = "X-CSRF-Token"
)

Base cookie names. Secure host-only deployments add the __Host- prefix (see cookieName), so a sibling subdomain cannot plant them.

Variables

View Source
var (
	ErrPasswordTooShort = errors.New("password must be at least 12 characters")
	ErrInvalidUsername  = errors.New("username must be 3-64 alphanumeric characters, underscores, or hyphens")
	ErrInvalidEmail     = errors.New("invalid email address format")
)
View Source
var ErrPasswordChangeRequired = errors.New("password change required")

Functions

func ClientIP

func ClientIP(r *http.Request, trusted []netip.Prefix) string

ClientIP returns the address a request should be attributed to: the rate limiter's key and the IP bound into a session. Both must agree, or a caller could be throttled as one client and recorded as another.

trusted is the parsed KY_TRUSTED_PROXIES allowlist. It is empty by default, and then the peer address is the answer and every header is ignored: X-Forwarded-For is caller-supplied, so honouring it unconditionally lets anyone mint a fresh limiter bucket per request.

When the peer is a trusted proxy, X-Forwarded-For is walked from the right, skipping entries that are themselves trusted proxies, and the first untrusted entry wins. Everything to its left was appended by a hop we do not trust and may be forged. An entry that does not parse as an IP ends the walk and the peer is used, since the rest of the chain sits behind something that is not speaking the protocol.

X-Real-IP is ignored outright. It carries no chain, so it cannot be walked; a deployment that needs a client IP must forward X-Forwarded-For.

func RequestNetwork

func RequestNetwork(r *http.Request, trusted []netip.Prefix) (clientIP string, proxyTrusted bool, scheme string)

RequestNetwork reports the same client address used for sessions and limits. Only the configured transport peer may supply forwarding metadata. The last scheme entry belongs to the nearest trusted proxy; earlier entries are ignored.

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail checks email syntax if provided.

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword ensures password satisfies standard KySecurity length policy (>= 12 chars).

func ValidateUsername

func ValidateUsername(username string) error

ValidateUsername checks username syntax.

func VerifyPoWSolution

func VerifyPoWSolution(solutionBase64, signingSecret string) bool

VerifyPoWSolution decodes and validates the client's base64-encoded JSON solution. It is stateless; login uses PoWSpent.Verify, which also refuses a replayed solution.

Types

type PoWChallenge

type PoWChallenge struct {
	Algorithm string `json:"algorithm"`
	Salt      string `json:"salt"`
	Challenge string `json:"challenge"`
	MaxNumber int    `json:"maxnumber"`
	ExpiresAt int64  `json:"expires_at"`
	Signature string `json:"signature"`
}

PoWChallenge represents a client-side SHA256 puzzle matching the KySecurity standard.

func GeneratePoWChallenge

func GeneratePoWChallenge(difficulty int, signingSecret string) (*PoWChallenge, error)

GeneratePoWChallenge creates a puzzle whose answer is uniform in [1, difficulty]; the client searches linearly, so it costs difficulty/2 SHA-256 operations on average.

type PoWSolution

type PoWSolution struct {
	Algorithm string `json:"algorithm"`
	Salt      string `json:"salt"`
	Challenge string `json:"challenge"`
	Number    int    `json:"number"`
	MaxNumber int    `json:"maxnumber"`
	ExpiresAt int64  `json:"expires_at"`
	Signature string `json:"signature"`
}

PoWSolution represents the client's submitted answer.

type PoWSpent

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

PoWSpent remembers verified salts until their challenge expires, so each solution buys one attempt. In memory, like the login limiter: valid for the single-instance server only.

func (*PoWSpent) Verify

func (p *PoWSpent) Verify(solutionBase64, signingSecret string) bool

Verify accepts a valid solution once.

type SessionManager

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

func NewSessionManager

func NewSessionManager(st store.Store, cfg config.SecurityConfig) *SessionManager

func (*SessionManager) AuthenticateRequest

func (sm *SessionManager) AuthenticateRequest(r *http.Request) (*store.User, *store.Session, error)

AuthenticateRequest reads the session cookie and returns the user. Sessions are cookie-only so the CSRF check always applies; Bearer is reserved for drive service tokens.

func (*SessionManager) CSRFToken

func (sm *SessionManager) CSRFToken(rawSession string) string

CSRFToken is derived from the session token, so only the session's own page can know it.

func (*SessionManager) IssueSSOSession added in v0.5.0

func (sm *SessionManager) IssueSSOSession(ctx context.Context, w http.ResponseWriter, r *http.Request, user *store.User, sid string, issuedAt time.Time) (*store.Session, string, error)

IssueSSOSession issues a session for an SSO login the provider names by sid and dates it by the ID token's issuedAt, so a back-channel logout for that sid or subject ends it. It fails with store.ErrSSOSessionEnded when the provider already ended that login.

func (*SessionManager) IssueSession

func (sm *SessionManager) IssueSession(ctx context.Context, w http.ResponseWriter, r *http.Request, user *store.User) (*store.Session, string, error)

IssueSession creates an active session in the database and writes HttpOnly cookie + CSRF token. The password was just verified, so the session starts stepped up.

func (*SessionManager) RefreshCSRF

func (sm *SessionManager) RefreshCSRF(w http.ResponseWriter, r *http.Request, sess *store.Session)

RefreshCSRF rewrites the CSRF cookie for the presented session (lost or pre-upgrade cookie).

func (*SessionManager) RevokeSession

func (sm *SessionManager) RevokeSession(ctx context.Context, w http.ResponseWriter, r *http.Request) error

RevokeSession ends the active session, with the account's editor sessions, and clears the browser cookies.

func (*SessionManager) SessionToken

func (sm *SessionManager) SessionToken(r *http.Request) string

SessionToken is the raw session token the request presents, or "".

func (*SessionManager) ValidateCSRF

func (sm *SessionManager) ValidateCSRF(r *http.Request) bool

ValidateCSRF compares the header with the token recomputed from the session cookie. The CSRF cookie only carries the value to the SPA; a planted one proves nothing.

Jump to

Keyboard shortcuts

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