samarth 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- samarth/__init__.py +1 -0
- samarth/build.py +105 -0
- samarth/cli.py +262 -0
- samarth/detect.py +138 -0
- samarth/guard.py +74 -0
- samarth/strategies.py +230 -0
- samarth-0.2.0.dist-info/METADATA +242 -0
- samarth-0.2.0.dist-info/RECORD +11 -0
- samarth-0.2.0.dist-info/WHEEL +5 -0
- samarth-0.2.0.dist-info/entry_points.txt +2 -0
- samarth-0.2.0.dist-info/top_level.txt +1 -0
samarth/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
samarth/build.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
import tempfile
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import asdict, dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from samarth.detect import Environment, detect_environment
|
|
11
|
+
from samarth.strategies import STRATEGIES, StrategyError, UnsupportedPlatform, pick_best_strategy
|
|
12
|
+
|
|
13
|
+
BuildError = StrategyError # same thing, kept importable under the old name too
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class BuildResult:
|
|
18
|
+
mode: str
|
|
19
|
+
output_dir: Path
|
|
20
|
+
source: Path
|
|
21
|
+
environment: Environment
|
|
22
|
+
tested_here: bool
|
|
23
|
+
manifest_path: Path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _copy_output(compiled: Path, output: str | None) -> Path:
|
|
27
|
+
dest = Path(output).resolve() if output else Path("samarth_output").resolve()
|
|
28
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
29
|
+
for item in compiled.iterdir():
|
|
30
|
+
target = dest / item.name
|
|
31
|
+
if target.exists():
|
|
32
|
+
shutil.rmtree(target) if target.is_dir() else target.unlink()
|
|
33
|
+
shutil.move(str(item), str(target))
|
|
34
|
+
return dest
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _validate(output_dir: Path) -> list[str]:
|
|
38
|
+
problems = []
|
|
39
|
+
if not output_dir.exists() or not any(output_dir.iterdir()):
|
|
40
|
+
problems.append("output directory is empty")
|
|
41
|
+
return problems
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _write_manifest(dest: Path, mode: str, env: Environment, source: Path, problems: list[str]) -> Path:
|
|
45
|
+
manifest = {
|
|
46
|
+
"samarth_mode": mode,
|
|
47
|
+
"source": str(source),
|
|
48
|
+
"built_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
49
|
+
"build_environment": {
|
|
50
|
+
"os": env.os_name,
|
|
51
|
+
"python": f"{env.python_implementation} {'.'.join(map(str, env.python_version))}",
|
|
52
|
+
"arch": env.arch,
|
|
53
|
+
"is_termux": env.is_termux,
|
|
54
|
+
"is_pydroid": env.is_pydroid,
|
|
55
|
+
"pyarmor_version": env.pyarmor_version,
|
|
56
|
+
"nuitka_version": env.nuitka_version,
|
|
57
|
+
},
|
|
58
|
+
"validated": not problems,
|
|
59
|
+
"validation_problems": problems,
|
|
60
|
+
"tested_platforms": [env.os_name + "." + env.arch],
|
|
61
|
+
"untested_platforms_note": (
|
|
62
|
+
"This manifest only reflects a build on the machine listed above. "
|
|
63
|
+
"It is not proof the output runs on any other OS, architecture, "
|
|
64
|
+
"or Python build -- including other Android environments."
|
|
65
|
+
),
|
|
66
|
+
}
|
|
67
|
+
path = dest / "samarth_manifest.json"
|
|
68
|
+
path.write_text(json.dumps(manifest, indent=2))
|
|
69
|
+
return path
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def run(source: str, mode: str | None, output: str | None, **strategy_kwargs) -> BuildResult:
|
|
73
|
+
src = Path(source).resolve()
|
|
74
|
+
if not src.exists():
|
|
75
|
+
raise StrategyError(f"source path does not exist: {src}")
|
|
76
|
+
|
|
77
|
+
env = detect_environment()
|
|
78
|
+
chosen = mode or pick_best_strategy(env)
|
|
79
|
+
if chosen not in STRATEGIES:
|
|
80
|
+
raise StrategyError(f"unknown mode '{chosen}', choose from: {', '.join(STRATEGIES)}")
|
|
81
|
+
|
|
82
|
+
spec = STRATEGIES[chosen]
|
|
83
|
+
compatible, reason = spec["compatible"](env)
|
|
84
|
+
if not compatible:
|
|
85
|
+
raise UnsupportedPlatform(f"'{chosen}' is not usable here: {reason}")
|
|
86
|
+
|
|
87
|
+
workdir = Path(tempfile.mkdtemp(prefix="samarth-"))
|
|
88
|
+
try:
|
|
89
|
+
compiled = spec["func"](src, workdir, env, **strategy_kwargs)
|
|
90
|
+
dest = _copy_output(compiled, output)
|
|
91
|
+
finally:
|
|
92
|
+
shutil.rmtree(workdir, ignore_errors=True)
|
|
93
|
+
|
|
94
|
+
problems = _validate(dest)
|
|
95
|
+
manifest_path = _write_manifest(dest, chosen, env, src, problems)
|
|
96
|
+
|
|
97
|
+
return BuildResult(
|
|
98
|
+
mode=chosen,
|
|
99
|
+
output_dir=dest,
|
|
100
|
+
source=src,
|
|
101
|
+
environment=env,
|
|
102
|
+
tested_here=not problems,
|
|
103
|
+
manifest_path=manifest_path,
|
|
104
|
+
)
|
|
105
|
+
|
samarth/cli.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from samarth import __version__
|
|
11
|
+
from samarth.build import run as run_build
|
|
12
|
+
from samarth.detect import detect_environment
|
|
13
|
+
from samarth.strategies import STRATEGIES
|
|
14
|
+
from samarth.strategies import StrategyError, UnsupportedPlatform
|
|
15
|
+
|
|
16
|
+
BANNER = r"""
|
|
17
|
+
_____ _ __ __ _ ____ _____ _ _
|
|
18
|
+
/ ___| / \ | \/ | / \ | _ \_ _| | | |
|
|
19
|
+
\___ \ / _ \ | |\/| | / _ \ | |_) || | | |_| |
|
|
20
|
+
___) / ___ \| | | |/ ___ \| _ < | | | _ |
|
|
21
|
+
|____/_/ \_\_| |_/_/ \_\_| \_\|_| |_| |_| enc
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
USE_COLOR = sys.stdout.isatty()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _c(code: str, text: str) -> str:
|
|
28
|
+
return f"\033[{code}m{text}\033[0m" if USE_COLOR else text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ok(msg: str) -> None:
|
|
32
|
+
print(f"{_c('32', '[+]')} {msg}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def warn(msg: str) -> None:
|
|
36
|
+
print(f"{_c('33', '[!]')} {msg}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def err(msg: str) -> None:
|
|
40
|
+
print(f"{_c('31', '[-]')} {msg}", file=sys.stderr)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def banner() -> None:
|
|
44
|
+
print(_c("36", BANNER))
|
|
45
|
+
print(f"SAMARTH ENC v{__version__}\n")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
MODE_BY_MENU_NUMBER = {
|
|
49
|
+
"1": "universal",
|
|
50
|
+
"2": "pyarmor",
|
|
51
|
+
"3": "nuitka",
|
|
52
|
+
"4": "combined",
|
|
53
|
+
"5": "termux-native",
|
|
54
|
+
"6": "pydroid-compat",
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def do_build(mode: str, source: str, output: str | None) -> int:
|
|
59
|
+
ok(f"mode: {STRATEGIES[mode]['label']}")
|
|
60
|
+
ok(f"source: {source}")
|
|
61
|
+
try:
|
|
62
|
+
result = run_build(source, mode, output)
|
|
63
|
+
except UnsupportedPlatform as exc:
|
|
64
|
+
err(f"not compatible with this environment: {exc}")
|
|
65
|
+
return 1
|
|
66
|
+
except StrategyError as exc:
|
|
67
|
+
err(str(exc))
|
|
68
|
+
return 1
|
|
69
|
+
|
|
70
|
+
ok("build completed")
|
|
71
|
+
ok(f"output saved: {result.output_dir}")
|
|
72
|
+
ok(f"manifest: {result.manifest_path}")
|
|
73
|
+
if not result.tested_here:
|
|
74
|
+
warn("output failed validation, check samarth_manifest.json")
|
|
75
|
+
return 0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def do_detect() -> int:
|
|
79
|
+
env = detect_environment()
|
|
80
|
+
print(env.summary())
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def do_check() -> int:
|
|
85
|
+
env = detect_environment()
|
|
86
|
+
print("Compatibility by mode, on this machine:\n")
|
|
87
|
+
for name, spec in STRATEGIES.items():
|
|
88
|
+
compatible, reason = spec["compatible"](env)
|
|
89
|
+
tag = ok if compatible else err
|
|
90
|
+
tag(f"{spec['label']:<30} {reason}")
|
|
91
|
+
return 0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def do_deps() -> int:
|
|
95
|
+
env = detect_environment()
|
|
96
|
+
print("Dependency check:\n")
|
|
97
|
+
(ok if env.pyarmor_version else warn)(f"pyarmor: {env.pyarmor_version or 'not installed'}")
|
|
98
|
+
(ok if env.nuitka_version else warn)(f"nuitka: {env.nuitka_version or 'not installed'}")
|
|
99
|
+
(ok if env.compiler else warn)(f"compiler: {env.compiler or 'not found'}")
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def do_integrity(path: str, expected_hash: str) -> int:
|
|
104
|
+
target = Path(path)
|
|
105
|
+
if not target.exists():
|
|
106
|
+
err(f"file not found: {target}")
|
|
107
|
+
return 1
|
|
108
|
+
digest = hashlib.sha256(target.read_bytes()).hexdigest()
|
|
109
|
+
if digest == expected_hash:
|
|
110
|
+
ok("integrity check passed")
|
|
111
|
+
return 0
|
|
112
|
+
err(f"hash mismatch, computed: {digest}")
|
|
113
|
+
return 1
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def do_debug_file(path: str) -> int:
|
|
117
|
+
target = Path(path)
|
|
118
|
+
if not target.exists():
|
|
119
|
+
err(f"file not found: {target}")
|
|
120
|
+
return 1
|
|
121
|
+
ok(f"running: {target}")
|
|
122
|
+
result = subprocess.run([sys.executable, str(target)], capture_output=True, text=True)
|
|
123
|
+
print("--- stdout ---")
|
|
124
|
+
print(result.stdout.strip() or "(empty)")
|
|
125
|
+
print("--- stderr ---")
|
|
126
|
+
print(result.stderr.strip() or "(empty)")
|
|
127
|
+
(ok if result.returncode == 0 else err)(f"exit code: {result.returncode}")
|
|
128
|
+
return result.returncode
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def do_diagnostics(output_dir: str) -> int:
|
|
132
|
+
manifest = Path(output_dir) / "samarth_manifest.json"
|
|
133
|
+
if not manifest.exists():
|
|
134
|
+
warn(f"no manifest found at {manifest}")
|
|
135
|
+
return 1
|
|
136
|
+
data = json.loads(manifest.read_text())
|
|
137
|
+
print(json.dumps(data, indent=2))
|
|
138
|
+
return 0
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def run_menu() -> int:
|
|
142
|
+
banner()
|
|
143
|
+
options = [
|
|
144
|
+
"[1] Universal Python Build",
|
|
145
|
+
"[2] PyArmor Protection",
|
|
146
|
+
"[3] Native Compilation",
|
|
147
|
+
"[4] PyArmor + Nuitka",
|
|
148
|
+
"[5] Termux Build",
|
|
149
|
+
"[6] Pydroid Compatibility Build",
|
|
150
|
+
"[7] Automatic Platform Detection",
|
|
151
|
+
"[8] Compatibility Checker",
|
|
152
|
+
"[9] Dependency Checker",
|
|
153
|
+
"[10] Integrity Checker",
|
|
154
|
+
"[11] Debug Protected File",
|
|
155
|
+
"[12] Build Diagnostics",
|
|
156
|
+
"[0] Exit",
|
|
157
|
+
]
|
|
158
|
+
print("\n".join(options))
|
|
159
|
+
choice = input("\n> ").strip()
|
|
160
|
+
|
|
161
|
+
if choice == "0":
|
|
162
|
+
return 0
|
|
163
|
+
if choice in MODE_BY_MENU_NUMBER:
|
|
164
|
+
source = input("Source path: ").strip()
|
|
165
|
+
output = input("Output dir [samarth_output]: ").strip() or None
|
|
166
|
+
return do_build(MODE_BY_MENU_NUMBER[choice], source, output)
|
|
167
|
+
if choice == "7":
|
|
168
|
+
return do_detect()
|
|
169
|
+
if choice == "8":
|
|
170
|
+
return do_check()
|
|
171
|
+
if choice == "9":
|
|
172
|
+
return do_deps()
|
|
173
|
+
if choice == "10":
|
|
174
|
+
path = input("File path: ").strip()
|
|
175
|
+
expected = input("Expected SHA-256: ").strip()
|
|
176
|
+
return do_integrity(path, expected)
|
|
177
|
+
if choice == "11":
|
|
178
|
+
path = input("File path: ").strip()
|
|
179
|
+
return do_debug_file(path)
|
|
180
|
+
if choice == "12":
|
|
181
|
+
out_dir = input("Build output dir [samarth_output]: ").strip() or "samarth_output"
|
|
182
|
+
return do_diagnostics(out_dir)
|
|
183
|
+
|
|
184
|
+
err("invalid choice")
|
|
185
|
+
return 1
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
189
|
+
parser = argparse.ArgumentParser(prog="samarth", description="SAMARTH ENC build tool")
|
|
190
|
+
sub = parser.add_subparsers(dest="command")
|
|
191
|
+
|
|
192
|
+
b = sub.add_parser("build", help="run a build strategy")
|
|
193
|
+
b.add_argument("source")
|
|
194
|
+
b.add_argument("--mode", choices=list(STRATEGIES), default=None,
|
|
195
|
+
help="omit to auto-select based on the detected environment")
|
|
196
|
+
b.add_argument("--output", default=None)
|
|
197
|
+
|
|
198
|
+
sub.add_parser("detect", help="show environment detection report")
|
|
199
|
+
sub.add_parser("check", help="show mode compatibility for this machine")
|
|
200
|
+
sub.add_parser("deps", help="check pyarmor/nuitka/compiler availability")
|
|
201
|
+
|
|
202
|
+
i = sub.add_parser("integrity", help="verify a file's sha256 hash")
|
|
203
|
+
i.add_argument("path")
|
|
204
|
+
i.add_argument("expected_sha256")
|
|
205
|
+
|
|
206
|
+
d = sub.add_parser("debug", help="run a protected file and show its output")
|
|
207
|
+
d.add_argument("path")
|
|
208
|
+
|
|
209
|
+
g = sub.add_parser("diagnostics", help="print a build's manifest")
|
|
210
|
+
g.add_argument("output_dir", nargs="?", default="samarth_output")
|
|
211
|
+
|
|
212
|
+
return parser
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def main(argv: list[str] | None = None) -> int:
|
|
216
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
217
|
+
|
|
218
|
+
if not argv:
|
|
219
|
+
try:
|
|
220
|
+
return run_menu()
|
|
221
|
+
except KeyboardInterrupt:
|
|
222
|
+
print()
|
|
223
|
+
return 130
|
|
224
|
+
|
|
225
|
+
args = build_parser().parse_args(argv)
|
|
226
|
+
try:
|
|
227
|
+
if args.command == "build":
|
|
228
|
+
banner()
|
|
229
|
+
if args.mode:
|
|
230
|
+
return do_build(args.mode, args.source, args.output)
|
|
231
|
+
return _build_auto(args)
|
|
232
|
+
if args.command == "detect":
|
|
233
|
+
return do_detect()
|
|
234
|
+
if args.command == "check":
|
|
235
|
+
return do_check()
|
|
236
|
+
if args.command == "deps":
|
|
237
|
+
return do_deps()
|
|
238
|
+
if args.command == "integrity":
|
|
239
|
+
return do_integrity(args.path, args.expected_sha256)
|
|
240
|
+
if args.command == "debug":
|
|
241
|
+
return do_debug_file(args.path)
|
|
242
|
+
if args.command == "diagnostics":
|
|
243
|
+
return do_diagnostics(args.output_dir)
|
|
244
|
+
except KeyboardInterrupt:
|
|
245
|
+
err("cancelled")
|
|
246
|
+
return 130
|
|
247
|
+
|
|
248
|
+
build_parser().print_help()
|
|
249
|
+
return 1
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _build_auto(args: argparse.Namespace) -> int:
|
|
253
|
+
from samarth.strategies import pick_best_strategy
|
|
254
|
+
env = detect_environment()
|
|
255
|
+
mode = pick_best_strategy(env)
|
|
256
|
+
ok(f"auto-selected mode: {STRATEGIES[mode]['label']}")
|
|
257
|
+
return do_build(mode, args.source, args.output)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == "__main__":
|
|
261
|
+
raise SystemExit(main())
|
|
262
|
+
|
samarth/detect.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def is_termux() -> bool:
|
|
12
|
+
return "com.termux" in os.environ.get("PREFIX", "") or "TERMUX_VERSION" in os.environ
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def is_pydroid() -> bool:
|
|
16
|
+
return "ru.iiec.pydroid3" in sys.executable or "ru.iiec.pydroid3" in sys.prefix
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_android() -> bool:
|
|
20
|
+
if is_termux() or is_pydroid():
|
|
21
|
+
return True
|
|
22
|
+
return os.path.exists("/system/build.prop")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def arch() -> str:
|
|
26
|
+
machine = platform.machine().lower()
|
|
27
|
+
aliases = {"amd64": "x86_64", "aarch64": "arm64", "arm64": "arm64", "armv7l": "armv7"}
|
|
28
|
+
return aliases.get(machine, machine)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def tool_version(name: str) -> str | None:
|
|
32
|
+
path = shutil.which(name)
|
|
33
|
+
if path is None:
|
|
34
|
+
return None
|
|
35
|
+
try:
|
|
36
|
+
out = subprocess.run([name, "--version"], capture_output=True, text=True, timeout=10)
|
|
37
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
38
|
+
return "unknown"
|
|
39
|
+
text = (out.stdout or out.stderr).strip().splitlines()
|
|
40
|
+
return text[0] if text else "unknown"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def find_compiler() -> str | None:
|
|
44
|
+
for name in ("clang", "gcc", "cc"):
|
|
45
|
+
if shutil.which(name):
|
|
46
|
+
return name
|
|
47
|
+
if platform.system() == "Windows" and shutil.which("cl"):
|
|
48
|
+
return "cl"
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def pyarmor_target_platform() -> str:
|
|
53
|
+
"""Best-guess PyArmor --platform value for the current environment.
|
|
54
|
+
|
|
55
|
+
Termux is a documented exception: PyArmor's own install notes say some
|
|
56
|
+
Termux builds need `linux.aarch64`/`linux.armv7` rather than the
|
|
57
|
+
`android.*` runtime, see pyarmor issue #1674.
|
|
58
|
+
"""
|
|
59
|
+
system = platform.system()
|
|
60
|
+
a = arch()
|
|
61
|
+
|
|
62
|
+
if is_termux():
|
|
63
|
+
return {"arm64": "linux.aarch64", "armv7": "linux.armv7"}.get(a, f"linux.{a}")
|
|
64
|
+
if is_pydroid() or is_android():
|
|
65
|
+
return {"arm64": "android.aarch64", "armv7": "android.armv7"}.get(a, f"android.{a}")
|
|
66
|
+
if system == "Linux":
|
|
67
|
+
return f"linux.{a}"
|
|
68
|
+
if system == "Darwin":
|
|
69
|
+
return f"darwin.{a}"
|
|
70
|
+
if system == "Windows":
|
|
71
|
+
return f"windows.{a}"
|
|
72
|
+
return f"{system.lower()}.{a}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class Environment:
|
|
77
|
+
os_name: str
|
|
78
|
+
python_implementation: str
|
|
79
|
+
python_version: tuple
|
|
80
|
+
arch: str
|
|
81
|
+
is_android: bool
|
|
82
|
+
is_termux: bool
|
|
83
|
+
is_pydroid: bool
|
|
84
|
+
compiler: str | None
|
|
85
|
+
pyarmor_version: str | None
|
|
86
|
+
nuitka_version: str | None
|
|
87
|
+
pyarmor_platform: str
|
|
88
|
+
warnings: list = field(default_factory=list)
|
|
89
|
+
|
|
90
|
+
def summary(self) -> str:
|
|
91
|
+
lines = [
|
|
92
|
+
f"OS : {self.os_name}",
|
|
93
|
+
f"Python : {self.python_implementation} {self.python_version[0]}.{self.python_version[1]}.{self.python_version[2]}",
|
|
94
|
+
f"Architecture : {self.arch}",
|
|
95
|
+
f"Android : {self.is_android} (Termux: {self.is_termux}, Pydroid: {self.is_pydroid})",
|
|
96
|
+
f"C compiler : {self.compiler or 'not found'}",
|
|
97
|
+
f"PyArmor : {self.pyarmor_version or 'not installed'}",
|
|
98
|
+
f"Nuitka : {self.nuitka_version or 'not installed'}",
|
|
99
|
+
f"PyArmor target : {self.pyarmor_platform}",
|
|
100
|
+
]
|
|
101
|
+
if self.warnings:
|
|
102
|
+
lines.append("Warnings:")
|
|
103
|
+
lines += [f" - {w}" for w in self.warnings]
|
|
104
|
+
return "\n".join(lines)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def detect_environment() -> Environment:
|
|
108
|
+
warnings: list = []
|
|
109
|
+
android = is_android()
|
|
110
|
+
termux = is_termux()
|
|
111
|
+
pydroid = is_pydroid()
|
|
112
|
+
|
|
113
|
+
if pydroid:
|
|
114
|
+
warnings.append(
|
|
115
|
+
"Pydroid does not expose a C compiler to Nuitka; only Universal "
|
|
116
|
+
"Python mode and experimental PyArmor-only mode are possible here."
|
|
117
|
+
)
|
|
118
|
+
if termux:
|
|
119
|
+
warnings.append(
|
|
120
|
+
"Nuitka on Termux only supports --module builds (Nuitka 2.6.7+), "
|
|
121
|
+
"never standalone/onefile."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
return Environment(
|
|
125
|
+
os_name=platform.system(),
|
|
126
|
+
python_implementation=platform.python_implementation(),
|
|
127
|
+
python_version=sys.version_info[:3],
|
|
128
|
+
arch=arch(),
|
|
129
|
+
is_android=android,
|
|
130
|
+
is_termux=termux,
|
|
131
|
+
is_pydroid=pydroid,
|
|
132
|
+
compiler=find_compiler(),
|
|
133
|
+
pyarmor_version=tool_version("pyarmor"),
|
|
134
|
+
nuitka_version=tool_version("nuitka"),
|
|
135
|
+
pyarmor_platform=pyarmor_target_platform(),
|
|
136
|
+
warnings=warnings,
|
|
137
|
+
)
|
|
138
|
+
|
samarth/guard.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import platform
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
DEBUGGER_MODULES = ("pdb", "pydevd", "debugpy", "bdb")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _fail(message: str) -> None:
|
|
12
|
+
print(f"samarth: {message}", file=sys.stderr)
|
|
13
|
+
raise SystemExit(1)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def refuse_if_debugger() -> None:
|
|
17
|
+
if sys.gettrace() is not None:
|
|
18
|
+
_fail("debugger or profiler attached, refusing to run")
|
|
19
|
+
|
|
20
|
+
monitoring = getattr(sys, "monitoring", None)
|
|
21
|
+
if monitoring is not None:
|
|
22
|
+
try:
|
|
23
|
+
if monitoring.get_tool(monitoring.DEBUGGER_ID) is not None:
|
|
24
|
+
_fail("debugger registered via sys.monitoring, refusing to run")
|
|
25
|
+
except AttributeError:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
loaded = DEBUGGER_MODULES
|
|
29
|
+
active = [m for m in loaded if m in sys.modules]
|
|
30
|
+
if active:
|
|
31
|
+
_fail(f"debugger module loaded ({active[0]}), refusing to run")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def timing_check(threshold: float = 0.25) -> None:
|
|
35
|
+
start = time.perf_counter()
|
|
36
|
+
sum(range(200_000))
|
|
37
|
+
if time.perf_counter() - start > threshold:
|
|
38
|
+
_fail("execution timing abnormal, possible single-step debugging")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def verify_integrity(path: str, expected_sha256: str) -> None:
|
|
42
|
+
with open(path, "rb") as f:
|
|
43
|
+
digest = hashlib.sha256(f.read()).hexdigest()
|
|
44
|
+
if digest != expected_sha256:
|
|
45
|
+
_fail("integrity check failed, file does not match expected hash")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def require_python(min_version: tuple[int, int], max_version: tuple[int, int] | None = None) -> None:
|
|
49
|
+
current = sys.version_info[:2]
|
|
50
|
+
if current < min_version or (max_version and current > max_version):
|
|
51
|
+
hi = f"{max_version[0]}.{max_version[1]}" if max_version else "latest"
|
|
52
|
+
_fail(f"requires Python {min_version[0]}.{min_version[1]}-{hi}, found {current[0]}.{current[1]}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def require_platform(allowed: tuple[str, ...]) -> None:
|
|
56
|
+
current = platform.system()
|
|
57
|
+
if current not in allowed:
|
|
58
|
+
_fail(f"unsupported platform {current}, this build supports {', '.join(allowed)}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def run_all(
|
|
62
|
+
expected_sha256: str | None = None,
|
|
63
|
+
file_path: str | None = None,
|
|
64
|
+
min_python: tuple[int, int] = (3, 10),
|
|
65
|
+
max_python: tuple[int, int] = (3, 13),
|
|
66
|
+
allowed_platforms: tuple[str, ...] = ("Linux", "Windows", "Darwin"),
|
|
67
|
+
) -> None:
|
|
68
|
+
refuse_if_debugger()
|
|
69
|
+
timing_check()
|
|
70
|
+
require_python(min_python, max_python)
|
|
71
|
+
require_platform(allowed_platforms)
|
|
72
|
+
if expected_sha256 and file_path:
|
|
73
|
+
verify_integrity(file_path, expected_sha256)
|
|
74
|
+
|
samarth/strategies.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import compileall
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from samarth.detect import Environment, tool_version
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class StrategyError(Exception):
|
|
13
|
+
"""Raised when a strategy can't run, or runs but produces no usable output."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnsupportedPlatform(StrategyError):
|
|
17
|
+
"""Raised when a strategy refuses to run because this environment can't support it."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _run(cmd: list[str]) -> None:
|
|
21
|
+
print(" $ " + " ".join(cmd))
|
|
22
|
+
try:
|
|
23
|
+
result = subprocess.run(cmd)
|
|
24
|
+
except OSError as exc:
|
|
25
|
+
raise StrategyError(f"failed to launch {cmd[0]}: {exc}") from exc
|
|
26
|
+
if result.returncode != 0:
|
|
27
|
+
raise StrategyError(f"{cmd[0]} exited with code {result.returncode}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _require_tool(name: str) -> None:
|
|
31
|
+
if shutil.which(name) is None:
|
|
32
|
+
raise StrategyError(f"'{name}' not found on PATH. Install it with: pip install {name}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def universal_python(source: Path, workdir: Path, env: Environment) -> Path:
|
|
36
|
+
"""No protection at all. Copies source, precompiles to .pyc. Works everywhere."""
|
|
37
|
+
out = workdir / "universal_out"
|
|
38
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
|
|
40
|
+
if source.is_dir():
|
|
41
|
+
dest = out / source.name
|
|
42
|
+
shutil.copytree(source, dest)
|
|
43
|
+
compileall.compile_dir(str(dest), quiet=1)
|
|
44
|
+
else:
|
|
45
|
+
dest = out / source.name
|
|
46
|
+
shutil.copy2(source, dest)
|
|
47
|
+
compileall.compile_file(str(dest), quiet=1)
|
|
48
|
+
|
|
49
|
+
return out
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def pyarmor_only(source: Path, workdir: Path, env: Environment, target_platform: str | None = None) -> Path:
|
|
53
|
+
"""PyArmor bytecode encryption, no compilation step."""
|
|
54
|
+
_require_tool("pyarmor")
|
|
55
|
+
out = workdir / "pyarmor_out"
|
|
56
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
|
|
58
|
+
cmd = ["pyarmor", "gen", "-O", str(out)]
|
|
59
|
+
plat = target_platform or env.pyarmor_platform
|
|
60
|
+
if plat:
|
|
61
|
+
cmd += ["--platform", plat]
|
|
62
|
+
cmd.append(str(source))
|
|
63
|
+
|
|
64
|
+
_run(cmd)
|
|
65
|
+
if not any(out.iterdir()):
|
|
66
|
+
raise StrategyError("pyarmor produced no output")
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def nuitka_only(source: Path, workdir: Path, env: Environment, mode: str) -> Path:
|
|
71
|
+
"""Compile source directly with Nuitka, no PyArmor layer."""
|
|
72
|
+
if env.is_pydroid:
|
|
73
|
+
raise UnsupportedPlatform("Pydroid has no C compiler available to Nuitka")
|
|
74
|
+
if env.is_termux and mode != "module":
|
|
75
|
+
raise UnsupportedPlatform("Termux only supports Nuitka --module builds, not standalone/onefile")
|
|
76
|
+
if env.compiler is None:
|
|
77
|
+
raise StrategyError("no C compiler found (install gcc/clang, or MSVC on Windows)")
|
|
78
|
+
|
|
79
|
+
_require_tool("nuitka")
|
|
80
|
+
out = workdir / "nuitka_out"
|
|
81
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
|
|
83
|
+
cmd = [sys.executable, "-m", "nuitka", f"--output-dir={out}"]
|
|
84
|
+
cmd += ["--module", str(source)] if mode == "module" else ["--standalone", "--onefile", str(source)]
|
|
85
|
+
_run(cmd)
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def pyarmor_nuitka(source: Path, workdir: Path, env: Environment, mode: str, entry: str | None = None) -> Path:
|
|
90
|
+
"""PyArmor encrypts first, Nuitka compiles the result. Desktop only."""
|
|
91
|
+
if env.is_android:
|
|
92
|
+
raise UnsupportedPlatform(
|
|
93
|
+
"PyArmor + Nuitka requires a native compiler toolchain Android doesn't "
|
|
94
|
+
"provide to Nuitka. Use 'termux-native' or 'pyarmor-only' instead."
|
|
95
|
+
)
|
|
96
|
+
if env.compiler is None:
|
|
97
|
+
raise StrategyError("no C compiler found (install gcc/clang, or MSVC on Windows)")
|
|
98
|
+
|
|
99
|
+
protected = pyarmor_only(source, workdir, env)
|
|
100
|
+
target = protected / (entry or source.name)
|
|
101
|
+
if not target.exists():
|
|
102
|
+
raise StrategyError(f"'{entry or source.name}' not found in PyArmor output, pass --entry")
|
|
103
|
+
|
|
104
|
+
_require_tool("nuitka")
|
|
105
|
+
out = workdir / "nuitka_out"
|
|
106
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
|
|
108
|
+
cmd = [sys.executable, "-m", "nuitka", f"--output-dir={out}"]
|
|
109
|
+
cmd += ["--module", str(target)] if mode == "module" else ["--standalone", "--onefile", str(target)]
|
|
110
|
+
_run(cmd)
|
|
111
|
+
|
|
112
|
+
shutil.rmtree(protected, ignore_errors=True)
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def termux_native(source: Path, workdir: Path, env: Environment, use_nuitka: bool = True) -> Path:
|
|
117
|
+
"""PyArmor (linux.* platform per PyArmor's own Termux notes) plus optional
|
|
118
|
+
Nuitka --module compilation. Must run inside Termux on the target device."""
|
|
119
|
+
if not env.is_termux:
|
|
120
|
+
raise UnsupportedPlatform(
|
|
121
|
+
"termux-native must run inside Termux on the target device; "
|
|
122
|
+
"builds from another machine cannot be copied onto Termux and work."
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
protected = pyarmor_only(source, workdir, env)
|
|
126
|
+
|
|
127
|
+
if not use_nuitka:
|
|
128
|
+
return protected
|
|
129
|
+
|
|
130
|
+
nuitka_ver = tool_version("nuitka")
|
|
131
|
+
if nuitka_ver is None:
|
|
132
|
+
raise StrategyError("nuitka not installed in Termux (pip install nuitka)")
|
|
133
|
+
if env.compiler is None:
|
|
134
|
+
raise StrategyError("no compiler found in Termux (pkg install clang)")
|
|
135
|
+
|
|
136
|
+
target = protected / source.name
|
|
137
|
+
if not target.exists():
|
|
138
|
+
raise StrategyError(f"'{source.name}' not found in PyArmor output")
|
|
139
|
+
|
|
140
|
+
out = workdir / "nuitka_out"
|
|
141
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
_run([sys.executable, "-m", "nuitka", "--module", f"--output-dir={out}", str(target)])
|
|
143
|
+
|
|
144
|
+
shutil.rmtree(protected, ignore_errors=True)
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def pydroid_compat(source: Path, workdir: Path, env: Environment, attempt_pyarmor: bool = False) -> Path:
|
|
149
|
+
"""Pydroid has no compiler Nuitka can use. By default this falls back to
|
|
150
|
+
Universal Python mode, which is guaranteed to run. PyArmor-only is offered
|
|
151
|
+
as an explicit opt-in because it is not verified to work inside Pydroid's
|
|
152
|
+
bundled interpreter -- its Android runtime libraries are built against
|
|
153
|
+
Termux/NDK Python, not Pydroid's own build."""
|
|
154
|
+
if not attempt_pyarmor:
|
|
155
|
+
return universal_python(source, workdir, env)
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
return pyarmor_only(source, workdir, env, target_platform=env.pyarmor_platform)
|
|
159
|
+
except StrategyError as exc:
|
|
160
|
+
raise StrategyError(
|
|
161
|
+
f"PyArmor attempt failed ({exc}); falling back is recommended "
|
|
162
|
+
f"-- rerun with attempt_pyarmor=False for Universal Python mode"
|
|
163
|
+
) from exc
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
STRATEGIES = {
|
|
167
|
+
"universal": {
|
|
168
|
+
"func": universal_python,
|
|
169
|
+
"label": "Universal Python Build",
|
|
170
|
+
"compatible": lambda env: (True, "runs on any CPython interpreter"),
|
|
171
|
+
},
|
|
172
|
+
"pyarmor": {
|
|
173
|
+
"func": pyarmor_only,
|
|
174
|
+
"label": "PyArmor Protection",
|
|
175
|
+
"compatible": lambda env: (
|
|
176
|
+
(True, "pyarmor on PATH") if tool_version("pyarmor") else (False, "pyarmor not installed")
|
|
177
|
+
),
|
|
178
|
+
},
|
|
179
|
+
"nuitka": {
|
|
180
|
+
"func": nuitka_only,
|
|
181
|
+
"label": "Native Compilation",
|
|
182
|
+
"compatible": lambda env: (
|
|
183
|
+
(False, "Pydroid has no usable compiler") if env.is_pydroid
|
|
184
|
+
else (False, "nuitka not installed") if env.nuitka_version is None
|
|
185
|
+
else (False, "no compiler available") if env.compiler is None
|
|
186
|
+
else (True, f"nuitka + {env.compiler}")
|
|
187
|
+
),
|
|
188
|
+
},
|
|
189
|
+
"combined": {
|
|
190
|
+
"func": pyarmor_nuitka,
|
|
191
|
+
"label": "PyArmor + Nuitka",
|
|
192
|
+
"compatible": lambda env: (
|
|
193
|
+
(False, "not supported on Android") if env.is_android
|
|
194
|
+
else (False, "pyarmor not installed") if env.pyarmor_version is None
|
|
195
|
+
else (False, "nuitka not installed") if env.nuitka_version is None
|
|
196
|
+
else (False, "no compiler available") if env.compiler is None
|
|
197
|
+
else (True, "desktop toolchain present")
|
|
198
|
+
),
|
|
199
|
+
},
|
|
200
|
+
"termux-native": {
|
|
201
|
+
"func": termux_native,
|
|
202
|
+
"label": "Termux Build",
|
|
203
|
+
"compatible": lambda env: (
|
|
204
|
+
(True, "running inside Termux") if env.is_termux
|
|
205
|
+
else (False, "must run inside Termux on the target device")
|
|
206
|
+
),
|
|
207
|
+
},
|
|
208
|
+
"pydroid-compat": {
|
|
209
|
+
"func": pydroid_compat,
|
|
210
|
+
"label": "Pydroid Compatibility Build",
|
|
211
|
+
"compatible": lambda env: (
|
|
212
|
+
(True, "falls back to Universal Python mode") if env.is_pydroid
|
|
213
|
+
else (False, "only meaningful when running inside Pydroid")
|
|
214
|
+
),
|
|
215
|
+
},
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def pick_best_strategy(env: Environment) -> str:
|
|
220
|
+
"""Automatic mode selection: strongest protection that's actually compatible."""
|
|
221
|
+
if env.is_pydroid:
|
|
222
|
+
return "pydroid-compat"
|
|
223
|
+
if env.is_termux:
|
|
224
|
+
return "termux-native"
|
|
225
|
+
if env.compiler and env.pyarmor_version and env.nuitka_version:
|
|
226
|
+
return "combined"
|
|
227
|
+
if env.pyarmor_version:
|
|
228
|
+
return "pyarmor"
|
|
229
|
+
return "universal"
|
|
230
|
+
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: samarth
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Multi-platform Python protection pipeline — PyArmor, Nuitka, and pure-Python modes
|
|
5
|
+
Author-email: Samarth <creatorpc@proton.me>
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
13
|
+
Requires-Python: <3.14,>=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: pyarmor>=9.0
|
|
16
|
+
Requires-Dist: nuitka>=2.0
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest; extra == "dev"
|
|
19
|
+
|
|
20
|
+
# SAMARTH ENC
|
|
21
|
+
|
|
22
|
+
A Python build tool that chains multiple protection strategies — PyArmor
|
|
23
|
+
bytecode encryption, Nuitka native compilation, or both — into one command.
|
|
24
|
+
It auto-detects your environment and picks the strongest strategy that
|
|
25
|
+
actually works there, rather than silently producing output that won't run.
|
|
26
|
+
|
|
27
|
+
## Platform support
|
|
28
|
+
|
|
29
|
+
| Platform | Universal | PyArmor | Nuitka | Combined |
|
|
30
|
+
|---|---|---|---|---|
|
|
31
|
+
| Linux x86_64 | ✓ | ✓ | ✓ | ✓ |
|
|
32
|
+
| Linux ARM64 | ✓ | ✓ | ✓ | ✓ |
|
|
33
|
+
| Windows x86_64 | ✓ | ✓ | ✓ | ✓ |
|
|
34
|
+
| macOS x86_64/ARM64 | ✓ | ✓ | ✓ | ✓ |
|
|
35
|
+
| Termux (ARM64) | ✓ | ✓ (linux.aarch64) | ✓ (module only, Nuitka 2.6.7+) | ✗ |
|
|
36
|
+
| Pydroid 3 | ✓ | Experimental | ✗ | ✗ |
|
|
37
|
+
|
|
38
|
+
**Notes:**
|
|
39
|
+
- Nuitka standalone/onefile builds don't work reliably on Termux due to
|
|
40
|
+
Android's dynamic linker not matching standard Linux assumptions.
|
|
41
|
+
- Pydroid has no accessible C compiler. PyArmor works experimentally there
|
|
42
|
+
(its Android runtime is built for Termux/NDK Python, not Pydroid's own
|
|
43
|
+
build — test before shipping).
|
|
44
|
+
- Cross-compiled artifacts are never portable. Build on the target device or
|
|
45
|
+
use PyArmor's `--platform` flag for cross-compilation.
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install samarth
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
If you want PyArmor and/or Nuitka protection (not just Universal mode):
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install pyarmor nuitka
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Nuitka requires a C compiler:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
# Debian/Ubuntu/VPS
|
|
63
|
+
sudo apt install build-essential patchelf
|
|
64
|
+
|
|
65
|
+
# Termux
|
|
66
|
+
pkg install clang patchelf
|
|
67
|
+
|
|
68
|
+
# Windows — Nuitka will offer to download MinGW64 on first run
|
|
69
|
+
# macOS
|
|
70
|
+
xcode-select --install
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**Termux-specific PyArmor fix** (if you get a `.so` load error):
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
patchelf --add-needed libpython3.11.so.0.1 \
|
|
77
|
+
$(python -c "import pyarmor; print(__import__('pathlib').Path(pyarmor.__file__).parent)")/cli/core/android/aarch64/pytransform3.so
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Replace `3.11` with your actual Python version.
|
|
81
|
+
|
|
82
|
+
## Usage
|
|
83
|
+
|
|
84
|
+
### Interactive menu
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
samarth
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
SAMARTH ENC
|
|
92
|
+
|
|
93
|
+
[1] Universal Python Build
|
|
94
|
+
[2] PyArmor Protection
|
|
95
|
+
[3] Native Compilation
|
|
96
|
+
[4] PyArmor + Nuitka
|
|
97
|
+
[5] Termux Build
|
|
98
|
+
[6] Pydroid Compatibility Build
|
|
99
|
+
[7] Automatic Platform Detection
|
|
100
|
+
[8] Compatibility Checker
|
|
101
|
+
[9] Dependency Checker
|
|
102
|
+
[10] Integrity Checker
|
|
103
|
+
[11] Debug Protected File
|
|
104
|
+
[12] Build Diagnostics
|
|
105
|
+
[0] Exit
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### CLI subcommands
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
samarth build app.py # auto-select best mode
|
|
112
|
+
samarth build app.py --mode pyarmor # specific mode
|
|
113
|
+
samarth build mypackage/ --mode combined --output dist/
|
|
114
|
+
|
|
115
|
+
samarth detect # show OS/arch/tool report
|
|
116
|
+
samarth check # show which modes work here
|
|
117
|
+
samarth deps # check tool availability
|
|
118
|
+
|
|
119
|
+
samarth integrity app.py <sha256-hash> # verify file hasn't changed
|
|
120
|
+
samarth debug dist/app.py # run and show stdout/stderr
|
|
121
|
+
samarth diagnostics samarth_output/ # print build manifest
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Build modes
|
|
125
|
+
|
|
126
|
+
**universal** — copies source and precompiles `.pyc`. No external tools
|
|
127
|
+
needed. Works on every CPython 3.10–3.13 environment including Pydroid.
|
|
128
|
+
Provides no meaningful protection, just bytecode instead of source.
|
|
129
|
+
|
|
130
|
+
**pyarmor** — PyArmor bytecode encryption. Output requires the
|
|
131
|
+
`pyarmor_runtime_*` package at runtime. Supports cross-compilation via
|
|
132
|
+
`--platform` (see PyArmor docs). The only practical option for Pydroid and
|
|
133
|
+
the safer Termux choice.
|
|
134
|
+
|
|
135
|
+
**nuitka** — Nuitka compiles source to native code. No PyArmor layer.
|
|
136
|
+
Requires a C compiler. On Termux, only `--mode module` is supported
|
|
137
|
+
(Nuitka 2.6.7+). Not available on Pydroid.
|
|
138
|
+
|
|
139
|
+
**combined** — PyArmor encrypts first, Nuitka compiles the result. Strongest
|
|
140
|
+
desktop protection. Not supported on Android because Nuitka needs a full
|
|
141
|
+
native toolchain Android doesn't provide in Termux/Pydroid.
|
|
142
|
+
|
|
143
|
+
**termux-native** — Must run inside Termux on the target device. Runs
|
|
144
|
+
PyArmor with the correct `linux.*` platform string (per PyArmor's own Termux
|
|
145
|
+
notes, issue #1674), then optionally compiles with Nuitka `--module`. Cross-
|
|
146
|
+
compiling from your VPS and copying the result to Termux will not work.
|
|
147
|
+
|
|
148
|
+
**pydroid-compat** — Falls back to Universal Python mode by default.
|
|
149
|
+
Optionally attempts PyArmor with `--attempt-pyarmor`, but this is unverified
|
|
150
|
+
against Pydroid's own Python build and may fail at runtime.
|
|
151
|
+
|
|
152
|
+
## Build output
|
|
153
|
+
|
|
154
|
+
Every build creates `samarth_output/` (or `--output DIR`) containing:
|
|
155
|
+
- The compiled/protected files
|
|
156
|
+
- `samarth_manifest.json` — records what was built, on what machine,
|
|
157
|
+
and explicitly notes which platforms have not been tested
|
|
158
|
+
|
|
159
|
+
The manifest is honest: a successful build on Linux x86_64 is not evidence
|
|
160
|
+
the output runs on Termux ARM64. Test on each target separately.
|
|
161
|
+
|
|
162
|
+
## Packaging for PyPI
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
pip install build twine
|
|
166
|
+
python -m build
|
|
167
|
+
twine upload dist/*
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
If shipping a PyArmor-protected extension, include the runtime folder:
|
|
171
|
+
|
|
172
|
+
```toml
|
|
173
|
+
[tool.setuptools.package-data]
|
|
174
|
+
"your_package" = ["*.so", "*.pyd", "pyarmor_runtime_*/**"]
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
First upload: create a PyPI account, generate an API token under Account
|
|
178
|
+
Settings → API tokens, then use `__token__` as the username and the token
|
|
179
|
+
as the password when twine prompts.
|
|
180
|
+
|
|
181
|
+
## Runtime checks
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
from samarth.guard import run_all
|
|
185
|
+
|
|
186
|
+
run_all(
|
|
187
|
+
min_python=(3, 10),
|
|
188
|
+
max_python=(3, 13),
|
|
189
|
+
allowed_platforms=("Linux", "Windows", "Darwin"),
|
|
190
|
+
)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
For integrity verification, compute the hash once after your final build:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
python -c "import hashlib; print(hashlib.sha256(open('app.py','rb').read()).hexdigest())"
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Then pass it to `run_all`:
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
run_all(expected_sha256="<hash>", file_path=__file__)
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Every check exits with status 1 and a message on failure. None of this
|
|
206
|
+
resists a determined reverse engineer — it catches version mismatches and
|
|
207
|
+
casual debugging.
|
|
208
|
+
|
|
209
|
+
## Running tests
|
|
210
|
+
|
|
211
|
+
```bash
|
|
212
|
+
python -m unittest discover -v tests/
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
All 13 tests run without PyArmor or Nuitka installed. Tests that require
|
|
216
|
+
those tools or specific hardware (Termux, Pydroid, ARM64) are marked
|
|
217
|
+
with `skipTest` where the environment isn't detected.
|
|
218
|
+
|
|
219
|
+
## Troubleshooting
|
|
220
|
+
|
|
221
|
+
**`'pyarmor' not found on PATH`** — `pip install pyarmor`, confirm
|
|
222
|
+
`pyarmor --version` works in the same shell.
|
|
223
|
+
|
|
224
|
+
**`'nuitka' not found on PATH`** — `pip install nuitka`, and confirm a C
|
|
225
|
+
compiler is installed (see Install section above).
|
|
226
|
+
|
|
227
|
+
**`pyarmor produced no output`** — run `pyarmor gen` directly on your
|
|
228
|
+
source to see the raw error. Usually a missing activation or empty input.
|
|
229
|
+
|
|
230
|
+
**PyArmor `.so` load error in Termux** — apply the `patchelf` fix shown
|
|
231
|
+
in the Install section above.
|
|
232
|
+
|
|
233
|
+
**`'<name>' not found in PyArmor output`** — PyArmor renamed the entry
|
|
234
|
+
file. Use `samarth build ... --entry <actual-name>`.
|
|
235
|
+
|
|
236
|
+
**Output runs on build machine but not on target** — compiled output is
|
|
237
|
+
tied to OS, architecture, and Python version. Build on each target, or
|
|
238
|
+
for PyArmor use cross-platform `--platform` flags.
|
|
239
|
+
|
|
240
|
+
## License
|
|
241
|
+
|
|
242
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
samarth/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
samarth/build.py,sha256=817Y3Q1q2d9lVWFuMVFwRLzOUiUhVmmW2LOng9qONs8,3485
|
|
3
|
+
samarth/cli.py,sha256=ywPUZUyspVCvAIzKJkd6-BllRGQOzfEa-4ys70eoUIw,7796
|
|
4
|
+
samarth/detect.py,sha256=g7jMzzK35-8Zz_vMdQ20y0_NLbpwTCdUX-YrCoVwRCw,4313
|
|
5
|
+
samarth/guard.py,sha256=rt9yPLMiE802vG91W4rEkTBViyBxvow7szpztfPpeBM,2442
|
|
6
|
+
samarth/strategies.py,sha256=_NWKU1AtR2tQz9zs-E3wdqiOHc3jK24i1ndlTsUVWbg,8440
|
|
7
|
+
samarth-0.2.0.dist-info/METADATA,sha256=q3K1sw0HEX-HNnPxNja046ccg85iPkgPwZhlLBX8eiU,7589
|
|
8
|
+
samarth-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
samarth-0.2.0.dist-info/entry_points.txt,sha256=4shLv5Sfb-JKPTBUT3fQt7WY-51lsF8eHbdln02yPJ4,45
|
|
10
|
+
samarth-0.2.0.dist-info/top_level.txt,sha256=NRYITlREkgU26Aw5dWzHd2u6E2dbYCA7_S7DhQgvzuo,8
|
|
11
|
+
samarth-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
samarth
|