A community based topic aggregation platform built on atproto
1package oauth
2
3import (
4 "encoding/base64"
5 "fmt"
6 "os"
7 "strings"
8)
9
10// GetEnvBase64OrPlain retrieves an environment variable that may be base64 encoded.
11// If the value starts with "base64:", it will be decoded.
12// Otherwise, it returns the plain value.
13//
14// This allows storing sensitive values like JWKs in base64 format to avoid
15// shell escaping issues and newline handling problems.
16//
17// Example usage in .env:
18//
19// OAUTH_PRIVATE_JWK={"alg":"ES256",...} (plain JSON)
20// OAUTH_PRIVATE_JWK=base64:eyJhbGc... (base64 encoded)
21func GetEnvBase64OrPlain(key string) (string, error) {
22 value := os.Getenv(key)
23 if value == "" {
24 return "", nil
25 }
26
27 // Check if value is base64 encoded
28 if strings.HasPrefix(value, "base64:") {
29 encoded := strings.TrimPrefix(value, "base64:")
30 decoded, err := base64.StdEncoding.DecodeString(encoded)
31 if err != nil {
32 return "", fmt.Errorf("invalid base64 encoding for %s: %w", key, err)
33 }
34 return string(decoded), nil
35 }
36
37 // Return plain value
38 return value, nil
39}