JerryCoder commited on
Commit
599ff3c
ยท
verified ยท
1 Parent(s): 7b6f0a2

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +90 -70
bot.py CHANGED
@@ -4,16 +4,22 @@ import zipfile
4
  import base64
5
  import uuid
6
  import tempfile
7
- from fastapi import FastAPI, Request, UploadFile, File
 
 
 
8
  import aiohttp
9
  import uvicorn
10
 
11
  app = FastAPI()
12
 
13
  # -------------------------------
14
- # ๐Ÿ” Simple Python File Encoder
15
  # -------------------------------
16
 
 
 
 
17
  def make_zip_bytes(filename: str, content: bytes) -> bytes:
18
  bio = io.BytesIO()
19
  with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
@@ -23,35 +29,65 @@ def make_zip_bytes(filename: str, content: bytes) -> bytes:
23
  def rand_bytes(n):
24
  return os.urandom(n)
25
 
26
- def xor_bytes(data: bytes, key: bytes) -> bytes:
27
- return bytes([b ^ key[i % len(key)] for i, b in enumerate(data)])
28
-
29
- def encode_bytes(file_bytes: bytes, filename: str):
30
- zipped = make_zip_bytes(filename, file_bytes)
31
- key = rand_bytes(16)
32
- enc = xor_bytes(zipped, key)
33
- enc_b64 = base64.b64encode(enc).decode()
34
- key_b64 = base64.b64encode(key).decode()
35
-
36
- wrapper = f"""# Auto Encrypted by JerryCoder Encryptor
37
  import base64,zipfile,io,tempfile,os,runpy
38
- D=base64.b64decode('{enc_b64}')
39
- K=base64.b64decode('{key_b64}')
40
- O=bytes([b^K[i%len(K)] for i,b in enumerate(D)])
41
- t=tempfile.mkdtemp()
42
- zipfile.ZipFile(io.BytesIO(O)).extractall(t)
43
- p=[f for f in os.listdir(t) if f.endswith('.py')][0]
44
- runpy.run_path(os.path.join(t,p))
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  """
46
- unique_name = f"{os.path.splitext(filename)[0]}_{uuid.uuid4().hex}_enc.py"
47
- return wrapper.encode(), unique_name
48
 
49
- MAX_FILE_SIZE = 3 * 1024 * 1024 # 3 MB limit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  # -------------------------------
52
- # POST /api/encode - receive raw file bytes
53
  # -------------------------------
54
-
55
  @app.post("/api/encode")
56
  async def encode_post(file: UploadFile = File(...)):
57
  filename = file.filename
@@ -61,80 +97,64 @@ async def encode_post(file: UploadFile = File(...)):
61
  try:
62
  file_bytes = await file.read()
63
  if len(file_bytes) > MAX_FILE_SIZE:
64
- return {"ok": False, "error": "File too large (max 3MB)"}
65
 
66
- encoded_bytes, out_name = encode_bytes(file_bytes, filename)
67
 
68
- tmp_path = os.path.join(tempfile.gettempdir(), out_name)
69
  with open(tmp_path, "wb") as f:
70
- f.write(encoded_bytes)
71
 
72
  # Upload to AR Hosting
73
- upload_url = "https://ar-hosting.pages.dev/upload"
74
- form_data = aiohttp.FormData()
75
- f = open(tmp_path, "rb")
76
- form_data.add_field("file", f, filename=out_name, content_type="application/octet-stream")
77
-
78
  async with aiohttp.ClientSession() as session:
79
- async with session.post(upload_url, data=form_data) as resp:
80
- try:
81
- result = await resp.json()
82
- except Exception:
83
- f.close()
84
- return {"ok": False, "error": f"AR Hosting returned invalid JSON (status {resp.status})"}
85
-
86
- if resp.status != 200 or "url" not in result:
87
  f.close()
88
- return {"ok": False, "error": f"AR Hosting upload failed: {result}"}
89
- f.close()
90
- return {"ok": True, "result_url": result.get("url"), "filename": out_name}
 
91
 
92
  except Exception as e:
93
- return {"ok": False, "error": f"Internal server error: {str(e)}"}
94
 
95
  # -------------------------------
96
- # GET /encode?url=...&filename=... (optional)
97
  # -------------------------------
98
-
99
  @app.get("/encode")
100
  async def encode_get(url: str, filename: str = "file.py"):
101
- # Keep GET for backward compatibility if URL is public
102
  try:
103
  async with aiohttp.ClientSession() as session:
104
  async with session.get(url) as resp:
105
  if resp.status != 200:
106
  return {"ok": False, "error": f"Failed to fetch file ({resp.status})"}
107
  file_bytes = await resp.read()
108
- encoded_bytes, out_name = encode_bytes(file_bytes, filename)
109
-
110
- tmp_path = os.path.join(tempfile.gettempdir(), out_name)
111
  with open(tmp_path, "wb") as f:
112
- f.write(encoded_bytes)
113
 
114
  # Upload to AR Hosting
115
- upload_url = "https://ar-hosting.pages.dev/upload"
116
- form_data = aiohttp.FormData()
117
- f = open(tmp_path, "rb")
118
- form_data.add_field("file", f, filename=out_name, content_type="application/octet-stream")
119
-
120
  async with aiohttp.ClientSession() as session:
121
- async with session.post(upload_url, data=form_data) as resp:
122
- try:
123
- result = await resp.json()
124
- except Exception:
125
- f.close()
126
- return {"ok": False, "error": f"AR Hosting returned invalid JSON (status {resp.status})"}
127
- if resp.status != 200 or "url" not in result:
128
  f.close()
129
- return {"ok": False, "error": f"AR Hosting upload failed: {result}"}
130
- f.close()
131
- return {"ok": True, "result_url": result.get("url"), "filename": out_name}
 
132
 
133
  except Exception as e:
134
- return {"ok": False, "error": f"Internal server error: {str(e)}"}
135
 
136
  # -------------------------------
137
- # ๐Ÿ Run App
138
  # -------------------------------
139
  if __name__ == "__main__":
140
  uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
 
4
  import base64
5
  import uuid
6
  import tempfile
7
+ import shutil
8
+ import subprocess
9
+ from pathlib import Path
10
+ from fastapi import FastAPI, UploadFile, File
11
  import aiohttp
12
  import uvicorn
13
 
14
  app = FastAPI()
15
 
16
  # -------------------------------
17
+ # ๐Ÿ” Custom C-Based Python File Encoder
18
  # -------------------------------
19
 
20
+ C_TEMPLATE = """/*KEY_BYTES*/""" # Replace with your actual C template
21
+ SETUP_PY = """# Your setup.py content""" # Replace with actual setup.py
22
+
23
  def make_zip_bytes(filename: str, content: bytes) -> bytes:
24
  bio = io.BytesIO()
25
  with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
 
29
  def rand_bytes(n):
30
  return os.urandom(n)
31
 
32
+ def compile_c_extension(build_dir: Path):
33
+ (build_dir/"setup.py").write_text(SETUP_PY)
34
+ proc = subprocess.run([os.sys.executable,"setup.py","build_ext","--inplace"],
35
+ cwd=str(build_dir), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=30)
36
+ candidates = list(build_dir.glob("aes_helper*.so")) + list(build_dir.glob("build/lib.*/*.so"))
37
+ if not candidates:
38
+ raise RuntimeError("Compile fail:\n"+proc.stdout.decode())
39
+ return candidates[0]
40
+
41
+ def build_wrapper(cipher_b64, so_b64, so_filename):
42
+ wrapper = f"""# Auto Encrypted by JerryCoder C Encryptor
43
  import base64,zipfile,io,tempfile,os,runpy
44
+ O = base64.b64decode('{cipher_b64}')
45
+ M = base64.b64decode('{so_b64}')
46
+ tmpdir = tempfile.mkdtemp()
47
+ so_path = os.path.join(tmpdir,'{so_filename}')
48
+ with open(so_path,'wb') as f: f.write(M)
49
+ import importlib.machinery as L, importlib.util as U
50
+ loader = L.ExtensionFileLoader('aes_helper',so_path)
51
+ spec = U.spec_from_loader(loader.name,loader)
52
+ mod = U.module_from_spec(spec)
53
+ loader.exec_module(mod)
54
+ try:
55
+ z = mod.decrypt(O)
56
+ extract_dir = tempfile.mkdtemp()
57
+ zipfile.ZipFile(io.BytesIO(z)).extractall(extract_dir)
58
+ py_file = [f for f in os.listdir(extract_dir) if f.endswith('.py')][0]
59
+ runpy.run_path(os.path.join(extract_dir, py_file))
60
+ except Exception as e:
61
+ print('decrypt_error', e)
62
+ finally:
63
+ os.remove(so_path)
64
  """
65
+ return wrapper.encode()
 
66
 
67
+ def encode_bytes(file_bytes: bytes, filename: str):
68
+ tmpdir = Path(tempfile.mkdtemp())
69
+ try:
70
+ # Save original .py
71
+ input_path = tmpdir/filename
72
+ input_path.write_bytes(file_bytes)
73
+ zipped = make_zip_bytes(filename, file_bytes)
74
+ key = rand_bytes(32)
75
+ iv = rand_bytes(16)
76
+ (tmpdir/"aes_helper.c").write_text(C_TEMPLATE.replace("/*KEY_BYTES*/", ",".join(str(x) for x in key)))
77
+ so_path = compile_c_extension(tmpdir)
78
+ so_b64 = base64.b64encode(so_path.read_bytes()).decode()
79
+ cipher_b64 = base64.b64encode(zipped).decode() # Optionally replace with mod.encrypt(zipped)
80
+ wrapper_name = f"{os.path.splitext(filename)[0]}_{uuid.uuid4().hex}_enc.py"
81
+ wrapper_bytes = build_wrapper(cipher_b64, so_b64, so_path.name)
82
+ return wrapper_bytes, wrapper_name
83
+ finally:
84
+ shutil.rmtree(tmpdir, ignore_errors=True)
85
+
86
+ MAX_FILE_SIZE = 5*1024*1024 # 5 MB limit
87
 
88
  # -------------------------------
89
+ # POST /api/encode
90
  # -------------------------------
 
91
  @app.post("/api/encode")
92
  async def encode_post(file: UploadFile = File(...)):
93
  filename = file.filename
 
97
  try:
98
  file_bytes = await file.read()
99
  if len(file_bytes) > MAX_FILE_SIZE:
100
+ return {"ok": False, "error": "File too large (max 5MB)"}
101
 
102
+ wrapper_bytes, wrapper_name = encode_bytes(file_bytes, filename)
103
 
104
+ tmp_path = os.path.join(tempfile.gettempdir(), wrapper_name)
105
  with open(tmp_path, "wb") as f:
106
+ f.write(wrapper_bytes)
107
 
108
  # Upload to AR Hosting
 
 
 
 
 
109
  async with aiohttp.ClientSession() as session:
110
+ form = aiohttp.FormData()
111
+ f = open(tmp_path,"rb")
112
+ form.add_field("file", f, filename=wrapper_name, content_type="application/octet-stream")
113
+ async with session.post("https://ar-hosting.pages.dev/upload", data=form) as resp:
114
+ if resp.status != 200:
 
 
 
115
  f.close()
116
+ return {"ok": False, "error": f"AR Hosting failed with status {resp.status}"}
117
+ result = await resp.json()
118
+ f.close()
119
+ return {"ok": True, "result_url": result.get("url"), "filename": wrapper_name}
120
 
121
  except Exception as e:
122
+ return {"ok": False, "error": f"Internal error: {str(e)}"}
123
 
124
  # -------------------------------
125
+ # GET /encode?url=...&filename=...
126
  # -------------------------------
 
127
  @app.get("/encode")
128
  async def encode_get(url: str, filename: str = "file.py"):
 
129
  try:
130
  async with aiohttp.ClientSession() as session:
131
  async with session.get(url) as resp:
132
  if resp.status != 200:
133
  return {"ok": False, "error": f"Failed to fetch file ({resp.status})"}
134
  file_bytes = await resp.read()
135
+ wrapper_bytes, wrapper_name = encode_bytes(file_bytes, filename)
136
+ tmp_path = os.path.join(tempfile.gettempdir(), wrapper_name)
 
137
  with open(tmp_path, "wb") as f:
138
+ f.write(wrapper_bytes)
139
 
140
  # Upload to AR Hosting
 
 
 
 
 
141
  async with aiohttp.ClientSession() as session:
142
+ form = aiohttp.FormData()
143
+ f = open(tmp_path,"rb")
144
+ form.add_field("file", f, filename=wrapper_name, content_type="application/octet-stream")
145
+ async with session.post("https://ar-hosting.pages.dev/upload", data=form) as resp:
146
+ if resp.status != 200:
 
 
147
  f.close()
148
+ return {"ok": False, "error": f"AR Hosting failed with status {resp.status}"}
149
+ result = await resp.json()
150
+ f.close()
151
+ return {"ok": True, "result_url": result.get("url"), "filename": wrapper_name}
152
 
153
  except Exception as e:
154
+ return {"ok": False, "error": f"Internal error: {str(e)}"}
155
 
156
  # -------------------------------
157
+ # Run App
158
  # -------------------------------
159
  if __name__ == "__main__":
160
  uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))