api

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// DefaultContentSecurityPolicy permits scripts only from this server.
	DefaultContentSecurityPolicy = "" /* 304-byte string literal not displayed */
)

Variables

This section is empty.

Functions

func APIAuthenticationMiddleware added in v1.4.0

func APIAuthenticationMiddleware(next http.Handler) http.Handler

APIAuthenticationMiddleware validates an optional bearer token.

func ConfigureAPIAuth added in v1.4.0

func ConfigureAPIAuth(store *auth.Store, adminToken string)

ConfigureAPIAuth installs the token store and optional bootstrap admin token.

func ConfigureItemFeatures added in v1.4.0

func ConfigureItemFeatures(config ItemFeatureConfig)

ConfigureItemFeatures replaces the item creation and expiry policies.

func ConfigurePreviewCache added in v1.4.0

func ConfigurePreviewCache(maxBytes int64)

ConfigurePreviewCache replaces the generated image cache.

func ConfigureWorkLimits added in v1.4.0

func ConfigureWorkLimits(config WorkLimitConfig) error

ConfigureWorkLimits updates all expensive-operation limits safely. Callers can update these limits while requests are active.

func LoggingMiddleware

func LoggingMiddleware(next http.Handler) http.Handler

LoggingMiddleware wraps an http.Handler to log the remote address, method, path, and duration of every request to stdout.

func NewJSONAccessLogMiddleware added in v1.4.0

func NewJSONAccessLogMiddleware(config AccessLogConfig, resolver *ClientIPResolver) func(http.Handler) http.Handler

NewJSONAccessLogMiddleware returns content-free structured access logging.

func NewRateLimitMiddleware added in v1.4.0

func NewRateLimitMiddleware(limiter *RateLimiter, resolver *ClientIPResolver, config RateLimitConfig) func(http.Handler) http.Handler

NewRateLimitMiddleware returns middleware for anonymous and authenticated limits. Authentication middleware must run first to provide a verified principal.

func NewRequestIDMiddleware added in v1.4.0

func NewRequestIDMiddleware(config RequestIDConfig) func(http.Handler) http.Handler

NewRequestIDMiddleware returns middleware that assigns validated request IDs.

func NewSecurityPolicyMiddleware added in v1.4.0

func NewSecurityPolicyMiddleware(config SecurityHeadersConfig, resolver *ClientIPResolver) func(http.Handler) http.Handler

NewSecurityPolicyMiddleware returns strict browser security middleware.

func PrincipalFromRequest added in v1.4.0

func PrincipalFromRequest(r *http.Request) (auth.Principal, bool)

PrincipalFromRequest returns an authenticated API principal.

func RegisterRoutes

func RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers all API endpoints on the provided mux.

func RequestIDFromContext added in v1.4.0

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID assigned by the middleware.

func SecurityHeadersMiddleware added in v1.4.0

func SecurityHeadersMiddleware(next http.Handler) http.Handler

SecurityHeadersMiddleware adds browser security headers to every response.

func WorkLimitStats added in v1.4.0

func WorkLimitStats() map[string]WorkLimitSnapshot

WorkLimitStats returns snapshots for operational diagnostics.

Types

type AccessLogConfig added in v1.4.0

type AccessLogConfig struct {
	Enabled bool
	Writer  io.Writer
	Clock   func() time.Time
}

AccessLogConfig controls structured JSON access logging.

type ClientIPConfig added in v1.4.0

type ClientIPConfig struct {
	TrustedProxyCIDRs     []string
	TrustForwardedHeaders bool
}

ClientIPConfig controls when the server trusts proxy forwarding headers.

type ClientIPResolver added in v1.4.0

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

ClientIPResolver extracts a client address according to an explicit trust policy.

func NewClientIPResolver added in v1.4.0

func NewClientIPResolver(config ClientIPConfig) (*ClientIPResolver, error)

NewClientIPResolver validates and creates a client IP resolver.

func (*ClientIPResolver) ClientIP added in v1.4.0

func (r *ClientIPResolver) ClientIP(request *http.Request) string

ClientIP returns the resolved client IP without a port.

type DiffRequest

type DiffRequest struct {
	Base    string `json:"base"`
	Compare string `json:"compare"`
}

DiffRequest represents the JSON payload for the POST /api/diff endpoint.

type DiffResponse

type DiffResponse struct {
	OpCodes      []OpCodeInfo `json:"opCodes"`
	BaseLines    []string     `json:"baseLines"`
	CompareLines []string     `json:"compareLines"`
}

DiffResponse is the structured JSON response for custom UI rendering.

type HTTPMiddleware added in v1.4.0

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

HTTPMiddleware owns the shared state for the complete middleware stack.

func NewHTTPMiddleware added in v1.4.0

func NewHTTPMiddleware(config HTTPMiddlewareConfig) (*HTTPMiddleware, error)

NewHTTPMiddleware validates and creates the complete middleware stack.

func (*HTTPMiddleware) Close added in v1.4.0

func (middleware *HTTPMiddleware) Close()

Close stops background middleware workers.

func (*HTTPMiddleware) Wrap added in v1.4.0

func (middleware *HTTPMiddleware) Wrap(next http.Handler) http.Handler

Wrap composes request IDs, JSON logs, security headers, and rate limits. An outer authentication middleware can provide a verified principal.

func (*HTTPMiddleware) WrapWithAuthentication added in v1.4.0

func (middleware *HTTPMiddleware) WrapWithAuthentication(next http.Handler, authentication func(http.Handler) http.Handler) http.Handler

WrapWithAuthentication runs authentication before rate classification.

type HTTPMiddlewareConfig added in v1.4.0

type HTTPMiddlewareConfig struct {
	ClientIP        ClientIPConfig
	RateLimit       RateLimitConfig
	RequestID       RequestIDConfig
	SecurityHeaders SecurityHeadersConfig
	AccessLog       AccessLogConfig
}

HTTPMiddlewareConfig configures the complete HTTP middleware stack.

func DefaultHTTPMiddlewareConfig added in v1.4.0

func DefaultHTTPMiddlewareConfig() HTTPMiddlewareConfig

DefaultHTTPMiddlewareConfig returns limits suitable for local development.

type ItemFeatureConfig added in v1.4.0

type ItemFeatureConfig struct {
	RequireTokenForCreate bool
	DefaultExpiry         time.Duration
	MaximumExpiry         time.Duration
}

ItemFeatureConfig controls item creation and expiry policies.

type OpCodeInfo

type OpCodeInfo struct {
	Tag string `json:"tag"` // "equal", "replace", "delete", "insert"
	I1  int    `json:"i1"`
	I2  int    `json:"i2"`
	J1  int    `json:"j1"`
	J2  int    `json:"j2"`
}

OpCodeInfo describes a block of changed/unchanged lines.

type RateLimitConfig added in v1.4.0

type RateLimitConfig struct {
	AnonymousPerIP              RateLimitPolicy
	AuthenticatedPerToken       RateLimitPolicy
	CreatePerIdentity           RateLimitPolicy
	CreatePaths                 []string
	ApplyIPLimitToAuthenticated bool
	AuthenticatedIdentity       func(*http.Request) (string, bool)
	MaxIPEntries                int
	MaxTokenEntries             int
	EntryTTL                    time.Duration
	CleanupInterval             time.Duration
}

RateLimitConfig controls IP and API-token rate limits.

type RateLimitPolicy added in v1.4.0

type RateLimitPolicy struct {
	Requests int
	Window   time.Duration
	Burst    int
}

RateLimitPolicy defines a token-bucket rate and burst capacity.

type RateLimiter added in v1.4.0

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

RateLimiter applies separate bounded token-bucket stores to IPs and tokens.

func NewRateLimiter added in v1.4.0

func NewRateLimiter(config RateLimitConfig) (*RateLimiter, error)

NewRateLimiter validates the configuration and starts periodic cleanup.

func (*RateLimiter) Allow added in v1.4.0

func (l *RateLimiter) Allow(ipAddress, tokenIdentity string) (bool, time.Duration)

Allow consumes general capacity for one anonymous IP or authenticated token.

func (*RateLimiter) Cleanup added in v1.4.0

func (l *RateLimiter) Cleanup()

Cleanup removes expired rate limit entries immediately.

func (*RateLimiter) Close added in v1.4.0

func (l *RateLimiter) Close()

Close stops the rate limiter cleanup worker.

func (*RateLimiter) EntryCount added in v1.4.0

func (l *RateLimiter) EntryCount() (int, int)

EntryCount reports the current IP and token entry counts.

type RequestIDConfig added in v1.4.0

type RequestIDConfig struct {
	Enabled        bool
	Header         string
	AcceptIncoming bool
	Generator      func() string
}

RequestIDConfig controls request ID generation and propagation.

type SecurityHeadersConfig added in v1.4.0

type SecurityHeadersConfig struct {
	Enabled               bool
	ContentSecurityPolicy string
	PermissionsPolicy     string
	ReferrerPolicy        string
	StrictTransportPolicy string
}

SecurityHeadersConfig controls browser security response headers.

type WorkLimitConfig added in v1.4.0

type WorkLimitConfig struct {
	DiffLimit    int
	FormatLimit  int
	PreviewLimit int
	WaitTimeout  time.Duration
}

WorkLimitConfig controls the number of concurrent expensive operations.

func DefaultWorkLimitConfig added in v1.4.0

func DefaultWorkLimitConfig() WorkLimitConfig

DefaultWorkLimitConfig returns limits suitable for local development.

type WorkLimitSnapshot added in v1.4.0

type WorkLimitSnapshot struct {
	Limit  int
	Active int
}

WorkLimitSnapshot reports the current work limit and active operation count.

Jump to

Keyboard shortcuts

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