Metadata-Version: 2.5
Name: shieldy-sdk
Version: 1.0.3
Summary: Python client for Shieldy's native runtime: licensing, remote variables, files and Protected Strings.
Project-URL: Documentation, https://docs.shieldy.app
License: Proprietary
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: cryptography>=42
Description-Content-Type: text/markdown

# Shieldy Python SDK

The Python client for Shieldy's native runtime (`native.dll` on Windows, `native.so` on Linux).
It signs your application in with the end user's license key and reads what the dashboard
delivers to that license: the license itself, remote variables, files and Protected Strings.

```python
import shieldy

try:
    shieldy.start(shieldy.Config("<App GUID>", "1.0"), read_license_key_from_user())
except shieldy.ShieldyError as exc:
    # exc.error is a shieldy.Error, e.g. Error.AUTHENTICATION_FAILED
    raise SystemExit(f"Could not sign in: {exc.error}")

lic = shieldy.license()
if lic.level >= 20:
    enable_pro_features()

api_url = shieldy.variable_by_id("<Lookup ID>")              # str
max_users = shieldy.variable_by_id_as("<Lookup ID>", int)    # int
with shieldy.file_by_id("<Lookup ID>") as pak:               # SecureBytes, wiped after the block
    load_assets(pak.view())
token = shieldy.protected_string("<ciphertext>")             # str
```

Python 3.9 or newer, 64-bit or 32-bit to match the runtime you ship. The only dependency is
[`cryptography`](https://cryptography.io).

## Supported Python versions

| Python | Tested | How |
|---|---|---|
| 3.9 to 3.14 | yes | the unit suite on Windows, with the mock runtime (`scripts/test_matrix.py`) |
| 3.9 and 3.14 on Linux | yes | the same suite in the official `python` Docker images |
| 3.8 and older | no | out of support from the Python core team; `pip` refuses to install the package |
| PyPy, free-threaded builds | no | nothing in the SDK rules them out, but nobody has run them |

The oldest `cryptography` the package allows (42.0.0) is part of the matrix, on Python 3.9.
Against the real runtime, the end-to-end suite (`tests/e2e`) runs on the interpreter of the
developer's machine, not on every version above: it needs the local stack described in
`tests/e2e/README.md`.

The 32-bit runtime needs a 32-bit Python, and the 64-bit runtime a 64-bit one. The matrix is
64-bit. The package bundles the 64-bit runtimes only (Windows x64, Linux x64): there is no win32 wheel,
because `cryptography` publishes win32 wheels only up to 48.0.1 and `pip` on a 32-bit Python would try to
compile a newer one. On a 32-bit Windows Python install with
`pip install --only-binary cryptography shieldy-sdk` and ship the Windows x86 runtime yourself
(`Config.native_library` or `SHIELDY_NATIVE_LIBRARY`); that combination was checked against core 0.1.4.

## Installing

```powershell
pip install shieldy-sdk                 # from PyPI
pip install path/to/ShieldyPythonSdk    # from a checkout
```

The wheels on PyPI carry the runtime for Windows x64 and Linux x64 (glibc 2.31 or newer), so nothing else
is needed there: the SDK finds it in the package directory. On other platforms, or to pin a runtime of
your own, download it from the dashboard (your app -> Activity -> Runtime) and put it next to your entry
script or your frozen executable; a copy there wins over the bundled one. A frozen build (PyInstaller,
cx_Freeze) must include the bundled `native.dll` / `native.so` or ship its own copy.

## Where the runtime is loaded from

The SDK loads exactly one file, chosen in this order:

1. `Config.native_library`, if you set it;
2. the `SHIELDY_NATIVE_LIBRARY` environment variable;
3. `native.dll` (`native.so` on Linux).

A relative path is resolved against your application's directory, **never** the current working
directory or `PATH`, so a library planted where the user starts your program is not picked up.
Your application's directory is:

| How the app runs | Directory |
|---|---|
| `python app.py` | the directory of `app.py` |
| `python -m package` | the directory of `package/__main__.py` |
| PyInstaller, cx_Freeze, py2exe | the directory of the executable, then PyInstaller's bundle directory (`sys._MEIPASS`) |
| interactive interpreter, `python -c` | none: give an absolute path |

`shieldy.application_directory()` shows what the SDK settled on.

With PyInstaller, either copy the runtime next to the built executable, or bundle it:
`pyinstaller --add-binary "native.dll;." app.py` (`native.so:.` on Linux).

## API

All calls are module-level functions on the one session the process has. They are thread-safe.

| Call | Returns |
|---|---|
| `init(config)` | Loads the runtime and runs its protected start-up (`/initialize` on the server). |
| `login(key)` | Signs in with the license key. |
| `start(config, key)` | `init` then `login`. |
| `shutdown()` | Ends the session. Also runs automatically when the interpreter exits. |
| `is_logged_in()` | `bool` |
| `supports(Feature.LOOKUP_IDS)` | Whether the runtime has the `*_by_id` calls (protocol 1.6.0+). |
| `supports(Feature.OFFLINE_START)` | Whether the runtime has `connection_state()` (protocol 1.12.0+). |
| `connection_state()` | `ConnectionState`: `offline` (`True` when this run started without a connection), `offline_until` (until when this device can start offline; `None`: it cannot). |
| `license()` | `License`: `level`, `hwid_seats_used`, `hwid_seats_total`, `created`, `expires` (`None`: never), `is_expired()`, `days_left()`. Read once at login. |
| `variable_by_id(id)` / `variable(name)` | `str` |
| `variable_by_id_as(id, type)` / `variable_as(name, type)` | `int`, `float`, `bool` or `str` |
| `file_by_id(id)` / `file(name)` | `SecureBytes`, wiped from memory when done |
| `protected_string(ciphertext)` | `str`, cached for the rest of the session |

Prefer the `*_by_id` calls: a lookup id is random, a name ends up readable in your code. A
variable whose name is hidden from the client (dashboard: "Hide name from client") can only be
read by id.

`bool` variables accept `true`, `false`, `1`, `0`. Numbers follow the C++ SDK's rules: surrounding
whitespace is ignored, a leading `+`, digit separators (`1_000`) and hex are not accepted.

### Errors

Every call raises `shieldy.ShieldyError` when it cannot deliver; `exc.error` says why. The codes
have the same numbers as the C++ SDK's `shieldy::Error`.

| `Error` | Meaning |
|---|---|
| `NATIVE_LIBRARY_NOT_FOUND` | No runtime at the resolved path, or one for the wrong architecture. |
| `NATIVE_LIBRARY_INVALID` | The file loaded but is not a Shieldy runtime. |
| `INITIALIZATION_FAILED` | The server refused to start the app: unknown App GUID, suspended app, outdated version, unregistered runtime build, maintenance. |
| `AUTHENTICATION_FAILED` | The key was refused: wrong, expired, banned, or no free device seat. The server does not say which. |
| `NOT_INITIALIZED`, `NOT_LOGGED_IN` | A call came too early. |
| `NOT_FOUND` | No variable with that id or name for this license. |
| `NATIVE_TOO_OLD` | The runtime predates the call; see `supports()`. |
| `ATTESTATION_FAILED`, `KEY_EXCHANGE_FAILED`, `DECRYPT_FAILED` | The runtime could not prove it holds the session key, or a value did not decrypt. Treat as tampering. |
| `INVALID_VALUE` | A variable did not parse as the requested type. |
| `SERVER_UNREACHABLE` | No connection, and this device cannot start offline (offline start is off, it never signed in online here, or that was with another key). |
| `OFFLINE_EXPIRED` | No connection, and this device's offline time (or the license) has run out. |
| `CLOCK_INVALID` | No connection, and the system clock reads earlier than the last run. |
| `OFFLINE_UNAVAILABLE` | The call needs a connection and the app is running offline (files). |

The full list is in `src/shieldy/errors.py`.

### Offline start

When the app has offline start on (dashboard: Security -> Availability), a device that signed in
online can start without internet for the number of days the app allows. Nothing changes in your
code: `init()` and `login()` succeed offline as they do online. Show it if you like:

```python
state = shieldy.connection_state()
if state.offline:
    show_banner(f"Offline - works until {state.offline_until:%b %d}")
```

Offline, `license()`, variables and Protected Strings work; files need a connection. The device
has to sign in with the same key it last used online. For a portable install, keep the lease next
to the app with `Config(..., lease_directory="leases")`. To test it without pulling the cable, set
`SHIELDY_DEV_FORCE_OFFLINE=1` with a development build of the runtime.

### Trying another key

When a key is refused, `login()` can be called again with another one, and `init()` works again
after `shutdown()`. Runtimes built before October 2026 allowed one sign-in per process (the server
ends the session at a refused key and they could not open another); with one of those, restart the
process to let the user try another key.

### Files and memory

`file_by_id()` returns a `SecureBytes`: a buffer the SDK zeroes when you call `wipe()`, when a
`with` block around it ends, or when it is garbage collected. Read it through the object
(`len()`, indexing, slicing, `view()`, `text()`); `bytes(data)` makes a copy that can never be
wiped. This is best effort, as it has to be in Python: copies the interpreter makes on its own
(a `str` from `text()`, for instance) are out of the SDK's reach.

## Protected Strings in the build

Write secrets as `SHIELDY_OBF("...")` (double quotes) and keep coding against the plain text:

```python
import shieldy
from shieldy.obf import SHIELDY_OBF

def api_endpoint() -> str:
    return SHIELDY_OBF("https://api.example.com/v2")
```

Before a release, run the dashboard's CLI over each file. It rewrites every marker to
`shieldy.protected_string("<ciphertext>")`:

```powershell
python tools/shieldy_strings_cli.py --api-url https://<dashboard>/api --app-guid <App GUID> `
    --api-key <key with apps:write> --file src/endpoints.py --language python --in-place
python -m shieldy.obf check src/        # exit code 1 while any marker is left
```

Python has no compile step that could refuse a forgotten marker, so `SHIELDY_OBF` raises
`UnencryptedMarkerError` when it runs, unless `SHIELDY_OBF_PLAINTEXT=1` is set (do that while you
develop, never in a release), and `python -m shieldy.obf check` belongs in your release pipeline.
Read protected strings where they are used, after `login()`, never at module level.
See `examples/protected_strings_marker.py`.

## Examples

- `examples/basic.py`: the whole flow, configured from environment variables
  (`SHIELDY_APP_GUID`, `SHIELDY_LICENSE_KEY`, optional `SHIELDY_VARIABLE_ID`, `SHIELDY_FILE_ID`,
  `SHIELDY_PROTECTED_STRING`).
- `examples/protected_strings_marker.py`: the `SHIELDY_OBF` workflow.

## Working on this repository

```powershell
uv sync                    # Python 3.9+, creates .venv with the dev tools
uv run pytest              # unit tests against a mock runtime, no server needed
uv run python scripts/test_matrix.py   # the same on Python 3.9 to 3.14, plus the oldest cryptography
uv run pytest -m e2e       # a real runtime against a real server, see tests/e2e/README.md
uv run ruff check src tests examples scripts
uv run mypy                # strict
```

How the SDK works inside, and why it is built the way it is: [docs/architecture.md](docs/architecture.md).
A quick map of the repository, its commands and invariants: [CLAUDE.md](CLAUDE.md).

`third_party/shieldy_api.h` is a copy of ShieldyCore's `cpp-module/shieldy_api.h`, the ABI the
SDK mirrors in `src/shieldy/_abi.py`. `tests/test_abi.py` fails when the two disagree, and when the
copy differs from a ShieldyCore checkout next to this repository.
