-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_github_app_manifest.py
More file actions
373 lines (300 loc) · 12.7 KB
/
create_github_app_manifest.py
File metadata and controls
373 lines (300 loc) · 12.7 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# -*- coding: utf-8 -*-
"""
🚀 CometX - GitHub App Creator (Manifest Flow)
يولد GitHub App تلقائياً مع كل المفاتيح:
- يفتح صفحة GitHub جاهزة بالإعدادات
- تضغط Create → تاخذ one-time code
- تلصقه هنا → يطلع لك App ID + Private Key + كل شيء
التشغيل:
python create_github_app_manifest.py
المتطلبات:
pip install requests pyjwt cryptography
"""
import json
import webbrowser
import urllib.parse
import requests
import os
import time
from pathlib import Path
# ========================================
# ⚙️ إعدادات CometX (عدّلها إذا تبي)
# ========================================
APP_NAME = "CometX Automation Bot"
HOMEPAGE_URL = "https://ai.gratech.sa"
WEBHOOK_URL = "https://api.gratech.sa/github/webhook" # خليه فاضي "" إذا ما عندك webhook الآن
DESCRIPTION = "🚀 CometX - Elite automation bot for GitHub, Issues, PRs, CI/CD & deployments"
# صلاحيات شاملة للأتمتة
PERMISSIONS = {
"actions": "write", # تشغيل وإدارة Actions
"administration": "read", # قراءة إعدادات الريبو
"checks": "write", # كتابة Check Runs
"contents": "write", # قراءة/كتابة الملفات والكود
"issues": "write", # إدارة Issues كاملة
"metadata": "read", # مطلوب دائماً (إلزامي)
"pull_requests": "write", # إدارة PRs كاملة
"workflows": "write", # تعديل وتشغيل Workflows
"deployments": "write", # إدارة Deployments
"statuses": "write", # كتابة Commit Statuses
}
# الأحداث المطلوبة (Webhooks)
EVENTS = [
"push",
"pull_request",
"issues",
"workflow_run",
"deployment",
"check_run",
"status"
]
# ملفات الإخراج
ENV_FILE = Path(".env.github")
PEM_FILE = Path("github-app-private-key.pem")
def print_banner():
"""بانر البداية"""
print("\n" + "="*60)
print("🚀 CometX - GitHub App Creator")
print("="*60 + "\n")
def make_manifest():
"""ينشئ manifest JSON للتطبيق"""
manifest = {
"name": APP_NAME,
"url": HOMEPAGE_URL,
"hook_attributes": {
"url": WEBHOOK_URL,
"active": True
} if WEBHOOK_URL else {},
"public": False,
"default_permissions": PERMISSIONS,
"default_events": EVENTS,
"description": DESCRIPTION,
}
return manifest
def open_manifest_in_browser(manifest: dict):
"""يفتح صفحة GitHub لإنشاء App بالإعدادات الجاهزة"""
manifest_json = json.dumps(manifest, separators=(',', ':'))
encoded = urllib.parse.quote(manifest_json, safe='')
url = f"https://github.com/settings/apps/new?manifest={encoded}"
print("📝 [1/4] فتح صفحة GitHub لإنشاء التطبيق...\n")
print("🌐 الرابط (إذا ما فتح تلقائياً):")
print(f" {url}\n")
try:
webbrowser.open(url)
print("✅ تم فتح المتصفح")
except Exception as e:
print(f"⚠️ ما قدرت أفتح المتصفح تلقائياً: {e}")
print("انسخ الرابط أعلاه وافتحه يدوياً")
def convert_code_to_app(code: str):
"""يحول one-time code إلى بيانات التطبيق الكاملة"""
api_url = f"https://api.github.com/app-manifests/{code}/conversions"
print("\n🔄 [3/4] جاري تحويل الكود إلى بيانات التطبيق...")
try:
response = requests.post(api_url, timeout=30)
if response.status_code == 201:
print("✅ تم التحويل بنجاح!\n")
return response.json()
else:
print(f"❌ فشل التحويل (HTTP {response.status_code})")
print(f"الاستجابة: {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"❌ خطأ في الاتصال: {e}")
return None
def write_outputs(app_data: dict):
"""يحفظ المفاتيح والبيانات في ملفات"""
app_id = app_data.get("id")
slug = app_data.get("slug")
webhook_secret = app_data.get("webhook_secret", "")
pem = app_data.get("pem")
client_id = app_data.get("client_id")
client_secret = app_data.get("client_secret")
html_url = app_data.get("html_url")
print("💾 [4/4] حفظ البيانات...")
# حفظ Private Key
PEM_FILE.write_text(pem, encoding="utf-8")
# تعيين صلاحيات أمنية (Unix/Linux/Mac فقط)
try:
os.chmod(PEM_FILE, 0o600)
except:
pass
# حفظ .env
env_content = f"""# CometX GitHub App Configuration
# Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}
GITHUB_APP_ID={app_id}
GITHUB_APP_SLUG={slug}
GITHUB_APP_CLIENT_ID={client_id}
GITHUB_APP_CLIENT_SECRET={client_secret}
GITHUB_WEBHOOK_SECRET={webhook_secret}
GITHUB_PRIVATE_KEY_FILE={PEM_FILE.name}
# URLs
GITHUB_APP_URL={html_url}
"""
ENV_FILE.write_text(env_content, encoding="utf-8")
print("\n" + "="*60)
print("✅ تم إنشاء GitHub App بنجاح!")
print("="*60)
print(f"\n📛 App Name: {APP_NAME}")
print(f"🆔 App ID: {app_id}")
print(f"🔗 App URL: {html_url}")
print(f"🔑 Client ID: {client_id}")
print(f"🔐 Client Secret: {client_secret[:10]}...")
print(f"📝 Webhook Secret: {webhook_secret[:10] if webhook_secret else 'N/A'}...")
print(f"\n💾 Files Created:")
print(f" • {PEM_FILE.resolve()} (Private Key)")
print(f" • {ENV_FILE.resolve()} (Environment Variables)")
print("="*60)
def generate_jwt(app_id: str, pem_path: Path):
"""ينشئ JWT Token للمصادقة"""
try:
import jwt
except ImportError:
print("\n⚠️ لتوليد JWT، نصّب PyJWT:")
print(" pip install pyjwt cryptography")
return None
now = int(time.time())
payload = {
"iat": now - 60, # Issued at (مع هامش)
"exp": now + (9 * 60), # Expires (9 دقائق)
"iss": app_id # Issuer (App ID)
}
with open(pem_path, "r", encoding="utf-8") as f:
private_key = f.read()
token = jwt.encode(payload, private_key, algorithm="RS256")
return token
def get_installation_token(jwt_token: str, installation_id: str):
"""يحصل على Installation Access Token"""
url = f"https://api.github.com/app/installations/{installation_id}/access_tokens"
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github+json"
}
try:
response = requests.post(url, headers=headers, timeout=30)
if response.status_code in [200, 201]:
data = response.json()
token = data.get("token")
expires_at = data.get("expires_at")
print(f"\n✅ Installation Token Created!")
print(f" Expires: {expires_at}")
return token
else:
print(f"\n❌ فشل الحصول على Token: {response.status_code}")
print(f" Response: {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"❌ خطأ: {e}")
return None
def trigger_workflow_example(token: str, owner: str, repo: str, workflow_id: str):
"""مثال: تشغيل GitHub Actions Workflow"""
url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json"
}
data = {
"ref": "main", # أو أي branch
"inputs": {} # أي inputs للـ workflow
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 204:
print("✅ تم تشغيل Workflow بنجاح!")
return True
else:
print(f"❌ فشل تشغيل Workflow: {response.status_code}")
print(response.text)
return False
def main():
"""البرنامج الرئيسي"""
print_banner()
# الخطوة 1: إنشاء Manifest وفتح المتصفح
manifest = make_manifest()
open_manifest_in_browser(manifest)
# الخطوة 2: انتظار المستخدم لإنشاء التطبيق
print("\n📋 [2/4] في صفحة GitHub:")
print(" 1. راجع الإعدادات (اختياري)")
print(" 2. اضغط 'Create GitHub App'")
print(" 3. GitHub بيعطيك 'one-time code'")
print(" 4. انسخ الكود وارجع هنا\n")
code = input("📥 الصق one-time code هنا: ").strip()
if not code:
print("\n❌ ما فيه كود! أعد التشغيل.")
return
# الخطوة 3: تحويل الكود إلى بيانات التطبيق
app_data = convert_code_to_app(code)
if not app_data:
print("\n❌ فشل إنشاء التطبيق. حاول مرة ثانية.")
return
# الخطوة 4: حفظ البيانات
write_outputs(app_data)
# الخطوة 5 (اختيارية): توليد JWT
print("\n" + "="*60)
print("🔐 JWT & Installation Token (اختياري)")
print("="*60)
do_jwt = input("\n❓ تبي تولد JWT الآن؟ (y/N): ").strip().lower()
if do_jwt == 'y':
app_id = str(app_data.get("id"))
jwt_token = generate_jwt(app_id, PEM_FILE)
if jwt_token:
print(f"\n🔑 JWT Token (صالح 9 دقائق):")
print(f" {jwt_token[:50]}...")
# Installation Token
do_installation = input("\n❓ عندك Installation ID وتبي Installation Token؟ (y/N): ").strip().lower()
if do_installation == 'y':
installation_id = input(" 📥 أدخل Installation ID: ").strip()
if installation_id:
inst_token = get_installation_token(jwt_token, installation_id)
if inst_token:
print(f"\n🎟️ Installation Access Token:")
print(f" {inst_token[:50]}...")
# مثال: تشغيل Workflow
test_workflow = input("\n❓ تبي تجرب تشغيل workflow؟ (y/N): ").strip().lower()
if test_workflow == 'y':
owner = input(" Owner: ").strip()
repo = input(" Repo: ").strip()
workflow = input(" Workflow ID/filename: ").strip()
if owner and repo and workflow:
trigger_workflow_example(inst_token, owner, repo, workflow)
# الخطوة النهائية
print("\n" + "="*60)
print("📚 الخطوات التالية:")
print("="*60)
print(f"\n1️⃣ ثبّت التطبيق على الحساب/المستودع:")
print(f" {app_data.get('html_url')}/installations/new")
print("\n2️⃣ احصل على Installation ID من:")
print(" Settings → Applications → Installed GitHub Apps")
print("\n3️⃣ استخدم البيانات من:")
print(f" {ENV_FILE.resolve()}")
print(f" {PEM_FILE.resolve()}")
print("\n4️⃣ مثال استخدام في Python:")
print("""
import jwt, requests, time
from pathlib import Path
# توليد JWT
app_id = "YOUR_APP_ID"
pem = Path("github-app-private-key.pem").read_text()
now = int(time.time())
payload = {"iat": now - 60, "exp": now + 540, "iss": app_id}
jwt_token = jwt.encode(payload, pem, algorithm="RS256")
# الحصول على Installation Token
installation_id = "YOUR_INSTALLATION_ID"
url = f"https://api.github.com/app/installations/{installation_id}/access_tokens"
headers = {"Authorization": f"Bearer {jwt_token}", "Accept": "application/vnd.github+json"}
token = requests.post(url, headers=headers).json()["token"]
# استخدام Token مع API
repos = requests.get(
"https://api.github.com/installation/repositories",
headers={"Authorization": f"Bearer {token}"}
).json()
print(repos)
""")
print("\n✅ تمام! CometX GitHub App جاهز للاستخدام 🚀")
print("="*60 + "\n")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n⚠️ تم إلغاء العملية.")
except Exception as e:
print(f"\n❌ خطأ غير متوقع: {e}")
import traceback
traceback.print_exc()