Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| """ | |
| Generate JWT Secret Key | |
| This script generates a cryptographically secure secret key for JWT signing. | |
| Run this locally and add the generated key to your .env file. | |
| Usage: | |
| python generate_jwt_secret.py | |
| # Or with custom length | |
| python generate_jwt_secret.py --length 128 | |
| Output: | |
| Prints the secret key and instructions for adding it to your environment. | |
| """ | |
| import argparse | |
| import secrets | |
| import sys | |
| def generate_secret(length: int = 64) -> str: | |
| """ | |
| Generate a cryptographically secure URL-safe secret. | |
| Args: | |
| length: Number of bytes for the secret (default: 64). | |
| The actual string length will be ~1.3x this due to base64 encoding. | |
| Returns: | |
| str: URL-safe base64 encoded secret. | |
| """ | |
| return secrets.token_urlsafe(length) | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Generate a secure JWT secret key", | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=""" | |
| Examples: | |
| python generate_jwt_secret.py | |
| python generate_jwt_secret.py --length 128 | |
| python generate_jwt_secret.py --format docker | |
| """ | |
| ) | |
| parser.add_argument( | |
| "--length", "-l", | |
| type=int, | |
| default=64, | |
| help="Number of bytes for the secret (default: 64)" | |
| ) | |
| parser.add_argument( | |
| "--format", "-f", | |
| choices=["env", "docker", "export", "raw"], | |
| default="env", | |
| help="Output format (default: env)" | |
| ) | |
| args = parser.parse_args() | |
| if args.length < 32: | |
| print("Warning: Secret length should be at least 32 bytes for security.", file=sys.stderr) | |
| secret = generate_secret(args.length) | |
| print("\n" + "=" * 60) | |
| print("π Generated JWT Secret Key") | |
| print("=" * 60) | |
| if args.format == "raw": | |
| print(secret) | |
| elif args.format == "env": | |
| print(f"\nAdd this line to your .env file:\n") | |
| print(f"JWT_SECRET={secret}") | |
| elif args.format == "docker": | |
| print(f"\nAdd this to your docker-compose.yml environment:\n") | |
| print(f" - JWT_SECRET={secret}") | |
| elif args.format == "export": | |
| print(f"\nRun this command to set the environment variable:\n") | |
| print(f"export JWT_SECRET='{secret}'") | |
| print("\n" + "-" * 60) | |
| print("β οΈ IMPORTANT SECURITY NOTES:") | |
| print("-" * 60) | |
| print("β’ Keep this secret confidential - never commit it to git") | |
| print("β’ Use different secrets for development and production") | |
| print("β’ If compromised, all existing tokens become invalid") | |
| print("β’ Store securely (e.g., secrets manager, encrypted env)") | |
| print("=" * 60 + "\n") | |
| if __name__ == "__main__": | |
| main() | |