package common import ( "regexp" "strings" "unicode/utf8" "github.com/google/uuid" ) var ( usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) idempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) ) func blank(s string) bool { return strings.TrimSpace(s) == "" } func strLenBetween(s string, min, max int) bool { n := utf8.RuneCountInString(s) return n >= min && n <= max } func ValidateCreateUser(username, displayName string) error { if !usernameRegex.MatchString(username) { return BadRequest("username must match ^[a-z0-9_]{3,32}$") } if blank(displayName) { return BadRequest("display_name must not be empty or only whitespace") } if !strLenBetween(displayName, 1, 100) { return BadRequest("display_name must be between 1 and 100 Unicode code points") } return nil } func ValidatePassword(password string) error { if blank(password) { return BadRequest("password must not be empty or only whitespace") } if !strLenBetween(password, 12, 128) { return BadRequest("password must be between 12 and 128 Unicode code points") } return nil } func ValidateChatTitle(title string) error { if blank(title) { return BadRequest("title must not be empty or only whitespace") } if !strLenBetween(title, 1, 100) { return BadRequest("title must be between 1 and 100 Unicode code points") } return nil } func ValidateMessageText(text string) error { if blank(text) { return BadRequest("text must not be empty or only whitespace") } if !strLenBetween(text, 1, 4000) { return BadRequest("text must be between 1 and 4000 Unicode code points") } return nil } func ValidateIdempotencyKey(key string) error { if key == "" { return BadRequest("Idempotency-Key header is required") } if !idempotencyKeyRegex.MatchString(key) { return BadRequest("Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$") } return nil } func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) error { if len(ids) < 1 || len(ids) > 100 { return BadRequest("member_ids must contain between 1 and 100 members") } seen := make(map[uuid.UUID]bool, len(ids)) callerFound := false for _, id := range ids { if seen[id] { return BadRequest("member_ids must not contain duplicates") } seen[id] = true if id == callerID { callerFound = true } } if !callerFound { return BadRequest("caller must be included in member_ids") } return nil }