sitrtech 1.2.0__tar.gz → 1.2.4__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sitrtech
3
- Version: 1.2.0
3
+ Version: 1.2.4
4
4
  Summary: SitrTech Python code encryption CLI — protect Odoo, Django, Flask, FastAPI and Tornado projects
5
5
  Author-email: SitrTech <info@sitrtech.com>
6
6
  License: Proprietary
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sitrtech"
7
- version = "1.2.0"
7
+ version = "1.2.4"
8
8
  description = "SitrTech Python code encryption CLI — protect Odoo, Django, Flask, FastAPI and Tornado projects"
9
9
  readme = "README.md"
10
10
  license = { text = "Proprietary" }
@@ -1,5 +1,5 @@
1
1
  """SitrTech — Python code encryption SDK."""
2
- __version__ = "1.2.0"
2
+ __version__ = "1.2.4"
3
3
  __all__ = ["encrypt", "balance", "encrypt_local", "encrypt_dir_local"]
4
4
 
5
5
  try: # optional: local-mode API (needs cryptography + bundled loaders)
@@ -1,8 +1,8 @@
1
1
  """
2
- sitrtech — Python code encryption CLI v1.0.2
2
+ sitrtech — Python code encryption CLI v1.2.4
3
3
  ==============================================
4
4
 
5
- Encrypt Odoo, Django, Flask, FastAPI and Tornado projects with AES-256-GCM
5
+ Encrypt Odoo, Frappe, Django, Flask, FastAPI, Tornado (and WordPress, Laravel, PHP) projects with AES-256-GCM
6
6
  in a single command. Supports incremental updates, expiry dates, and IP-based
7
7
  network restrictions.
8
8
 
@@ -44,7 +44,7 @@ from rich.table import Table
44
44
  # Constants
45
45
  # ─────────────────────────────────────────────────────────────────────────────
46
46
 
47
- __version__ = "1.0.2"
47
+ __version__ = "1.2.4"
48
48
  API_BASE_DEFAULT = "https://sitrtech.com"
49
49
  MANIFEST_SUFFIX = ".sitr_manifest.json"
50
50
 
@@ -52,14 +52,20 @@ console = Console()
52
52
  err_console = Console(stderr=True)
53
53
 
54
54
  FRAMEWORKS = {
55
- "odoo": "__manifest__.py",
56
- "frappe": "hooks.py",
57
- "django": "manage.py",
58
- "flask": "app.py / wsgi.py / application.py",
59
- "fastapi": "main.py / asgi.py",
60
- "tornado": "main.py / server.py",
55
+ "odoo": "__manifest__.py",
56
+ "frappe": "hooks.py",
57
+ "django": "manage.py",
58
+ "flask": "app.py / wsgi.py / application.py",
59
+ "fastapi": "main.py / asgi.py",
60
+ "tornado": "main.py / server.py",
61
+ "wordpress": "wp-config.php / style.css",
62
+ "laravel": "artisan / composer.json",
63
+ "php": "index.php / composer.json",
61
64
  }
62
65
 
66
+ # PHP frameworks are protected by the PHP-side loader (not the Python engine).
67
+ PHP_FRAMEWORKS = {"wordpress", "laravel", "php"}
68
+
63
69
  _STRUCTURAL = {
64
70
  "__manifest__.py", "__openerp__.py", "__init__.py",
65
71
  "manage.py", "app.py", "application.py", "wsgi.py",
@@ -227,8 +233,87 @@ def main(ctx: click.Context, secret: Optional[str], base: Optional[str]) -> None
227
233
  # encrypt
228
234
  # ─────────────────────────────────────────────────────────────────────────────
229
235
 
236
+ def _php_binding(protection: dict, expiry, start, domain, network) -> dict:
237
+ """Map the shared protection options to PHP-loader binding keys."""
238
+ import datetime
239
+ def _epoch(d):
240
+ if not d:
241
+ return None
242
+ try:
243
+ return int(datetime.datetime.fromisoformat(str(d)).timestamp())
244
+ except Exception:
245
+ return None
246
+ b: dict = {}
247
+ if _epoch(expiry):
248
+ b["expires"] = _epoch(expiry)
249
+ if _epoch(start):
250
+ b["start"] = _epoch(start)
251
+ if domain:
252
+ b["domains"] = list(domain)
253
+ if network:
254
+ b["ips"] = list(network)
255
+ return b
256
+
257
+
258
+ def _encrypt_php(ctx, source, fw, version, protection, output,
259
+ base, secret, expiry, start, domain, network) -> None:
260
+ """Encrypt a PHP project directory with the PHP-side loader."""
261
+ try:
262
+ from . import local as _local
263
+ except Exception as e: # pragma: no cover
264
+ err_console.print(f"[red]Error:[/] {e}")
265
+ sys.exit(1)
266
+
267
+ src = Path(source)
268
+ if not src.is_dir():
269
+ err_console.print(
270
+ f"[red]Error:[/] For [bold]{fw}[/] the input must be a project "
271
+ f"DIRECTORY (got [bold]{src.name}[/bold]).")
272
+ sys.exit(1)
273
+ out_dir: Path = Path(output) if output else src.with_name(src.name + "_encrypted")
274
+
275
+ console.print()
276
+ console.print(Panel.fit(
277
+ f"[bold]SitrTech Encrypt[/] · [cyan]{fw}[/] [magenta]PHP[/]"
278
+ f"\n[dim]{src} → {out_dir}[/]",
279
+ border_style="bright_black",
280
+ ))
281
+ console.print("[dim]PHP mode — source is encrypted on this machine; the "
282
+ "platform is contacted only to authorize + meter.[/]")
283
+
284
+ binding = _php_binding(protection, expiry, start, domain, network)
285
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"),
286
+ BarColumn(bar_width=30), TimeElapsedColumn(),
287
+ console=console, transient=True) as prog:
288
+ task = prog.add_task("Authorizing…", total=None)
289
+ def _status(stage):
290
+ prog.update(task, description={
291
+ "authorize": "Authorizing…", "encrypt": "Encrypting locally…",
292
+ "commit": "Finalizing…", "offline": "Offline grant…"}.get(stage, stage))
293
+ try:
294
+ res = _local.encrypt_php_local(
295
+ str(src), str(out_dir), fw, base, secret,
296
+ protection=binding, version=version, on_status=_status,
297
+ )
298
+ except _local.LocalError as e:
299
+ err_console.print(f"[red]Error:[/] {e}")
300
+ sys.exit(1)
301
+
302
+ console.print(
303
+ f"\n[bold green]✓ Encrypted[/] [bold]{out_dir}[/] "
304
+ f"({res['files']} file(s), {res['lines']:,} lines)")
305
+ console.print(f"[dim]Runtime loader: {Path(res['loader']).name} "
306
+ "(ships inside the output — deploy the whole folder).[/]")
307
+ if res.get("charged") is not None:
308
+ console.print(f"[dim]Charged {res['charged']:,} tokens · "
309
+ f"{res.get('tokens_left', '?'):,} left[/]")
310
+ if res.get("protection"):
311
+ console.print("[dim]License binding embedded (enforced at runtime).[/]")
312
+ console.print()
313
+
314
+
230
315
  @main.command()
231
- @click.argument("file", type=click.Path(exists=True, dir_okay=False, path_type=Path))
316
+ @click.argument("file", type=click.Path(exists=True, dir_okay=True, path_type=Path))
232
317
  @click.option("--framework", "-f",
233
318
  type=click.Choice(list(FRAMEWORKS.keys()), case_sensitive=False),
234
319
  default="odoo", show_default=True,
@@ -303,11 +388,6 @@ def encrypt(
303
388
  resolved_secret = _resolve_secret(ctx.obj, secret)
304
389
  base = _resolve_base(ctx.obj)
305
390
  fw = framework.lower()
306
- output_path: Path = output or file.with_name(file.stem + "_encrypted.zip")
307
-
308
- if not file.name.endswith(".zip"):
309
- err_console.print(f"[red]Error:[/] FILE must be a .zip archive (got [bold]{file.name}[/bold])")
310
- sys.exit(1)
311
391
 
312
392
  # Collect binding / protection options shared by both modes.
313
393
  protection = {
@@ -322,6 +402,18 @@ def encrypt(
322
402
  "domain": list(domain),
323
403
  }
324
404
 
405
+ # ── PHP frameworks: encrypt a project DIRECTORY with the PHP-side loader.
406
+ if fw in PHP_FRAMEWORKS:
407
+ _encrypt_php(ctx, file, fw, version, protection, output,
408
+ base, resolved_secret, expiry, start, domain, network)
409
+ return
410
+
411
+ output_path: Path = output or file.with_name(file.stem + "_encrypted.zip")
412
+
413
+ if not file.name.endswith(".zip"):
414
+ err_console.print(f"[red]Error:[/] FILE must be a .zip archive (got [bold]{file.name}[/bold])")
415
+ sys.exit(1)
416
+
325
417
  console.print()
326
418
  console.print(Panel.fit(
327
419
  f"[bold]SitrTech Encrypt[/] · [cyan]{fw}[/]"
@@ -342,6 +434,26 @@ def encrypt(
342
434
  f"[dim]{e}[/]")
343
435
  sys.exit(1)
344
436
  console.print("[dim]Local mode — your source never leaves this machine.[/]")
437
+
438
+ # Incremental: meter only the files that changed since the last run. The
439
+ # whole project is still re-encrypted (free, local CPU) so a single job
440
+ # key keeps every file decryptable — you just pay for what changed.
441
+ current_checksums = _get_checksums(file)
442
+ manifest = _load_manifest(output_path)
443
+ bill_members: Optional[set] = None
444
+ if not full and manifest is not None and output_path.exists():
445
+ prev = (manifest or {}).get("files", {})
446
+ changed = {n for n, h in current_checksums.items() if prev.get(n) != h}
447
+ if not changed:
448
+ console.print("\n[green]✓ No changes detected.[/] Output is already up to date.")
449
+ return
450
+ console.print("[dim]▸ Manifest found — incremental mode[/]")
451
+ console.print(f"[bold cyan]Incremental:[/] {len(changed)} file(s) changed")
452
+ for n in sorted(changed):
453
+ tag = "[green]+new[/]" if n not in prev else "[yellow]~mod[/]"
454
+ console.print(f" {tag} {n}")
455
+ bill_members = changed
456
+
345
457
  with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"),
346
458
  BarColumn(bar_width=30), TimeElapsedColumn(),
347
459
  console=console, transient=True) as prog:
@@ -353,7 +465,8 @@ def encrypt(
353
465
  try:
354
466
  res = _local.encrypt_local(
355
467
  str(file), str(output_path), fw, base, resolved_secret,
356
- protection=protection, version=version, on_status=_status,
468
+ protection=protection, version=version,
469
+ bill_members=bill_members, on_status=_status,
357
470
  )
358
471
  except _local.LocalError as e:
359
472
  err_console.print(f"[red]Error:[/] {e}")
@@ -366,6 +479,8 @@ def encrypt(
366
479
  f"{res.get('tokens_left', '?'):,} left[/]")
367
480
  if res.get("protection"):
368
481
  console.print("[dim]Binding rules embedded (license enforced at runtime).[/]")
482
+ mp = _save_manifest(output_path, fw, current_checksums)
483
+ console.print(f"[dim]Manifest: {mp.name} — next run is incremental.[/]")
369
484
  console.print()
370
485
  return
371
486
 
@@ -14,10 +14,13 @@ from __future__ import annotations
14
14
 
15
15
  import os
16
16
  import re
17
+ import io
18
+ import ast
17
19
  import json
18
20
  import base64
19
- import secrets
20
21
  import shutil
22
+ import secrets
23
+ import tokenize
21
24
  import datetime
22
25
  from typing import Optional, Callable, List, Dict, Any
23
26
 
@@ -32,7 +35,7 @@ from cryptography.hazmat.primitives.asymmetric.x25519 import (
32
35
  )
33
36
 
34
37
  # Injected at build time (build_engine.py replaces this placeholder with the real key).
35
- EMBEDDED_GRANT_PUBKEY_B64 = os.environ.get("SITR_GRANT_PK_B64", "")
38
+ EMBEDDED_GRANT_PUBKEY_B64 = os.environ.get("SITR_GRANT_PK_B64", "") or "nLFEnli4G4ELB2NraUif5spkal2IIZBYl00avjLVzJ4"
36
39
 
37
40
  FRAMEWORK_MARKERS: Dict[str, list] = {
38
41
  "odoo": ["__manifest__.py", "__openerp__.py"],
@@ -121,6 +124,12 @@ def _to_ts(v) -> Optional[int]:
121
124
  return int(dt.timestamp())
122
125
 
123
126
 
127
+ def _norm_mac(s: str) -> str:
128
+ """Normalize a MAC to 12 lowercase hex chars, matching the loader's format."""
129
+ h = "".join(c for c in str(s).lower() if c in "0123456789abcdef")
130
+ return h if len(h) == 12 else str(s).strip().lower()
131
+
132
+
124
133
  def build_license_meta(options: Dict[str, Any]) -> Optional[Dict[str, Any]]:
125
134
  """Turn CLI/API options into the compact license metadata the loader enforces."""
126
135
  meta: Dict[str, Any] = {}
@@ -131,7 +140,7 @@ def build_license_meta(options: Dict[str, Any]) -> Optional[Dict[str, Any]]:
131
140
  if options.get("network"):
132
141
  meta["net_scopes"] = _split(options["network"])
133
142
  if options.get("mac"):
134
- meta["macs"] = [m.lower() for m in _split(options["mac"])]
143
+ meta["macs"] = [_norm_mac(m) for m in _split(options["mac"])]
135
144
  if options.get("machine_id"):
136
145
  meta["machine_ids"] = [m.lower() for m in _split(options["machine_id"])]
137
146
  if options.get("hostname"):
@@ -146,10 +155,30 @@ def build_license_meta(options: Dict[str, Any]) -> Optional[Dict[str, Any]]:
146
155
 
147
156
 
148
157
  # ── file encryption (v6: file key wrapped under jobKEK) ─────────────────────
158
+ def _strip_comments(source: str) -> str:
159
+ """Remove comments before encryption so the protected payload carries no
160
+ human-readable annotations — even in memory once decrypted at runtime.
161
+
162
+ Docstrings are preserved (some frameworks read them, e.g. FastAPI/OpenAPI).
163
+ The transform is verified to be semantics-preserving: the comment-free source
164
+ must parse to an identical AST, otherwise the original source is kept.
165
+ """
166
+ try:
167
+ stripped = tokenize.untokenize(
168
+ tok for tok in tokenize.generate_tokens(io.StringIO(source).readline)
169
+ if tok.type != tokenize.COMMENT
170
+ )
171
+ if ast.dump(ast.parse(stripped)) == ast.dump(ast.parse(source)):
172
+ return stripped
173
+ except Exception:
174
+ pass
175
+ return source
176
+
177
+
149
178
  def encrypt_file_v6(src_path: str, out_path: str, job_kek: bytes,
150
179
  license_meta: Optional[Dict[str, Any]] = None) -> None:
151
180
  with open(src_path, "r", encoding="utf-8") as f:
152
- payload = f.read().encode("utf-8")
181
+ payload = _strip_comments(f.read()).encode("utf-8")
153
182
 
154
183
  file_key = secrets.token_bytes(32)
155
184
  file_nonce = secrets.token_bytes(12)
@@ -30,8 +30,11 @@ from typing import Optional, Dict, Any, List
30
30
  import requests
31
31
 
32
32
  from . import engine
33
+ from . import php as phpmod
33
34
  from .runtime import native_injector
34
35
 
36
+ PHP_FRAMEWORKS = {"wordpress", "laravel", "php"}
37
+
35
38
 
36
39
  # ── secure transport: HMAC-signed requests (integrity + anti-replay) ─────────
37
40
  def _sig_headers(secret: str, method: str, path: str, body_str: str) -> Dict[str, str]:
@@ -193,34 +196,98 @@ def _bundled_has_loaders() -> Optional[str]:
193
196
  return None
194
197
 
195
198
 
196
- def _ensure_loaders(base_url: str, secret: str) -> str:
197
- """Download runtime loaders from the platform (authenticated) into a local cache.
199
+ _LOADER_CACHE = os.path.join(os.path.expanduser("~"), ".cache", "sitrtech", "loaders")
200
+ _VERSION_FILE = ".loader_version"
198
201
 
199
- Keeps the master-secret loaders out of the public wheel — they are served only
200
- to authenticated customers and cached under ~/.cache/sitrtech/loaders.
201
- """
202
+
203
+ def _cached_loader_version(cache: str) -> Optional[int]:
204
+ try:
205
+ with open(os.path.join(cache, _VERSION_FILE)) as f:
206
+ return int(f.read().strip())
207
+ except Exception:
208
+ return None
209
+
210
+
211
+ def _download_loaders(base_url: str, secret: str, cache: str) -> int:
212
+ """Fetch the loader set + its version; returns the downloaded version."""
202
213
  import glob
203
- cache = os.path.join(os.path.expanduser("~"), ".cache", "sitrtech", "loaders")
204
- os.makedirs(cache, exist_ok=True)
205
- if glob.glob(os.path.join(cache, "sitry-*.*")):
206
- return cache
207
214
  r = _get_signed(base_url, "/api/loaders", secret)
208
215
  if not r.ok:
209
216
  raise LocalError(f"Cannot fetch runtime loaders ({r.status_code}).")
210
- files = r.json().get("files", [])
217
+ body = r.json()
218
+ files = body.get("files", [])
219
+ version = int(body.get("version", 0) or 0)
211
220
  if not files:
212
221
  raise LocalError("Platform has no runtime loaders available.")
222
+ # clear stale loaders so a rotated set fully replaces the old one
223
+ for old in glob.glob(os.path.join(cache, "sitry-*.*")):
224
+ try:
225
+ os.remove(old)
226
+ except Exception:
227
+ pass
213
228
  for name in files:
214
229
  fr = _get_signed(base_url, f"/api/loaders/{name}", secret, 120)
215
230
  if fr.ok:
216
231
  with open(os.path.join(cache, name), "wb") as f:
217
232
  f.write(fr.content)
233
+ with open(os.path.join(cache, _VERSION_FILE), "w") as f:
234
+ f.write(str(version))
235
+ return version
236
+
237
+
238
+ def _ensure_loaders(base_url: str, secret: str) -> str:
239
+ """Download / auto-update runtime loaders into the local cache.
240
+
241
+ The master-secret loaders are kept out of the public wheel — served only to
242
+ authenticated customers. Each run checks the platform's loader *version*: if
243
+ it changed, the newest loaders are fetched automatically so a customer never
244
+ encrypts with a stale/unsupported loader. `min_supported` forces an update
245
+ (and lets the platform revoke a compromised loader).
246
+ """
247
+ import glob
248
+ cache = _LOADER_CACHE
249
+ os.makedirs(cache, exist_ok=True)
250
+ have = bool(glob.glob(os.path.join(cache, "sitry-*.*")))
251
+ cached_ver = _cached_loader_version(cache)
252
+
253
+ # Lightweight version probe (best-effort; never blocks when offline).
254
+ server_ver = None
255
+ min_supported = None
256
+ try:
257
+ vr = _get_signed(base_url, "/api/loaders/version", secret, 15)
258
+ if vr.ok:
259
+ vj = vr.json()
260
+ server_ver = int(vj.get("version", 0) or 0)
261
+ min_supported = int(vj.get("min_supported", 0) or 0)
262
+ except _NET_ERRORS:
263
+ pass
264
+
265
+ if not have:
266
+ _download_loaders(base_url, secret, cache)
267
+ elif server_ver is not None and server_ver != cached_ver:
268
+ # loaders rotated on the platform → pull the newest set
269
+ try:
270
+ _download_loaders(base_url, secret, cache)
271
+ except LocalError:
272
+ if min_supported and (cached_ver or 0) < min_supported:
273
+ raise LocalError(
274
+ "Your runtime loaders are outdated and no longer supported, "
275
+ "and the newest set could not be downloaded. Reconnect and retry.")
276
+
277
+ # Hard floor: refuse to run on a loader below the platform's min_supported.
278
+ if min_supported:
279
+ cur = _cached_loader_version(cache) or 0
280
+ if cur and cur < min_supported:
281
+ raise LocalError(
282
+ f"Loader version {cur} is below the minimum supported "
283
+ f"({min_supported}). Update failed — reconnect to the platform.")
218
284
  return cache
219
285
 
220
286
 
221
287
  def _resolve_loaders(base_url: str, secret: str, explicit: Optional[str]) -> str:
222
288
  if explicit:
223
289
  return explicit
290
+ # A bundled loader dir (dev) skips the fetch; otherwise ensure/auto-update.
224
291
  return _bundled_has_loaders() or _ensure_loaders(base_url, secret)
225
292
 
226
293
 
@@ -233,9 +300,16 @@ def encrypt_local(
233
300
  protection: Optional[Dict[str, Any]] = None,
234
301
  version: str = "",
235
302
  loaders_dir: Optional[str] = None,
303
+ bill_members: Optional[set] = None,
236
304
  on_status=None,
237
305
  ) -> Dict[str, Any]:
238
- """Encrypt `zip_path` locally; contact `base_url` only to authorize + meter."""
306
+ """Encrypt `zip_path` locally; contact `base_url` only to authorize + meter.
307
+
308
+ Incremental billing: when `bill_members` is given (the set of changed source
309
+ files, relative to the zip root), only those lines are authorized and charged.
310
+ The whole project is still re-encrypted locally — that is free CPU and keeps a
311
+ single per-job key so every file decrypts — but you only pay for what changed.
312
+ """
239
313
  framework = (framework or "odoo").lower()
240
314
  protection = protection or {}
241
315
  say = on_status or (lambda *_: None)
@@ -261,6 +335,21 @@ def encrypt_local(
261
335
  if est_lines <= 0:
262
336
  raise LocalError("No encryptable Python files found.")
263
337
 
338
+ # Incremental: meter only the changed encryptable files.
339
+ if bill_members is not None:
340
+ skip = engine.FRAMEWORK_SKIP_ENCRYPT.get(framework, set())
341
+ changed_lines = 0
342
+ for m in bill_members:
343
+ if not m.endswith(".py") or os.path.basename(m) in skip:
344
+ continue
345
+ fp = os.path.join(extract, m)
346
+ if os.path.isfile(fp):
347
+ with open(fp, "r", encoding="utf-8", errors="ignore") as f:
348
+ changed_lines += sum(1 for _ in f)
349
+ bill_lines = max(1, changed_lines)
350
+ else:
351
+ bill_lines = est_lines
352
+
264
353
  # 2) authorize online; if the platform is unreachable, fall back to a
265
354
  # cached signed offline grant so encryption never stops.
266
355
  say("authorize")
@@ -270,7 +359,7 @@ def encrypt_local(
270
359
  try:
271
360
  r = _post_signed(
272
361
  base_url, "/api/authorize", secret,
273
- {"framework": framework, "version": version, "est_lines": est_lines,
362
+ {"framework": framework, "version": version, "est_lines": bill_lines,
274
363
  "client_pub": client_pub},
275
364
  )
276
365
  if r.status_code == 401:
@@ -293,7 +382,7 @@ def encrypt_local(
293
382
  "Platform unreachable and no offline grant cached. "
294
383
  "While online run: sitr offline fetch")
295
384
  say("offline")
296
- job_kek, wrapped = _offline_acquire(cache, est_lines)
385
+ job_kek, wrapped = _offline_acquire(cache, bill_lines)
297
386
  offline = True
298
387
 
299
388
  try:
@@ -322,7 +411,7 @@ def encrypt_local(
322
411
  say("commit")
323
412
  c = _post_signed(
324
413
  base_url, "/api/commit", secret,
325
- {"job_id": job_id, "actual_lines": stats["lines"],
414
+ {"job_id": job_id, "actual_lines": bill_lines,
326
415
  "module_name": os.path.basename(zip_path), "framework": framework,
327
416
  "version": version, "modules": stats.get("files")},
328
417
  )
@@ -342,6 +431,100 @@ def encrypt_local(
342
431
  }
343
432
 
344
433
 
434
+ def encrypt_php_local(
435
+ source_dir: str,
436
+ output_dir: str,
437
+ framework: str,
438
+ base_url: str,
439
+ secret: str,
440
+ protection: Optional[Dict[str, Any]] = None,
441
+ version: str = "",
442
+ on_status=None,
443
+ ) -> Dict[str, Any]:
444
+ """Encrypt a PHP project (WordPress/Laravel/PHP) locally.
445
+
446
+ Same billing contract as `encrypt_local`: the platform is contacted only to
447
+ authorize (reserve tokens) and commit (charge real lines). Encryption and
448
+ the runtime PHP loader are produced entirely on this machine.
449
+ """
450
+ framework = (framework or "php").lower()
451
+ protection = protection or {}
452
+ say = on_status or (lambda *_: None)
453
+
454
+ if not os.path.isdir(source_dir):
455
+ raise LocalError(f"Source directory not found: {source_dir}")
456
+
457
+ files = phpmod.discover_php_files(source_dir)
458
+ if not files:
459
+ raise LocalError("No .php files found to encrypt.")
460
+ est_lines = phpmod.count_php_lines(files)
461
+
462
+ say("authorize")
463
+ client_priv, client_pub = engine.new_client_keypair()
464
+ offline = False
465
+ job_id = None
466
+ try:
467
+ r = _post_signed(
468
+ base_url, "/api/authorize", secret,
469
+ {"framework": framework, "version": version, "est_lines": est_lines,
470
+ "client_pub": client_pub},
471
+ )
472
+ if r.status_code == 401:
473
+ raise LocalError("Invalid API secret.")
474
+ if r.status_code == 402:
475
+ d = r.json()
476
+ raise LocalError(f"Insufficient tokens: need {d.get('needed')}, have {d.get('available')}.")
477
+ if not r.ok:
478
+ raise LocalError(f"Authorize failed ({r.status_code}): {r.text[:200]}")
479
+ job_id = r.json().get("job_id")
480
+ except _NET_ERRORS:
481
+ cache = _offline_load()
482
+ if not cache:
483
+ raise LocalError(
484
+ "Platform unreachable and no offline grant cached. "
485
+ "While online run: sitr offline fetch")
486
+ say("offline")
487
+ _offline_acquire(cache, est_lines) # meter locally against the grant
488
+ offline = True
489
+
490
+ try:
491
+ say("encrypt")
492
+ summary = phpmod.encrypt_php_project(source_dir, output_dir, protection, say)
493
+ except Exception as e:
494
+ if not offline and job_id:
495
+ try:
496
+ _post_signed(base_url, "/api/cancel", secret, {"job_id": job_id}, 15)
497
+ except Exception:
498
+ pass
499
+ raise LocalError(f"PHP encryption failed: {e}")
500
+
501
+ charged = None
502
+ tokens_left = None
503
+ if not offline and job_id:
504
+ say("commit")
505
+ c = _post_signed(
506
+ base_url, "/api/commit", secret,
507
+ {"job_id": job_id, "actual_lines": summary["lines"],
508
+ "module_name": os.path.basename(os.path.abspath(source_dir)),
509
+ "framework": framework, "version": version, "modules": summary["files"]},
510
+ )
511
+ if c.ok:
512
+ cj = c.json()
513
+ charged = cj.get("charged")
514
+ tokens_left = cj.get("tokens")
515
+
516
+ return {
517
+ "output": output_dir,
518
+ "offline": offline,
519
+ "lines": summary["lines"],
520
+ "files": summary["files"],
521
+ "loader": summary["loader"],
522
+ "charged": charged,
523
+ "tokens_left": tokens_left,
524
+ "protection": bool(phpmod.build_php_license(protection)),
525
+ }
526
+
527
+
345
528
  # ─────────────────────────────────────────────────────────────────────────────
346
529
  # Batch / directory mode — for CI/CD (many modules, incremental, parallel)
347
530
  # ─────────────────────────────────────────────────────────────────────────────
@@ -0,0 +1,277 @@
1
+ """SitrTech PHP encoder — protect WordPress / Laravel / generic PHP projects.
2
+
3
+ The platform's primary engine protects Python with a compiled native loader
4
+ (``sitry-*.so``) that holds a whitebox secret. PHP runs a different runtime, so
5
+ PHP code is protected by a *PHP-side loader* instead:
6
+
7
+ • every ``.php`` file's source is encrypted with AES-256-GCM (a fresh IV per
8
+ file) under a random 256-bit project key;
9
+ • the original file is replaced by a tiny stub that hands its encrypted blob
10
+ to ``\\SitrTech\\SitrLoader``;
11
+ • ``sitrtech-loader.php`` (dropped at the project root) decrypts the blob,
12
+ enforces the license (expiry / domain / IP binding) and executes it.
13
+
14
+ Billing is identical to the Python path: the platform is contacted only to
15
+ ``authorize`` (reserve tokens) and ``commit`` (charge the real line count).
16
+
17
+ Protection tiers
18
+ ----------------
19
+ The bundled ``sitrtech-loader.php`` is a **pure-PHP** loader: it needs the
20
+ decryption key at runtime, so the key lives (obfuscated) inside it. That is
21
+ obfuscation-grade protection — equivalent to non-extension PHP encoders — and
22
+ it is honestly documented as such. A hardened **native PHP (Zend) extension**
23
+ (``sitrtech.so``), built like the Python loader matrix, is the production-grade
24
+ tier and slots in without re-encrypting: the blob format is identical.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import base64
31
+ import json
32
+ import secrets
33
+ from typing import Any, Dict, List, Optional, Tuple
34
+
35
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
36
+
37
+ # ── framework detection ──────────────────────────────────────────────────────
38
+ # Marker files that identify a PHP project kind. `php` is the generic fallback.
39
+ PHP_MARKERS: Dict[str, list] = {
40
+ "wordpress": ["wp-config.php", "wp-load.php", "wp-settings.php", "style.css"],
41
+ "laravel": ["artisan"],
42
+ "php": ["composer.json", "index.php"],
43
+ }
44
+
45
+ # Directories never encrypted (dependencies, build output, runtime caches).
46
+ PHP_SKIP_DIRS = {
47
+ "vendor", "node_modules", ".git", ".github", "storage", "bootstrap",
48
+ "cache", "tests", "test", "dist", "build", ".idea", ".vscode",
49
+ }
50
+
51
+ # Files never encrypted — bootstrap/config PHP that frameworks read directly.
52
+ PHP_SKIP_FILES = {
53
+ "wp-config.php", "wp-load.php", "wp-settings.php", "wp-blog-header.php",
54
+ "index.php", "artisan", "sitrtech-loader.php",
55
+ }
56
+
57
+ LOADER_NAME = "sitrtech-loader.php"
58
+ MAGIC = "SITRPHP1"
59
+
60
+
61
+ class PhpError(RuntimeError):
62
+ pass
63
+
64
+
65
+ # ── discovery / metering ─────────────────────────────────────────────────────
66
+ def discover_php_files(root: str) -> List[str]:
67
+ """Every encryptable ``.php`` file under *root* (skip deps/config/loader)."""
68
+ out: List[str] = []
69
+ for r, dirs, files in os.walk(root):
70
+ dirs[:] = [d for d in dirs if d.lower() not in PHP_SKIP_DIRS]
71
+ for fn in files:
72
+ if not fn.endswith(".php"):
73
+ continue
74
+ if fn in PHP_SKIP_FILES:
75
+ continue
76
+ out.append(os.path.join(r, fn))
77
+ return out
78
+
79
+
80
+ def count_php_lines(files: List[str]) -> int:
81
+ total = 0
82
+ for fp in files:
83
+ try:
84
+ with open(fp, "r", encoding="utf-8", errors="ignore") as f:
85
+ total += sum(1 for _ in f)
86
+ except Exception:
87
+ pass
88
+ return max(1, total)
89
+
90
+
91
+ def detect_php_framework(root: str) -> Optional[str]:
92
+ """Return 'wordpress' | 'laravel' | 'php' if *root* looks like a PHP app."""
93
+ names = set()
94
+ for r, _d, files in os.walk(root):
95
+ names.update(files)
96
+ # only need the top couple of levels for markers
97
+ if r.count(os.sep) - root.count(os.sep) > 2:
98
+ break
99
+ for kind in ("wordpress", "laravel"):
100
+ if any(m in names for m in PHP_MARKERS[kind]):
101
+ return kind
102
+ if any(m in names for m in PHP_MARKERS["php"]):
103
+ return "php"
104
+ return None
105
+
106
+
107
+ # ── crypto ───────────────────────────────────────────────────────────────────
108
+ def _encrypt_source(src: bytes, key: bytes) -> str:
109
+ """AES-256-GCM one file → base64(MAGIC-less payload: iv || ct || tag)."""
110
+ iv = secrets.token_bytes(12)
111
+ ct = AESGCM(key).encrypt(iv, src, None) # ct = ciphertext || 16-byte tag
112
+ return base64.b64encode(iv + ct).decode("ascii")
113
+
114
+
115
+ def _obfuscate_key(key: bytes) -> Tuple[str, str]:
116
+ """Split the key into two XOR-masked halves for the loader (obfuscation)."""
117
+ pad = secrets.token_bytes(len(key))
118
+ masked = bytes(a ^ b for a, b in zip(key, pad))
119
+ return base64.b64encode(masked).decode(), base64.b64encode(pad).decode()
120
+
121
+
122
+ def _stub(rel_blob: str) -> str:
123
+ """The tiny PHP file that replaces an encrypted source file."""
124
+ return (
125
+ "<?php\n"
126
+ "/* Protected by SitrTech — https://sitrtech.com */\n"
127
+ "if(!class_exists('SitrTech\\\\SitrLoader')){$d=__DIR__;"
128
+ "while($d!==dirname($d)){if(is_file($d.'/" + LOADER_NAME + "')){"
129
+ "require_once $d.'/" + LOADER_NAME + "';break;}$d=dirname($d);}}\n"
130
+ "\\SitrTech\\SitrLoader::exec(__FILE__,'" + rel_blob + "');\n"
131
+ )
132
+
133
+
134
+ # ── license meta ─────────────────────────────────────────────────────────────
135
+ def build_php_license(binding: Optional[Dict[str, Any]]) -> Dict[str, Any]:
136
+ b = binding or {}
137
+ meta: Dict[str, Any] = {}
138
+ if b.get("expires"):
139
+ meta["exp"] = int(b["expires"])
140
+ if b.get("start"):
141
+ meta["nbf"] = int(b["start"])
142
+ for k_in, k_out in (
143
+ ("domains", "domains"), ("ips", "ips"), ("hostnames", "hostnames"),
144
+ ):
145
+ v = b.get(k_in)
146
+ if v:
147
+ meta[k_out] = list(v)
148
+ return meta
149
+
150
+
151
+ # ── PHP loader template ──────────────────────────────────────────────────────
152
+ def render_loader(key: bytes, meta: Dict[str, Any]) -> str:
153
+ masked_b64, pad_b64 = _obfuscate_key(key)
154
+ meta_json = json.dumps(meta, separators=(",", ":"))
155
+ # The loader is intentionally compact. It reconstitutes the key from two
156
+ # XOR halves, enforces the license, then decrypts + executes each blob.
157
+ return f"""<?php
158
+ /* SitrTech PHP loader — protected runtime. https://sitrtech.com
159
+ * Pure-PHP tier: obfuscation-grade. Replace with the native sitrtech.so
160
+ * Zend extension for hardened protection (same blob format). */
161
+ namespace SitrTech;
162
+
163
+ final class SitrLoader {{
164
+ const MAGIC = '{MAGIC}';
165
+ private static $key = null;
166
+
167
+ private static function key() {{
168
+ if (self::$key !== null) return self::$key;
169
+ $m = base64_decode('{masked_b64}');
170
+ $p = base64_decode('{pad_b64}');
171
+ $k = '';
172
+ for ($i = 0; $i < strlen($m); $i++) $k .= chr(ord($m[$i]) ^ ord($p[$i]));
173
+ return self::$key = $k;
174
+ }}
175
+
176
+ private static function deny($why) {{
177
+ http_response_code(403);
178
+ die('SitrTech: license check failed (' . $why . ')');
179
+ }}
180
+
181
+ private static function checkLicense() {{
182
+ $meta = json_decode('{meta_json}', true);
183
+ if (!$meta) return;
184
+ $now = time();
185
+ if (isset($meta['nbf']) && $now < $meta['nbf']) self::deny('not-yet-valid');
186
+ if (isset($meta['exp']) && $now > $meta['exp']) self::deny('expired');
187
+ if (!empty($meta['domains'])) {{
188
+ $host = strtolower($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '');
189
+ $host = preg_replace('/:\\d+$/', '', $host);
190
+ $ok = false;
191
+ foreach ($meta['domains'] as $d) {{
192
+ $d = strtolower(trim($d));
193
+ if ($host === $d || ($d[0] === '.' && substr($host, -strlen($d)) === $d)
194
+ || substr($host, -strlen('.' . $d)) === '.' . $d || $host === ltrim($d, '.')) {{
195
+ $ok = true; break;
196
+ }}
197
+ }}
198
+ if (!$ok) self::deny('domain');
199
+ }}
200
+ if (!empty($meta['ips'])) {{
201
+ $ip = $_SERVER['SERVER_ADDR'] ?? '';
202
+ if (!in_array($ip, $meta['ips'], true)) self::deny('ip');
203
+ }}
204
+ }}
205
+
206
+ public static function exec($file, $blob) {{
207
+ self::checkLicense();
208
+ $raw = base64_decode($blob, true);
209
+ if ($raw === false || strlen($raw) < 28) self::deny('corrupt');
210
+ $iv = substr($raw, 0, 12);
211
+ $rest = substr($raw, 12);
212
+ $tag = substr($rest, -16);
213
+ $ct = substr($rest, 0, -16);
214
+ $src = openssl_decrypt($ct, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag);
215
+ if ($src === false) self::deny('decrypt');
216
+ // Prepend a close-tag so eval() runs a complete PHP file (with inline HTML).
217
+ eval('?>' . $src);
218
+ }}
219
+ }}
220
+ """
221
+
222
+
223
+ # ── project encryption ───────────────────────────────────────────────────────
224
+ def encrypt_php_project(
225
+ source_dir: str,
226
+ out_dir: str,
227
+ binding: Optional[Dict[str, Any]] = None,
228
+ say=lambda *_a: None,
229
+ ) -> Dict[str, Any]:
230
+ """Encrypt every ``.php`` file under *source_dir* into *out_dir*.
231
+
232
+ Returns a summary dict: {files, lines, loader}. Caller handles billing
233
+ (authorize/commit) around this call so metering matches the Python path.
234
+ """
235
+ if not os.path.isdir(source_dir):
236
+ raise PhpError(f"source not found: {source_dir}")
237
+
238
+ files = discover_php_files(source_dir)
239
+ if not files:
240
+ raise PhpError("no .php files to encrypt")
241
+
242
+ key = secrets.token_bytes(32)
243
+ meta = build_php_license(binding)
244
+
245
+ os.makedirs(out_dir, exist_ok=True)
246
+ n = 0
247
+ for r, dirs, fnames in os.walk(source_dir):
248
+ dirs[:] = [d for d in dirs if d.lower() not in PHP_SKIP_DIRS]
249
+ rel_dir = os.path.relpath(r, source_dir)
250
+ dst_dir = out_dir if rel_dir == "." else os.path.join(out_dir, rel_dir)
251
+ os.makedirs(dst_dir, exist_ok=True)
252
+ for fn in fnames:
253
+ src_fp = os.path.join(r, fn)
254
+ dst_fp = os.path.join(dst_dir, fn)
255
+ if fn.endswith(".php") and fn not in PHP_SKIP_FILES:
256
+ with open(src_fp, "rb") as f:
257
+ blob = _encrypt_source(f.read(), key)
258
+ with open(dst_fp, "w", encoding="utf-8") as f:
259
+ f.write(_stub(blob))
260
+ n += 1
261
+ else:
262
+ # copy assets / skipped files verbatim
263
+ with open(src_fp, "rb") as f:
264
+ data = f.read()
265
+ with open(dst_fp, "wb") as f:
266
+ f.write(data)
267
+
268
+ loader_path = os.path.join(out_dir, LOADER_NAME)
269
+ with open(loader_path, "w", encoding="utf-8") as f:
270
+ f.write(render_loader(key, meta))
271
+ say(f"encrypted {n} php file(s)")
272
+
273
+ return {
274
+ "files": n,
275
+ "lines": count_php_lines(files),
276
+ "loader": loader_path,
277
+ }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sitrtech
3
- Version: 1.2.0
3
+ Version: 1.2.4
4
4
  Summary: SitrTech Python code encryption CLI — protect Odoo, Django, Flask, FastAPI and Tornado projects
5
5
  Author-email: SitrTech <info@sitrtech.com>
6
6
  License: Proprietary
@@ -4,6 +4,7 @@ src/sitrtech/__init__.py
4
4
  src/sitrtech/cli.py
5
5
  src/sitrtech/engine.py
6
6
  src/sitrtech/local.py
7
+ src/sitrtech/php.py
7
8
  src/sitrtech/runtime.py
8
9
  src/sitrtech.egg-info/PKG-INFO
9
10
  src/sitrtech.egg-info/SOURCES.txt
File without changes
File without changes