Metadata-Version: 2.4
Name: pyencode-protector
Version: 0.3.1
Summary: Protect CPython applications with authenticated encrypted module bundles
Author: PyEncode contributors
License: MIT
Project-URL: Homepage, https://github.com/VanThanBK/pyencode
Project-URL: Repository, https://github.com/VanThanBK/pyencode
Project-URL: Issues, https://github.com/VanThanBK/pyencode/issues
Keywords: python,code-protection,obfuscation,encryption
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Software Development :: Build Tools
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: cryptography>=42

# PyEncode

PyEncode is a pure-Python tool for protecting CPython applications on Windows and
Linux. Each module is compiled to a code object, serialized with `marshal`,
compressed, and authenticated-encrypted with AES-256-GCM. The runtime decrypts and
executes the code in memory; neither plaintext source nor plaintext bytecode is
written to a temporary file.

Version 0.3 uses the PYE2 format:

- Every artifact receives a random 128-bit filename, for example
  `myapp/7b82a40e9aa14e60db7094f2de3fbc33.pye`.
- PYE2 has no plaintext JSON header; an artifact contains only its magic value,
  nonce, and ciphertext/authentication tag.
- Module names, the entry point, and package flags are stored in an encrypted module
  index.
- Manifest format 3 is signed with Ed25519 and contains the SHA-256 digest of every
  artifact.
- The runtime, launcher, resources, and support trees copied by the builder are all
  signed, key-bound, and verified again during `install()`.
- The loader exposes only a small trampoline to `runpy`, rather than returning the
  application's real code object. Module keys are derived on demand and are not
  retained by the finder.

The goal is to make static analysis substantially more expensive than it is for
`.pyc` files. PyEncode does not claim to make reverse engineering impossible.

## Supported Python versions

PyEncode 0.3 requires **standard CPython 3.10 or later**. CI directly tests Python
3.10 through 3.15. Newer CPython feature releases may install and build under the
forward-compatible version policy, and are added to the required test matrix once
the release and its dependency wheels are available. PyPy and other Python
implementations are not currently supported.

The runtime is pure Python, so the same runtime source works on Windows and Linux.
However, a built artifact is tied to the exact CPython major/minor version used to
build it:

- an artifact built with CPython 3.11 runs on CPython 3.11;
- that artifact does not run on CPython 3.10, 3.12, or 3.14;
- to support several minor versions, build a separate output with each interpreter.

If a bundle includes `.pyd`, `.so`, `.dll`, or other native dependencies through
`--support`, the whole bundle is also constrained by the operating system,
architecture, and ABI of those files. Current testing targets the standard GIL
build of CPython; free-threaded and debug ABIs require separate builds and testing.

## Installation

Install the published package from PyPI in a virtual environment:

```powershell
py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install pyencode-protector
```

The CLI command and import namespace are both named `pyencode`.

For source development, use an editable installation in a virtual environment.

Windows PowerShell:

```powershell
py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -e .
```

Linux:

```bash
python3.11 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e .
```

The only runtime dependency is `cryptography>=42`.

## Usage

Built-in command-line help is available without opening the documentation:

```bash
pyencode --help
pyencode build --help
python -m pyencode --help
```

Protect a single file:

```bash
pyencode build hello.py -o dist/hello
python dist/hello/run.py
```

Protect a package containing `__main__.py`:

```bash
pyencode build src/myapp -o dist/myapp
python dist/myapp/run.py
```

Specify the entry module explicitly:

```bash
pyencode build src -o dist/app --entry myapp.__main__
```

Sign and key-bind additional dependencies or support trees:

```bash
pyencode build src -o dist/app \
  --entry myapp.main \
  --support build/vendor _vendor \
  --support public/config.json config.json
```

`--support SOURCE DEST` may be repeated. If `SOURCE` is a directory, its tree is
copied below `DEST`; if it is a file, `DEST` is the output file path. Symlinks,
reparse points, paths that escape the root, and case-insensitive path collisions are
rejected.

The exact destination `_vendor` is treated as a bootstrap dependency path for hosts
that do not already have `cryptography` installed, such as Fusion. Only the exact
`_vendor` entry remains on `sys.path` while the verifier loads; every other bundle
subdirectory is isolated. Because the vendored cryptography library must run before
Ed25519 can verify the bundle itself, `_vendor` is a trusted bootstrap component by
design in this pure-Python runtime. Vendor only wheels obtained from trusted
sources.

Main options:

- `-o`, `--output`: output directory; it must not exist or must be completely empty.
- `-e`, `--entry`: dotted name of the entry module or package.
- `--exclude GLOB`: exclude paths matching a glob; may be repeated.
- `--no-resources`: do not copy non-Python files from the source tree.
- `--keep-docstrings`: preserve docstrings.
- `--optimize {0,1,2}`: CPython optimization level.
- `--expires YYYY-MM-DD`: refuse to run after the specified UTC date.
- `--launcher PATH`: use a custom `.py` launcher.
- `--support SOURCE DEST`: copy, sign, and key-bind a support file or tree.
- `--rename-locals`: rename metadata for local variables that are not parameters.
- `--allow-extra-data`: allow the host to create additional unsigned data files and
  directories; signed files and recognized Python/native artifact types remain
  protected. The application must not execute or trust the added data.

`--rename-locals` is opt-in because code that uses a dynamic alias of `locals()`,
reads `frame.f_locals`, or depends on debugger/framework introspection may require
the original local names. Arguments, closures, line tables, and exception tables are
always preserved.

## Custom launchers and embedded hosts

A custom launcher is copied byte-for-byte, signed, and included in key derivation.
It must set:

```python
import sys
sys.dont_write_bytecode = True
```

before any non-bootstrap import. The builder enforces this minimum requirement. A
secure production launcher must also verify that `pyencode_runtime` contains no
`__pycache__`, `.pyc`, or unexpected files **before** importing the package. The
default launcher and the Weldments pipeline include the complete preflight check.

A host such as Fusion can load an entry point without placing its plaintext module
name in the stub:

```python
import sys
sys.dont_write_bytecode = True

# Perform the pyencode_runtime preflight here.
from pyencode_runtime import load_entry

implementation = load_entry()
```

`install()` intentionally returns `None`. `load_entry()` returns the entry module to
an embedding host, while `run()` executes the entry point with `__main__` semantics.

## Output layout and runtime behavior

```text
dist/app/
├── .pyencode-manifest.json
├── myapp/
│   ├── 14a0...f91c.pye
│   ├── 7b82...bc33.pye
│   └── assets/config.json
├── pyencode_runtime/
│   ├── __init__.py
│   ├── _build.py
│   ├── _mp_main.py
│   └── _runtime.py
├── requirements.txt
└── run.py
```

Resources are not encrypted, but their build-time bytes and paths are signed and
key-bound. By default, the entire output tree is immutable: the runtime rejects any
file or directory that is added, removed, or modified.

For hosts that create metadata or caches beside an add-in, `--allow-extra-data`
permits additional data files and directories without invalidating the bundle. This
mode still rejects modifications or removal of signed files, unexpected `.py`,
`.pyc`, native libraries, or `.pye` files, and all symlinks or reparse points. Do not
use this extra data as trusted input for licensing or security decisions. The
Weldments pipeline enables this compatibility mode so Fusion can create `.vscode`,
logs, or machine-specific caches.

The `__file__` value of a protected module is the real path to its randomly named
artifact. Consequently, `Path(__file__).parent`, `pkgutil.get_data()`, and
`importlib.resources`, including nested directory resources, continue to work. Code
that depends on the basename or stem of `__file__` sees the random token.

Integration tests cover imports by full name, relative imports, circular imports,
namespace packages, Unicode module names, reloads, `runpy.run_module()`, and
`multiprocessing` spawn for applications launched through the default launcher.
`pkgutil.iter_modules()` and `walk_packages()` cannot automatically discover
protected child names because those names intentionally reside in the encrypted
index; importing a known full name still works.

For an embedding host that calls `load_entry()`, spawning works if the child process
also runs the host bootstrap. A host that places its bootstrap only inside
`if __name__ == '__main__'` and then directly spawns a protected target requires a
dedicated launcher. Automatic spawn bootstrapping currently focuses on applications
executed through `run()`.

Version 0.3 uses one fixed runtime namespace per process. Do not load two independent
PyEncode distributions into the same interpreter; run them in separate processes.
Randomized or multi-bundle runtime namespaces are a compatibility item to resolve
before declaring a stable 1.0 API.

## Security limitations

PyEncode makes static analysis harder, but it cannot guarantee secrecy on a machine
fully controlled by an attacker:

- The default mode is offline, so key material must remain in the bundle. An
  experienced analyst can inspect the runtime and reproduce the key-derivation
  process.
- Code objects must exist in memory while they execute. Tracing, debuggers,
  monkeypatching, or native hooks may still observe code and runtime state.
- The integrity interlock prevents straightforward file modification, artifact
  substitution, code injection, and re-signing. It does not turn a pure-Python
  runtime into a native trust anchor.
- Module and entry-point names are hidden at rest, but appear during import in
  `sys.modules`, tracebacks, and runtime state. Package and resource directories may
  still reveal part of the application structure.
- `--expires` relies on the system clock and is not a replacement for a licensing
  system.

Never store long-lived API keys or private keys in a client. For high-value products,
the security upgrade that makes the greatest practical difference is an external or
envelope key obtained from a license server or keyring. A native runtime primarily
adds further reverse-engineering cost.

## Testing

```bash
python -m unittest discover -v
```

CI runs on Windows and Ubuntu with CPython 3.10 through 3.15. Tests cover PYE2, the
encrypted module index, KDF vectors, tampering and re-signing, resource/support
integrity, opaque filenames, imports, packages, namespaces, Unicode, `runpy`,
`multiprocessing` spawn, ordinary launchers without `-B`, expiration policy, and
atomic output creation.

## Releasing

The production release process using GitHub OIDC is documented in
[RELEASING.md](RELEASING.md). The workflow uploads to PyPI only when a pushed tag
exactly matches the project version, for example `v0.3.1`.
