| 1 |
package user |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/sha256" |
| 5 |
"database/sql" |
| 6 |
"encoding/hex" |
| 7 |
"regexp" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"golang.org/x/crypto/bcrypt" |
| 11 |
"heckel.io/ntfy/v2/util" |
| 12 |
) |
| 13 |
|
| 14 |
// linkTokenLength is the length of a raw magic-link token. At 48 base62 characters |
| 15 |
// it carries ~285 bits of entropy, well above the ~256-bit target, so the tokens |
| 16 |
// need no brute-force cap -- just expiry and single-use. |
| 17 |
const linkTokenLength = 48 |
| 18 |
|
| 19 |
var ( |
| 20 |
allowedUsernameRegex = regexp.MustCompile(`^[-_.+@a-zA-Z0-9]+$`) // Does not include Everyone (*) |
| 21 |
allowedTopicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No '*' |
| 22 |
allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards! |
| 23 |
allowedTierRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) |
| 24 |
allowedTokenRegex = regexp.MustCompile(`^tk_[-_A-Za-z0-9]{29}$`) // Must be tokenLength-len(tokenPrefix) |
| 25 |
) |
| 26 |
|
| 27 |
// AllowedRole returns true if the given role can be used for new users |
| 28 |
func AllowedRole(role Role) bool { |
| 29 |
return role == RoleUser || role == RoleAdmin |
| 30 |
} |
| 31 |
|
| 32 |
// AllowedUsername returns true if the given username is valid |
| 33 |
func AllowedUsername(username string) bool { |
| 34 |
return allowedUsernameRegex.MatchString(username) |
| 35 |
} |
| 36 |
|
| 37 |
// AllowedTopic returns true if the given topic name is valid |
| 38 |
func AllowedTopic(topic string) bool { |
| 39 |
return allowedTopicRegex.MatchString(topic) |
| 40 |
} |
| 41 |
|
| 42 |
// AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*) |
| 43 |
func AllowedTopicPattern(topic string) bool { |
| 44 |
return allowedTopicPatternRegex.MatchString(topic) |
| 45 |
} |
| 46 |
|
| 47 |
// AllowedTier returns true if the given tier name is valid |
| 48 |
func AllowedTier(tier string) bool { |
| 49 |
return allowedTierRegex.MatchString(tier) |
| 50 |
} |
| 51 |
|
| 52 |
// ValidPasswordHash checks if the given password hash is a valid bcrypt hash |
| 53 |
func ValidPasswordHash(hash string, minCost int) error { |
| 54 |
if !strings.HasPrefix(hash, "$2a$") && !strings.HasPrefix(hash, "$2b$") && !strings.HasPrefix(hash, "$2y$") { |
| 55 |
return ErrPasswordHashInvalid |
| 56 |
} |
| 57 |
cost, err := bcrypt.Cost([]byte(hash)) |
| 58 |
if err != nil { // Check if the hash is valid (length, format, etc.) |
| 59 |
return err |
| 60 |
} else if cost < minCost { |
| 61 |
return ErrPasswordHashWeak |
| 62 |
} |
| 63 |
return nil |
| 64 |
} |
| 65 |
|
| 66 |
// ValidToken returns true if the given token matches the naming convention |
| 67 |
func ValidToken(token string) bool { |
| 68 |
return allowedTokenRegex.MatchString(token) |
| 69 |
} |
| 70 |
|
| 71 |
// GenerateToken generates a new token with a prefix and a fixed length |
| 72 |
// Lowercase only to support "<topic>+<token>@<domain>" email addresses |
| 73 |
func GenerateToken() string { |
| 74 |
return util.RandomLowerStringPrefix(tokenPrefix, tokenLength) |
| 75 |
} |
| 76 |
|
| 77 |
// generateLinkToken returns a fresh high-entropy raw token for a magic link |
| 78 |
// (email verification or password reset). The raw token is carried in the emailed |
| 79 |
// link; only its hashToken digest is persisted. |
| 80 |
func generateLinkToken() string { |
| 81 |
return util.RandomString(linkTokenLength) |
| 82 |
} |
| 83 |
|
| 84 |
// hashToken returns the hex-encoded SHA-256 digest of a raw magic-link token. |
| 85 |
// Tokens are stored hashed so a database read cannot yield working links; a high-entropy |
| 86 |
// token makes a fast (unsalted) hash sufficient, unlike a password. |
| 87 |
func hashToken(raw string) string { |
| 88 |
sum := sha256.Sum256([]byte(raw)) |
| 89 |
return hex.EncodeToString(sum[:]) |
| 90 |
} |
| 91 |
|
| 92 |
// HashPassword hashes the given password using bcrypt with the given cost |
| 93 |
func HashPassword(password string, cost int) (string, error) { |
| 94 |
hash, err := bcrypt.GenerateFromPassword([]byte(password), cost) |
| 95 |
if err != nil { |
| 96 |
return "", err |
| 97 |
} |
| 98 |
return string(hash), nil |
| 99 |
} |
| 100 |
|
| 101 |
func nullString(s string) sql.NullString { |
| 102 |
if s == "" { |
| 103 |
return sql.NullString{} |
| 104 |
} |
| 105 |
return sql.NullString{String: s, Valid: true} |
| 106 |
} |
| 107 |
|
| 108 |
func nullInt64(v int64) sql.NullInt64 { |
| 109 |
if v == 0 { |
| 110 |
return sql.NullInt64{} |
| 111 |
} |
| 112 |
return sql.NullInt64{Int64: v, Valid: true} |
| 113 |
} |
| 114 |
|
| 115 |
// toSQLWildcard converts a wildcard string to a SQL wildcard string. It only allows '*' as wildcards, |
| 116 |
// and escapes '_', assuming '\' as escape character. |
| 117 |
func toSQLWildcard(s string) string { |
| 118 |
return escapeUnderscore(strings.ReplaceAll(s, "*", "%")) |
| 119 |
} |
| 120 |
|
| 121 |
// fromSQLWildcard converts a SQL wildcard string to a wildcard string. It converts '%' to '*', |
| 122 |
// and removes the '\_' escape character. |
| 123 |
func fromSQLWildcard(s string) string { |
| 124 |
return strings.ReplaceAll(unescapeUnderscore(s), "%", "*") |
| 125 |
} |
| 126 |
|
| 127 |
func escapeUnderscore(s string) string { |
| 128 |
return strings.ReplaceAll(s, "_", "\\_") |
| 129 |
} |
| 130 |
|
| 131 |
func unescapeUnderscore(s string) string { |
| 132 |
return strings.ReplaceAll(s, "\\_", "_") |
| 133 |
} |