Documentation
¶
Overview ¶
Package common provides shared authentication helper functions and types for the Lesser project. These helpers consolidate common authentication patterns found across all services.
Package common provides centralized business logic utilities for the Lesser project. This consolidates common business logic patterns found across all services to eliminate duplication and ensure consistency in business rule enforcement.
Package common provides ActivityPub-specific business logic utilities for the Lesser project. This consolidates ActivityPub federation business patterns found across services to eliminate duplication and ensure consistency in federation behavior.
Package common provides Mastodon API-specific business logic utilities for the Lesser project. This consolidates Mastodon API business patterns found across the API layer to eliminate duplication and ensure consistency with Mastodon API specifications.
Package common provides centralized constants to comply with goconst linting requirements. This consolidates frequently used string literals found throughout the codebase.
Package common provides secure cookie configuration and utilities for HTTP session management. revive:disable-next-line:var-naming - package name is a longstanding public import path
Package common provides shared utilities consumed across services. revive:disable:var-naming - package name is part of the public API surface
Package common provides shared error constants for the Lesser application. revive:disable-next-line var-naming // historical package name kept for backwards compatibility
Package common provides standardized error response functions for HTTP APIs. It consolidates error handling patterns to maintain consistency across the application.
Package common provides common utilities and helpers for the Lesser application. revive:disable-next-line:var-naming - package name is a longstanding public import path
Package common provides shared JSON utilities for ActivityPub operations.
Package common provides shared utilities for key operations.
Package common provides Lambda-specific helper utilities for standardized initialization ¶
Package common provides Lambda initialization helpers and patterns.
Package common provides shared logging utilities for the Lesser application. revive:disable:var-naming - package name retained for backwards-compatible imports.
Package common provides centralized pagination functionality for consistent pagination handling across all Lesser APIs and services.
Package common provides shared utilities for the Lesser application. revive:disable-next-line var-naming // legacy package name used across public APIs
Package common provides additional standardized response functions that extend the existing error_responses.go with more convenience functions and Mastodon-specific patterns
Package common provides runtime environment helpers for AWS Lambda functions.
Package common exposes helpers shared across tests. revive:disable:var-naming - package name retained for backwards-compatible imports.
Package common provides shared time formatting utilities for the Lesser application.
Index ¶
- Constants
- Variables
- func Accepted(body any) *events.APIGatewayV2HTTPResponse
- func ActivityPubHeaders() map[string]string
- func ActivityPubResponse(statusCode int, body any) *events.APIGatewayV2HTTPResponse
- func AddLinkHeader(headers map[string]string, baseURL string, endpoint string, cursor string, ...)
- func AddPaginationHeaders(headers map[string]string, baseURL string, endpoint string, cursor string, ...)
- func BadRequest(err error) *events.APIGatewayV2HTTPResponse
- func BuildLinkHeader(baseURL string, params PaginationParams, hasNext, hasPrev bool, ...) string
- func CalculateHasMore(itemCount, requestedLimit int) bool
- func CalculateOffset(page, limit int) int
- func CalculatePage(offset, limit int) int
- func CheckLambdaResources(operation string) error
- func ConfigureAllowedRedirectHosts(hosts []string)
- func Conflict(err error) *events.APIGatewayV2HTTPResponse
- func CreateAPIErrorMiddleware(logger *zap.Logger) apptheory.Middleware
- func CreateFederationErrorMiddleware(logger *zap.Logger) apptheory.Middleware
- func CreateGraphQLErrorMiddleware(logger *zap.Logger) apptheory.Middleware
- func CreateStandardErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
- func Created(body any) *events.APIGatewayV2HTTPResponse
- func DeleteSecureCookie(w http.ResponseWriter, name string)
- func DetectJSONBomb(data []byte) error
- func DevelopmentErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
- func ErrFeatureDisabled(feature string) error
- func ErrorFromType(err error) *events.APIGatewayV2HTTPResponse
- func ErrorHandlingMiddleware(config ErrorMiddlewareConfig) apptheory.Middleware
- func ErrorRecoveryMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
- func ErrorResponseWithCode(statusCode int, code string, err error) *events.APIGatewayV2HTTPResponse
- func EscapeHTML(s string) string
- func ExtractAuthHeader(ctx *apptheory.Context) string
- func ExtractBearerToken(authHeader string) (string, error)
- func ExtractHashtags(content string) []string
- func ExtractMentions(content string) []string
- func Forbidden(err error) *events.APIGatewayV2HTTPResponse
- func FormatMastodonTimestamp(t time.Time) string
- func FormatUntrustedHTTPBodySnippet(body []byte, truncated bool) string
- func GenerateActivityPubID(domain, objectType, localID string) string
- func GenerateActivityPubIDULID(domain, objectType string) string
- func GenerateActorID(domain, username string) string
- func GenerateID() string
- func GenerateJobIDULID() string
- func GenerateMediaIDULID() string
- func GenerateNoteIDULID() string
- func GenerateNumericID(username string) string
- func GenerateNumericIDFromActorID(actorID string) string
- func GenerateObjectID(domain, objectType, objectID string) string
- func GenerateOperationIDULID() string
- func GenerateRequestIDULID() string
- func GenerateSessionIDULID() string
- func GenerateSnowflakeID() string
- func GenerateStatusID() string
- func GetAPIHeaders() map[string]string
- func GetBaseURL(ctx *apptheory.Context) string
- func GetCORSHeaders() map[string]string
- func GetCookie(headers map[string]string, name string) string
- func GetEnvInt(key string, defaultValue int) int
- func GetLambdaFunctionName() string
- func GetLambdaFunctionVersion() string
- func GetLambdaInitializationType() string
- func GetLambdaLogGroupName() string
- func GetLambdaLogStreamName() string
- func GetLambdaMemorySize() string
- func GetLambdaMemorySizeInt() (int, error)
- func GetSafeRedirectURL(redirectURL, currentHost, defaultPath string) string
- func GetStandardActivityPubContext() []interface{}
- func GetXRayTraceID() string
- func HandleError(logger *zap.Logger, err error) (int, string)
- func HasAllScopes(claims Claims, scopes []string) bool
- func HasAnyScope(claims Claims, scopes []string) bool
- func HashOAuthClientSecret(secret string) (string, error)
- func Headers() map[string]string
- func IdentityTransformer[T any](_ context.Context, input T) (T, error)
- func InitGlobalIDGenerator(logger *zap.Logger)
- func InitSecurityLogger()
- func InsecureTLSOverrideEnabled() bool
- func InternalServerError(err error) *events.APIGatewayV2HTTPResponse
- func IsAuthentication(err error) bool
- func IsAuthorization(err error) bool
- func IsColdStart() bool
- func IsConflict(err error) bool
- func IsFederation(err error) bool
- func IsModerationMLEnabled(_ context.Context, tenantID string) bool
- func IsNotFound(err error) bool
- func IsProcessableMediaType(mediaType string) bool
- func IsPubliclyVisible(visibility string) bool
- func IsRunningInLambda() bool
- func IsValidation(err error) bool
- func IsXRayEnabled() bool
- func JSONResponse(statusCode int, body any) *events.APIGatewayV2HTTPResponse
- func JoinKey(parts ...string) string
- func LogAuthFailure(reason string, username string, ip string, userAgent string, requestID string)
- func LogCSRFFailure(reason string, username string, ip string, path string, userAgent string, ...)
- func LogRateLimit(userID string, ip string, endpoint string, limit int, requestID string)
- func LogSecurityEvent(event string, fields ...zap.Field)
- func LogSuspiciousActivity(activity string, userID string, ip string, details map[string]any, ...)
- func Logger() *zap.Logger
- func Marshal(v any) ([]byte, error)
- func MarshalString(v any) (string, error)
- func MaskSensitiveData(data string) string
- func MethodNotAllowed(err error) *events.APIGatewayV2HTTPResponse
- func MustCheckModerationMLAccess(ctx context.Context, tenantID string) error
- func NewDecoder(r io.Reader) *json.Decoder
- func NewEncoder(w io.Writer) *json.Encoder
- func NoContent() *events.APIGatewayV2HTTPResponse
- func NotFound(err error) *events.APIGatewayV2HTTPResponse
- func NotFoundMiddleware() apptheory.Middleware
- func OK(body any) *events.APIGatewayV2HTTPResponse
- func ParseAccountStatusesLimit(limitStr string) (int, error)
- func ParseActivityPubObject(body []byte, v any) error
- func ParseAdminLimit(limitStr string) (int, error)
- func ParseAndValidateAPILimit(limitStr string, maxLimit int) (int, error)
- func ParseAndValidateActivityPubLimit(limitStr string) (int, error)
- func ParseAndValidateBoolean(value string) (bool, error)
- func ParseAndValidateIntWithBounds(field, value string, minValue, maxValue, defaultValue int) (int, error)
- func ParseCookies(cookieHeader string) map[string]string
- func ParseFederationLimit(limitStr string) (int, error)
- func ParseFollowLimit(limitStr string) (int, error)
- func ParseFormURLEncoded(body string) (map[string]string, error)
- func ParseFormValues(body string) (url.Values, error)
- func ParseHTTPResponse(r io.Reader, v any) error
- func ParseHashtagLimit(limitStr string) (int, error)
- func ParseMastodonTimestamp(timestamp string) (time.Time, error)
- func ParseMultipartForm(body string, contentType string) (map[string]string, error)
- func ParseRequestBody(body []byte, v any) error
- func ParseRequestBodyWithValidation(ctx *apptheory.Context, target interface{}, fieldName string) (*apptheory.Response, error)
- func ParseRequestWithComplexFallback(ctx *apptheory.Context, target interface{}) error
- func ParseRequestWithCustomError(ctx *apptheory.Context, target interface{}, errorMessage string) (*apptheory.Response, error)
- func ParseRequestWithFallback(ctx *apptheory.Context, target interface{}) error
- func ParseRequestWithValidation(ctx *apptheory.Context, target interface{}) (*apptheory.Response, error)
- func ParseSearchLimit(limitStr string) (int, error)
- func ParseSearchOffset(offsetStr string) (int, error)
- func ParseStatusContextLimit(limitStr string) (int, error)
- func ParseStatusTimelineLimit(limitStr string) (int, error)
- func ParseTimelineLimit(limitStr string) (int, error)
- func ProductionErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
- func ReadRequestBody(body io.Reader, maxSize int64) ([]byte, error)
- func ReadRequestBodyString(body io.Reader, maxSize int64) (string, error)
- func ReadUntrustedHTTPResponseBody(r io.Reader, maxBytes int64) ([]byte, bool, error)
- func RecordBusinessMetric(_ context.Context, metricType, _ string, actorID string, ...) error
- func RespondAccountNotFound(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondActorNotFound(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondAlreadyExists(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondAuthErrorWithCode(ctx *apptheory.Context, errorCode int, err error) (*apptheory.Response, error)
- func RespondBadRequest(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondConflict(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondConversationNotFound(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondCreateError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
- func RespondDatabaseError(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondDeleteError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
- func RespondExpiredToken(_ *apptheory.Context) (*apptheory.Response, error)
- func RespondFailedToCreate(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondFailedToDelete(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondFailedToGet(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondFailedToUpdate(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondFilterNotFound(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondForbidden(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondGetError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
- func RespondGone(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondInsufficientScope(_ *apptheory.Context, requiredScope ...string) (*apptheory.Response, error)
- func RespondInternalServerError(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondInvalidContent(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondInvalidParameter(ctx *apptheory.Context, paramName string) (*apptheory.Response, error)
- func RespondInvalidRequest(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondInvalidToken(_ *apptheory.Context) (*apptheory.Response, error)
- func RespondLegacyError(_ *apptheory.Context, statusCode int, message string) (*apptheory.Response, error)
- func RespondMethodNotAllowed(_ *apptheory.Context) (*apptheory.Response, error)
- func RespondMissingAccountID(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondMissingAuth(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondMissingParameter(ctx *apptheory.Context, paramName string) (*apptheory.Response, error)
- func RespondMissingStatusID(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondNotAuthorized(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondNotAuthorizedToDelete(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondNotAuthorizedToModify(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
- func RespondNotFound(_ *apptheory.Context, resource ...string) (*apptheory.Response, error)
- func RespondRateLimited(_ *apptheory.Context) (*apptheory.Response, error)
- func RespondServiceUnavailable(_ *apptheory.Context, service ...string) (*apptheory.Response, error)
- func RespondStatusNotFound(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondStatusTooLong(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondSuccess(_ *apptheory.Context, data interface{}) (*apptheory.Response, error)
- func RespondUnauthorized(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondUnauthorizedWithDescription(_ *apptheory.Context, description string) (*apptheory.Response, error)
- func RespondUnprocessableEntity(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
- func RespondUpdateError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
- func RespondUserNotFound(ctx *apptheory.Context) (*apptheory.Response, error)
- func RespondValidationError(_ *apptheory.Context, err error) (*apptheory.Response, error)
- func RespondValidationOrError(ctx *apptheory.Context, err error) (*apptheory.Response, error)
- func RespondWithAppError(_ *apptheory.Context, appErr *errors.AppError) (*apptheory.Response, error)
- func RespondWithError(ctx *apptheory.Context, code int, message string) (*apptheory.Response, error)
- func RespondWithErrorAndDescription(_ *apptheory.Context, statusCode int, errorMsg, description string) (*apptheory.Response, error)
- func RespondWithErrorCode(_ *apptheory.Context, statusCode int, errorMsg, code string) (*apptheory.Response, error)
- func RespondWithErrorMessage(_ *apptheory.Context, statusCode int, message string) (*apptheory.Response, error)
- func RespondWithJSON(ctx *apptheory.Context, code int, data interface{}) (*apptheory.Response, error)
- func RunningUnitTests() bool
- func SafeRedirect(w http.ResponseWriter, r *http.Request, defaultPath string)
- func SafeRedirectOrDefault(w http.ResponseWriter, r *http.Request, redirectURL, defaultPath string)
- func SafeUnmarshalJSON(data []byte, v any) error
- func SafeUnmarshalJSONWithoutUnknownFields(data []byte, v any) error
- func SanitizeActivityPubObjectDefault(obj map[string]any)
- func SanitizeContent(content string) string
- func SanitizeHTML(content string) string
- func SanitizeInput(input string) string
- func SendAccepted(ctx *apptheory.Context, data interface{}) (*apptheory.Response, error)
- func SendBool(ctx *apptheory.Context, value bool) (*apptheory.Response, error)
- func SendCount(ctx *apptheory.Context, count int) (*apptheory.Response, error)
- func SendCreated(ctx *apptheory.Context, data interface{}) (*apptheory.Response, error)
- func SendEmpty(ctx *apptheory.Context) (*apptheory.Response, error)
- func SendEmptyObject(ctx *apptheory.Context) (*apptheory.Response, error)
- func SendError(_ *apptheory.Context, code int, message string) (*apptheory.Response, error)
- func SendHealthCheck(ctx *apptheory.Context, health HealthCheckResponse) (*apptheory.Response, error)
- func SendID(ctx *apptheory.Context, id string) (*apptheory.Response, error)
- func SendJSON(_ *apptheory.Context, code int, data interface{}) (*apptheory.Response, error)
- func SendMastodonAccount(ctx *apptheory.Context, account MastodonAccount) (*apptheory.Response, error)
- func SendMastodonAccounts(ctx *apptheory.Context, accounts []MastodonAccount) (*apptheory.Response, error)
- func SendMastodonError(_ *apptheory.Context, code int, errorMsg string) (*apptheory.Response, error)
- func SendMastodonStatus(ctx *apptheory.Context, status MastodonStatus) (*apptheory.Response, error)
- func SendMastodonStatuses(ctx *apptheory.Context, statuses []MastodonStatus) (*apptheory.Response, error)
- func SendNoContent(ctx *apptheory.Context) (*apptheory.Response, error)
- func SendOK(ctx *apptheory.Context, data interface{}) (*apptheory.Response, error)
- func SendPaginatedMastodonResponse(ctx *apptheory.Context, data interface{}, params PaginationParams, ...) (*apptheory.Response, error)
- func SendPaginatedResponse(ctx *apptheory.Context, data interface{}, pagination *Pagination) (*apptheory.Response, error)
- func SendRateLimitHeaders(resp *apptheory.Response, limit, remaining int, resetTime int64)
- func SendStreamingMessage(ctx *apptheory.Context, event string, data interface{}) (*apptheory.Response, error)
- func SetActivityPubHeaders(resp *apptheory.Response)
- func SetCORSHeaders(resp *apptheory.Response)
- func SetCacheHeaders(resp *apptheory.Response, maxAge int)
- func SetJSONHeaders(resp *apptheory.Response)
- func SetNoCache(resp *apptheory.Response)
- func SetPaginationHeaders(resp *apptheory.Response, baseURL string, params PaginationParams, ...)
- func SetSecureCookie(w http.ResponseWriter, name, value string, maxAge int)
- func SetSecureCookieWithConfig(w http.ResponseWriter, name, value string, maxAge int, config CookieConfig)
- func SetSecurityHeaders(resp *apptheory.Response)
- func Slugify(value string) string
- func SplitKey(key string) []string
- func Sync()
- func TimeoutErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
- func TitleCase(s string) string
- func TooManyRequests(err error) *events.APIGatewayV2HTTPResponse
- func Unauthorized(err error) *events.APIGatewayV2HTTPResponse
- func Unmarshal(data []byte, v any) error
- func UnprocessableEntity(err error) *events.APIGatewayV2HTTPResponse
- func ValidateAccountBio(bio string) error
- func ValidateAccountFields(fields interface{}) error
- func ValidateAccountID(accountID string) error
- func ValidateAccountIDsParameter(accountIDsStr string) ([]string, error)
- func ValidateAccountParamID(accountID string) error
- func ValidateAccountParams(params map[string]interface{}) error
- func ValidateAcctParameter(acct string) error
- func ValidateActivityPubActivity(activity map[string]interface{}) error
- func ValidateActivityPubActor(actor map[string]interface{}) error
- func ValidateActivityPubAddressing(addressing interface{}, fieldName string) error
- func ValidateActivityPubAttachments(attachments interface{}, fieldName string) error
- func ValidateActivityPubContentType(contentType string) error
- func ValidateActivityPubContext(obj map[string]interface{}) error
- func ValidateActivityPubJSON(jsonStr string, fieldName string) error
- func ValidateActivityPubNote(note map[string]interface{}) error
- func ValidateActivityPubPublicKey(publicKey map[string]interface{}) error
- func ValidateActivityPubSignature(signature string) error
- func ValidateActivityPubTags(tags interface{}, fieldName string) error
- func ValidateActivityPubTimestamp(timestamp, fieldName string) error
- func ValidateActivityPubURL(urlStr, fieldName string) error
- func ValidateActivityPubUsername(username string) error
- func ValidateActivityType(activityType string, rules ActivityPubValidationRules) error
- func ValidateActorEntity(actorID, username string) error
- func ValidateActorURI(actorURI string, rules ActivityPubValidationRules) error
- func ValidateAdminScopes(claims Claims) bool
- func ValidateAlphanumericID(field, value string) error
- func ValidateAndSanitizeMediaType(mediaType string) (string, error)
- func ValidateAndSanitizeString(field, value string, minLen, maxLen int) (string, error)
- func ValidateApplicationName(name string) error
- func ValidateApplicationParams(params map[string]interface{}) error
- func ValidateApplicationScopes(scopes string) error
- func ValidateBlockScopes(claims Claims) bool
- func ValidateBooleanString(value string) bool
- func ValidateBusinessContent(content string, rules ContentValidationRules) error
- func ValidateBusinessVisibility(visibility VisibilityLevel, _ string) error
- func ValidateContentOrAttachments(content string, attachmentIDs []string) error
- func ValidateDisplayName(displayName string) error
- func ValidateDomainName(domain string) error
- func ValidateEntityID(id string, entityType string) error
- func ValidateEntityIDsList(ids []string, entityType string) error
- func ValidateEnum(field, value string, allowedValues []string) error
- func ValidateEnumField(value string, allowedValues []string, fieldName string) error
- func ValidateFilterAction(action string) error
- func ValidateFilterContext(contexts []string) error
- func ValidateFilterContextParam(context interface{}) error
- func ValidateFilterExpiration(expiresIn interface{}) error
- func ValidateFilterKeyword(keyword string) error
- func ValidateFilterKeywords(keywords interface{}) error
- func ValidateFilterParamID(filterID string) error
- func ValidateFilterParams(params map[string]interface{}) error
- func ValidateFilterTitle(title string) error
- func ValidateFloatRange(field string, value, minValue, maxValue float64) error
- func ValidateFollowScopes(claims Claims) bool
- func ValidateHTTPScheme(scheme string) error
- func ValidateHashtag(hashtag string) error
- func ValidateIntRange(field string, value, minValue, maxValue int) error
- func ValidateJSONField(jsonData string, fieldName string) error
- func ValidateKeywordParamID(keywordID string) error
- func ValidateLanguageCode(language string) error
- func ValidateLimit(limit int, maxValue int) error
- func ValidateListParams(params map[string]interface{}) error
- func ValidateListRepliesPolicy(policy string) error
- func ValidateListTitle(title string) error
- func ValidateMastodonAccountID(accountID string) error
- func ValidateMastodonFilterKeyword(keyword string) error
- func ValidateMastodonID(id string) error
- func ValidateMastodonMimeType(mimeType string) error
- func ValidateMastodonOAuthScopes(scopes string) ([]string, error)
- func ValidateMastodonStatusID(statusID string) error
- func ValidateMastodonTimeline(params map[string]interface{}) error
- func ValidateMastodonUsername(username string) error
- func ValidateMediaDescription(description string) error
- func ValidateMediaEntity(mediaID, filename string, fileSize int64) error
- func ValidateMediaFile(fileData, fieldName string) error
- func ValidateMediaFocus(focus string) error
- func ValidateMediaIDs(mediaIDs interface{}) error
- func ValidateMediaParams(params map[string]interface{}) error
- func ValidateMediaType(mediaType string) error
- func ValidateMultipleRequiredParams(params map[string]string) error
- func ValidateNormalizedQuery(query string) (string, error)
- func ValidateNotificationType(notificationType string) error
- func ValidateNumericID(field, value string) error
- func ValidateOffset(offset int) error
- func ValidatePaginationLimit(limit int) int
- func ValidatePollParams(poll interface{}) error
- func ValidatePreferenceValue(key string, value interface{}) error
- func ValidateQueryFilters(filters map[string]interface{}) error
- func ValidateQueryLimit(limit int, maxLimit int, operationType string) error
- func ValidateQueryOffset(offset int, maxOffset int) error
- func ValidateReadAccess(authResult *AuthenticationResult) error
- func ValidateReadScopes(claims Claims) bool
- func ValidateRedirectURIs(uris string) error
- func ValidateRedirectURL(redirectURL string, currentHost string) (string, error)
- func ValidateReportCategory(category string) error
- func ValidateReportComment(comment string) error
- func ValidateReportParams(params map[string]interface{}) error
- func ValidateReportStatusIDs(statusIDs interface{}) error
- func ValidateRepositoryAccess(userID, resourceID string, operation string) error
- func ValidateRepositoryCursor(cursor string) error
- func ValidateRepositoryRelationship(fromEntity, toEntity string, relationType string) error
- func ValidateRepositorySearchQuery(query string, minLength int) error
- func ValidateRequiredParam(paramName, value string) error
- func ValidateResourceAccess(_ context.Context, actorID, resourceID, resourceType string, ...) error
- func ValidateResponseData(data interface{}) interface{}
- func ValidateScheduledTime(scheduledAt string) error
- func ValidateSearchQuery(query string) error
- func ValidateSliceLength(fieldName string, slice interface{}, maxLength int) error
- func ValidateSliceNotEmpty(fieldName string, slice interface{}) error
- func ValidateSortParameters(sortBy, sortOrder string, allowedFields []string) error
- func ValidateSpoilerText(spoilerText string) error
- func ValidateStateTransition(currentState, newState EntityState, entityType string) error
- func ValidateStatusContent(content string) error
- func ValidateStatusEntity(statusID, content string, visibility string) error
- func ValidateStatusID(statusID string) error
- func ValidateStatusParamID(statusID string) error
- func ValidateStatusParams(params map[string]interface{}) error
- func ValidateStatusState(status string) error
- func ValidateStringLength(field, value string, minLen, maxLen int) error
- func ValidateStruct(data interface{}, rules ValidationRules) error
- func ValidateTimestamp(timestamp string, fieldName string) error
- func ValidateURL(url string, fieldName string) error
- func ValidateUUID(field, value string) error
- func ValidateUserEntity(username, email string) error
- func ValidateUserRelationship(_ context.Context, actorID, targetID string, relationshipType string) error
- func ValidateUsername(username string) error
- func ValidateUsernameParamID(username string) error
- func ValidateVisibility(visibility string) error
- func ValidateWebfingerResource(resource string) error
- func ValidateWriteAccess(authResult *AuthenticationResult) error
- func ValidateWriteScopes(claims Claims) bool
- func ValidationErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
- func VerifyOAuthClientSecret(providedSecret, storedValue string) (bool, bool, error)
- func WithContext(ctx context.Context) *zap.Logger
- func WithFields(fields ...zap.Field) *zap.Logger
- func WithSecurityContext(logger *zap.Logger, ctx SecurityContext) *zap.Logger
- func WrapError(err error, context string) error
- func WrapObjectInActivity(activityType, actorID string, object interface{}, published time.Time) map[string]interface{}
- func WrapWithLambdaResourceCheck(operation string, fn func() error) error
- type AccessLevel
- type AccountSuspendedError
- type ActivityNotFoundError
- type ActivityPubActivity
- type ActivityPubActor
- type ActivityPubAudience
- type ActivityPubBusinessLogic
- type ActivityPubCollection
- type ActivityPubCollectionPage
- type ActivityPubError
- type ActivityPubObject
- type ActivityPubOperation
- type ActivityPubSanitizer
- type ActivityPubValidationRules
- type ActorNotFoundError
- type AdminPaginationParams
- type AlreadyFollowingError
- type AppError
- type AuthContext
- type AuthenticationError
- type AuthenticationResult
- func ExtractAndValidateAuth(ctx *apptheory.Context, requiredScope string, ...) *AuthenticationResult
- func ExtractAndValidateAuthWithMultipleScopes(ctx *apptheory.Context, allowedScopes []string, ...) *AuthenticationResult
- func ExtractOptionalAuth(ctx *apptheory.Context, oauthService OAuthServiceInterface) *AuthenticationResult
- type AuthorizationError
- type BaseTransformer
- type BatchTransformer
- type BatchTransformerImpl
- type BusinessLogicContext
- type BusinessLogicService
- type BusinessOperation
- type BusinessRuleValidator
- type CacheEntry
- type Claims
- type CommandValidationResult
- type ConditionalTransformer
- type ConditionalTransformerImpl
- type ConflictError
- type ContentValidationRules
- type ContextKey
- type CookieConfig
- type DeliveryTarget
- type EntityState
- type ErrorMiddlewareConfig
- type ErrorResponse
- type EventEmitter
- type ExpiredTokenError
- type FederationConfig
- type FederationDeliveryConfig
- type FederationError
- type FilterAction
- type FilterContext
- type FilterParams
- type HTTPSignatureInfo
- type HealthCheckResponse
- type IDGenerator
- func (g *IDGenerator) ExtractTimestamp(id string) (time.Time, error)
- func (g *IDGenerator) GenerateActivityID(domain string) string
- func (g *IDGenerator) GenerateActivityPubID(domain, objectType string) string
- func (g *IDGenerator) GenerateActorID(domain, username string) string
- func (g *IDGenerator) GenerateAuditLogID() string
- func (g *IDGenerator) GenerateCommunityNoteID() string
- func (g *IDGenerator) GenerateConversationID() string
- func (g *IDGenerator) GenerateExportID() string
- func (g *IDGenerator) GenerateImportID() string
- func (g *IDGenerator) GenerateJobID() string
- func (g *IDGenerator) GenerateMediaID() string
- func (g *IDGenerator) GenerateMessageID() string
- func (g *IDGenerator) GenerateNoteID() string
- func (g *IDGenerator) GenerateObjectID(domain string) string
- func (g *IDGenerator) GenerateOperationID() string
- func (g *IDGenerator) GenerateReportID() string
- func (g *IDGenerator) GenerateRequestID() string
- func (g *IDGenerator) GenerateSessionID() string
- func (g *IDGenerator) GenerateStatusID() string
- func (g *IDGenerator) GenerateStreamingSessionID() string
- func (g *IDGenerator) GenerateULID() string
- func (g *IDGenerator) GenerateVouchID() string
- func (g *IDGenerator) IsOlderThan(id string, duration time.Duration) bool
- func (g *IDGenerator) ShortID() string
- func (g *IDGenerator) ValidateULID(id string) bool
- type InvalidPasswordError
- type InvalidTokenError
- type LambdaConfig
- type LambdaContext
- func (lambdaCtx *LambdaContext) CreateLambdaHandler(handler func(ctx context.Context, event interface{}) (interface{}, error)) func(ctx context.Context, event interface{}) (interface{}, error)
- func (lambdaCtx *LambdaContext) CreateStandardizedLambdaHandler(handler func(ctx context.Context, event interface{}) (interface{}, error)) func(ctx context.Context, event interface{}) (interface{}, error)
- func (lambdaCtx *LambdaContext) FlushObservability()
- func (lambdaCtx *LambdaContext) FlushObservabilityServices()
- func (lambdaCtx *LambdaContext) InitializeObservabilityServices(options LambdaInitOptions) error
- func (lambdaCtx *LambdaContext) InitializeServiceSpecificDependencies(options LambdaInitOptions) error
- func (lambdaCtx *LambdaContext) InitializeStorageServices(options LambdaInitOptions) error
- func (lambdaCtx *LambdaContext) InitializeWithDefaults() error
- func (lambdaCtx *LambdaContext) InitializeWithOptions(options LambdaInitOptions) error
- type LambdaInitOptions
- type LambdaResourceMonitor
- func (m *LambdaResourceMonitor) CheckResources(operation string) error
- func (m *LambdaResourceMonitor) GetCheckpoints() []ResourceCheckpoint
- func (m *LambdaResourceMonitor) GetElapsedTime() time.Duration
- func (m *LambdaResourceMonitor) GetMemoryUsageMB() uint64
- func (m *LambdaResourceMonitor) GetResourceUtilization() (memoryPercent float64, timePercent float64)
- func (m *LambdaResourceMonitor) WrapWithResourceCheck(operation string, fn func() error) error
- type LambdaRuntimeInfo
- func (l *LambdaRuntimeInfo) GetFunctionName() string
- func (l *LambdaRuntimeInfo) GetFunctionVersion() string
- func (l *LambdaRuntimeInfo) GetInitializationType() string
- func (l *LambdaRuntimeInfo) GetLogGroupName() string
- func (l *LambdaRuntimeInfo) GetLogStreamName() string
- func (l *LambdaRuntimeInfo) GetMemorySize() string
- func (l *LambdaRuntimeInfo) GetMemorySizeInt() (int, error)
- func (l *LambdaRuntimeInfo) GetXRayTraceID() string
- func (l *LambdaRuntimeInfo) IsColdStart() bool
- func (l *LambdaRuntimeInfo) IsRunningInLambda() bool
- func (l *LambdaRuntimeInfo) IsXRayEnabled() bool
- type LambdaType
- type ListNotFoundError
- type MastodonAPIConfig
- type MastodonAPIError
- type MastodonAccount
- type MastodonBusinessLogic
- func (m *MastodonBusinessLogic) ExecuteMastodonAPIOperation(ctx context.Context, operation MastodonOperation) (interface{}, error)
- func (m *MastodonBusinessLogic) ValidateBio(bio string) error
- func (m *MastodonBusinessLogic) ValidateDisplayName(displayName string) error
- func (m *MastodonBusinessLogic) ValidateMastodonPaginationParams(params MastodonPaginationParams) MastodonPaginationParams
- func (m *MastodonBusinessLogic) ValidateMediaUpload(data []byte, mimeType string, mediaType MediaType) error
- func (m *MastodonBusinessLogic) ValidatePollOptions(options []PollOption, expiresIn int) error
- func (m *MastodonBusinessLogic) ValidateRateLimit(_ context.Context, _, _ string, _ RateLimitConfig) error
- func (m *MastodonBusinessLogic) ValidateStatusContent(content string, mediaCount int, pollOptions int) error
- type MastodonOperation
- type MastodonPaginationParams
- type MastodonStatus
- type MediaType
- type NotificationType
- type OAuthServiceInterface
- type PaginatedResponse
- type Pagination
- type PaginationLinks
- type PaginationParams
- type PaginationResult
- type PollOption
- type QuotaValidator
- type RateLimitConfig
- type RequestPaginationParams
- type ResourceCheckpoint
- type SafeJSONDecoder
- type SearchPaginationParams
- type SecurityContext
- type SessionNotFoundError
- type Snowflake
- type StandardErrorResponse
- type StatusValidationRules
- type StreamingEvent
- func EmitBusinessEvent(_ context.Context, eventType, objectType, objectID, actorID string, ...) *StreamingEvent
- func EmitEntityCreatedEvents(ctx context.Context, entityType, entityID, actorID string, entity interface{}) []*StreamingEvent
- func EmitEntityDeletedEvents(ctx context.Context, entityType, entityID, actorID string) []*StreamingEvent
- func EmitEntityUpdatedEvents(ctx context.Context, entityType, entityID, actorID string, entity interface{}, ...) []*StreamingEvent
- type StreamingMessage
- type TimelinePaginationParams
- type TimelineParams
- type TransformationCache
- func (tc *TransformationCache[TSource, TTarget]) Clear()
- func (tc *TransformationCache[TSource, TTarget]) Get(source TSource) (TTarget, bool)
- func (tc *TransformationCache[TSource, TTarget]) Set(source TSource, target TTarget)
- func (tc *TransformationCache[TSource, TTarget]) Stats() (hits, misses int64, hitRate float64)
- type TransformationContext
- type TransformationError
- type TransformationMetrics
- type TransformationPipeline
- type TransformationRegistry
- type TransformationStep
- type Transformer
- func MemoizedTransformer[TSource, TTarget any](transformer Transformer[TSource, TTarget], keyFunc func(TSource) string, ...) Transformer[TSource, TTarget]
- func ValidatingTransformer[TSource, TTarget any](transformer Transformer[TSource, TTarget], validator func(TSource) error) Transformer[TSource, TTarget]
- type UsedTokenError
- type UserNotFoundError
- type ValidationError
- type ValidationRules
- type VisibilityLevel
- type WebSocketMessage
Constants ¶
const ( ScopeRead = "read" ScopeWrite = "write" WriteFollows = "write:follows" ReadFollows = "read:follows" AdminRead = "admin:read" AdminWrite = "admin:write" )
Common scope constants to avoid import cycles
const ( ScopeFollow = "write:follows" ScopeReadAccounts = "read:accounts" ScopeWriteMedia = "write:media" ScopeReadStatuses = "read:statuses" ScopeWriteStatuses = "write:statuses" ScopePush = "push" )
Additional OAuth scopes beyond the existing ones
const ( // Entity status states StatusActive = "active" StatusInactive = "inactive" StatusPending = "pending" StatusProcessing = "processing" StatusCompleted = "completed" StatusFailed = "failed" StatusCancelled = "cancelled" StatusExpired = "expired" StatusSuspended = "suspended" StatusDeleted = "deleted" // Account/Actor states AccountStatusActive = "active" AccountStatusSuspended = "suspended" AccountStatusPending = "pending" AccountStatusDeleted = "deleted" )
Status constants - used across multiple services for consistent status tracking
const ( // CRUD operations OperationCreate = "create" OperationRead = "read" OperationUpdate = "update" OperationDelete = "delete" // ActivityPub activities ActivityCreate = "Create" ActivityUpdate = "Update" ActivityDelete = "Delete" ActivityFollow = "Follow" ActivityAccept = "Accept" ActivityReject = "Reject" ActivityAnnounce = "Announce" ActivityLike = "Like" ActivityUndo = "Undo" ActivityBlock = "Block" ActivityFlag = "Flag" ActivityMove = "Move" ActivityAdd = "Add" ActivityRemove = "Remove" )
Operation type constants - used in ActivityPub and audit logging
const ( ContentTypeActivityPub = "application/activity+json" ContentTypePlain = "text/plain" ContentTypeForm = "application/x-www-form-urlencoded" ContentTypeMultipart = "multipart/form-data" )
Content type constants - additional to http_constants.go
const ( // Specific image MIME types MediaTypeJPEG = "image/jpeg" MediaTypePNG = "image/png" MediaTypeWebP = "image/webp" MediaTypeGIFImage = "image/gif" // Specific video MIME types MediaTypeMP4 = "video/mp4" MediaTypeWebM = "video/webm" MediaTypeMOV = "video/quicktime" // Specific audio MIME types MediaTypeMP3 = "audio/mpeg" MediaTypeOGG = "audio/ogg" MediaTypeWAV = "audio/wav" MediaTypeFLAC = "audio/flac" )
Specific MIME type constants (complementary to business_mastodon.go MediaType)
const ( // Actor types ActorTypePerson = "Person" ActorTypeService = "Service" ActorTypeGroup = "Group" // Object types ObjectTypeNote = "Note" ObjectTypeArticle = "Article" ObjectTypeImage = "Image" ObjectTypeVideo = "Video" ObjectTypeAudio = "Audio" ObjectTypeDocument = "Document" ObjectTypePage = "Page" ObjectTypeEvent = "Event" ObjectTypePlace = "Place" ObjectTypeProfile = "Profile" ObjectTypeTombstone = "Tombstone" // Collection types CollectionTypeOrderedCollection = "OrderedCollection" CollectionTypeOrderedCollectionPage = "OrderedCollectionPage" CollectionTypeCollection = "Collection" CollectionTypeCollectionPage = "CollectionPage" )
Federation constants
const ( TimelineHome = "home" TimelinePublic = "public" TimelineLocal = "local" TimelineFederated = "federated" TimelineUser = "user" TimelineHashtag = "hashtag" TimelineList = "list" // Stream event types StreamEventUpdate = "update" StreamEventDelete = "delete" StreamEventNotification = "notification" StreamEventFilters = "filters_changed" StreamEventConversation = "conversation" StreamEventAnnouncement = "announcement" StreamEventStatusUpdate = "status.update" )
Timeline and stream constants
const ( NotificationTypeMention = "mention" NotificationTypeReblog = "reblog" NotificationTypeFavourite = "favourite" NotificationTypeFollow = "follow" NotificationTypeFollowRequest = "follow_request" NotificationTypePoll = "poll" NotificationTypeStatus = "status" NotificationTypeUpdate = "update" NotificationTypeAdminSignUp = "admin.sign_up" NotificationTypeAdminReport = "admin.report" )
Notification types
const ( // Job types JobTypeImport = "import" JobTypeExport = "export" JobTypeMedia = "media" JobTypeFederation = "federation" JobTypeModeration = "moderation" JobTypeNotification = "notification" JobTypeSearch = "search" JobTypeAnalytics = "analytics" // Job priorities JobPriorityLow = "low" JobPriorityNormal = "normal" JobPriorityHigh = "high" JobPriorityCritical = "critical" // Queue names QueueDefault = "default" QueueImport = "import" QueueExport = "export" QueueMedia = "media" QueueFederation = "federation" QueueModeration = "moderation" QueueNotification = "notification" QueueSearch = "search" QueueAnalytics = "analytics" QueueDLQ = "dlq" // Dead letter queue )
Job processing constants
const ( RelationshipFollowing = "following" RelationshipFollowed = "followed_by" RelationshipBlocked = "blocked" RelationshipBlocking = "blocking" RelationshipMuted = "muted" RelationshipMuting = "muting" RelationshipRequested = "requested" RelationshipDomainBlocked = "domain_blocked" RelationshipEndorsed = "endorsed" )
Relationship constants
const ( ReportCategorySpam = "spam" ReportCategoryViolation = "violation" ReportCategoryOther = "other" ReportCategoryLegal = "legal" ReportStatusOpen = "open" ReportStatusResolved = "resolved" ReportStatusRejected = "rejected" )
Report constants
const ( ModerationActionNone = "none" ModerationActionWarn = "warn" ModerationActionSilence = "silence" ModerationActionSuspend = "suspend" ModerationActionSensitive = "mark_as_sensitive" ModerationActionDelete = "delete" ModerationSeverityInfo = "info" ModerationSeverityWarning = "warning" ModerationSeverityError = "error" ModerationSeverityCritical = "critical" )
Moderation constants
const ( SearchTypeAccount = "accounts" SearchTypeStatus = "statuses" SearchTypeHashtag = "hashtags" SearchTypeAll = "all" SearchScopeLocal = "local" SearchScopeRemote = "remote" SearchScopeAll = "all" )
Search constants
const ( ProcessingStatusQueued = "queued" ProcessingStatusProcessing = "processing" ProcessingStatusCompleted = "completed" ProcessingStatusFailed = "failed" // File categories FileCategoryAvatar = "avatar" FileCategoryHeader = "header" FileCategoryAttachment = "attachment" FileCategoryEmoji = "emoji" FileCategoryPreview = "preview" )
File processing constants
const ( CacheKeyUser = "user:" CacheKeyActor = "actor:" CacheKeyStatus = "status:" CacheKeyAccount = "account:" CacheKeyTimeline = "timeline:" CacheKeyNotification = "notification:" CacheKeySearch = "search:" CacheKeyMedia = "media:" CacheKeyFederation = "federation:" // Cache durations (used as string constants for configuration) CacheDurationShort = "5m" CacheDurationMedium = "30m" CacheDurationLong = "2h" CacheDurationExtended = "24h" )
Cache constants
const ( DBOperationCreate = "create" DBOperationRead = "read" DBOperationUpdate = "update" DBOperationDelete = "delete" DBOperationScan = "scan" DBOperationQuery = "query" DBOperationBatch = "batch" // DynamoDB specific operations DynamoOperationPutItem = "PutItem" DynamoOperationGetItem = "GetItem" DynamoOperationUpdateItem = "UpdateItem" DynamoOperationDeleteItem = "DeleteItem" DynamoOperationQuery = "Query" DynamoOperationScan = "Scan" DynamoOperationBatchGetItem = "BatchGetItem" DynamoOperationBatchWriteItem = "BatchWriteItem" DynamoOperationTransactWriteItems = "TransactWriteItems" DynamoOperationTransactGetItems = "TransactGetItems" )
Database operation constants
const ( LogLevelDebug = "debug" LogLevelInfo = "info" LogLevelWarn = "warn" LogLevelError = "error" LogLevelFatal = "fatal" LogFieldComponent = "component" LogFieldOperation = "operation" LogFieldUserID = "user_id" LogFieldStatusID = "status_id" LogFieldDomain = "domain" LogFieldError = "error" LogFieldDuration = "duration" LogFieldSize = "size" )
Logging constants
const ( HeaderAuthorization = "Authorization" HeaderContentType = "Content-Type" HeaderAccept = "Accept" HeaderUserAgent = "User-Agent" HeaderSignature = "Signature" HeaderDigest = "Digest" HeaderDate = "Date" HeaderHost = "Host" HeaderActivityPub = "activity+json" // CORS headers HeaderCORSOrigin = "Access-Control-Allow-Origin" HeaderCORSMethods = "Access-Control-Allow-Methods" HeaderCORSHeaders = "Access-Control-Allow-Headers" HeaderCORSCredentials = "Access-Control-Allow-Credentials" HeaderCORSMaxAge = "Access-Control-Max-Age" // Security headers HeaderXFrameOptions = "X-Frame-Options" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderReferrerPolicy = "Referrer-Policy" )
HTTP header constants
const ( EnvProduction = "production" EnvStaging = "staging" EnvDevelopment = "development" EnvTesting = "testing" EnvLocal = "local" )
Environment constants
const ( ConfigKeyDBHost = "db.host" ConfigKeyDBPort = "db.port" ConfigKeyDBName = "db.name" ConfigKeyDBUser = "db.user" ConfigKeyDBPassword = "db.password" ConfigKeyRedisHost = "redis.host" ConfigKeyRedisPort = "redis.port" ConfigKeyRedisPassword = "redis.password" ConfigKeyS3Bucket = "s3.bucket" ConfigKeyS3Region = "s3.region" ConfigKeyS3AccessKey = "s3.access_key" ConfigKeyS3SecretKey = "s3.secret_key" // #nosec G101 -- configuration key name, not a credential ConfigKeyDomainName = "domain.name" ConfigKeyBaseURL = "base.url" ConfigKeyAPIVersion = "api.version" ConfigKeyJWTSecret = "jwt.secret" ConfigKeyOAuthSecret = "oauth.secret" ConfigKeyEncryptionKey = "encryption.key" ConfigKeyLogLevel = "log.level" ConfigKeyLogFormat = "log.format" ConfigKeyLogOutput = "log.output" ConfigKeyRateLimitEnabled = "ratelimit.enabled" ConfigKeyRateLimitRequests = "ratelimit.requests" ConfigKeyRateLimitWindow = "ratelimit.window" ConfigKeyCacheEnabled = "cache.enabled" ConfigKeyCacheTTL = "cache.ttl" ConfigKeyCacheSize = "cache.size" )
Configuration keys (used in configuration files and environment variables)
const ( DefaultMaxFileSize = 10 * 1024 * 1024 // 10MB DefaultTimeout = 30 // seconds DefaultRetryCount = 3 DefaultBatchSize = 100 // Default TTL values (in seconds) DefaultCacheTTL = 300 // 5 minutes DefaultSessionTTL = 3600 // 1 hour DefaultTokenTTL = 900 // 15 minutes DefaultRefreshTTL = 604800 // 7 days )
Default values as constants (excluding DefaultPaginationLimit which exists in pagination.go)
const ( PatternUsername = `^[a-zA-Z0-9_]{1,30}$` PatternEmail = `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` PatternURL = `^https?://[^\s/$.?#].[^\s]*$` PatternHashtag = `#[a-zA-Z0-9_]+` PatternMention = `@[a-zA-Z0-9_]+(@[a-zA-Z0-9.-]+)?` PatternUUID = `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$` )
Regular expression patterns as constants
const ( CharSpace = " " CharNewline = "\n" CharTab = "\t" CharEmpty = "" CharDot = "." CharComma = "," CharSemicolon = ";" CharColon = ":" CharSlash = "/" CharBackslash = "\\" CharHash = "#" CharAt = "@" CharPlus = "+" CharMinus = "-" CharEquals = "=" CharQuestion = "?" CharAmpersand = "&" )
Special character constants
const ( // Validation errors ValidationMustNotBeNull = "must not be null" ValidationPeriodRequired = "period is required" // General error categories ErrorGeneral = "general" ErrorExpected = "expected" ErrorTimeout = "timeout" ErrorOther = "other" // Access errors ErrorAdminAccessRequired = "admin access required" // Vote related ErrorFailedToStoreVote = "Failed to store vote" // Delivery related ErrorFailedToDeliverToRecipients = "Failed to deliver to recipients" // Subscription related ErrorSubscriptionManagerNotRunning = "subscription manager is not running" // Import related ErrorImportNotFound = "import not found: %s" // Export related ErrorFailedToGetExportsForUser = "failed to get exports for user: %w" // Federation related ErrorFailedToRecordCircuitBreakerFailure = "failed to record circuit breaker failure" // Collection related ErrorFailedToCheckCollectionMembership = "failed to check collection membership" // Moderation related ErrorFailedToStoreAnalysisResult = "failed to store analysis result" // DLQ related ErrorFailedToGetQueueURL = "failed to get queue URL for %s: %w" // Reputation related ErrorInvalidPublicKeyEncoding = "invalid public key encoding: %w" // WebSocket related ErrorFailedToStoreSubscription = "failed to store subscription: %w" // Follow request related ErrorFollowRequestNotFound = "follow request not found" ErrorFailedToGetFollowerActor = "failed to get follower actor" ErrorFailedToGetFollowedActor = "failed to get followed actor" // Search related ErrorSearchFailed = "search failed: %w" ErrorPrivacyAwareSearchFailed = "privacy-aware search failed: %w" ErrorStatusSearchFailed = "status search failed: %w" ErrorPrivacyAwareStatusSearchFailed = "privacy-aware status search failed: %w" // Deployment/initialization related ErrorFailedToGeneratePrivateKey = "failed to generate private key: %w" ErrorFailedToMarshalPrivateKey = "failed to marshal private key: %w" ErrorFailedToConvertToECDHKey = "failed to convert to ECDH key: %w" ErrorFailedToCreateOrUpdateSecret = "failed to create or update secret: %w" // Middleware RBAC related ErrorForbiddenAdminRequired = "forbidden: admin access required" ErrorForbiddenModeratorRequired = "forbidden: moderator access required" ErrorForbiddenViewerRequired = "forbidden: viewer access required" ErrorForbiddenUnknownPermission = "forbidden: unknown permission level" // Translation related ErrorInvalidSourceLanguageCode = "invalid source language code: %w" ErrorInvalidTargetLanguageCode = "invalid target language code: %w" )
Common Error Messages
const ( // Standard headers AuthorizationHeader = "Authorization" ContentTypeHeader = "Content-Type" UserAgentHeader = "User-Agent" AcceptHeader = "Accept" // Custom headers XTenantIDHeader = "X-Tenant-ID" XRequestIDHeader = "X-Request-ID" XRealIPHeader = "X-Real-IP" XForwardedForHeader = "X-Forwarded-For" XProcessingDelayHeader = "X-Processing-Delay" XNextCursorHeader = "X-Next-Cursor" XInboxBacklogHeader = "X-Inbox-Backlog" // Security headers XFrameOptionsHeader = "X-Frame-Options" XContentTypeOptionsHeader = "X-Content-Type-Options" XXSSProtectionHeader = "X-XSS-Protection" // ActivityPub headers DigestHeader = "Digest" SignatureHeader = "Signature" DateHeader = "Date" HostHeader = "Host" )
HTTP Headers
const ( ContentTypeJSON = "application/json" ContentTypeHTML = "text/html" ContentTypeActivityPubJSON = "application/activity+json" ContentTypeLDJSON = "application/ld+json" // Media types ImageGIF = "image/gif" ImagePNG = "image/png" ImageJPEG = "image/jpeg" ImageJPG = "image/jpg" ImageWEBP = "image/webp" VideoMP4 = "video/mp4" VideoWEBM = "video/webm" VideoQuickTime = "video/quicktime" )
Content Types
const ( StringFalse = "false" StringTrue = "true" )
String literals commonly used in parameter processing
const ( SchemeHTTPS = "https" SchemeHTTP = "http" )
URL schemes
const ( // MaxJSONDepth is the maximum JSON depth to prevent deep nesting attacks MaxJSONDepth = 10 // MaxJSONKeys is the maximum number of keys in an object MaxJSONKeys = 100 // MaxJSONArrayLength is the maximum array length MaxJSONArrayLength = 1000 // MaxJSONStringLength is the maximum string length in JSON MaxJSONStringLength = 50000 // MaxJSONSize is the maximum total JSON size (already enforced by request limits) MaxJSONSize = 512 * 1024 // 512KB )
const ( DefaultPaginationLimit = 20 MaxPaginationLimit = 100 MinPaginationLimit = 1 DefaultPaginationPage = 1 )
PaginationDefaults holds the default values for pagination
const ( // MaxRequestSize is the default maximum size for general requests (1MB) MaxRequestSize = 1 * 1024 * 1024 // 1MB // MaxActivitySize is the maximum size for ActivityPub activities MaxActivitySize = 512 * 1024 // 512KB // MaxMediaSize is the maximum size for media uploads (50MB) MaxMediaSize = 50 * 1024 * 1024 // 50MB // MaxImportSize is the maximum size for import files (100MB) MaxImportSize = 100 * 1024 * 1024 // 100MB )
const ( // MaxUntrustedHTTPResponseBodyBytes is the default maximum number of bytes to read from // untrusted HTTP responses when the body is only needed for logging/debugging. // // This is intentionally far smaller than MaxRequestSize: untrusted servers may return // arbitrarily large bodies, and we should never allow them to amplify memory/cost. MaxUntrustedHTTPResponseBodyBytes = 64 * 1024 // 64KB // TruncatedBodyMarker is appended to snippets when the body exceeded the cap. TruncatedBodyMarker = "…[truncated]" )
const ( EventAuthFailure = "auth_failure" EventCSRFFailure = "csrf_failure" EventTokenReuse = "token_reuse" EventRateLimitExceed = "rate_limit_exceed" EventSSRFBlocked = "ssrf_blocked" EventSuspiciousActivity = "suspicious_activity" EventPasswordFailure = "password_failure" EventAccountLocked = "account_locked" EventTokenRevoked = "token_revoked" EventTokenFamilyRevoked = "token_family_revoked" // #nosec G101 - not a credential EventUserTokensRevoked = "user_tokens_revoked" // #nosec G101 - not a credential EventSecurityAlert = "security_alert" )
Security event types
const ( // DateFormat represents YYYY-MM-DD format (e.g., 2006-01-02) DateFormat = "2006-01-02" // MonthFormat represents YYYY-MM format (e.g., 2006-01) MonthFormat = "2006-01" // CompactDateFormat represents YYYYMMDD format (e.g., 20060102) CompactDateFormat = "20060102" // CompactTimeFormat represents YYYYMMDDHHMMSS format (e.g., 20060102150405) CompactTimeFormat = "20060102150405" // DayHourFormat represents YYYYMMDDHH format (e.g., 2006010215) DayHourFormat = "2006010215" // YearFormat represents YYYY format (e.g., 2006) YearFormat = "2006" )
Time format constants used throughout the application
const ( // Status limits MaxStatusLength = 500 MaxStatusSpoiler = 200 MaxStatusAttachment = 4 // Account limits MaxDisplayNameLength = 30 MaxBioLength = 500 MaxFieldNameLength = 255 MaxFieldValueLength = 255 MaxAccountFields = 4 // Media limits MaxMediaDescLength = 1500 MaxMediaFileSize = 100 * 1024 * 1024 // 100MB // Filter limits MaxFilterTitleLength = 200 MaxFilterKeywordLength = 500 MaxFilterKeywords = 50 // Poll limits MaxPollOptions = 4 MaxPollOptionLength = 50 MinPollDuration = 5 * 60 // 5 minutes MaxPollDuration = 30 * 24 * 60 * 60 // 30 days // List limits MaxListTitleLength = 100 MaxListAccounts = 500 // Application limits MaxAppNameLength = 100 MaxAppWebsiteLength = 2000 MaxAppScopesLength = 500 )
Mastodon API constants
const InsecureTLSOverrideEnvVar = "LESSER_ALLOW_INSECURE_TLS"
InsecureTLSOverrideEnvVar enables explicitly allowing insecure TLS in narrowly scoped, debug-only scenarios.
Insecure TLS means certificate verification may be disabled (e.g., tls.Config.InsecureSkipVerify).
const ( // OAuthClientSecretHashPrefix marks hashed secrets stored for OAuth clients. // Prefixing avoids ambiguity with legacy plaintext values. OAuthClientSecretHashPrefix = "bcrypt:" )
const (
VisibilityLocal = "local" // Additional visibility level not in business.go
)
Visibility constants - used for post visibility settings (additional to business.go)
Variables ¶
var ( ReadScopes = []string{ScopeRead, "read:accounts", "read:statuses", "read:follows"} WriteScopes = []string{ScopeWrite, "write:accounts", "write:statuses", "write:follows"} FollowScopes = []string{WriteFollows, ScopeWrite, "write:follows"} BlockScopes = []string{ScopeWrite, "write:blocks"} AdminScopes = []string{AdminRead, AdminWrite} )
Common scope combinations found in the codebase
var ( ErrMastodonInvalidToken = NewMastodonAPIError("invalid_token", "The access token is invalid", 401) ErrMastodonInsufficientScope = NewMastodonAPIError("insufficient_scope", "The request requires higher privileges than provided", 403) ErrMastodonRateLimited = NewMastodonAPIError("rate_limited", "Rate limit exceeded", 429) ErrMastodonValidation = NewMastodonAPIError("validation_failed", "Validation failed", 422) ErrMastodonNotFound = NewMastodonAPIError("record_not_found", "Record not found", 404) )
Common Mastodon API errors
var ( // 400 Bad Request variants ErrorMissingAccountID = "missing account id" ErrorMissingStatusID = "missing status id" ErrorMissingParameter = "missing required parameter" ErrorInvalidParameter = "invalid parameter" ErrorInvalidRequest = "invalid request" ErrorInvalidFormat = "invalid format" // 401 Unauthorized variants ErrorInvalidToken = "invalid token" ErrorMissingAuth = "authentication required" ErrorExpiredToken = "token expired" // 403 Forbidden variants ErrorInsufficientScope = "insufficient scope" ErrorNotAuthorized = "not authorized" ErrorAccessDenied = "access denied" // 404 Not Found variants ErrorNotFound = "not found" ErrorAccountNotFound = "account not found" ErrorStatusNotFound = "status not found" ErrorUserNotFound = "user not found" ErrorActorNotFound = "actor not found" // 422 Unprocessable Entity variants ErrorStatusTooLong = "status text too long" ErrorInvalidContent = "invalid content" // 500 Internal Server Error variants ErrorInternalServer = "internal server error" ErrorDatabaseError = "database error" ErrorFailedToCreate = "failed to create" ErrorFailedToUpdate = "failed to update" ErrorFailedToDelete = "failed to delete" ErrorFailedToGet = "failed to get" )
Common error status/message combinations found in the codebase
var ( ErrTokenNotFound = errors.TokenNotFound() ErrTokenExpired = errors.TokenExpired() ErrTokenRevoked = errors.TokenRevoked() )
Token-related errors
var ( ErrMissingAuthorizationHeader = errors.NewAuthError(errors.CodeAuthFailed, "Missing authorization header") ErrAuthHeaderEmpty = errors.NewAuthError(errors.CodeAuthFailed, "Authorization header is empty") ErrAuthHeaderInvalidPrefix = errors.NewAuthError(errors.CodeAuthFailed, "Authorization header must start with 'Bearer '") ErrAuthenticationRequired = errors.NewAuthError(errors.CodeAuthFailed, "Authentication required for write operations") ErrAuthenticationRequiredRead = errors.NewAuthError(errors.CodeAuthFailed, "Authentication required for read operations") ErrInsufficientScope = errors.InsufficientScope("") ErrInsufficientScopeWrite = errors.InsufficientScope("write access required") ErrInsufficientScopeRead = errors.InsufficientScope("read access required") )
Auth helper errors
var ( ErrDataCannotBeNil = errors.RequiredFieldMissing("data") ErrRequiredFieldMissing = errors.RequiredFieldMissing("field") ErrFieldExceedsMaxLength = errors.FieldTooLong("field", 0, 0) ErrFieldBelowMinLength = errors.FieldTooShort("field", 0, 0) ErrCannotPerformOperationOnSelf = errors.OperationNotAllowedOnSelf("operation") ErrActorAndTargetIDsRequired = errors.MultipleValidationErrors([]string{"Both actor and target IDs are required for operation"}) ErrContentExceedsMaxLength = errors.ContentTooLong("content", 0) ErrContentBelowMinLength = errors.ContentEmpty("content") ErrContentContainsForbiddenWord = errors.ContentContainsForbiddenWord("word") ErrInvalidVisibilityLevel = errors.StatusInvalidVisibility("") ErrActorIDRequiredForQuotaValidation = errors.RequiredFieldMissing("actorID") ErrActionTypeRequiredForQuotaValidation = errors.RequiredFieldMissing("actionType") ErrMetricTypeRequired = errors.RequiredFieldMissing("metricType") ErrActorIDRequiredForMetrics = errors.RequiredFieldMissing("actorID") ErrInvalidCurrentState = errors.InvalidStateForOperation("", "operation") ErrInvalidStateTransition = errors.InvalidStateForOperation("", "state_transition") ErrAuthenticationRequiredForAccess = errors.InsufficientPermissions("access") ErrResourceIDRequiredForAccessValidation = errors.RequiredFieldMissing("resourceID") ErrResourceTypeRequiredForAccessValidation = errors.RequiredFieldMissing("resourceType") ErrInvalidAccessLevel = errors.InvalidValue("access_level", []string{"read", "write", "admin"}, "") ErrOperationValidationFailed = errors.ValidationFailedWithField("operation") ErrOperationExecutionFailed = errors.ProcessingFailed("operation", stdErrors.New("operation execution failed")) )
Business logic validation errors
var ( ErrActorURIEmpty = errors.ActivityPubActorURIEmpty() ErrActivityTypeEmpty = errors.ActivityPubActivityTypeEmpty() ErrSignatureHeaderEmpty = errors.ActivityPubSignatureHeaderEmpty() ErrInvalidSignature = errors.ActivityPubInvalidSignature() ErrActorURIMustUseHTTPS = errors.ActivityPubActorURIMustUseHTTPS() ErrActorDomainBlocked = errors.ContentNotAllowed("actor_domain", "domain is blocked") ErrActorDomainNotAllowed = errors.ContentNotAllowed("actor_domain", "domain not in allowed list") ErrUnsupportedActivityType = errors.ActivityPubUnsupportedActivityType("") )
ActivityPub-specific errors
var ( ErrStatusContentTooLong = errors.ContentTooLong("status", 500) ErrStatusMustHaveContent = errors.ContentMustHaveContentOrMedia() ErrStatusTooManyMedia = errors.StatusTooManyMedia(4, 0) ErrStatusTooManyPollOptions = errors.PollTooManyOptions(4, 0) )
Status validation errors
var ( ErrDisplayNameTooLong = errors.DisplayNameTooLong(30) ErrUsernameEmpty = errors.UsernameEmpty() ErrUsernameInvalidCharacters = errors.UsernameInvalidCharacters() ErrUsernameConsecutiveUnderscores = errors.UsernameConsecutiveUnderscores() ErrUsernameInvalidLength = errors.UsernameInvalidLength(1, 30) ErrUsernameInvalidFormat = errors.UsernameStartsOrEndsWithUnderscore() ErrBioTooLong = errors.BioTooLong(160) )
Account validation errors
var ( ErrVideoFileTooLarge = errors.VideoFileTooLarge(0, 0) ErrMediaFileTooLarge = errors.MediaFileTooLarge(0, 0) ErrInvalidImageMimeType = errors.ImageInvalidFormat("") ErrInvalidVideoMimeType = errors.VideoInvalidFormat("") ErrInvalidAudioMimeType = errors.AudioInvalidFormat("") )
Media validation errors
var ( ErrFilterKeywordEmpty = errors.FilterKeywordEmpty() ErrFilterKeywordTooLong = errors.FilterKeywordTooLong(100) )
Filter validation errors
var ( ErrPollTooFewOptions = errors.PollTooFewOptions(2) ErrPollTooManyOptions = errors.PollTooManyOptions(4, 0) ErrPollOptionEmpty = errors.PollOptionEmpty() ErrPollOptionTooLong = errors.PollOptionTooLong(50) ErrPollExpiryInvalid = errors.PollExpiryInvalid() ErrPollExpiryTooLong = errors.PollExpiryTooLong(604800) )
Poll validation errors
var ( ErrInvalidNotificationType = errors.NotificationTypeInvalid("") ErrInvalidOAuthScope = errors.OAuthScopeInvalid("") ErrIDEmpty = errors.IDEmpty("") ErrInvalidIDFormat = errors.IDInvalidFormat("") ErrInvalidTimestampFormat = errors.TimestampInvalidFormat("") )
General validation errors
var ( ErrJSONDepthExceedsMaximum = errors.JSONTooDeep(10) ErrJSONObjectTooManyKeys = errors.JSONTooManyKeys(100) ErrJSONKeyTooLong = errors.JSONKeyTooLong(256) ErrJSONArrayTooManyElements = errors.JSONArrayTooLarge(1000) ErrJSONStringTooLong = errors.JSONStringTooLong(10000) ErrUnexpectedJSONType = errors.JSONInvalid("unexpected type") ErrJSONSizeExceedsMaximum = errors.JSONSizeTooLarge(1048576) ErrJSONBombRepetitionDetected = errors.JSONBombDetected("excessive repetition") ErrJSONBombNestingDetected = errors.JSONBombDetected("excessive nesting") )
JSON safety validation errors
var ( ErrDynamoTableRequired = errors.EnvironmentVariableRequired("DYNAMODB_TABLE") ErrDynamORMNotImplemented = errors.ServiceInitializationFailedGeneric("DynamORM", nil) ErrRepositoryFactoryNotImplemented = errors.ServiceInitializationFailedGeneric("repository factory", nil) ErrAuthServicesNotImplemented = errors.ServiceInitializationFailedGeneric("auth services", nil) )
Lambda helper errors
var ( ErrRedirectURLEmpty = errors.RequiredFieldMissing("redirect_url") ErrProtocolRelativeURLsNotAllowed = errors.URLSchemeNotAllowed("", "protocol-relative") ErrJavascriptDataURLsNotAllowed = errors.URLSchemeNotAllowed("", "javascript/data") ErrExternalHostNotAllowed = errors.URLHostNotAllowed("", "external") )
Redirect validation errors
var ( ErrRequestBodyTooLarge = errors.FileSizeExceedsLimit(0, 0) ErrFailedToParseRequestBody = errors.ParsingFailed("request body", nil) ErrFailedToParseWithComplexFallback = errors.ParsingFailed("request with complex fallback", nil) )
Request handling errors
var ( ErrLambdaTimeoutApproaching = errors.TimeoutError("Lambda operation") ErrMemoryLimitExceeded = errors.LambdaMemoryExceeded("", 0) )
Resource monitoring errors
var ( ErrTransformFunctionNotSet = errors.TransformFunctionNotSet() ErrTransformationConditionNotMet = errors.PreConditionFailed("transformation condition") ErrUnknownNumber = errors.InvalidValue("number", []string{"valid number"}, "unknown") )
Transformer errors
var ( ErrMastodonOperationValidationFailed = errors.ValidationFailedWithField("mastodon operation") ErrMastodonOperationExecutionFailed = errors.ProcessingFailed("mastodon operation", stdErrors.New("mastodon operation execution failed")) ErrMastodonAPIIncompatibility = errors.BusinessRuleViolated("mastodon API compatibility", nil) ErrInvalidBusinessRule = errors.BusinessRuleViolated("business rule", nil) ErrBusinessValidationFailed = errors.ValidationFailedWithField("business rule") ErrInvalidRequestFormat = errors.InvalidFormat("request", "expected format") ErrUnsupportedOperation = errors.FormatNotSupported("operation") )
Mastodon business logic errors
var ( // UsernamePattern is the regex pattern for valid usernames // Alphanumeric characters, underscores, and hyphens, 1-30 chars UsernamePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,30}$`) // StatusIDPattern is the regex pattern for valid status IDs // Should be numeric or UUID-like format StatusIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) )
Username validation patterns
var ( // Standard limits used across the API StandardTimelineLimit = 40 StandardFollowLimit = 80 StandardSearchLimit = 80 StandardHashtagLimit = 200 StandardAdminLimit = 100 StandardFederationLimit = 200 )
Common API limit validators for different endpoint types
var ( // ActorTypePattern matches valid ActivityPub actor types ActorTypePattern = regexp.MustCompile(`^(Person|Service|Group|Organization|Application)$`) // ActivityTypePattern matches valid ActivityPub activity types ActivityTypePattern = regexp.MustCompile(`^(Create|Update|Delete|Follow|Accept|Reject|Like|Announce|Undo|Block|Move|Add|Remove)$`) // ObjectTypePattern matches valid ActivityPub object types ObjectTypePattern = regexp.MustCompile(`^(Note|Article|Video|Image|Audio|Document|Page|Event|Place|Profile|Relationship|Tombstone)$`) // PublicAddress is the ActivityPub public addressing URI PublicAddress = "https://www.w3.org/ns/activitystreams#Public" // WebfingerPattern matches acct: URIs for webfinger WebfingerPattern = regexp.MustCompile(`^acct:([^@]+)@([^@]+)$`) // ActivityPubMimeTypes are accepted Content-Type headers for ActivityPub ActivityPubMimeTypes = []string{ "application/activity+json", "application/ld+json", "application/json", } )
ActivityPub validation patterns
var ( // StatusIDPattern validates Mastodon status IDs (numeric or alphanumeric) MastodonStatusIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`) // AccountIDPattern validates Mastodon account IDs MastodonAccountIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_\-\.@:\/]+$`) // HashtagPattern validates hashtag format HashtagPattern = regexp.MustCompile(`^[a-zA-Z0-9_]+$`) // LanguageCodePattern validates ISO 639-1 language codes LanguageCodePattern = regexp.MustCompile(`^[a-z]{2}$`) // MimeTypePattern validates basic MIME type format MimeTypePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_.]*$`) )
Mastodon API validation patterns
var DefaultCookieConfig = CookieConfig{ Domain: "", Path: "/", Secure: true, HTTPOnly: true, SameSite: http.SameSiteStrictMode, }
DefaultCookieConfig provides secure defaults
var (
ErrNoBoundaryInContentType = errors.FormBoundaryMissing()
)
Form parsing errors
var SecurityLogger *zap.Logger
SecurityLogger is the global logger for security-related events
var ValidFilterActions = []string{"warn", "hide", "blur"}
ValidFilterActions defines the valid Mastodon filter actions
var ValidFilterContexts = []string{"home", "notifications", "public", "thread", "account"}
ValidFilterContexts defines the valid Mastodon filter contexts
var ValidNotificationTypes = []string{"mention", "status", "reblog", "follow", "follow_request", "favourite", "poll", "update", "admin.sign_up", "admin.report"}
ValidNotificationTypes defines the valid Mastodon notification types
var ValidReportCategories = []string{"spam", "violation", "other"}
ValidReportCategories defines the valid Mastodon report categories
var ValidVisibilityLevels = []string{"public", "unlisted", "private", "direct"}
ValidVisibilityLevels defines the valid Mastodon visibility levels
Functions ¶
func Accepted ¶
func Accepted(body any) *events.APIGatewayV2HTTPResponse
Accepted returns a 202 Accepted response
func ActivityPubHeaders ¶
ActivityPubHeaders returns headers for ActivityPub responses
func ActivityPubResponse ¶
func ActivityPubResponse(statusCode int, body any) *events.APIGatewayV2HTTPResponse
ActivityPubResponse creates a successful ActivityPub response
func AddLinkHeader ¶
func AddLinkHeader(headers map[string]string, baseURL string, endpoint string, cursor string, params map[string]string)
AddLinkHeader adds a Link header for pagination
func AddPaginationHeaders ¶
func AddPaginationHeaders(headers map[string]string, baseURL string, endpoint string, cursor string, params map[string]string, totalCount int)
AddPaginationHeaders adds both Link and custom pagination headers
func BadRequest ¶
func BadRequest(err error) *events.APIGatewayV2HTTPResponse
BadRequest returns a 400 Bad Request response
func BuildLinkHeader ¶
func BuildLinkHeader(baseURL string, params PaginationParams, hasNext, hasPrev bool, nextCursor, prevCursor string) string
BuildLinkHeader creates a Link header for pagination following RFC 5988 This consolidates the link header building logic found across multiple handlers
func CalculateHasMore ¶
CalculateHasMore determines if there are more results based on the returned items count This helps with pagination logic across different storage backends
func CalculateOffset ¶
CalculateOffset calculates the offset from page number and limit
func CalculatePage ¶
CalculatePage calculates the page number from offset and limit
func CheckLambdaResources ¶
CheckLambdaResources is a convenience function to check resources using the global monitor
func ConfigureAllowedRedirectHosts ¶
func ConfigureAllowedRedirectHosts(hosts []string)
ConfigureAllowedRedirectHosts updates the allowed redirect hosts
func Conflict ¶
func Conflict(err error) *events.APIGatewayV2HTTPResponse
Conflict returns a 409 Conflict response
func CreateAPIErrorMiddleware ¶
func CreateAPIErrorMiddleware(logger *zap.Logger) apptheory.Middleware
CreateAPIErrorMiddleware creates error middleware specifically for API services
func CreateFederationErrorMiddleware ¶
func CreateFederationErrorMiddleware(logger *zap.Logger) apptheory.Middleware
CreateFederationErrorMiddleware creates error middleware specifically for federation services
func CreateGraphQLErrorMiddleware ¶
func CreateGraphQLErrorMiddleware(logger *zap.Logger) apptheory.Middleware
CreateGraphQLErrorMiddleware creates error middleware specifically for GraphQL services
func CreateStandardErrorMiddleware ¶
func CreateStandardErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
CreateStandardErrorMiddleware creates the standard error handling middleware stack
func Created ¶
func Created(body any) *events.APIGatewayV2HTTPResponse
Created returns a 201 Created response
func DeleteSecureCookie ¶
func DeleteSecureCookie(w http.ResponseWriter, name string)
DeleteSecureCookie removes a cookie securely
func DetectJSONBomb ¶
DetectJSONBomb checks for obvious JSON bomb patterns
func DevelopmentErrorMiddleware ¶
func DevelopmentErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
DevelopmentErrorMiddleware creates error middleware optimized for development
func ErrFeatureDisabled ¶
ErrFeatureDisabled creates an error indicating a feature is disabled
func ErrorFromType ¶
func ErrorFromType(err error) *events.APIGatewayV2HTTPResponse
ErrorFromType returns an appropriate error response based on error type
func ErrorHandlingMiddleware ¶
func ErrorHandlingMiddleware(config ErrorMiddlewareConfig) apptheory.Middleware
ErrorHandlingMiddleware creates centralized error handling middleware for Lift
func ErrorRecoveryMiddleware ¶
func ErrorRecoveryMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
ErrorRecoveryMiddleware provides graceful degradation for critical errors
func ErrorResponseWithCode ¶
func ErrorResponseWithCode(statusCode int, code string, err error) *events.APIGatewayV2HTTPResponse
ErrorResponseWithCode creates an error response with a specific code
func ExtractAuthHeader ¶
ExtractAuthHeader extracts Authorization header with multiple fallback patterns This consolidates the various patterns found across the codebase
func ExtractBearerToken ¶
ExtractBearerToken extracts the token from the Authorization header This consolidates auth.ExtractBearerToken to avoid import cycles
func ExtractHashtags ¶
ExtractHashtags extracts hashtags from content
func ExtractMentions ¶
ExtractMentions extracts mentions from content
func Forbidden ¶
func Forbidden(err error) *events.APIGatewayV2HTTPResponse
Forbidden returns a 403 Forbidden response
func FormatMastodonTimestamp ¶
FormatMastodonTimestamp formats a time to Mastodon-compatible ISO8601
func FormatUntrustedHTTPBodySnippet ¶
FormatUntrustedHTTPBodySnippet returns a stable string snippet for logs and stored error fields.
func GenerateActivityPubID ¶
GenerateActivityPubID generates a standard ActivityPub ID
func GenerateActivityPubIDULID ¶
GenerateActivityPubIDULID generates an ActivityPub ID using the global generator
func GenerateActorID ¶
GenerateActorID generates a standard actor ID
func GenerateJobIDULID ¶
func GenerateJobIDULID() string
GenerateJobIDULID generates a job ID using the global generator
func GenerateMediaIDULID ¶
func GenerateMediaIDULID() string
GenerateMediaIDULID generates a media ID using the global generator
func GenerateNoteIDULID ¶
func GenerateNoteIDULID() string
GenerateNoteIDULID generates a note ID using the global generator
func GenerateNumericID ¶
GenerateNumericID generates a stable numeric ID from a username This ensures the same username always generates the same ID
func GenerateNumericIDFromActorID ¶
GenerateNumericIDFromActorID generates a stable numeric ID from an ActivityPub actor ID
func GenerateObjectID ¶
GenerateObjectID generates a standard object ID
func GenerateOperationIDULID ¶
func GenerateOperationIDULID() string
GenerateOperationIDULID generates an operation ID using the global generator
func GenerateRequestIDULID ¶
func GenerateRequestIDULID() string
GenerateRequestIDULID generates a request ID using the global generator
func GenerateSessionIDULID ¶
func GenerateSessionIDULID() string
GenerateSessionIDULID generates a session ID using the global generator
func GenerateSnowflakeID ¶
func GenerateSnowflakeID() string
GenerateSnowflakeID generates a Mastodon-compatible snowflake ID
func GenerateStatusID ¶
func GenerateStatusID() string
GenerateStatusID generates a status ID using the global generator
func GetAPIHeaders ¶
GetAPIHeaders returns standard headers for API responses including CORS
func GetBaseURL ¶
GetBaseURL constructs the base URL for the current request
func GetCORSHeaders ¶
GetCORSHeaders returns standard CORS headers for API responses
func GetEnvInt ¶
GetEnvInt gets an integer environment variable with a default value DEPRECATED: Use centralized config.Get() for application configuration instead This consolidates the common pattern: strconv.Atoi(os.Getenv(key)); err == nil Only use this for AWS Lambda runtime variables or when config is not available
func GetLambdaFunctionName ¶
func GetLambdaFunctionName() string
GetLambdaFunctionName returns the AWS Lambda function name
func GetLambdaFunctionVersion ¶
func GetLambdaFunctionVersion() string
GetLambdaFunctionVersion returns the AWS Lambda function version
func GetLambdaInitializationType ¶
func GetLambdaInitializationType() string
GetLambdaInitializationType returns the AWS Lambda initialization type
func GetLambdaLogGroupName ¶
func GetLambdaLogGroupName() string
GetLambdaLogGroupName returns the AWS Lambda log group name
func GetLambdaLogStreamName ¶
func GetLambdaLogStreamName() string
GetLambdaLogStreamName returns the AWS Lambda log stream name
func GetLambdaMemorySize ¶
func GetLambdaMemorySize() string
GetLambdaMemorySize returns the AWS Lambda function memory size
func GetLambdaMemorySizeInt ¶
GetLambdaMemorySizeInt returns the AWS Lambda function memory size as an integer
func GetSafeRedirectURL ¶
GetSafeRedirectURL returns a validated redirect URL or the default
func GetStandardActivityPubContext ¶
func GetStandardActivityPubContext() []interface{}
GetStandardActivityPubContext returns the standard ActivityPub JSON-LD context
func HandleError ¶
HandleError processes an error and returns safe HTTP response values
func HasAllScopes ¶
HasAllScopes checks if claims has all of the provided scopes
func HasAnyScope ¶
HasAnyScope checks if claims has any of the provided scopes
func HashOAuthClientSecret ¶
HashOAuthClientSecret returns a versioned hash string suitable for storage.
func IdentityTransformer ¶
IdentityTransformer returns the input unchanged (useful for pipeline testing)
func InitGlobalIDGenerator ¶
InitGlobalIDGenerator initializes the global ID generator
func InitSecurityLogger ¶
func InitSecurityLogger()
InitSecurityLogger initializes the security-specific logger
func InsecureTLSOverrideEnabled ¶
func InsecureTLSOverrideEnabled() bool
InsecureTLSOverrideEnabled reports whether the runtime explicitly allows disabling TLS verification.
This is a defense-in-depth guardrail: callers must opt-in via an environment variable before any "insecure TLS" code path can be activated.
func InternalServerError ¶
func InternalServerError(err error) *events.APIGatewayV2HTTPResponse
InternalServerError returns a 500 Internal Server Error response
func IsAuthentication ¶
IsAuthentication returns true if the error is an authentication error
func IsAuthorization ¶
IsAuthorization returns true if the error is an authorization error
func IsConflict ¶
IsConflict returns true if the error is a conflict error
func IsFederation ¶
IsFederation returns true if the error is a federation error
func IsModerationMLEnabled ¶
IsModerationMLEnabled checks if ML moderation is enabled for a request. It checks both the global flag and optional tenant allow-list.
func IsNotFound ¶
IsNotFound returns true if the error is a not found error
func IsProcessableMediaType ¶
IsProcessableMediaType checks if media type can be processed (Image, Video, Document)
func IsPubliclyVisible ¶
IsPubliclyVisible checks if content is visible to public (public or unlisted)
func IsRunningInLambda ¶
func IsRunningInLambda() bool
IsRunningInLambda returns true if running in AWS Lambda environment
func IsValidation ¶
IsValidation returns true if the error is a validation error
func IsXRayEnabled ¶
func IsXRayEnabled() bool
IsXRayEnabled returns true if X-Ray tracing is enabled
func JSONResponse ¶
func JSONResponse(statusCode int, body any) *events.APIGatewayV2HTTPResponse
JSONResponse creates a successful JSON response
func JoinKey ¶
JoinKey joins parts into a composite key For example, JoinKey("user", "123") becomes "user#123"
func LogAuthFailure ¶
LogAuthFailure logs authentication failures
func LogCSRFFailure ¶
func LogCSRFFailure(reason string, username string, ip string, path string, userAgent string, requestID string)
LogCSRFFailure logs CSRF validation failures
func LogRateLimit ¶
LogRateLimit logs rate limit exceeded events
func LogSecurityEvent ¶
LogSecurityEvent logs a security-relevant event
func LogSuspiciousActivity ¶
func LogSuspiciousActivity(activity string, userID string, ip string, details map[string]any, requestID string)
LogSuspiciousActivity logs general suspicious activity
func Marshal ¶
Marshal serializes v to JSON with ActivityPub optimizations Using standard library json for now (will upgrade to json/v2 when stable)
func MarshalString ¶
MarshalString is optimized for string output
func MaskSensitiveData ¶
MaskSensitiveData masks sensitive information in logs
func MethodNotAllowed ¶
func MethodNotAllowed(err error) *events.APIGatewayV2HTTPResponse
MethodNotAllowed returns a 405 error response
func MustCheckModerationMLAccess ¶
MustCheckModerationMLAccess returns an error if ML moderation is not available. Useful for resolver-level validation.
func NewDecoder ¶
NewDecoder creates a streaming JSON decoder
func NewEncoder ¶
NewEncoder creates a streaming JSON encoder
func NoContent ¶
func NoContent() *events.APIGatewayV2HTTPResponse
NoContent returns a 204 No Content response
func NotFound ¶
func NotFound(err error) *events.APIGatewayV2HTTPResponse
NotFound returns a 404 Not Found response
func NotFoundMiddleware ¶
func NotFoundMiddleware() apptheory.Middleware
NotFoundMiddleware creates middleware that handles 404 errors gracefully
func ParseAccountStatusesLimit ¶
ParseAccountStatusesLimit parses and validates limits for account status listings
func ParseActivityPubObject ¶
ParseActivityPubObject safely parses an ActivityPub object with JSON bomb detection Use this for ActivityPub objects that may have extensions
func ParseAdminLimit ¶
ParseAdminLimit parses limit for admin endpoints (max 100)
func ParseAndValidateAPILimit ¶
ParseAndValidateAPILimit parses and validates common API limit parameters This consolidates the very common pattern in API handlers
func ParseAndValidateActivityPubLimit ¶
ParseAndValidateActivityPubLimit parses and validates limits for ActivityPub collections
func ParseAndValidateBoolean ¶
ParseAndValidateBoolean parses a boolean parameter from string
func ParseAndValidateIntWithBounds ¶
func ParseAndValidateIntWithBounds(field, value string, minValue, maxValue, defaultValue int) (int, error)
ParseAndValidateIntWithBounds parses a string to int and validates bounds This consolidates the common pattern: strconv.Atoi(str); err == nil && val > min && val <= max
func ParseCookies ¶
ParseCookies extracts cookies from request headers (Lambda compatible)
func ParseFederationLimit ¶
ParseFederationLimit parses limit for federation endpoints (max 200)
func ParseFollowLimit ¶
ParseFollowLimit parses limit for follow/follower endpoints (max 80)
func ParseFormURLEncoded ¶
ParseFormURLEncoded parses URL-encoded form data
func ParseFormValues ¶
ParseFormValues parses URL-encoded form data
func ParseHTTPResponse ¶
ParseHTTPResponse safely parses an HTTP response body Use this when fetching data from external sources
func ParseHashtagLimit ¶
ParseHashtagLimit parses limit for hashtag endpoints (max 200)
func ParseMastodonTimestamp ¶
ParseMastodonTimestamp parses a Mastodon timestamp
func ParseMultipartForm ¶
ParseMultipartForm parses multipart form data from a request body
func ParseRequestBody ¶
ParseRequestBody safely parses a request body with JSON bomb detection Use this for API endpoints with known request structures
func ParseRequestBodyWithValidation ¶
func ParseRequestBodyWithValidation(ctx *apptheory.Context, target interface{}, fieldName string) (*apptheory.Response, error)
ParseRequestBodyWithValidation parses request body with validation error response
func ParseRequestWithComplexFallback ¶
ParseRequestWithComplexFallback handles the complex fallback pattern found in quotes.go and other files
func ParseRequestWithCustomError ¶
func ParseRequestWithCustomError(ctx *apptheory.Context, target interface{}, errorMessage string) (*apptheory.Response, error)
ParseRequestWithCustomError allows custom error handling
func ParseRequestWithFallback ¶
ParseRequestWithFallback attempts to parse request using ctx.ParseRequest with fallback strategies This consolidates the common pattern of:
if err := ctx.ParseRequest(&req); err != nil {
// Fallback logic for test environments
...
}
func ParseRequestWithValidation ¶
func ParseRequestWithValidation(ctx *apptheory.Context, target interface{}) (*apptheory.Response, error)
ParseRequestWithValidation combines parsing with common validation responses
func ParseSearchLimit ¶
ParseSearchLimit parses limit for search endpoints (max 80)
func ParseSearchOffset ¶
ParseSearchOffset parses and validates search offset parameters
func ParseStatusContextLimit ¶
ParseStatusContextLimit parses and validates limits for status context endpoints
func ParseStatusTimelineLimit ¶
ParseStatusTimelineLimit parses and validates limits for status timelines (home, public)
func ParseTimelineLimit ¶
ParseTimelineLimit parses limit for timeline endpoints (max 40)
func ProductionErrorMiddleware ¶
func ProductionErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
ProductionErrorMiddleware creates error middleware optimized for production
func ReadRequestBody ¶
ReadRequestBody safely reads a request body with a size limit If maxSize is 0 or negative, MaxRequestSize is used as default
func ReadRequestBodyString ¶
ReadRequestBodyString is a convenience function that returns the body as a string
func ReadUntrustedHTTPResponseBody ¶
ReadUntrustedHTTPResponseBody reads up to maxBytes from r and reports whether the response body was truncated. It never allocates more than maxBytes+1.
func RecordBusinessMetric ¶
func RecordBusinessMetric(_ context.Context, metricType, _ string, actorID string, _ map[string]interface{}) error
RecordBusinessMetric records business metrics using the existing metrics infrastructure
func RespondAccountNotFound ¶
RespondAccountNotFound handles account not found errors by returning a 404 not found response
func RespondActorNotFound ¶
RespondActorNotFound handles actor not found errors by returning a 404 not found response
func RespondAlreadyExists ¶
RespondAlreadyExists handles resource already exists conflicts by returning a 409 conflict response
func RespondAuthErrorWithCode ¶
func RespondAuthErrorWithCode(ctx *apptheory.Context, errorCode int, err error) (*apptheory.Response, error)
RespondAuthErrorWithCode handles authentication/authorization errors with status code
func RespondBadRequest ¶
RespondBadRequest handles validation and bad request errors (400) - now using centralized errors
func RespondConflict ¶
RespondConflict handles resource conflict errors (409) - now using centralized errors
func RespondConversationNotFound ¶
RespondConversationNotFound handles conversation not found errors by returning a 404 not found response
func RespondCreateError ¶
func RespondCreateError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
RespondCreateError handles errors from create operations - now using centralized errors
func RespondDatabaseError ¶
RespondDatabaseError handles database errors by returning a 500 internal server error response
func RespondDeleteError ¶
func RespondDeleteError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
RespondDeleteError handles errors from delete operations - now using centralized errors
func RespondExpiredToken ¶
RespondExpiredToken handles expired token errors by returning a 401 unauthorized response
func RespondFailedToCreate ¶
RespondFailedToCreate handles resource creation failures by returning a 500 internal server error response
func RespondFailedToDelete ¶
RespondFailedToDelete handles resource deletion failures by returning a 500 internal server error response
func RespondFailedToGet ¶
RespondFailedToGet handles resource retrieval failures by returning a 500 internal server error response
func RespondFailedToUpdate ¶
RespondFailedToUpdate handles resource update failures by returning a 500 internal server error response
func RespondFilterNotFound ¶
RespondFilterNotFound handles filter not found errors by returning a 404 not found response
func RespondForbidden ¶
RespondForbidden handles authorization/permission errors (403) - now using centralized errors
func RespondGetError ¶
func RespondGetError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
RespondGetError handles errors from get/fetch operations - now using centralized errors
func RespondGone ¶
RespondGone handles resource gone errors (410) with optional custom message
func RespondInsufficientScope ¶
func RespondInsufficientScope(_ *apptheory.Context, requiredScope ...string) (*apptheory.Response, error)
RespondInsufficientScope handles insufficient OAuth scope errors by returning a 403 forbidden response
func RespondInternalServerError ¶
func RespondInternalServerError(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
RespondInternalServerError handles internal server errors (500) - now using centralized errors
func RespondInvalidContent ¶
RespondInvalidContent handles invalid content errors by returning a 422 unprocessable entity response
func RespondInvalidParameter ¶
RespondInvalidParameter handles invalid parameter errors by returning a 400 bad request response
func RespondInvalidRequest ¶
RespondInvalidRequest handles general invalid request errors by returning a 400 bad request response
func RespondInvalidToken ¶
RespondInvalidToken handles invalid token errors by returning a 401 unauthorized response
func RespondLegacyError ¶
func RespondLegacyError(_ *apptheory.Context, statusCode int, message string) (*apptheory.Response, error)
RespondLegacyError maintains compatibility with existing map[string]string{"error": "message"} pattern
func RespondMethodNotAllowed ¶
RespondMethodNotAllowed handles HTTP method not allowed errors by returning a 405 response
func RespondMissingAccountID ¶
RespondMissingAccountID handles missing account ID errors by returning a 400 bad request response
func RespondMissingAuth ¶
RespondMissingAuth handles authentication required errors by returning a 401 unauthorized response
func RespondMissingParameter ¶
RespondMissingParameter handles missing required parameter errors by returning a 400 bad request response
func RespondMissingStatusID ¶
RespondMissingStatusID handles missing status ID errors by returning a 400 bad request response
func RespondNotAuthorized ¶
RespondNotAuthorized handles general authorization errors by returning a 403 forbidden response
func RespondNotAuthorizedToDelete ¶
func RespondNotAuthorizedToDelete(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
RespondNotAuthorizedToDelete handles deletion authorization errors by returning a 403 forbidden response
func RespondNotAuthorizedToModify ¶
func RespondNotAuthorizedToModify(ctx *apptheory.Context, resource string) (*apptheory.Response, error)
RespondNotAuthorizedToModify handles modification authorization errors by returning a 403 forbidden response
func RespondNotFound ¶
RespondNotFound handles resource not found errors (404) - now using centralized errors
func RespondRateLimited ¶
RespondRateLimited handles rate limit exceeded errors by returning a 429 response
func RespondServiceUnavailable ¶
func RespondServiceUnavailable(_ *apptheory.Context, service ...string) (*apptheory.Response, error)
RespondServiceUnavailable handles service unavailable errors (503) with optional service name
func RespondStatusNotFound ¶
RespondStatusNotFound handles status not found errors by returning a 404 not found response
func RespondStatusTooLong ¶
RespondStatusTooLong handles status text too long errors by returning a 422 unprocessable entity response
func RespondSuccess ¶
RespondSuccess handles successful responses with data
func RespondUnauthorized ¶
RespondUnauthorized handles authentication errors (401) - now using centralized errors
func RespondUnauthorizedWithDescription ¶
func RespondUnauthorizedWithDescription(_ *apptheory.Context, description string) (*apptheory.Response, error)
RespondUnauthorizedWithDescription handles authentication errors (401) with additional description
func RespondUnprocessableEntity ¶
func RespondUnprocessableEntity(_ *apptheory.Context, message ...string) (*apptheory.Response, error)
RespondUnprocessableEntity handles unprocessable entity errors (422) with optional custom message
func RespondUpdateError ¶
func RespondUpdateError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)
RespondUpdateError handles errors from update operations - now using centralized errors
func RespondUserNotFound ¶
RespondUserNotFound handles user not found errors by returning a 404 not found response
func RespondValidationError ¶
RespondValidationError handles validation failed errors - now using centralized errors
func RespondValidationOrError ¶
RespondValidationOrError handles validation errors and other errors appropriately
func RespondWithAppError ¶
func RespondWithAppError(_ *apptheory.Context, appErr *errors.AppError) (*apptheory.Response, error)
RespondWithAppError creates a response from a centralized AppError
func RespondWithError ¶
func RespondWithError(ctx *apptheory.Context, code int, message string) (*apptheory.Response, error)
RespondWithError is an alias for SendError for consistency with existing patterns
func RespondWithErrorAndDescription ¶
func RespondWithErrorAndDescription(_ *apptheory.Context, statusCode int, errorMsg, description string) (*apptheory.Response, error)
RespondWithErrorAndDescription creates a detailed error response
func RespondWithErrorCode ¶
func RespondWithErrorCode(_ *apptheory.Context, statusCode int, errorMsg, code string) (*apptheory.Response, error)
RespondWithErrorCode creates an error response with an error code
func RespondWithErrorMessage ¶
func RespondWithErrorMessage(_ *apptheory.Context, statusCode int, message string) (*apptheory.Response, error)
RespondWithErrorMessage creates a standardized error response with custom message
func RespondWithJSON ¶
func RespondWithJSON(ctx *apptheory.Context, code int, data interface{}) (*apptheory.Response, error)
RespondWithJSON is an alias for SendJSON for consistency with existing patterns
func RunningUnitTests ¶
func RunningUnitTests() bool
RunningUnitTests reports whether the current binary is the Go test harness. It uses the convention that test binaries end with the .test suffix.
func SafeRedirect ¶
func SafeRedirect(w http.ResponseWriter, r *http.Request, defaultPath string)
SafeRedirect performs a safe redirect with validation
func SafeRedirectOrDefault ¶
func SafeRedirectOrDefault(w http.ResponseWriter, r *http.Request, redirectURL, defaultPath string)
SafeRedirectOrDefault redirects to the given URL if safe, otherwise to default
func SafeUnmarshalJSON ¶
SafeUnmarshalJSON is a convenience function for safe JSON unmarshaling
func SafeUnmarshalJSONWithoutUnknownFields ¶
SafeUnmarshalJSONWithoutUnknownFields unmarshals JSON without DisallowUnknownFields Use this for ActivityPub objects which may have extensions
func SanitizeActivityPubObjectDefault ¶
SanitizeActivityPubObjectDefault sanitizes an object using the default sanitizer
func SanitizeContent ¶
SanitizeContent is a convenience function using the default sanitizer
func SanitizeHTML ¶
SanitizeHTML removes or escapes HTML content for Mastodon API responses
func SanitizeInput ¶
SanitizeInput performs basic input sanitization
func SendAccepted ¶
SendAccepted sends a 202 Accepted response with data
func SendCreated ¶
SendCreated sends a 201 Created response with data
func SendEmptyObject ¶
SendEmptyObject sends an empty object response
func SendError ¶
SendError is a convenience function for sending standardized error responses with Lift This consolidates the pattern: return apptheory.JSON(code, map[string]string{"error": message})
func SendHealthCheck ¶
func SendHealthCheck(ctx *apptheory.Context, health HealthCheckResponse) (*apptheory.Response, error)
SendHealthCheck sends a health check response
func SendJSON ¶
SendJSON is a convenience function for sending successful JSON responses with Lift This consolidates the pattern: return apptheory.JSON(code, data)
func SendMastodonAccount ¶
func SendMastodonAccount(ctx *apptheory.Context, account MastodonAccount) (*apptheory.Response, error)
SendMastodonAccount sends a Mastodon-formatted account response
func SendMastodonAccounts ¶
func SendMastodonAccounts(ctx *apptheory.Context, accounts []MastodonAccount) (*apptheory.Response, error)
SendMastodonAccounts sends a Mastodon-formatted accounts array response
func SendMastodonError ¶
func SendMastodonError(_ *apptheory.Context, code int, errorMsg string) (*apptheory.Response, error)
SendMastodonError sends Mastodon API-compatible error responses Mastodon clients expect a specific error format for proper error handling
func SendMastodonStatus ¶
SendMastodonStatus sends a Mastodon-formatted status response
func SendMastodonStatuses ¶
func SendMastodonStatuses(ctx *apptheory.Context, statuses []MastodonStatus) (*apptheory.Response, error)
SendMastodonStatuses sends a Mastodon-formatted statuses array response
func SendNoContent ¶
SendNoContent sends a 204 No Content response
func SendPaginatedMastodonResponse ¶
func SendPaginatedMastodonResponse(ctx *apptheory.Context, data interface{}, params PaginationParams, hasNext, hasPrev bool, nextCursor, prevCursor string) (*apptheory.Response, error)
SendPaginatedMastodonResponse sends Mastodon-compatible paginated response Mastodon uses Link headers for pagination instead of response body metadata
func SendPaginatedResponse ¶
func SendPaginatedResponse(ctx *apptheory.Context, data interface{}, pagination *Pagination) (*apptheory.Response, error)
SendPaginatedResponse sends a response with pagination metadata
func SendRateLimitHeaders ¶
SendRateLimitHeaders sets rate limit headers
func SendStreamingMessage ¶
func SendStreamingMessage(ctx *apptheory.Context, event string, data interface{}) (*apptheory.Response, error)
SendStreamingMessage sends a Server-Sent Events formatted message
func SetActivityPubHeaders ¶
SetActivityPubHeaders sets headers for ActivityPub responses
func SetCORSHeaders ¶
SetCORSHeaders sets comprehensive CORS headers for API responses.
func SetCacheHeaders ¶
SetCacheHeaders sets appropriate cache headers based on content type
func SetJSONHeaders ¶
SetJSONHeaders sets headers for JSON API responses
func SetNoCache ¶
SetNoCache sets no-cache headers for sensitive responses
func SetPaginationHeaders ¶
func SetPaginationHeaders(resp *apptheory.Response, baseURL string, params PaginationParams, hasNext, hasPrev bool, nextCursor, prevCursor string)
SetPaginationHeaders sets standard pagination headers on an AppTheory response.
func SetSecureCookie ¶
func SetSecureCookie(w http.ResponseWriter, name, value string, maxAge int)
SetSecureCookie sets a cookie with all security flags
func SetSecureCookieWithConfig ¶
func SetSecureCookieWithConfig(w http.ResponseWriter, name, value string, maxAge int, config CookieConfig)
SetSecureCookieWithConfig sets a cookie with custom configuration
func SetSecurityHeaders ¶
SetSecurityHeaders sets security-related headers
func SplitKey ¶
SplitKey splits a composite key into its parts For example, "user#123" becomes ["user", "123"]
func TimeoutErrorMiddleware ¶
func TimeoutErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
TimeoutErrorMiddleware creates middleware that handles timeout errors
func TooManyRequests ¶
func TooManyRequests(err error) *events.APIGatewayV2HTTPResponse
TooManyRequests returns a 429 Too Many Requests response
func Unauthorized ¶
func Unauthorized(err error) *events.APIGatewayV2HTTPResponse
Unauthorized returns a 401 Unauthorized response
func UnprocessableEntity ¶
func UnprocessableEntity(err error) *events.APIGatewayV2HTTPResponse
UnprocessableEntity returns a 422 Unprocessable Entity response
func ValidateAccountBio ¶
ValidateAccountBio validates account bio length
func ValidateAccountFields ¶
func ValidateAccountFields(fields interface{}) error
ValidateAccountFields validates account profile fields
func ValidateAccountID ¶
ValidateAccountID validates an account ID (can be username, numeric ID, or URL)
func ValidateAccountIDsParameter ¶
ValidateAccountIDsParameter validates comma-separated account IDs (used in familiar followers)
func ValidateAccountParamID ¶
ValidateAccountParamID validates account ID from URL parameters (commonly used in API handlers)
func ValidateAccountParams ¶
ValidateAccountParams validates parameters for account updates
func ValidateAcctParameter ¶
ValidateAcctParameter validates the 'acct' parameter used in account lookups
func ValidateActivityPubActivity ¶
ValidateActivityPubActivity validates an ActivityPub Activity object structure
func ValidateActivityPubActor ¶
ValidateActivityPubActor validates an ActivityPub Actor object structure
func ValidateActivityPubAddressing ¶
ValidateActivityPubAddressing validates addressing fields (to, cc, bto, bcc)
func ValidateActivityPubAttachments ¶
ValidateActivityPubAttachments validates attachment arrays
func ValidateActivityPubContentType ¶
ValidateActivityPubContentType validates Content-Type headers for ActivityPub
func ValidateActivityPubContext ¶
ValidateActivityPubContext validates the @context field
func ValidateActivityPubJSON ¶
ValidateActivityPubJSON validates that a string contains valid ActivityPub JSON
func ValidateActivityPubNote ¶
ValidateActivityPubNote validates an ActivityPub Note object structure
func ValidateActivityPubPublicKey ¶
ValidateActivityPubPublicKey validates public key objects
func ValidateActivityPubSignature ¶
ValidateActivityPubSignature validates HTTP signature headers for ActivityPub
func ValidateActivityPubTags ¶
ValidateActivityPubTags validates tag arrays
func ValidateActivityPubTimestamp ¶
ValidateActivityPubTimestamp validates timestamp formats used in ActivityPub
func ValidateActivityPubURL ¶
ValidateActivityPubURL validates URLs for ActivityPub compliance
func ValidateActivityPubUsername ¶
ValidateActivityPubUsername validates usernames for ActivityPub compliance
func ValidateActivityType ¶
func ValidateActivityType(activityType string, rules ActivityPubValidationRules) error
ValidateActivityType validates ActivityPub activity types
func ValidateActorEntity ¶
ValidateActorEntity validates actor entity data before repository operations
func ValidateActorURI ¶
func ValidateActorURI(actorURI string, rules ActivityPubValidationRules) error
ValidateActorURI validates ActivityPub actor URIs
func ValidateAdminScopes ¶
ValidateAdminScopes validates against common admin scope combinations
func ValidateAlphanumericID ¶
ValidateAlphanumericID validates an alphanumeric ID
func ValidateAndSanitizeMediaType ¶
ValidateAndSanitizeMediaType validates and sanitizes media MIME types
func ValidateAndSanitizeString ¶
ValidateAndSanitizeString validates string length and sanitizes content
func ValidateApplicationName ¶
ValidateApplicationName validates application name
func ValidateApplicationParams ¶
ValidateApplicationParams validates parameters for application creation
func ValidateApplicationScopes ¶
ValidateApplicationScopes validates OAuth application scopes
func ValidateBlockScopes ¶
ValidateBlockScopes validates against common block scope combinations
func ValidateBooleanString ¶
ValidateBooleanString validates boolean-like strings
func ValidateBusinessContent ¶
func ValidateBusinessContent(content string, rules ContentValidationRules) error
ValidateBusinessContent validates content against business rules
func ValidateBusinessVisibility ¶
func ValidateBusinessVisibility(visibility VisibilityLevel, _ string) error
ValidateBusinessVisibility validates business visibility settings
func ValidateContentOrAttachments ¶
ValidateContentOrAttachments validates that either content or attachments are provided
func ValidateDisplayName ¶
ValidateDisplayName validates display name length
func ValidateDomainName ¶
ValidateDomainName validates domain names for ActivityPub
func ValidateEntityID ¶
ValidateEntityID validates entity IDs used in repository operations
func ValidateEntityIDsList ¶
ValidateEntityIDsList validates a list of entity IDs
func ValidateEnum ¶
ValidateEnum validates that a value is within a set of allowed values
func ValidateEnumField ¶
ValidateEnumField validates enum values used in repository models
func ValidateFilterAction ¶
ValidateFilterAction validates filter action
func ValidateFilterContext ¶
ValidateFilterContext validates filter context values
func ValidateFilterContextParam ¶
func ValidateFilterContextParam(context interface{}) error
ValidateFilterContextParam validates filter context parameter
func ValidateFilterExpiration ¶
func ValidateFilterExpiration(expiresIn interface{}) error
ValidateFilterExpiration validates filter expiration parameters
func ValidateFilterKeyword ¶
ValidateFilterKeyword validates filter keyword
func ValidateFilterKeywords ¶
func ValidateFilterKeywords(keywords interface{}) error
ValidateFilterKeywords validates filter keywords
func ValidateFilterParamID ¶
ValidateFilterParamID validates filter ID from URL parameters
func ValidateFilterParams ¶
ValidateFilterParams validates parameters for filter creation/update
func ValidateFilterTitle ¶
ValidateFilterTitle validates filter title
func ValidateFloatRange ¶
ValidateFloatRange validates that a float value is within the specified range
func ValidateFollowScopes ¶
ValidateFollowScopes validates against common follow scope combinations
func ValidateHTTPScheme ¶
ValidateHTTPScheme validates HTTP/HTTPS schemes
func ValidateHashtag ¶
ValidateHashtag validates hashtag format for Mastodon
func ValidateIntRange ¶
ValidateIntRange validates that an int value is within the specified range
func ValidateJSONField ¶
ValidateJSONField validates JSON string fields in repository models
func ValidateKeywordParamID ¶
ValidateKeywordParamID validates keyword ID from URL parameters
func ValidateLanguageCode ¶
ValidateLanguageCode validates language codes (ISO 639-1 format)
func ValidateLimit ¶
ValidateLimit validates a limit parameter with bounds checking
func ValidateListParams ¶
ValidateListParams validates parameters for list creation/update
func ValidateListRepliesPolicy ¶
ValidateListRepliesPolicy validates list replies policy
func ValidateListTitle ¶
ValidateListTitle validates list title
func ValidateMastodonAccountID ¶
ValidateMastodonAccountID validates Mastodon account ID format
func ValidateMastodonFilterKeyword ¶
ValidateMastodonFilterKeyword validates filter keyword patterns
func ValidateMastodonID ¶
ValidateMastodonID validates Mastodon-style IDs
func ValidateMastodonMimeType ¶
ValidateMastodonMimeType validates MIME types for Mastodon API
func ValidateMastodonOAuthScopes ¶
ValidateMastodonOAuthScopes validates OAuth scope strings for Mastodon API
func ValidateMastodonStatusID ¶
ValidateMastodonStatusID validates Mastodon status ID format
func ValidateMastodonTimeline ¶
ValidateMastodonTimeline validates timeline parameters
func ValidateMastodonUsername ¶
ValidateMastodonUsername validates Mastodon-compatible usernames
func ValidateMediaDescription ¶
ValidateMediaDescription validates media attachment descriptions
func ValidateMediaEntity ¶
ValidateMediaEntity validates media entity data before repository operations
func ValidateMediaFile ¶
ValidateMediaFile validates media file format/type
func ValidateMediaFocus ¶
ValidateMediaFocus validates media focus point coordinates
func ValidateMediaIDs ¶
func ValidateMediaIDs(mediaIDs interface{}) error
ValidateMediaIDs validates media attachment IDs
func ValidateMediaParams ¶
ValidateMediaParams validates parameters for media uploads
func ValidateMediaType ¶
ValidateMediaType validates media attachment types
func ValidateMultipleRequiredParams ¶
ValidateMultipleRequiredParams validates multiple required parameters at once
func ValidateNormalizedQuery ¶
ValidateNormalizedQuery validates and normalizes search queries
func ValidateNotificationType ¶
ValidateNotificationType validates notification type
func ValidateNumericID ¶
ValidateNumericID validates a numeric ID (string representation)
func ValidateOffset ¶
ValidateOffset validates an offset parameter
func ValidatePaginationLimit ¶
ValidatePaginationLimit ensures the limit is within acceptable bounds
func ValidatePollParams ¶
func ValidatePollParams(poll interface{}) error
ValidatePollParams validates poll creation parameters
func ValidatePreferenceValue ¶
ValidatePreferenceValue validates user preference values
func ValidateQueryFilters ¶
ValidateQueryFilters validates filter parameters for repository queries
func ValidateQueryLimit ¶
ValidateQueryLimit validates query limits with repository-specific maximums
func ValidateQueryOffset ¶
ValidateQueryOffset validates query offsets for repository operations
func ValidateReadAccess ¶
func ValidateReadAccess(authResult *AuthenticationResult) error
ValidateReadAccess validates that the authenticated user can perform read operations
func ValidateReadScopes ¶
ValidateReadScopes validates against common read scope combinations
func ValidateRedirectURIs ¶
ValidateRedirectURIs validates OAuth redirect URIs
func ValidateRedirectURL ¶
ValidateRedirectURL validates that a redirect URL is safe and allowed and returns the sanitized value.
func ValidateReportCategory ¶
ValidateReportCategory validates report category
func ValidateReportComment ¶
ValidateReportComment validates report comment
func ValidateReportParams ¶
ValidateReportParams validates parameters for report creation
func ValidateReportStatusIDs ¶
func ValidateReportStatusIDs(statusIDs interface{}) error
ValidateReportStatusIDs validates status IDs in reports
func ValidateRepositoryAccess ¶
ValidateRepositoryAccess validates access permissions for repository operations
func ValidateRepositoryCursor ¶
ValidateRepositoryCursor validates cursor parameters for pagination
func ValidateRepositoryRelationship ¶
ValidateRepositoryRelationship validates relationships between entities
func ValidateRepositorySearchQuery ¶
ValidateRepositorySearchQuery validates search queries for repository operations
func ValidateRequiredParam ¶
ValidateRequiredParam validates that a required parameter is not empty
func ValidateResourceAccess ¶
func ValidateResourceAccess(_ context.Context, actorID, resourceID, resourceType string, requiredAccess AccessLevel) error
ValidateResourceAccess validates access to resources using existing auth patterns
func ValidateResponseData ¶
func ValidateResponseData(data interface{}) interface{}
ValidateResponseData ensures response data is not nil and properly formatted
func ValidateScheduledTime ¶
ValidateScheduledTime validates scheduled posting time
func ValidateSearchQuery ¶
ValidateSearchQuery validates search query parameters
func ValidateSliceLength ¶
ValidateSliceLength validates slice length against bounds
func ValidateSliceNotEmpty ¶
ValidateSliceNotEmpty validates that a slice is not empty
func ValidateSortParameters ¶
ValidateSortParameters validates sort field and order parameters
func ValidateSpoilerText ¶
ValidateSpoilerText validates content warning text
func ValidateStateTransition ¶
func ValidateStateTransition(currentState, newState EntityState, entityType string) error
ValidateStateTransition validates state transitions
func ValidateStatusContent ¶
ValidateStatusContent validates status content length and format
func ValidateStatusEntity ¶
ValidateStatusEntity validates status entity data before repository operations
func ValidateStatusID ¶
ValidateStatusID validates a status ID format
func ValidateStatusParamID ¶
ValidateStatusParamID validates status ID from URL parameters
func ValidateStatusParams ¶
ValidateStatusParams validates parameters for status creation/update
func ValidateStatusState ¶
ValidateStatusState validates status states (pending, completed, failed, etc.)
func ValidateStringLength ¶
ValidateStringLength validates string length within bounds
func ValidateStruct ¶
func ValidateStruct(data interface{}, rules ValidationRules) error
ValidateStruct performs basic struct validation using reflection
func ValidateTimestamp ¶
ValidateTimestamp validates timestamp formats used in repositories
func ValidateURL ¶
ValidateURL validates URL formats used in repositories
func ValidateUUID ¶
ValidateUUID validates a UUID format
func ValidateUserEntity ¶
ValidateUserEntity validates user entity data before repository operations
func ValidateUserRelationship ¶
func ValidateUserRelationship(_ context.Context, actorID, targetID string, relationshipType string) error
ValidateUserRelationship validates relationships between users
func ValidateUsername ¶
ValidateUsername validates a username according to platform rules
func ValidateUsernameParamID ¶
ValidateUsernameParamID validates username from URL parameters
func ValidateVisibility ¶
ValidateVisibility validates status visibility values
func ValidateWebfingerResource ¶
ValidateWebfingerResource validates WebFinger resource identifiers
func ValidateWriteAccess ¶
func ValidateWriteAccess(authResult *AuthenticationResult) error
ValidateWriteAccess validates that the authenticated user can perform write operations
func ValidateWriteScopes ¶
ValidateWriteScopes validates against common write scope combinations
func ValidationErrorMiddleware ¶
func ValidationErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware
ValidationErrorMiddleware creates middleware specifically for validation error handling
func VerifyOAuthClientSecret ¶
VerifyOAuthClientSecret verifies a provided secret against a stored value. It returns (valid, needsMigration, err). needsMigration is true when the stored value is a legacy plaintext secret and the verification succeeded.
func WithContext ¶
WithContext returns a logger with Lambda context fields
func WithFields ¶
WithFields returns a logger with additional fields
func WithSecurityContext ¶
func WithSecurityContext(logger *zap.Logger, ctx SecurityContext) *zap.Logger
WithSecurityContext adds security context to logger
func WrapObjectInActivity ¶
func WrapObjectInActivity(activityType, actorID string, object interface{}, published time.Time) map[string]interface{}
WrapObjectInActivity wraps an object in an ActivityPub activity
func WrapWithLambdaResourceCheck ¶
WrapWithLambdaResourceCheck is a convenience function to wrap operations with the global monitor
Types ¶
type AccessLevel ¶
type AccessLevel string
AccessLevel represents access levels
const ( AccessNone AccessLevel = "none" // AccessNone represents no access required AccessRead AccessLevel = "read" // AccessRead represents read access required AccessWrite AccessLevel = "write" // AccessWrite represents write access required AccessAdmin AccessLevel = "admin" // AccessAdmin represents admin access required )
Resource access level constants
type AccountSuspendedError ¶
type AccountSuspendedError struct {
Username string
}
AccountSuspendedError indicates an account is suspended
func (AccountSuspendedError) Error ¶
func (e AccountSuspendedError) Error() string
type ActivityNotFoundError ¶
type ActivityNotFoundError struct {
ID string
}
ActivityNotFoundError indicates an activity was not found
func (ActivityNotFoundError) Error ¶
func (e ActivityNotFoundError) Error() string
type ActivityPubActivity ¶
ActivityPubActivity represents an ActivityPub activity
func CreateFederationActivity ¶
func CreateFederationActivity(actorID, activityType string, object interface{}) *ActivityPubActivity
CreateFederationActivity creates ActivityPub activities for federation
type ActivityPubActor ¶
type ActivityPubActor interface {
GetID() string
GetType() string
GetInbox() string
GetOutbox() string
GetFollowers() string
GetFollowing() string
}
ActivityPubActor represents a generic ActivityPub actor interface
type ActivityPubAudience ¶
type ActivityPubAudience struct {
To []string `json:"to,omitempty"`
CC []string `json:"cc,omitempty"`
BTo []string `json:"bto,omitempty"`
BCC []string `json:"bcc,omitempty"`
}
ActivityPubAudience represents the audience for an ActivityPub object
func CalculateActivityPubAudience ¶
func CalculateActivityPubAudience(visibility VisibilityLevel, actorFollowers string, mentions []string) ActivityPubAudience
CalculateActivityPubAudience calculates the audience for an ActivityPub object
type ActivityPubBusinessLogic ¶
type ActivityPubBusinessLogic struct {
// contains filtered or unexported fields
}
ActivityPubBusinessLogic provides centralized ActivityPub business operations
func NewActivityPubBusinessLogic ¶
func NewActivityPubBusinessLogic(config *FederationConfig, logger *zap.Logger) *ActivityPubBusinessLogic
NewActivityPubBusinessLogic creates a new ActivityPub business logic service
func (*ActivityPubBusinessLogic) ExecuteActivityPubOperation ¶
func (ap *ActivityPubBusinessLogic) ExecuteActivityPubOperation(ctx context.Context, operation ActivityPubOperation) error
ExecuteActivityPubOperation executes a federation operation with standard error handling and retry logic
type ActivityPubCollection ¶
type ActivityPubCollection struct {
Context interface{} `json:"@context"`
ID string `json:"id"`
Type string `json:"type"`
TotalItems int `json:"totalItems"`
First string `json:"first,omitempty"`
Last string `json:"last,omitempty"`
Items []interface{} `json:"items,omitempty"`
OrderedItems []interface{} `json:"orderedItems,omitempty"`
}
ActivityPubCollection represents a paginated ActivityPub collection
func CreateActivityPubCollection ¶
func CreateActivityPubCollection(id, collectionType string, totalItems int, firstPage string) ActivityPubCollection
CreateActivityPubCollection creates a standard ActivityPub collection
type ActivityPubCollectionPage ¶
type ActivityPubCollectionPage struct {
Context interface{} `json:"@context"`
ID string `json:"id"`
Type string `json:"type"`
PartOf string `json:"partOf"`
Next string `json:"next,omitempty"`
Prev string `json:"prev,omitempty"`
Items []interface{} `json:"items,omitempty"`
OrderedItems []interface{} `json:"orderedItems,omitempty"`
}
ActivityPubCollectionPage represents a page in an ActivityPub collection
func CreateActivityPubCollectionPage ¶
func CreateActivityPubCollectionPage(id, pageType, partOf string, items []interface{}, nextPage, prevPage string) ActivityPubCollectionPage
CreateActivityPubCollectionPage creates a standard ActivityPub collection page
type ActivityPubError ¶
type ActivityPubError struct {
Type string `json:"type"`
Message string `json:"message"`
ActorID string `json:"actor,omitempty"`
ObjectID string `json:"object,omitempty"`
Temporary bool `json:"temporary"`
RetryAfter time.Duration `json:"retry_after,omitempty"`
}
ActivityPubError represents an ActivityPub-specific error
func MapActivityPubError ¶
func MapActivityPubError(err error, actorID, objectID string) ActivityPubError
MapActivityPubError maps common federation errors to ActivityPub error types
func NewActivityPubError ¶
func NewActivityPubError(errorType, message string, temporary bool) ActivityPubError
NewActivityPubError creates a new ActivityPub error
func (ActivityPubError) Error ¶
func (e ActivityPubError) Error() string
Error implements the error interface
func (ActivityPubError) IsTemporary ¶
func (e ActivityPubError) IsTemporary() bool
IsTemporary returns whether the error is temporary and should be retried
type ActivityPubObject ¶
type ActivityPubObject interface {
GetID() string
GetType() string
GetActor() string
GetObject() interface{}
GetPublished() time.Time
}
ActivityPubObject represents a generic ActivityPub object interface
type ActivityPubOperation ¶
type ActivityPubOperation interface {
Validate(ctx context.Context) error
Execute(ctx context.Context) error
RecordMetrics(ctx context.Context, outcome string, attempts int) error
}
ActivityPubOperation defines the interface for ActivityPub operations
type ActivityPubSanitizer ¶
type ActivityPubSanitizer struct {
// contains filtered or unexported fields
}
ActivityPubSanitizer provides HTML sanitization for ActivityPub content
func NewActivityPubSanitizer ¶
func NewActivityPubSanitizer() *ActivityPubSanitizer
NewActivityPubSanitizer creates a new sanitizer configured for ActivityPub content
func (*ActivityPubSanitizer) SanitizeActivityPubObject ¶
func (s *ActivityPubSanitizer) SanitizeActivityPubObject(obj map[string]any)
SanitizeActivityPubObject sanitizes all string fields in an ActivityPub object
func (*ActivityPubSanitizer) SanitizeHTML ¶
func (s *ActivityPubSanitizer) SanitizeHTML(content string) string
SanitizeHTML sanitizes HTML content for safe display
type ActivityPubValidationRules ¶
type ActivityPubValidationRules struct {
RequireHTTPS bool
AllowedDomains []string
BlockedDomains []string
MaxObjectSize int64
RequireSignature bool
ValidActivityTypes []string
}
ActivityPubValidationRules defines validation rules for ActivityPub objects
type ActorNotFoundError ¶
type ActorNotFoundError struct {
Username string
}
ActorNotFoundError indicates an actor was not found
func (ActorNotFoundError) Error ¶
func (e ActorNotFoundError) Error() string
type AdminPaginationParams ¶
type AdminPaginationParams struct {
PaginationParams
Origin string `json:"origin"` // local, remote
Status string `json:"status"` // active, pending, disabled, etc.
Permissions string `json:"permissions"` // Filter by permission level
IP string `json:"ip"` // Filter by IP address
Email string `json:"email"` // Filter by email pattern
Username string `json:"username"` // Filter by username pattern
ByDomain string `json:"by_domain"` // Filter by domain
InviteFilter bool `json:"invite_filter"` // Show only invited accounts
}
AdminPaginationParams extends PaginationParams for admin-specific needs
func GetAdminPaginationParams ¶
func GetAdminPaginationParams(ctx *apptheory.Context) AdminPaginationParams
GetAdminPaginationParams extracts admin-specific pagination parameters.
type AlreadyFollowingError ¶
AlreadyFollowingError indicates already following the user
func (AlreadyFollowingError) Error ¶
func (e AlreadyFollowingError) Error() string
type AppError ¶
type AppError struct {
Code string // Internal error code for logging/monitoring
UserMessage string // Safe message for users
InternalError error // Detailed error for logging
StatusCode int // HTTP status code
}
AppError represents a safe application error that separates internal details from user messages
func ErrBadRequest ¶
ErrBadRequest creates a bad request error
func ErrForbidden ¶
ErrForbidden creates a forbidden error
func ErrInternal ¶
ErrInternal creates an internal server error
func ErrUnauthorized ¶
ErrUnauthorized creates an unauthorized error
func ErrValidation ¶
ErrValidation creates a validation error
type AuthContext ¶
AuthContext holds authentication state
type AuthenticationError ¶
type AuthenticationError struct {
Message string
}
AuthenticationError indicates authentication failed
func (AuthenticationError) Error ¶
func (e AuthenticationError) Error() string
type AuthenticationResult ¶
type AuthenticationResult struct {
Context *AuthContext
Error error
ErrorCode int
}
AuthenticationResult holds the result of authentication validation
func ExtractAndValidateAuth ¶
func ExtractAndValidateAuth(ctx *apptheory.Context, requiredScope string, oauthService OAuthServiceInterface) *AuthenticationResult
ExtractAndValidateAuth performs the complete authentication flow This consolidates the most common pattern found across 80+ files:
- Extract Authorization header (with fallback patterns)
- Extract bearer token
- Validate JWT token
- Check required scopes
func ExtractAndValidateAuthWithMultipleScopes ¶
func ExtractAndValidateAuthWithMultipleScopes(ctx *apptheory.Context, allowedScopes []string, oauthService OAuthServiceInterface) *AuthenticationResult
ExtractAndValidateAuthWithMultipleScopes validates authentication with multiple allowed scopes This handles the pattern where either of several scopes is acceptable
func ExtractOptionalAuth ¶
func ExtractOptionalAuth(ctx *apptheory.Context, oauthService OAuthServiceInterface) *AuthenticationResult
ExtractOptionalAuth performs optional authentication (for public endpoints that benefit from auth) This consolidates the pattern where auth is optional but used if present
type AuthorizationError ¶
AuthorizationError indicates authorization failed
func (AuthorizationError) Error ¶
func (e AuthorizationError) Error() string
type BaseTransformer ¶
type BaseTransformer[TSource, TTarget any] struct { // contains filtered or unexported fields }
BaseTransformer provides a concrete implementation of the Transformer interface
func NewBaseTransformer ¶
func NewBaseTransformer[TSource, TTarget any]( name string, transformFn func(context.Context, TSource) (TTarget, error), logger *zap.Logger, ) *BaseTransformer[TSource, TTarget]
NewBaseTransformer creates a new BaseTransformer with the given function
func (*BaseTransformer[TSource, TTarget]) Transform ¶
func (bt *BaseTransformer[TSource, TTarget]) Transform(ctx context.Context, source TSource) (TTarget, error)
Transform executes the transformation function
func (*BaseTransformer[TSource, TTarget]) WithCache ¶
func (bt *BaseTransformer[TSource, TTarget]) WithCache( ttl time.Duration, maxSize int, keyFunc func(TSource) string, ) *BaseTransformer[TSource, TTarget]
WithCache enables caching for this transformer
type BatchTransformer ¶
type BatchTransformer[TSource, TTarget any] interface { Transformer[TSource, TTarget] TransformBatch(ctx context.Context, sources []TSource) ([]TTarget, error) }
BatchTransformer extends Transformer to handle batch operations efficiently
type BatchTransformerImpl ¶
type BatchTransformerImpl[TSource, TTarget any] struct { *BaseTransformer[TSource, TTarget] // contains filtered or unexported fields }
BatchTransformerImpl provides efficient batch processing capabilities
func NewBatchTransformer ¶
func NewBatchTransformer[TSource, TTarget any]( name string, transformFn func(context.Context, TSource) (TTarget, error), batchFn func(context.Context, []TSource) ([]TTarget, error), logger *zap.Logger, ) *BatchTransformerImpl[TSource, TTarget]
NewBatchTransformer creates a new batch transformer
func (*BatchTransformerImpl[TSource, TTarget]) TransformBatch ¶
func (bt *BatchTransformerImpl[TSource, TTarget]) TransformBatch( ctx context.Context, sources []TSource, ) ([]TTarget, error)
TransformBatch processes multiple items efficiently
type BusinessLogicContext ¶
type BusinessLogicContext struct {
UserID string
Username string
DomainName string
Logger *zap.Logger
EventEmitter EventEmitter
}
BusinessLogicContext provides context for business operations
type BusinessLogicService ¶
type BusinessLogicService struct {
// contains filtered or unexported fields
}
BusinessLogicService provides centralized business logic operations
func NewBusinessLogicService ¶
func NewBusinessLogicService(logger *zap.Logger, eventEmitter EventEmitter, domainName string) *BusinessLogicService
NewBusinessLogicService creates a new business logic service
func (*BusinessLogicService) ExecuteBusinessOperation ¶
func (s *BusinessLogicService) ExecuteBusinessOperation(ctx context.Context, operation BusinessOperation) error
ExecuteBusinessOperation executes a business operation with standard patterns
type BusinessOperation ¶
type BusinessOperation interface {
Validate(ctx context.Context) error
Execute(ctx context.Context) error
GetEvents(ctx context.Context) []*StreamingEvent
RecordMetrics(ctx context.Context) error
}
BusinessOperation defines the interface for business operations
type BusinessRuleValidator ¶
BusinessRuleValidator defines the interface for business rule validation
type CacheEntry ¶
CacheEntry represents a cached transformation result
type CommandValidationResult ¶
CommandValidationResult represents the result of command validation
func ValidateCommand ¶
func ValidateCommand(_ context.Context, cmd interface{}, rules ValidationRules) *CommandValidationResult
ValidateCommand performs standard validation on command structures
type ConditionalTransformer ¶
type ConditionalTransformer[TSource, TTarget any] interface { Transformer[TSource, TTarget] CanTransform(ctx context.Context, source TSource) bool }
ConditionalTransformer allows transformation based on runtime conditions
type ConditionalTransformerImpl ¶
type ConditionalTransformerImpl[TSource, TTarget any] struct { *BaseTransformer[TSource, TTarget] // contains filtered or unexported fields }
ConditionalTransformerImpl implements conditional transformation logic
func NewConditionalTransformer ¶
func NewConditionalTransformer[TSource, TTarget any]( name string, transformFn func(context.Context, TSource) (TTarget, error), conditionFn func(context.Context, TSource) bool, logger *zap.Logger, ) *ConditionalTransformerImpl[TSource, TTarget]
NewConditionalTransformer creates a transformer that only runs when condition is met
func (*ConditionalTransformerImpl[TSource, TTarget]) CanTransform ¶
func (ct *ConditionalTransformerImpl[TSource, TTarget]) CanTransform( ctx context.Context, source TSource, ) bool
CanTransform checks if the transformation should be applied
type ConflictError ¶
ConflictError indicates a resource conflict
func (ConflictError) Error ¶
func (e ConflictError) Error() string
type ContentValidationRules ¶
type ContentValidationRules struct {
MaxLength int
MinLength int
AllowedTypes []string
RequiredFields []string
ForbiddenWords []string
}
ContentValidationRules defines rules for content validation
type ContextKey ¶
type ContextKey string
ContextKey is the type for context keys
const ( // ContextKeyClaims is the context key for JWT claims ContextKeyClaims ContextKey = "claims" )
type CookieConfig ¶
type CookieConfig struct {
Domain string // Leave empty to let browser handle
Path string
Secure bool // HTTPS only
HTTPOnly bool // No JavaScript access
SameSite http.SameSite
}
CookieConfig holds configuration for secure cookies
type DeliveryTarget ¶
DeliveryTarget represents a federation delivery target
func CalculateDeliveryTargets ¶
func CalculateDeliveryTargets(_ context.Context, audience ActivityPubAudience, actorResolver func(string) (ActivityPubActor, error)) ([]DeliveryTarget, error)
CalculateDeliveryTargets calculates delivery targets for an ActivityPub activity
type EntityState ¶
type EntityState string
EntityState represents entity states
const ( StateDraft EntityState = "draft" // StateDraft represents entities in draft state StatePending EntityState = "pending" // StatePending represents entities awaiting approval StateActive EntityState = "active" // StateActive represents active entities StateInactive EntityState = "inactive" // StateInactive represents temporarily disabled entities StateSuspended EntityState = "suspended" // StateSuspended represents suspended entities StateDeleted EntityState = "deleted" // StateDeleted represents deleted entities )
Entity state constants for state machine transitions
type ErrorMiddlewareConfig ¶
type ErrorMiddlewareConfig struct {
Logger *zap.Logger
ServiceName string
EnableStackTrace bool
EnablePanicRecovery bool
EnableErrorMetrics bool
MaxErrorLogLength int
}
ErrorMiddlewareConfig holds configuration for error handling middleware
func DefaultErrorConfig ¶
func DefaultErrorConfig(serviceName string, logger *zap.Logger) ErrorMiddlewareConfig
DefaultErrorConfig returns a default error middleware configuration
type ErrorResponse ¶
type ErrorResponse struct {
Error string `json:"error"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
ErrorResponse represents a standard error response
type EventEmitter ¶
type EventEmitter interface {
EmitEvents(ctx context.Context, events []*StreamingEvent) error
}
EventEmitter defines the interface for event emission
type ExpiredTokenError ¶
type ExpiredTokenError struct {
Token string
}
ExpiredTokenError indicates a token has expired
func (ExpiredTokenError) Error ¶
func (e ExpiredTokenError) Error() string
type FederationConfig ¶
type FederationConfig struct {
Domain string
PrivateKeyPath string
PublicKeyPath string
UserAgent string
MaxRetries int
RetryDelay time.Duration
RequestTimeout time.Duration
}
FederationConfig configures federation behavior
type FederationDeliveryConfig ¶
type FederationDeliveryConfig struct {
MaxRetries int
RetryDelay time.Duration
RequestTimeout time.Duration
MaxConcurrency int
SignRequests bool
}
FederationDeliveryConfig configures federation delivery behavior
type FederationError ¶
FederationError indicates a federation operation failed
func (FederationError) Error ¶
func (e FederationError) Error() string
func (FederationError) Unwrap ¶
func (e FederationError) Unwrap() error
type FilterAction ¶
type FilterAction string
FilterAction represents what action to take when filter matches
const ( FilterActionWarn FilterAction = "warn" FilterActionHide FilterAction = "hide" )
Actions that can be taken when a content filter matches
type FilterContext ¶
type FilterContext string
FilterContext represents where a filter applies
const ( FilterContextHome FilterContext = "home" FilterContextNotifications FilterContext = "notifications" FilterContextPublic FilterContext = "public" FilterContextThread FilterContext = "thread" FilterContextAccount FilterContext = "account" )
Mastodon filter contexts define where content filters should be applied
type FilterParams ¶
type FilterParams struct {
Phrase string `json:"phrase"`
Context []string `json:"context"`
ExpiresIn int `json:"expires_in"`
Irreversible bool `json:"irreversible"`
WholeWord bool `json:"whole_word"`
}
FilterParams extracts filter-specific parameters
type HTTPSignatureInfo ¶
HTTPSignatureInfo represents HTTP signature information
func ParseHTTPSignature ¶
func ParseHTTPSignature(signatureHeader string) (*HTTPSignatureInfo, error)
ParseHTTPSignature parses an HTTP signature header
type HealthCheckResponse ¶
type HealthCheckResponse struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
Version string `json:"version,omitempty"`
Checks map[string]interface{} `json:"checks,omitempty"`
}
HealthCheckResponse represents a health check response
type IDGenerator ¶
type IDGenerator struct {
// contains filtered or unexported fields
}
IDGenerator provides production-ready ID generation with multiple formats
func NewIDGenerator ¶
func NewIDGenerator(logger *zap.Logger) *IDGenerator
NewIDGenerator creates a new ID generator with cryptographically secure entropy
func (*IDGenerator) ExtractTimestamp ¶
func (g *IDGenerator) ExtractTimestamp(id string) (time.Time, error)
ExtractTimestamp extracts the timestamp from a ULID
func (*IDGenerator) GenerateActivityID ¶
func (g *IDGenerator) GenerateActivityID(domain string) string
GenerateActivityID generates an activity ID for ActivityPub activities
func (*IDGenerator) GenerateActivityPubID ¶
func (g *IDGenerator) GenerateActivityPubID(domain, objectType string) string
GenerateActivityPubID generates an ActivityPub-compatible ID with domain context
func (*IDGenerator) GenerateActorID ¶
func (g *IDGenerator) GenerateActorID(domain, username string) string
GenerateActorID generates an actor ID with proper ActivityPub format
func (*IDGenerator) GenerateAuditLogID ¶
func (g *IDGenerator) GenerateAuditLogID() string
GenerateAuditLogID generates an audit log ID
func (*IDGenerator) GenerateCommunityNoteID ¶
func (g *IDGenerator) GenerateCommunityNoteID() string
GenerateCommunityNoteID generates a community note ID
func (*IDGenerator) GenerateConversationID ¶
func (g *IDGenerator) GenerateConversationID() string
GenerateConversationID generates a conversation ID
func (*IDGenerator) GenerateExportID ¶
func (g *IDGenerator) GenerateExportID() string
GenerateExportID generates an export ID
func (*IDGenerator) GenerateImportID ¶
func (g *IDGenerator) GenerateImportID() string
GenerateImportID generates an import ID
func (*IDGenerator) GenerateJobID ¶
func (g *IDGenerator) GenerateJobID() string
GenerateJobID generates a job ID for background jobs
func (*IDGenerator) GenerateMediaID ¶
func (g *IDGenerator) GenerateMediaID() string
GenerateMediaID generates a media ID with proper prefix
func (*IDGenerator) GenerateMessageID ¶
func (g *IDGenerator) GenerateMessageID() string
GenerateMessageID generates a message ID
func (*IDGenerator) GenerateNoteID ¶
func (g *IDGenerator) GenerateNoteID() string
GenerateNoteID generates a note ID with proper prefix
func (*IDGenerator) GenerateObjectID ¶
func (g *IDGenerator) GenerateObjectID(domain string) string
GenerateObjectID generates an object ID for ActivityPub objects
func (*IDGenerator) GenerateOperationID ¶
func (g *IDGenerator) GenerateOperationID() string
GenerateOperationID generates an operation ID for bulk operations
func (*IDGenerator) GenerateReportID ¶
func (g *IDGenerator) GenerateReportID() string
GenerateReportID generates a report ID for moderation reports
func (*IDGenerator) GenerateRequestID ¶
func (g *IDGenerator) GenerateRequestID() string
GenerateRequestID generates a request ID for tracing
func (*IDGenerator) GenerateSessionID ¶
func (g *IDGenerator) GenerateSessionID() string
GenerateSessionID generates a session ID for user sessions
func (*IDGenerator) GenerateStatusID ¶
func (g *IDGenerator) GenerateStatusID() string
GenerateStatusID generates a status ID with time-based prefix for better sorting
func (*IDGenerator) GenerateStreamingSessionID ¶
func (g *IDGenerator) GenerateStreamingSessionID() string
GenerateStreamingSessionID generates a streaming session ID
func (*IDGenerator) GenerateULID ¶
func (g *IDGenerator) GenerateULID() string
GenerateULID generates a ULID (Universally Unique Lexicographically Sortable Identifier) ULIDs are preferred for database performance as they are: - Lexicographically sortable - 128-bit compatible with UUID - More compact string representation - Better for database indexing performance
func (*IDGenerator) GenerateVouchID ¶
func (g *IDGenerator) GenerateVouchID() string
GenerateVouchID generates a vouch ID for reputation system
func (*IDGenerator) IsOlderThan ¶
func (g *IDGenerator) IsOlderThan(id string, duration time.Duration) bool
IsOlderThan checks if a ULID-based ID is older than the given duration
func (*IDGenerator) ShortID ¶
func (g *IDGenerator) ShortID() string
ShortID generates a shorter ID for cases where full ULID is too long Uses base32 encoding of 8 bytes for readability while maintaining uniqueness
func (*IDGenerator) ValidateULID ¶
func (g *IDGenerator) ValidateULID(id string) bool
ValidateULID validates if a string is a valid ULID
type InvalidPasswordError ¶
type InvalidPasswordError struct{}
InvalidPasswordError indicates password validation failed
func (InvalidPasswordError) Error ¶
func (e InvalidPasswordError) Error() string
type InvalidTokenError ¶
type InvalidTokenError struct {
Token string
}
InvalidTokenError indicates a token is invalid
func (InvalidTokenError) Error ¶
func (e InvalidTokenError) Error() string
type LambdaConfig ¶
type LambdaConfig struct {
// Basic configuration
ServiceName string
LambdaType LambdaType
Version string
// Feature flags
EnableMetrics bool
EnableTracing bool
EnableHealthCheck bool
EnableCostTracking bool
// Timeout and retry settings
RequestTimeout time.Duration
RetryMaxAttempts int
// Custom AWS service requirements (overrides defaults)
CustomServiceConfig *awsInit.ServiceConfig
}
LambdaConfig defines Lambda initialization configuration
type LambdaContext ¶
type LambdaContext struct {
// Configuration
Config *config.Config
Logger *zap.Logger
StartTime time.Time
// AWS Services
AWSServices *awsInit.AWSServices
// Storage (interfaces to avoid import cycles)
DynamoDB interface{} // *tabletheory.Client
Repos interface{} // core.RepositoryStorage
// Observability (interfaces to avoid import cycles)
EMFMetrics interface{} // *observability.EMFMetrics
HealthChecker interface{} // *observability.HealthChecker
TracingManager interface{} // *observability.TracingManager
MetricsCollector interface{} // *observability.MetricsCollector
LatencyAggregator interface{} // *observability.LatencyAggregator
LatencyAlerter interface{} // *observability.LatencyAlerter
AlertManager interface{} // *monitoring.AlertManager
// Service specific
ServiceName string
LambdaType LambdaType
// Service utilities (interfaces to avoid import cycles)
AuthService interface{} // *auth.AuthService
AuthMiddleware interface{} // *auth.Middleware
StreamQueue interface{} // *streaming.StreamQueue
SignatureService interface{} // *federation.SignatureService
DeliveryService interface{} // *federation.DeliveryService
CostCalculator interface{} // *federation.CostCalculator
RateLimiter interface{} // *auth.RateLimiter
}
LambdaContext contains initialized Lambda dependencies
func InitializeLambda ¶
func InitializeLambda(lambdaConfig LambdaConfig) (*LambdaContext, error)
InitializeLambda initializes a Lambda function with standard dependencies
func MustInitializeLambda ¶
func MustInitializeLambda(lambdaConfig LambdaConfig) *LambdaContext
MustInitializeLambda is like InitializeLambda but panics on error
func (*LambdaContext) CreateLambdaHandler ¶
func (lambdaCtx *LambdaContext) CreateLambdaHandler(handler func(ctx context.Context, event interface{}) (interface{}, error)) func(ctx context.Context, event interface{}) (interface{}, error)
CreateLambdaHandler creates a Lambda handler wrapper with basic logging
func (*LambdaContext) CreateStandardizedLambdaHandler ¶
func (lambdaCtx *LambdaContext) CreateStandardizedLambdaHandler(handler func(ctx context.Context, event interface{}) (interface{}, error)) func(ctx context.Context, event interface{}) (interface{}, error)
CreateStandardizedLambdaHandler creates a Lambda handler with standardized observability and error handling
func (*LambdaContext) FlushObservability ¶
func (lambdaCtx *LambdaContext) FlushObservability()
FlushObservability flushes all observability data before Lambda termination
func (*LambdaContext) FlushObservabilityServices ¶
func (lambdaCtx *LambdaContext) FlushObservabilityServices()
FlushObservabilityServices flushes all observability data before Lambda termination
func (*LambdaContext) InitializeObservabilityServices ¶
func (lambdaCtx *LambdaContext) InitializeObservabilityServices(options LambdaInitOptions) error
InitializeObservabilityServices initializes observability services based on options
func (*LambdaContext) InitializeServiceSpecificDependencies ¶
func (lambdaCtx *LambdaContext) InitializeServiceSpecificDependencies(options LambdaInitOptions) error
InitializeServiceSpecificDependencies initializes service-specific dependencies
func (*LambdaContext) InitializeStorageServices ¶
func (lambdaCtx *LambdaContext) InitializeStorageServices(options LambdaInitOptions) error
InitializeStorageServices initializes DynamORM and repository storage
func (*LambdaContext) InitializeWithDefaults ¶
func (lambdaCtx *LambdaContext) InitializeWithDefaults() error
InitializeWithDefaults initializes Lambda with default options for the Lambda type
func (*LambdaContext) InitializeWithOptions ¶
func (lambdaCtx *LambdaContext) InitializeWithOptions(options LambdaInitOptions) error
InitializeWithOptions initializes Lambda with custom options
type LambdaInitOptions ¶
type LambdaInitOptions struct {
// Storage options
InitializeStorage bool
InitializeRepositories bool
TableName string
// Observability options
InitializeEMFMetrics bool
InitializeHealthChecker bool
InitializeTracingManager bool
InitializeMetricsCollector bool
InitializeLatencyTracking bool
InitializeAlerting bool
// Service-specific options
InitializeAuthService bool
InitializeFederationServices bool
InitializeStreamingServices bool
// Performance options
OptimizeForColdStart bool
EnableServiceCaching bool
}
LambdaInitOptions provides additional initialization options
func DefaultLambdaInitOptions ¶
func DefaultLambdaInitOptions(lambdaType LambdaType) LambdaInitOptions
DefaultLambdaInitOptions returns sensible defaults for different Lambda types
type LambdaResourceMonitor ¶
type LambdaResourceMonitor struct {
// contains filtered or unexported fields
}
LambdaResourceMonitor tracks resource usage in Lambda environment
func GetLambdaMonitor ¶
func GetLambdaMonitor() *LambdaResourceMonitor
GetLambdaMonitor returns the global Lambda resource monitor
func NewLambdaResourceMonitor ¶
func NewLambdaResourceMonitor() *LambdaResourceMonitor
NewLambdaResourceMonitor creates a monitor based on Lambda limits
func (*LambdaResourceMonitor) CheckResources ¶
func (m *LambdaResourceMonitor) CheckResources(operation string) error
CheckResources verifies we're within Lambda limits
func (*LambdaResourceMonitor) GetCheckpoints ¶
func (m *LambdaResourceMonitor) GetCheckpoints() []ResourceCheckpoint
GetCheckpoints returns all recorded checkpoints
func (*LambdaResourceMonitor) GetElapsedTime ¶
func (m *LambdaResourceMonitor) GetElapsedTime() time.Duration
GetElapsedTime returns time elapsed since monitor creation
func (*LambdaResourceMonitor) GetMemoryUsageMB ¶
func (m *LambdaResourceMonitor) GetMemoryUsageMB() uint64
GetMemoryUsageMB returns current memory usage in MB
func (*LambdaResourceMonitor) GetResourceUtilization ¶
func (m *LambdaResourceMonitor) GetResourceUtilization() (memoryPercent float64, timePercent float64)
GetResourceUtilization returns current resource utilization as percentages
func (*LambdaResourceMonitor) WrapWithResourceCheck ¶
func (m *LambdaResourceMonitor) WrapWithResourceCheck(operation string, fn func() error) error
WrapWithResourceCheck wraps an operation with resource monitoring
type LambdaRuntimeInfo ¶
type LambdaRuntimeInfo struct{}
LambdaRuntimeInfo provides access to AWS Lambda runtime environment variables
func NewLambdaRuntime ¶
func NewLambdaRuntime() *LambdaRuntimeInfo
NewLambdaRuntime creates a new LambdaRuntimeInfo instance
func (*LambdaRuntimeInfo) GetFunctionName ¶
func (l *LambdaRuntimeInfo) GetFunctionName() string
GetFunctionName returns the AWS Lambda function name from AWS_LAMBDA_FUNCTION_NAME
func (*LambdaRuntimeInfo) GetFunctionVersion ¶
func (l *LambdaRuntimeInfo) GetFunctionVersion() string
GetFunctionVersion returns the AWS Lambda function version from AWS_LAMBDA_FUNCTION_VERSION
func (*LambdaRuntimeInfo) GetInitializationType ¶
func (l *LambdaRuntimeInfo) GetInitializationType() string
GetInitializationType returns the AWS Lambda initialization type from AWS_LAMBDA_INITIALIZATION_TYPE
func (*LambdaRuntimeInfo) GetLogGroupName ¶
func (l *LambdaRuntimeInfo) GetLogGroupName() string
GetLogGroupName returns the AWS Lambda log group name from AWS_LAMBDA_LOG_GROUP_NAME
func (*LambdaRuntimeInfo) GetLogStreamName ¶
func (l *LambdaRuntimeInfo) GetLogStreamName() string
GetLogStreamName returns the AWS Lambda log stream name from AWS_LAMBDA_LOG_STREAM_NAME
func (*LambdaRuntimeInfo) GetMemorySize ¶
func (l *LambdaRuntimeInfo) GetMemorySize() string
GetMemorySize returns the AWS Lambda function memory size from AWS_LAMBDA_FUNCTION_MEMORY_SIZE
func (*LambdaRuntimeInfo) GetMemorySizeInt ¶
func (l *LambdaRuntimeInfo) GetMemorySizeInt() (int, error)
GetMemorySizeInt returns the AWS Lambda function memory size as an integer
func (*LambdaRuntimeInfo) GetXRayTraceID ¶
func (l *LambdaRuntimeInfo) GetXRayTraceID() string
GetXRayTraceID returns the X-Ray trace ID from _X_AMZN_TRACE_ID
func (*LambdaRuntimeInfo) IsColdStart ¶
func (l *LambdaRuntimeInfo) IsColdStart() bool
IsColdStart returns true if this is a cold start (initialization type is on-demand)
func (*LambdaRuntimeInfo) IsRunningInLambda ¶
func (l *LambdaRuntimeInfo) IsRunningInLambda() bool
IsRunningInLambda returns true if running in AWS Lambda environment
func (*LambdaRuntimeInfo) IsXRayEnabled ¶
func (l *LambdaRuntimeInfo) IsXRayEnabled() bool
IsXRayEnabled returns true if X-Ray tracing is enabled
type LambdaType ¶
type LambdaType string
LambdaType defines the type of Lambda function for initialization
const ( // LambdaTypeAPI represents the API Lambda function type LambdaTypeAPI LambdaType = "api" // LambdaTypeProcessor represents the processor Lambda function type LambdaTypeProcessor LambdaType = "processor" // LambdaTypeMedia represents the media Lambda function type LambdaTypeMedia LambdaType = "media" // LambdaTypeFederation represents the federation Lambda function type LambdaTypeFederation LambdaType = "federation" // LambdaTypeAI represents the AI Lambda function type LambdaTypeAI LambdaType = "ai" // LambdaTypeBasic represents the basic Lambda function type LambdaTypeBasic LambdaType = "basic" )
type ListNotFoundError ¶
type ListNotFoundError struct {
ID string
}
ListNotFoundError indicates a list was not found
func (ListNotFoundError) Error ¶
func (e ListNotFoundError) Error() string
type MastodonAPIConfig ¶
type MastodonAPIConfig struct {
InstanceName string
Domain string
MaxStatusLength int
MaxBioLength int
MaxDisplayName int
MaxPollOptions int
MaxPollExpiry time.Duration
MediaUploadLimit int64
VideoUploadLimit int64
DefaultPagination int
MaxPagination int
}
MastodonAPIConfig configures Mastodon API behavior
func DefaultMastodonConfig ¶
func DefaultMastodonConfig() *MastodonAPIConfig
DefaultMastodonConfig returns sensible defaults for Mastodon API
type MastodonAPIError ¶
type MastodonAPIError struct {
Type string `json:"error"`
Description string `json:"error_description,omitempty"`
StatusCode int `json:"-"`
}
MastodonAPIError represents a Mastodon API-specific error
func NewMastodonAPIError ¶
func NewMastodonAPIError(errorType, description string, statusCode int) MastodonAPIError
NewMastodonAPIError creates a new Mastodon API error
func (MastodonAPIError) Error ¶
func (e MastodonAPIError) Error() string
Error implements the error interface
type MastodonAccount ¶
type MastodonAccount struct {
ID string `json:"id"`
Username string `json:"username"`
Acct string `json:"acct"`
DisplayName string `json:"display_name"`
Note string `json:"note"`
URL string `json:"url"`
Avatar string `json:"avatar"`
Header string `json:"header"`
Locked bool `json:"locked"`
CreatedAt string `json:"created_at"`
FollowersCount int `json:"followers_count"`
FollowingCount int `json:"following_count"`
StatusesCount int `json:"statuses_count"`
Bot bool `json:"bot"`
Discoverable bool `json:"discoverable"`
}
MastodonAccount represents a basic Mastodon account structure for responses
type MastodonBusinessLogic ¶
type MastodonBusinessLogic struct {
// contains filtered or unexported fields
}
MastodonBusinessLogic provides centralized Mastodon API business operations
func NewMastodonBusinessLogic ¶
func NewMastodonBusinessLogic(config *MastodonAPIConfig, logger *zap.Logger) *MastodonBusinessLogic
NewMastodonBusinessLogic creates a new Mastodon business logic service
func (*MastodonBusinessLogic) ExecuteMastodonAPIOperation ¶
func (m *MastodonBusinessLogic) ExecuteMastodonAPIOperation(ctx context.Context, operation MastodonOperation) (interface{}, error)
ExecuteMastodonAPIOperation executes a Mastodon API operation with standard validation and error handling
func (*MastodonBusinessLogic) ValidateBio ¶
func (m *MastodonBusinessLogic) ValidateBio(bio string) error
ValidateBio validates account bio/note
func (*MastodonBusinessLogic) ValidateDisplayName ¶
func (m *MastodonBusinessLogic) ValidateDisplayName(displayName string) error
ValidateDisplayName validates account display name
func (*MastodonBusinessLogic) ValidateMastodonPaginationParams ¶
func (m *MastodonBusinessLogic) ValidateMastodonPaginationParams(params MastodonPaginationParams) MastodonPaginationParams
ValidateMastodonPaginationParams validates Mastodon pagination parameters
func (*MastodonBusinessLogic) ValidateMediaUpload ¶
func (m *MastodonBusinessLogic) ValidateMediaUpload(data []byte, mimeType string, mediaType MediaType) error
ValidateMediaUpload validates media upload according to Mastodon limits
func (*MastodonBusinessLogic) ValidatePollOptions ¶
func (m *MastodonBusinessLogic) ValidatePollOptions(options []PollOption, expiresIn int) error
ValidatePollOptions validates poll creation
func (*MastodonBusinessLogic) ValidateRateLimit ¶
func (m *MastodonBusinessLogic) ValidateRateLimit(_ context.Context, _, _ string, _ RateLimitConfig) error
ValidateRateLimit checks if an action is within rate limits
func (*MastodonBusinessLogic) ValidateStatusContent ¶
func (m *MastodonBusinessLogic) ValidateStatusContent(content string, mediaCount int, pollOptions int) error
ValidateStatusContent validates status content according to Mastodon rules
type MastodonOperation ¶
type MastodonOperation interface {
Validate(ctx context.Context) error
Execute(ctx context.Context) error
GetResponse(ctx context.Context) interface{}
RecordMetrics(ctx context.Context) error
}
MastodonOperation defines the interface for Mastodon API operations
type MastodonPaginationParams ¶
type MastodonPaginationParams struct {
Limit int `json:"limit,omitempty"`
MaxID string `json:"max_id,omitempty"`
MinID string `json:"min_id,omitempty"`
SinceID string `json:"since_id,omitempty"`
Cursor string `json:"cursor,omitempty"` // For some endpoints
}
MastodonPaginationParams represents standard Mastodon API pagination
type MastodonStatus ¶
type MastodonStatus struct {
ID string `json:"id"`
CreatedAt string `json:"created_at"`
InReplyToID *string `json:"in_reply_to_id"`
InReplyToAccountID *string `json:"in_reply_to_account_id"`
Sensitive bool `json:"sensitive"`
SpoilerText string `json:"spoiler_text"`
Visibility string `json:"visibility"`
Language *string `json:"language"`
URI string `json:"uri"`
URL *string `json:"url"`
RepliesCount int `json:"replies_count"`
ReblogsCount int `json:"reblogs_count"`
FavouritesCount int `json:"favourites_count"`
Content string `json:"content"`
Reblog *MastodonStatus `json:"reblog"`
Account MastodonAccount `json:"account"`
Reblogged bool `json:"reblogged"`
Favourited bool `json:"favourited"`
Bookmarked bool `json:"bookmarked"`
Pinned bool `json:"pinned"`
}
MastodonStatus represents a basic Mastodon status structure for responses
type MediaType ¶
type MediaType string
MediaType represents different media types supported by Mastodon MediaType represents the type of media attachment in Mastodon These values correspond to the standard Mastodon media attachment types used for categorizing uploaded media files
type NotificationType ¶
type NotificationType string
NotificationType represents different Mastodon notification types
const ( NotificationMention NotificationType = "mention" NotificationStatus NotificationType = "status" NotificationReblog NotificationType = "reblog" NotificationFollow NotificationType = "follow" NotificationFollowRequest NotificationType = "follow_request" NotificationFavourite NotificationType = "favourite" NotificationPoll NotificationType = "poll" NotificationUpdate NotificationType = "update" NotificationAdminSignUp NotificationType = "admin.sign_up" NotificationAdminReport NotificationType = "admin.report" )
Mastodon notification types as defined in the Mastodon API specification
type OAuthServiceInterface ¶
OAuthServiceInterface defines the interface for OAuth validation This avoids import cycles while providing the needed validation functionality
type PaginatedResponse ¶
type PaginatedResponse struct {
Data interface{} `json:"data"`
Pagination *Pagination `json:"pagination,omitempty"`
}
PaginatedResponse wraps data with pagination metadata
type Pagination ¶
type Pagination struct {
Limit int `json:"limit"`
Offset int `json:"offset"`
Page int `json:"page,omitempty"`
TotalCount int `json:"total_count,omitempty"`
HasNext bool `json:"has_next"`
HasPrev bool `json:"has_prev"`
NextCursor string `json:"next_cursor,omitempty"`
PrevCursor string `json:"prev_cursor,omitempty"`
}
Pagination contains pagination metadata
type PaginationLinks ¶
type PaginationLinks struct {
Next string `json:"next,omitempty"`
Prev string `json:"prev,omitempty"`
}
PaginationLinks holds Link header data for Mastodon API compatibility
type PaginationParams ¶
type PaginationParams struct {
Limit int `json:"limit"`
Offset int `json:"offset"`
Page int `json:"page"`
MaxID string `json:"max_id"`
MinID string `json:"min_id"`
SinceID string `json:"since_id"`
Cursor string `json:"cursor"`
}
PaginationParams represents standardized pagination parameters used across the application
func GetPaginationParams ¶
func GetPaginationParams(ctx *apptheory.Context) PaginationParams
GetPaginationParams extracts and validates pagination parameters from an AppTheory context.
func GetPaginationParamsFromRequest ¶
func GetPaginationParamsFromRequest(queryParams map[string][]string) PaginationParams
GetPaginationParamsFromRequest extracts pagination from standard HTTP request This provides compatibility with non-Lift request handling
type PaginationResult ¶
type PaginationResult struct {
Items interface{} `json:"items"`
TotalCount int `json:"total_count,omitempty"`
HasNext bool `json:"has_next,omitempty"`
HasPrev bool `json:"has_prev,omitempty"`
NextCursor string `json:"next_cursor,omitempty"`
PrevCursor string `json:"prev_cursor,omitempty"`
}
PaginationResult holds pagination response data
type PollOption ¶
PollOption represents a poll option
type QuotaValidator ¶
QuotaValidator validates operations against quotas
func (*QuotaValidator) ValidateQuota ¶
func (q *QuotaValidator) ValidateQuota(_ context.Context, actorID, actionType string) error
ValidateQuota checks if action is within quota limits
type RateLimitConfig ¶
type RateLimitConfig struct {
PostsPerHour int
FollowsPerHour int
ReportsPerHour int
UploadsPerHour int
SearchesPerHour int
}
RateLimitConfig configures rate limiting for different endpoints
func DefaultRateLimits ¶
func DefaultRateLimits() RateLimitConfig
DefaultRateLimits returns Mastodon-compatible rate limits
type RequestPaginationParams ¶
type RequestPaginationParams struct {
Limit int `json:"limit"`
Offset int `json:"offset"`
MaxID string `json:"max_id"`
MinID string `json:"min_id"`
SinceID string `json:"since_id"`
}
RequestPaginationParams extracts common pagination parameters (different from pagination.go version)
type ResourceCheckpoint ¶
type ResourceCheckpoint struct {
Timestamp time.Time
MemoryUsed uint64
Goroutines int
Description string
}
ResourceCheckpoint represents a point-in-time snapshot of resource usage
type SafeJSONDecoder ¶
type SafeJSONDecoder struct {
// contains filtered or unexported fields
}
SafeJSONDecoder wraps json.Decoder with safety limits
func NewSafeJSONDecoder ¶
func NewSafeJSONDecoder(r io.Reader) *SafeJSONDecoder
NewSafeJSONDecoder creates a decoder with safety limits
func (*SafeJSONDecoder) Decode ¶
func (d *SafeJSONDecoder) Decode(v any) error
Decode safely decodes JSON with depth and size limits
type SearchPaginationParams ¶
type SearchPaginationParams struct {
PaginationParams
Type string `json:"type"` // account, hashtag, status
Resolve bool `json:"resolve"` // Resolve remote resources
Following bool `json:"following"` // Only search followed accounts
AccountID string `json:"account_id"` // Limit search to specific account
MaxResults int `json:"max_results"` // Override limit for search APIs
ExcludeUnreviewed bool `json:"exclude_unreviewed"` // Exclude unreviewed content
}
SearchPaginationParams extends PaginationParams for search-specific needs
func GetSearchPaginationParams ¶
func GetSearchPaginationParams(ctx *apptheory.Context) SearchPaginationParams
GetSearchPaginationParams extracts search-specific pagination parameters.
type SecurityContext ¶
type SecurityContext struct {
UserID string
SessionID string
IP string
UserAgent string
RequestID string
}
SecurityContext provides context for security logging
type SessionNotFoundError ¶
type SessionNotFoundError struct {
SessionID string
}
SessionNotFoundError indicates a session was not found
func (SessionNotFoundError) Error ¶
func (e SessionNotFoundError) Error() string
type StandardErrorResponse ¶
type StandardErrorResponse struct {
Error string `json:"error"`
Description string `json:"error_description,omitempty"`
Code string `json:"error_code,omitempty"`
}
StandardErrorResponse represents a standardized API error response
type StatusValidationRules ¶
type StatusValidationRules struct {
MaxLength int
AllowMarkdown bool
AllowHTML bool
RequireContent bool
MaxMediaItems int
MaxPollOptions int
}
StatusValidationRules defines validation rules for status content
type StreamingEvent ¶
type StreamingEvent struct {
Type string
Object string
ObjectID string
ActorID string
Timestamp time.Time
Metadata map[string]interface{}
}
StreamingEvent represents a streaming event without import dependencies
func EmitBusinessEvent ¶
func EmitBusinessEvent(_ context.Context, eventType, objectType, objectID, actorID string, metadata map[string]interface{}) *StreamingEvent
EmitBusinessEvent creates standardized business events
func EmitEntityCreatedEvents ¶
func EmitEntityCreatedEvents(ctx context.Context, entityType, entityID, actorID string, entity interface{}) []*StreamingEvent
EmitEntityCreatedEvents creates standard creation events
func EmitEntityDeletedEvents ¶
func EmitEntityDeletedEvents(ctx context.Context, entityType, entityID, actorID string) []*StreamingEvent
EmitEntityDeletedEvents creates standard deletion events
func EmitEntityUpdatedEvents ¶
func EmitEntityUpdatedEvents(ctx context.Context, entityType, entityID, actorID string, entity interface{}, changes map[string]interface{}) []*StreamingEvent
EmitEntityUpdatedEvents creates standard update events
type StreamingMessage ¶
type StreamingMessage struct {
Event string `json:"event"`
Data interface{} `json:"data"`
}
StreamingMessage represents a Server-Sent Events message
type TimelinePaginationParams ¶
type TimelinePaginationParams struct {
PaginationParams
Local bool `json:"local"`
OnlyMedia bool `json:"only_media"`
RemoteOnly bool `json:"remote_only"`
IncludeReplies bool `json:"include_replies"`
}
TimelinePaginationParams extends PaginationParams for timeline-specific needs
func GetTimelinePaginationParams ¶
func GetTimelinePaginationParams(ctx *apptheory.Context) TimelinePaginationParams
GetTimelinePaginationParams extracts timeline-specific pagination parameters.
type TimelineParams ¶
type TimelineParams struct {
RequestPaginationParams
Local bool `json:"local"`
OnlyMedia bool `json:"only_media"`
}
TimelineParams extracts timeline-specific parameters
type TransformationCache ¶
type TransformationCache[TSource, TTarget any] struct { // contains filtered or unexported fields }
TransformationCache provides caching for expensive transformations
func NewTransformationCache ¶
func NewTransformationCache[TSource, TTarget any]( ttl time.Duration, maxSize int, keyFunc func(TSource) string, logger *zap.Logger, ) *TransformationCache[TSource, TTarget]
NewTransformationCache creates a new cache for transformations
func (*TransformationCache[TSource, TTarget]) Clear ¶
func (tc *TransformationCache[TSource, TTarget]) Clear()
Clear removes all cached entries
func (*TransformationCache[TSource, TTarget]) Get ¶
func (tc *TransformationCache[TSource, TTarget]) Get(source TSource) (TTarget, bool)
Get retrieves a cached transformation result
func (*TransformationCache[TSource, TTarget]) Set ¶
func (tc *TransformationCache[TSource, TTarget]) Set(source TSource, target TTarget)
Set stores a transformation result in the cache
func (*TransformationCache[TSource, TTarget]) Stats ¶
func (tc *TransformationCache[TSource, TTarget]) Stats() (hits, misses int64, hitRate float64)
Stats returns cache performance statistics
type TransformationContext ¶
type TransformationContext struct {
UserID string
RequestID string
Metadata map[string]interface{}
StartTime time.Time
Transformers map[string]interface{}
}
TransformationContext carries metadata through transformation pipelines
func NewTransformationContext ¶
func NewTransformationContext(userID, requestID string) *TransformationContext
NewTransformationContext creates a new transformation context
func (*TransformationContext) Duration ¶
func (tc *TransformationContext) Duration() time.Duration
Duration returns the elapsed time since context creation
func (*TransformationContext) GetMetadata ¶
func (tc *TransformationContext) GetMetadata(key string) (interface{}, bool)
GetMetadata retrieves metadata from the transformation context
func (*TransformationContext) WithMetadata ¶
func (tc *TransformationContext) WithMetadata(key string, value interface{}) *TransformationContext
WithMetadata adds metadata to the transformation context
type TransformationError ¶
TransformationError provides detailed error information for failed transformations
func (TransformationError) Error ¶
func (e TransformationError) Error() string
func (TransformationError) Unwrap ¶
func (e TransformationError) Unwrap() error
type TransformationMetrics ¶
type TransformationMetrics struct {
// contains filtered or unexported fields
}
TransformationMetrics tracks performance and success rates
func NewTransformationMetrics ¶
func NewTransformationMetrics() *TransformationMetrics
NewTransformationMetrics creates a new metrics tracker
func (*TransformationMetrics) GetStats ¶
func (tm *TransformationMetrics) GetStats() (count, errors int64, avgDuration time.Duration, errorRate float64)
GetStats returns current transformation statistics
func (*TransformationMetrics) RecordTransformation ¶
func (tm *TransformationMetrics) RecordTransformation(duration time.Duration, success bool)
RecordTransformation updates transformation metrics
func (*TransformationMetrics) Reset ¶
func (tm *TransformationMetrics) Reset()
Reset clears all metrics
type TransformationPipeline ¶
type TransformationPipeline[TSource, TTarget any] struct { // contains filtered or unexported fields }
TransformationPipeline provides a framework for chaining transformations
type TransformationRegistry ¶
type TransformationRegistry struct {
// contains filtered or unexported fields
}
TransformationRegistry manages named transformers for dynamic lookup
func NewTransformationRegistry ¶
func NewTransformationRegistry(logger *zap.Logger) *TransformationRegistry
NewTransformationRegistry creates a new registry for managing transformers
func (*TransformationRegistry) Get ¶
func (tr *TransformationRegistry) Get(name string) (interface{}, bool)
Get retrieves a transformer from the registry
func (*TransformationRegistry) List ¶
func (tr *TransformationRegistry) List() []string
List returns all registered transformer names
func (*TransformationRegistry) Register ¶
func (tr *TransformationRegistry) Register(name string, transformer interface{}) error
Register adds a transformer to the registry
func (*TransformationRegistry) Unregister ¶
func (tr *TransformationRegistry) Unregister(name string) bool
Unregister removes a transformer from the registry
type TransformationStep ¶
type TransformationStep[T any] struct { Name string Transformer Transformer[T, T] Required bool // If true, failure stops the pipeline }
TransformationStep represents a single step in a transformation pipeline
type Transformer ¶
type Transformer[TSource, TTarget any] interface { Transform(ctx context.Context, source TSource) (TTarget, error) }
Transformer defines the core interface for data transformations This interface provides type-safe transformations with error handling
func MemoizedTransformer ¶
func MemoizedTransformer[TSource, TTarget any]( transformer Transformer[TSource, TTarget], keyFunc func(TSource) string, ttl time.Duration, ) Transformer[TSource, TTarget]
MemoizedTransformer provides memoization for expensive transformations
func ValidatingTransformer ¶
func ValidatingTransformer[TSource, TTarget any]( transformer Transformer[TSource, TTarget], validator func(TSource) error, ) Transformer[TSource, TTarget]
ValidatingTransformer wraps a transformer with input validation
type UsedTokenError ¶
type UsedTokenError struct {
Token string
}
UsedTokenError indicates a token has already been used
func (UsedTokenError) Error ¶
func (e UsedTokenError) Error() string
type UserNotFoundError ¶
type UserNotFoundError struct {
Username string
}
UserNotFoundError indicates a user was not found
func (UserNotFoundError) Error ¶
func (e UserNotFoundError) Error() string
type ValidationError ¶
ValidationError indicates input validation failed
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type ValidationRules ¶
type ValidationRules struct {
Required []string
MaxLen map[string]int
MinLen map[string]int
Pattern map[string]string
}
ValidationRules defines basic validation rules
type VisibilityLevel ¶
type VisibilityLevel string
VisibilityLevel represents different visibility levels
const ( VisibilityPublic VisibilityLevel = "public" // VisibilityPublic makes content visible to everyone VisibilityUnlisted VisibilityLevel = "unlisted" // VisibilityUnlisted makes content visible but not in public timelines VisibilityPrivate VisibilityLevel = "private" // VisibilityPrivate makes content visible only to followers VisibilityDirect VisibilityLevel = "direct" // VisibilityDirect makes content visible only to mentioned users )
Visibility levels for content
type WebSocketMessage ¶
type WebSocketMessage struct {
Type string `json:"type"`
Stream []string `json:"stream,omitempty"`
Event string `json:"event,omitempty"`
Payload interface{} `json:"payload,omitempty"`
}
WebSocketMessage represents a WebSocket message
func CreateWebSocketMessage ¶
func CreateWebSocketMessage(msgType string, stream []string, event string, payload interface{}) WebSocketMessage
CreateWebSocketMessage creates a properly formatted WebSocket message
Source Files
¶
- auth_helpers.go
- business.go
- business_activitypub.go
- business_mastodon.go
- constants.go
- cookies.go
- doc.go
- error_constants.go
- error_middleware.go
- error_responses.go
- errors.go
- feature_flags.go
- form.go
- headers.go
- http_constants.go
- id_generator.go
- insecure_tls.go
- json.go
- json_safety.go
- keys.go
- lambda_helpers.go
- lambda_init.go
- logging.go
- oauth_client_secret.go
- pagination.go
- redirect.go
- request.go
- resources.go
- response.go
- response_body.go
- responses.go
- runtime_env.go
- sanitize.go
- security_logger.go
- slug.go
- testing.go
- time_formats.go
- transformers.go
- validation.go
- validation_activitypub.go
- validation_mastodon.go