Files
2026-06-18 16:28:33 +02:00

52 lines
1.3 KiB
Go

package authkit
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
)
var servicePrefixes = map[string]string{
"bot": "bot",
"server-manager": "sm",
"portal": "ptl",
"addon": "adn",
"mc-wrapper": "mcw",
"gate-waker": "gwk",
"cloud-svc": "cld",
}
// PrefixFor returns the key prefix for a service name.
func PrefixFor(service string) (string, bool) {
p, ok := servicePrefixes[service]
return p, ok
}
// GenerateAPIKey mints a new API key for the given service.
// Returns plaintext, sha256-hex hash, and the first-8-char prefix.
// Unknown service or crypto/rand failure returns a non-nil error.
func GenerateAPIKey(service string) (plaintext, hash, prefix string, err error) {
pfx, ok := servicePrefixes[service]
if !ok {
return "", "", "", fmt.Errorf("authkit: unknown service %q", service)
}
var raw [24]byte
if _, err := rand.Read(raw[:]); err != nil {
return "", "", "", fmt.Errorf("authkit: crypto/rand: %w", err)
}
hexPart := hex.EncodeToString(raw[:])
plaintext = pfx + "_" + hexPart
hash = HashKey(plaintext)
prefix = plaintext[:8]
return plaintext, hash, prefix, nil
}
// HashKey returns the sha256 hex digest of plaintext.
func HashKey(plaintext string) string {
sum := sha256.Sum256([]byte(plaintext))
return hex.EncodeToString(sum[:])
}