|
| 1 | +package jwt |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + jwtlib "github.com/golang-jwt/jwt/v5" |
| 8 | +) |
| 9 | + |
| 10 | +const ( |
| 11 | + // Status constants for captcha tokens |
| 12 | + Pending = "pending" |
| 13 | + Valid = "valid" |
| 14 | + |
| 15 | + // DefaultPendingTTL is the default TTL for pending captcha tokens (30 minutes) |
| 16 | + DefaultPendingTTL = 30 * time.Minute |
| 17 | + // DefaultPassedTTL is the default TTL for passed captcha tokens (24 hours) |
| 18 | + DefaultPassedTTL = 24 * time.Hour |
| 19 | +) |
| 20 | + |
| 21 | +// Token represents the payload stored in a signed captcha cookie |
| 22 | +type Token struct { |
| 23 | + UUID string `json:"uuid"` // UUID for traceability and debugging |
| 24 | + St string `json:"st"` // status: "pending", "passed", "failed", etc. |
| 25 | + Iat int64 `json:"iat"` // issued at (unix seconds) |
| 26 | + Exp int64 `json:"exp"` // expires at (unix seconds) |
| 27 | +} |
| 28 | + |
| 29 | +// Sign signs a Token using JWT (JWS) and returns a signed JWT string |
| 30 | +// Uses HMAC-SHA256 for signing. The token can be encrypted (JWE) in the future if needed. |
| 31 | +func Sign(tok Token, secret []byte) (string, error) { |
| 32 | + // Create JWT claims from Token |
| 33 | + claims := jwtlib.MapClaims{ |
| 34 | + "uuid": tok.UUID, |
| 35 | + "st": tok.St, |
| 36 | + "iat": tok.Iat, |
| 37 | + "exp": tok.Exp, |
| 38 | + } |
| 39 | + |
| 40 | + // Create token with HMAC-SHA256 signing method |
| 41 | + token := jwtlib.NewWithClaims(jwtlib.SigningMethodHS256, claims) |
| 42 | + |
| 43 | + // Sign and get the complete encoded token as a string |
| 44 | + tokenString, err := token.SignedString(secret) |
| 45 | + if err != nil { |
| 46 | + return "", fmt.Errorf("failed to sign token: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + return tokenString, nil |
| 50 | +} |
| 51 | + |
| 52 | +// ParseAndVerify parses and verifies a JWT token string |
| 53 | +// Returns the token if valid, or an error if invalid, expired, or tampered with |
| 54 | +// JWT library automatically handles expiration checking via the "exp" claim |
| 55 | +func ParseAndVerify(raw string, secret []byte) (*Token, error) { |
| 56 | + if raw == "" { |
| 57 | + return nil, fmt.Errorf("empty token") |
| 58 | + } |
| 59 | + |
| 60 | + // Parse and verify the JWT token |
| 61 | + token, err := jwtlib.Parse(raw, func(token *jwtlib.Token) (any, error) { |
| 62 | + // Validate signing method |
| 63 | + if _, ok := token.Method.(*jwtlib.SigningMethodHMAC); !ok { |
| 64 | + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) |
| 65 | + } |
| 66 | + return secret, nil |
| 67 | + }) |
| 68 | + |
| 69 | + if err != nil { |
| 70 | + return nil, fmt.Errorf("failed to parse/verify token: %w", err) |
| 71 | + } |
| 72 | + |
| 73 | + // Verify token is valid (signature, expiration, etc.) |
| 74 | + if !token.Valid { |
| 75 | + return nil, fmt.Errorf("invalid token") |
| 76 | + } |
| 77 | + |
| 78 | + // Extract claims |
| 79 | + claims, ok := token.Claims.(jwtlib.MapClaims) |
| 80 | + if !ok { |
| 81 | + return nil, fmt.Errorf("invalid token claims") |
| 82 | + } |
| 83 | + |
| 84 | + // Convert JWT claims back to Token |
| 85 | + tok := &Token{ |
| 86 | + UUID: getStringClaim(claims, "uuid"), |
| 87 | + St: getStringClaim(claims, "st"), |
| 88 | + Iat: getInt64Claim(claims, "iat"), |
| 89 | + Exp: getInt64Claim(claims, "exp"), |
| 90 | + } |
| 91 | + |
| 92 | + return tok, nil |
| 93 | +} |
| 94 | + |
| 95 | +// Helper functions to safely extract claims from JWT |
| 96 | +func getStringClaim(claims jwtlib.MapClaims, key string) string { |
| 97 | + if val, ok := claims[key]; ok { |
| 98 | + if str, ok := val.(string); ok { |
| 99 | + return str |
| 100 | + } |
| 101 | + } |
| 102 | + return "" |
| 103 | +} |
| 104 | + |
| 105 | +func getInt64Claim(claims jwtlib.MapClaims, key string) int64 { |
| 106 | + if val, ok := claims[key]; ok { |
| 107 | + switch v := val.(type) { |
| 108 | + case int64: |
| 109 | + return v |
| 110 | + case float64: |
| 111 | + return int64(v) |
| 112 | + case int: |
| 113 | + return int64(v) |
| 114 | + } |
| 115 | + } |
| 116 | + return 0 |
| 117 | +} |
| 118 | + |
| 119 | +// IsPassed checks if the token indicates the captcha was passed (not expired and status is valid) |
| 120 | +func (t *Token) IsPassed() bool { |
| 121 | + return time.Now().Unix() <= t.Exp && t.St == Valid |
| 122 | +} |
| 123 | + |
| 124 | +// IsPending checks if the token indicates the captcha is pending (not expired and status is pending) |
| 125 | +func (t *Token) IsPending() bool { |
| 126 | + return time.Now().Unix() <= t.Exp && t.St == Pending |
| 127 | +} |
0 commit comments