-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-secrets.py
More file actions
231 lines (196 loc) · 6.67 KB
/
setup-secrets.py
File metadata and controls
231 lines (196 loc) · 6.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#!/usr/bin/env python3
"""
GitHub Secrets Setup Script
Sets all required secrets for Cloudflare deployment via GitHub API
"""
import os
import sys
import json
import base64
from pathlib import Path
try:
import requests
except ImportError:
print("❌ requests library not installed")
print("Install with: pip install requests")
sys.exit(1)
try:
from nacl import public, utils
except ImportError:
print("❌ PyNaCl library not installed")
print("Install with: pip install pynacl")
sys.exit(1)
# Configuration
REPO = "ciscoittech/binary-math-system"
GITHUB_API = "https://api.github.com"
SECRETS = {
"CLOUDFLARE_API_TOKEN": {
"description": "API token for Cloudflare",
"source": "https://dash.cloudflare.com/profile/api-tokens",
"permission": "Edit Cloudflare Workers",
"sensitive": True,
},
"CLOUDFLARE_ACCOUNT_ID": {
"description": "Your Cloudflare Account ID",
"source": "https://dash.cloudflare.com (right sidebar)",
"permission": "None",
"sensitive": False,
},
"TURSO_URL": {
"description": "Turso database connection URL",
"source": "Turso Dashboard",
"permission": "None",
"example": "libsql://your-db.turso.io",
"sensitive": False,
},
"TURSO_AUTH_TOKEN": {
"description": "Turso authentication token",
"source": "Turso Dashboard",
"permission": "None",
"sensitive": True,
},
"OPENROUTER_API_KEY": {
"description": "OpenRouter API key (optional)",
"source": "https://openrouter.ai",
"permission": "None",
"sensitive": True,
"optional": True,
},
}
def get_github_token():
"""Get GitHub token from environment variable"""
token = os.getenv("GITHUB_TOKEN")
if not token:
print("❌ GITHUB_TOKEN environment variable not set")
print()
print("Create a Personal Access Token:")
print(" 1. Go to: https://github.com/settings/tokens/new")
print(" 2. Name: 'Binary Math Secrets'")
print(" 3. Scopes: repo, admin:repo_hook")
print(" 4. Generate token and copy it")
print()
print("Then run:")
print(" export GITHUB_TOKEN=ghp_xxxxxxxxxxxx")
print(" python3 setup-secrets.py")
return None
return token
def get_public_key(token):
"""Get repository public key for encrypting secrets"""
url = f"{GITHUB_API}/repos/{REPO}/actions/secrets/public-key"
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github.v3+json",
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print(f"❌ Failed to get public key: {response.status_code}")
print(response.text)
return None
def encrypt_secret(public_key_b64, secret_value):
"""Encrypt secret using public key"""
try:
from nacl import public, utils, pynacl
except ImportError:
print("❌ PyNaCl not installed")
print("Install with: pip install pynacl")
sys.exit(1)
public_key = public.PublicKey(public_key_b64, encoder=public.Base64Encoder)
secret_bytes = secret_value.encode("utf-8")
encrypted = public.SealedBox(public_key).encrypt(secret_bytes)
return base64.b64encode(encrypted.ciphertext).decode("utf-8")
def set_secret(token, secret_name, secret_value, public_key_info):
"""Set a secret in GitHub"""
url = f"{GITHUB_API}/repos/{REPO}/actions/secrets/{secret_name}"
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github.v3+json",
}
try:
encrypted_value = encrypt_secret(
public_key_info["key"], secret_value
)
except Exception as e:
print(f"❌ Encryption failed: {e}")
return False
payload = {
"encrypted_value": encrypted_value,
"key_id": public_key_info["key_id"],
}
response = requests.put(url, json=payload, headers=headers)
return response.status_code in [201, 204]
def main():
print("🔐 GitHub Secrets Setup for Binary Math System")
print("=" * 50)
print()
# Get GitHub token
token = get_github_token()
if not token:
print("\n❌ Could not authenticate with GitHub")
sys.exit(1)
# Get public key for encryption
print("📍 Fetching encryption key from GitHub...")
public_key_info = get_public_key(token)
if not public_key_info:
sys.exit(1)
print("✅ Got encryption key")
print()
# Collect secrets from user
print("📝 Enter the following secrets:")
print()
collected_secrets = {}
for i, (secret_name, config) in enumerate(SECRETS.items(), 1):
is_optional = config.get("optional", False)
optional_text = " (optional)" if is_optional else ""
is_sensitive = config.get("sensitive", False)
print(f"{i}️⃣ {secret_name}{optional_text}")
print(f" {config['description']}")
print(f" Source: {config['source']}")
if "example" in config:
print(f" Example: {config['example']}")
print()
if is_sensitive:
import getpass
value = getpass.getpass(f" Enter value (hidden): ")
else:
value = input(f" Enter value: ")
if value:
collected_secrets[secret_name] = value
print(f" ✅ Got value")
elif is_optional:
print(f" ⏭️ Skipped (optional)")
else:
print(f" ❌ Required - skipping for now")
print()
if not collected_secrets:
print("❌ No secrets provided")
sys.exit(1)
# Set secrets
print("🚀 Setting secrets in GitHub...")
print()
failed = []
for secret_name, secret_value in collected_secrets.items():
try:
if set_secret(token, secret_name, secret_value, public_key_info):
print(f"✅ Set {secret_name}")
else:
print(f"❌ Failed to set {secret_name}")
failed.append(secret_name)
except Exception as e:
print(f"❌ Error setting {secret_name}: {e}")
failed.append(secret_name)
print()
print("=" * 50)
if not failed:
print("✅ All secrets configured successfully!")
print()
print("Next steps:")
print(f"1. Verify: gh secret list --repo {REPO}")
print("2. Deploy: git push origin main")
print(f"3. Monitor: https://github.com/{REPO}/actions")
else:
print(f"⚠️ {len(failed)} secret(s) failed to set: {', '.join(failed)}")
sys.exit(1)
if __name__ == "__main__":
main()